blob: a0379914795abe5165bd42ae7d39fa5990e20261 [file] [log] [blame]
Thierry Fourniere726b142016-02-11 17:57:57 +01001/*
2 * Lua unsafe core engine
3 *
4 * Copyright 2015-2016 Thierry Fournier <tfournier@arpalert.org>
5 *
6 * This program is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU General Public License
8 * as published by the Free Software Foundation; either version
9 * 2 of the License, or (at your option) any later version.
10 *
11 */
12
Bertrand Jacquinf4c12d42021-01-21 21:14:07 +000013#define _GNU_SOURCE
14
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +010015#include <ctype.h>
Thierry FOURNIERbabae282015-09-17 11:36:37 +020016#include <setjmp.h>
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +010017
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +010018#include <lauxlib.h>
19#include <lua.h>
20#include <lualib.h>
21
Thierry FOURNIER463119c2015-03-10 00:35:36 +010022#if !defined(LUA_VERSION_NUM) || LUA_VERSION_NUM < 503
23#error "Requires Lua 5.3 or later."
Cyril Bontédc0306e2015-03-02 00:08:40 +010024#endif
25
Willy Tarreau8d2b7772020-05-27 10:58:19 +020026#include <import/ebpttree.h>
Thierry FOURNIER380d0932015-01-23 14:27:52 +010027
Willy Tarreaub2551052020-06-09 09:07:15 +020028#include <haproxy/api.h>
29#include <haproxy/applet.h>
Willy Tarreaudfd3de82020-06-04 23:46:14 +020030#include <haproxy/arg.h>
Christopher Fauletd25d9262020-08-06 11:04:46 +020031#include <haproxy/auth.h>
Willy Tarreau6be78492020-06-05 00:00:29 +020032#include <haproxy/cfgparse.h>
Willy Tarreauf1d32c42020-06-04 21:07:02 +020033#include <haproxy/channel.h>
Willy Tarreau83487a82020-06-04 20:19:54 +020034#include <haproxy/cli.h>
Willy Tarreau55542642021-10-08 09:33:24 +020035#include <haproxy/clock.h>
Willy Tarreau7ea393d2020-06-04 18:02:10 +020036#include <haproxy/connection.h>
Christopher Faulet69c581a2021-05-31 08:54:04 +020037#include <haproxy/filters.h>
Willy Tarreau5413a872020-06-02 19:33:08 +020038#include <haproxy/h1.h>
Willy Tarreau86416052020-06-04 09:20:54 +020039#include <haproxy/hlua.h>
Willy Tarreau8c794002020-06-04 10:05:25 +020040#include <haproxy/hlua_fcn.h>
Willy Tarreauc2b1ff02020-06-04 21:21:03 +020041#include <haproxy/http_ana.h>
William Lallemand3956c4e2021-09-21 16:25:15 +020042#include <haproxy/http_client.h>
Willy Tarreau126ba3a2020-06-04 18:26:43 +020043#include <haproxy/http_fetch.h>
Willy Tarreaub2551052020-06-09 09:07:15 +020044#include <haproxy/http_htx.h>
Willy Tarreauc761f842020-06-04 11:40:28 +020045#include <haproxy/http_rules.h>
Willy Tarreau36979d92020-06-05 17:27:29 +020046#include <haproxy/log.h>
Willy Tarreau2cd58092020-06-04 15:10:43 +020047#include <haproxy/map.h>
Willy Tarreau8efbdfb2020-06-04 11:29:21 +020048#include <haproxy/obj_type.h>
Willy Tarreau225a90a2020-06-04 15:06:28 +020049#include <haproxy/pattern.h>
Willy Tarreau469509b2020-06-04 15:13:30 +020050#include <haproxy/payload.h>
Willy Tarreau3d6ee402021-05-08 20:28:07 +020051#include <haproxy/proxy.h>
Willy Tarreaub2551052020-06-09 09:07:15 +020052#include <haproxy/regex.h>
Willy Tarreaue6ce10b2020-06-04 15:33:47 +020053#include <haproxy/sample.h>
Willy Tarreau5edca2f2022-05-27 09:25:10 +020054#include <haproxy/sc_strm.h>
Willy Tarreau198e92a2021-03-05 10:23:32 +010055#include <haproxy/server.h>
Willy Tarreau48d25b32020-06-04 18:58:52 +020056#include <haproxy/session.h>
William Lallemand30fcca12022-03-30 12:03:12 +020057#include <haproxy/ssl_ckch.h>
58#include <haproxy/ssl_sock.h>
Willy Tarreau2eec9b52020-06-04 19:58:55 +020059#include <haproxy/stats-t.h>
Willy Tarreaucb086c62022-05-27 09:47:12 +020060#include <haproxy/stconn.h>
Willy Tarreaudfd3de82020-06-04 23:46:14 +020061#include <haproxy/stream.h>
Willy Tarreaucea0e1b2020-06-04 17:25:40 +020062#include <haproxy/task.h>
Willy Tarreau8b550af2020-06-04 17:42:48 +020063#include <haproxy/tcp_rules.h>
Willy Tarreaub2551052020-06-09 09:07:15 +020064#include <haproxy/thread.h>
Willy Tarreau48fbcae2020-06-03 18:09:46 +020065#include <haproxy/tools.h>
Willy Tarreaua1718922020-06-04 16:25:31 +020066#include <haproxy/vars.h>
Willy Tarreaub2551052020-06-09 09:07:15 +020067#include <haproxy/xref.h>
68
Thierry FOURNIER380d0932015-01-23 14:27:52 +010069
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +010070/* Lua uses longjmp to perform yield or throwing errors. This
71 * macro is used only for identifying the function that can
72 * not return because a longjmp is executed.
73 * __LJMP marks a prototype of hlua file that can use longjmp.
74 * WILL_LJMP() marks an lua function that will use longjmp.
75 * MAY_LJMP() marks an lua function that may use longjmp.
76 */
77#define __LJMP
Willy Tarreau4e7cc332018-10-20 17:45:48 +020078#define WILL_LJMP(func) do { func; my_unreachable(); } while(0)
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +010079#define MAY_LJMP(func) func
80
Thierry FOURNIERbabae282015-09-17 11:36:37 +020081/* This couple of function executes securely some Lua calls outside of
82 * the lua runtime environment. Each Lua call can return a longjmp
83 * if it encounter a memory error.
84 *
85 * Lua documentation extract:
86 *
87 * If an error happens outside any protected environment, Lua calls
88 * a panic function (see lua_atpanic) and then calls abort, thus
89 * exiting the host application. Your panic function can avoid this
90 * exit by never returning (e.g., doing a long jump to your own
91 * recovery point outside Lua).
92 *
93 * The panic function runs as if it were a message handler (see
Willy Tarreau3dfb7da2022-03-02 22:33:39 +010094 * #2.3); in particular, the error message is at the top of the
Thierry FOURNIERbabae282015-09-17 11:36:37 +020095 * stack. However, there is no guarantee about stack space. To push
96 * anything on the stack, the panic function must first check the
Willy Tarreau3dfb7da2022-03-02 22:33:39 +010097 * available space (see #4.2).
Thierry FOURNIERbabae282015-09-17 11:36:37 +020098 *
99 * We must check all the Lua entry point. This includes:
100 * - The include/proto/hlua.h exported functions
101 * - the task wrapper function
102 * - The action wrapper function
103 * - The converters wrapper function
104 * - The sample-fetch wrapper functions
105 *
Ilya Shipitsin46a030c2020-07-05 16:36:08 +0500106 * It is tolerated that the initialisation function returns an abort.
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -0800107 * Before each Lua abort, an error message is written on stderr.
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200108 *
109 * The macro SET_SAFE_LJMP initialise the longjmp. The Macro
110 * RESET_SAFE_LJMP reset the longjmp. These function must be macro
111 * because they must be exists in the program stack when the longjmp
112 * is called.
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +0200113 *
114 * Note that the Lua processing is not really thread safe. It provides
115 * heavy system which consists to add our own lock function in the Lua
116 * code and recompile the library. This system will probably not accepted
117 * by maintainers of various distribs.
118 *
Ilya Shipitsin856aabc2020-04-16 23:51:34 +0500119 * Our main execution point of the Lua is the function lua_resume(). A
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +0200120 * quick looking on the Lua sources displays a lua_lock() a the start
121 * of function and a lua_unlock() at the end of the function. So I
122 * conclude that the Lua thread safe mode just perform a mutex around
123 * all execution. So I prefer to do this in the HAProxy code, it will be
124 * easier for distro maintainers.
125 *
126 * Note that the HAProxy lua functions rounded by the macro SET_SAFE_LJMP
127 * and RESET_SAFE_LJMP manipulates the Lua stack, so it will be careful
128 * to set mutex around these functions.
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200129 */
Willy Tarreau86abe442018-11-25 20:12:18 +0100130__decl_spinlock(hlua_global_lock);
Thierry FOURNIERffbad792017-07-12 11:39:04 +0200131THREAD_LOCAL jmp_buf safe_ljmp_env;
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200132static int hlua_panic_safe(lua_State *L) { return 0; }
Willy Tarreau6a510902021-07-14 19:41:25 +0200133static int hlua_panic_ljmp(lua_State *L) { WILL_LJMP(longjmp(safe_ljmp_env, 1)); return 0; }
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200134
Thierry Fournier62a22aa2020-11-28 21:06:35 +0100135/* This is the chained list of struct hlua_function referenced
136 * for haproxy action, sample-fetches, converters, cli and
137 * applet bindings. It is used for a post-initialisation control.
138 */
139static struct list referenced_functions = LIST_HEAD_INIT(referenced_functions);
140
Thierry Fournierc7492592020-11-28 23:57:24 +0100141/* This variable is used only during initialization to identify the Lua state
142 * currently being initialized. 0 is the common lua state, 1 to n are the Lua
143 * states dedicated to each thread (in this case hlua_state_id==tid+1).
144 */
145static int hlua_state_id;
146
Thierry Fournier59f11be2020-11-29 00:37:41 +0100147/* This is a NULL-terminated list of lua file which are referenced to load per thread */
Thierry Fournierae6b5682022-09-19 09:04:16 +0200148static char ***per_thread_load = NULL;
Thierry Fournier59f11be2020-11-29 00:37:41 +0100149
150lua_State *hlua_init_state(int thread_id);
151
Willy Tarreau1e7bef12021-08-20 15:47:25 +0200152/* This function takes the Lua global lock. Keep this function's visibility
153 * global so that it can appear in stack dumps and performance profiles!
154 */
155void lua_take_global_lock()
156{
157 HA_SPIN_LOCK(LUA_LOCK, &hlua_global_lock);
158}
159
160static inline void lua_drop_global_lock()
161{
162 HA_SPIN_UNLOCK(LUA_LOCK, &hlua_global_lock);
163}
164
Thierry Fournier7cbe5042020-11-28 17:02:21 +0100165#define SET_SAFE_LJMP_L(__L, __HLUA) \
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200166 ({ \
167 int ret; \
Thierry Fournier021d9862020-11-28 23:42:03 +0100168 if ((__HLUA)->state_id == 0) \
Willy Tarreau1e7bef12021-08-20 15:47:25 +0200169 lua_take_global_lock(); \
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200170 if (setjmp(safe_ljmp_env) != 0) { \
171 lua_atpanic(__L, hlua_panic_safe); \
172 ret = 0; \
Thierry Fournier021d9862020-11-28 23:42:03 +0100173 if ((__HLUA)->state_id == 0) \
Willy Tarreau1e7bef12021-08-20 15:47:25 +0200174 lua_drop_global_lock(); \
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200175 } else { \
176 lua_atpanic(__L, hlua_panic_ljmp); \
177 ret = 1; \
178 } \
179 ret; \
180 })
181
182/* If we are the last function catching Lua errors, we
183 * must reset the panic function.
184 */
Thierry Fournier7cbe5042020-11-28 17:02:21 +0100185#define RESET_SAFE_LJMP_L(__L, __HLUA) \
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200186 do { \
187 lua_atpanic(__L, hlua_panic_safe); \
Thierry Fournier021d9862020-11-28 23:42:03 +0100188 if ((__HLUA)->state_id == 0) \
Willy Tarreau1e7bef12021-08-20 15:47:25 +0200189 lua_drop_global_lock(); \
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200190 } while(0)
191
Thierry Fournier7cbe5042020-11-28 17:02:21 +0100192#define SET_SAFE_LJMP(__HLUA) \
193 SET_SAFE_LJMP_L((__HLUA)->T, __HLUA)
194
195#define RESET_SAFE_LJMP(__HLUA) \
196 RESET_SAFE_LJMP_L((__HLUA)->T, __HLUA)
197
198#define SET_SAFE_LJMP_PARENT(__HLUA) \
Thierry Fournier021d9862020-11-28 23:42:03 +0100199 SET_SAFE_LJMP_L(hlua_states[(__HLUA)->state_id], __HLUA)
Thierry Fournier7cbe5042020-11-28 17:02:21 +0100200
201#define RESET_SAFE_LJMP_PARENT(__HLUA) \
Thierry Fournier021d9862020-11-28 23:42:03 +0100202 RESET_SAFE_LJMP_L(hlua_states[(__HLUA)->state_id], __HLUA)
Thierry Fournier7cbe5042020-11-28 17:02:21 +0100203
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +0200204/* Applet status flags */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200205#define APPLET_DONE 0x01 /* applet processing is done. */
Christopher Faulet18c2e8d2019-03-01 12:02:08 +0100206/* unused: 0x02 */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200207#define APPLET_HDR_SENT 0x04 /* Response header sent. */
Christopher Fauleta2097962019-07-15 16:25:33 +0200208/* unused: 0x08, 0x10 */
Thierry FOURNIERd93ea2b2015-12-20 19:14:52 +0100209#define APPLET_HTTP11 0x20 /* Last chunk sent. */
Christopher Faulet56a3d6e2019-02-27 22:06:23 +0100210#define APPLET_RSP_SENT 0x40 /* The response was fully sent */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200211
Thierry Fournierafc63e22020-11-28 17:06:51 +0100212/* The main Lua execution context. The 0 index is the
213 * common state shared by all threads.
214 */
Willy Tarreau186f3762020-12-04 11:48:12 +0100215static lua_State *hlua_states[MAX_THREADS + 1];
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100216
Christopher Fauletc404f112020-02-26 15:03:09 +0100217#define HLUA_FLT_CB_FINAL 0x00000001
218#define HLUA_FLT_CB_RETVAL 0x00000002
219#define HLUA_FLT_CB_ARG_CHN 0x00000004
220#define HLUA_FLT_CB_ARG_HTTP_MSG 0x00000008
221
Christopher Faulet9f55a502020-02-25 15:21:02 +0100222#define HLUA_FLT_CTX_FL_PAYLOAD 0x00000001
223
Christopher Faulet69c581a2021-05-31 08:54:04 +0200224struct hlua_reg_filter {
225 char *name;
226 int flt_ref[MAX_THREADS + 1];
227 int fun_ref[MAX_THREADS + 1];
228 struct list l;
229};
230
231struct hlua_flt_config {
232 struct hlua_reg_filter *reg;
233 int ref[MAX_THREADS + 1];
234 char **args;
235};
236
237struct hlua_flt_ctx {
238 int ref; /* ref to the filter lua object */
239 struct hlua *hlua[2]; /* lua runtime context (0: request, 1: response) */
240 unsigned int cur_off[2]; /* current offset (0: request, 1: response) */
241 unsigned int cur_len[2]; /* current forwardable length (0: request, 1: response) */
242 unsigned int flags; /* HLUA_FLT_CTX_FL_* */
243};
244
Willy Tarreau5321da92022-05-06 11:57:34 +0200245/* appctx context used by the cosockets */
246struct hlua_csk_ctx {
247 int connected;
248 struct xref xref; /* cross reference with the Lua object owner. */
249 struct list wake_on_read;
250 struct list wake_on_write;
251 struct appctx *appctx;
252 int die;
253};
254
Willy Tarreaue23f33b2022-05-06 14:07:13 +0200255/* appctx context used by TCP services */
256struct hlua_tcp_ctx {
257 struct hlua *hlua;
258 int flags;
259 struct task *task;
260};
261
Willy Tarreauaa229cc2022-05-06 14:26:10 +0200262/* appctx context used by HTTP services */
263struct hlua_http_ctx {
264 struct hlua *hlua;
265 int left_bytes; /* The max amount of bytes that we can read. */
266 int flags;
267 int status;
268 const char *reason;
269 struct task *task;
270};
271
Willy Tarreaubcda5f62022-05-03 18:13:39 +0200272/* used by registered CLI keywords */
273struct hlua_cli_ctx {
274 struct hlua *hlua;
275 struct task *task;
276 struct hlua_function *fcn;
277};
278
Christopher Faulet69c581a2021-05-31 08:54:04 +0200279DECLARE_STATIC_POOL(pool_head_hlua_flt_ctx, "hlua_flt_ctx", sizeof(struct hlua_flt_ctx));
280
Christopher Faulet9f55a502020-02-25 15:21:02 +0100281static int hlua_filter_from_payload(struct filter *filter);
282
Christopher Faulet69c581a2021-05-31 08:54:04 +0200283/* This is the chained list of struct hlua_flt referenced
284 * for haproxy filters. It is used for a post-initialisation control.
285 */
286static struct list referenced_filters = LIST_HEAD_INIT(referenced_filters);
287
288
Thierry FOURNIERebed6e92016-12-16 11:54:07 +0100289/* This is the memory pool containing struct lua for applets
290 * (including cli).
291 */
Willy Tarreau8ceae722018-11-26 11:58:30 +0100292DECLARE_STATIC_POOL(pool_head_hlua, "hlua", sizeof(struct hlua));
Thierry FOURNIERebed6e92016-12-16 11:54:07 +0100293
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +0100294/* Used for Socket connection. */
Amaury Denoyelle239fdbf2021-03-24 10:22:03 +0100295static struct proxy *socket_proxy;
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +0100296static struct server *socket_tcp;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +0100297#ifdef USE_OPENSSL
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +0100298static struct server *socket_ssl;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +0100299#endif
300
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +0100301/* List head of the function called at the initialisation time. */
Thierry Fournierc7492592020-11-28 23:57:24 +0100302struct list hlua_init_functions[MAX_THREADS + 1];
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +0100303
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +0100304/* The following variables contains the reference of the different
305 * Lua classes. These references are useful for identify metadata
306 * associated with an object.
307 */
Thierry FOURNIER65f34c62015-02-16 20:11:43 +0100308static int class_txn_ref;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +0100309static int class_socket_ref;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +0100310static int class_channel_ref;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +0100311static int class_fetches_ref;
Thierry FOURNIER594afe72015-03-10 23:58:30 +0100312static int class_converters_ref;
Thierry FOURNIER08504f42015-03-16 14:17:08 +0100313static int class_http_ref;
Christopher Fauletdf97ac42020-02-26 16:57:19 +0100314static int class_http_msg_ref;
William Lallemand3956c4e2021-09-21 16:25:15 +0200315static int class_httpclient_ref;
Thierry FOURNIER3def3932015-04-07 11:27:54 +0200316static int class_map_ref;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +0200317static int class_applet_tcp_ref;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200318static int class_applet_http_ref;
Christopher Faulet700d9e82020-01-31 12:21:52 +0100319static int class_txn_reply_ref;
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +0100320
Thierry FOURNIERbd413492015-03-03 16:52:26 +0100321/* Global Lua execution timeout. By default Lua, execution linked
Willy Tarreau87b09662015-04-03 00:22:06 +0200322 * with stream (actions, sample-fetches and converters) have a
Thierry FOURNIERbd413492015-03-03 16:52:26 +0100323 * short timeout. Lua linked with tasks doesn't have a timeout
324 * because a task may remain alive during all the haproxy execution.
325 */
326static unsigned int hlua_timeout_session = 4000; /* session timeout. */
327static unsigned int hlua_timeout_task = TICK_ETERNITY; /* task timeout. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +0200328static unsigned int hlua_timeout_applet = 4000; /* applet timeout. */
Thierry FOURNIERbd413492015-03-03 16:52:26 +0100329
Thierry FOURNIERee9f8022015-03-03 17:37:37 +0100330/* Interrupts the Lua processing each "hlua_nb_instruction" instructions.
331 * it is used for preventing infinite loops.
332 *
333 * I test the scheer with an infinite loop containing one incrementation
334 * and one test. I run this loop between 10 seconds, I raise a ceil of
335 * 710M loops from one interrupt each 9000 instructions, so I fix the value
336 * to one interrupt each 10 000 instructions.
337 *
338 * configured | Number of
339 * instructions | loops executed
340 * between two | in milions
341 * forced yields |
342 * ---------------+---------------
343 * 10 | 160
344 * 500 | 670
345 * 1000 | 680
346 * 5000 | 700
347 * 7000 | 700
348 * 8000 | 700
349 * 9000 | 710 <- ceil
350 * 10000 | 710
351 * 100000 | 710
352 * 1000000 | 710
353 *
354 */
355static unsigned int hlua_nb_instruction = 10000;
356
Willy Tarreaucdb53462020-12-02 12:12:00 +0100357/* Descriptor for the memory allocation state. The limit is pre-initialised to
358 * 0 until it is replaced by "tune.lua.maxmem" during the config parsing, or it
359 * is replaced with ~0 during post_init after everything was loaded. This way
360 * it is guaranteed that if limit is ~0 the boot is complete and that if it's
361 * zero it's not yet limited and proper accounting is required.
Willy Tarreau32f61e22015-03-18 17:54:59 +0100362 */
363struct hlua_mem_allocator {
364 size_t allocated;
365 size_t limit;
366};
367
Willy Tarreaucdb53462020-12-02 12:12:00 +0100368static struct hlua_mem_allocator hlua_global_allocator THREAD_ALIGNED(64);
Willy Tarreau32f61e22015-03-18 17:54:59 +0100369
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100370/* These functions converts types between HAProxy internal args or
371 * sample and LUA types. Another function permits to check if the
372 * LUA stack contains arguments according with an required ARG_T
373 * format.
374 */
375static int hlua_arg2lua(lua_State *L, const struct arg *arg);
376static int hlua_lua2arg(lua_State *L, int ud, struct arg *arg);
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100377__LJMP static int hlua_lua2arg_check(lua_State *L, int first, struct arg *argp,
David Carlier0c437f42016-04-27 16:21:56 +0100378 uint64_t mask, struct proxy *p);
Willy Tarreau5eadada2015-03-10 17:28:54 +0100379static int hlua_smp2lua(lua_State *L, struct sample *smp);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100380static int hlua_smp2lua_str(lua_State *L, struct sample *smp);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100381static int hlua_lua2smp(lua_State *L, int ud, struct sample *smp);
382
Christopher Faulet9d1332b2020-02-24 16:46:16 +0100383__LJMP static int hlua_http_get_headers(lua_State *L, struct http_msg *msg);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200384
Thierry Fournier59f11be2020-11-29 00:37:41 +0100385struct prepend_path {
386 struct list l;
387 char *type;
388 char *path;
389};
390
391static struct list prepend_path_list = LIST_HEAD_INIT(prepend_path_list);
392
Thierry FOURNIER23bc3752015-09-11 19:15:43 +0200393#define SEND_ERR(__be, __fmt, __args...) \
394 do { \
395 send_log(__be, LOG_ERR, __fmt, ## __args); \
396 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE)) \
Christopher Faulet767a84b2017-11-24 16:50:31 +0100397 ha_alert(__fmt, ## __args); \
Thierry FOURNIER23bc3752015-09-11 19:15:43 +0200398 } while (0)
399
Thierry Fournier62a22aa2020-11-28 21:06:35 +0100400static inline struct hlua_function *new_hlua_function()
401{
402 struct hlua_function *fcn;
Thierry Fournierc7492592020-11-28 23:57:24 +0100403 int i;
Thierry Fournier62a22aa2020-11-28 21:06:35 +0100404
405 fcn = calloc(1, sizeof(*fcn));
406 if (!fcn)
407 return NULL;
Willy Tarreau2b718102021-04-21 07:32:39 +0200408 LIST_APPEND(&referenced_functions, &fcn->l);
Thierry Fournierc7492592020-11-28 23:57:24 +0100409 for (i = 0; i < MAX_THREADS + 1; i++)
410 fcn->function_ref[i] = -1;
Thierry Fournier62a22aa2020-11-28 21:06:35 +0100411 return fcn;
412}
413
Christopher Fauletdda44442021-04-12 14:05:43 +0200414static inline void release_hlua_function(struct hlua_function *fcn)
415{
416 if (!fcn)
417 return;
418 if (fcn->name)
419 ha_free(&fcn->name);
Willy Tarreau2b718102021-04-21 07:32:39 +0200420 LIST_DELETE(&fcn->l);
Christopher Fauletdda44442021-04-12 14:05:43 +0200421 ha_free(&fcn);
422}
423
Thierry Fournierc7492592020-11-28 23:57:24 +0100424/* If the common state is set, the stack id is 0, otherwise it is the tid + 1 */
425static inline int fcn_ref_to_stack_id(struct hlua_function *fcn)
426{
427 if (fcn->function_ref[0] == -1)
428 return tid + 1;
429 return 0;
430}
431
Christopher Faulet69c581a2021-05-31 08:54:04 +0200432/* Create a new registered filter. Only its name is filled */
433static inline struct hlua_reg_filter *new_hlua_reg_filter(const char *name)
434{
435 struct hlua_reg_filter *reg_flt;
436 int i;
437
438 reg_flt = calloc(1, sizeof(*reg_flt));
439 if (!reg_flt)
440 return NULL;
441 reg_flt->name = strdup(name);
442 if (!reg_flt->name) {
443 free(reg_flt);
444 return NULL;
445 }
446 LIST_APPEND(&referenced_filters, &reg_flt->l);
447 for (i = 0; i < MAX_THREADS + 1; i++) {
448 reg_flt->flt_ref[i] = -1;
449 reg_flt->fun_ref[i] = -1;
450 }
451 return reg_flt;
452}
453
454/* Release a registered filter */
455static inline void release_hlua_reg_filter(struct hlua_reg_filter *reg_flt)
456{
457 if (!reg_flt)
458 return;
459 if (reg_flt->name)
460 ha_free(&reg_flt->name);
461 LIST_DELETE(&reg_flt->l);
462 ha_free(&reg_flt);
463}
464
465/* If the common state is set, the stack id is 0, otherwise it is the tid + 1 */
466static inline int reg_flt_to_stack_id(struct hlua_reg_filter *reg_flt)
467{
468 if (reg_flt->fun_ref[0] == -1)
469 return tid + 1;
470 return 0;
471}
472
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100473/* Used to check an Lua function type in the stack. It creates and
474 * returns a reference of the function. This function throws an
475 * error if the rgument is not a "function".
476 */
477__LJMP unsigned int hlua_checkfunction(lua_State *L, int argno)
478{
479 if (!lua_isfunction(L, argno)) {
Thierry FOURNIERfd1e9552018-02-23 18:41:18 +0100480 const char *msg = lua_pushfstring(L, "function expected, got %s", luaL_typename(L, argno));
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100481 WILL_LJMP(luaL_argerror(L, argno, msg));
482 }
483 lua_pushvalue(L, argno);
484 return luaL_ref(L, LUA_REGISTRYINDEX);
485}
486
Christopher Fauletba9e21d2020-02-25 10:20:04 +0100487/* Used to check an Lua table type in the stack. It creates and
488 * returns a reference of the table. This function throws an
489 * error if the rgument is not a "table".
490 */
491__LJMP unsigned int hlua_checktable(lua_State *L, int argno)
492{
493 if (!lua_istable(L, argno)) {
494 const char *msg = lua_pushfstring(L, "table expected, got %s", luaL_typename(L, argno));
495 WILL_LJMP(luaL_argerror(L, argno, msg));
496 }
497 lua_pushvalue(L, argno);
498 return luaL_ref(L, LUA_REGISTRYINDEX);
499}
500
Christopher Fauletd09cc512021-03-24 14:48:45 +0100501__LJMP const char *hlua_traceback(lua_State *L, const char* sep)
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200502{
503 lua_Debug ar;
504 int level = 0;
Willy Tarreau83061a82018-07-13 11:56:34 +0200505 struct buffer *msg = get_trash_chunk();
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200506
507 while (lua_getstack(L, level++, &ar)) {
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200508 /* Fill fields:
509 * 'S': fills in the fields source, short_src, linedefined, lastlinedefined, and what;
510 * 'l': fills in the field currentline;
511 * 'n': fills in the field name and namewhat;
512 * 't': fills in the field istailcall;
513 */
514 lua_getinfo(L, "Slnt", &ar);
515
Willy Tarreau5c143402022-06-19 17:35:53 +0200516 /* skip these empty entries, usually they come from deep C functions */
517 if (ar.currentline < 0 && *ar.what == 'C' && !*ar.namewhat && !ar.name)
518 continue;
519
520 /* Add separator */
521 if (b_data(msg))
522 chunk_appendf(msg, "%s", sep);
523
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200524 /* Append code localisation */
525 if (ar.currentline > 0)
Christopher Fauletd09cc512021-03-24 14:48:45 +0100526 chunk_appendf(msg, "%s:%d: ", ar.short_src, ar.currentline);
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200527 else
Christopher Fauletd09cc512021-03-24 14:48:45 +0100528 chunk_appendf(msg, "%s: ", ar.short_src);
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200529
530 /*
531 * Get function name
532 *
533 * if namewhat is no empty, name is defined.
534 * what contains "Lua" for Lua function, "C" for C function,
535 * or "main" for main code.
536 */
537 if (*ar.namewhat != '\0' && ar.name != NULL) /* is there a name from code? */
Christopher Fauletd09cc512021-03-24 14:48:45 +0100538 chunk_appendf(msg, "in %s '%s'", ar.namewhat, ar.name); /* use it */
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200539
540 else if (*ar.what == 'm') /* "main", the code is not executed in a function */
Christopher Fauletd09cc512021-03-24 14:48:45 +0100541 chunk_appendf(msg, "in main chunk");
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200542
543 else if (*ar.what != 'C') /* for Lua functions, use <file:line> */
Christopher Fauletd09cc512021-03-24 14:48:45 +0100544 chunk_appendf(msg, "in function line %d", ar.linedefined);
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200545
546 else /* nothing left... */
547 chunk_appendf(msg, "?");
548
549
550 /* Display tailed call */
551 if (ar.istailcall)
552 chunk_appendf(msg, " ...");
553 }
554
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200555 return msg->area;
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200556}
557
558
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100559/* This function check the number of arguments available in the
560 * stack. If the number of arguments available is not the same
Ilya Shipitsinc02a23f2020-05-06 00:53:22 +0500561 * then <nb> an error is thrown.
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100562 */
563__LJMP static inline void check_args(lua_State *L, int nb, char *fcn)
564{
565 if (lua_gettop(L) == nb)
566 return;
567 WILL_LJMP(luaL_error(L, "'%s' needs %d arguments", fcn, nb));
568}
569
Mark Lakes22154b42018-01-29 14:38:40 -0800570/* This function pushes an error string prefixed by the file name
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100571 * and the line number where the error is encountered.
572 */
573static int hlua_pusherror(lua_State *L, const char *fmt, ...)
574{
575 va_list argp;
576 va_start(argp, fmt);
577 luaL_where(L, 1);
578 lua_pushvfstring(L, fmt, argp);
579 va_end(argp);
580 lua_concat(L, 2);
581 return 1;
582}
583
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100584/* This functions is used with sample fetch and converters. It
585 * converts the HAProxy configuration argument in a lua stack
586 * values.
587 *
588 * It takes an array of "arg", and each entry of the array is
589 * converted and pushed in the LUA stack.
590 */
591static int hlua_arg2lua(lua_State *L, const struct arg *arg)
592{
593 switch (arg->type) {
594 case ARGT_SINT:
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100595 case ARGT_TIME:
596 case ARGT_SIZE:
Thierry FOURNIERf90838b2015-03-06 13:48:32 +0100597 lua_pushinteger(L, arg->data.sint);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100598 break;
599
600 case ARGT_STR:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200601 lua_pushlstring(L, arg->data.str.area, arg->data.str.data);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100602 break;
603
604 case ARGT_IPV4:
605 case ARGT_IPV6:
606 case ARGT_MSK4:
607 case ARGT_MSK6:
608 case ARGT_FE:
609 case ARGT_BE:
610 case ARGT_TAB:
611 case ARGT_SRV:
612 case ARGT_USR:
613 case ARGT_MAP:
614 default:
615 lua_pushnil(L);
616 break;
617 }
618 return 1;
619}
620
Ilya Shipitsinc02a23f2020-05-06 00:53:22 +0500621/* This function take one entry in an LUA stack at the index "ud",
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100622 * and try to convert it in an HAProxy argument entry. This is useful
Ilya Shipitsind4259502020-04-08 01:07:56 +0500623 * with sample fetch wrappers. The input arguments are given to the
624 * lua wrapper and converted as arg list by the function.
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100625 */
626static int hlua_lua2arg(lua_State *L, int ud, struct arg *arg)
627{
628 switch (lua_type(L, ud)) {
629
630 case LUA_TNUMBER:
631 case LUA_TBOOLEAN:
632 arg->type = ARGT_SINT;
633 arg->data.sint = lua_tointeger(L, ud);
634 break;
635
636 case LUA_TSTRING:
637 arg->type = ARGT_STR;
Tim Duesterhus2e89dec2019-09-29 23:03:08 +0200638 arg->data.str.area = (char *)lua_tolstring(L, ud, &arg->data.str.data);
Tim Duesterhus29d2e8a2019-09-29 23:03:07 +0200639 /* We don't know the actual size of the underlying allocation, so be conservative. */
Christopher Fauletfdea1b62020-08-06 08:29:18 +0200640 arg->data.str.size = arg->data.str.data+1; /* count the terminating null byte */
Tim Duesterhus29d2e8a2019-09-29 23:03:07 +0200641 arg->data.str.head = 0;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100642 break;
643
644 case LUA_TUSERDATA:
645 case LUA_TNIL:
646 case LUA_TTABLE:
647 case LUA_TFUNCTION:
648 case LUA_TTHREAD:
649 case LUA_TLIGHTUSERDATA:
650 arg->type = ARGT_SINT;
Thierry FOURNIERbf65cd42015-07-20 17:45:02 +0200651 arg->data.sint = 0;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100652 break;
653 }
654 return 1;
655}
656
657/* the following functions are used to convert a struct sample
658 * in Lua type. This useful to convert the return of the
Ilya Shipitsind4259502020-04-08 01:07:56 +0500659 * fetches or converters.
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100660 */
Willy Tarreau5eadada2015-03-10 17:28:54 +0100661static int hlua_smp2lua(lua_State *L, struct sample *smp)
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100662{
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200663 switch (smp->data.type) {
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100664 case SMP_T_SINT:
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100665 case SMP_T_BOOL:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200666 lua_pushinteger(L, smp->data.u.sint);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100667 break;
668
669 case SMP_T_BIN:
670 case SMP_T_STR:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200671 lua_pushlstring(L, smp->data.u.str.area, smp->data.u.str.data);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100672 break;
673
674 case SMP_T_METH:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200675 switch (smp->data.u.meth.meth) {
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100676 case HTTP_METH_OPTIONS: lua_pushstring(L, "OPTIONS"); break;
677 case HTTP_METH_GET: lua_pushstring(L, "GET"); break;
678 case HTTP_METH_HEAD: lua_pushstring(L, "HEAD"); break;
679 case HTTP_METH_POST: lua_pushstring(L, "POST"); break;
680 case HTTP_METH_PUT: lua_pushstring(L, "PUT"); break;
681 case HTTP_METH_DELETE: lua_pushstring(L, "DELETE"); break;
682 case HTTP_METH_TRACE: lua_pushstring(L, "TRACE"); break;
683 case HTTP_METH_CONNECT: lua_pushstring(L, "CONNECT"); break;
684 case HTTP_METH_OTHER:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200685 lua_pushlstring(L, smp->data.u.meth.str.area, smp->data.u.meth.str.data);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100686 break;
687 default:
688 lua_pushnil(L);
689 break;
690 }
691 break;
692
693 case SMP_T_IPV4:
694 case SMP_T_IPV6:
695 case SMP_T_ADDR: /* This type is never used to qualify a sample. */
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200696 if (sample_casts[smp->data.type][SMP_T_STR] &&
697 sample_casts[smp->data.type][SMP_T_STR](smp))
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200698 lua_pushlstring(L, smp->data.u.str.area, smp->data.u.str.data);
Willy Tarreau5eadada2015-03-10 17:28:54 +0100699 else
700 lua_pushnil(L);
701 break;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100702 default:
703 lua_pushnil(L);
704 break;
705 }
706 return 1;
707}
708
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100709/* the following functions are used to convert a struct sample
710 * in Lua strings. This is useful to convert the return of the
Ilya Shipitsind4259502020-04-08 01:07:56 +0500711 * fetches or converters.
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100712 */
713static int hlua_smp2lua_str(lua_State *L, struct sample *smp)
714{
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200715 switch (smp->data.type) {
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100716
717 case SMP_T_BIN:
718 case SMP_T_STR:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200719 lua_pushlstring(L, smp->data.u.str.area, smp->data.u.str.data);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100720 break;
721
722 case SMP_T_METH:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200723 switch (smp->data.u.meth.meth) {
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100724 case HTTP_METH_OPTIONS: lua_pushstring(L, "OPTIONS"); break;
725 case HTTP_METH_GET: lua_pushstring(L, "GET"); break;
726 case HTTP_METH_HEAD: lua_pushstring(L, "HEAD"); break;
727 case HTTP_METH_POST: lua_pushstring(L, "POST"); break;
728 case HTTP_METH_PUT: lua_pushstring(L, "PUT"); break;
729 case HTTP_METH_DELETE: lua_pushstring(L, "DELETE"); break;
730 case HTTP_METH_TRACE: lua_pushstring(L, "TRACE"); break;
731 case HTTP_METH_CONNECT: lua_pushstring(L, "CONNECT"); break;
732 case HTTP_METH_OTHER:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200733 lua_pushlstring(L, smp->data.u.meth.str.area, smp->data.u.meth.str.data);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100734 break;
735 default:
736 lua_pushstring(L, "");
737 break;
738 }
739 break;
740
741 case SMP_T_SINT:
742 case SMP_T_BOOL:
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100743 case SMP_T_IPV4:
744 case SMP_T_IPV6:
745 case SMP_T_ADDR: /* This type is never used to qualify a sample. */
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200746 if (sample_casts[smp->data.type][SMP_T_STR] &&
747 sample_casts[smp->data.type][SMP_T_STR](smp))
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200748 lua_pushlstring(L, smp->data.u.str.area, smp->data.u.str.data);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100749 else
750 lua_pushstring(L, "");
751 break;
752 default:
753 lua_pushstring(L, "");
754 break;
755 }
756 return 1;
757}
758
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100759/* the following functions are used to convert an Lua type in a
760 * struct sample. This is useful to provide data from a converter
761 * to the LUA code.
762 */
763static int hlua_lua2smp(lua_State *L, int ud, struct sample *smp)
764{
765 switch (lua_type(L, ud)) {
766
767 case LUA_TNUMBER:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200768 smp->data.type = SMP_T_SINT;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200769 smp->data.u.sint = lua_tointeger(L, ud);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100770 break;
771
772
773 case LUA_TBOOLEAN:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200774 smp->data.type = SMP_T_BOOL;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200775 smp->data.u.sint = lua_toboolean(L, ud);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100776 break;
777
778 case LUA_TSTRING:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200779 smp->data.type = SMP_T_STR;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100780 smp->flags |= SMP_F_CONST;
Tim Duesterhus2e89dec2019-09-29 23:03:08 +0200781 smp->data.u.str.area = (char *)lua_tolstring(L, ud, &smp->data.u.str.data);
Tim Duesterhus29d2e8a2019-09-29 23:03:07 +0200782 /* We don't know the actual size of the underlying allocation, so be conservative. */
Christopher Fauletfdea1b62020-08-06 08:29:18 +0200783 smp->data.u.str.size = smp->data.u.str.data+1; /* count the terminating null byte */
Tim Duesterhus29d2e8a2019-09-29 23:03:07 +0200784 smp->data.u.str.head = 0;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100785 break;
786
787 case LUA_TUSERDATA:
788 case LUA_TNIL:
789 case LUA_TTABLE:
790 case LUA_TFUNCTION:
791 case LUA_TTHREAD:
792 case LUA_TLIGHTUSERDATA:
Thierry FOURNIER93405e12015-08-26 14:19:03 +0200793 case LUA_TNONE:
794 default:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200795 smp->data.type = SMP_T_BOOL;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200796 smp->data.u.sint = 0;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100797 break;
798 }
799 return 1;
800}
801
Ilya Shipitsind4259502020-04-08 01:07:56 +0500802/* This function check the "argp" built by another conversion function
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -0800803 * is in accord with the expected argp defined by the "mask". The function
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100804 * returns true or false. It can be adjust the types if there compatibles.
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100805 *
Ilya Shipitsinc02a23f2020-05-06 00:53:22 +0500806 * This function assumes that the argp argument contains ARGM_NBARGS + 1
Willy Tarreauee0d7272021-07-16 10:26:56 +0200807 * entries and that there is at least one stop at the last position.
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100808 */
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100809__LJMP int hlua_lua2arg_check(lua_State *L, int first, struct arg *argp,
David Carlier0c437f42016-04-27 16:21:56 +0100810 uint64_t mask, struct proxy *p)
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100811{
812 int min_arg;
Willy Tarreauee0d7272021-07-16 10:26:56 +0200813 int idx;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100814 struct proxy *px;
Christopher Fauletd25d9262020-08-06 11:04:46 +0200815 struct userlist *ul;
Christopher Fauletfd2e9062020-08-06 11:10:57 +0200816 struct my_regex *reg;
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200817 const char *msg = NULL;
Christopher Fauletfd2e9062020-08-06 11:10:57 +0200818 char *sname, *pname, *err = NULL;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100819
820 idx = 0;
821 min_arg = ARGM(mask);
822 mask >>= ARGM_BITS;
823
824 while (1) {
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200825 struct buffer tmp = BUF_NULL;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100826
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100827 /* Check for mandatory arguments. */
828 if (argp[idx].type == ARGT_STOP) {
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100829 if (idx < min_arg) {
830
831 /* If miss other argument than the first one, we return an error. */
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200832 if (idx > 0) {
833 msg = "Mandatory argument expected";
834 goto error;
835 }
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100836
837 /* If first argument have a certain type, some default values
838 * may be used. See the function smp_resolve_args().
839 */
840 switch (mask & ARGT_MASK) {
841
842 case ARGT_FE:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200843 if (!(p->cap & PR_CAP_FE)) {
844 msg = "Mandatory argument expected";
845 goto error;
846 }
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100847 argp[idx].data.prx = p;
848 argp[idx].type = ARGT_FE;
849 argp[idx+1].type = ARGT_STOP;
850 break;
851
852 case ARGT_BE:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200853 if (!(p->cap & PR_CAP_BE)) {
854 msg = "Mandatory argument expected";
855 goto error;
856 }
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100857 argp[idx].data.prx = p;
858 argp[idx].type = ARGT_BE;
859 argp[idx+1].type = ARGT_STOP;
860 break;
861
862 case ARGT_TAB:
Olivier Houchard14f62682022-09-13 00:35:53 +0200863 if (!p->table) {
864 msg = "Mandatory argument expected";
865 goto error;
866 }
867 argp[idx].data.t = p->table;
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100868 argp[idx].type = ARGT_TAB;
869 argp[idx+1].type = ARGT_STOP;
870 break;
871
872 default:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200873 msg = "Mandatory argument expected";
874 goto error;
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100875 break;
876 }
877 }
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200878 break;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100879 }
880
Ilya Shipitsin856aabc2020-04-16 23:51:34 +0500881 /* Check for exceed the number of required argument. */
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100882 if ((mask & ARGT_MASK) == ARGT_STOP &&
883 argp[idx].type != ARGT_STOP) {
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200884 msg = "Last argument expected";
885 goto error;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100886 }
887
888 if ((mask & ARGT_MASK) == ARGT_STOP &&
889 argp[idx].type == ARGT_STOP) {
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200890 break;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100891 }
892
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200893 /* Convert some argument types. All string in argp[] are for not
894 * duplicated yet.
895 */
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100896 switch (mask & ARGT_MASK) {
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100897 case ARGT_SINT:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200898 if (argp[idx].type != ARGT_SINT) {
899 msg = "integer expected";
900 goto error;
901 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100902 argp[idx].type = ARGT_SINT;
903 break;
904
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100905 case ARGT_TIME:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200906 if (argp[idx].type != ARGT_SINT) {
907 msg = "integer expected";
908 goto error;
909 }
Thierry FOURNIER29176f32015-07-07 00:41:29 +0200910 argp[idx].type = ARGT_TIME;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100911 break;
912
913 case ARGT_SIZE:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200914 if (argp[idx].type != ARGT_SINT) {
915 msg = "integer expected";
916 goto error;
917 }
Thierry FOURNIER29176f32015-07-07 00:41:29 +0200918 argp[idx].type = ARGT_SIZE;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100919 break;
920
921 case ARGT_FE:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200922 if (argp[idx].type != ARGT_STR) {
923 msg = "string expected";
924 goto error;
925 }
Christopher Fauletfdea1b62020-08-06 08:29:18 +0200926 argp[idx].data.prx = proxy_fe_by_name(argp[idx].data.str.area);
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200927 if (!argp[idx].data.prx) {
928 msg = "frontend doesn't exist";
929 goto error;
930 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100931 argp[idx].type = ARGT_FE;
932 break;
933
934 case ARGT_BE:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200935 if (argp[idx].type != ARGT_STR) {
936 msg = "string expected";
937 goto error;
938 }
Christopher Fauletfdea1b62020-08-06 08:29:18 +0200939 argp[idx].data.prx = proxy_be_by_name(argp[idx].data.str.area);
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200940 if (!argp[idx].data.prx) {
941 msg = "backend doesn't exist";
942 goto error;
943 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100944 argp[idx].type = ARGT_BE;
945 break;
946
947 case ARGT_TAB:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200948 if (argp[idx].type != ARGT_STR) {
949 msg = "string expected";
950 goto error;
951 }
Christopher Fauletfdea1b62020-08-06 08:29:18 +0200952 argp[idx].data.t = stktable_find_by_name(argp[idx].data.str.area);
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200953 if (!argp[idx].data.t) {
954 msg = "table doesn't exist";
955 goto error;
956 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100957 argp[idx].type = ARGT_TAB;
958 break;
959
960 case ARGT_SRV:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200961 if (argp[idx].type != ARGT_STR) {
962 msg = "string expected";
963 goto error;
964 }
Christopher Fauletfdea1b62020-08-06 08:29:18 +0200965 sname = strrchr(argp[idx].data.str.area, '/');
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100966 if (sname) {
967 *sname++ = '\0';
Christopher Fauletfdea1b62020-08-06 08:29:18 +0200968 pname = argp[idx].data.str.area;
Willy Tarreau9e0bb102015-05-26 11:24:42 +0200969 px = proxy_be_by_name(pname);
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200970 if (!px) {
971 msg = "backend doesn't exist";
972 goto error;
973 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100974 }
975 else {
Christopher Fauletfdea1b62020-08-06 08:29:18 +0200976 sname = argp[idx].data.str.area;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100977 px = p;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100978 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100979 argp[idx].data.srv = findserver(px, sname);
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200980 if (!argp[idx].data.srv) {
981 msg = "server doesn't exist";
982 goto error;
983 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100984 argp[idx].type = ARGT_SRV;
985 break;
986
987 case ARGT_IPV4:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200988 if (argp[idx].type != ARGT_STR) {
989 msg = "string expected";
990 goto error;
991 }
992 if (inet_pton(AF_INET, argp[idx].data.str.area, &argp[idx].data.ipv4)) {
993 msg = "invalid IPv4 address";
994 goto error;
995 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100996 argp[idx].type = ARGT_IPV4;
997 break;
998
999 case ARGT_MSK4:
Christopher Faulete663a6e2020-08-07 09:11:22 +02001000 if (argp[idx].type == ARGT_SINT)
1001 len2mask4(argp[idx].data.sint, &argp[idx].data.ipv4);
1002 else if (argp[idx].type == ARGT_STR) {
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001003 if (!str2mask(argp[idx].data.str.area, &argp[idx].data.ipv4)) {
1004 msg = "invalid IPv4 mask";
1005 goto error;
1006 }
1007 }
1008 else {
1009 msg = "integer or string expected";
1010 goto error;
Christopher Faulete663a6e2020-08-07 09:11:22 +02001011 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001012 argp[idx].type = ARGT_MSK4;
1013 break;
1014
1015 case ARGT_IPV6:
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001016 if (argp[idx].type != ARGT_STR) {
1017 msg = "string expected";
1018 goto error;
1019 }
1020 if (inet_pton(AF_INET6, argp[idx].data.str.area, &argp[idx].data.ipv6)) {
1021 msg = "invalid IPv6 address";
1022 goto error;
1023 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001024 argp[idx].type = ARGT_IPV6;
1025 break;
1026
1027 case ARGT_MSK6:
Christopher Faulete663a6e2020-08-07 09:11:22 +02001028 if (argp[idx].type == ARGT_SINT)
1029 len2mask6(argp[idx].data.sint, &argp[idx].data.ipv6);
1030 else if (argp[idx].type == ARGT_STR) {
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001031 if (!str2mask6(argp[idx].data.str.area, &argp[idx].data.ipv6)) {
1032 msg = "invalid IPv6 mask";
1033 goto error;
1034 }
1035 }
1036 else {
1037 msg = "integer or string expected";
1038 goto error;
Christopher Faulete663a6e2020-08-07 09:11:22 +02001039 }
Tim Duesterhusb814da62018-01-25 16:24:50 +01001040 argp[idx].type = ARGT_MSK6;
1041 break;
1042
Christopher Fauletfd2e9062020-08-06 11:10:57 +02001043 case ARGT_REG:
1044 if (argp[idx].type != ARGT_STR) {
1045 msg = "string expected";
1046 goto error;
1047 }
1048 reg = regex_comp(argp[idx].data.str.area, !(argp[idx].type_flags & ARGF_REG_ICASE), 1, &err);
1049 if (!reg) {
1050 msg = lua_pushfstring(L, "error compiling regex '%s' : '%s'",
1051 argp[idx].data.str.area, err);
1052 free(err);
1053 goto error;
1054 }
1055 argp[idx].type = ARGT_REG;
1056 argp[idx].data.reg = reg;
1057 break;
1058
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001059 case ARGT_USR:
Christopher Fauletd25d9262020-08-06 11:04:46 +02001060 if (argp[idx].type != ARGT_STR) {
1061 msg = "string expected";
1062 goto error;
1063 }
1064 if (p->uri_auth && p->uri_auth->userlist &&
Tim Duesterhuse5ff1412021-01-02 22:31:53 +01001065 strcmp(p->uri_auth->userlist->name, argp[idx].data.str.area) == 0)
Christopher Fauletd25d9262020-08-06 11:04:46 +02001066 ul = p->uri_auth->userlist;
1067 else
1068 ul = auth_find_userlist(argp[idx].data.str.area);
1069
1070 if (!ul) {
1071 msg = lua_pushfstring(L, "unable to find userlist '%s'", argp[idx].data.str.area);
1072 goto error;
1073 }
1074 argp[idx].type = ARGT_USR;
1075 argp[idx].data.usr = ul;
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001076 break;
1077
1078 case ARGT_STR:
1079 if (!chunk_dup(&tmp, &argp[idx].data.str)) {
1080 msg = "unable to duplicate string arg";
1081 goto error;
1082 }
1083 argp[idx].data.str = tmp;
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001084 break;
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001085
Christopher Fauletd25d9262020-08-06 11:04:46 +02001086 case ARGT_MAP:
Christopher Fauletd25d9262020-08-06 11:04:46 +02001087 msg = "type not yet supported";
1088 goto error;
1089 break;
1090
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001091 }
1092
1093 /* Check for type of argument. */
1094 if ((mask & ARGT_MASK) != argp[idx].type) {
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001095 msg = lua_pushfstring(L, "'%s' expected, got '%s'",
1096 arg_type_names[(mask & ARGT_MASK)],
1097 arg_type_names[argp[idx].type & ARGT_MASK]);
1098 goto error;
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001099 }
1100
1101 /* Next argument. */
1102 mask >>= ARGT_BITS;
1103 idx++;
1104 }
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001105 return 0;
1106
1107 error:
Olivier Houchardca431612022-09-13 00:31:17 +02001108 argp[idx].type = ARGT_STOP;
Willy Tarreauee0d7272021-07-16 10:26:56 +02001109 free_args(argp);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001110 WILL_LJMP(luaL_argerror(L, first + idx, msg));
1111 return 0; /* Never reached */
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001112}
1113
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001114/*
Ilya Shipitsinc02a23f2020-05-06 00:53:22 +05001115 * The following functions are used to make correspondence between the the
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001116 * executed lua pointer and the "struct hlua *" that contain the context.
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001117 *
1118 * - hlua_gethlua : return the hlua context associated with an lua_State.
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001119 * - hlua_sethlua : create the association between hlua context and lua_state.
1120 */
1121static inline struct hlua *hlua_gethlua(lua_State *L)
1122{
Thierry FOURNIER38c5fd62015-03-10 02:40:29 +01001123 struct hlua **hlua = lua_getextraspace(L);
1124 return *hlua;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001125}
1126static inline void hlua_sethlua(struct hlua *hlua)
1127{
Thierry FOURNIER38c5fd62015-03-10 02:40:29 +01001128 struct hlua **hlua_store = lua_getextraspace(hlua->T);
1129 *hlua_store = hlua;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001130}
1131
Willy Tarreau0b7b6392022-06-19 17:39:33 +02001132/* Will return a non-NULL string indicating the Lua call trace if the caller
1133 * currently is executing from within a Lua function. One line per entry will
1134 * be emitted, and each extra line will be prefixed with <pfx>. If a current
1135 * Lua function is not detected, NULL is returned.
1136 */
1137const char *hlua_show_current_location(const char *pfx)
1138{
1139 lua_State *L;
1140 lua_Debug ar;
1141
1142 /* global or per-thread stack initializing ? */
1143 if (hlua_state_id != -1 && (L = hlua_states[hlua_state_id]) && lua_getstack(L, 0, &ar))
1144 return hlua_traceback(L, pfx);
1145
1146 /* per-thread stack running ? */
1147 if (hlua_states[tid + 1] && (L = hlua_states[tid + 1]) && lua_getstack(L, 0, &ar))
1148 return hlua_traceback(L, pfx);
1149
1150 /* global stack running ? */
1151 if (hlua_states[0] && (L = hlua_states[0]) && lua_getstack(L, 0, &ar))
1152 return hlua_traceback(L, pfx);
1153
1154 return NULL;
1155}
1156
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01001157/* This function is used to send logs. It try to send on screen (stderr)
1158 * and on the default syslog server.
1159 */
1160static inline void hlua_sendlog(struct proxy *px, int level, const char *msg)
1161{
1162 struct tm tm;
1163 char *p;
1164
1165 /* Cleanup the log message. */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001166 p = trash.area;
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01001167 for (; *msg != '\0'; msg++, p++) {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001168 if (p >= trash.area + trash.size - 1) {
Thierry FOURNIERccf00632015-09-16 12:47:03 +02001169 /* Break the message if exceed the buffer size. */
1170 *(p-4) = ' ';
1171 *(p-3) = '.';
1172 *(p-2) = '.';
1173 *(p-1) = '.';
1174 break;
1175 }
Willy Tarreau90807112020-02-25 08:16:33 +01001176 if (isprint((unsigned char)*msg))
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01001177 *p = *msg;
1178 else
1179 *p = '.';
1180 }
1181 *p = '\0';
1182
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001183 send_log(px, level, "%s\n", trash.area);
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01001184 if (!(global.mode & MODE_QUIET) || (global.mode & (MODE_VERBOSE | MODE_STARTING))) {
Christopher Fauletf98d8212020-10-02 18:13:52 +02001185 if (level == LOG_DEBUG && !(global.mode & MODE_DEBUG))
1186 return;
1187
Willy Tarreaua678b432015-08-28 10:14:59 +02001188 get_localtime(date.tv_sec, &tm);
1189 fprintf(stderr, "[%s] %03d/%02d%02d%02d (%d) : %s\n",
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01001190 log_levels[level], tm.tm_yday, tm.tm_hour, tm.tm_min, tm.tm_sec,
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001191 (int)getpid(), trash.area);
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01001192 fflush(stderr);
1193 }
1194}
1195
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001196/* This function just ensure that the yield will be always
1197 * returned with a timeout and permit to set some flags
1198 */
1199__LJMP void hlua_yieldk(lua_State *L, int nresults, int ctx,
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001200 lua_KFunction k, int timeout, unsigned int flags)
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001201{
Thierry Fournier4234dbd2020-11-28 13:18:23 +01001202 struct hlua *hlua;
1203
1204 /* Get hlua struct, or NULL if we execute from main lua state */
1205 hlua = hlua_gethlua(L);
1206 if (!hlua) {
1207 return;
1208 }
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001209
1210 /* Set the wake timeout. If timeout is required, we set
1211 * the expiration time.
1212 */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001213 hlua->wake_time = timeout;
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001214
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01001215 hlua->flags |= flags;
1216
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001217 /* Process the yield. */
Willy Tarreau9635e032018-10-16 17:52:55 +02001218 MAY_LJMP(lua_yieldk(L, nresults, ctx, k));
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001219}
1220
Willy Tarreau87b09662015-04-03 00:22:06 +02001221/* This function initialises the Lua environment stored in the stream.
1222 * It must be called at the start of the stream. This function creates
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001223 * an LUA coroutine. It can not be use to crete the main LUA context.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02001224 *
1225 * This function is particular. it initialises a new Lua thread. If the
1226 * initialisation fails (example: out of memory error), the lua function
1227 * throws an error (longjmp).
1228 *
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +01001229 * In some case (at least one), this function can be called from safe
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001230 * environment, so we must not initialise it. While the support of
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +01001231 * threads appear, the safe environment set a lock to ensure only one
1232 * Lua execution at a time. If we initialize safe environment in another
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001233 * safe environment, we have a dead lock.
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +01001234 *
1235 * set "already_safe" true if the context is initialized form safe
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001236 * Lua function.
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +01001237 *
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001238 * This function manipulates two Lua stacks: the main and the thread. Only
Thierry FOURNIERbabae282015-09-17 11:36:37 +02001239 * the main stack can fail. The thread is not manipulated. This function
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001240 * MUST NOT manipulate the created thread stack state, because it is not
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001241 * protected against errors thrown by the thread stack.
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001242 */
Thierry Fournier021d9862020-11-28 23:42:03 +01001243int hlua_ctx_init(struct hlua *lua, int state_id, struct task *task, int already_safe)
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001244{
1245 lua->Mref = LUA_REFNIL;
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001246 lua->flags = 0;
Willy Tarreauf31af932020-01-14 09:59:38 +01001247 lua->gc_count = 0;
Christopher Fauletbc275a92020-02-26 14:55:16 +01001248 lua->wake_time = TICK_ETERNITY;
Thierry Fournier021d9862020-11-28 23:42:03 +01001249 lua->state_id = state_id;
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01001250 LIST_INIT(&lua->com);
William Lallemandbb581422022-10-20 10:57:28 +02001251 LIST_INIT(&lua->hc_list);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001252 if (!already_safe) {
1253 if (!SET_SAFE_LJMP_PARENT(lua)) {
1254 lua->Tref = LUA_REFNIL;
1255 return 0;
1256 }
1257 }
Thierry Fournier021d9862020-11-28 23:42:03 +01001258 lua->T = lua_newthread(hlua_states[state_id]);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001259 if (!lua->T) {
1260 lua->Tref = LUA_REFNIL;
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +01001261 if (!already_safe)
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001262 RESET_SAFE_LJMP_PARENT(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001263 return 0;
1264 }
1265 hlua_sethlua(lua);
Thierry Fournier021d9862020-11-28 23:42:03 +01001266 lua->Tref = luaL_ref(hlua_states[state_id], LUA_REGISTRYINDEX);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001267 lua->task = task;
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +01001268 if (!already_safe)
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001269 RESET_SAFE_LJMP_PARENT(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001270 return 1;
1271}
1272
William Lallemandbb581422022-10-20 10:57:28 +02001273/* kill all associated httpclient to this hlua task */
1274static void hlua_httpclient_destroy_all(struct hlua *hlua)
1275{
1276 struct hlua_httpclient *hlua_hc, *back;
1277
1278 list_for_each_entry_safe(hlua_hc, back, &hlua->hc_list, by_hlua) {
1279 if (hlua_hc->hc)
1280 httpclient_stop_and_destroy(hlua_hc->hc);
1281 hlua_hc->hc = NULL;
William Lallemand94dbfed2022-12-08 11:11:36 +01001282 LIST_DEL_INIT(&hlua_hc->by_hlua);
William Lallemandbb581422022-10-20 10:57:28 +02001283 }
1284}
1285
1286
Willy Tarreau87b09662015-04-03 00:22:06 +02001287/* Used to destroy the Lua coroutine when the attached stream or task
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001288 * is destroyed. The destroy also the memory context. The struct "lua"
1289 * is not freed.
1290 */
1291void hlua_ctx_destroy(struct hlua *lua)
1292{
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01001293 if (!lua)
Thierry FOURNIERa718b292015-03-04 16:48:34 +01001294 return;
1295
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01001296 if (!lua->T)
1297 goto end;
1298
William Lallemandbb581422022-10-20 10:57:28 +02001299 /* clean all running httpclient */
1300 hlua_httpclient_destroy_all(lua);
1301
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01001302 /* Purge all the pending signals. */
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001303 notification_purge(&lua->com);
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01001304
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001305 if (!SET_SAFE_LJMP(lua))
Thierry FOURNIER75d02082017-07-12 13:41:33 +02001306 return;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001307 luaL_unref(lua->T, LUA_REGISTRYINDEX, lua->Mref);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001308 RESET_SAFE_LJMP(lua);
Thierry FOURNIER5a50a852015-09-23 16:59:28 +02001309
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001310 if (!SET_SAFE_LJMP_PARENT(lua))
Thierry FOURNIER75d02082017-07-12 13:41:33 +02001311 return;
Thierry Fournier021d9862020-11-28 23:42:03 +01001312 luaL_unref(hlua_states[lua->state_id], LUA_REGISTRYINDEX, lua->Tref);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001313 RESET_SAFE_LJMP_PARENT(lua);
Thierry FOURNIER5a50a852015-09-23 16:59:28 +02001314 /* Forces a garbage collecting process. If the Lua program is finished
1315 * without error, we run the GC on the thread pointer. Its freed all
1316 * the unused memory.
1317 * If the thread is finnish with an error or is currently yielded,
1318 * it seems that the GC applied on the thread doesn't clean anything,
1319 * so e run the GC on the main thread.
1320 * NOTE: maybe this action locks all the Lua threads untiml the en of
1321 * the garbage collection.
1322 */
Willy Tarreauf31af932020-01-14 09:59:38 +01001323 if (lua->gc_count) {
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001324 if (!SET_SAFE_LJMP_PARENT(lua))
Thierry FOURNIER75d02082017-07-12 13:41:33 +02001325 return;
Thierry Fournier021d9862020-11-28 23:42:03 +01001326 lua_gc(hlua_states[lua->state_id], LUA_GCCOLLECT, 0);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001327 RESET_SAFE_LJMP_PARENT(lua);
Thierry FOURNIER7c39ab42015-09-27 22:53:33 +02001328 }
Thierry FOURNIER5a50a852015-09-23 16:59:28 +02001329
Thierry FOURNIERa7b536b2015-09-21 22:50:24 +02001330 lua->T = NULL;
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01001331
1332end:
Willy Tarreaubafbe012017-11-24 17:34:44 +01001333 pool_free(pool_head_hlua, lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001334}
1335
1336/* This function is used to restore the Lua context when a coroutine
1337 * fails. This function copy the common memory between old coroutine
1338 * and the new coroutine. The old coroutine is destroyed, and its
1339 * replaced by the new coroutine.
1340 * If the flag "keep_msg" is set, the last entry of the old is assumed
1341 * as string error message and it is copied in the new stack.
1342 */
1343static int hlua_ctx_renew(struct hlua *lua, int keep_msg)
1344{
1345 lua_State *T;
1346 int new_ref;
1347
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001348 /* New Lua coroutine. */
Thierry Fournier021d9862020-11-28 23:42:03 +01001349 T = lua_newthread(hlua_states[lua->state_id]);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001350 if (!T)
1351 return 0;
1352
1353 /* Copy last error message. */
1354 if (keep_msg)
1355 lua_xmove(lua->T, T, 1);
1356
1357 /* Copy data between the coroutines. */
1358 lua_rawgeti(lua->T, LUA_REGISTRYINDEX, lua->Mref);
1359 lua_xmove(lua->T, T, 1);
Ilya Shipitsin46a030c2020-07-05 16:36:08 +05001360 new_ref = luaL_ref(T, LUA_REGISTRYINDEX); /* Value popped. */
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001361
1362 /* Destroy old data. */
1363 luaL_unref(lua->T, LUA_REGISTRYINDEX, lua->Mref);
1364
1365 /* The thread is garbage collected by Lua. */
Thierry Fournier021d9862020-11-28 23:42:03 +01001366 luaL_unref(hlua_states[lua->state_id], LUA_REGISTRYINDEX, lua->Tref);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001367
1368 /* Fill the struct with the new coroutine values. */
1369 lua->Mref = new_ref;
1370 lua->T = T;
Thierry Fournier021d9862020-11-28 23:42:03 +01001371 lua->Tref = luaL_ref(hlua_states[lua->state_id], LUA_REGISTRYINDEX);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001372
1373 /* Set context. */
1374 hlua_sethlua(lua);
1375
1376 return 1;
1377}
1378
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001379void hlua_hook(lua_State *L, lua_Debug *ar)
1380{
Thierry Fournier4234dbd2020-11-28 13:18:23 +01001381 struct hlua *hlua;
1382
1383 /* Get hlua struct, or NULL if we execute from main lua state */
1384 hlua = hlua_gethlua(L);
1385 if (!hlua)
1386 return;
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001387
1388 /* Lua cannot yield when its returning from a function,
1389 * so, we can fix the interrupt hook to 1 instruction,
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001390 * expecting that the function is finished.
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001391 */
1392 if (lua_gethookmask(L) & LUA_MASKRET) {
1393 lua_sethook(hlua->T, hlua_hook, LUA_MASKCOUNT, 1);
1394 return;
1395 }
1396
1397 /* restore the interrupt condition. */
1398 lua_sethook(hlua->T, hlua_hook, LUA_MASKCOUNT, hlua_nb_instruction);
1399
1400 /* If we interrupt the Lua processing in yieldable state, we yield.
1401 * If the state is not yieldable, trying yield causes an error.
1402 */
1403 if (lua_isyieldable(L))
Willy Tarreau9635e032018-10-16 17:52:55 +02001404 MAY_LJMP(hlua_yieldk(L, 0, 0, NULL, TICK_ETERNITY, HLUA_CTRLYIELD));
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001405
Thierry FOURNIERa85cfb12015-03-13 14:50:06 +01001406 /* If we cannot yield, update the clock and check the timeout. */
Willy Tarreau55542642021-10-08 09:33:24 +02001407 clock_update_date(0, 1);
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001408 hlua->run_time += now_ms - hlua->start_time;
1409 if (hlua->max_time && hlua->run_time >= hlua->max_time) {
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001410 lua_pushfstring(L, "execution timeout");
1411 WILL_LJMP(lua_error(L));
1412 }
1413
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001414 /* Update the start time. */
1415 hlua->start_time = now_ms;
1416
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001417 /* Try to interrupt the process at the end of the current
1418 * unyieldable function.
1419 */
1420 lua_sethook(hlua->T, hlua_hook, LUA_MASKRET|LUA_MASKCOUNT, hlua_nb_instruction);
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001421}
1422
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001423/* This function start or resumes the Lua stack execution. If the flag
1424 * "yield_allowed" if no set and the LUA stack execution returns a yield
1425 * The function return an error.
1426 *
1427 * The function can returns 4 values:
1428 * - HLUA_E_OK : The execution is terminated without any errors.
1429 * - HLUA_E_AGAIN : The execution must continue at the next associated
1430 * task wakeup.
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001431 * - HLUA_E_ERRMSG : An error has occurred, an error message is set in
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001432 * the top of the stack.
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001433 * - HLUA_E_ERR : An error has occurred without error message.
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001434 *
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001435 * If an error occurred, the stack is renewed and it is ready to run new
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001436 * LUA code.
1437 */
1438static enum hlua_exec hlua_ctx_resume(struct hlua *lua, int yield_allowed)
1439{
Christopher Faulet08ed98f2020-07-28 10:33:25 +02001440#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM >= 504
1441 int nres;
1442#endif
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001443 int ret;
1444 const char *msg;
Thierry FOURNIERfc044c92018-06-07 14:40:48 +02001445 const char *trace;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001446
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001447 /* Initialise run time counter. */
1448 if (!HLUA_IS_RUNNING(lua))
1449 lua->run_time = 0;
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001450
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +02001451 /* Lock the whole Lua execution. This lock must be before the
1452 * label "resume_execution".
1453 */
Thierry Fournier021d9862020-11-28 23:42:03 +01001454 if (lua->state_id == 0)
Willy Tarreau1e7bef12021-08-20 15:47:25 +02001455 lua_take_global_lock();
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +02001456
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001457resume_execution:
1458
1459 /* This hook interrupts the Lua processing each 'hlua_nb_instruction'
1460 * instructions. it is used for preventing infinite loops.
1461 */
1462 lua_sethook(lua->T, hlua_hook, LUA_MASKCOUNT, hlua_nb_instruction);
1463
Thierry FOURNIER1bfc09b2015-03-05 17:10:14 +01001464 /* Remove all flags except the running flags. */
Thierry FOURNIER2f3867f2015-09-28 01:02:01 +02001465 HLUA_SET_RUN(lua);
1466 HLUA_CLR_CTRLYIELD(lua);
1467 HLUA_CLR_WAKERESWR(lua);
1468 HLUA_CLR_WAKEREQWR(lua);
Christopher Faulet1f43a342021-08-04 17:58:21 +02001469 HLUA_CLR_NOYIELD(lua);
1470 if (!yield_allowed)
1471 HLUA_SET_NOYIELD(lua);
Thierry FOURNIER1bfc09b2015-03-05 17:10:14 +01001472
Christopher Fauletbc275a92020-02-26 14:55:16 +01001473 /* Update the start time and reset wake_time. */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001474 lua->start_time = now_ms;
Christopher Fauletbc275a92020-02-26 14:55:16 +01001475 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001476
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001477 /* Call the function. */
Christopher Faulet08ed98f2020-07-28 10:33:25 +02001478#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM >= 504
Thierry Fournier021d9862020-11-28 23:42:03 +01001479 ret = lua_resume(lua->T, hlua_states[lua->state_id], lua->nargs, &nres);
Christopher Faulet08ed98f2020-07-28 10:33:25 +02001480#else
Thierry Fournier021d9862020-11-28 23:42:03 +01001481 ret = lua_resume(lua->T, hlua_states[lua->state_id], lua->nargs);
Christopher Faulet08ed98f2020-07-28 10:33:25 +02001482#endif
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001483 switch (ret) {
1484
1485 case LUA_OK:
1486 ret = HLUA_E_OK;
1487 break;
1488
1489 case LUA_YIELD:
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001490 /* Check if the execution timeout is expired. It it is the case, we
1491 * break the Lua execution.
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001492 */
Willy Tarreau55542642021-10-08 09:33:24 +02001493 clock_update_date(0, 1);
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001494 lua->run_time += now_ms - lua->start_time;
1495 if (lua->max_time && lua->run_time > lua->max_time) {
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001496 lua_settop(lua->T, 0); /* Empty the stack. */
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001497 ret = HLUA_E_ETMOUT;
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001498 break;
1499 }
1500 /* Process the forced yield. if the general yield is not allowed or
1501 * if no task were associated this the current Lua execution
1502 * coroutine, we resume the execution. Else we want to return in the
1503 * scheduler and we want to be waked up again, to continue the
1504 * current Lua execution. So we schedule our own task.
1505 */
1506 if (HLUA_IS_CTRLYIELDING(lua)) {
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001507 if (!yield_allowed || !lua->task)
1508 goto resume_execution;
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001509 task_wakeup(lua->task, TASK_WOKEN_MSG);
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001510 }
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001511 if (!yield_allowed) {
1512 lua_settop(lua->T, 0); /* Empty the stack. */
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001513 ret = HLUA_E_YIELD;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001514 break;
1515 }
1516 ret = HLUA_E_AGAIN;
1517 break;
1518
1519 case LUA_ERRRUN:
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001520
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001521 /* Special exit case. The traditional exit is returned as an error
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001522 * because the errors ares the only one mean to return immediately
1523 * from and lua execution.
1524 */
1525 if (lua->flags & HLUA_EXIT) {
1526 ret = HLUA_E_OK;
Christopher Faulet7716cdf2020-01-29 11:53:30 +01001527 hlua_ctx_renew(lua, 1);
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001528 break;
1529 }
1530
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001531 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001532 if (!lua_checkstack(lua->T, 1)) {
1533 ret = HLUA_E_ERR;
1534 break;
1535 }
1536 msg = lua_tostring(lua->T, -1);
1537 lua_settop(lua->T, 0); /* Empty the stack. */
1538 lua_pop(lua->T, 1);
Christopher Fauletd09cc512021-03-24 14:48:45 +01001539 trace = hlua_traceback(lua->T, ", ");
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001540 if (msg)
Thierry Fournier46278ff2020-11-29 11:48:12 +01001541 lua_pushfstring(lua->T, "[state-id %d] runtime error: %s from %s", lua->state_id, msg, trace);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001542 else
Thierry Fournier46278ff2020-11-29 11:48:12 +01001543 lua_pushfstring(lua->T, "[state-id %d] unknown runtime error from %s", lua->state_id, trace);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001544 ret = HLUA_E_ERRMSG;
1545 break;
1546
1547 case LUA_ERRMEM:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001548 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001549 lua_settop(lua->T, 0); /* Empty the stack. */
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001550 ret = HLUA_E_NOMEM;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001551 break;
1552
1553 case LUA_ERRERR:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001554 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001555 if (!lua_checkstack(lua->T, 1)) {
1556 ret = HLUA_E_ERR;
1557 break;
1558 }
1559 msg = lua_tostring(lua->T, -1);
1560 lua_settop(lua->T, 0); /* Empty the stack. */
1561 lua_pop(lua->T, 1);
1562 if (msg)
Thierry Fournier46278ff2020-11-29 11:48:12 +01001563 lua_pushfstring(lua->T, "[state-id %d] message handler error: %s", lua->state_id, msg);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001564 else
Thierry Fournier46278ff2020-11-29 11:48:12 +01001565 lua_pushfstring(lua->T, "[state-id %d] message handler error", lua->state_id);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001566 ret = HLUA_E_ERRMSG;
1567 break;
1568
1569 default:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001570 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001571 lua_settop(lua->T, 0); /* Empty the stack. */
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001572 ret = HLUA_E_ERR;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001573 break;
1574 }
1575
1576 switch (ret) {
1577 case HLUA_E_AGAIN:
1578 break;
1579
1580 case HLUA_E_ERRMSG:
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001581 notification_purge(&lua->com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001582 hlua_ctx_renew(lua, 1);
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001583 HLUA_CLR_RUN(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001584 break;
1585
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001586 case HLUA_E_ETMOUT:
1587 case HLUA_E_NOMEM:
1588 case HLUA_E_YIELD:
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001589 case HLUA_E_ERR:
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001590 HLUA_CLR_RUN(lua);
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001591 notification_purge(&lua->com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001592 hlua_ctx_renew(lua, 0);
1593 break;
1594
1595 case HLUA_E_OK:
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001596 HLUA_CLR_RUN(lua);
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001597 notification_purge(&lua->com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001598 break;
1599 }
1600
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +02001601 /* This is the main exit point, remove the Lua lock. */
Thierry Fournier021d9862020-11-28 23:42:03 +01001602 if (lua->state_id == 0)
Willy Tarreau1e7bef12021-08-20 15:47:25 +02001603 lua_drop_global_lock();
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +02001604
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001605 return ret;
1606}
1607
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001608/* This function exit the current code. */
1609__LJMP static int hlua_done(lua_State *L)
1610{
Thierry Fournier4234dbd2020-11-28 13:18:23 +01001611 struct hlua *hlua;
1612
1613 /* Get hlua struct, or NULL if we execute from main lua state */
1614 hlua = hlua_gethlua(L);
1615 if (!hlua)
1616 return 0;
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001617
1618 hlua->flags |= HLUA_EXIT;
1619 WILL_LJMP(lua_error(L));
1620
1621 return 0;
1622}
1623
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001624/* This function is an LUA binding. It provides a function
1625 * for deleting ACL from a referenced ACL file.
1626 */
1627__LJMP static int hlua_del_acl(lua_State *L)
1628{
1629 const char *name;
1630 const char *key;
1631 struct pat_ref *ref;
1632
1633 MAY_LJMP(check_args(L, 2, "del_acl"));
1634
1635 name = MAY_LJMP(luaL_checkstring(L, 1));
1636 key = MAY_LJMP(luaL_checkstring(L, 2));
1637
1638 ref = pat_ref_lookup(name);
1639 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001640 WILL_LJMP(luaL_error(L, "'del_acl': unknown acl file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001641
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001642 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001643 pat_ref_delete(ref, key);
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001644 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001645 return 0;
1646}
1647
1648/* This function is an LUA binding. It provides a function
1649 * for deleting map entry from a referenced map file.
1650 */
1651static int hlua_del_map(lua_State *L)
1652{
1653 const char *name;
1654 const char *key;
1655 struct pat_ref *ref;
1656
1657 MAY_LJMP(check_args(L, 2, "del_map"));
1658
1659 name = MAY_LJMP(luaL_checkstring(L, 1));
1660 key = MAY_LJMP(luaL_checkstring(L, 2));
1661
1662 ref = pat_ref_lookup(name);
1663 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001664 WILL_LJMP(luaL_error(L, "'del_map': unknown acl file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001665
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001666 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001667 pat_ref_delete(ref, key);
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001668 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001669 return 0;
1670}
1671
1672/* This function is an LUA binding. It provides a function
1673 * for adding ACL pattern from a referenced ACL file.
1674 */
1675static int hlua_add_acl(lua_State *L)
1676{
1677 const char *name;
1678 const char *key;
1679 struct pat_ref *ref;
1680
1681 MAY_LJMP(check_args(L, 2, "add_acl"));
1682
1683 name = MAY_LJMP(luaL_checkstring(L, 1));
1684 key = MAY_LJMP(luaL_checkstring(L, 2));
1685
1686 ref = pat_ref_lookup(name);
1687 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001688 WILL_LJMP(luaL_error(L, "'add_acl': unknown acl file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001689
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001690 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001691 if (pat_ref_find_elt(ref, key) == NULL)
1692 pat_ref_add(ref, key, NULL, NULL);
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001693 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001694 return 0;
1695}
1696
1697/* This function is an LUA binding. It provides a function
1698 * for setting map pattern and sample from a referenced map
1699 * file.
1700 */
1701static int hlua_set_map(lua_State *L)
1702{
1703 const char *name;
1704 const char *key;
1705 const char *value;
1706 struct pat_ref *ref;
1707
1708 MAY_LJMP(check_args(L, 3, "set_map"));
1709
1710 name = MAY_LJMP(luaL_checkstring(L, 1));
1711 key = MAY_LJMP(luaL_checkstring(L, 2));
1712 value = MAY_LJMP(luaL_checkstring(L, 3));
1713
1714 ref = pat_ref_lookup(name);
1715 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001716 WILL_LJMP(luaL_error(L, "'set_map': unknown map file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001717
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001718 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001719 if (pat_ref_find_elt(ref, key) != NULL)
1720 pat_ref_set(ref, key, value, NULL);
1721 else
1722 pat_ref_add(ref, key, value, NULL);
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001723 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001724 return 0;
1725}
1726
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01001727/* A class is a lot of memory that contain data. This data can be a table,
1728 * an integer or user data. This data is associated with a metatable. This
Ilya Shipitsinc02a23f2020-05-06 00:53:22 +05001729 * metatable have an original version registered in the global context with
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01001730 * the name of the object (_G[<name>] = <metable> ).
1731 *
1732 * A metable is a table that modify the standard behavior of a standard
1733 * access to the associated data. The entries of this new metatable are
1734 * defined as is:
1735 *
1736 * http://lua-users.org/wiki/MetatableEvents
1737 *
1738 * __index
1739 *
1740 * we access an absent field in a table, the result is nil. This is
1741 * true, but it is not the whole truth. Actually, such access triggers
1742 * the interpreter to look for an __index metamethod: If there is no
1743 * such method, as usually happens, then the access results in nil;
1744 * otherwise, the metamethod will provide the result.
1745 *
1746 * Control 'prototype' inheritance. When accessing "myTable[key]" and
1747 * the key does not appear in the table, but the metatable has an __index
1748 * property:
1749 *
1750 * - if the value is a function, the function is called, passing in the
1751 * table and the key; the return value of that function is returned as
1752 * the result.
1753 *
1754 * - if the value is another table, the value of the key in that table is
1755 * asked for and returned (and if it doesn't exist in that table, but that
1756 * table's metatable has an __index property, then it continues on up)
1757 *
1758 * - Use "rawget(myTable,key)" to skip this metamethod.
1759 *
1760 * http://www.lua.org/pil/13.4.1.html
1761 *
1762 * __newindex
1763 *
1764 * Like __index, but control property assignment.
1765 *
1766 * __mode - Control weak references. A string value with one or both
1767 * of the characters 'k' and 'v' which specifies that the the
1768 * keys and/or values in the table are weak references.
1769 *
1770 * __call - Treat a table like a function. When a table is followed by
1771 * parenthesis such as "myTable( 'foo' )" and the metatable has
1772 * a __call key pointing to a function, that function is invoked
1773 * (passing any specified arguments) and the return value is
1774 * returned.
1775 *
1776 * __metatable - Hide the metatable. When "getmetatable( myTable )" is
1777 * called, if the metatable for myTable has a __metatable
1778 * key, the value of that key is returned instead of the
1779 * actual metatable.
1780 *
1781 * __tostring - Control string representation. When the builtin
1782 * "tostring( myTable )" function is called, if the metatable
1783 * for myTable has a __tostring property set to a function,
1784 * that function is invoked (passing myTable to it) and the
1785 * return value is used as the string representation.
1786 *
1787 * __len - Control table length. When the table length is requested using
1788 * the length operator ( '#' ), if the metatable for myTable has
1789 * a __len key pointing to a function, that function is invoked
1790 * (passing myTable to it) and the return value used as the value
1791 * of "#myTable".
1792 *
1793 * __gc - Userdata finalizer code. When userdata is set to be garbage
1794 * collected, if the metatable has a __gc field pointing to a
1795 * function, that function is first invoked, passing the userdata
1796 * to it. The __gc metamethod is not called for tables.
1797 * (See http://lua-users.org/lists/lua-l/2006-11/msg00508.html)
1798 *
1799 * Special metamethods for redefining standard operators:
1800 * http://www.lua.org/pil/13.1.html
1801 *
1802 * __add "+"
1803 * __sub "-"
1804 * __mul "*"
1805 * __div "/"
1806 * __unm "!"
1807 * __pow "^"
1808 * __concat ".."
1809 *
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001810 * Special methods for redefining standard relations
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01001811 * http://www.lua.org/pil/13.2.html
1812 *
1813 * __eq "=="
1814 * __lt "<"
1815 * __le "<="
1816 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001817
1818/*
1819 *
1820 *
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001821 * Class Map
1822 *
1823 *
1824 */
1825
1826/* Returns a struct hlua_map if the stack entry "ud" is
1827 * a class session, otherwise it throws an error.
1828 */
1829__LJMP static struct map_descriptor *hlua_checkmap(lua_State *L, int ud)
1830{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02001831 return MAY_LJMP(hlua_checkudata(L, ud, class_map_ref));
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001832}
1833
1834/* This function is the map constructor. It don't need
1835 * the class Map object. It creates and return a new Map
1836 * object. It must be called only during "body" or "init"
1837 * context because it process some filesystem accesses.
1838 */
1839__LJMP static int hlua_map_new(struct lua_State *L)
1840{
1841 const char *fn;
1842 int match = PAT_MATCH_STR;
1843 struct sample_conv conv;
1844 const char *file = "";
1845 int line = 0;
1846 lua_Debug ar;
1847 char *err = NULL;
1848 struct arg args[2];
1849
1850 if (lua_gettop(L) < 1 || lua_gettop(L) > 2)
1851 WILL_LJMP(luaL_error(L, "'new' needs at least 1 argument."));
1852
1853 fn = MAY_LJMP(luaL_checkstring(L, 1));
1854
1855 if (lua_gettop(L) >= 2) {
1856 match = MAY_LJMP(luaL_checkinteger(L, 2));
1857 if (match < 0 || match >= PAT_MATCH_NUM)
1858 WILL_LJMP(luaL_error(L, "'new' needs a valid match method."));
1859 }
1860
1861 /* Get Lua filename and line number. */
1862 if (lua_getstack(L, 1, &ar)) { /* check function at level */
1863 lua_getinfo(L, "Sl", &ar); /* get info about it */
1864 if (ar.currentline > 0) { /* is there info? */
1865 file = ar.short_src;
1866 line = ar.currentline;
1867 }
1868 }
1869
1870 /* fill fake sample_conv struct. */
1871 conv.kw = ""; /* unused. */
1872 conv.process = NULL; /* unused. */
1873 conv.arg_mask = 0; /* unused. */
1874 conv.val_args = NULL; /* unused. */
1875 conv.out_type = SMP_T_STR;
1876 conv.private = (void *)(long)match;
1877 switch (match) {
1878 case PAT_MATCH_STR: conv.in_type = SMP_T_STR; break;
1879 case PAT_MATCH_BEG: conv.in_type = SMP_T_STR; break;
1880 case PAT_MATCH_SUB: conv.in_type = SMP_T_STR; break;
1881 case PAT_MATCH_DIR: conv.in_type = SMP_T_STR; break;
1882 case PAT_MATCH_DOM: conv.in_type = SMP_T_STR; break;
1883 case PAT_MATCH_END: conv.in_type = SMP_T_STR; break;
1884 case PAT_MATCH_REG: conv.in_type = SMP_T_STR; break;
Thierry FOURNIER07ee64e2015-07-06 23:43:03 +02001885 case PAT_MATCH_INT: conv.in_type = SMP_T_SINT; break;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001886 case PAT_MATCH_IP: conv.in_type = SMP_T_ADDR; break;
1887 default:
1888 WILL_LJMP(luaL_error(L, "'new' doesn't support this match mode."));
1889 }
1890
1891 /* fill fake args. */
1892 args[0].type = ARGT_STR;
Christopher Faulet73292e92020-08-06 08:40:09 +02001893 args[0].data.str.area = strdup(fn);
1894 args[0].data.str.data = strlen(fn);
1895 args[0].data.str.size = args[0].data.str.data+1;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001896 args[1].type = ARGT_STOP;
1897
1898 /* load the map. */
1899 if (!sample_load_map(args, &conv, file, line, &err)) {
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +05001900 /* error case: we can't use luaL_error because we must
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001901 * free the err variable.
1902 */
1903 luaL_where(L, 1);
1904 lua_pushfstring(L, "'new': %s.", err);
1905 lua_concat(L, 2);
1906 free(err);
Christopher Faulet6ad7df42020-08-07 11:45:18 +02001907 chunk_destroy(&args[0].data.str);
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001908 WILL_LJMP(lua_error(L));
1909 }
1910
1911 /* create the lua object. */
1912 lua_newtable(L);
1913 lua_pushlightuserdata(L, args[0].data.map);
1914 lua_rawseti(L, -2, 0);
1915
1916 /* Pop a class Map metatable and affect it to the userdata. */
1917 lua_rawgeti(L, LUA_REGISTRYINDEX, class_map_ref);
1918 lua_setmetatable(L, -2);
1919
1920
1921 return 1;
1922}
1923
1924__LJMP static inline int _hlua_map_lookup(struct lua_State *L, int str)
1925{
1926 struct map_descriptor *desc;
1927 struct pattern *pat;
1928 struct sample smp;
1929
1930 MAY_LJMP(check_args(L, 2, "lookup"));
1931 desc = MAY_LJMP(hlua_checkmap(L, 1));
Thierry FOURNIER07ee64e2015-07-06 23:43:03 +02001932 if (desc->pat.expect_type == SMP_T_SINT) {
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02001933 smp.data.type = SMP_T_SINT;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +02001934 smp.data.u.sint = MAY_LJMP(luaL_checkinteger(L, 2));
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001935 }
1936 else {
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02001937 smp.data.type = SMP_T_STR;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001938 smp.flags = SMP_F_CONST;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001939 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 +01001940 smp.data.u.str.size = smp.data.u.str.data + 1;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001941 }
1942
1943 pat = pattern_exec_match(&desc->pat, &smp, 1);
Thierry FOURNIER503bb092015-08-19 08:35:43 +02001944 if (!pat || !pat->data) {
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001945 if (str)
1946 lua_pushstring(L, "");
1947 else
1948 lua_pushnil(L);
1949 return 1;
1950 }
1951
1952 /* The Lua pattern must return a string, so we can't check the returned type */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001953 lua_pushlstring(L, pat->data->u.str.area, pat->data->u.str.data);
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001954 return 1;
1955}
1956
1957__LJMP static int hlua_map_lookup(struct lua_State *L)
1958{
1959 return _hlua_map_lookup(L, 0);
1960}
1961
1962__LJMP static int hlua_map_slookup(struct lua_State *L)
1963{
1964 return _hlua_map_lookup(L, 1);
1965}
1966
1967/*
1968 *
1969 *
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001970 * Class Socket
1971 *
1972 *
1973 */
1974
1975__LJMP static struct hlua_socket *hlua_checksocket(lua_State *L, int ud)
1976{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02001977 return MAY_LJMP(hlua_checkudata(L, ud, class_socket_ref));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001978}
1979
1980/* This function is the handler called for each I/O on the established
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001981 * connection. It is used for notify space available to send or data
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001982 * received.
1983 */
Willy Tarreau00a37f02015-04-13 12:05:19 +02001984static void hlua_socket_handler(struct appctx *appctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001985{
Willy Tarreau5321da92022-05-06 11:57:34 +02001986 struct hlua_csk_ctx *ctx = appctx->svcctx;
Willy Tarreauc12b3212022-05-27 11:08:15 +02001987 struct stconn *sc = appctx_sc(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001988
Willy Tarreau5321da92022-05-06 11:57:34 +02001989 if (ctx->die) {
Willy Tarreau3e7be362022-05-27 10:35:27 +02001990 sc_shutw(sc);
1991 sc_shutr(sc);
1992 sc_ic(sc)->flags |= CF_READ_NULL;
Willy Tarreau5321da92022-05-06 11:57:34 +02001993 notification_wake(&ctx->wake_on_read);
1994 notification_wake(&ctx->wake_on_write);
Willy Tarreau3e7be362022-05-27 10:35:27 +02001995 stream_shutdown(__sc_strm(sc), SF_ERR_KILLED);
Thierry FOURNIERb13b20a2017-07-16 20:48:54 +02001996 }
1997
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +05001998 /* If we can't write, wakeup the pending write signals. */
Willy Tarreau3e7be362022-05-27 10:35:27 +02001999 if (channel_output_closed(sc_ic(sc)))
Willy Tarreau5321da92022-05-06 11:57:34 +02002000 notification_wake(&ctx->wake_on_write);
Thierry FOURNIER6d695e62015-09-27 19:29:38 +02002001
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +05002002 /* If we can't read, wakeup the pending read signals. */
Willy Tarreau3e7be362022-05-27 10:35:27 +02002003 if (channel_input_closed(sc_oc(sc)))
Willy Tarreau5321da92022-05-06 11:57:34 +02002004 notification_wake(&ctx->wake_on_read);
Thierry FOURNIER6d695e62015-09-27 19:29:38 +02002005
Willy Tarreau5a0b25d2019-07-18 18:01:14 +02002006 /* if the connection is not established, inform the stream that we want
Thierry FOURNIER316e3192015-09-04 18:25:53 +02002007 * to be notified whenever the connection completes.
2008 */
Willy Tarreau3e7be362022-05-27 10:35:27 +02002009 if (sc_opposite(sc)->state < SC_ST_EST) {
Willy Tarreau90e8b452022-05-25 18:21:43 +02002010 applet_need_more_data(appctx);
Willy Tarreaub23edc82022-05-24 16:49:03 +02002011 se_need_remote_conn(appctx->sedesc);
Willy Tarreau4164eb92022-05-25 15:42:03 +02002012 applet_have_more_data(appctx);
Willy Tarreaud4da1962015-04-20 01:31:23 +02002013 return;
Thierry FOURNIER316e3192015-09-04 18:25:53 +02002014 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002015
2016 /* This function is called after the connect. */
Willy Tarreau5321da92022-05-06 11:57:34 +02002017 ctx->connected = 1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002018
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002019 /* Wake the tasks which wants to write if the buffer have available space. */
Willy Tarreau3e7be362022-05-27 10:35:27 +02002020 if (channel_may_recv(sc_ic(sc)))
Willy Tarreau5321da92022-05-06 11:57:34 +02002021 notification_wake(&ctx->wake_on_write);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002022
2023 /* Wake the tasks which wants to read if the buffer contains data. */
Willy Tarreau3e7be362022-05-27 10:35:27 +02002024 if (!channel_is_empty(sc_oc(sc)))
Willy Tarreau5321da92022-05-06 11:57:34 +02002025 notification_wake(&ctx->wake_on_read);
Thierry FOURNIER101b9762018-05-27 01:27:40 +02002026
2027 /* Some data were injected in the buffer, notify the stream
2028 * interface.
2029 */
Willy Tarreau3e7be362022-05-27 10:35:27 +02002030 if (!channel_is_empty(sc_ic(sc)))
2031 sc_update(sc);
Thierry FOURNIER101b9762018-05-27 01:27:40 +02002032
2033 /* If write notifications are registered, we considers we want
Willy Tarreau3367d412018-11-15 10:57:41 +01002034 * to write, so we clear the blocking flag.
Thierry FOURNIER101b9762018-05-27 01:27:40 +02002035 */
Willy Tarreau5321da92022-05-06 11:57:34 +02002036 if (notification_registered(&ctx->wake_on_write))
Willy Tarreau4164eb92022-05-25 15:42:03 +02002037 applet_have_more_data(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002038}
2039
Christopher Faulet5f35a3e2022-05-12 15:31:05 +02002040static int hlua_socket_init(struct appctx *appctx)
2041{
2042 struct hlua_csk_ctx *ctx = appctx->svcctx;
2043 struct stream *s;
2044
2045 if (appctx_finalize_startup(appctx, socket_proxy, &BUF_NULL) == -1)
2046 goto error;
2047
2048 s = appctx_strm(appctx);
2049
Willy Tarreau4596fe22022-05-17 19:07:51 +02002050 /* Configure "right" stream connector. This stconn is used to connect
Christopher Faulet5f35a3e2022-05-12 15:31:05 +02002051 * and retrieve data from the server. The connection is initialized
2052 * with the "struct server".
2053 */
Willy Tarreau74568cf2022-05-27 09:03:30 +02002054 sc_set_state(s->scb, SC_ST_ASS);
Christopher Faulet5f35a3e2022-05-12 15:31:05 +02002055
2056 /* Force destination server. */
2057 s->flags |= SF_DIRECT | SF_ASSIGNED | SF_BE_ASSIGNED;
2058 s->target = &socket_tcp->obj_type;
2059
2060 ctx->appctx = appctx;
2061 return 0;
2062
2063 error:
2064 return -1;
2065}
2066
Willy Tarreau87b09662015-04-03 00:22:06 +02002067/* This function is called when the "struct stream" is destroyed.
2068 * Remove the link from the object to this stream.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002069 * Wake all the pending signals.
2070 */
Willy Tarreau00a37f02015-04-13 12:05:19 +02002071static void hlua_socket_release(struct appctx *appctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002072{
Willy Tarreau5321da92022-05-06 11:57:34 +02002073 struct hlua_csk_ctx *ctx = appctx->svcctx;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002074 struct xref *peer;
2075
Christopher Faulet5f35a3e2022-05-12 15:31:05 +02002076 /* Remove my link in the original objects. */
Willy Tarreau5321da92022-05-06 11:57:34 +02002077 peer = xref_get_peer_and_lock(&ctx->xref);
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002078 if (peer)
Willy Tarreau5321da92022-05-06 11:57:34 +02002079 xref_disconnect(&ctx->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002080
2081 /* Wake all the task waiting for me. */
Willy Tarreau5321da92022-05-06 11:57:34 +02002082 notification_wake(&ctx->wake_on_read);
2083 notification_wake(&ctx->wake_on_write);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002084}
2085
2086/* If the garbage collectio of the object is launch, nobody
Willy Tarreau87b09662015-04-03 00:22:06 +02002087 * uses this object. If the stream does not exists, just quit.
2088 * Send the shutdown signal to the stream. In some cases,
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002089 * pending signal can rest in the read and write lists. destroy
2090 * it.
2091 */
2092__LJMP static int hlua_socket_gc(lua_State *L)
2093{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002094 struct hlua_socket *socket;
Willy Tarreau5321da92022-05-06 11:57:34 +02002095 struct hlua_csk_ctx *ctx;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002096 struct xref *peer;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002097
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002098 MAY_LJMP(check_args(L, 1, "__gc"));
2099
2100 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002101 peer = xref_get_peer_and_lock(&socket->xref);
2102 if (!peer)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002103 return 0;
Willy Tarreau5321da92022-05-06 11:57:34 +02002104
2105 ctx = container_of(peer, struct hlua_csk_ctx, xref);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002106
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002107 /* Set the flag which destroy the session. */
Willy Tarreau5321da92022-05-06 11:57:34 +02002108 ctx->die = 1;
2109 appctx_wakeup(ctx->appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002110
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002111 /* Remove all reference between the Lua stack and the coroutine stream. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002112 xref_disconnect(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002113 return 0;
2114}
2115
2116/* The close function send shutdown signal and break the
Willy Tarreau87b09662015-04-03 00:22:06 +02002117 * links between the stream and the object.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002118 */
sada05ed3302018-05-11 11:48:18 -07002119__LJMP static int hlua_socket_close_helper(lua_State *L)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002120{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002121 struct hlua_socket *socket;
Willy Tarreau5321da92022-05-06 11:57:34 +02002122 struct hlua_csk_ctx *ctx;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002123 struct xref *peer;
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002124 struct hlua *hlua;
2125
2126 /* Get hlua struct, or NULL if we execute from main lua state */
2127 hlua = hlua_gethlua(L);
2128 if (!hlua)
2129 return 0;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002130
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002131 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002132
2133 /* Check if we run on the same thread than the xreator thread.
2134 * We cannot access to the socket if the thread is different.
2135 */
2136 if (socket->tid != tid)
2137 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2138
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002139 peer = xref_get_peer_and_lock(&socket->xref);
2140 if (!peer)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002141 return 0;
Willy Tarreauf31af932020-01-14 09:59:38 +01002142
2143 hlua->gc_count--;
Willy Tarreau5321da92022-05-06 11:57:34 +02002144 ctx = container_of(peer, struct hlua_csk_ctx, xref);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002145
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002146 /* Set the flag which destroy the session. */
Willy Tarreau5321da92022-05-06 11:57:34 +02002147 ctx->die = 1;
2148 appctx_wakeup(ctx->appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002149
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002150 /* Remove all reference between the Lua stack and the coroutine stream. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002151 xref_disconnect(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002152 return 0;
2153}
2154
sada05ed3302018-05-11 11:48:18 -07002155/* The close function calls close_helper.
2156 */
2157__LJMP static int hlua_socket_close(lua_State *L)
2158{
2159 MAY_LJMP(check_args(L, 1, "close"));
2160 return hlua_socket_close_helper(L);
2161}
2162
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002163/* This Lua function assumes that the stack contain three parameters.
2164 * 1 - USERDATA containing a struct socket
2165 * 2 - INTEGER with values of the macro defined below
2166 * If the integer is -1, we must read at most one line.
2167 * If the integer is -2, we ust read all the data until the
2168 * end of the stream.
2169 * If the integer is positive value, we must read a number of
2170 * bytes corresponding to this value.
2171 */
2172#define HLSR_READ_LINE (-1)
2173#define HLSR_READ_ALL (-2)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002174__LJMP static int hlua_socket_receive_yield(struct lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002175{
2176 struct hlua_socket *socket = MAY_LJMP(hlua_checksocket(L, 1));
2177 int wanted = lua_tointeger(L, 2);
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002178 struct hlua *hlua;
Willy Tarreau5321da92022-05-06 11:57:34 +02002179 struct hlua_csk_ctx *csk_ctx;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002180 struct appctx *appctx;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02002181 size_t len;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002182 int nblk;
Willy Tarreau206ba832018-06-14 15:27:31 +02002183 const char *blk1;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02002184 size_t len1;
Willy Tarreau206ba832018-06-14 15:27:31 +02002185 const char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02002186 size_t len2;
Thierry FOURNIER00543922015-03-09 18:35:06 +01002187 int skip_at_end = 0;
Willy Tarreau81389672015-03-10 12:03:52 +01002188 struct channel *oc;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002189 struct stream *s;
2190 struct xref *peer;
Thierry FOURNIER8c126c72018-05-25 16:27:44 +02002191 int missing_bytes;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002192
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002193 /* Get hlua struct, or NULL if we execute from main lua state */
2194 hlua = hlua_gethlua(L);
2195
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002196 /* Check if this lua stack is schedulable. */
2197 if (!hlua || !hlua->task)
2198 WILL_LJMP(luaL_error(L, "The 'receive' function is only allowed in "
2199 "'frontend', 'backend' or 'task'"));
2200
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002201 /* Check if we run on the same thread than the xreator thread.
2202 * We cannot access to the socket if the thread is different.
2203 */
2204 if (socket->tid != tid)
2205 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2206
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002207 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002208 peer = xref_get_peer_and_lock(&socket->xref);
2209 if (!peer)
2210 goto no_peer;
Willy Tarreau5321da92022-05-06 11:57:34 +02002211
2212 csk_ctx = container_of(peer, struct hlua_csk_ctx, xref);
2213 appctx = csk_ctx->appctx;
Willy Tarreau0698c802022-05-11 14:09:57 +02002214 s = appctx_strm(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002215
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002216 oc = &s->res;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002217 if (wanted == HLSR_READ_LINE) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002218 /* Read line. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02002219 nblk = co_getline_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002220 if (nblk < 0) /* Connection close. */
2221 goto connection_closed;
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002222 if (nblk == 0) /* No data available. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002223 goto connection_empty;
Thierry FOURNIER00543922015-03-09 18:35:06 +01002224
2225 /* remove final \r\n. */
2226 if (nblk == 1) {
2227 if (blk1[len1-1] == '\n') {
2228 len1--;
2229 skip_at_end++;
2230 if (blk1[len1-1] == '\r') {
2231 len1--;
2232 skip_at_end++;
2233 }
2234 }
2235 }
2236 else {
2237 if (blk2[len2-1] == '\n') {
2238 len2--;
2239 skip_at_end++;
2240 if (blk2[len2-1] == '\r') {
2241 len2--;
2242 skip_at_end++;
2243 }
2244 }
2245 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002246 }
2247
2248 else if (wanted == HLSR_READ_ALL) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002249 /* Read all the available data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02002250 nblk = co_getblk_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002251 if (nblk < 0) /* Connection close. */
2252 goto connection_closed;
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002253 if (nblk == 0) /* No data available. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002254 goto connection_empty;
2255 }
2256
2257 else {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002258 /* Read a block of data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02002259 nblk = co_getblk_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002260 if (nblk < 0) /* Connection close. */
2261 goto connection_closed;
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002262 if (nblk == 0) /* No data available. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002263 goto connection_empty;
2264
Thierry FOURNIER8c126c72018-05-25 16:27:44 +02002265 missing_bytes = wanted - socket->b.n;
2266 if (len1 > missing_bytes) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002267 nblk = 1;
Thierry FOURNIER8c126c72018-05-25 16:27:44 +02002268 len1 = missing_bytes;
2269 } if (nblk == 2 && len1 + len2 > missing_bytes)
2270 len2 = missing_bytes - len1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002271 }
2272
2273 len = len1;
2274
2275 luaL_addlstring(&socket->b, blk1, len1);
2276 if (nblk == 2) {
2277 len += len2;
2278 luaL_addlstring(&socket->b, blk2, len2);
2279 }
2280
2281 /* Consume data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02002282 co_skip(oc, len + skip_at_end);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002283
2284 /* Don't wait anything. */
Thierry FOURNIER7e4ee472018-05-25 15:03:50 +02002285 appctx_wakeup(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002286
2287 /* If the pattern reclaim to read all the data
2288 * in the connection, got out.
2289 */
2290 if (wanted == HLSR_READ_ALL)
2291 goto connection_empty;
Thierry FOURNIER8c126c72018-05-25 16:27:44 +02002292 else if (wanted >= 0 && socket->b.n < wanted)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002293 goto connection_empty;
2294
2295 /* Return result. */
2296 luaL_pushresult(&socket->b);
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002297 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002298 return 1;
2299
2300connection_closed:
2301
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002302 xref_unlock(&socket->xref, peer);
2303
2304no_peer:
2305
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002306 /* If the buffer containds data. */
2307 if (socket->b.n > 0) {
2308 luaL_pushresult(&socket->b);
2309 return 1;
2310 }
2311 lua_pushnil(L);
2312 lua_pushstring(L, "connection closed.");
2313 return 2;
2314
2315connection_empty:
2316
Willy Tarreau5321da92022-05-06 11:57:34 +02002317 if (!notification_new(&hlua->com, &csk_ctx->wake_on_read, hlua->task)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002318 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002319 WILL_LJMP(luaL_error(L, "out of memory"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002320 }
2321 xref_unlock(&socket->xref, peer);
Willy Tarreau9635e032018-10-16 17:52:55 +02002322 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_receive_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002323 return 0;
2324}
2325
Tim Duesterhusb33754c2018-01-04 19:32:14 +01002326/* This Lua function gets two parameters. The first one can be string
2327 * or a number. If the string is "*l", the user requires one line. If
2328 * the string is "*a", the user requires all the contents of the stream.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002329 * If the value is a number, the user require a number of bytes equal
2330 * to the value. The default value is "*l" (a line).
2331 *
Tim Duesterhusb33754c2018-01-04 19:32:14 +01002332 * This parameter with a variable type is converted in integer. This
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002333 * integer takes this values:
2334 * -1 : read a line
2335 * -2 : read all the stream
Tim Duesterhusb33754c2018-01-04 19:32:14 +01002336 * >0 : amount of bytes.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002337 *
Tim Duesterhusb33754c2018-01-04 19:32:14 +01002338 * The second parameter is optional. It contains a string that must be
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002339 * concatenated with the read data.
2340 */
2341__LJMP static int hlua_socket_receive(struct lua_State *L)
2342{
2343 int wanted = HLSR_READ_LINE;
2344 const char *pattern;
Christopher Fauletc31b2002021-05-03 10:11:13 +02002345 int lastarg, type;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002346 char *error;
2347 size_t len;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002348 struct hlua_socket *socket;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002349
2350 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
2351 WILL_LJMP(luaL_error(L, "The 'receive' function requires between 1 and 3 arguments."));
2352
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002353 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002354
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002355 /* Check if we run on the same thread than the xreator thread.
2356 * We cannot access to the socket if the thread is different.
2357 */
2358 if (socket->tid != tid)
2359 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2360
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002361 /* check for pattern. */
2362 if (lua_gettop(L) >= 2) {
2363 type = lua_type(L, 2);
2364 if (type == LUA_TSTRING) {
2365 pattern = lua_tostring(L, 2);
2366 if (strcmp(pattern, "*a") == 0)
2367 wanted = HLSR_READ_ALL;
2368 else if (strcmp(pattern, "*l") == 0)
2369 wanted = HLSR_READ_LINE;
2370 else {
2371 wanted = strtoll(pattern, &error, 10);
2372 if (*error != '\0')
2373 WILL_LJMP(luaL_error(L, "Unsupported pattern."));
2374 }
2375 }
2376 else if (type == LUA_TNUMBER) {
2377 wanted = lua_tointeger(L, 2);
2378 if (wanted < 0)
2379 WILL_LJMP(luaL_error(L, "Unsupported size."));
2380 }
2381 }
2382
2383 /* Set pattern. */
2384 lua_pushinteger(L, wanted);
Tim Duesterhusc6e377e2018-01-04 19:32:13 +01002385
2386 /* Check if we would replace the top by itself. */
2387 if (lua_gettop(L) != 2)
2388 lua_replace(L, 2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002389
Christopher Fauletc31b2002021-05-03 10:11:13 +02002390 /* Save index of the top of the stack because since buffers are used, it
2391 * may change
2392 */
2393 lastarg = lua_gettop(L);
2394
Tim Duesterhusb33754c2018-01-04 19:32:14 +01002395 /* init buffer, and fill it with prefix. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002396 luaL_buffinit(L, &socket->b);
2397
2398 /* Check prefix. */
Christopher Fauletc31b2002021-05-03 10:11:13 +02002399 if (lastarg >= 3) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002400 if (lua_type(L, 3) != LUA_TSTRING)
2401 WILL_LJMP(luaL_error(L, "Expect a 'string' for the prefix"));
2402 pattern = lua_tolstring(L, 3, &len);
2403 luaL_addlstring(&socket->b, pattern, len);
2404 }
2405
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002406 return __LJMP(hlua_socket_receive_yield(L, 0, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002407}
2408
2409/* Write the Lua input string in the output buffer.
Mark Lakes22154b42018-01-29 14:38:40 -08002410 * This function returns a yield if no space is available.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002411 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002412static int hlua_socket_write_yield(struct lua_State *L,int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002413{
2414 struct hlua_socket *socket;
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002415 struct hlua *hlua;
Willy Tarreau5321da92022-05-06 11:57:34 +02002416 struct hlua_csk_ctx *csk_ctx;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002417 struct appctx *appctx;
2418 size_t buf_len;
2419 const char *buf;
2420 int len;
2421 int send_len;
2422 int sent;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002423 struct xref *peer;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002424 struct stream *s;
Willy Tarreau3e7be362022-05-27 10:35:27 +02002425 struct stconn *sc;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002426
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002427 /* Get hlua struct, or NULL if we execute from main lua state */
2428 hlua = hlua_gethlua(L);
2429
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002430 /* Check if this lua stack is schedulable. */
2431 if (!hlua || !hlua->task)
2432 WILL_LJMP(luaL_error(L, "The 'write' function is only allowed in "
2433 "'frontend', 'backend' or 'task'"));
2434
2435 /* Get object */
2436 socket = MAY_LJMP(hlua_checksocket(L, 1));
2437 buf = MAY_LJMP(luaL_checklstring(L, 2, &buf_len));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002438 sent = MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002439
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002440 /* Check if we run on the same thread than the xreator thread.
2441 * We cannot access to the socket if the thread is different.
2442 */
2443 if (socket->tid != tid)
2444 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2445
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002446 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002447 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002448 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002449 lua_pushinteger(L, -1);
2450 return 1;
2451 }
Willy Tarreau5321da92022-05-06 11:57:34 +02002452
2453 csk_ctx = container_of(peer, struct hlua_csk_ctx, xref);
2454 appctx = csk_ctx->appctx;
Willy Tarreauc12b3212022-05-27 11:08:15 +02002455 sc = appctx_sc(appctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02002456 s = __sc_strm(sc);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002457
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002458 /* Check for connection close. */
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002459 if (channel_output_closed(&s->req)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002460 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002461 lua_pushinteger(L, -1);
2462 return 1;
2463 }
2464
2465 /* Update the input buffer data. */
2466 buf += sent;
2467 send_len = buf_len - sent;
2468
2469 /* All the data are sent. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002470 if (sent >= buf_len) {
2471 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002472 return 1; /* Implicitly return the length sent. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002473 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002474
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002475 /* Check if the buffer is available because HAProxy doesn't allocate
Thierry FOURNIER486d52a2015-03-09 17:51:43 +01002476 * the request buffer if its not required.
2477 */
Willy Tarreauc9fa0482018-07-10 17:43:27 +02002478 if (s->req.buf.size == 0) {
Willy Tarreau3e7be362022-05-27 10:35:27 +02002479 if (!sc_alloc_ibuf(sc, &appctx->buffer_wait))
Christopher Faulet33834b12016-12-19 09:29:06 +01002480 goto hlua_socket_write_yield_return;
Thierry FOURNIER486d52a2015-03-09 17:51:43 +01002481 }
2482
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002483 /* Check for available space. */
Willy Tarreauc9fa0482018-07-10 17:43:27 +02002484 len = b_room(&s->req.buf);
Christopher Faulet33834b12016-12-19 09:29:06 +01002485 if (len <= 0) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002486 goto hlua_socket_write_yield_return;
Christopher Faulet33834b12016-12-19 09:29:06 +01002487 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002488
2489 /* send data */
2490 if (len < send_len)
2491 send_len = len;
Thierry FOURNIER66b89192018-05-27 01:14:47 +02002492 len = ci_putblk(&s->req, buf, send_len);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002493
2494 /* "Not enough space" (-1), "Buffer too little to contain
2495 * the data" (-2) are not expected because the available length
2496 * is tested.
2497 * Other unknown error are also not expected.
2498 */
2499 if (len <= 0) {
Willy Tarreaubc18da12015-03-13 14:00:47 +01002500 if (len == -1)
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002501 s->req.flags |= CF_WAKE_WRITE;
Willy Tarreaubc18da12015-03-13 14:00:47 +01002502
sada05ed3302018-05-11 11:48:18 -07002503 MAY_LJMP(hlua_socket_close_helper(L));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002504 lua_pop(L, 1);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002505 lua_pushinteger(L, -1);
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002506 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002507 return 1;
2508 }
2509
2510 /* update buffers. */
Thierry FOURNIER101b9762018-05-27 01:27:40 +02002511 appctx_wakeup(appctx);
Willy Tarreaude70fa12015-09-26 11:25:05 +02002512
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002513 s->req.rex = TICK_ETERNITY;
2514 s->res.wex = TICK_ETERNITY;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002515
2516 /* Update length sent. */
2517 lua_pop(L, 1);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002518 lua_pushinteger(L, sent + len);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002519
2520 /* All the data buffer is sent ? */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002521 if (sent + len >= buf_len) {
2522 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002523 return 1;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002524 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002525
2526hlua_socket_write_yield_return:
Willy Tarreau5321da92022-05-06 11:57:34 +02002527 if (!notification_new(&hlua->com, &csk_ctx->wake_on_write, hlua->task)) {
Thierry FOURNIERba42fcd2018-05-27 00:59:48 +02002528 xref_unlock(&socket->xref, peer);
2529 WILL_LJMP(luaL_error(L, "out of memory"));
2530 }
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002531 xref_unlock(&socket->xref, peer);
Willy Tarreau9635e032018-10-16 17:52:55 +02002532 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_write_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002533 return 0;
2534}
2535
2536/* This function initiate the send of data. It just check the input
2537 * parameters and push an integer in the Lua stack that contain the
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002538 * amount of data written to the buffer. This is used by the function
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002539 * "hlua_socket_write_yield" that can yield.
2540 *
2541 * The Lua function gets between 3 and 4 parameters. The first one is
2542 * the associated object. The second is a string buffer. The third is
2543 * a facultative integer that represents where is the buffer position
2544 * of the start of the data that can send. The first byte is the
2545 * position "1". The default value is "1". The fourth argument is a
2546 * facultative integer that represents where is the buffer position
2547 * of the end of the data that can send. The default is the last byte.
2548 */
2549static int hlua_socket_send(struct lua_State *L)
2550{
2551 int i;
2552 int j;
2553 const char *buf;
2554 size_t buf_len;
2555
2556 /* Check number of arguments. */
2557 if (lua_gettop(L) < 2 || lua_gettop(L) > 4)
2558 WILL_LJMP(luaL_error(L, "'send' needs between 2 and 4 arguments"));
2559
2560 /* Get the string. */
2561 buf = MAY_LJMP(luaL_checklstring(L, 2, &buf_len));
2562
2563 /* Get and check j. */
2564 if (lua_gettop(L) == 4) {
2565 j = MAY_LJMP(luaL_checkinteger(L, 4));
2566 if (j < 0)
2567 j = buf_len + j + 1;
2568 if (j > buf_len)
2569 j = buf_len + 1;
2570 lua_pop(L, 1);
2571 }
2572 else
2573 j = buf_len;
2574
2575 /* Get and check i. */
2576 if (lua_gettop(L) == 3) {
2577 i = MAY_LJMP(luaL_checkinteger(L, 3));
2578 if (i < 0)
2579 i = buf_len + i + 1;
2580 if (i > buf_len)
2581 i = buf_len + 1;
2582 lua_pop(L, 1);
2583 } else
2584 i = 1;
2585
2586 /* Check bth i and j. */
2587 if (i > j) {
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002588 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002589 return 1;
2590 }
2591 if (i == 0 && j == 0) {
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002592 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002593 return 1;
2594 }
2595 if (i == 0)
2596 i = 1;
2597 if (j == 0)
2598 j = 1;
2599
2600 /* Pop the string. */
2601 lua_pop(L, 1);
2602
2603 /* Update the buffer length. */
2604 buf += i - 1;
2605 buf_len = j - i + 1;
2606 lua_pushlstring(L, buf, buf_len);
2607
2608 /* This unsigned is used to remember the amount of sent data. */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002609 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002610
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002611 return MAY_LJMP(hlua_socket_write_yield(L, 0, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002612}
2613
Willy Tarreau22b0a682015-06-17 19:43:49 +02002614#define SOCKET_INFO_MAX_LEN sizeof("[0000:0000:0000:0000:0000:0000:0000:0000]:12345")
Christopher Faulete6465b32021-10-22 15:36:08 +02002615__LJMP static inline int hlua_socket_info(struct lua_State *L, const struct sockaddr_storage *addr)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002616{
2617 static char buffer[SOCKET_INFO_MAX_LEN];
2618 int ret;
2619 int len;
2620 char *p;
2621
2622 ret = addr_to_str(addr, buffer+1, SOCKET_INFO_MAX_LEN-1);
2623 if (ret <= 0) {
2624 lua_pushnil(L);
2625 return 1;
2626 }
2627
2628 if (ret == AF_UNIX) {
2629 lua_pushstring(L, buffer+1);
2630 return 1;
2631 }
2632 else if (ret == AF_INET6) {
2633 buffer[0] = '[';
2634 len = strlen(buffer);
2635 buffer[len] = ']';
2636 len++;
2637 buffer[len] = ':';
2638 len++;
2639 p = buffer;
2640 }
2641 else if (ret == AF_INET) {
2642 p = buffer + 1;
2643 len = strlen(p);
2644 p[len] = ':';
2645 len++;
2646 }
2647 else {
2648 lua_pushnil(L);
2649 return 1;
2650 }
2651
2652 if (port_to_str(addr, p + len, SOCKET_INFO_MAX_LEN-1 - len) <= 0) {
2653 lua_pushnil(L);
2654 return 1;
2655 }
2656
2657 lua_pushstring(L, p);
2658 return 1;
2659}
2660
2661/* Returns information about the peer of the connection. */
2662__LJMP static int hlua_socket_getpeername(struct lua_State *L)
2663{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002664 struct hlua_socket *socket;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002665 struct xref *peer;
2666 struct appctx *appctx;
Willy Tarreau3e7be362022-05-27 10:35:27 +02002667 struct stconn *sc;
Christopher Faulet16f16af2021-10-27 09:34:56 +02002668 const struct sockaddr_storage *dst;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002669 int ret;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002670
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002671 MAY_LJMP(check_args(L, 1, "getpeername"));
2672
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002673 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002674
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002675 /* Check if we run on the same thread than the xreator thread.
2676 * We cannot access to the socket if the thread is different.
2677 */
2678 if (socket->tid != tid)
2679 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2680
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002681 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002682 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002683 if (!peer) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002684 lua_pushnil(L);
2685 return 1;
2686 }
Willy Tarreau5321da92022-05-06 11:57:34 +02002687
2688 appctx = container_of(peer, struct hlua_csk_ctx, xref)->appctx;
Willy Tarreauc12b3212022-05-27 11:08:15 +02002689 sc = appctx_sc(appctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02002690 dst = sc_dst(sc_opposite(sc));
Christopher Faulet16f16af2021-10-27 09:34:56 +02002691 if (!dst) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002692 xref_unlock(&socket->xref, peer);
Willy Tarreaua71f6422016-11-16 17:00:14 +01002693 lua_pushnil(L);
2694 return 1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002695 }
2696
Christopher Faulet16f16af2021-10-27 09:34:56 +02002697 ret = MAY_LJMP(hlua_socket_info(L, dst));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002698 xref_unlock(&socket->xref, peer);
2699 return ret;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002700}
2701
2702/* Returns information about my connection side. */
2703static int hlua_socket_getsockname(struct lua_State *L)
2704{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002705 struct hlua_socket *socket;
2706 struct connection *conn;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002707 struct appctx *appctx;
2708 struct xref *peer;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002709 struct stream *s;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002710 int ret;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002711
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002712 MAY_LJMP(check_args(L, 1, "getsockname"));
2713
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002714 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002715
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002716 /* Check if we run on the same thread than the xreator thread.
2717 * We cannot access to the socket if the thread is different.
2718 */
2719 if (socket->tid != tid)
2720 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2721
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002722 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002723 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002724 if (!peer) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002725 lua_pushnil(L);
2726 return 1;
2727 }
Willy Tarreau5321da92022-05-06 11:57:34 +02002728
2729 appctx = container_of(peer, struct hlua_csk_ctx, xref)->appctx;
Willy Tarreau0698c802022-05-11 14:09:57 +02002730 s = appctx_strm(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002731
Willy Tarreaufd9417b2022-05-18 16:23:22 +02002732 conn = sc_conn(s->scb);
Willy Tarreau5a0b25d2019-07-18 18:01:14 +02002733 if (!conn || !conn_get_src(conn)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002734 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002735 lua_pushnil(L);
2736 return 1;
2737 }
2738
Willy Tarreau9da9a6f2019-07-17 14:49:44 +02002739 ret = hlua_socket_info(L, conn->src);
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002740 xref_unlock(&socket->xref, peer);
2741 return ret;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002742}
2743
2744/* This struct define the applet. */
Willy Tarreau30576452015-04-13 13:50:30 +02002745static struct applet update_applet = {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002746 .obj_type = OBJ_TYPE_APPLET,
2747 .name = "<LUA_TCP>",
2748 .fct = hlua_socket_handler,
Christopher Faulet5f35a3e2022-05-12 15:31:05 +02002749 .init = hlua_socket_init,
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002750 .release = hlua_socket_release,
2751};
2752
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002753__LJMP static int hlua_socket_connect_yield(struct lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002754{
2755 struct hlua_socket *socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002756 struct hlua *hlua;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002757 struct xref *peer;
Willy Tarreau5321da92022-05-06 11:57:34 +02002758 struct hlua_csk_ctx *csk_ctx;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002759 struct appctx *appctx;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002760 struct stream *s;
2761
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002762 /* Get hlua struct, or NULL if we execute from main lua state */
2763 hlua = hlua_gethlua(L);
2764 if (!hlua)
2765 return 0;
2766
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002767 /* Check if we run on the same thread than the xreator thread.
2768 * We cannot access to the socket if the thread is different.
2769 */
2770 if (socket->tid != tid)
2771 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2772
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002773 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002774 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002775 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002776 lua_pushnil(L);
2777 lua_pushstring(L, "Can't connect");
2778 return 2;
2779 }
Willy Tarreau5321da92022-05-06 11:57:34 +02002780
2781 csk_ctx = container_of(peer, struct hlua_csk_ctx, xref);
2782 appctx = csk_ctx->appctx;
Willy Tarreau0698c802022-05-11 14:09:57 +02002783 s = appctx_strm(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002784
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002785 /* Check if we run on the same thread than the xreator thread.
2786 * We cannot access to the socket if the thread is different.
2787 */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002788 if (socket->tid != tid) {
2789 xref_unlock(&socket->xref, peer);
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002790 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002791 }
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002792
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002793 /* Check for connection close. */
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002794 if (!hlua || channel_output_closed(&s->req)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002795 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002796 lua_pushnil(L);
2797 lua_pushstring(L, "Can't connect");
2798 return 2;
2799 }
2800
Willy Tarreau8e7c6e62022-05-18 17:58:02 +02002801 appctx = __sc_appctx(s->scf);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002802
2803 /* Check for connection established. */
Willy Tarreau5321da92022-05-06 11:57:34 +02002804 if (csk_ctx->connected) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002805 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002806 lua_pushinteger(L, 1);
2807 return 1;
2808 }
2809
Willy Tarreau5321da92022-05-06 11:57:34 +02002810 if (!notification_new(&hlua->com, &csk_ctx->wake_on_write, hlua->task)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002811 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002812 WILL_LJMP(luaL_error(L, "out of memory error"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002813 }
2814 xref_unlock(&socket->xref, peer);
Willy Tarreau9635e032018-10-16 17:52:55 +02002815 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_connect_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002816 return 0;
2817}
2818
2819/* This function fail or initite the connection. */
2820__LJMP static int hlua_socket_connect(struct lua_State *L)
2821{
2822 struct hlua_socket *socket;
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002823 int port = -1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002824 const char *ip;
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002825 struct hlua *hlua;
Willy Tarreau5321da92022-05-06 11:57:34 +02002826 struct hlua_csk_ctx *csk_ctx;
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002827 struct appctx *appctx;
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002828 int low, high;
2829 struct sockaddr_storage *addr;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002830 struct xref *peer;
Willy Tarreau3e7be362022-05-27 10:35:27 +02002831 struct stconn *sc;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002832 struct stream *s;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002833
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002834 if (lua_gettop(L) < 2)
2835 WILL_LJMP(luaL_error(L, "connect: need at least 2 arguments"));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002836
2837 /* Get args. */
2838 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002839
2840 /* Check if we run on the same thread than the xreator thread.
2841 * We cannot access to the socket if the thread is different.
2842 */
2843 if (socket->tid != tid)
2844 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2845
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002846 ip = MAY_LJMP(luaL_checkstring(L, 2));
Tim Duesterhus6edab862018-01-06 19:04:45 +01002847 if (lua_gettop(L) >= 3) {
2848 luaL_Buffer b;
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002849 port = MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002850
Tim Duesterhus6edab862018-01-06 19:04:45 +01002851 /* Force the ip to end with a colon, to support IPv6 addresses
2852 * that are not enclosed within square brackets.
2853 */
2854 if (port > 0) {
2855 luaL_buffinit(L, &b);
2856 luaL_addstring(&b, ip);
2857 luaL_addchar(&b, ':');
2858 luaL_pushresult(&b);
2859 ip = lua_tolstring(L, lua_gettop(L), NULL);
2860 }
2861 }
2862
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002863 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002864 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002865 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002866 lua_pushnil(L);
2867 return 1;
2868 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002869
2870 /* Parse ip address. */
Willy Tarreau5fc93282020-09-16 18:25:03 +02002871 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 +02002872 if (!addr) {
2873 xref_unlock(&socket->xref, peer);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002874 WILL_LJMP(luaL_error(L, "connect: cannot parse destination address '%s'", ip));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002875 }
Willy Tarreau9da9a6f2019-07-17 14:49:44 +02002876
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002877 /* Set port. */
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002878 if (low == 0) {
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02002879 if (addr->ss_family == AF_INET) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002880 if (port == -1) {
2881 xref_unlock(&socket->xref, peer);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002882 WILL_LJMP(luaL_error(L, "connect: port missing"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002883 }
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02002884 ((struct sockaddr_in *)addr)->sin_port = htons(port);
2885 } else if (addr->ss_family == AF_INET6) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002886 if (port == -1) {
2887 xref_unlock(&socket->xref, peer);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002888 WILL_LJMP(luaL_error(L, "connect: port missing"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002889 }
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02002890 ((struct sockaddr_in6 *)addr)->sin6_port = htons(port);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002891 }
2892 }
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02002893
Willy Tarreau5321da92022-05-06 11:57:34 +02002894 csk_ctx = container_of(peer, struct hlua_csk_ctx, xref);
2895 appctx = csk_ctx->appctx;
Willy Tarreauc12b3212022-05-27 11:08:15 +02002896 sc = appctx_sc(appctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02002897 s = __sc_strm(sc);
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02002898
Willy Tarreau3e7be362022-05-27 10:35:27 +02002899 if (!sockaddr_alloc(&sc_opposite(sc)->dst, addr, sizeof(*addr))) {
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02002900 xref_unlock(&socket->xref, peer);
2901 WILL_LJMP(luaL_error(L, "connect: internal error"));
2902 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002903
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002904 /* Get hlua struct, or NULL if we execute from main lua state */
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002905 hlua = hlua_gethlua(L);
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002906 if (!hlua)
2907 return 0;
Willy Tarreaubdc97a82015-08-24 15:42:28 +02002908
2909 /* inform the stream that we want to be notified whenever the
2910 * connection completes.
2911 */
Willy Tarreau90e8b452022-05-25 18:21:43 +02002912 applet_need_more_data(appctx);
Willy Tarreau4164eb92022-05-25 15:42:03 +02002913 applet_have_more_data(appctx);
Thierry FOURNIER8c8fbbe2015-09-26 17:02:35 +02002914 appctx_wakeup(appctx);
Willy Tarreaubdc97a82015-08-24 15:42:28 +02002915
Willy Tarreauf31af932020-01-14 09:59:38 +01002916 hlua->gc_count++;
Thierry FOURNIER7c39ab42015-09-27 22:53:33 +02002917
Willy Tarreau5321da92022-05-06 11:57:34 +02002918 if (!notification_new(&hlua->com, &csk_ctx->wake_on_write, hlua->task)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002919 xref_unlock(&socket->xref, peer);
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002920 WILL_LJMP(luaL_error(L, "out of memory"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002921 }
2922 xref_unlock(&socket->xref, peer);
PiBa-NL706d5ee2018-05-05 23:51:42 +02002923
2924 task_wakeup(s->task, TASK_WOKEN_INIT);
2925 /* Return yield waiting for connection. */
2926
Willy Tarreau9635e032018-10-16 17:52:55 +02002927 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_connect_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002928
2929 return 0;
2930}
2931
Baptiste Assmann84bb4932015-03-02 21:40:06 +01002932#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002933__LJMP static int hlua_socket_connect_ssl(struct lua_State *L)
2934{
2935 struct hlua_socket *socket;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002936 struct xref *peer;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002937 struct stream *s;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002938
2939 MAY_LJMP(check_args(L, 3, "connect_ssl"));
2940 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002941
2942 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002943 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002944 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002945 lua_pushnil(L);
2946 return 1;
2947 }
Willy Tarreau5321da92022-05-06 11:57:34 +02002948
Willy Tarreau0698c802022-05-11 14:09:57 +02002949 s = appctx_strm(container_of(peer, struct hlua_csk_ctx, xref)->appctx);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002950
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +01002951 s->target = &socket_ssl->obj_type;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002952 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002953 return MAY_LJMP(hlua_socket_connect(L));
2954}
Baptiste Assmann84bb4932015-03-02 21:40:06 +01002955#endif
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002956
2957__LJMP static int hlua_socket_setoption(struct lua_State *L)
2958{
2959 return 0;
2960}
2961
2962__LJMP static int hlua_socket_settimeout(struct lua_State *L)
2963{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002964 struct hlua_socket *socket;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002965 int tmout;
Mark Lakes56cc1252018-03-27 09:48:06 +02002966 double dtmout;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002967 struct xref *peer;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002968 struct stream *s;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002969
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002970 MAY_LJMP(check_args(L, 2, "settimeout"));
2971
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002972 socket = MAY_LJMP(hlua_checksocket(L, 1));
Mark Lakes56cc1252018-03-27 09:48:06 +02002973
Cyril Bonté7ee465f2018-08-19 22:08:50 +02002974 /* convert the timeout to millis */
2975 dtmout = MAY_LJMP(luaL_checknumber(L, 2)) * 1000;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002976
Thierry Fournier17a921b2018-03-08 09:59:02 +01002977 /* Check for negative values */
Mark Lakes56cc1252018-03-27 09:48:06 +02002978 if (dtmout < 0)
Thierry Fournier17a921b2018-03-08 09:59:02 +01002979 WILL_LJMP(luaL_error(L, "settimeout: cannot set negatives values"));
2980
Mark Lakes56cc1252018-03-27 09:48:06 +02002981 if (dtmout > INT_MAX) /* overflow check */
Cyril Bonté7ee465f2018-08-19 22:08:50 +02002982 WILL_LJMP(luaL_error(L, "settimeout: cannot set values larger than %d ms", INT_MAX));
Mark Lakes56cc1252018-03-27 09:48:06 +02002983
2984 tmout = MS_TO_TICKS((int)dtmout);
Cyril Bonté7ee465f2018-08-19 22:08:50 +02002985 if (tmout == 0)
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05002986 tmout++; /* very small timeouts are adjusted to a minimum of 1ms */
Mark Lakes56cc1252018-03-27 09:48:06 +02002987
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002988 /* Check if we run on the same thread than the xreator thread.
2989 * We cannot access to the socket if the thread is different.
2990 */
2991 if (socket->tid != tid)
2992 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2993
Mark Lakes56cc1252018-03-27 09:48:06 +02002994 /* check for connection break. If some data were read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002995 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002996 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002997 hlua_pusherror(L, "socket: not yet initialised, you can't set timeouts.");
2998 WILL_LJMP(lua_error(L));
2999 return 0;
3000 }
Willy Tarreau5321da92022-05-06 11:57:34 +02003001
Willy Tarreau0698c802022-05-11 14:09:57 +02003002 s = appctx_strm(container_of(peer, struct hlua_csk_ctx, xref)->appctx);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003003
Cyril Bonté7bb63452018-08-17 23:51:02 +02003004 s->sess->fe->timeout.connect = tmout;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003005 s->req.rto = tmout;
3006 s->req.wto = tmout;
3007 s->res.rto = tmout;
3008 s->res.wto = tmout;
Cyril Bonté7bb63452018-08-17 23:51:02 +02003009 s->req.rex = tick_add_ifset(now_ms, tmout);
3010 s->req.wex = tick_add_ifset(now_ms, tmout);
3011 s->res.rex = tick_add_ifset(now_ms, tmout);
3012 s->res.wex = tick_add_ifset(now_ms, tmout);
3013
3014 s->task->expire = tick_add_ifset(now_ms, tmout);
3015 task_queue(s->task);
3016
Thierry FOURNIER952939d2017-09-01 14:17:32 +02003017 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003018
Thierry Fourniere9636f12018-03-08 09:54:32 +01003019 lua_pushinteger(L, 1);
Tim Duesterhus119a5f12018-01-06 19:16:25 +01003020 return 1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003021}
3022
3023__LJMP static int hlua_socket_new(lua_State *L)
3024{
3025 struct hlua_socket *socket;
Willy Tarreau5321da92022-05-06 11:57:34 +02003026 struct hlua_csk_ctx *ctx;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003027 struct appctx *appctx;
3028
3029 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003030 if (!lua_checkstack(L, 3)) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003031 hlua_pusherror(L, "socket: full stack");
3032 goto out_fail_conf;
3033 }
3034
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003035 /* Create the object: obj[0] = userdata. */
3036 lua_newtable(L);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003037 socket = MAY_LJMP(lua_newuserdata(L, sizeof(*socket)));
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003038 lua_rawseti(L, -2, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003039 memset(socket, 0, sizeof(*socket));
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02003040 socket->tid = tid;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003041
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05003042 /* Check if the various memory pools are initialized. */
Willy Tarreaubafbe012017-11-24 17:34:44 +01003043 if (!pool_head_stream || !pool_head_buffer) {
Thierry FOURNIER4a6170c2015-03-09 17:07:10 +01003044 hlua_pusherror(L, "socket: uninitialized pools.");
3045 goto out_fail_conf;
3046 }
3047
Willy Tarreau87b09662015-04-03 00:22:06 +02003048 /* Pop a class stream metatable and affect it to the userdata. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003049 lua_rawgeti(L, LUA_REGISTRYINDEX, class_socket_ref);
3050 lua_setmetatable(L, -2);
3051
Willy Tarreaud420a972015-04-06 00:39:18 +02003052 /* Create the applet context */
Christopher Faulet6095d572022-05-16 17:09:48 +02003053 appctx = appctx_new_here(&update_applet, NULL);
Willy Tarreau61cf7c82015-04-06 00:48:33 +02003054 if (!appctx) {
3055 hlua_pusherror(L, "socket: out of memory");
Christopher Fauleta9e8b392022-03-23 11:01:09 +01003056 goto out_fail_conf;
Willy Tarreau61cf7c82015-04-06 00:48:33 +02003057 }
Willy Tarreau5321da92022-05-06 11:57:34 +02003058 ctx = applet_reserve_svcctx(appctx, sizeof(*ctx));
3059 ctx->connected = 0;
Willy Tarreau5321da92022-05-06 11:57:34 +02003060 ctx->die = 0;
3061 LIST_INIT(&ctx->wake_on_write);
3062 LIST_INIT(&ctx->wake_on_read);
Willy Tarreaub2bf8332015-04-04 15:58:58 +02003063
Christopher Faulet5f35a3e2022-05-12 15:31:05 +02003064 if (appctx_init(appctx) == -1) {
3065 hlua_pusherror(L, "socket: fail to init applet.");
Christopher Faulet13a35e52021-12-20 15:34:16 +01003066 goto out_fail_appctx;
3067 }
3068
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003069 /* Initialise cross reference between stream and Lua socket object. */
Willy Tarreau5321da92022-05-06 11:57:34 +02003070 xref_create(&socket->xref, &ctx->xref);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003071 return 1;
3072
Christopher Faulet13a35e52021-12-20 15:34:16 +01003073 out_fail_appctx:
Christopher Faulet5f35a3e2022-05-12 15:31:05 +02003074 appctx_free_on_early_error(appctx);
Willy Tarreaud420a972015-04-06 00:39:18 +02003075 out_fail_conf:
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003076 WILL_LJMP(lua_error(L));
3077 return 0;
3078}
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01003079
3080/*
3081 *
3082 *
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003083 * Class Channel
3084 *
3085 *
3086 */
3087
3088/* Returns the struct hlua_channel join to the class channel in the
3089 * stack entry "ud" or throws an argument error.
3090 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01003091__LJMP static struct channel *hlua_checkchannel(lua_State *L, int ud)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003092{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003093 return MAY_LJMP(hlua_checkudata(L, ud, class_channel_ref));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003094}
3095
Willy Tarreau47860ed2015-03-10 14:07:50 +01003096/* Pushes the channel onto the top of the stack. If the stask does not have a
3097 * free slots, the function fails and returns 0;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003098 */
Willy Tarreau2a71af42015-03-10 13:51:50 +01003099static int hlua_channel_new(lua_State *L, struct channel *channel)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003100{
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003101 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003102 if (!lua_checkstack(L, 3))
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003103 return 0;
3104
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003105 lua_newtable(L);
Willy Tarreau47860ed2015-03-10 14:07:50 +01003106 lua_pushlightuserdata(L, channel);
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003107 lua_rawseti(L, -2, 0);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003108
3109 /* Pop a class sesison metatable and affect it to the userdata. */
3110 lua_rawgeti(L, LUA_REGISTRYINDEX, class_channel_ref);
3111 lua_setmetatable(L, -2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003112 return 1;
3113}
3114
Christopher Faulet9f55a502020-02-25 15:21:02 +01003115/* Helper function returning a filter attached to a channel at the position <ud>
3116 * in the stack, filling the current offset and length of the filter. If no
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05003117 * filter is attached, NULL is returned and <offset> and <len> are not
Christopher Faulet9f55a502020-02-25 15:21:02 +01003118 * initialized.
3119 */
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003120static 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 +01003121{
3122 struct filter *filter = NULL;
3123
3124 if (lua_getfield(L, ud, "__filter") == LUA_TLIGHTUSERDATA) {
3125 struct hlua_flt_ctx *flt_ctx;
3126
3127 filter = lua_touserdata (L, -1);
3128 flt_ctx = filter->ctx;
3129 if (hlua_filter_from_payload(filter)) {
3130 *offset = flt_ctx->cur_off[CHN_IDX(chn)];
3131 *len = flt_ctx->cur_len[CHN_IDX(chn)];
3132 }
3133 }
3134
3135 lua_pop(L, 1);
3136 return filter;
3137}
3138
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003139/* Copies <len> bytes of data present in the channel's buffer, starting at the
3140* offset <offset>, and put it in a LUA string variable. It is the caller
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003141* responsibility to ensure <len> and <offset> are valid. It always return the
3142* length of the built string. <len> may be 0, in this case, an empty string is
3143* created and 0 is returned.
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003144*/
3145static inline int _hlua_channel_dup(struct channel *chn, lua_State *L, size_t offset, size_t len)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003146{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003147 size_t block1, block2;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003148 luaL_Buffer b;
3149
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003150 block1 = len;
3151 if (block1 > b_contig_data(&chn->buf, b_peek_ofs(&chn->buf, offset)))
3152 block1 = b_contig_data(&chn->buf, b_peek_ofs(&chn->buf, offset));
3153 block2 = len - block1;
3154
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003155 luaL_buffinit(L, &b);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003156 luaL_addlstring(&b, b_peek(&chn->buf, offset), block1);
3157 if (block2)
3158 luaL_addlstring(&b, b_orig(&chn->buf), block2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003159 luaL_pushresult(&b);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003160 return len;
3161}
3162
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003163/* Inserts the string <str> to the channel's buffer at the offset <offset>. This
3164 * function returns -1 if data cannot be copied. Otherwise, it returns the
3165 * number of bytes copied.
3166 */
3167static int _hlua_channel_insert(struct channel *chn, lua_State *L, struct ist str, size_t offset)
3168{
3169 int ret = 0;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003170
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003171 /* Nothing to do, just return */
3172 if (unlikely(istlen(str) == 0))
3173 goto end;
3174
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003175 if (istlen(str) > c_room(chn)) {
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003176 ret = -1;
3177 goto end;
3178 }
3179 ret = b_insert_blk(&chn->buf, offset, istptr(str), istlen(str));
3180
3181 end:
3182 return ret;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003183}
3184
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003185/* Removes <len> bytes of data at the absolute position <offset>.
3186 */
3187static void _hlua_channel_delete(struct channel *chn, size_t offset, size_t len)
3188{
3189 size_t end = offset + len;
3190
3191 if (b_peek(&chn->buf, end) != b_tail(&chn->buf))
3192 b_move(&chn->buf, b_peek_ofs(&chn->buf, end),
3193 b_data(&chn->buf) - end, -len);
3194 b_sub(&chn->buf, len);
3195}
3196
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003197/* Copies input data in the channel's buffer. It is possible to set a specific
3198 * offset (0 by default) and a length (all remaining input data starting for the
3199 * offset by default). If there is not enough input data and more data can be
3200 * received, this function yields.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003201 *
3202 * From an action, All input data are considered. For a filter, the offset and
3203 * the length of input data to consider are retrieved from the filter context.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003204 */
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003205__LJMP static int hlua_channel_get_data_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003206{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003207 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003208 struct filter *filter;
3209 size_t input, output;
3210 int offset, len;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003211
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003212 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003213
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003214 output = co_data(chn);
3215 input = ci_data(chn);
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003216
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003217 filter = hlua_channel_filter(L, 1, chn, &output, &input);
3218 if (filter && !hlua_filter_from_payload(filter))
3219 WILL_LJMP(lua_error(L));
3220
3221 offset = output;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003222 if (lua_gettop(L) > 1) {
3223 offset = MAY_LJMP(luaL_checkinteger(L, 2));
3224 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02003225 offset = MAX(0, (int)input + offset);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003226 offset += output;
3227 if (offset < output || offset > input + output) {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003228 lua_pushfstring(L, "offset out of range.");
3229 WILL_LJMP(lua_error(L));
3230 }
3231 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003232 len = output + input - offset;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003233 if (lua_gettop(L) == 3) {
3234 len = MAY_LJMP(luaL_checkinteger(L, 3));
3235 if (!len)
3236 goto dup;
3237 if (len == -1)
3238 len = global.tune.bufsize;
3239 if (len < 0) {
3240 lua_pushfstring(L, "length out of range.");
3241 WILL_LJMP(lua_error(L));
3242 }
3243 }
3244
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003245 if (offset + len > output + input) {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003246 if (!HLUA_CANT_YIELD(hlua_gethlua(L)) && !channel_input_closed(chn) && channel_may_recv(chn)) {
3247 /* Yield waiting for more data, as requested */
3248 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_get_data_yield, TICK_ETERNITY, 0));
3249 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003250 len = output + input - offset;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003251 }
3252
3253 dup:
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003254 _hlua_channel_dup(chn, L, offset, len);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003255 return 1;
3256}
3257
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003258/* Copies the first line (including the trailing LF) of input data in the
3259 * channel's buffer. It is possible to set a specific offset (0 by default) and
3260 * a length (all remaining input data starting for the offset by default). If
3261 * there is not enough input data and more data can be received, the function
3262 * yields. If a length is explicitly specified, no more data are
3263 * copied. Otherwise, if no LF is found and more data can be received, this
3264 * function yields.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003265 *
3266 * From an action, All input data are considered. For a filter, the offset and
3267 * the length of input data to consider are retrieved from the filter context.
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003268 */
3269__LJMP static int hlua_channel_get_line_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003270{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003271 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003272 struct filter *filter;
3273 size_t l, input, output;
3274 int offset, len;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003275
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003276 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003277 output = co_data(chn);
3278 input = ci_data(chn);
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003279
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003280 filter = hlua_channel_filter(L, 1, chn, &output, &input);
3281 if (filter && !hlua_filter_from_payload(filter))
3282 WILL_LJMP(lua_error(L));
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003283
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003284 offset = output;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003285 if (lua_gettop(L) > 1) {
3286 offset = MAY_LJMP(luaL_checkinteger(L, 2));
3287 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02003288 offset = MAX(0, (int)input + offset);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003289 offset += output;
3290 if (offset < output || offset > input + output) {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003291 lua_pushfstring(L, "offset out of range.");
3292 WILL_LJMP(lua_error(L));
3293 }
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003294 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003295
3296 len = output + input - offset;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003297 if (lua_gettop(L) == 3) {
3298 len = MAY_LJMP(luaL_checkinteger(L, 3));
3299 if (!len)
3300 goto dup;
3301 if (len == -1)
3302 len = global.tune.bufsize;
3303 if (len < 0) {
3304 lua_pushfstring(L, "length out of range.");
3305 WILL_LJMP(lua_error(L));
3306 }
3307 }
3308
3309 for (l = 0; l < len; l++) {
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003310 if (l + offset >= output + input)
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003311 break;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003312 if (*(b_peek(&chn->buf, offset + l)) == '\n') {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003313 len = l+1;
3314 goto dup;
3315 }
3316 }
3317
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003318 if (offset + len > output + input) {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003319 if (!HLUA_CANT_YIELD(hlua_gethlua(L)) && !channel_input_closed(chn) && channel_may_recv(chn)) {
3320 /* Yield waiting for more data */
3321 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_get_line_yield, TICK_ETERNITY, 0));
3322 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003323 len = output + input - offset;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003324 }
3325
3326 dup:
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003327 _hlua_channel_dup(chn, L, offset, len);
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003328 return 1;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003329}
3330
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003331/* [ DEPRECATED ]
3332 *
3333 * Duplicate all input data foud in the channel's buffer. The data are not
3334 * removed from the buffer. This function relies on _hlua_channel_dup().
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003335 *
3336 * From an action, All input data are considered. For a filter, the offset and
3337 * the length of input data to consider are retrieved from the filter context.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003338 */
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003339__LJMP static int hlua_channel_dup(lua_State *L)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003340{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003341 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003342 struct filter *filter;
3343 size_t offset, len;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003344
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003345 MAY_LJMP(check_args(L, 1, "dup"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003346 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003347 if (IS_HTX_STRM(chn_strm(chn))) {
3348 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3349 WILL_LJMP(lua_error(L));
3350 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003351
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003352 offset = co_data(chn);
3353 len = ci_data(chn);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003354
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003355 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3356 if (filter && !hlua_filter_from_payload(filter))
3357 WILL_LJMP(lua_error(L));
3358
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003359 if (!ci_data(chn) && channel_input_closed(chn)) {
3360 lua_pushnil(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003361 return 1;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003362 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003363
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003364 _hlua_channel_dup(chn, L, offset, len);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003365 return 1;
3366}
3367
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003368/* [ DEPRECATED ]
3369 *
3370 * Get all input data foud in the channel's buffer. The data are removed from
3371 * the buffer after the copy. This function relies on _hlua_channel_dup() and
3372 * _hlua_channel_delete().
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003373 *
3374 * From an action, All input data are considered. For a filter, the offset and
3375 * the length of input data to consider are retrieved from the filter context.
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003376 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003377__LJMP static int hlua_channel_get(lua_State *L)
3378{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003379 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003380 struct filter *filter;
3381 size_t offset, len;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003382 int ret;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003383
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003384 MAY_LJMP(check_args(L, 1, "get"));
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003385 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3386 if (IS_HTX_STRM(chn_strm(chn))) {
3387 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3388 WILL_LJMP(lua_error(L));
3389 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003390
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003391 offset = co_data(chn);
3392 len = ci_data(chn);
3393
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003394 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3395 if (filter && !hlua_filter_from_payload(filter))
3396 WILL_LJMP(lua_error(L));
3397
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003398 if (!ci_data(chn) && channel_input_closed(chn)) {
3399 lua_pushnil(L);
3400 return 1;
3401 }
3402
3403 ret = _hlua_channel_dup(chn, L, offset, len);
3404 _hlua_channel_delete(chn, offset, ret);
3405 return 1;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003406}
3407
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003408/* This functions consumes and returns one line. If the channel is closed,
3409 * and the last data does not contains a final '\n', the data are returned
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003410 * without the final '\n'. When no more data are available, it returns nil
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003411 * value.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003412 *
3413 * From an action, All input data are considered. For a filter, the offset and
3414 * the length of input data to consider are retrieved from the filter context.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003415 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003416__LJMP static int hlua_channel_getline_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003417{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003418 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003419 struct filter *filter;
3420 size_t l, offset, len;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003421 int ret;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003422
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003423 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003424
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003425 offset = co_data(chn);
3426 len = ci_data(chn);
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003427
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003428 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3429 if (filter && !hlua_filter_from_payload(filter))
3430 WILL_LJMP(lua_error(L));
3431
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003432 if (!ci_data(chn) && channel_input_closed(chn)) {
3433 lua_pushnil(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003434 return 1;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003435 }
3436
3437 for (l = 0; l < len; l++) {
3438 if (*(b_peek(&chn->buf, offset+l)) == '\n') {
3439 len = l+1;
3440 goto dup;
3441 }
3442 }
3443
3444 if (!HLUA_CANT_YIELD(hlua_gethlua(L)) && !channel_input_closed(chn) && channel_may_recv(chn)) {
3445 /* Yield waiting for more data */
3446 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_getline_yield, TICK_ETERNITY, 0));
3447 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003448
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003449 dup:
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003450 ret = _hlua_channel_dup(chn, L, offset, len);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003451 _hlua_channel_delete(chn, offset, ret);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003452 return 1;
3453}
3454
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003455/* [ DEPRECATED ]
3456 *
3457 * Check arguments for the function "hlua_channel_getline_yield".
3458 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003459__LJMP static int hlua_channel_getline(lua_State *L)
3460{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003461 struct channel *chn;
3462
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003463 MAY_LJMP(check_args(L, 1, "getline"));
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003464 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3465 if (IS_HTX_STRM(chn_strm(chn))) {
3466 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3467 WILL_LJMP(lua_error(L));
3468 }
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003469 return MAY_LJMP(hlua_channel_getline_yield(L, 0, 0));
3470}
3471
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003472/* Retrieves a given amount of input data at the given offset. By default all
3473 * available input data are returned. The offset may be negactive to start from
3474 * the end of input data. The length may be -1 to set it to the maximum buffer
3475 * size.
3476 */
3477__LJMP static int hlua_channel_get_data(lua_State *L)
3478{
3479 struct channel *chn;
3480
3481 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
3482 WILL_LJMP(luaL_error(L, "'data' expects at most 2 arguments"));
3483 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3484 if (IS_HTX_STRM(chn_strm(chn))) {
3485 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3486 WILL_LJMP(lua_error(L));
3487 }
3488 return MAY_LJMP(hlua_channel_get_data_yield(L, 0, 0));
3489}
3490
3491/* Retrieves a given amount of input data at the given offset. By default all
3492 * available input data are returned. The offset may be negactive to start from
3493 * the end of input data. The length may be -1 to set it to the maximum buffer
3494 * size.
3495 */
3496__LJMP static int hlua_channel_get_line(lua_State *L)
3497{
3498 struct channel *chn;
3499
3500 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
3501 WILL_LJMP(luaL_error(L, "'line' expects at most 2 arguments"));
3502 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3503 if (IS_HTX_STRM(chn_strm(chn))) {
3504 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3505 WILL_LJMP(lua_error(L));
3506 }
3507 return MAY_LJMP(hlua_channel_get_line_yield(L, 0, 0));
3508}
3509
3510/* Appends a string into the input side of channel. It returns the length of the
3511 * written string, or -1 if the channel is closed or if the buffer size is too
3512 * little for the data. 0 may be returned if nothing is copied. This function
3513 * does not yield.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003514 *
3515 * For a filter, the context is updated on success.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003516 */
Christopher Faulet23976d92021-08-06 09:59:49 +02003517__LJMP static int hlua_channel_append(lua_State *L)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003518{
Christopher Faulet23976d92021-08-06 09:59:49 +02003519 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003520 struct filter *filter;
Christopher Faulet23976d92021-08-06 09:59:49 +02003521 const char *str;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003522 size_t sz, offset, len;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003523 int ret;
Christopher Faulet23976d92021-08-06 09:59:49 +02003524
3525 MAY_LJMP(check_args(L, 2, "append"));
3526 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003527 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
Christopher Faulet1bb6afa2021-03-08 17:57:53 +01003528 if (IS_HTX_STRM(chn_strm(chn))) {
Thierry Fournier77016da2020-08-15 14:35:51 +02003529 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
Christopher Faulet3f829a42018-12-13 21:56:45 +01003530 WILL_LJMP(lua_error(L));
Thierry Fournier77016da2020-08-15 14:35:51 +02003531 }
Christopher Faulet3f829a42018-12-13 21:56:45 +01003532
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003533 offset = co_data(chn);
3534 len = ci_data(chn);
3535
3536 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3537 if (filter && !hlua_filter_from_payload(filter))
3538 WILL_LJMP(lua_error(L));
3539
3540 ret = _hlua_channel_insert(chn, L, ist2(str, sz), offset);
3541 if (ret > 0 && filter) {
3542 struct hlua_flt_ctx *flt_ctx = filter->ctx;
3543
3544 flt_update_offsets(filter, chn, ret);
3545 flt_ctx->cur_len[CHN_IDX(chn)] += ret;
3546 }
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003547 lua_pushinteger(L, ret);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003548 return 1;
3549}
3550
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003551/* Prepends a string into the input side of channel. It returns the length of the
3552 * written string, or -1 if the channel is closed or if the buffer size is too
3553 * little for the data. 0 may be returned if nothing is copied. This function
3554 * does not yield.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003555 *
3556 * For a filter, the context is updated on success.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003557 */
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003558__LJMP static int hlua_channel_prepend(lua_State *L)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003559{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003560 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003561 struct filter *filter;
Christopher Faulet23976d92021-08-06 09:59:49 +02003562 const char *str;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003563 size_t sz, offset, len;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003564 int ret;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003565
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003566 MAY_LJMP(check_args(L, 2, "prepend"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003567 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003568 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
3569 if (IS_HTX_STRM(chn_strm(chn))) {
3570 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3571 WILL_LJMP(lua_error(L));
3572 }
3573
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003574 offset = co_data(chn);
3575 len = ci_data(chn);
3576
3577 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3578 if (filter && !hlua_filter_from_payload(filter))
3579 WILL_LJMP(lua_error(L));
3580
3581 ret = _hlua_channel_insert(chn, L, ist2(str, sz), offset);
3582 if (ret > 0 && filter) {
3583 struct hlua_flt_ctx *flt_ctx = filter->ctx;
3584
3585 flt_update_offsets(filter, chn, ret);
3586 flt_ctx->cur_len[CHN_IDX(chn)] += ret;
3587 }
3588
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003589 lua_pushinteger(L, ret);
3590 return 1;
3591}
3592
3593/* Inserts a given amount of input data at the given offset by a string
Aurelien DARRAGONafb7daf2022-10-04 12:16:05 +02003594 * content. By default the string is appended in front of input data. It
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003595 * returns the length of the written string, or -1 if the channel is closed or
3596 * if the buffer size is too little for the data.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003597 *
3598 * For a filter, the context is updated on success.
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003599 */
3600__LJMP static int hlua_channel_insert_data(lua_State *L)
3601{
3602 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003603 struct filter *filter;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003604 const char *str;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003605 size_t sz, input, output;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003606 int ret, offset;
3607
3608 if (lua_gettop(L) < 2 || lua_gettop(L) > 3)
3609 WILL_LJMP(luaL_error(L, "'insert' expects at least 1 argument and at most 2 arguments"));
3610 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3611 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003612
3613 output = co_data(chn);
3614 input = ci_data(chn);
3615
3616 filter = hlua_channel_filter(L, 1, chn, &output, &input);
3617 if (filter && !hlua_filter_from_payload(filter))
3618 WILL_LJMP(lua_error(L));
3619
Aurelien DARRAGONafb7daf2022-10-04 12:16:05 +02003620 offset = output;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003621 if (lua_gettop(L) > 2) {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003622 offset = MAY_LJMP(luaL_checkinteger(L, 3));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003623 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02003624 offset = MAX(0, (int)input + offset);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003625 offset += output;
Aurelien DARRAGONafb7daf2022-10-04 12:16:05 +02003626 if (offset > output + input) {
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003627 lua_pushfstring(L, "offset out of range.");
3628 WILL_LJMP(lua_error(L));
3629 }
3630 }
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003631 if (IS_HTX_STRM(chn_strm(chn))) {
3632 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3633 WILL_LJMP(lua_error(L));
3634 }
3635
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003636 ret = _hlua_channel_insert(chn, L, ist2(str, sz), offset);
3637 if (ret > 0 && filter) {
3638 struct hlua_flt_ctx *flt_ctx = filter->ctx;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003639
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003640 flt_update_offsets(filter, chn, ret);
3641 flt_ctx->cur_len[CHN_IDX(chn)] += ret;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003642 }
3643
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003644 lua_pushinteger(L, ret);
3645 return 1;
3646}
3647/* Replaces a given amount of input data at the given offset by a string
3648 * content. By default all remaining data are removed (offset = 0 and len =
3649 * -1). It returns the length of the written string, or -1 if the channel is
3650 * closed or if the buffer size is too little for the data.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003651 *
3652 * For a filter, the context is updated on success.
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003653 */
3654__LJMP static int hlua_channel_set_data(lua_State *L)
3655{
3656 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003657 struct filter *filter;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003658 const char *str;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003659 size_t sz, input, output;
3660 int ret, offset, len;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003661
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003662 if (lua_gettop(L) < 2 || lua_gettop(L) > 4)
3663 WILL_LJMP(luaL_error(L, "'set' expects at least 1 argument and at most 3 arguments"));
3664 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3665 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003666
Christopher Faulet1bb6afa2021-03-08 17:57:53 +01003667 if (IS_HTX_STRM(chn_strm(chn))) {
Thierry Fournier77016da2020-08-15 14:35:51 +02003668 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
Christopher Faulet3f829a42018-12-13 21:56:45 +01003669 WILL_LJMP(lua_error(L));
Thierry Fournier77016da2020-08-15 14:35:51 +02003670 }
Christopher Faulet3f829a42018-12-13 21:56:45 +01003671
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003672 output = co_data(chn);
3673 input = ci_data(chn);
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003674
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003675 filter = hlua_channel_filter(L, 1, chn, &output, &input);
3676 if (filter && !hlua_filter_from_payload(filter))
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003677 WILL_LJMP(lua_error(L));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003678
3679 offset = output;
3680 if (lua_gettop(L) > 2) {
3681 offset = MAY_LJMP(luaL_checkinteger(L, 3));
3682 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02003683 offset = MAX(0, (int)input + offset);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003684 offset += output;
3685 if (offset < output || offset > input + output) {
3686 lua_pushfstring(L, "offset out of range.");
3687 WILL_LJMP(lua_error(L));
3688 }
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003689 }
3690
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003691 len = output + input - offset;
3692 if (lua_gettop(L) == 4) {
3693 len = MAY_LJMP(luaL_checkinteger(L, 4));
3694 if (!len)
3695 goto set;
3696 if (len == -1)
3697 len = output + input - offset;
3698 if (len < 0 || offset + len > output + input) {
3699 lua_pushfstring(L, "length out of range.");
3700 WILL_LJMP(lua_error(L));
3701 }
3702 }
3703
3704 set:
Christopher Faulet23976d92021-08-06 09:59:49 +02003705 /* Be sure we can copied the string once input data will be removed. */
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003706 if (sz > c_room(chn) + len)
Christopher Faulet23976d92021-08-06 09:59:49 +02003707 lua_pushinteger(L, -1);
3708 else {
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003709 _hlua_channel_delete(chn, offset, len);
3710 ret = _hlua_channel_insert(chn, L, ist2(str, sz), offset);
3711 if (filter) {
3712 struct hlua_flt_ctx *flt_ctx = filter->ctx;
3713
3714 len -= (ret > 0 ? ret : 0);
3715 flt_update_offsets(filter, chn, -len);
3716 flt_ctx->cur_len[CHN_IDX(chn)] -= len;
3717 }
3718
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003719 lua_pushinteger(L, ret);
Christopher Faulet23976d92021-08-06 09:59:49 +02003720 }
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003721 return 1;
3722}
3723
3724/* Removes a given amount of input data at the given offset. By default all
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003725 * input data are removed (offset = 0 and len = -1). It returns the amount of
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003726 * the removed data.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003727 *
3728 * For a filter, the context is updated on success.
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003729 */
3730__LJMP static int hlua_channel_del_data(lua_State *L)
3731{
3732 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003733 struct filter *filter;
3734 size_t input, output;
3735 int offset, len;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003736
3737 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
3738 WILL_LJMP(luaL_error(L, "'remove' expects at most 2 arguments"));
3739 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003740
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003741 if (IS_HTX_STRM(chn_strm(chn))) {
3742 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3743 WILL_LJMP(lua_error(L));
3744 }
3745
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003746 output = co_data(chn);
3747 input = ci_data(chn);
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003748
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003749 filter = hlua_channel_filter(L, 1, chn, &output, &input);
3750 if (filter && !hlua_filter_from_payload(filter))
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003751 WILL_LJMP(lua_error(L));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003752
3753 offset = output;
Boyang Lie0c54352022-05-10 17:47:23 +00003754 if (lua_gettop(L) > 1) {
3755 offset = MAY_LJMP(luaL_checkinteger(L, 2));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003756 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02003757 offset = MAX(0, (int)input + offset);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003758 offset += output;
3759 if (offset < output || offset > input + output) {
3760 lua_pushfstring(L, "offset out of range.");
3761 WILL_LJMP(lua_error(L));
3762 }
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003763 }
3764
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003765 len = output + input - offset;
Boyang Lie0c54352022-05-10 17:47:23 +00003766 if (lua_gettop(L) == 3) {
3767 len = MAY_LJMP(luaL_checkinteger(L, 3));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003768 if (!len)
3769 goto end;
3770 if (len == -1)
3771 len = output + input - offset;
3772 if (len < 0 || offset + len > output + input) {
3773 lua_pushfstring(L, "length out of range.");
3774 WILL_LJMP(lua_error(L));
3775 }
3776 }
3777
3778 _hlua_channel_delete(chn, offset, len);
3779 if (filter) {
3780 struct hlua_flt_ctx *flt_ctx = filter->ctx;
3781
3782 flt_update_offsets(filter, chn, -len);
3783 flt_ctx->cur_len[CHN_IDX(chn)] -= len;
3784 }
3785
3786 end:
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003787 lua_pushinteger(L, len);
Christopher Faulet23976d92021-08-06 09:59:49 +02003788 return 1;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003789}
3790
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003791/* Append data in the output side of the buffer. This data is immediately
3792 * sent. The function returns the amount of data written. If the buffer
3793 * cannot contain the data, the function yields. The function returns -1
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003794 * if the channel is closed.
3795 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003796__LJMP static int hlua_channel_send_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003797{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003798 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003799 struct filter *filter;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003800 const char *str;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003801 size_t offset, len, sz;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003802 int l, ret;
Thierry Fournier4234dbd2020-11-28 13:18:23 +01003803 struct hlua *hlua;
3804
3805 /* Get hlua struct, or NULL if we execute from main lua state */
3806 hlua = hlua_gethlua(L);
3807 if (!hlua) {
3808 lua_pushnil(L);
3809 return 1;
3810 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003811
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003812 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3813 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
3814 l = MAY_LJMP(luaL_checkinteger(L, 3));
Christopher Faulet3f829a42018-12-13 21:56:45 +01003815
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003816 offset = co_data(chn);
3817 len = ci_data(chn);
3818
3819 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3820 if (filter && !hlua_filter_from_payload(filter))
3821 WILL_LJMP(lua_error(L));
3822
3823
Willy Tarreau47860ed2015-03-10 14:07:50 +01003824 if (unlikely(channel_output_closed(chn))) {
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003825 lua_pushinteger(L, -1);
3826 return 1;
3827 }
3828
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003829 len = c_room(chn);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003830 if (len > sz -l) {
3831 if (filter) {
3832 lua_pushinteger(L, -1);
3833 return 1;
3834 }
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003835 len = sz - l;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003836 }
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01003837
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003838 ret = _hlua_channel_insert(chn, L, ist2(str, len), offset);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003839 if (ret == -1) {
3840 lua_pop(L, 1);
3841 lua_pushinteger(L, -1);
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01003842 return 1;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003843 }
3844 if (ret) {
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003845 if (filter) {
3846 struct hlua_flt_ctx *flt_ctx = filter->ctx;
3847
3848
3849 flt_update_offsets(filter, chn, ret);
3850 FLT_OFF(filter, chn) += ret;
3851 flt_ctx->cur_off[CHN_IDX(chn)] += ret;
3852 }
3853 else
3854 c_adv(chn, ret);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003855
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003856 l += ret;
3857 lua_pop(L, 1);
3858 lua_pushinteger(L, l);
3859 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003860
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003861 if (l < sz) {
3862 /* Yield only if the channel's output is not empty.
3863 * Otherwise it means we cannot add more data. */
3864 if (co_data(chn) == 0 || HLUA_CANT_YIELD(hlua_gethlua(L)))
Christopher Faulet2e60aa42021-08-05 11:58:37 +02003865 return 1;
3866
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003867 /* If we are waiting for space in the response buffer, we
3868 * must set the flag WAKERESWR. This flag required the task
3869 * wake up if any activity is detected on the response buffer.
3870 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01003871 if (chn->flags & CF_ISRESP)
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003872 HLUA_SET_WAKERESWR(hlua);
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01003873 else
3874 HLUA_SET_WAKEREQWR(hlua);
Willy Tarreau9635e032018-10-16 17:52:55 +02003875 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003876 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003877
3878 return 1;
3879}
3880
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05003881/* Just a wrapper of "_hlua_channel_send". This wrapper permits
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003882 * yield the LUA process, and resume it without checking the
3883 * input arguments.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003884 *
3885 * This function cannot be called from a filter.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003886 */
3887__LJMP static int hlua_channel_send(lua_State *L)
3888{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003889 struct channel *chn;
3890
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003891 MAY_LJMP(check_args(L, 2, "send"));
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003892 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3893 if (IS_HTX_STRM(chn_strm(chn))) {
3894 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3895 WILL_LJMP(lua_error(L));
3896 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003897 lua_pushinteger(L, 0);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003898 return MAY_LJMP(hlua_channel_send_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003899}
3900
3901/* This function forward and amount of butes. The data pass from
3902 * the input side of the buffer to the output side, and can be
3903 * forwarded. This function never fails.
3904 *
3905 * The Lua function takes an amount of bytes to be forwarded in
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05003906 * input. It returns the number of bytes forwarded.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003907 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003908__LJMP static int hlua_channel_forward_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003909{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003910 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003911 struct filter *filter;
3912 size_t offset, len, fwd;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003913 int l, max;
Thierry Fournier4234dbd2020-11-28 13:18:23 +01003914 struct hlua *hlua;
3915
3916 /* Get hlua struct, or NULL if we execute from main lua state */
3917 hlua = hlua_gethlua(L);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003918 if (!hlua) {
3919 lua_pushnil(L);
Thierry Fournier4234dbd2020-11-28 13:18:23 +01003920 return 1;
Thierry Fournier77016da2020-08-15 14:35:51 +02003921 }
Christopher Faulet3f829a42018-12-13 21:56:45 +01003922
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003923 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003924 fwd = MAY_LJMP(luaL_checkinteger(L, 2));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003925 l = MAY_LJMP(luaL_checkinteger(L, -1));
3926
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003927 offset = co_data(chn);
3928 len = ci_data(chn);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003929
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003930 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3931 if (filter && !hlua_filter_from_payload(filter))
3932 WILL_LJMP(lua_error(L));
3933
3934 max = fwd - l;
3935 if (max > len)
3936 max = len;
3937
3938 if (filter) {
3939 struct hlua_flt_ctx *flt_ctx = filter->ctx;
3940
3941 FLT_OFF(filter, chn) += max;
3942 flt_ctx->cur_off[CHN_IDX(chn)] += max;
3943 flt_ctx->cur_len[CHN_IDX(chn)] -= max;
3944 }
3945 else
3946 channel_forward(chn, max);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003947
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003948 l += max;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003949 lua_pop(L, 1);
3950 lua_pushinteger(L, l);
3951
3952 /* Check if it miss bytes to forward. */
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003953 if (l < fwd) {
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003954 /* The the input channel or the output channel are closed, we
3955 * must return the amount of data forwarded.
3956 */
Christopher Faulet2e60aa42021-08-05 11:58:37 +02003957 if (channel_input_closed(chn) || channel_output_closed(chn) || HLUA_CANT_YIELD(hlua_gethlua(L)))
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003958 return 1;
3959
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003960 /* If we are waiting for space data in the response buffer, we
3961 * must set the flag WAKERESWR. This flag required the task
3962 * wake up if any activity is detected on the response buffer.
3963 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01003964 if (chn->flags & CF_ISRESP)
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003965 HLUA_SET_WAKERESWR(hlua);
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01003966 else
3967 HLUA_SET_WAKEREQWR(hlua);
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003968
Ilya Shipitsin4a689da2022-10-29 09:34:32 +05003969 /* Otherwise, we can yield waiting for new data in the input side. */
Willy Tarreau9635e032018-10-16 17:52:55 +02003970 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_forward_yield, TICK_ETERNITY, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003971 }
3972
3973 return 1;
3974}
3975
3976/* Just check the input and prepare the stack for the previous
3977 * function "hlua_channel_forward_yield"
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003978 *
3979 * This function cannot be called from a filter.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003980 */
3981__LJMP static int hlua_channel_forward(lua_State *L)
3982{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003983 struct channel *chn;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003984
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003985 MAY_LJMP(check_args(L, 2, "forward"));
3986 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3987 if (IS_HTX_STRM(chn_strm(chn))) {
3988 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3989 WILL_LJMP(lua_error(L));
3990 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003991 lua_pushinteger(L, 0);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003992 return MAY_LJMP(hlua_channel_forward_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003993}
3994
3995/* Just returns the number of bytes available in the input
3996 * side of the buffer. This function never fails.
3997 */
3998__LJMP static int hlua_channel_get_in_len(lua_State *L)
3999{
Willy Tarreau47860ed2015-03-10 14:07:50 +01004000 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004001 struct filter *filter;
4002 size_t output, input;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004003
Christopher Faulet6a79fc12021-08-06 16:02:36 +02004004 MAY_LJMP(check_args(L, 1, "input"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004005 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004006
4007 output = co_data(chn);
4008 input = ci_data(chn);
4009 filter = hlua_channel_filter(L, 1, chn, &output, &input);
4010 if (filter || !IS_HTX_STRM(chn_strm(chn)))
4011 lua_pushinteger(L, input);
4012 else {
Christopher Fauleta3ceac12018-12-14 13:39:09 +01004013 struct htx *htx = htxbuf(&chn->buf);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004014
Christopher Fauleta3ceac12018-12-14 13:39:09 +01004015 lua_pushinteger(L, htx->data - co_data(chn));
4016 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004017 return 1;
4018}
4019
Thierry FOURNIER / OZON.IO65192f32016-11-07 15:28:40 +01004020/* Returns true if the channel is full. */
4021__LJMP static int hlua_channel_is_full(lua_State *L)
4022{
4023 struct channel *chn;
Thierry FOURNIER / OZON.IO65192f32016-11-07 15:28:40 +01004024
4025 MAY_LJMP(check_args(L, 1, "is_full"));
4026 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Faulet0ec740e2020-02-26 11:59:19 +01004027 /* ignore the reserve, we are not on a producer side (ie in an
4028 * applet).
4029 */
4030 lua_pushboolean(L, channel_full(chn, 0));
Thierry FOURNIER / OZON.IO65192f32016-11-07 15:28:40 +01004031 return 1;
4032}
4033
Christopher Faulet6a79fc12021-08-06 16:02:36 +02004034/* Returns true if the channel may still receive data. */
4035__LJMP static int hlua_channel_may_recv(lua_State *L)
4036{
4037 struct channel *chn;
4038
4039 MAY_LJMP(check_args(L, 1, "may_recv"));
4040 chn = MAY_LJMP(hlua_checkchannel(L, 1));
4041 lua_pushboolean(L, (!channel_input_closed(chn) && channel_may_recv(chn)));
4042 return 1;
4043}
4044
Christopher Faulet2ac9ba22020-02-25 10:15:50 +01004045/* Returns true if the channel is the response channel. */
4046__LJMP static int hlua_channel_is_resp(lua_State *L)
4047{
4048 struct channel *chn;
4049
4050 MAY_LJMP(check_args(L, 1, "is_resp"));
4051 chn = MAY_LJMP(hlua_checkchannel(L, 1));
4052
4053 lua_pushboolean(L, !!(chn->flags & CF_ISRESP));
4054 return 1;
4055}
4056
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004057/* Just returns the number of bytes available in the output
4058 * side of the buffer. This function never fails.
4059 */
4060__LJMP static int hlua_channel_get_out_len(lua_State *L)
4061{
Willy Tarreau47860ed2015-03-10 14:07:50 +01004062 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004063 size_t output, input;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004064
Christopher Faulet6a79fc12021-08-06 16:02:36 +02004065 MAY_LJMP(check_args(L, 1, "output"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004066 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004067
4068 output = co_data(chn);
4069 input = ci_data(chn);
4070 hlua_channel_filter(L, 1, chn, &output, &input);
4071
4072 lua_pushinteger(L, output);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004073 return 1;
4074}
4075
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004076/*
4077 *
4078 *
4079 * Class Fetches
4080 *
4081 *
4082 */
4083
4084/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02004085 * a class stream, otherwise it throws an error.
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004086 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004087__LJMP static struct hlua_smp *hlua_checkfetches(lua_State *L, int ud)
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004088{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004089 return MAY_LJMP(hlua_checkudata(L, ud, class_fetches_ref));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004090}
4091
4092/* This function creates and push in the stack a fetch object according
4093 * with a current TXN.
4094 */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004095static int hlua_fetches_new(lua_State *L, struct hlua_txn *txn, unsigned int flags)
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004096{
Willy Tarreau7073c472015-04-06 11:15:40 +02004097 struct hlua_smp *hsmp;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004098
4099 /* Check stack size. */
4100 if (!lua_checkstack(L, 3))
4101 return 0;
4102
4103 /* Create the object: obj[0] = userdata.
4104 * Note that the base of the Fetches object is the
4105 * transaction object.
4106 */
4107 lua_newtable(L);
Willy Tarreau7073c472015-04-06 11:15:40 +02004108 hsmp = lua_newuserdata(L, sizeof(*hsmp));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004109 lua_rawseti(L, -2, 0);
4110
Willy Tarreau7073c472015-04-06 11:15:40 +02004111 hsmp->s = txn->s;
4112 hsmp->p = txn->p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01004113 hsmp->dir = txn->dir;
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004114 hsmp->flags = flags;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004115
4116 /* Pop a class sesison metatable and affect it to the userdata. */
4117 lua_rawgeti(L, LUA_REGISTRYINDEX, class_fetches_ref);
4118 lua_setmetatable(L, -2);
4119
4120 return 1;
4121}
4122
4123/* This function is an LUA binding. It is called with each sample-fetch.
4124 * It uses closure argument to store the associated sample-fetch. It
4125 * returns only one argument or throws an error. An error is thrown
4126 * only if an error is encountered during the argument parsing. If
4127 * the "sample-fetch" function fails, nil is returned.
4128 */
4129__LJMP static int hlua_run_sample_fetch(lua_State *L)
4130{
Willy Tarreaub2ccb562015-04-06 11:11:15 +02004131 struct hlua_smp *hsmp;
Willy Tarreau2ec22742015-03-10 14:27:20 +01004132 struct sample_fetch *f;
Frédéric Lécaillef874a832018-06-15 13:56:04 +02004133 struct arg args[ARGM_NBARGS + 1] = {{0}};
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004134 int i;
4135 struct sample smp;
4136
4137 /* Get closure arguments. */
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004138 f = lua_touserdata(L, lua_upvalueindex(1));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004139
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004140 /* Get traditional arguments. */
Willy Tarreaub2ccb562015-04-06 11:11:15 +02004141 hsmp = MAY_LJMP(hlua_checkfetches(L, 1));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004142
Thierry FOURNIERca988662015-12-20 18:43:03 +01004143 /* Check execution authorization. */
4144 if (f->use & SMP_USE_HTTP_ANY &&
4145 !(hsmp->flags & HLUA_F_MAY_USE_HTTP)) {
4146 lua_pushfstring(L, "the sample-fetch '%s' needs an HTTP parser which "
4147 "is not available in Lua services", f->kw);
4148 WILL_LJMP(lua_error(L));
4149 }
4150
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004151 /* Get extra arguments. */
4152 for (i = 0; i < lua_gettop(L) - 1; i++) {
4153 if (i >= ARGM_NBARGS)
4154 break;
4155 hlua_lua2arg(L, i + 2, &args[i]);
4156 }
4157 args[i].type = ARGT_STOP;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004158 args[i].data.str.area = NULL;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004159
4160 /* Check arguments. */
Willy Tarreaub2ccb562015-04-06 11:11:15 +02004161 MAY_LJMP(hlua_lua2arg_check(L, 2, args, f->arg_mask, hsmp->p));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004162
4163 /* Run the special args checker. */
Willy Tarreau2ec22742015-03-10 14:27:20 +01004164 if (f->val_args && !f->val_args(args, NULL)) {
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004165 lua_pushfstring(L, "error in arguments");
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004166 goto error;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004167 }
4168
4169 /* Initialise the sample. */
4170 memset(&smp, 0, sizeof(smp));
4171
4172 /* Run the sample fetch process. */
Willy Tarreau1777ea62016-03-10 16:15:46 +01004173 smp_set_owner(&smp, hsmp->p, hsmp->s->sess, hsmp->s, hsmp->dir & SMP_OPT_DIR);
Thierry FOURNIER0786d052015-05-11 15:42:45 +02004174 if (!f->process(args, &smp, f->kw, f->private)) {
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004175 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004176 lua_pushstring(L, "");
4177 else
4178 lua_pushnil(L);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004179 goto end;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004180 }
4181
4182 /* Convert the returned sample in lua value. */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004183 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004184 hlua_smp2lua_str(L, &smp);
4185 else
4186 hlua_smp2lua(L, &smp);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004187
4188 end:
Willy Tarreauee0d7272021-07-16 10:26:56 +02004189 free_args(args);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004190 return 1;
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004191
4192 error:
Willy Tarreauee0d7272021-07-16 10:26:56 +02004193 free_args(args);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004194 WILL_LJMP(lua_error(L));
4195 return 0; /* Never reached */
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004196}
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004197
4198/*
4199 *
4200 *
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004201 * Class Converters
4202 *
4203 *
4204 */
4205
4206/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02004207 * a class stream, otherwise it throws an error.
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004208 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004209__LJMP static struct hlua_smp *hlua_checkconverters(lua_State *L, int ud)
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004210{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004211 return MAY_LJMP(hlua_checkudata(L, ud, class_converters_ref));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004212}
4213
4214/* This function creates and push in the stack a Converters object
4215 * according with a current TXN.
4216 */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004217static int hlua_converters_new(lua_State *L, struct hlua_txn *txn, unsigned int flags)
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004218{
Willy Tarreau7073c472015-04-06 11:15:40 +02004219 struct hlua_smp *hsmp;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004220
4221 /* Check stack size. */
4222 if (!lua_checkstack(L, 3))
4223 return 0;
4224
4225 /* Create the object: obj[0] = userdata.
4226 * Note that the base of the Converters object is the
4227 * same than the TXN object.
4228 */
4229 lua_newtable(L);
Willy Tarreau7073c472015-04-06 11:15:40 +02004230 hsmp = lua_newuserdata(L, sizeof(*hsmp));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004231 lua_rawseti(L, -2, 0);
4232
Willy Tarreau7073c472015-04-06 11:15:40 +02004233 hsmp->s = txn->s;
4234 hsmp->p = txn->p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01004235 hsmp->dir = txn->dir;
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004236 hsmp->flags = flags;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004237
Willy Tarreau87b09662015-04-03 00:22:06 +02004238 /* Pop a class stream metatable and affect it to the table. */
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004239 lua_rawgeti(L, LUA_REGISTRYINDEX, class_converters_ref);
4240 lua_setmetatable(L, -2);
4241
4242 return 1;
4243}
4244
4245/* This function is an LUA binding. It is called with each converter.
4246 * It uses closure argument to store the associated converter. It
4247 * returns only one argument or throws an error. An error is thrown
4248 * only if an error is encountered during the argument parsing. If
4249 * the converter function function fails, nil is returned.
4250 */
4251__LJMP static int hlua_run_sample_conv(lua_State *L)
4252{
Willy Tarreauda5f1082015-04-06 11:17:13 +02004253 struct hlua_smp *hsmp;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004254 struct sample_conv *conv;
Frédéric Lécaillef874a832018-06-15 13:56:04 +02004255 struct arg args[ARGM_NBARGS + 1] = {{0}};
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004256 int i;
4257 struct sample smp;
4258
4259 /* Get closure arguments. */
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004260 conv = lua_touserdata(L, lua_upvalueindex(1));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004261
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004262 /* Get traditional arguments. */
Willy Tarreauda5f1082015-04-06 11:17:13 +02004263 hsmp = MAY_LJMP(hlua_checkconverters(L, 1));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004264
4265 /* Get extra arguments. */
4266 for (i = 0; i < lua_gettop(L) - 2; i++) {
4267 if (i >= ARGM_NBARGS)
4268 break;
4269 hlua_lua2arg(L, i + 3, &args[i]);
4270 }
4271 args[i].type = ARGT_STOP;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004272 args[i].data.str.area = NULL;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004273
4274 /* Check arguments. */
Willy Tarreauda5f1082015-04-06 11:17:13 +02004275 MAY_LJMP(hlua_lua2arg_check(L, 3, args, conv->arg_mask, hsmp->p));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004276
4277 /* Run the special args checker. */
4278 if (conv->val_args && !conv->val_args(args, conv, "", 0, NULL)) {
4279 hlua_pusherror(L, "error in arguments");
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004280 goto error;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004281 }
4282
4283 /* Initialise the sample. */
Amaury Denoyellebc0af6a2020-10-29 17:21:20 +01004284 memset(&smp, 0, sizeof(smp));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004285 if (!hlua_lua2smp(L, 2, &smp)) {
4286 hlua_pusherror(L, "error in the input argument");
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004287 goto error;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004288 }
4289
Willy Tarreau1777ea62016-03-10 16:15:46 +01004290 smp_set_owner(&smp, hsmp->p, hsmp->s->sess, hsmp->s, hsmp->dir & SMP_OPT_DIR);
4291
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004292 /* Apply expected cast. */
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02004293 if (!sample_casts[smp.data.type][conv->in_type]) {
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004294 hlua_pusherror(L, "invalid input argument: cannot cast '%s' to '%s'",
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02004295 smp_to_type[smp.data.type], smp_to_type[conv->in_type]);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004296 goto error;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004297 }
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02004298 if (sample_casts[smp.data.type][conv->in_type] != c_none &&
4299 !sample_casts[smp.data.type][conv->in_type](&smp)) {
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004300 hlua_pusherror(L, "error during the input argument casting");
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004301 goto error;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004302 }
4303
4304 /* Run the sample conversion process. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02004305 if (!conv->process(args, &smp, conv->private)) {
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004306 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004307 lua_pushstring(L, "");
4308 else
Willy Tarreaua678b432015-08-28 10:14:59 +02004309 lua_pushnil(L);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004310 goto end;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004311 }
4312
4313 /* Convert the returned sample in lua value. */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004314 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004315 hlua_smp2lua_str(L, &smp);
4316 else
4317 hlua_smp2lua(L, &smp);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004318 end:
Willy Tarreauee0d7272021-07-16 10:26:56 +02004319 free_args(args);
Willy Tarreaua678b432015-08-28 10:14:59 +02004320 return 1;
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004321
4322 error:
Willy Tarreauee0d7272021-07-16 10:26:56 +02004323 free_args(args);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004324 WILL_LJMP(lua_error(L));
4325 return 0; /* Never reached */
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004326}
4327
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004328/*
4329 *
4330 *
4331 * Class AppletTCP
4332 *
4333 *
4334 */
4335
4336/* Returns a struct hlua_txn if the stack entry "ud" is
4337 * a class stream, otherwise it throws an error.
4338 */
4339__LJMP static struct hlua_appctx *hlua_checkapplet_tcp(lua_State *L, int ud)
4340{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004341 return MAY_LJMP(hlua_checkudata(L, ud, class_applet_tcp_ref));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004342}
4343
4344/* This function creates and push in the stack an Applet object
4345 * according with a current TXN.
4346 */
4347static int hlua_applet_tcp_new(lua_State *L, struct appctx *ctx)
4348{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004349 struct hlua_appctx *luactx;
Willy Tarreau0698c802022-05-11 14:09:57 +02004350 struct stream *s = appctx_strm(ctx);
Christopher Faulet2da02ae2022-02-24 13:45:27 +01004351 struct proxy *p;
4352
4353 ALREADY_CHECKED(s);
4354 p = s->be;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004355
4356 /* Check stack size. */
4357 if (!lua_checkstack(L, 3))
4358 return 0;
4359
4360 /* Create the object: obj[0] = userdata.
4361 * Note that the base of the Converters object is the
4362 * same than the TXN object.
4363 */
4364 lua_newtable(L);
Willy Tarreau7e702d12021-04-28 17:59:21 +02004365 luactx = lua_newuserdata(L, sizeof(*luactx));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004366 lua_rawseti(L, -2, 0);
Willy Tarreau7e702d12021-04-28 17:59:21 +02004367 luactx->appctx = ctx;
4368 luactx->htxn.s = s;
4369 luactx->htxn.p = p;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004370
4371 /* Create the "f" field that contains a list of fetches. */
4372 lua_pushstring(L, "f");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004373 if (!hlua_fetches_new(L, &luactx->htxn, 0))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004374 return 0;
4375 lua_settable(L, -3);
4376
4377 /* Create the "sf" field that contains a list of stringsafe fetches. */
4378 lua_pushstring(L, "sf");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004379 if (!hlua_fetches_new(L, &luactx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004380 return 0;
4381 lua_settable(L, -3);
4382
4383 /* Create the "c" field that contains a list of converters. */
4384 lua_pushstring(L, "c");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004385 if (!hlua_converters_new(L, &luactx->htxn, 0))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004386 return 0;
4387 lua_settable(L, -3);
4388
4389 /* Create the "sc" field that contains a list of stringsafe converters. */
4390 lua_pushstring(L, "sc");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004391 if (!hlua_converters_new(L, &luactx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004392 return 0;
4393 lua_settable(L, -3);
4394
4395 /* Pop a class stream metatable and affect it to the table. */
4396 lua_rawgeti(L, LUA_REGISTRYINDEX, class_applet_tcp_ref);
4397 lua_setmetatable(L, -2);
4398
4399 return 1;
4400}
4401
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004402__LJMP static int hlua_applet_tcp_set_var(lua_State *L)
4403{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004404 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004405 struct stream *s;
4406 const char *name;
4407 size_t len;
4408 struct sample smp;
4409
Tim Duesterhus4e172c92020-05-19 13:49:42 +02004410 if (lua_gettop(L) < 3 || lua_gettop(L) > 4)
4411 WILL_LJMP(luaL_error(L, "'set_var' needs between 3 and 4 arguments"));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004412
4413 /* It is useles to retrieve the stream, but this function
4414 * runs only in a stream context.
4415 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004416 luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004417 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02004418 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004419
4420 /* Converts the third argument in a sample. */
Amaury Denoyellebc0af6a2020-10-29 17:21:20 +01004421 memset(&smp, 0, sizeof(smp));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004422 hlua_lua2smp(L, 3, &smp);
4423
4424 /* Store the sample in a variable. */
4425 smp_set_owner(&smp, s->be, s->sess, s, 0);
Tim Duesterhus4e172c92020-05-19 13:49:42 +02004426
4427 if (lua_gettop(L) == 4 && lua_toboolean(L, 4))
4428 lua_pushboolean(L, vars_set_by_name_ifexist(name, len, &smp) != 0);
4429 else
4430 lua_pushboolean(L, vars_set_by_name(name, len, &smp) != 0);
4431
Tim Duesterhus84ebc132020-05-19 13:49:41 +02004432 return 1;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004433}
4434
4435__LJMP static int hlua_applet_tcp_unset_var(lua_State *L)
4436{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004437 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004438 struct stream *s;
4439 const char *name;
4440 size_t len;
4441 struct sample smp;
4442
4443 MAY_LJMP(check_args(L, 2, "unset_var"));
4444
4445 /* It is useles to retrieve the stream, but this function
4446 * runs only in a stream context.
4447 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004448 luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004449 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02004450 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004451
4452 /* Unset the variable. */
4453 smp_set_owner(&smp, s->be, s->sess, s, 0);
Tim Duesterhus84ebc132020-05-19 13:49:41 +02004454 lua_pushboolean(L, vars_unset_by_name_ifexist(name, len, &smp) != 0);
4455 return 1;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004456}
4457
4458__LJMP static int hlua_applet_tcp_get_var(lua_State *L)
4459{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004460 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004461 struct stream *s;
4462 const char *name;
4463 size_t len;
4464 struct sample smp;
4465
4466 MAY_LJMP(check_args(L, 2, "get_var"));
4467
4468 /* It is useles to retrieve the stream, but this function
4469 * runs only in a stream context.
4470 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004471 luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004472 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02004473 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004474
4475 smp_set_owner(&smp, s->be, s->sess, s, 0);
Willy Tarreaue352b9d2021-09-03 11:52:38 +02004476 if (!vars_get_by_name(name, len, &smp, NULL)) {
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004477 lua_pushnil(L);
4478 return 1;
4479 }
4480
4481 return hlua_smp2lua(L, &smp);
4482}
4483
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004484__LJMP static int hlua_applet_tcp_set_priv(lua_State *L)
4485{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004486 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
4487 struct stream *s = luactx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01004488 struct hlua *hlua;
4489
4490 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01004491 if (!s->hlua)
4492 return 0;
4493 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004494
4495 MAY_LJMP(check_args(L, 2, "set_priv"));
4496
4497 /* Remove previous value. */
Thierry FOURNIERe068b602017-04-26 13:27:05 +02004498 luaL_unref(L, LUA_REGISTRYINDEX, hlua->Mref);
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004499
4500 /* Get and store new value. */
4501 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
4502 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
4503
4504 return 0;
4505}
4506
4507__LJMP static int hlua_applet_tcp_get_priv(lua_State *L)
4508{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004509 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
4510 struct stream *s = luactx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01004511 struct hlua *hlua;
4512
4513 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01004514 if (!s->hlua) {
4515 lua_pushnil(L);
4516 return 1;
4517 }
4518 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004519
4520 /* Push configuration index in the stack. */
4521 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
4522
4523 return 1;
4524}
4525
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004526/* If expected data not yet available, it returns a yield. This function
4527 * consumes the data in the buffer. It returns a string containing the
4528 * data. This string can be empty.
4529 */
4530__LJMP static int hlua_applet_tcp_getline_yield(lua_State *L, int status, lua_KContext ctx)
4531{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004532 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Willy Tarreauc12b3212022-05-27 11:08:15 +02004533 struct stconn *sc = appctx_sc(luactx->appctx);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004534 int ret;
Willy Tarreau206ba832018-06-14 15:27:31 +02004535 const char *blk1;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004536 size_t len1;
Willy Tarreau206ba832018-06-14 15:27:31 +02004537 const char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004538 size_t len2;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004539
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004540 /* Read the maximum amount of data available. */
Willy Tarreau3e7be362022-05-27 10:35:27 +02004541 ret = co_getline_nc(sc_oc(sc), &blk1, &len1, &blk2, &len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004542
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004543 /* Data not yet available. return yield. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004544 if (ret == 0) {
Willy Tarreau90e8b452022-05-25 18:21:43 +02004545 applet_need_more_data(luactx->appctx);
Willy Tarreau9635e032018-10-16 17:52:55 +02004546 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_getline_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004547 }
4548
4549 /* End of data: commit the total strings and return. */
4550 if (ret < 0) {
Willy Tarreau7e702d12021-04-28 17:59:21 +02004551 luaL_pushresult(&luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004552 return 1;
4553 }
4554
4555 /* Ensure that the block 2 length is usable. */
4556 if (ret == 1)
4557 len2 = 0;
4558
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -07004559 /* don't check the max length read and don't check. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004560 luaL_addlstring(&luactx->b, blk1, len1);
4561 luaL_addlstring(&luactx->b, blk2, len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004562
4563 /* Consume input channel output buffer data. */
Willy Tarreau3e7be362022-05-27 10:35:27 +02004564 co_skip(sc_oc(sc), len1 + len2);
Willy Tarreau7e702d12021-04-28 17:59:21 +02004565 luaL_pushresult(&luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004566 return 1;
4567}
4568
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004569/* Check arguments for the function "hlua_channel_get_yield". */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004570__LJMP static int hlua_applet_tcp_getline(lua_State *L)
4571{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004572 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004573
4574 /* Initialise the string catenation. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004575 luaL_buffinit(L, &luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004576
4577 return MAY_LJMP(hlua_applet_tcp_getline_yield(L, 0, 0));
4578}
4579
4580/* If expected data not yet available, it returns a yield. This function
4581 * consumes the data in the buffer. It returns a string containing the
4582 * data. This string can be empty.
4583 */
4584__LJMP static int hlua_applet_tcp_recv_yield(lua_State *L, int status, lua_KContext ctx)
4585{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004586 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Willy Tarreauc12b3212022-05-27 11:08:15 +02004587 struct stconn *sc = appctx_sc(luactx->appctx);
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004588 size_t len = MAY_LJMP(luaL_checkinteger(L, 2));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004589 int ret;
Willy Tarreau206ba832018-06-14 15:27:31 +02004590 const char *blk1;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004591 size_t len1;
Willy Tarreau206ba832018-06-14 15:27:31 +02004592 const char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004593 size_t len2;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004594
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004595 /* Read the maximum amount of data available. */
Willy Tarreau3e7be362022-05-27 10:35:27 +02004596 ret = co_getblk_nc(sc_oc(sc), &blk1, &len1, &blk2, &len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004597
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004598 /* Data not yet available. return yield. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004599 if (ret == 0) {
Willy Tarreau90e8b452022-05-25 18:21:43 +02004600 applet_need_more_data(luactx->appctx);
Willy Tarreau9635e032018-10-16 17:52:55 +02004601 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004602 }
4603
4604 /* End of data: commit the total strings and return. */
4605 if (ret < 0) {
Willy Tarreau7e702d12021-04-28 17:59:21 +02004606 luaL_pushresult(&luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004607 return 1;
4608 }
4609
4610 /* Ensure that the block 2 length is usable. */
4611 if (ret == 1)
4612 len2 = 0;
4613
4614 if (len == -1) {
4615
4616 /* If len == -1, catenate all the data avalaile and
4617 * yield because we want to get all the data until
4618 * the end of data stream.
4619 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004620 luaL_addlstring(&luactx->b, blk1, len1);
4621 luaL_addlstring(&luactx->b, blk2, len2);
Willy Tarreau3e7be362022-05-27 10:35:27 +02004622 co_skip(sc_oc(sc), len1 + len2);
Willy Tarreau90e8b452022-05-25 18:21:43 +02004623 applet_need_more_data(luactx->appctx);
Willy Tarreau9635e032018-10-16 17:52:55 +02004624 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004625
4626 } else {
4627
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05004628 /* Copy the first block caping to the length required. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004629 if (len1 > len)
4630 len1 = len;
Willy Tarreau7e702d12021-04-28 17:59:21 +02004631 luaL_addlstring(&luactx->b, blk1, len1);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004632 len -= len1;
4633
4634 /* Copy the second block. */
4635 if (len2 > len)
4636 len2 = len;
Willy Tarreau7e702d12021-04-28 17:59:21 +02004637 luaL_addlstring(&luactx->b, blk2, len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004638 len -= len2;
4639
4640 /* Consume input channel output buffer data. */
Willy Tarreau3e7be362022-05-27 10:35:27 +02004641 co_skip(sc_oc(sc), len1 + len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004642
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004643 /* If there is no other data available, yield waiting for new data. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004644 if (len > 0) {
4645 lua_pushinteger(L, len);
4646 lua_replace(L, 2);
Willy Tarreau90e8b452022-05-25 18:21:43 +02004647 applet_need_more_data(luactx->appctx);
Willy Tarreau9635e032018-10-16 17:52:55 +02004648 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004649 }
4650
4651 /* return the result. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004652 luaL_pushresult(&luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004653 return 1;
4654 }
4655
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004656 /* we never execute this */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004657 hlua_pusherror(L, "Lua: internal error");
4658 WILL_LJMP(lua_error(L));
4659 return 0;
4660}
4661
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004662/* Check arguments for the function "hlua_channel_get_yield". */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004663__LJMP static int hlua_applet_tcp_recv(lua_State *L)
4664{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004665 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004666 int len = -1;
4667
4668 if (lua_gettop(L) > 2)
4669 WILL_LJMP(luaL_error(L, "The 'recv' function requires between 1 and 2 arguments."));
4670 if (lua_gettop(L) >= 2) {
4671 len = MAY_LJMP(luaL_checkinteger(L, 2));
4672 lua_pop(L, 1);
4673 }
4674
4675 /* Confirm or set the required length */
4676 lua_pushinteger(L, len);
4677
4678 /* Initialise the string catenation. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004679 luaL_buffinit(L, &luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004680
4681 return MAY_LJMP(hlua_applet_tcp_recv_yield(L, 0, 0));
4682}
4683
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004684/* Append data in the output side of the buffer. This data is immediately
4685 * sent. The function returns the amount of data written. If the buffer
4686 * cannot contain the data, the function yields. The function returns -1
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004687 * if the channel is closed.
4688 */
4689__LJMP static int hlua_applet_tcp_send_yield(lua_State *L, int status, lua_KContext ctx)
4690{
4691 size_t len;
Willy Tarreau7e702d12021-04-28 17:59:21 +02004692 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004693 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
4694 int l = MAY_LJMP(luaL_checkinteger(L, 3));
Willy Tarreauc12b3212022-05-27 11:08:15 +02004695 struct stconn *sc = appctx_sc(luactx->appctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02004696 struct channel *chn = sc_ic(sc);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004697 int max;
4698
4699 /* Get the max amount of data which can write as input in the channel. */
4700 max = channel_recv_max(chn);
4701 if (max > (len - l))
4702 max = len - l;
4703
4704 /* Copy data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02004705 ci_putblk(chn, str + l, max);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004706
4707 /* update counters. */
4708 l += max;
4709 lua_pop(L, 1);
4710 lua_pushinteger(L, l);
4711
4712 /* If some data is not send, declares the situation to the
4713 * applet, and returns a yield.
4714 */
4715 if (l < len) {
Willy Tarreau3e7be362022-05-27 10:35:27 +02004716 sc_need_room(sc);
Willy Tarreau9635e032018-10-16 17:52:55 +02004717 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004718 }
4719
4720 return 1;
4721}
4722
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05004723/* Just a wrapper of "hlua_applet_tcp_send_yield". This wrapper permits
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004724 * yield the LUA process, and resume it without checking the
4725 * input arguments.
4726 */
4727__LJMP static int hlua_applet_tcp_send(lua_State *L)
4728{
4729 MAY_LJMP(check_args(L, 2, "send"));
4730 lua_pushinteger(L, 0);
4731
4732 return MAY_LJMP(hlua_applet_tcp_send_yield(L, 0, 0));
4733}
4734
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004735/*
4736 *
4737 *
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004738 * Class AppletHTTP
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004739 *
4740 *
4741 */
4742
4743/* Returns a struct hlua_txn if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02004744 * a class stream, otherwise it throws an error.
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004745 */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004746__LJMP static struct hlua_appctx *hlua_checkapplet_http(lua_State *L, int ud)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004747{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004748 return MAY_LJMP(hlua_checkudata(L, ud, class_applet_http_ref));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004749}
4750
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004751/* This function creates and push in the stack an Applet object
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004752 * according with a current TXN.
Willy Tarreauaa229cc2022-05-06 14:26:10 +02004753 * It relies on the caller to have already reserved the room in ctx->svcctx
4754 * for the local storage of hlua_http_ctx.
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004755 */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004756static int hlua_applet_http_new(lua_State *L, struct appctx *ctx)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004757{
Willy Tarreauaa229cc2022-05-06 14:26:10 +02004758 struct hlua_http_ctx *http_ctx = ctx->svcctx;
Willy Tarreau7e702d12021-04-28 17:59:21 +02004759 struct hlua_appctx *luactx;
Thierry FOURNIER841475e2015-12-11 17:10:09 +01004760 struct hlua_txn htxn;
Willy Tarreau0698c802022-05-11 14:09:57 +02004761 struct stream *s = appctx_strm(ctx);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004762 struct proxy *px = s->be;
Christopher Fauleta2097962019-07-15 16:25:33 +02004763 struct htx *htx;
4764 struct htx_blk *blk;
4765 struct htx_sl *sl;
4766 struct ist path;
4767 unsigned long long len = 0;
4768 int32_t pos;
Amaury Denoyellec453f952021-07-06 11:40:12 +02004769 struct http_uri_parser parser;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004770
4771 /* Check stack size. */
4772 if (!lua_checkstack(L, 3))
4773 return 0;
4774
4775 /* Create the object: obj[0] = userdata.
4776 * Note that the base of the Converters object is the
4777 * same than the TXN object.
4778 */
4779 lua_newtable(L);
Willy Tarreau7e702d12021-04-28 17:59:21 +02004780 luactx = lua_newuserdata(L, sizeof(*luactx));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004781 lua_rawseti(L, -2, 0);
Willy Tarreau7e702d12021-04-28 17:59:21 +02004782 luactx->appctx = ctx;
Willy Tarreauaa229cc2022-05-06 14:26:10 +02004783 http_ctx->status = 200; /* Default status code returned. */
4784 http_ctx->reason = NULL; /* Use default reason based on status */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004785 luactx->htxn.s = s;
4786 luactx->htxn.p = px;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004787
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004788 /* Create the "f" field that contains a list of fetches. */
4789 lua_pushstring(L, "f");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004790 if (!hlua_fetches_new(L, &luactx->htxn, 0))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004791 return 0;
4792 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004793
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004794 /* Create the "sf" field that contains a list of stringsafe fetches. */
4795 lua_pushstring(L, "sf");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004796 if (!hlua_fetches_new(L, &luactx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004797 return 0;
4798 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004799
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004800 /* Create the "c" field that contains a list of converters. */
4801 lua_pushstring(L, "c");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004802 if (!hlua_converters_new(L, &luactx->htxn, 0))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004803 return 0;
4804 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004805
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004806 /* Create the "sc" field that contains a list of stringsafe converters. */
4807 lua_pushstring(L, "sc");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004808 if (!hlua_converters_new(L, &luactx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004809 return 0;
4810 lua_settable(L, -3);
Willy Tarreaueee5b512015-04-03 23:46:31 +02004811
Christopher Fauleta2097962019-07-15 16:25:33 +02004812 htx = htxbuf(&s->req.buf);
4813 blk = htx_get_first_blk(htx);
Christopher Fauletea009732019-11-18 15:50:25 +01004814 BUG_ON(!blk || htx_get_blk_type(blk) != HTX_BLK_REQ_SL);
Christopher Fauleta2097962019-07-15 16:25:33 +02004815 sl = htx_get_blk_ptr(htx, blk);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004816
Christopher Fauleta2097962019-07-15 16:25:33 +02004817 /* Stores the request method. */
4818 lua_pushstring(L, "method");
4819 lua_pushlstring(L, HTX_SL_REQ_MPTR(sl), HTX_SL_REQ_MLEN(sl));
4820 lua_settable(L, -3);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004821
Christopher Fauleta2097962019-07-15 16:25:33 +02004822 /* Stores the http version. */
4823 lua_pushstring(L, "version");
4824 lua_pushlstring(L, HTX_SL_REQ_VPTR(sl), HTX_SL_REQ_VLEN(sl));
4825 lua_settable(L, -3);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004826
Christopher Fauleta2097962019-07-15 16:25:33 +02004827 /* creates an array of headers. hlua_http_get_headers() crates and push
4828 * the array on the top of the stack.
4829 */
4830 lua_pushstring(L, "headers");
4831 htxn.s = s;
4832 htxn.p = px;
4833 htxn.dir = SMP_OPT_DIR_REQ;
Christopher Faulet9d1332b2020-02-24 16:46:16 +01004834 if (!hlua_http_get_headers(L, &htxn.s->txn->req))
Christopher Fauleta2097962019-07-15 16:25:33 +02004835 return 0;
4836 lua_settable(L, -3);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004837
Amaury Denoyellec453f952021-07-06 11:40:12 +02004838 parser = http_uri_parser_init(htx_sl_req_uri(sl));
4839 path = http_parse_path(&parser);
Tim Duesterhused526372020-03-05 17:56:33 +01004840 if (isttest(path)) {
Christopher Fauleta2097962019-07-15 16:25:33 +02004841 char *p, *q, *end;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004842
Christopher Fauleta2097962019-07-15 16:25:33 +02004843 p = path.ptr;
Tim Duesterhus4c8f75f2021-11-06 15:14:44 +01004844 end = istend(path);
Christopher Fauleta2097962019-07-15 16:25:33 +02004845 q = p;
4846 while (q < end && *q != '?')
4847 q++;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004848
Thierry FOURNIER7d388632017-02-22 02:06:16 +01004849 /* Stores the request path. */
Christopher Fauleta2097962019-07-15 16:25:33 +02004850 lua_pushstring(L, "path");
4851 lua_pushlstring(L, p, q - p);
Thierry FOURNIER7d388632017-02-22 02:06:16 +01004852 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01004853
Christopher Fauleta2097962019-07-15 16:25:33 +02004854 /* Stores the query string. */
4855 lua_pushstring(L, "qs");
4856 if (*q == '?')
4857 q++;
4858 lua_pushlstring(L, q, end - q);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004859 lua_settable(L, -3);
Christopher Fauleta2097962019-07-15 16:25:33 +02004860 }
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004861
Christopher Fauleta2097962019-07-15 16:25:33 +02004862 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
4863 struct htx_blk *blk = htx_get_blk(htx, pos);
4864 enum htx_blk_type type = htx_get_blk_type(blk);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004865
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01004866 if (type == HTX_BLK_TLR || type == HTX_BLK_EOT)
Christopher Fauleta2097962019-07-15 16:25:33 +02004867 break;
4868 if (type == HTX_BLK_DATA)
4869 len += htx_get_blksz(blk);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004870 }
Christopher Fauleta2097962019-07-15 16:25:33 +02004871 if (htx->extra != ULLONG_MAX)
4872 len += htx->extra;
4873
4874 /* Stores the request path. */
4875 lua_pushstring(L, "length");
4876 lua_pushinteger(L, len);
4877 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01004878
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004879 /* Create an empty array of HTTP request headers. */
4880 lua_pushstring(L, "response");
4881 lua_newtable(L);
4882 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01004883
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004884 /* Pop a class stream metatable and affect it to the table. */
4885 lua_rawgeti(L, LUA_REGISTRYINDEX, class_applet_http_ref);
4886 lua_setmetatable(L, -2);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004887
4888 return 1;
4889}
4890
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004891__LJMP static int hlua_applet_http_set_var(lua_State *L)
4892{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004893 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004894 struct stream *s;
4895 const char *name;
4896 size_t len;
4897 struct sample smp;
4898
Tim Duesterhus4e172c92020-05-19 13:49:42 +02004899 if (lua_gettop(L) < 3 || lua_gettop(L) > 4)
4900 WILL_LJMP(luaL_error(L, "'set_var' needs between 3 and 4 arguments"));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004901
4902 /* It is useles to retrieve the stream, but this function
4903 * runs only in a stream context.
4904 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004905 luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004906 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02004907 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004908
4909 /* Converts the third argument in a sample. */
Amaury Denoyellebc0af6a2020-10-29 17:21:20 +01004910 memset(&smp, 0, sizeof(smp));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004911 hlua_lua2smp(L, 3, &smp);
4912
4913 /* Store the sample in a variable. */
4914 smp_set_owner(&smp, s->be, s->sess, s, 0);
Tim Duesterhus4e172c92020-05-19 13:49:42 +02004915
4916 if (lua_gettop(L) == 4 && lua_toboolean(L, 4))
4917 lua_pushboolean(L, vars_set_by_name_ifexist(name, len, &smp) != 0);
4918 else
4919 lua_pushboolean(L, vars_set_by_name(name, len, &smp) != 0);
4920
Tim Duesterhus84ebc132020-05-19 13:49:41 +02004921 return 1;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004922}
4923
4924__LJMP static int hlua_applet_http_unset_var(lua_State *L)
4925{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004926 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004927 struct stream *s;
4928 const char *name;
4929 size_t len;
4930 struct sample smp;
4931
4932 MAY_LJMP(check_args(L, 2, "unset_var"));
4933
4934 /* It is useles to retrieve the stream, but this function
4935 * runs only in a stream context.
4936 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004937 luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004938 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02004939 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004940
4941 /* Unset the variable. */
4942 smp_set_owner(&smp, s->be, s->sess, s, 0);
Tim Duesterhus84ebc132020-05-19 13:49:41 +02004943 lua_pushboolean(L, vars_unset_by_name_ifexist(name, len, &smp) != 0);
4944 return 1;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004945}
4946
4947__LJMP static int hlua_applet_http_get_var(lua_State *L)
4948{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004949 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004950 struct stream *s;
4951 const char *name;
4952 size_t len;
4953 struct sample smp;
4954
4955 MAY_LJMP(check_args(L, 2, "get_var"));
4956
4957 /* It is useles to retrieve the stream, but this function
4958 * runs only in a stream context.
4959 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004960 luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004961 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02004962 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004963
4964 smp_set_owner(&smp, s->be, s->sess, s, 0);
Willy Tarreaue352b9d2021-09-03 11:52:38 +02004965 if (!vars_get_by_name(name, len, &smp, NULL)) {
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004966 lua_pushnil(L);
4967 return 1;
4968 }
4969
4970 return hlua_smp2lua(L, &smp);
4971}
4972
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004973__LJMP static int hlua_applet_http_set_priv(lua_State *L)
4974{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004975 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4976 struct stream *s = luactx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01004977 struct hlua *hlua;
4978
4979 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01004980 if (!s->hlua)
4981 return 0;
4982 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004983
4984 MAY_LJMP(check_args(L, 2, "set_priv"));
4985
4986 /* Remove previous value. */
Thierry FOURNIERe068b602017-04-26 13:27:05 +02004987 luaL_unref(L, LUA_REGISTRYINDEX, hlua->Mref);
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004988
4989 /* Get and store new value. */
4990 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
4991 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
4992
4993 return 0;
4994}
4995
4996__LJMP static int hlua_applet_http_get_priv(lua_State *L)
4997{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004998 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4999 struct stream *s = luactx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01005000 struct hlua *hlua;
5001
5002 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005003 if (!s->hlua) {
5004 lua_pushnil(L);
5005 return 1;
5006 }
5007 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01005008
5009 /* Push configuration index in the stack. */
5010 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
5011
5012 return 1;
5013}
5014
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005015/* If expected data not yet available, it returns a yield. This function
5016 * consumes the data in the buffer. It returns a string containing the
5017 * data. This string can be empty.
5018 */
Christopher Fauleta2097962019-07-15 16:25:33 +02005019__LJMP static int hlua_applet_http_getline_yield(lua_State *L, int status, lua_KContext ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005020{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005021 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Willy Tarreauc12b3212022-05-27 11:08:15 +02005022 struct stconn *sc = appctx_sc(luactx->appctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02005023 struct channel *req = sc_oc(sc);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005024 struct htx *htx;
5025 struct htx_blk *blk;
5026 size_t count;
5027 int stop = 0;
5028
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005029 htx = htx_from_buf(&req->buf);
5030 count = co_data(req);
Christopher Fauleta3f15502019-05-13 15:27:23 +02005031 blk = htx_get_first_blk(htx);
Christopher Fauletcc26b132018-12-18 21:20:57 +01005032
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005033 while (count && !stop && blk) {
5034 enum htx_blk_type type = htx_get_blk_type(blk);
5035 uint32_t sz = htx_get_blksz(blk);
5036 struct ist v;
5037 uint32_t vlen;
5038 char *nl;
5039
5040 vlen = sz;
5041 if (vlen > count) {
5042 if (type != HTX_BLK_DATA)
5043 break;
5044 vlen = count;
5045 }
5046
5047 switch (type) {
5048 case HTX_BLK_UNUSED:
5049 break;
5050
5051 case HTX_BLK_DATA:
5052 v = htx_get_blk_value(htx, blk);
5053 v.len = vlen;
5054 nl = istchr(v, '\n');
5055 if (nl != NULL) {
5056 stop = 1;
5057 vlen = nl - v.ptr + 1;
5058 }
Willy Tarreau7e702d12021-04-28 17:59:21 +02005059 luaL_addlstring(&luactx->b, v.ptr, vlen);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005060 break;
5061
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005062 case HTX_BLK_TLR:
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01005063 case HTX_BLK_EOT:
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005064 stop = 1;
5065 break;
5066
5067 default:
5068 break;
5069 }
5070
Willy Tarreau84240042022-02-28 16:51:23 +01005071 c_rew(req, vlen);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005072 count -= vlen;
5073 if (sz == vlen)
5074 blk = htx_remove_blk(htx, blk);
5075 else {
5076 htx_cut_data_blk(htx, blk, vlen);
5077 break;
5078 }
5079 }
5080
Christopher Fauleteccb31c2021-04-02 14:24:56 +02005081 /* The message was fully consumed and no more data are expected
5082 * (EOM flag set).
5083 */
Christopher Faulet4a209722022-08-29 15:37:16 +02005084 if (htx_is_empty(htx) && (req->flags & CF_EOI))
Christopher Fauleteccb31c2021-04-02 14:24:56 +02005085 stop = 1;
5086
Christopher Faulet0ae79d02019-02-27 21:36:59 +01005087 htx_to_buf(htx, &req->buf);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005088 if (!stop) {
Willy Tarreau90e8b452022-05-25 18:21:43 +02005089 applet_need_more_data(luactx->appctx);
Christopher Fauleta2097962019-07-15 16:25:33 +02005090 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_getline_yield, TICK_ETERNITY, 0));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005091 }
5092
5093 /* return the result. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005094 luaL_pushresult(&luactx->b);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005095 return 1;
5096}
5097
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005098
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08005099/* Check arguments for the function "hlua_channel_get_yield". */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005100__LJMP static int hlua_applet_http_getline(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005101{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005102 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005103
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005104 /* Initialise the string catenation. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005105 luaL_buffinit(L, &luactx->b);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005106
Christopher Fauleta2097962019-07-15 16:25:33 +02005107 return MAY_LJMP(hlua_applet_http_getline_yield(L, 0, 0));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005108}
5109
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005110/* If expected data not yet available, it returns a yield. This function
5111 * consumes the data in the buffer. It returns a string containing the
5112 * data. This string can be empty.
5113 */
Christopher Fauleta2097962019-07-15 16:25:33 +02005114__LJMP static int hlua_applet_http_recv_yield(lua_State *L, int status, lua_KContext ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005115{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005116 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Willy Tarreauc12b3212022-05-27 11:08:15 +02005117 struct stconn *sc = appctx_sc(luactx->appctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02005118 struct channel *req = sc_oc(sc);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005119 struct htx *htx;
5120 struct htx_blk *blk;
5121 size_t count;
5122 int len;
5123
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005124 htx = htx_from_buf(&req->buf);
5125 len = MAY_LJMP(luaL_checkinteger(L, 2));
5126 count = co_data(req);
Christopher Faulet29f17582019-05-23 11:03:26 +02005127 blk = htx_get_head_blk(htx);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005128 while (count && len && blk) {
5129 enum htx_blk_type type = htx_get_blk_type(blk);
5130 uint32_t sz = htx_get_blksz(blk);
5131 struct ist v;
5132 uint32_t vlen;
5133
5134 vlen = sz;
5135 if (len > 0 && vlen > len)
5136 vlen = len;
5137 if (vlen > count) {
5138 if (type != HTX_BLK_DATA)
5139 break;
5140 vlen = count;
5141 }
5142
5143 switch (type) {
5144 case HTX_BLK_UNUSED:
5145 break;
5146
5147 case HTX_BLK_DATA:
5148 v = htx_get_blk_value(htx, blk);
Willy Tarreau7e702d12021-04-28 17:59:21 +02005149 luaL_addlstring(&luactx->b, v.ptr, vlen);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005150 break;
5151
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005152 case HTX_BLK_TLR:
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01005153 case HTX_BLK_EOT:
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005154 len = 0;
5155 break;
5156
5157 default:
5158 break;
5159 }
5160
Willy Tarreau84240042022-02-28 16:51:23 +01005161 c_rew(req, vlen);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005162 count -= vlen;
5163 if (len > 0)
5164 len -= vlen;
5165 if (sz == vlen)
5166 blk = htx_remove_blk(htx, blk);
5167 else {
5168 htx_cut_data_blk(htx, blk, vlen);
5169 break;
5170 }
5171 }
5172
Christopher Fauleteccb31c2021-04-02 14:24:56 +02005173 /* The message was fully consumed and no more data are expected
5174 * (EOM flag set).
5175 */
Christopher Faulet4a209722022-08-29 15:37:16 +02005176 if (htx_is_empty(htx) && (req->flags & CF_EOI))
Christopher Fauleteccb31c2021-04-02 14:24:56 +02005177 len = 0;
5178
Christopher Faulet0ae79d02019-02-27 21:36:59 +01005179 htx_to_buf(htx, &req->buf);
5180
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005181 /* If we are no other data available, yield waiting for new data. */
5182 if (len) {
5183 if (len > 0) {
5184 lua_pushinteger(L, len);
5185 lua_replace(L, 2);
5186 }
Willy Tarreau90e8b452022-05-25 18:21:43 +02005187 applet_need_more_data(luactx->appctx);
Willy Tarreau9635e032018-10-16 17:52:55 +02005188 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005189 }
5190
5191 /* return the result. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005192 luaL_pushresult(&luactx->b);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005193 return 1;
5194}
5195
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08005196/* Check arguments for the function "hlua_channel_get_yield". */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005197__LJMP static int hlua_applet_http_recv(lua_State *L)
5198{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005199 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005200 int len = -1;
5201
5202 /* Check arguments. */
5203 if (lua_gettop(L) > 2)
5204 WILL_LJMP(luaL_error(L, "The 'recv' function requires between 1 and 2 arguments."));
5205 if (lua_gettop(L) >= 2) {
5206 len = MAY_LJMP(luaL_checkinteger(L, 2));
5207 lua_pop(L, 1);
5208 }
5209
Christopher Fauleta2097962019-07-15 16:25:33 +02005210 lua_pushinteger(L, len);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005211
Christopher Fauleta2097962019-07-15 16:25:33 +02005212 /* Initialise the string catenation. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005213 luaL_buffinit(L, &luactx->b);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005214
Christopher Fauleta2097962019-07-15 16:25:33 +02005215 return MAY_LJMP(hlua_applet_http_recv_yield(L, 0, 0));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005216}
5217
5218/* Append data in the output side of the buffer. This data is immediately
5219 * sent. The function returns the amount of data written. If the buffer
5220 * cannot contain the data, the function yields. The function returns -1
5221 * if the channel is closed.
5222 */
Christopher Fauleta2097962019-07-15 16:25:33 +02005223__LJMP static int hlua_applet_http_send_yield(lua_State *L, int status, lua_KContext ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005224{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005225 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Willy Tarreauc12b3212022-05-27 11:08:15 +02005226 struct stconn *sc = appctx_sc(luactx->appctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02005227 struct channel *res = sc_ic(sc);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005228 struct htx *htx = htx_from_buf(&res->buf);
5229 const char *data;
5230 size_t len;
5231 int l = MAY_LJMP(luaL_checkinteger(L, 3));
5232 int max;
5233
Christopher Faulet9060fc02019-07-03 11:39:30 +02005234 max = htx_get_max_blksz(htx, channel_htx_recv_max(res, htx));
Christopher Faulet4b0e9b22019-01-09 12:16:58 +01005235 if (!max)
5236 goto snd_yield;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005237
5238 data = MAY_LJMP(luaL_checklstring(L, 2, &len));
5239
5240 /* Get the max amount of data which can write as input in the channel. */
5241 if (max > (len - l))
5242 max = len - l;
5243
5244 /* Copy data. */
Willy Tarreau0a7ef022019-05-28 10:30:11 +02005245 max = htx_add_data(htx, ist2(data + l, max));
Christopher Fauletf6cce3f2019-02-27 21:20:09 +01005246 channel_add_input(res, max);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005247
5248 /* update counters. */
5249 l += max;
5250 lua_pop(L, 1);
5251 lua_pushinteger(L, l);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005252
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005253 /* If some data is not send, declares the situation to the
5254 * applet, and returns a yield.
5255 */
5256 if (l < len) {
Christopher Faulet4b0e9b22019-01-09 12:16:58 +01005257 snd_yield:
Christopher Faulet0ae79d02019-02-27 21:36:59 +01005258 htx_to_buf(htx, &res->buf);
Willy Tarreau3e7be362022-05-27 10:35:27 +02005259 sc_need_room(sc);
Willy Tarreau9635e032018-10-16 17:52:55 +02005260 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005261 }
5262
Christopher Fauleta2097962019-07-15 16:25:33 +02005263 htx_to_buf(htx, &res->buf);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005264 return 1;
5265}
5266
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05005267/* Just a wrapper of "hlua_applet_send_yield". This wrapper permits
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005268 * yield the LUA process, and resume it without checking the
5269 * input arguments.
5270 */
5271__LJMP static int hlua_applet_http_send(lua_State *L)
5272{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005273 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005274 struct hlua_http_ctx *http_ctx = luactx->appctx->svcctx;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005275
5276 /* We want to send some data. Headers must be sent. */
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005277 if (!(http_ctx->flags & APPLET_HDR_SENT)) {
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005278 hlua_pusherror(L, "Lua: 'send' you must call start_response() before sending data.");
5279 WILL_LJMP(lua_error(L));
5280 }
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005281
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05005282 /* This integer is used for followinf the amount of data sent. */
Christopher Fauleta2097962019-07-15 16:25:33 +02005283 lua_pushinteger(L, 0);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005284
Christopher Fauleta2097962019-07-15 16:25:33 +02005285 return MAY_LJMP(hlua_applet_http_send_yield(L, 0, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005286}
5287
5288__LJMP static int hlua_applet_http_addheader(lua_State *L)
5289{
5290 const char *name;
5291 int ret;
5292
5293 MAY_LJMP(hlua_checkapplet_http(L, 1));
5294 name = MAY_LJMP(luaL_checkstring(L, 2));
5295 MAY_LJMP(luaL_checkstring(L, 3));
5296
5297 /* Push in the stack the "response" entry. */
5298 ret = lua_getfield(L, 1, "response");
5299 if (ret != LUA_TTABLE) {
5300 hlua_pusherror(L, "Lua: 'add_header' internal error: AppletHTTP['response'] "
5301 "is expected as an array. %s found", lua_typename(L, ret));
5302 WILL_LJMP(lua_error(L));
5303 }
5304
5305 /* check if the header is already registered if it is not
5306 * the case, register it.
5307 */
5308 ret = lua_getfield(L, -1, name);
5309 if (ret == LUA_TNIL) {
5310
5311 /* Entry not found. */
5312 lua_pop(L, 1); /* remove the nil. The "response" table is the top of the stack. */
5313
5314 /* Insert the new header name in the array in the top of the stack.
5315 * It left the new array in the top of the stack.
5316 */
5317 lua_newtable(L);
5318 lua_pushvalue(L, 2);
5319 lua_pushvalue(L, -2);
5320 lua_settable(L, -4);
5321
5322 } else if (ret != LUA_TTABLE) {
5323
5324 /* corruption error. */
5325 hlua_pusherror(L, "Lua: 'add_header' internal error: AppletHTTP['response']['%s'] "
5326 "is expected as an array. %s found", name, lua_typename(L, ret));
5327 WILL_LJMP(lua_error(L));
5328 }
5329
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -07005330 /* Now the top of thestack is an array of values. We push
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005331 * the header value as new entry.
5332 */
5333 lua_pushvalue(L, 3);
5334 ret = lua_rawlen(L, -2);
5335 lua_rawseti(L, -2, ret + 1);
5336 lua_pushboolean(L, 1);
5337 return 1;
5338}
5339
5340__LJMP static int hlua_applet_http_status(lua_State *L)
5341{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005342 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005343 int status = MAY_LJMP(luaL_checkinteger(L, 2));
Robin H. Johnson52f5db22017-01-01 13:10:52 -08005344 const char *reason = MAY_LJMP(luaL_optlstring(L, 3, NULL, NULL));
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005345 struct hlua_http_ctx *http_ctx = luactx->appctx->svcctx;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005346
5347 if (status < 100 || status > 599) {
5348 lua_pushboolean(L, 0);
5349 return 1;
5350 }
5351
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005352 http_ctx->status = status;
5353 http_ctx->reason = reason;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005354 lua_pushboolean(L, 1);
5355 return 1;
5356}
5357
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005358
Christopher Fauleta2097962019-07-15 16:25:33 +02005359__LJMP static int hlua_applet_http_send_response(lua_State *L)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005360{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005361 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005362 struct hlua_http_ctx *http_ctx = luactx->appctx->svcctx;
Willy Tarreauc12b3212022-05-27 11:08:15 +02005363 struct stconn *sc = appctx_sc(luactx->appctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02005364 struct channel *res = sc_ic(sc);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005365 struct htx *htx;
5366 struct htx_sl *sl;
5367 struct h1m h1m;
5368 const char *status, *reason;
5369 const char *name, *value;
5370 size_t nlen, vlen;
5371 unsigned int flags;
5372
5373 /* Send the message at once. */
5374 htx = htx_from_buf(&res->buf);
5375 h1m_init_res(&h1m);
5376
5377 /* Use the same http version than the request. */
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005378 status = ultoa_r(http_ctx->status, trash.area, trash.size);
5379 reason = http_ctx->reason;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005380 if (reason == NULL)
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005381 reason = http_get_reason(http_ctx->status);
5382 if (http_ctx->flags & APPLET_HTTP11) {
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005383 flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11);
5384 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.1"), ist(status), ist(reason));
5385 }
5386 else {
5387 flags = HTX_SL_F_IS_RESP;
5388 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.0"), ist(status), ist(reason));
5389 }
5390 if (!sl) {
5391 hlua_pusherror(L, "Lua applet http '%s': Failed to create response.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005392 luactx->appctx->rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005393 WILL_LJMP(lua_error(L));
5394 }
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005395 sl->info.res.status = http_ctx->status;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005396
5397 /* Get the array associated to the field "response" in the object AppletHTTP. */
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005398 if (lua_getfield(L, 1, "response") != LUA_TTABLE) {
5399 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response'] missing.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005400 luactx->appctx->rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005401 WILL_LJMP(lua_error(L));
5402 }
5403
5404 /* Browse the list of headers. */
5405 lua_pushnil(L);
5406 while(lua_next(L, -2) != 0) {
5407 /* We expect a string as -2. */
5408 if (lua_type(L, -2) != LUA_TSTRING) {
5409 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response'][] element must be a string. got %s.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005410 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005411 lua_typename(L, lua_type(L, -2)));
5412 WILL_LJMP(lua_error(L));
5413 }
5414 name = lua_tolstring(L, -2, &nlen);
5415
5416 /* We expect an array as -1. */
5417 if (lua_type(L, -1) != LUA_TTABLE) {
5418 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 +02005419 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005420 name,
5421 lua_typename(L, lua_type(L, -1)));
5422 WILL_LJMP(lua_error(L));
5423 }
5424
5425 /* Browse the table who is on the top of the stack. */
5426 lua_pushnil(L);
5427 while(lua_next(L, -2) != 0) {
5428 int id;
5429
5430 /* We expect a number as -2. */
5431 if (lua_type(L, -2) != LUA_TNUMBER) {
5432 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 +02005433 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005434 name,
5435 lua_typename(L, lua_type(L, -2)));
5436 WILL_LJMP(lua_error(L));
5437 }
5438 id = lua_tointeger(L, -2);
5439
5440 /* We expect a string as -2. */
5441 if (lua_type(L, -1) != LUA_TSTRING) {
5442 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 +02005443 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005444 name, id,
5445 lua_typename(L, lua_type(L, -1)));
5446 WILL_LJMP(lua_error(L));
5447 }
5448 value = lua_tolstring(L, -1, &vlen);
5449
5450 /* Simple Protocol checks. */
Christopher Faulet545fbba2021-09-28 09:36:25 +02005451 if (isteqi(ist2(name, nlen), ist("transfer-encoding"))) {
5452 int ret;
5453
5454 ret = h1_parse_xfer_enc_header(&h1m, ist2(value, vlen));
5455 if (ret < 0) {
5456 hlua_pusherror(L, "Lua applet http '%s': Invalid '%s' header.\n",
5457 luactx->appctx->rule->arg.hlua_rule->fcn->name,
5458 name);
5459 WILL_LJMP(lua_error(L));
5460 }
5461 else if (ret == 0)
5462 goto next; /* Skip it */
5463 }
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005464 else if (isteqi(ist2(name, nlen), ist("content-length"))) {
5465 struct ist v = ist2(value, vlen);
5466 int ret;
5467
5468 ret = h1_parse_cont_len_header(&h1m, &v);
5469 if (ret < 0) {
5470 hlua_pusherror(L, "Lua applet http '%s': Invalid '%s' header.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005471 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005472 name);
5473 WILL_LJMP(lua_error(L));
5474 }
5475 else if (ret == 0)
5476 goto next; /* Skip it */
5477 }
5478
5479 /* Add a new header */
5480 if (!htx_add_header(htx, ist2(name, nlen), ist2(value, vlen))) {
5481 hlua_pusherror(L, "Lua applet http '%s': Failed to add header '%s' in the response.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005482 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005483 name);
5484 WILL_LJMP(lua_error(L));
5485 }
5486 next:
5487 /* Remove the array from the stack, and get next element with a remaining string. */
5488 lua_pop(L, 1);
5489 }
5490
5491 /* Remove the array from the stack, and get next element with a remaining string. */
5492 lua_pop(L, 1);
5493 }
5494
5495 if (h1m.flags & H1_MF_CHNK)
5496 h1m.flags &= ~H1_MF_CLEN;
5497 if (h1m.flags & (H1_MF_CLEN|H1_MF_CHNK))
5498 h1m.flags |= H1_MF_XFER_LEN;
5499
5500 /* Uset HTX start-line flags */
5501 if (h1m.flags & H1_MF_XFER_ENC)
5502 flags |= HTX_SL_F_XFER_ENC;
5503 if (h1m.flags & H1_MF_XFER_LEN) {
5504 flags |= HTX_SL_F_XFER_LEN;
5505 if (h1m.flags & H1_MF_CHNK)
5506 flags |= HTX_SL_F_CHNK;
5507 else if (h1m.flags & H1_MF_CLEN)
5508 flags |= HTX_SL_F_CLEN;
5509 if (h1m.body_len == 0)
5510 flags |= HTX_SL_F_BODYLESS;
5511 }
5512 sl->flags |= flags;
5513
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -07005514 /* If we don't have a content-length set, and the HTTP version is 1.1
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005515 * and the status code implies the presence of a message body, we must
5516 * announce a transfer encoding chunked. This is required by haproxy
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05005517 * for the keepalive compliance. If the applet announces a transfer-encoding
5518 * chunked itself, don't do anything.
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005519 */
5520 if ((flags & (HTX_SL_F_VER_11|HTX_SL_F_XFER_LEN)) == HTX_SL_F_VER_11 &&
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005521 http_ctx->status >= 200 && http_ctx->status != 204 && http_ctx->status != 304) {
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005522 /* Add a new header */
5523 sl->flags |= (HTX_SL_F_XFER_ENC|H1_MF_CHNK|H1_MF_XFER_LEN);
5524 if (!htx_add_header(htx, ist("transfer-encoding"), ist("chunked"))) {
5525 hlua_pusherror(L, "Lua applet http '%s': Failed to add header 'transfer-encoding' in the response.\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 WILL_LJMP(lua_error(L));
5528 }
5529 }
5530
5531 /* Finalize headers. */
5532 if (!htx_add_endof(htx, HTX_BLK_EOH)) {
5533 hlua_pusherror(L, "Lua applet http '%s': Failed create the response.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005534 luactx->appctx->rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005535 WILL_LJMP(lua_error(L));
5536 }
5537
5538 if (htx_used_space(htx) > b_size(&res->buf) - global.tune.maxrewrite) {
5539 b_reset(&res->buf);
5540 hlua_pusherror(L, "Lua: 'start_response': response header block too big");
5541 WILL_LJMP(lua_error(L));
5542 }
5543
5544 htx_to_buf(htx, &res->buf);
Christopher Fauletf6cce3f2019-02-27 21:20:09 +01005545 channel_add_input(res, htx->data);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005546
5547 /* Headers sent, set the flag. */
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005548 http_ctx->flags |= APPLET_HDR_SENT;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005549 return 0;
5550
5551}
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005552/* We will build the status line and the headers of the HTTP response.
5553 * We will try send at once if its not possible, we give back the hand
5554 * waiting for more room.
5555 */
Christopher Fauleta2097962019-07-15 16:25:33 +02005556__LJMP static int hlua_applet_http_start_response_yield(lua_State *L, int status, lua_KContext ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005557{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005558 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Willy Tarreauc12b3212022-05-27 11:08:15 +02005559 struct stconn *sc = appctx_sc(luactx->appctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02005560 struct channel *res = sc_ic(sc);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005561
5562 if (co_data(res)) {
Willy Tarreau3e7be362022-05-27 10:35:27 +02005563 sc_need_room(sc);
Christopher Fauleta2097962019-07-15 16:25:33 +02005564 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_start_response_yield, TICK_ETERNITY, 0));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005565 }
Christopher Fauleta2097962019-07-15 16:25:33 +02005566 return MAY_LJMP(hlua_applet_http_send_response(L));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005567}
5568
5569
Christopher Fauleta2097962019-07-15 16:25:33 +02005570__LJMP static int hlua_applet_http_start_response(lua_State *L)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005571{
Christopher Fauleta2097962019-07-15 16:25:33 +02005572 return MAY_LJMP(hlua_applet_http_start_response_yield(L, 0, 0));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005573}
5574
Christopher Fauleta2097962019-07-15 16:25:33 +02005575/*
5576 *
5577 *
5578 * Class HTTP
5579 *
5580 *
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005581 */
Christopher Fauleta2097962019-07-15 16:25:33 +02005582
5583/* Returns a struct hlua_txn if the stack entry "ud" is
5584 * a class stream, otherwise it throws an error.
5585 */
5586__LJMP static struct hlua_txn *hlua_checkhttp(lua_State *L, int ud)
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005587{
Christopher Fauleta2097962019-07-15 16:25:33 +02005588 return MAY_LJMP(hlua_checkudata(L, ud, class_http_ref));
5589}
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005590
Christopher Fauleta2097962019-07-15 16:25:33 +02005591/* This function creates and push in the stack a HTTP object
5592 * according with a current TXN.
5593 */
5594static int hlua_http_new(lua_State *L, struct hlua_txn *txn)
5595{
5596 struct hlua_txn *htxn;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005597
Christopher Fauleta2097962019-07-15 16:25:33 +02005598 /* Check stack size. */
5599 if (!lua_checkstack(L, 3))
5600 return 0;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005601
Christopher Fauleta2097962019-07-15 16:25:33 +02005602 /* Create the object: obj[0] = userdata.
5603 * Note that the base of the Converters object is the
5604 * same than the TXN object.
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005605 */
Christopher Fauleta2097962019-07-15 16:25:33 +02005606 lua_newtable(L);
5607 htxn = lua_newuserdata(L, sizeof(*htxn));
5608 lua_rawseti(L, -2, 0);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005609
5610 htxn->s = txn->s;
5611 htxn->p = txn->p;
Christopher Faulet256b69a2019-05-23 11:14:21 +02005612 htxn->dir = txn->dir;
5613 htxn->flags = txn->flags;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005614
5615 /* Pop a class stream metatable and affect it to the table. */
5616 lua_rawgeti(L, LUA_REGISTRYINDEX, class_http_ref);
5617 lua_setmetatable(L, -2);
5618
5619 return 1;
5620}
5621
Christopher Fauletdf97ac42020-02-26 16:57:19 +01005622/* This function creates and returns an array containing the status-line
5623 * elements. This function does not fails.
5624 */
5625__LJMP static int hlua_http_get_stline(lua_State *L, struct htx_sl *sl)
5626{
5627 /* Create the table. */
5628 lua_newtable(L);
5629
5630 if (sl->flags & HTX_SL_F_IS_RESP) {
5631 lua_pushstring(L, "version");
5632 lua_pushlstring(L, HTX_SL_RES_VPTR(sl), HTX_SL_RES_VLEN(sl));
5633 lua_settable(L, -3);
5634 lua_pushstring(L, "code");
5635 lua_pushlstring(L, HTX_SL_RES_CPTR(sl), HTX_SL_RES_CLEN(sl));
5636 lua_settable(L, -3);
5637 lua_pushstring(L, "reason");
5638 lua_pushlstring(L, HTX_SL_RES_RPTR(sl), HTX_SL_RES_RLEN(sl));
5639 lua_settable(L, -3);
5640 }
5641 else {
5642 lua_pushstring(L, "method");
5643 lua_pushlstring(L, HTX_SL_REQ_MPTR(sl), HTX_SL_REQ_MLEN(sl));
5644 lua_settable(L, -3);
5645 lua_pushstring(L, "uri");
5646 lua_pushlstring(L, HTX_SL_REQ_UPTR(sl), HTX_SL_REQ_ULEN(sl));
5647 lua_settable(L, -3);
5648 lua_pushstring(L, "version");
5649 lua_pushlstring(L, HTX_SL_REQ_VPTR(sl), HTX_SL_REQ_VLEN(sl));
5650 lua_settable(L, -3);
5651 }
5652 return 1;
5653}
5654
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005655/* This function creates ans returns an array of HTTP headers.
5656 * This function does not fails. It is used as wrapper with the
5657 * 2 following functions.
5658 */
Christopher Faulet9d1332b2020-02-24 16:46:16 +01005659__LJMP static int hlua_http_get_headers(lua_State *L, struct http_msg *msg)
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005660{
Christopher Fauleta2097962019-07-15 16:25:33 +02005661 struct htx *htx;
5662 int32_t pos;
5663
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005664 /* Create the table. */
5665 lua_newtable(L);
5666
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005667
Christopher Fauleta2097962019-07-15 16:25:33 +02005668 htx = htxbuf(&msg->chn->buf);
5669 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
5670 struct htx_blk *blk = htx_get_blk(htx, pos);
5671 enum htx_blk_type type = htx_get_blk_type(blk);
5672 struct ist n, v;
5673 int len;
Christopher Faulet724a12c2018-12-13 22:12:15 +01005674
Christopher Fauleta2097962019-07-15 16:25:33 +02005675 if (type == HTX_BLK_HDR) {
5676 n = htx_get_blk_name(htx,blk);
5677 v = htx_get_blk_value(htx, blk);
Christopher Faulet724a12c2018-12-13 22:12:15 +01005678 }
Christopher Fauleta2097962019-07-15 16:25:33 +02005679 else if (type == HTX_BLK_EOH)
5680 break;
5681 else
5682 continue;
Christopher Faulet724a12c2018-12-13 22:12:15 +01005683
Christopher Fauleta2097962019-07-15 16:25:33 +02005684 /* Check for existing entry:
5685 * assume that the table is on the top of the stack, and
5686 * push the key in the stack, the function lua_gettable()
5687 * perform the lookup.
5688 */
5689 lua_pushlstring(L, n.ptr, n.len);
5690 lua_gettable(L, -2);
Christopher Faulet724a12c2018-12-13 22:12:15 +01005691
Christopher Fauleta2097962019-07-15 16:25:33 +02005692 switch (lua_type(L, -1)) {
5693 case LUA_TNIL:
5694 /* Table not found, create it. */
5695 lua_pop(L, 1); /* remove the nil value. */
5696 lua_pushlstring(L, n.ptr, n.len); /* push the header name as key. */
5697 lua_newtable(L); /* create and push empty table. */
5698 lua_pushlstring(L, v.ptr, v.len); /* push header value. */
5699 lua_rawseti(L, -2, 0); /* index header value (pop it). */
5700 lua_rawset(L, -3); /* index new table with header name (pop the values). */
Christopher Faulet724a12c2018-12-13 22:12:15 +01005701 break;
Christopher Faulet724a12c2018-12-13 22:12:15 +01005702
Christopher Fauleta2097962019-07-15 16:25:33 +02005703 case LUA_TTABLE:
5704 /* Entry found: push the value in the table. */
5705 len = lua_rawlen(L, -1);
5706 lua_pushlstring(L, v.ptr, v.len); /* push header value. */
5707 lua_rawseti(L, -2, len+1); /* index header value (pop it). */
5708 lua_pop(L, 1); /* remove the table (it is stored in the main table). */
5709 break;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005710
Christopher Fauleta2097962019-07-15 16:25:33 +02005711 default:
5712 /* Other cases are errors. */
5713 hlua_pusherror(L, "internal error during the parsing of headers.");
5714 WILL_LJMP(lua_error(L));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005715 }
5716 }
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005717 return 1;
5718}
5719
5720__LJMP static int hlua_http_req_get_headers(lua_State *L)
5721{
5722 struct hlua_txn *htxn;
5723
5724 MAY_LJMP(check_args(L, 1, "req_get_headers"));
5725 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5726
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005727 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005728 WILL_LJMP(lua_error(L));
5729
Christopher Faulet9d1332b2020-02-24 16:46:16 +01005730 return hlua_http_get_headers(L, &htxn->s->txn->req);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005731}
5732
5733__LJMP static int hlua_http_res_get_headers(lua_State *L)
5734{
5735 struct hlua_txn *htxn;
5736
5737 MAY_LJMP(check_args(L, 1, "res_get_headers"));
5738 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5739
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005740 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005741 WILL_LJMP(lua_error(L));
5742
Christopher Faulet9d1332b2020-02-24 16:46:16 +01005743 return hlua_http_get_headers(L, &htxn->s->txn->rsp);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005744}
5745
5746/* This function replace full header, or just a value in
5747 * the request or in the response. It is a wrapper fir the
5748 * 4 following functions.
5749 */
Christopher Fauletd1914aa2020-02-24 16:52:46 +01005750__LJMP static inline int hlua_http_rep_hdr(lua_State *L, struct http_msg *msg, int full)
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005751{
5752 size_t name_len;
5753 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
5754 const char *reg = MAY_LJMP(luaL_checkstring(L, 3));
5755 const char *value = MAY_LJMP(luaL_checkstring(L, 4));
Christopher Fauleta2097962019-07-15 16:25:33 +02005756 struct htx *htx;
Dragan Dosen26743032019-04-30 15:54:36 +02005757 struct my_regex *re;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005758
Dragan Dosen26743032019-04-30 15:54:36 +02005759 if (!(re = regex_comp(reg, 1, 1, NULL)))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005760 WILL_LJMP(luaL_argerror(L, 3, "invalid regex"));
5761
Christopher Fauleta2097962019-07-15 16:25:33 +02005762 htx = htxbuf(&msg->chn->buf);
Christopher Fauletd1914aa2020-02-24 16:52:46 +01005763 http_replace_hdrs(chn_strm(msg->chn), htx, ist2(name, name_len), value, re, full);
Dragan Dosen26743032019-04-30 15:54:36 +02005764 regex_free(re);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005765 return 0;
5766}
5767
5768__LJMP static int hlua_http_req_rep_hdr(lua_State *L)
5769{
5770 struct hlua_txn *htxn;
5771
5772 MAY_LJMP(check_args(L, 4, "req_rep_hdr"));
5773 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5774
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005775 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005776 WILL_LJMP(lua_error(L));
5777
Christopher Fauletd1914aa2020-02-24 16:52:46 +01005778 return MAY_LJMP(hlua_http_rep_hdr(L, &htxn->s->txn->req, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005779}
5780
5781__LJMP static int hlua_http_res_rep_hdr(lua_State *L)
5782{
5783 struct hlua_txn *htxn;
5784
5785 MAY_LJMP(check_args(L, 4, "res_rep_hdr"));
5786 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5787
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005788 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005789 WILL_LJMP(lua_error(L));
5790
Christopher Fauletd1914aa2020-02-24 16:52:46 +01005791 return MAY_LJMP(hlua_http_rep_hdr(L, &htxn->s->txn->rsp, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005792}
5793
5794__LJMP static int hlua_http_req_rep_val(lua_State *L)
5795{
5796 struct hlua_txn *htxn;
5797
5798 MAY_LJMP(check_args(L, 4, "req_rep_hdr"));
5799 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5800
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005801 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005802 WILL_LJMP(lua_error(L));
5803
Christopher Fauletd1914aa2020-02-24 16:52:46 +01005804 return MAY_LJMP(hlua_http_rep_hdr(L, &htxn->s->txn->req, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005805}
5806
5807__LJMP static int hlua_http_res_rep_val(lua_State *L)
5808{
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005809 struct hlua_txn *htxn;
5810
5811 MAY_LJMP(check_args(L, 4, "res_rep_val"));
5812 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5813
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005814 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005815 WILL_LJMP(lua_error(L));
5816
Christopher Fauletd1914aa2020-02-24 16:52:46 +01005817 return MAY_LJMP(hlua_http_rep_hdr(L, &htxn->s->txn->rsp, 0));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005818}
5819
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08005820/* This function deletes all the occurrences of an header.
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005821 * It is a wrapper for the 2 following functions.
5822 */
Christopher Fauletd31c7b32020-02-25 09:37:57 +01005823__LJMP static inline int hlua_http_del_hdr(lua_State *L, struct http_msg *msg)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005824{
5825 size_t len;
5826 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Christopher Fauleta2097962019-07-15 16:25:33 +02005827 struct htx *htx = htxbuf(&msg->chn->buf);
5828 struct http_hdr_ctx ctx;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005829
Christopher Fauleta2097962019-07-15 16:25:33 +02005830 ctx.blk = NULL;
5831 while (http_find_header(htx, ist2(name, len), &ctx, 1))
5832 http_remove_header(htx, &ctx);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005833 return 0;
5834}
5835
5836__LJMP static int hlua_http_req_del_hdr(lua_State *L)
5837{
5838 struct hlua_txn *htxn;
5839
5840 MAY_LJMP(check_args(L, 2, "req_del_hdr"));
5841 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5842
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005843 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005844 WILL_LJMP(lua_error(L));
5845
Christopher Fauletd31c7b32020-02-25 09:37:57 +01005846 return hlua_http_del_hdr(L, &htxn->s->txn->req);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005847}
5848
5849__LJMP static int hlua_http_res_del_hdr(lua_State *L)
5850{
5851 struct hlua_txn *htxn;
5852
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005853 MAY_LJMP(check_args(L, 2, "res_del_hdr"));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005854 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5855
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005856 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005857 WILL_LJMP(lua_error(L));
5858
Christopher Fauletd31c7b32020-02-25 09:37:57 +01005859 return hlua_http_del_hdr(L, &htxn->s->txn->rsp);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005860}
5861
5862/* This function adds an header. It is a wrapper used by
5863 * the 2 following functions.
5864 */
Christopher Fauletd31c7b32020-02-25 09:37:57 +01005865__LJMP static inline int hlua_http_add_hdr(lua_State *L, struct http_msg *msg)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005866{
5867 size_t name_len;
5868 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
5869 size_t value_len;
5870 const char *value = MAY_LJMP(luaL_checklstring(L, 3, &value_len));
Christopher Fauleta2097962019-07-15 16:25:33 +02005871 struct htx *htx = htxbuf(&msg->chn->buf);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005872
Christopher Fauleta2097962019-07-15 16:25:33 +02005873 lua_pushboolean(L, http_add_header(htx, ist2(name, name_len),
5874 ist2(value, value_len)));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005875 return 0;
5876}
5877
Christopher Fauletdf97ac42020-02-26 16:57:19 +01005878__LJMP static int hlua_http_req_add_hdr(lua_State *L)
5879{
5880 struct hlua_txn *htxn;
5881
5882 MAY_LJMP(check_args(L, 3, "req_add_hdr"));
5883 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5884
5885 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
5886 WILL_LJMP(lua_error(L));
5887
5888 return hlua_http_add_hdr(L, &htxn->s->txn->req);
5889}
5890
5891__LJMP static int hlua_http_res_add_hdr(lua_State *L)
5892{
5893 struct hlua_txn *htxn;
5894
5895 MAY_LJMP(check_args(L, 3, "res_add_hdr"));
5896 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5897
5898 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
5899 WILL_LJMP(lua_error(L));
5900
5901 return hlua_http_add_hdr(L, &htxn->s->txn->rsp);
5902}
5903
5904static int hlua_http_req_set_hdr(lua_State *L)
5905{
5906 struct hlua_txn *htxn;
5907
5908 MAY_LJMP(check_args(L, 3, "req_set_hdr"));
5909 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5910
5911 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
5912 WILL_LJMP(lua_error(L));
5913
5914 hlua_http_del_hdr(L, &htxn->s->txn->req);
5915 return hlua_http_add_hdr(L, &htxn->s->txn->req);
5916}
5917
5918static int hlua_http_res_set_hdr(lua_State *L)
5919{
5920 struct hlua_txn *htxn;
5921
5922 MAY_LJMP(check_args(L, 3, "res_set_hdr"));
5923 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5924
5925 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
5926 WILL_LJMP(lua_error(L));
5927
5928 hlua_http_del_hdr(L, &htxn->s->txn->rsp);
5929 return hlua_http_add_hdr(L, &htxn->s->txn->rsp);
5930}
5931
5932/* This function set the method. */
5933static int hlua_http_req_set_meth(lua_State *L)
5934{
5935 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5936 size_t name_len;
5937 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
5938
5939 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
5940 WILL_LJMP(lua_error(L));
5941
5942 lua_pushboolean(L, http_req_replace_stline(0, name, name_len, htxn->p, htxn->s) != -1);
5943 return 1;
5944}
5945
5946/* This function set the method. */
5947static int hlua_http_req_set_path(lua_State *L)
5948{
5949 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5950 size_t name_len;
5951 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
5952
5953 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
5954 WILL_LJMP(lua_error(L));
5955
5956 lua_pushboolean(L, http_req_replace_stline(1, name, name_len, htxn->p, htxn->s) != -1);
5957 return 1;
5958}
5959
5960/* This function set the query-string. */
5961static int hlua_http_req_set_query(lua_State *L)
5962{
5963 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5964 size_t name_len;
5965 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
5966
5967 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
5968 WILL_LJMP(lua_error(L));
5969
5970 /* Check length. */
5971 if (name_len > trash.size - 1) {
5972 lua_pushboolean(L, 0);
5973 return 1;
5974 }
5975
5976 /* Add the mark question as prefix. */
5977 chunk_reset(&trash);
5978 trash.area[trash.data++] = '?';
5979 memcpy(trash.area + trash.data, name, name_len);
5980 trash.data += name_len;
5981
5982 lua_pushboolean(L,
5983 http_req_replace_stline(2, trash.area, trash.data, htxn->p, htxn->s) != -1);
5984 return 1;
5985}
5986
5987/* This function set the uri. */
5988static int hlua_http_req_set_uri(lua_State *L)
5989{
5990 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5991 size_t name_len;
5992 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
5993
5994 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
5995 WILL_LJMP(lua_error(L));
5996
5997 lua_pushboolean(L, http_req_replace_stline(3, name, name_len, htxn->p, htxn->s) != -1);
5998 return 1;
5999}
6000
6001/* This function set the response code & optionally reason. */
6002static int hlua_http_res_set_status(lua_State *L)
6003{
6004 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
6005 unsigned int code = MAY_LJMP(luaL_checkinteger(L, 2));
6006 const char *str = MAY_LJMP(luaL_optlstring(L, 3, NULL, NULL));
6007 const struct ist reason = ist2(str, (str ? strlen(str) : 0));
6008
6009 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
6010 WILL_LJMP(lua_error(L));
6011
6012 http_res_set_status(code, reason, htxn->s);
6013 return 0;
6014}
6015
6016/*
6017 *
6018 *
6019 * Class HTTPMessage
6020 *
6021 *
6022 */
6023
6024/* Returns a struct http_msg if the stack entry "ud" is a class HTTPMessage,
6025 * otherwise it throws an error.
6026 */
6027__LJMP static struct http_msg *hlua_checkhttpmsg(lua_State *L, int ud)
6028{
6029 return MAY_LJMP(hlua_checkudata(L, ud, class_http_msg_ref));
6030}
6031
6032/* Creates and pushes on the stack a HTTP object according with a current TXN.
6033 */
Christopher Faulet78c35472020-02-26 17:14:08 +01006034static int hlua_http_msg_new(lua_State *L, struct http_msg *msg)
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006035{
6036 /* Check stack size. */
6037 if (!lua_checkstack(L, 3))
6038 return 0;
6039
6040 lua_newtable(L);
6041 lua_pushlightuserdata(L, msg);
6042 lua_rawseti(L, -2, 0);
6043
6044 /* Create the "channel" field that contains the request channel object. */
6045 lua_pushstring(L, "channel");
6046 if (!hlua_channel_new(L, msg->chn))
6047 return 0;
6048 lua_rawset(L, -3);
6049
6050 /* Pop a class stream metatable and affect it to the table. */
6051 lua_rawgeti(L, LUA_REGISTRYINDEX, class_http_msg_ref);
6052 lua_setmetatable(L, -2);
6053
6054 return 1;
6055}
6056
6057/* Helper function returning a filter attached to the HTTP message at the
6058 * position <ud> in the stack, filling the current offset and length of the
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006059 * filter. If no filter is attached, NULL is returned and <offset> and <len> are
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006060 * filled with output and input length respectively.
6061 */
6062static struct filter *hlua_http_msg_filter(lua_State *L, int ud, struct http_msg *msg, size_t *offset, size_t *len)
6063{
6064 struct channel *chn = msg->chn;
6065 struct htx *htx = htxbuf(&chn->buf);
6066 struct filter *filter = NULL;
6067
6068 *offset = co_data(msg->chn);
6069 *len = htx->data - co_data(msg->chn);
6070
6071 if (lua_getfield(L, ud, "__filter") == LUA_TLIGHTUSERDATA) {
6072 filter = lua_touserdata (L, -1);
6073 if (msg->msg_state >= HTTP_MSG_DATA) {
6074 struct hlua_flt_ctx *flt_ctx = filter->ctx;
6075
6076 *offset = flt_ctx->cur_off[CHN_IDX(chn)];
6077 *len = flt_ctx->cur_len[CHN_IDX(chn)];
6078 }
6079 }
6080
6081 lua_pop(L, 1);
6082 return filter;
6083}
6084
6085/* Returns true if the channel attached to the HTTP message is the response
6086 * channel.
6087 */
6088__LJMP static int hlua_http_msg_is_resp(lua_State *L)
6089{
6090 struct http_msg *msg;
6091
6092 MAY_LJMP(check_args(L, 1, "is_resp"));
6093 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6094
6095 lua_pushboolean(L, !!(msg->chn->flags & CF_ISRESP));
6096 return 1;
6097}
6098
6099/* Returns an array containing the elements status-line of the HTTP message. It relies
6100 * on hlua_http_get_stline().
6101 */
6102__LJMP static int hlua_http_msg_get_stline(lua_State *L)
6103{
6104 struct http_msg *msg;
6105 struct htx *htx;
6106 struct htx_sl *sl;
6107
6108 MAY_LJMP(check_args(L, 1, "get_stline"));
6109 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6110
6111 if (msg->msg_state > HTTP_MSG_BODY)
6112 WILL_LJMP(lua_error(L));
6113
6114 htx = htxbuf(&msg->chn->buf);
6115 sl = http_get_stline(htx);
6116 if (!sl)
6117 return 0;
6118 return hlua_http_get_stline(L, sl);
6119}
6120
6121/* Returns an array containing all headers of the HTTP message. it relies on
6122 * hlua_http_get_headers().
6123 */
6124__LJMP static int hlua_http_msg_get_headers(lua_State *L)
6125{
6126 struct http_msg *msg;
6127
6128 MAY_LJMP(check_args(L, 1, "get_headers"));
6129 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6130
6131 if (msg->msg_state > HTTP_MSG_BODY)
6132 WILL_LJMP(lua_error(L));
6133
6134 return hlua_http_get_headers(L, msg);
6135}
6136
6137/* Deletes all occurrences of an header in the HTTP message matching on its
6138 * name. It relies on hlua_http_del_hdr().
6139 */
6140__LJMP static int hlua_http_msg_del_hdr(lua_State *L)
6141{
6142 struct http_msg *msg;
6143
6144 MAY_LJMP(check_args(L, 2, "del_header"));
6145 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6146
6147 if (msg->msg_state > HTTP_MSG_BODY)
6148 WILL_LJMP(lua_error(L));
6149
6150 return hlua_http_del_hdr(L, msg);
6151}
6152
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006153/* Matches the full value line of all occurrences of an header in the HTTP
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006154 * message given its name against a regex and replaces it if it matches. It
6155 * relies on hlua_http_rep_hdr().
6156 */
6157__LJMP static int hlua_http_msg_rep_hdr(lua_State *L)
6158{
6159 struct http_msg *msg;
6160
6161 MAY_LJMP(check_args(L, 4, "rep_header"));
6162 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6163
6164 if (msg->msg_state > HTTP_MSG_BODY)
6165 WILL_LJMP(lua_error(L));
6166
6167 return hlua_http_rep_hdr(L, msg, 1);
6168}
6169
Ilya Shipitsinbd6b4be2021-10-15 16:18:21 +05006170/* Matches all comma-separated values of all occurrences of an header in the HTTP
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006171 * message given its name against a regex and replaces it if it matches. It
6172 * relies on hlua_http_rep_hdr().
6173 */
6174__LJMP static int hlua_http_msg_rep_val(lua_State *L)
6175{
6176 struct http_msg *msg;
6177
6178 MAY_LJMP(check_args(L, 4, "rep_value"));
6179 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6180
6181 if (msg->msg_state > HTTP_MSG_BODY)
6182 WILL_LJMP(lua_error(L));
6183
6184 return hlua_http_rep_hdr(L, msg, 0);
6185}
6186
6187/* Add an header in the HTTP message. It relies on hlua_http_add_hdr() */
6188__LJMP static int hlua_http_msg_add_hdr(lua_State *L)
6189{
6190 struct http_msg *msg;
6191
6192 MAY_LJMP(check_args(L, 3, "add_header"));
6193 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6194
6195 if (msg->msg_state > HTTP_MSG_BODY)
6196 WILL_LJMP(lua_error(L));
6197
6198 return hlua_http_add_hdr(L, msg);
6199}
6200
6201/* Add an header in the HTTP message removing existing headers with the same
6202 * name. It relies on hlua_http_del_hdr() and hlua_http_add_hdr().
6203 */
6204__LJMP static int hlua_http_msg_set_hdr(lua_State *L)
6205{
6206 struct http_msg *msg;
6207
6208 MAY_LJMP(check_args(L, 3, "set_header"));
6209 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6210
6211 if (msg->msg_state > HTTP_MSG_BODY)
6212 WILL_LJMP(lua_error(L));
6213
6214 hlua_http_del_hdr(L, msg);
6215 return hlua_http_add_hdr(L, msg);
6216}
6217
6218/* Rewrites the request method. It relies on http_req_replace_stline(). */
6219__LJMP static int hlua_http_msg_set_meth(lua_State *L)
6220{
6221 struct stream *s;
6222 struct http_msg *msg;
6223 const char *name;
6224 size_t name_len;
6225
6226 MAY_LJMP(check_args(L, 2, "set_method"));
6227 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6228 name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
6229
6230 if ((msg->chn->flags & CF_ISRESP) || msg->msg_state > HTTP_MSG_BODY)
6231 WILL_LJMP(lua_error(L));
6232
6233 s = chn_strm(msg->chn);
6234 lua_pushboolean(L, http_req_replace_stline(0, name, name_len, s->be, s) != -1);
6235 return 1;
6236}
6237
6238/* Rewrites the request path. It relies on http_req_replace_stline(). */
6239__LJMP static int hlua_http_msg_set_path(lua_State *L)
6240{
6241 struct stream *s;
6242 struct http_msg *msg;
6243 const char *name;
6244 size_t name_len;
6245
6246 MAY_LJMP(check_args(L, 2, "set_path"));
6247 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6248 name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
6249
6250 if ((msg->chn->flags & CF_ISRESP) || msg->msg_state > HTTP_MSG_BODY)
6251 WILL_LJMP(lua_error(L));
6252
6253 s = chn_strm(msg->chn);
6254 lua_pushboolean(L, http_req_replace_stline(1, name, name_len, s->be, s) != -1);
6255 return 1;
6256}
6257
6258/* Rewrites the request query-string. It relies on http_req_replace_stline(). */
6259__LJMP static int hlua_http_msg_set_query(lua_State *L)
6260{
6261 struct stream *s;
6262 struct http_msg *msg;
6263 const char *name;
6264 size_t name_len;
6265
6266 MAY_LJMP(check_args(L, 2, "set_query"));
6267 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6268 name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
6269
6270 if ((msg->chn->flags & CF_ISRESP) || msg->msg_state > HTTP_MSG_BODY)
6271 WILL_LJMP(lua_error(L));
6272
6273 /* Check length. */
6274 if (name_len > trash.size - 1) {
6275 lua_pushboolean(L, 0);
6276 return 1;
6277 }
6278
6279 /* Add the mark question as prefix. */
6280 chunk_reset(&trash);
6281 trash.area[trash.data++] = '?';
6282 memcpy(trash.area + trash.data, name, name_len);
6283 trash.data += name_len;
6284
6285 s = chn_strm(msg->chn);
6286 lua_pushboolean(L, http_req_replace_stline(2, trash.area, trash.data, s->be, s) != -1);
6287 return 1;
6288}
6289
6290/* Rewrites the request URI. It relies on http_req_replace_stline(). */
6291__LJMP static int hlua_http_msg_set_uri(lua_State *L)
6292{
6293 struct stream *s;
6294 struct http_msg *msg;
6295 const char *name;
6296 size_t name_len;
6297
6298 MAY_LJMP(check_args(L, 2, "set_uri"));
6299 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6300 name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
6301
6302 if ((msg->chn->flags & CF_ISRESP) || msg->msg_state > HTTP_MSG_BODY)
6303 WILL_LJMP(lua_error(L));
6304
6305 s = chn_strm(msg->chn);
6306 lua_pushboolean(L, http_req_replace_stline(3, name, name_len, s->be, s) != -1);
6307 return 1;
6308}
6309
6310/* Rewrites the response status code. It relies on http_res_set_status(). */
6311__LJMP static int hlua_http_msg_set_status(lua_State *L)
6312{
6313 struct http_msg *msg;
6314 unsigned int code;
6315 const char *reason;
6316 size_t reason_len;
6317
6318 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6319 code = MAY_LJMP(luaL_checkinteger(L, 2));
6320 reason = MAY_LJMP(luaL_optlstring(L, 3, NULL, &reason_len));
6321
6322 if (!(msg->chn->flags & CF_ISRESP) || msg->msg_state > HTTP_MSG_BODY)
6323 WILL_LJMP(lua_error(L));
6324
6325 lua_pushboolean(L, http_res_set_status(code, ist2(reason, reason_len), chn_strm(msg->chn)) != -1);
6326 return 1;
6327}
6328
6329/* Returns true if the HTTP message is full. */
6330__LJMP static int hlua_http_msg_is_full(lua_State *L)
6331{
6332 struct http_msg *msg;
6333
6334 MAY_LJMP(check_args(L, 1, "is_full"));
6335 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6336 lua_pushboolean(L, channel_full(msg->chn, 0));
6337 return 1;
6338}
6339
6340/* Returns true if the HTTP message may still receive data. */
6341__LJMP static int hlua_http_msg_may_recv(lua_State *L)
6342{
6343 struct http_msg *msg;
6344 struct htx *htx;
6345
6346 MAY_LJMP(check_args(L, 1, "may_recv"));
6347 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6348 htx = htxbuf(&msg->chn->buf);
6349 lua_pushboolean(L, (htx_expect_more(htx) && !channel_input_closed(msg->chn) && channel_may_recv(msg->chn)));
6350 return 1;
6351}
6352
6353/* Returns true if the HTTP message EOM was received */
6354__LJMP static int hlua_http_msg_is_eom(lua_State *L)
6355{
6356 struct http_msg *msg;
6357 struct htx *htx;
6358
6359 MAY_LJMP(check_args(L, 1, "may_recv"));
6360 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6361 htx = htxbuf(&msg->chn->buf);
6362 lua_pushboolean(L, !htx_expect_more(htx));
6363 return 1;
6364}
6365
6366/* Returns the number of bytes available in the input side of the HTTP
6367 * message. This function never fails.
6368 */
6369__LJMP static int hlua_http_msg_get_in_len(lua_State *L)
6370{
6371 struct http_msg *msg;
Christopher Fauleteae8afa2020-02-26 17:15:48 +01006372 size_t output, input;
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006373
6374 MAY_LJMP(check_args(L, 1, "input"));
6375 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
Christopher Fauleteae8afa2020-02-26 17:15:48 +01006376 hlua_http_msg_filter(L, 1, msg, &output, &input);
6377 lua_pushinteger(L, input);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006378 return 1;
6379}
6380
6381/* Returns the number of bytes available in the output side of the HTTP
6382 * message. This function never fails.
6383 */
6384__LJMP static int hlua_http_msg_get_out_len(lua_State *L)
6385{
6386 struct http_msg *msg;
Christopher Fauleteae8afa2020-02-26 17:15:48 +01006387 size_t output, input;
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006388
6389 MAY_LJMP(check_args(L, 1, "output"));
6390 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
Christopher Fauleteae8afa2020-02-26 17:15:48 +01006391 hlua_http_msg_filter(L, 1, msg, &output, &input);
6392 lua_pushinteger(L, output);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006393 return 1;
6394}
6395
6396/* Copies at most <len> bytes of DATA blocks from the HTTP message <msg>
6397 * starting at the offset <offset> and put it in a string LUA variables. It
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006398 * returns the built string length. It stops on the first non-DATA HTX
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006399 * block. This function is called during the payload filtering, so the headers
6400 * are already scheduled for output (from the filter point of view).
6401 */
6402static int _hlua_http_msg_dup(struct http_msg *msg, lua_State *L, size_t offset, size_t len)
6403{
6404 struct htx *htx = htxbuf(&msg->chn->buf);
6405 struct htx_blk *blk;
6406 struct htx_ret htxret;
6407 luaL_Buffer b;
6408 int ret = 0;
6409
6410 luaL_buffinit(L, &b);
6411 htxret = htx_find_offset(htx, offset);
6412 for (blk = htxret.blk, offset = htxret.ret; blk && len; blk = htx_get_next_blk(htx, blk)) {
6413 enum htx_blk_type type = htx_get_blk_type(blk);
6414 struct ist v;
6415
6416 switch (type) {
6417 case HTX_BLK_UNUSED:
6418 break;
6419
6420 case HTX_BLK_DATA:
6421 v = htx_get_blk_value(htx, blk);
Tim Duesterhusb113b5c2021-09-15 13:58:44 +02006422 v = istadv(v, offset);
Tim Duesterhus2471f5c2021-11-08 09:05:01 +01006423 v = isttrim(v, len);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006424
6425 luaL_addlstring(&b, v.ptr, v.len);
6426 ret += v.len;
6427 break;
6428
6429 default:
vishnu0af4bd72021-10-24 06:46:24 +05306430 if (!ret)
6431 goto no_data;
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006432 goto end;
6433 }
6434 offset = 0;
6435 }
6436
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006437end:
vishnu0af4bd72021-10-24 06:46:24 +05306438 if (!ret && (htx->flags & HTX_FL_EOM))
6439 goto no_data;
6440 luaL_pushresult(&b);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006441 return ret;
vishnu0af4bd72021-10-24 06:46:24 +05306442
6443 no_data:
6444 /* Remove the empty string and push nil on the stack */
6445 lua_pop(L, 1);
6446 lua_pushnil(L);
6447 return 0;
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006448}
6449
6450/* Copies the string <str> to the HTTP message <msg> at the offset
6451 * <offset>. This function returns -1 if data cannot be copied. Otherwise, it
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006452 * returns the amount of data written. This function is responsible to update
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006453 * the filter context.
6454 */
6455static int _hlua_http_msg_insert(struct http_msg *msg, struct filter *filter, struct ist str, size_t offset)
6456{
6457 struct htx *htx = htx_from_buf(&msg->chn->buf);
6458 struct htx_ret htxret;
6459 int /*max, */ret = 0;
6460
6461 /* Nothing to do, just return */
6462 if (unlikely(istlen(str) == 0))
6463 goto end;
6464
6465 if (istlen(str) > htx_free_data_space(htx)) {
6466 ret = -1;
6467 goto end;
6468 }
6469
6470 htxret = htx_find_offset(htx, offset);
6471 if (!htxret.blk || htx_get_blk_type(htxret.blk) != HTX_BLK_DATA) {
6472 if (!htx_add_last_data(htx, str))
6473 goto end;
6474 }
6475 else {
6476 struct ist v = htx_get_blk_value(htx, htxret.blk);
6477 v.ptr += htxret.ret;
6478 v.len = 0;
6479 if (!htx_replace_blk_value(htx, htxret.blk, v, str))
6480 goto end;
6481 }
6482 ret = str.len;
6483 if (ret) {
6484 struct hlua_flt_ctx *flt_ctx = filter->ctx;
6485 flt_update_offsets(filter, msg->chn, ret);
6486 flt_ctx->cur_len[CHN_IDX(msg->chn)] += ret;
6487 }
6488
6489 end:
6490 htx_to_buf(htx, &msg->chn->buf);
6491 return ret;
6492}
6493
6494/* Helper function removing at most <len> bytes of DATA blocks at the absolute
6495 * position <offset>. It stops on the first non-DATA HTX block. This function is
6496 * called during the payload filtering, so the headers are already scheduled for
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006497 * output (from the filter point of view). This function is responsible to
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006498 * update the filter context.
6499 */
6500static void _hlua_http_msg_delete(struct http_msg *msg, struct filter *filter, size_t offset, size_t len)
6501{
6502 struct hlua_flt_ctx *flt_ctx = filter->ctx;
6503 struct htx *htx = htx_from_buf(&msg->chn->buf);
6504 struct htx_blk *blk;
6505 struct htx_ret htxret;
6506 size_t ret = 0;
6507
6508 /* Be sure <len> is always the amount of DATA to remove */
6509 if (htx->data == offset+len && htx_get_tail_type(htx) == HTX_BLK_DATA) {
Aurelien DARRAGONbcbcf982022-09-28 19:08:15 +02006510 /* When htx tail type == HTX_BLK_DATA, no need to take care
6511 * of special blocks like HTX_BLK_EOT.
6512 * We simply truncate after offset
6513 * (truncate targeted blk and discard the following ones)
6514 */
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006515 htx_truncate(htx, offset);
6516 ret = len;
6517 goto end;
6518 }
6519
6520 htxret = htx_find_offset(htx, offset);
6521 blk = htxret.blk;
6522 if (htxret.ret) {
Aurelien DARRAGONbcbcf982022-09-28 19:08:15 +02006523 /* dealing with offset: we need to trim targeted blk */
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006524 struct ist v;
6525
6526 if (htx_get_blk_type(blk) != HTX_BLK_DATA)
6527 goto end;
Aurelien DARRAGONbcbcf982022-09-28 19:08:15 +02006528
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006529 v = htx_get_blk_value(htx, blk);
Tim Duesterhusa029d782022-10-08 12:33:18 +02006530 v = istadv(v, htxret.ret);
Aurelien DARRAGONbcbcf982022-09-28 19:08:15 +02006531
Tim Duesterhus2471f5c2021-11-08 09:05:01 +01006532 v = isttrim(v, len);
Aurelien DARRAGONbcbcf982022-09-28 19:08:15 +02006533 /* trimming data in blk: discard everything after the offset
6534 * (replace 'v' with 'IST_NULL')
6535 */
Tim Duesterhusb113b5c2021-09-15 13:58:44 +02006536 blk = htx_replace_blk_value(htx, blk, v, IST_NULL);
Aurelien DARRAGONbcbcf982022-09-28 19:08:15 +02006537 if (blk && v.len < len) {
6538 /* In this case, caller wants to keep removing data,
6539 * but we need to spare current blk
6540 * because it was already trimmed
6541 */
6542 blk = htx_get_next_blk(htx, blk);
6543 }
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006544 len -= v.len;
6545 ret += v.len;
6546 }
6547
6548
6549 while (blk && len) {
Aurelien DARRAGONbcbcf982022-09-28 19:08:15 +02006550 /* there is more data that needs to be discarded */
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006551 enum htx_blk_type type = htx_get_blk_type(blk);
6552 uint32_t sz = htx_get_blksz(blk);
6553
6554 switch (type) {
6555 case HTX_BLK_UNUSED:
6556 break;
6557
6558 case HTX_BLK_DATA:
6559 if (len < sz) {
Aurelien DARRAGONbcbcf982022-09-28 19:08:15 +02006560 /* don't discard whole blk, only part of it
6561 * (from the beginning)
6562 */
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006563 htx_cut_data_blk(htx, blk, len);
6564 ret += len;
6565 goto end;
6566 }
6567 break;
6568
6569 default:
Aurelien DARRAGONbcbcf982022-09-28 19:08:15 +02006570 /* HTX_BLK_EOT blk won't be removed */
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006571 goto end;
6572 }
6573
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006574 /* Remove all the data block */
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006575 len -= sz;
6576 ret += sz;
6577 blk = htx_remove_blk(htx, blk);
6578 }
6579
6580end:
6581 flt_update_offsets(filter, msg->chn, -ret);
6582 flt_ctx->cur_len[CHN_IDX(msg->chn)] -= ret;
6583 /* WARNING: we don't call htx_to_buf() on purpose, because we don't want
6584 * to loose the EOM flag if the message is empty.
6585 */
6586}
6587
6588/* Copies input data found in an HTTP message. Unlike the channel function used
6589 * to duplicate raw data, this one can only be called inside a filter, from
6590 * http_payload callback. So it cannot yield. An exception is returned if it is
6591 * called from another callback. If nothing was copied, a nil value is pushed on
6592 * the stack.
6593 */
6594__LJMP static int hlua_http_msg_get_body(lua_State *L)
6595{
6596 struct http_msg *msg;
6597 struct filter *filter;
6598 size_t output, input;
6599 int offset, len;
6600
6601 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
6602 WILL_LJMP(luaL_error(L, "'data' expects at most 2 arguments"));
6603 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6604
6605 if (msg->msg_state < HTTP_MSG_DATA)
6606 WILL_LJMP(lua_error(L));
6607
6608 filter = hlua_http_msg_filter(L, 1, msg, &output, &input);
6609 if (!filter || !hlua_filter_from_payload(filter))
6610 WILL_LJMP(lua_error(L));
6611
6612 if (!ci_data(msg->chn) && channel_input_closed(msg->chn)) {
6613 lua_pushnil(L);
6614 return 1;
6615 }
6616
6617 offset = output;
6618 if (lua_gettop(L) > 1) {
6619 offset = MAY_LJMP(luaL_checkinteger(L, 2));
6620 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02006621 offset = MAX(0, (int)input + offset);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006622 offset += output;
6623 if (offset < output || offset > input + output) {
6624 lua_pushfstring(L, "offset out of range.");
6625 WILL_LJMP(lua_error(L));
6626 }
6627 }
6628 len = output + input - offset;
6629 if (lua_gettop(L) == 3) {
6630 len = MAY_LJMP(luaL_checkinteger(L, 3));
6631 if (!len)
6632 goto dup;
6633 if (len == -1)
6634 len = global.tune.bufsize;
6635 if (len < 0) {
6636 lua_pushfstring(L, "length out of range.");
6637 WILL_LJMP(lua_error(L));
6638 }
6639 }
6640
6641 dup:
6642 _hlua_http_msg_dup(msg, L, offset, len);
6643 return 1;
6644}
6645
6646/* Appends a string to the HTTP message, after all existing DATA blocks but
6647 * before the trailers, if any. It returns the amount of data written or -1 if
6648 * nothing was copied. Unlike the channel function used to append data, this one
6649 * can only be called inside a filter, from http_payload callback. So it cannot
6650 * yield. An exception is returned if it is called from another callback.
6651 */
6652__LJMP static int hlua_http_msg_append(lua_State *L)
6653{
6654 struct http_msg *msg;
6655 struct filter *filter;
6656 const char *str;
6657 size_t offset, len, sz;
6658 int ret;
6659
6660 MAY_LJMP(check_args(L, 2, "append"));
6661 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6662
6663 if (msg->msg_state < HTTP_MSG_DATA)
6664 WILL_LJMP(lua_error(L));
6665
6666 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
6667 filter = hlua_http_msg_filter(L, 1, msg, &offset, &len);
6668 if (!filter || !hlua_filter_from_payload(filter))
6669 WILL_LJMP(lua_error(L));
6670
6671 ret = _hlua_http_msg_insert(msg, filter, ist2(str, sz), offset+len);
6672 lua_pushinteger(L, ret);
6673 return 1;
6674}
6675
6676/* Prepends a string to the HTTP message, before all existing DATA blocks. It
6677 * returns the amount of data written or -1 if nothing was copied. Unlike the
6678 * channel function used to prepend data, this one can only be called inside a
6679 * filter, from http_payload callback. So it cannot yield. An exception is
6680 * returned if it is called from another callback.
6681 */
6682__LJMP static int hlua_http_msg_prepend(lua_State *L)
6683{
6684 struct http_msg *msg;
6685 struct filter *filter;
6686 const char *str;
6687 size_t offset, len, sz;
6688 int ret;
6689
6690 MAY_LJMP(check_args(L, 2, "prepend"));
6691 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006692
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006693 if (msg->msg_state < HTTP_MSG_DATA)
6694 WILL_LJMP(lua_error(L));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006695
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006696 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
6697 filter = hlua_http_msg_filter(L, 1, msg, &offset, &len);
6698 if (!filter || !hlua_filter_from_payload(filter))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006699 WILL_LJMP(lua_error(L));
6700
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006701 ret = _hlua_http_msg_insert(msg, filter, ist2(str, sz), offset);
6702 lua_pushinteger(L, ret);
6703 return 1;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006704}
6705
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006706/* Inserts a string to the HTTP message at a given offset. By default the string
6707 * is appended at the end of DATA blocks. It returns the amount of data written
6708 * or -1 if nothing was copied. Unlike the channel function used to insert data,
6709 * this one can only be called inside a filter, from http_payload callback. So
6710 * it cannot yield. An exception is returned if it is called from another
6711 * callback.
6712 */
6713__LJMP static int hlua_http_msg_insert_data(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006714{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006715 struct http_msg *msg;
6716 struct filter *filter;
6717 const char *str;
6718 size_t input, output, sz;
6719 int offset;
6720 int ret;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006721
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006722 if (lua_gettop(L) < 2 || lua_gettop(L) > 3)
6723 WILL_LJMP(luaL_error(L, "'insert' expects at least 1 argument and at most 2 arguments"));
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006724 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006725
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006726 if (msg->msg_state < HTTP_MSG_DATA)
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006727 WILL_LJMP(lua_error(L));
6728
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006729 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
Aurelien DARRAGON7fdba0a2022-09-28 16:03:45 +02006730 filter = hlua_http_msg_filter(L, 1, msg, &output, &input);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006731 if (!filter || !hlua_filter_from_payload(filter))
6732 WILL_LJMP(lua_error(L));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006733
Aurelien DARRAGON7fdba0a2022-09-28 16:03:45 +02006734 offset = output;
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006735 if (lua_gettop(L) > 2) {
6736 offset = MAY_LJMP(luaL_checkinteger(L, 3));
6737 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02006738 offset = MAX(0, (int)input + offset);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006739 offset += output;
Aurelien DARRAGON7fdba0a2022-09-28 16:03:45 +02006740 if (offset > output + input) {
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006741 lua_pushfstring(L, "offset out of range.");
6742 WILL_LJMP(lua_error(L));
6743 }
6744 }
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006745
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006746 ret = _hlua_http_msg_insert(msg, filter, ist2(str, sz), offset);
6747 lua_pushinteger(L, ret);
6748 return 1;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006749}
6750
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006751/* Removes a given amount of data from the HTTP message at a given offset. By
6752 * default all DATA blocks are removed. It returns the amount of data
6753 * removed. Unlike the channel function used to remove data, this one can only
6754 * be called inside a filter, from http_payload callback. So it cannot yield. An
6755 * exception is returned if it is called from another callback.
6756 */
6757__LJMP static int hlua_http_msg_del_data(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006758{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006759 struct http_msg *msg;
6760 struct filter *filter;
6761 size_t input, output;
6762 int offset, len;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006763
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006764 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
Boyang Lie0c54352022-05-10 17:47:23 +00006765 WILL_LJMP(luaL_error(L, "'remove' expects at most 2 arguments"));
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006766 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006767
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006768 if (msg->msg_state < HTTP_MSG_DATA)
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006769 WILL_LJMP(lua_error(L));
6770
Aurelien DARRAGONd7c71b02022-09-28 15:52:18 +02006771 filter = hlua_http_msg_filter(L, 1, msg, &output, &input);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006772 if (!filter || !hlua_filter_from_payload(filter))
6773 WILL_LJMP(lua_error(L));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006774
Aurelien DARRAGONd7c71b02022-09-28 15:52:18 +02006775 offset = output;
Boyang Lie0c54352022-05-10 17:47:23 +00006776 if (lua_gettop(L) > 1) {
6777 offset = MAY_LJMP(luaL_checkinteger(L, 2));
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006778 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02006779 offset = MAX(0, (int)input + offset);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006780 offset += output;
Aurelien DARRAGONd7c71b02022-09-28 15:52:18 +02006781 if (offset > output + input) {
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006782 lua_pushfstring(L, "offset out of range.");
6783 WILL_LJMP(lua_error(L));
6784 }
6785 }
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006786
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006787 len = output + input - offset;
Boyang Lie0c54352022-05-10 17:47:23 +00006788 if (lua_gettop(L) == 3) {
6789 len = MAY_LJMP(luaL_checkinteger(L, 3));
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006790 if (!len)
6791 goto end;
6792 if (len == -1)
6793 len = output + input - offset;
6794 if (len < 0 || offset + len > output + input) {
6795 lua_pushfstring(L, "length out of range.");
6796 WILL_LJMP(lua_error(L));
6797 }
6798 }
6799
6800 _hlua_http_msg_delete(msg, filter, offset, len);
6801
6802 end:
6803 lua_pushinteger(L, len);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006804 return 1;
6805}
6806
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006807/* Replaces a given amount of data at the given offset by a string. By default,
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006808 * all remaining data are removed, accordingly to the filter context. It returns
6809 * the amount of data written or -1 if nothing was copied. Unlike the channel
6810 * function used to replace data, this one can only be called inside a filter,
6811 * from http_payload callback. So it cannot yield. An exception is returned if
6812 * it is called from another callback.
6813 */
6814__LJMP static int hlua_http_msg_set_data(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006815{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006816 struct http_msg *msg;
6817 struct filter *filter;
6818 struct htx *htx;
6819 const char *str;
6820 size_t input, output, sz;
6821 int offset, len;
6822 int ret;
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02006823
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006824 if (lua_gettop(L) < 2 || lua_gettop(L) > 4)
6825 WILL_LJMP(luaL_error(L, "'set' expects at least 1 argument and at most 3 arguments"));
6826 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6827
6828 if (msg->msg_state < HTTP_MSG_DATA)
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006829 WILL_LJMP(lua_error(L));
6830
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006831 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
6832 filter = hlua_http_msg_filter(L, 1, msg, &output, &input);
6833 if (!filter || !hlua_filter_from_payload(filter))
6834 WILL_LJMP(lua_error(L));
6835
6836 offset = output;
6837 if (lua_gettop(L) > 2) {
6838 offset = MAY_LJMP(luaL_checkinteger(L, 3));
6839 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02006840 offset = MAX(0, (int)input + offset);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006841 offset += output;
6842 if (offset < output || offset > input + output) {
6843 lua_pushfstring(L, "offset out of range.");
6844 WILL_LJMP(lua_error(L));
6845 }
6846 }
6847
6848 len = output + input - offset;
6849 if (lua_gettop(L) == 4) {
6850 len = MAY_LJMP(luaL_checkinteger(L, 4));
6851 if (!len)
6852 goto set;
6853 if (len == -1)
6854 len = output + input - offset;
6855 if (len < 0 || offset + len > output + input) {
6856 lua_pushfstring(L, "length out of range.");
6857 WILL_LJMP(lua_error(L));
6858 }
6859 }
6860
6861 set:
6862 /* Be sure we can copied the string once input data will be removed. */
6863 htx = htx_from_buf(&msg->chn->buf);
6864 if (sz > htx_free_data_space(htx) + len)
6865 lua_pushinteger(L, -1);
6866 else {
6867 _hlua_http_msg_delete(msg, filter, offset, len);
6868 ret = _hlua_http_msg_insert(msg, filter, ist2(str, sz), offset);
6869 lua_pushinteger(L, ret);
6870 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006871 return 1;
6872}
6873
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006874/* Prepends data into an HTTP message and forward it, from the filter point of
6875 * view. It returns the amount of data written or -1 if nothing was sent. Unlike
6876 * the channel function used to send data, this one can only be called inside a
6877 * filter, from http_payload callback. So it cannot yield. An exception is
6878 * returned if it is called from another callback.
6879 */
6880__LJMP static int hlua_http_msg_send(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006881{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006882 struct http_msg *msg;
6883 struct filter *filter;
6884 struct htx *htx;
6885 const char *str;
6886 size_t offset, len, sz;
6887 int ret;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006888
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006889 MAY_LJMP(check_args(L, 2, "send"));
6890 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6891
6892 if (msg->msg_state < HTTP_MSG_DATA)
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006893 WILL_LJMP(lua_error(L));
6894
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006895 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
6896 filter = hlua_http_msg_filter(L, 1, msg, &offset, &len);
6897 if (!filter || !hlua_filter_from_payload(filter))
6898 WILL_LJMP(lua_error(L));
6899
6900 /* Return an error if the channel's output is closed */
6901 if (unlikely(channel_output_closed(msg->chn))) {
6902 lua_pushinteger(L, -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006903 return 1;
6904 }
6905
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006906 htx = htx_from_buf(&msg->chn->buf);
6907 if (sz > htx_free_data_space(htx)) {
6908 lua_pushinteger(L, -1);
6909 return 1;
6910 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006911
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006912 ret = _hlua_http_msg_insert(msg, filter, ist2(str, sz), offset);
6913 if (ret > 0) {
6914 struct hlua_flt_ctx *flt_ctx = filter->ctx;
6915
6916 FLT_OFF(filter, msg->chn) += ret;
6917 flt_ctx->cur_len[CHN_IDX(msg->chn)] -= ret;
6918 flt_ctx->cur_off[CHN_IDX(msg->chn)] += ret;
6919 }
6920
6921 lua_pushinteger(L, ret);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006922 return 1;
6923}
6924
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006925/* Forwards a given amount of bytes. It return -1 if the channel's output is
6926 * closed. Otherwise, it returns the number of bytes forwarded. Unlike the
6927 * channel function used to forward data, this one can only be called inside a
6928 * filter, from http_payload callback. So it cannot yield. An exception is
6929 * returned if it is called from another callback. All other functions deal with
6930 * DATA block, this one not.
6931*/
6932__LJMP static int hlua_http_msg_forward(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006933{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006934 struct http_msg *msg;
6935 struct filter *filter;
6936 size_t offset, len;
6937 int fwd, ret = 0;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006938
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006939 MAY_LJMP(check_args(L, 2, "forward"));
6940 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6941
6942 if (msg->msg_state < HTTP_MSG_DATA)
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006943 WILL_LJMP(lua_error(L));
6944
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006945 fwd = MAY_LJMP(luaL_checkinteger(L, 2));
6946 filter = hlua_http_msg_filter(L, 1, msg, &offset, &len);
6947 if (!filter || !hlua_filter_from_payload(filter))
6948 WILL_LJMP(lua_error(L));
6949
6950 /* Nothing to do, just return */
6951 if (!fwd)
6952 goto end;
6953
6954 /* Return an error if the channel's output is closed */
6955 if (unlikely(channel_output_closed(msg->chn))) {
6956 ret = -1;
6957 goto end;
6958 }
6959
6960 ret = fwd;
6961 if (ret > len)
6962 ret = len;
6963
6964 if (ret) {
6965 struct hlua_flt_ctx *flt_ctx = filter->ctx;
6966
6967 FLT_OFF(filter, msg->chn) += ret;
6968 flt_ctx->cur_off[CHN_IDX(msg->chn)] += ret;
6969 flt_ctx->cur_len[CHN_IDX(msg->chn)] -= ret;
6970 }
6971
6972 end:
6973 lua_pushinteger(L, ret);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006974 return 1;
6975}
6976
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006977/* Set EOM flag on the HTX message.
6978 *
6979 * NOTE: Not sure it is a good idea to manipulate this flag but for now I don't
6980 * really know how to do without this feature.
6981 */
6982__LJMP static int hlua_http_msg_set_eom(lua_State *L)
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02006983{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006984 struct http_msg *msg;
6985 struct htx *htx;
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02006986
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006987 MAY_LJMP(check_args(L, 1, "set_eom"));
6988 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6989 htx = htxbuf(&msg->chn->buf);
6990 htx->flags |= HTX_FL_EOM;
6991 return 0;
6992}
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006993
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006994/* Unset EOM flag on the HTX message.
6995 *
6996 * NOTE: Not sure it is a good idea to manipulate this flag but for now I don't
6997 * really know how to do without this feature.
6998 */
6999__LJMP static int hlua_http_msg_unset_eom(lua_State *L)
7000{
7001 struct http_msg *msg;
7002 struct htx *htx;
7003
7004 MAY_LJMP(check_args(L, 1, "set_eom"));
7005 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
7006 htx = htxbuf(&msg->chn->buf);
7007 htx->flags &= ~HTX_FL_EOM;
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02007008 return 0;
7009}
7010
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007011/*
7012 *
7013 *
William Lallemand3956c4e2021-09-21 16:25:15 +02007014 * Class HTTPClient
7015 *
7016 *
7017 */
7018__LJMP static struct hlua_httpclient *hlua_checkhttpclient(lua_State *L, int ud)
7019{
7020 return MAY_LJMP(hlua_checkudata(L, ud, class_httpclient_ref));
7021}
7022
William Lallemandf77f1de2021-09-28 19:10:38 +02007023
7024/* stops the httpclient and ask it to kill itself */
7025__LJMP static int hlua_httpclient_gc(lua_State *L)
7026{
7027 struct hlua_httpclient *hlua_hc;
7028
7029 MAY_LJMP(check_args(L, 1, "__gc"));
7030
7031 hlua_hc = MAY_LJMP(hlua_checkhttpclient(L, 1));
7032
William Lallemandbb581422022-10-20 10:57:28 +02007033 if (hlua_hc->hc)
7034 httpclient_stop_and_destroy(hlua_hc->hc);
7035
William Lallemandf77f1de2021-09-28 19:10:38 +02007036 hlua_hc->hc = NULL;
William Lallemand94dbfed2022-12-08 11:11:36 +01007037 LIST_DEL_INIT(&hlua_hc->by_hlua);
William Lallemandf77f1de2021-09-28 19:10:38 +02007038
7039 return 0;
7040}
7041
7042
William Lallemand3956c4e2021-09-21 16:25:15 +02007043__LJMP static int hlua_httpclient_new(lua_State *L)
7044{
7045 struct hlua_httpclient *hlua_hc;
7046 struct hlua *hlua;
7047
7048 /* Get hlua struct, or NULL if we execute from main lua state */
7049 hlua = hlua_gethlua(L);
7050 if (!hlua)
7051 return 0;
7052
7053 /* Check stack size. */
7054 if (!lua_checkstack(L, 3)) {
7055 hlua_pusherror(L, "httpclient: full stack");
7056 goto err;
7057 }
7058 /* Create the object: obj[0] = userdata. */
7059 lua_newtable(L);
7060 hlua_hc = MAY_LJMP(lua_newuserdata(L, sizeof(*hlua_hc)));
7061 lua_rawseti(L, -2, 0);
7062 memset(hlua_hc, 0, sizeof(*hlua_hc));
7063
7064 hlua_hc->hc = httpclient_new(hlua, 0, IST_NULL);
7065 if (!hlua_hc->hc)
7066 goto err;
7067
William Lallemandbb581422022-10-20 10:57:28 +02007068 LIST_APPEND(&hlua->hc_list, &hlua_hc->by_hlua);
7069
William Lallemand3956c4e2021-09-21 16:25:15 +02007070 /* Pop a class stream metatable and affect it to the userdata. */
7071 lua_rawgeti(L, LUA_REGISTRYINDEX, class_httpclient_ref);
7072 lua_setmetatable(L, -2);
7073
7074 return 1;
7075
7076 err:
7077 WILL_LJMP(lua_error(L));
7078 return 0;
7079}
7080
7081
7082/*
7083 * Callback of the httpclient, this callback wakes the lua task up, once the
7084 * httpclient receives some data
7085 *
7086 */
7087
William Lallemandbd5739e2021-10-28 15:41:38 +02007088static void hlua_httpclient_cb(struct httpclient *hc)
William Lallemand3956c4e2021-09-21 16:25:15 +02007089{
7090 struct hlua *hlua = hc->caller;
7091
7092 if (!hlua || !hlua->task)
7093 return;
7094
7095 task_wakeup(hlua->task, TASK_WOKEN_MSG);
7096}
7097
7098/*
William Lallemandd7df73a2021-09-23 17:54:00 +02007099 * Fill the lua stack with headers from the httpclient response
7100 * This works the same way as the hlua_http_get_headers() function
7101 */
7102__LJMP static int hlua_httpclient_get_headers(lua_State *L, struct hlua_httpclient *hlua_hc)
7103{
7104 struct http_hdr *hdr;
7105
7106 lua_newtable(L);
7107
William Lallemandef574b22021-10-05 16:19:31 +02007108 for (hdr = hlua_hc->hc->res.hdrs; hdr && isttest(hdr->n); hdr++) {
William Lallemandd7df73a2021-09-23 17:54:00 +02007109 struct ist n, v;
7110 int len;
7111
7112 n = hdr->n;
7113 v = hdr->v;
7114
7115 /* Check for existing entry:
7116 * assume that the table is on the top of the stack, and
7117 * push the key in the stack, the function lua_gettable()
7118 * perform the lookup.
7119 */
7120
7121 lua_pushlstring(L, n.ptr, n.len);
7122 lua_gettable(L, -2);
7123
7124 switch (lua_type(L, -1)) {
7125 case LUA_TNIL:
7126 /* Table not found, create it. */
7127 lua_pop(L, 1); /* remove the nil value. */
7128 lua_pushlstring(L, n.ptr, n.len); /* push the header name as key. */
7129 lua_newtable(L); /* create and push empty table. */
7130 lua_pushlstring(L, v.ptr, v.len); /* push header value. */
7131 lua_rawseti(L, -2, 0); /* index header value (pop it). */
7132 lua_rawset(L, -3); /* index new table with header name (pop the values). */
7133 break;
7134
7135 case LUA_TTABLE:
7136 /* Entry found: push the value in the table. */
7137 len = lua_rawlen(L, -1);
7138 lua_pushlstring(L, v.ptr, v.len); /* push header value. */
7139 lua_rawseti(L, -2, len+1); /* index header value (pop it). */
7140 lua_pop(L, 1); /* remove the table (it is stored in the main table). */
7141 break;
7142
7143 default:
7144 /* Other cases are errors. */
7145 hlua_pusherror(L, "internal error during the parsing of headers.");
7146 WILL_LJMP(lua_error(L));
7147 }
7148 }
7149 return 1;
7150}
7151
7152/*
William Lallemand746e6f32021-10-06 10:57:44 +02007153 * Allocate and return an array of http_hdr ist extracted from the <headers> lua table
7154 *
7155 * Caller must free the result
7156 */
7157struct http_hdr *hlua_httpclient_table_to_hdrs(lua_State *L)
7158{
7159 struct http_hdr hdrs[global.tune.max_http_hdr];
7160 struct http_hdr *result = NULL;
7161 uint32_t hdr_num = 0;
7162
7163 lua_pushnil(L);
7164 while (lua_next(L, -2) != 0) {
7165 struct ist name, value;
7166 const char *n, *v;
7167 size_t nlen, vlen;
7168
7169 if (!lua_isstring(L, -2) || !lua_istable(L, -1)) {
7170 /* Skip element if the key is not a string or if the value is not a table */
7171 goto next_hdr;
7172 }
7173
7174 n = lua_tolstring(L, -2, &nlen);
7175 name = ist2(n, nlen);
7176
7177 /* Loop on header's values */
7178 lua_pushnil(L);
7179 while (lua_next(L, -2)) {
7180 if (!lua_isstring(L, -1)) {
7181 /* Skip the value if it is not a string */
7182 goto next_value;
7183 }
7184
7185 v = lua_tolstring(L, -1, &vlen);
7186 value = ist2(v, vlen);
7187 name = ist2(n, nlen);
7188
7189 hdrs[hdr_num].n = istdup(name);
7190 hdrs[hdr_num].v = istdup(value);
7191
7192 hdr_num++;
7193
7194 next_value:
7195 lua_pop(L, 1);
7196 }
7197
7198 next_hdr:
7199 lua_pop(L, 1);
7200
7201 }
7202
7203 if (hdr_num) {
7204 /* alloc and copy the headers in the httpclient struct */
Tim Duesterhus16cc16d2021-11-06 15:14:45 +01007205 result = calloc((hdr_num + 1), sizeof(*result));
William Lallemand746e6f32021-10-06 10:57:44 +02007206 if (!result)
7207 goto skip_headers;
7208 memcpy(result, hdrs, sizeof(struct http_hdr) * (hdr_num + 1));
7209
7210 result[hdr_num].n = IST_NULL;
7211 result[hdr_num].v = IST_NULL;
7212 }
7213
7214skip_headers:
William Lallemand746e6f32021-10-06 10:57:44 +02007215
7216 return result;
7217}
7218
7219
William Lallemandbd5739e2021-10-28 15:41:38 +02007220/*
7221 * For each yield, checks if there is some data in the httpclient and push them
7222 * in the lua buffer, once the httpclient finished its job, push the result on
7223 * the stack
7224 */
7225__LJMP static int hlua_httpclient_rcv_yield(lua_State *L, int status, lua_KContext ctx)
7226{
7227 struct buffer *tr;
7228 int res;
7229 struct hlua *hlua = hlua_gethlua(L);
7230 struct hlua_httpclient *hlua_hc = hlua_checkhttpclient(L, 1);
7231
7232
7233 tr = get_trash_chunk();
7234
7235 res = httpclient_res_xfer(hlua_hc->hc, tr);
7236 luaL_addlstring(&hlua_hc->b, b_orig(tr), res);
7237
7238 if (!httpclient_data(hlua_hc->hc) && httpclient_ended(hlua_hc->hc)) {
7239
7240 luaL_pushresult(&hlua_hc->b);
7241 lua_settable(L, -3);
7242
7243 lua_pushstring(L, "status");
7244 lua_pushinteger(L, hlua_hc->hc->res.status);
7245 lua_settable(L, -3);
7246
7247
7248 lua_pushstring(L, "reason");
7249 lua_pushlstring(L, hlua_hc->hc->res.reason.ptr, hlua_hc->hc->res.reason.len);
7250 lua_settable(L, -3);
7251
7252 lua_pushstring(L, "headers");
7253 hlua_httpclient_get_headers(L, hlua_hc);
7254 lua_settable(L, -3);
7255
7256 return 1;
7257 }
7258
7259 if (httpclient_data(hlua_hc->hc))
7260 task_wakeup(hlua->task, TASK_WOKEN_MSG);
7261
7262 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_httpclient_rcv_yield, TICK_ETERNITY, 0));
7263
7264 return 0;
7265}
7266
7267/*
7268 * Call this when trying to stream a body during a request
7269 */
7270__LJMP static int hlua_httpclient_snd_yield(lua_State *L, int status, lua_KContext ctx)
7271{
7272 struct hlua *hlua;
7273 struct hlua_httpclient *hlua_hc = hlua_checkhttpclient(L, 1);
7274 const char *body_str = NULL;
7275 int ret;
7276 int end = 0;
7277 size_t buf_len;
7278 size_t to_send = 0;
7279
7280 hlua = hlua_gethlua(L);
7281
7282 if (!hlua || !hlua->task)
7283 WILL_LJMP(luaL_error(L, "The 'get' function is only allowed in "
7284 "'frontend', 'backend' or 'task'"));
7285
7286 ret = lua_getfield(L, -1, "body");
7287 if (ret != LUA_TSTRING)
7288 goto rcv;
7289
7290 body_str = lua_tolstring(L, -1, &buf_len);
7291 lua_pop(L, 1);
7292
Christopher Fauletfc591292022-01-12 14:46:03 +01007293 to_send = buf_len - hlua_hc->sent;
William Lallemandbd5739e2021-10-28 15:41:38 +02007294
7295 if ((hlua_hc->sent + to_send) >= buf_len)
7296 end = 1;
7297
7298 /* the end flag is always set since we are using the whole remaining size */
7299 hlua_hc->sent += httpclient_req_xfer(hlua_hc->hc, ist2(body_str + hlua_hc->sent, to_send), end);
7300
7301 if (buf_len > hlua_hc->sent) {
7302 /* still need to process the buffer */
7303 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_httpclient_snd_yield, TICK_ETERNITY, 0));
7304 } else {
7305 goto rcv;
7306 /* we sent the whole request buffer we can recv */
7307 }
7308 return 0;
7309
7310rcv:
7311
7312 /* we return a "res" object */
7313 lua_newtable(L);
7314
William Lallemandbd5739e2021-10-28 15:41:38 +02007315 lua_pushstring(L, "body");
William Lallemandd1187eb2021-11-02 10:40:06 +01007316 luaL_buffinit(L, &hlua_hc->b);
William Lallemandbd5739e2021-10-28 15:41:38 +02007317
William Lallemand933fe392021-11-04 09:45:58 +01007318 task_wakeup(hlua->task, TASK_WOKEN_MSG);
William Lallemandbd5739e2021-10-28 15:41:38 +02007319 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_httpclient_rcv_yield, TICK_ETERNITY, 0));
7320
7321 return 1;
7322}
William Lallemand746e6f32021-10-06 10:57:44 +02007323
William Lallemand3956c4e2021-09-21 16:25:15 +02007324/*
William Lallemanddc2cc902021-10-26 11:43:26 +02007325 * Send an HTTP request and wait for a response
William Lallemand3956c4e2021-09-21 16:25:15 +02007326 */
7327
William Lallemanddc2cc902021-10-26 11:43:26 +02007328__LJMP static int hlua_httpclient_send(lua_State *L, enum http_meth_t meth)
William Lallemand3956c4e2021-09-21 16:25:15 +02007329{
7330 struct hlua_httpclient *hlua_hc;
William Lallemand746e6f32021-10-06 10:57:44 +02007331 struct http_hdr *hdrs = NULL;
7332 struct http_hdr *hdrs_i = NULL;
William Lallemand3956c4e2021-09-21 16:25:15 +02007333 struct hlua *hlua;
William Lallemand746e6f32021-10-06 10:57:44 +02007334 const char *url_str = NULL;
William Lallemanddec25c32021-10-25 19:48:37 +02007335 const char *body_str = NULL;
Christopher Faulet380ae9c2022-10-14 14:57:04 +02007336 size_t buf_len = 0;
William Lallemand746e6f32021-10-06 10:57:44 +02007337 int ret;
William Lallemand3956c4e2021-09-21 16:25:15 +02007338
7339 hlua = hlua_gethlua(L);
7340
7341 if (!hlua || !hlua->task)
7342 WILL_LJMP(luaL_error(L, "The 'get' function is only allowed in "
7343 "'frontend', 'backend' or 'task'"));
7344
William Lallemand746e6f32021-10-06 10:57:44 +02007345 if (lua_gettop(L) != 2 || lua_type(L, -1) != LUA_TTABLE)
7346 WILL_LJMP(luaL_error(L, "'get' needs a table as argument"));
7347
William Lallemand4f4f2b72022-02-17 20:00:23 +01007348 hlua_hc = hlua_checkhttpclient(L, 1);
7349
William Lallemand7177a952022-03-03 15:33:12 +01007350 lua_pushnil(L); /* first key */
7351 while (lua_next(L, 2)) {
7352 if (strcmp(lua_tostring(L, -2), "dst") == 0) {
7353 if (httpclient_set_dst(hlua_hc->hc, lua_tostring(L, -1)) < 0)
7354 WILL_LJMP(luaL_error(L, "Can't use the 'dst' argument"));
William Lallemand4f4f2b72022-02-17 20:00:23 +01007355
William Lallemand7177a952022-03-03 15:33:12 +01007356 } else if (strcmp(lua_tostring(L, -2), "url") == 0) {
7357 if (lua_type(L, -1) != LUA_TSTRING)
7358 WILL_LJMP(luaL_error(L, "invalid parameter in 'url', must be a string"));
7359 url_str = lua_tostring(L, -1);
William Lallemand3956c4e2021-09-21 16:25:15 +02007360
William Lallemand7177a952022-03-03 15:33:12 +01007361 } else if (strcmp(lua_tostring(L, -2), "timeout") == 0) {
7362 if (lua_type(L, -1) != LUA_TNUMBER)
7363 WILL_LJMP(luaL_error(L, "invalid parameter in 'timeout', must be a number"));
7364 httpclient_set_timeout(hlua_hc->hc, lua_tointeger(L, -1));
William Lallemandb4a4ef62022-02-23 14:18:16 +01007365
William Lallemand7177a952022-03-03 15:33:12 +01007366 } else if (strcmp(lua_tostring(L, -2), "headers") == 0) {
7367 if (lua_type(L, -1) != LUA_TTABLE)
7368 WILL_LJMP(luaL_error(L, "invalid parameter in 'headers', must be a table"));
7369 hdrs = hlua_httpclient_table_to_hdrs(L);
William Lallemand79416cb2021-09-24 14:51:44 +02007370
William Lallemand7177a952022-03-03 15:33:12 +01007371 } else if (strcmp(lua_tostring(L, -2), "body") == 0) {
7372 if (lua_type(L, -1) != LUA_TSTRING)
7373 WILL_LJMP(luaL_error(L, "invalid parameter in 'body', must be a string"));
7374 body_str = lua_tolstring(L, -1, &buf_len);
William Lallemandbd5739e2021-10-28 15:41:38 +02007375
William Lallemand7177a952022-03-03 15:33:12 +01007376 } else {
7377 WILL_LJMP(luaL_error(L, "'%s' invalid parameter name", lua_tostring(L, -2)));
7378 }
7379 /* removes 'value'; keeps 'key' for next iteration */
7380 lua_pop(L, 1);
7381 }
William Lallemanddec25c32021-10-25 19:48:37 +02007382
William Lallemand746e6f32021-10-06 10:57:44 +02007383 if (!url_str) {
7384 WILL_LJMP(luaL_error(L, "'get' need a 'url' argument"));
7385 return 0;
7386 }
William Lallemand3956c4e2021-09-21 16:25:15 +02007387
William Lallemand10a37362022-03-02 16:18:26 +01007388 hlua_hc->sent = 0;
William Lallemand3956c4e2021-09-21 16:25:15 +02007389
7390 hlua_hc->hc->req.url = istdup(ist(url_str));
William Lallemanddc2cc902021-10-26 11:43:26 +02007391 hlua_hc->hc->req.meth = meth;
William Lallemand3956c4e2021-09-21 16:25:15 +02007392
7393 /* update the httpclient callbacks */
William Lallemandbd5739e2021-10-28 15:41:38 +02007394 hlua_hc->hc->ops.res_stline = hlua_httpclient_cb;
7395 hlua_hc->hc->ops.res_headers = hlua_httpclient_cb;
7396 hlua_hc->hc->ops.res_payload = hlua_httpclient_cb;
William Lallemand8f170c72022-03-15 10:52:07 +01007397 hlua_hc->hc->ops.res_end = hlua_httpclient_cb;
William Lallemand3956c4e2021-09-21 16:25:15 +02007398
William Lallemandbd5739e2021-10-28 15:41:38 +02007399 /* a body is available, it will use the request callback */
Christopher Faulet380ae9c2022-10-14 14:57:04 +02007400 if (body_str && buf_len) {
William Lallemandbd5739e2021-10-28 15:41:38 +02007401 hlua_hc->hc->ops.req_payload = hlua_httpclient_cb;
7402 }
William Lallemand3956c4e2021-09-21 16:25:15 +02007403
William Lallemandbd5739e2021-10-28 15:41:38 +02007404 ret = httpclient_req_gen(hlua_hc->hc, hlua_hc->hc->req.url, meth, hdrs, IST_NULL);
William Lallemand3956c4e2021-09-21 16:25:15 +02007405
William Lallemand746e6f32021-10-06 10:57:44 +02007406 /* free the temporary headers array */
7407 hdrs_i = hdrs;
7408 while (hdrs_i && isttest(hdrs_i->n)) {
7409 istfree(&hdrs_i->n);
7410 istfree(&hdrs_i->v);
7411 hdrs_i++;
7412 }
7413 ha_free(&hdrs);
7414
7415
William Lallemand6137a9e2021-10-26 15:01:53 +02007416 if (ret != ERR_NONE) {
7417 WILL_LJMP(luaL_error(L, "Can't generate the HTTP request"));
7418 return 0;
7419 }
7420
William Lallemandc2d3db42022-04-26 11:46:13 +02007421 if (!httpclient_start(hlua_hc->hc))
7422 WILL_LJMP(luaL_error(L, "couldn't start the httpclient"));
William Lallemand6137a9e2021-10-26 15:01:53 +02007423
William Lallemandbd5739e2021-10-28 15:41:38 +02007424 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_httpclient_snd_yield, TICK_ETERNITY, 0));
William Lallemand3956c4e2021-09-21 16:25:15 +02007425
William Lallemand3956c4e2021-09-21 16:25:15 +02007426 return 0;
7427}
7428
7429/*
William Lallemanddc2cc902021-10-26 11:43:26 +02007430 * Sends an HTTP HEAD request and wait for a response
7431 *
7432 * httpclient:head(url, headers, payload)
7433 */
7434__LJMP static int hlua_httpclient_head(lua_State *L)
7435{
7436 return hlua_httpclient_send(L, HTTP_METH_HEAD);
7437}
7438
7439/*
7440 * Send an HTTP GET request and wait for a response
7441 *
7442 * httpclient:get(url, headers, payload)
7443 */
7444__LJMP static int hlua_httpclient_get(lua_State *L)
7445{
7446 return hlua_httpclient_send(L, HTTP_METH_GET);
7447
7448}
7449
7450/*
7451 * Sends an HTTP PUT request and wait for a response
7452 *
7453 * httpclient:put(url, headers, payload)
7454 */
7455__LJMP static int hlua_httpclient_put(lua_State *L)
7456{
7457 return hlua_httpclient_send(L, HTTP_METH_PUT);
7458}
7459
7460/*
7461 * Send an HTTP POST request and wait for a response
7462 *
7463 * httpclient:post(url, headers, payload)
7464 */
7465__LJMP static int hlua_httpclient_post(lua_State *L)
7466{
7467 return hlua_httpclient_send(L, HTTP_METH_POST);
7468}
7469
7470
7471/*
7472 * Sends an HTTP DELETE request and wait for a response
7473 *
7474 * httpclient:delete(url, headers, payload)
7475 */
7476__LJMP static int hlua_httpclient_delete(lua_State *L)
7477{
7478 return hlua_httpclient_send(L, HTTP_METH_DELETE);
7479}
7480
7481/*
William Lallemand3956c4e2021-09-21 16:25:15 +02007482 *
7483 *
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007484 * Class TXN
7485 *
7486 *
7487 */
7488
7489/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02007490 * a class stream, otherwise it throws an error.
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007491 */
7492__LJMP static struct hlua_txn *hlua_checktxn(lua_State *L, int ud)
7493{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02007494 return MAY_LJMP(hlua_checkudata(L, ud, class_txn_ref));
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007495}
7496
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007497__LJMP static int hlua_set_var(lua_State *L)
7498{
7499 struct hlua_txn *htxn;
7500 const char *name;
7501 size_t len;
7502 struct sample smp;
7503
Tim Duesterhus4e172c92020-05-19 13:49:42 +02007504 if (lua_gettop(L) < 3 || lua_gettop(L) > 4)
7505 WILL_LJMP(luaL_error(L, "'set_var' needs between 3 and 4 arguments"));
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007506
7507 /* It is useles to retrieve the stream, but this function
7508 * runs only in a stream context.
7509 */
7510 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7511 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
7512
7513 /* Converts the third argument in a sample. */
Amaury Denoyellebc0af6a2020-10-29 17:21:20 +01007514 memset(&smp, 0, sizeof(smp));
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007515 hlua_lua2smp(L, 3, &smp);
7516
7517 /* Store the sample in a variable. */
Willy Tarreau7560dd42016-03-10 16:28:58 +01007518 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
Tim Duesterhus4e172c92020-05-19 13:49:42 +02007519
7520 if (lua_gettop(L) == 4 && lua_toboolean(L, 4))
7521 lua_pushboolean(L, vars_set_by_name_ifexist(name, len, &smp) != 0);
7522 else
7523 lua_pushboolean(L, vars_set_by_name(name, len, &smp) != 0);
7524
Tim Duesterhus84ebc132020-05-19 13:49:41 +02007525 return 1;
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007526}
7527
Christopher Faulet85d79c92016-11-09 16:54:56 +01007528__LJMP static int hlua_unset_var(lua_State *L)
7529{
7530 struct hlua_txn *htxn;
7531 const char *name;
7532 size_t len;
7533 struct sample smp;
7534
7535 MAY_LJMP(check_args(L, 2, "unset_var"));
7536
7537 /* It is useles to retrieve the stream, but this function
7538 * runs only in a stream context.
7539 */
7540 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7541 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
7542
7543 /* Unset the variable. */
7544 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
Tim Duesterhus84ebc132020-05-19 13:49:41 +02007545 lua_pushboolean(L, vars_unset_by_name_ifexist(name, len, &smp) != 0);
7546 return 1;
Christopher Faulet85d79c92016-11-09 16:54:56 +01007547}
7548
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007549__LJMP static int hlua_get_var(lua_State *L)
7550{
7551 struct hlua_txn *htxn;
7552 const char *name;
7553 size_t len;
7554 struct sample smp;
7555
7556 MAY_LJMP(check_args(L, 2, "get_var"));
7557
7558 /* It is useles to retrieve the stream, but this function
7559 * runs only in a stream context.
7560 */
7561 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7562 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
7563
Willy Tarreau7560dd42016-03-10 16:28:58 +01007564 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
Willy Tarreaue352b9d2021-09-03 11:52:38 +02007565 if (!vars_get_by_name(name, len, &smp, NULL)) {
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007566 lua_pushnil(L);
7567 return 1;
7568 }
7569
7570 return hlua_smp2lua(L, &smp);
7571}
7572
Willy Tarreau59551662015-03-10 14:23:13 +01007573__LJMP static int hlua_set_priv(lua_State *L)
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007574{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007575 struct hlua *hlua;
7576
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007577 MAY_LJMP(check_args(L, 2, "set_priv"));
7578
Willy Tarreau87b09662015-04-03 00:22:06 +02007579 /* It is useles to retrieve the stream, but this function
7580 * runs only in a stream context.
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007581 */
7582 MAY_LJMP(hlua_checktxn(L, 1));
Thierry Fournier4234dbd2020-11-28 13:18:23 +01007583
7584 /* Get hlua struct, or NULL if we execute from main lua state */
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007585 hlua = hlua_gethlua(L);
Thierry Fournier4234dbd2020-11-28 13:18:23 +01007586 if (!hlua)
7587 return 0;
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007588
7589 /* Remove previous value. */
Thierry FOURNIERe068b602017-04-26 13:27:05 +02007590 luaL_unref(L, LUA_REGISTRYINDEX, hlua->Mref);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007591
7592 /* Get and store new value. */
7593 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
7594 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
7595
7596 return 0;
7597}
7598
Willy Tarreau59551662015-03-10 14:23:13 +01007599__LJMP static int hlua_get_priv(lua_State *L)
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007600{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007601 struct hlua *hlua;
7602
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007603 MAY_LJMP(check_args(L, 1, "get_priv"));
7604
Willy Tarreau87b09662015-04-03 00:22:06 +02007605 /* It is useles to retrieve the stream, but this function
7606 * runs only in a stream context.
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007607 */
7608 MAY_LJMP(hlua_checktxn(L, 1));
Thierry Fournier4234dbd2020-11-28 13:18:23 +01007609
7610 /* Get hlua struct, or NULL if we execute from main lua state */
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007611 hlua = hlua_gethlua(L);
Thierry Fournier4234dbd2020-11-28 13:18:23 +01007612 if (!hlua) {
7613 lua_pushnil(L);
7614 return 1;
7615 }
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007616
7617 /* Push configuration index in the stack. */
7618 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
7619
7620 return 1;
7621}
7622
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007623/* Create stack entry containing a class TXN. This function
7624 * return 0 if the stack does not contains free slots,
7625 * otherwise it returns 1.
7626 */
Thierry FOURNIERab00df62016-07-14 11:42:37 +02007627static int hlua_txn_new(lua_State *L, struct stream *s, struct proxy *p, int dir, int flags)
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007628{
Willy Tarreaude491382015-04-06 11:04:28 +02007629 struct hlua_txn *htxn;
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007630
7631 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01007632 if (!lua_checkstack(L, 3))
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007633 return 0;
7634
7635 /* NOTE: The allocation never fails. The failure
7636 * throw an error, and the function never returns.
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08007637 * if the throw is not available, the process is aborted.
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007638 */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01007639 /* Create the object: obj[0] = userdata. */
7640 lua_newtable(L);
Willy Tarreaude491382015-04-06 11:04:28 +02007641 htxn = lua_newuserdata(L, sizeof(*htxn));
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01007642 lua_rawseti(L, -2, 0);
7643
Willy Tarreaude491382015-04-06 11:04:28 +02007644 htxn->s = s;
7645 htxn->p = p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01007646 htxn->dir = dir;
Thierry FOURNIERab00df62016-07-14 11:42:37 +02007647 htxn->flags = flags;
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007648
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01007649 /* Create the "f" field that contains a list of fetches. */
7650 lua_pushstring(L, "f");
Thierry FOURNIERca988662015-12-20 18:43:03 +01007651 if (!hlua_fetches_new(L, htxn, HLUA_F_MAY_USE_HTTP))
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01007652 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007653 lua_rawset(L, -3);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01007654
7655 /* Create the "sf" field that contains a list of stringsafe fetches. */
7656 lua_pushstring(L, "sf");
Thierry FOURNIERca988662015-12-20 18:43:03 +01007657 if (!hlua_fetches_new(L, htxn, HLUA_F_MAY_USE_HTTP | HLUA_F_AS_STRING))
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01007658 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007659 lua_rawset(L, -3);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01007660
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007661 /* Create the "c" field that contains a list of converters. */
7662 lua_pushstring(L, "c");
Willy Tarreaude491382015-04-06 11:04:28 +02007663 if (!hlua_converters_new(L, htxn, 0))
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01007664 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007665 lua_rawset(L, -3);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01007666
7667 /* Create the "sc" field that contains a list of stringsafe converters. */
7668 lua_pushstring(L, "sc");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01007669 if (!hlua_converters_new(L, htxn, HLUA_F_AS_STRING))
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007670 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007671 lua_rawset(L, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007672
Thierry FOURNIER397826a2015-03-11 19:39:09 +01007673 /* Create the "req" field that contains the request channel object. */
7674 lua_pushstring(L, "req");
Willy Tarreau2a71af42015-03-10 13:51:50 +01007675 if (!hlua_channel_new(L, &s->req))
Thierry FOURNIER397826a2015-03-11 19:39:09 +01007676 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007677 lua_rawset(L, -3);
Thierry FOURNIER397826a2015-03-11 19:39:09 +01007678
7679 /* Create the "res" field that contains the response channel object. */
7680 lua_pushstring(L, "res");
Willy Tarreau2a71af42015-03-10 13:51:50 +01007681 if (!hlua_channel_new(L, &s->res))
Thierry FOURNIER397826a2015-03-11 19:39:09 +01007682 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007683 lua_rawset(L, -3);
Thierry FOURNIER397826a2015-03-11 19:39:09 +01007684
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007685 /* Creates the HTTP object is the current proxy allows http. */
7686 lua_pushstring(L, "http");
Christopher Faulet1bb6afa2021-03-08 17:57:53 +01007687 if (IS_HTX_STRM(s)) {
Willy Tarreaude491382015-04-06 11:04:28 +02007688 if (!hlua_http_new(L, htxn))
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007689 return 0;
7690 }
7691 else
7692 lua_pushnil(L);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007693 lua_rawset(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007694
Christopher Faulet78c35472020-02-26 17:14:08 +01007695 if ((htxn->flags & HLUA_TXN_CTX_MASK) == HLUA_TXN_FLT_CTX) {
7696 /* HTTPMessage object are created when a lua TXN is created from
7697 * a filter context only
7698 */
7699
7700 /* Creates the HTTP-Request object is the current proxy allows http. */
7701 lua_pushstring(L, "http_req");
7702 if (p->mode == PR_MODE_HTTP) {
7703 if (!hlua_http_msg_new(L, &s->txn->req))
7704 return 0;
7705 }
7706 else
7707 lua_pushnil(L);
7708 lua_rawset(L, -3);
7709
7710 /* Creates the HTTP-Response object is the current proxy allows http. */
7711 lua_pushstring(L, "http_res");
7712 if (p->mode == PR_MODE_HTTP) {
7713 if (!hlua_http_msg_new(L, &s->txn->rsp))
7714 return 0;
7715 }
7716 else
7717 lua_pushnil(L);
7718 lua_rawset(L, -3);
7719 }
7720
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007721 /* Pop a class sesison metatable and affect it to the userdata. */
7722 lua_rawgeti(L, LUA_REGISTRYINDEX, class_txn_ref);
7723 lua_setmetatable(L, -2);
7724
7725 return 1;
7726}
7727
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01007728__LJMP static int hlua_txn_deflog(lua_State *L)
7729{
7730 const char *msg;
7731 struct hlua_txn *htxn;
7732
7733 MAY_LJMP(check_args(L, 2, "deflog"));
7734 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7735 msg = MAY_LJMP(luaL_checkstring(L, 2));
7736
7737 hlua_sendlog(htxn->s->be, htxn->s->logs.level, msg);
7738 return 0;
7739}
7740
7741__LJMP static int hlua_txn_log(lua_State *L)
7742{
7743 int level;
7744 const char *msg;
7745 struct hlua_txn *htxn;
7746
7747 MAY_LJMP(check_args(L, 3, "log"));
7748 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7749 level = MAY_LJMP(luaL_checkinteger(L, 2));
7750 msg = MAY_LJMP(luaL_checkstring(L, 3));
7751
7752 if (level < 0 || level >= NB_LOG_LEVELS)
7753 WILL_LJMP(luaL_argerror(L, 1, "Invalid loglevel."));
7754
7755 hlua_sendlog(htxn->s->be, level, msg);
7756 return 0;
7757}
7758
7759__LJMP static int hlua_txn_log_debug(lua_State *L)
7760{
7761 const char *msg;
7762 struct hlua_txn *htxn;
7763
7764 MAY_LJMP(check_args(L, 2, "Debug"));
7765 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7766 msg = MAY_LJMP(luaL_checkstring(L, 2));
7767 hlua_sendlog(htxn->s->be, LOG_DEBUG, msg);
7768 return 0;
7769}
7770
7771__LJMP static int hlua_txn_log_info(lua_State *L)
7772{
7773 const char *msg;
7774 struct hlua_txn *htxn;
7775
7776 MAY_LJMP(check_args(L, 2, "Info"));
7777 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7778 msg = MAY_LJMP(luaL_checkstring(L, 2));
7779 hlua_sendlog(htxn->s->be, LOG_INFO, msg);
7780 return 0;
7781}
7782
7783__LJMP static int hlua_txn_log_warning(lua_State *L)
7784{
7785 const char *msg;
7786 struct hlua_txn *htxn;
7787
7788 MAY_LJMP(check_args(L, 2, "Warning"));
7789 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7790 msg = MAY_LJMP(luaL_checkstring(L, 2));
7791 hlua_sendlog(htxn->s->be, LOG_WARNING, msg);
7792 return 0;
7793}
7794
7795__LJMP static int hlua_txn_log_alert(lua_State *L)
7796{
7797 const char *msg;
7798 struct hlua_txn *htxn;
7799
7800 MAY_LJMP(check_args(L, 2, "Alert"));
7801 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7802 msg = MAY_LJMP(luaL_checkstring(L, 2));
7803 hlua_sendlog(htxn->s->be, LOG_ALERT, msg);
7804 return 0;
7805}
7806
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01007807__LJMP static int hlua_txn_set_loglevel(lua_State *L)
7808{
7809 struct hlua_txn *htxn;
7810 int ll;
7811
7812 MAY_LJMP(check_args(L, 2, "set_loglevel"));
7813 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7814 ll = MAY_LJMP(luaL_checkinteger(L, 2));
7815
7816 if (ll < 0 || ll > 7)
7817 WILL_LJMP(luaL_argerror(L, 2, "Bad log level. It must be between 0 and 7"));
7818
7819 htxn->s->logs.level = ll;
7820 return 0;
7821}
7822
7823__LJMP static int hlua_txn_set_tos(lua_State *L)
7824{
7825 struct hlua_txn *htxn;
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01007826 int tos;
7827
7828 MAY_LJMP(check_args(L, 2, "set_tos"));
7829 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7830 tos = MAY_LJMP(luaL_checkinteger(L, 2));
7831
Willy Tarreau1a18b542018-12-11 16:37:42 +01007832 conn_set_tos(objt_conn(htxn->s->sess->origin), tos);
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01007833 return 0;
7834}
7835
7836__LJMP static int hlua_txn_set_mark(lua_State *L)
7837{
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01007838 struct hlua_txn *htxn;
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01007839 int mark;
7840
7841 MAY_LJMP(check_args(L, 2, "set_mark"));
7842 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7843 mark = MAY_LJMP(luaL_checkinteger(L, 2));
7844
Lukas Tribus579e3e32019-08-11 18:03:45 +02007845 conn_set_mark(objt_conn(htxn->s->sess->origin), mark);
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01007846 return 0;
7847}
7848
Patrick Hemmer268a7072018-05-11 12:52:31 -04007849__LJMP static int hlua_txn_set_priority_class(lua_State *L)
7850{
7851 struct hlua_txn *htxn;
7852
7853 MAY_LJMP(check_args(L, 2, "set_priority_class"));
7854 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7855 htxn->s->priority_class = queue_limit_class(MAY_LJMP(luaL_checkinteger(L, 2)));
7856 return 0;
7857}
7858
7859__LJMP static int hlua_txn_set_priority_offset(lua_State *L)
7860{
7861 struct hlua_txn *htxn;
7862
7863 MAY_LJMP(check_args(L, 2, "set_priority_offset"));
7864 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7865 htxn->s->priority_offset = queue_limit_offset(MAY_LJMP(luaL_checkinteger(L, 2)));
7866 return 0;
7867}
7868
Christopher Faulet700d9e82020-01-31 12:21:52 +01007869/* Forward the Reply object to the client. This function converts the reply in
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05007870 * HTX an push it to into the response channel. It is response to forward the
Christopher Faulet700d9e82020-01-31 12:21:52 +01007871 * message and terminate the transaction. It returns 1 on success and 0 on
7872 * error. The Reply must be on top of the stack.
7873 */
7874__LJMP static int hlua_txn_forward_reply(lua_State *L, struct stream *s)
7875{
7876 struct htx *htx;
7877 struct htx_sl *sl;
7878 struct h1m h1m;
7879 const char *status, *reason, *body;
7880 size_t status_len, reason_len, body_len;
7881 int ret, code, flags;
7882
7883 code = 200;
7884 status = "200";
7885 status_len = 3;
7886 ret = lua_getfield(L, -1, "status");
7887 if (ret == LUA_TNUMBER) {
7888 code = lua_tointeger(L, -1);
7889 status = lua_tolstring(L, -1, &status_len);
7890 }
7891 lua_pop(L, 1);
7892
7893 reason = http_get_reason(code);
7894 reason_len = strlen(reason);
7895 ret = lua_getfield(L, -1, "reason");
7896 if (ret == LUA_TSTRING)
7897 reason = lua_tolstring(L, -1, &reason_len);
7898 lua_pop(L, 1);
7899
7900 body = NULL;
7901 body_len = 0;
7902 ret = lua_getfield(L, -1, "body");
7903 if (ret == LUA_TSTRING)
7904 body = lua_tolstring(L, -1, &body_len);
7905 lua_pop(L, 1);
7906
7907 /* Prepare the response before inserting the headers */
7908 h1m_init_res(&h1m);
7909 htx = htx_from_buf(&s->res.buf);
7910 channel_htx_truncate(&s->res, htx);
7911 if (s->txn->req.flags & HTTP_MSGF_VER_11) {
7912 flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11);
7913 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.1"),
7914 ist2(status, status_len), ist2(reason, reason_len));
7915 }
7916 else {
7917 flags = HTX_SL_F_IS_RESP;
7918 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.0"),
7919 ist2(status, status_len), ist2(reason, reason_len));
7920 }
7921 if (!sl)
7922 goto fail;
7923 sl->info.res.status = code;
7924
7925 /* Push in the stack the "headers" entry. */
7926 ret = lua_getfield(L, -1, "headers");
7927 if (ret != LUA_TTABLE)
7928 goto skip_headers;
7929
7930 lua_pushnil(L);
7931 while (lua_next(L, -2) != 0) {
7932 struct ist name, value;
7933 const char *n, *v;
7934 size_t nlen, vlen;
7935
7936 if (!lua_isstring(L, -2) || !lua_istable(L, -1)) {
7937 /* Skip element if the key is not a string or if the value is not a table */
7938 goto next_hdr;
7939 }
7940
7941 n = lua_tolstring(L, -2, &nlen);
7942 name = ist2(n, nlen);
7943 if (isteqi(name, ist("content-length"))) {
7944 /* Always skip content-length header. It will be added
7945 * later with the correct len
7946 */
7947 goto next_hdr;
7948 }
7949
7950 /* Loop on header's values */
7951 lua_pushnil(L);
7952 while (lua_next(L, -2)) {
7953 if (!lua_isstring(L, -1)) {
7954 /* Skip the value if it is not a string */
7955 goto next_value;
7956 }
7957
7958 v = lua_tolstring(L, -1, &vlen);
7959 value = ist2(v, vlen);
7960
7961 if (isteqi(name, ist("transfer-encoding")))
7962 h1_parse_xfer_enc_header(&h1m, value);
7963 if (!htx_add_header(htx, ist2(n, nlen), ist2(v, vlen)))
7964 goto fail;
7965
7966 next_value:
7967 lua_pop(L, 1);
7968 }
7969
7970 next_hdr:
7971 lua_pop(L, 1);
7972 }
7973 skip_headers:
7974 lua_pop(L, 1);
7975
7976 /* Update h1m flags: CLEN is set if CHNK is not present */
7977 if (!(h1m.flags & H1_MF_CHNK)) {
7978 const char *clen = ultoa(body_len);
7979
7980 h1m.flags |= H1_MF_CLEN;
7981 if (!htx_add_header(htx, ist("content-length"), ist(clen)))
7982 goto fail;
7983 }
7984 if (h1m.flags & (H1_MF_CLEN|H1_MF_CHNK))
7985 h1m.flags |= H1_MF_XFER_LEN;
7986
7987 /* Update HTX start-line flags */
7988 if (h1m.flags & H1_MF_XFER_ENC)
7989 flags |= HTX_SL_F_XFER_ENC;
7990 if (h1m.flags & H1_MF_XFER_LEN) {
7991 flags |= HTX_SL_F_XFER_LEN;
7992 if (h1m.flags & H1_MF_CHNK)
7993 flags |= HTX_SL_F_CHNK;
7994 else if (h1m.flags & H1_MF_CLEN)
7995 flags |= HTX_SL_F_CLEN;
7996 if (h1m.body_len == 0)
7997 flags |= HTX_SL_F_BODYLESS;
7998 }
7999 sl->flags |= flags;
8000
8001
8002 if (!htx_add_endof(htx, HTX_BLK_EOH) ||
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01008003 (body_len && !htx_add_data_atonce(htx, ist2(body, body_len))))
Christopher Faulet700d9e82020-01-31 12:21:52 +01008004 goto fail;
8005
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01008006 htx->flags |= HTX_FL_EOM;
8007
Christopher Faulet700d9e82020-01-31 12:21:52 +01008008 /* Now, forward the response and terminate the transaction */
8009 s->txn->status = code;
8010 htx_to_buf(htx, &s->res.buf);
8011 if (!http_forward_proxy_resp(s, 1))
8012 goto fail;
8013
8014 return 1;
8015
8016 fail:
8017 channel_htx_truncate(&s->res, htx);
8018 return 0;
8019}
8020
8021/* Terminate a transaction if called from a lua action. For TCP streams,
8022 * processing is just aborted. Nothing is returned to the client and all
8023 * arguments are ignored. For HTTP streams, if a reply is passed as argument, it
8024 * is forwarded to the client before terminating the transaction. On success,
8025 * the function exits with ACT_RET_DONE code. If an error occurred, it exits
8026 * with ACT_RET_ERR code. If this function is not called from a lua action, it
8027 * just exits without any processing.
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01008028 */
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02008029__LJMP static int hlua_txn_done(lua_State *L)
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01008030{
Willy Tarreaub2ccb562015-04-06 11:11:15 +02008031 struct hlua_txn *htxn;
Christopher Faulet700d9e82020-01-31 12:21:52 +01008032 struct stream *s;
8033 int finst;
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01008034
Willy Tarreaub2ccb562015-04-06 11:11:15 +02008035 htxn = MAY_LJMP(hlua_checktxn(L, 1));
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01008036
Christopher Faulet700d9e82020-01-31 12:21:52 +01008037 /* If the flags NOTERM is set, we cannot terminate the session, so we
8038 * just end the execution of the current lua code. */
8039 if (htxn->flags & HLUA_TXN_NOTERM)
Thierry FOURNIERab00df62016-07-14 11:42:37 +02008040 WILL_LJMP(hlua_done(L));
Thierry FOURNIERab00df62016-07-14 11:42:37 +02008041
Christopher Faulet700d9e82020-01-31 12:21:52 +01008042 s = htxn->s;
Christopher Fauletd8f0e072020-02-25 09:45:51 +01008043 if (!IS_HTX_STRM(htxn->s)) {
Christopher Faulet700d9e82020-01-31 12:21:52 +01008044 struct channel *req = &s->req;
8045 struct channel *res = &s->res;
Willy Tarreau81389672015-03-10 12:03:52 +01008046
Christopher Faulet700d9e82020-01-31 12:21:52 +01008047 channel_auto_read(req);
8048 channel_abort(req);
8049 channel_auto_close(req);
8050 channel_erase(req);
8051
8052 res->wex = tick_add_ifset(now_ms, res->wto);
8053 channel_auto_read(res);
8054 channel_auto_close(res);
8055 channel_shutr_now(res);
8056
8057 finst = ((htxn->dir == SMP_OPT_DIR_REQ) ? SF_FINST_R : SF_FINST_D);
8058 goto done;
Christopher Fauletfe6a71b2019-07-26 16:40:24 +02008059 }
Thierry FOURNIER10ec2142015-08-24 17:23:45 +02008060
Christopher Faulet700d9e82020-01-31 12:21:52 +01008061 if (lua_gettop(L) == 1 || !lua_istable(L, 2)) {
8062 /* No reply or invalid reply */
8063 s->txn->status = 0;
8064 http_reply_and_close(s, 0, NULL);
8065 }
8066 else {
8067 /* Remove extra args to have the reply on top of the stack */
8068 if (lua_gettop(L) > 2)
8069 lua_pop(L, lua_gettop(L) - 2);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01008070
Christopher Faulet700d9e82020-01-31 12:21:52 +01008071 if (!hlua_txn_forward_reply(L, s)) {
8072 if (!(s->flags & SF_ERR_MASK))
8073 s->flags |= SF_ERR_PRXCOND;
8074 lua_pushinteger(L, ACT_RET_ERR);
8075 WILL_LJMP(hlua_done(L));
8076 return 0; /* Never reached */
8077 }
Christopher Faulet4d0e2632019-07-16 10:52:40 +02008078 }
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02008079
Christopher Faulet700d9e82020-01-31 12:21:52 +01008080 finst = ((htxn->dir == SMP_OPT_DIR_REQ) ? SF_FINST_R : SF_FINST_H);
8081 if (htxn->dir == SMP_OPT_DIR_REQ) {
8082 /* let's log the request time */
8083 s->logs.tv_request = now;
8084 if (s->sess->fe == s->be) /* report it if the request was intercepted by the frontend */
Willy Tarreau4781b152021-04-06 13:53:36 +02008085 _HA_ATOMIC_INC(&s->sess->fe->fe_counters.intercepted_req);
Christopher Faulet700d9e82020-01-31 12:21:52 +01008086 }
Christopher Fauletfe6a71b2019-07-26 16:40:24 +02008087
Christopher Faulet700d9e82020-01-31 12:21:52 +01008088 done:
8089 if (!(s->flags & SF_ERR_MASK))
8090 s->flags |= SF_ERR_LOCAL;
8091 if (!(s->flags & SF_FINST_MASK))
8092 s->flags |= finst;
Christopher Fauletfe6a71b2019-07-26 16:40:24 +02008093
Christopher Faulete48d1dc2021-08-13 14:11:17 +02008094 if ((htxn->flags & HLUA_TXN_CTX_MASK) == HLUA_TXN_FLT_CTX)
8095 lua_pushinteger(L, -1);
8096 else
8097 lua_pushinteger(L, ACT_RET_ABRT);
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02008098 WILL_LJMP(hlua_done(L));
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01008099 return 0;
8100}
8101
Christopher Faulet700d9e82020-01-31 12:21:52 +01008102/*
8103 *
8104 *
8105 * Class REPLY
8106 *
8107 *
8108 */
8109
8110/* Pushes the TXN reply onto the top of the stack. If the stask does not have a
8111 * free slots, the function fails and returns 0;
8112 */
8113static int hlua_txn_reply_new(lua_State *L)
8114{
8115 struct hlua_txn *htxn;
8116 const char *reason, *body = NULL;
8117 int ret, status;
8118
8119 htxn = MAY_LJMP(hlua_checktxn(L, 1));
Christopher Fauletd8f0e072020-02-25 09:45:51 +01008120 if (!IS_HTX_STRM(htxn->s)) {
Christopher Faulet700d9e82020-01-31 12:21:52 +01008121 hlua_pusherror(L, "txn object is not an HTTP transaction.");
8122 WILL_LJMP(lua_error(L));
8123 }
8124
8125 /* Default value */
8126 status = 200;
8127 reason = http_get_reason(status);
8128
8129 if (lua_istable(L, 2)) {
8130 /* load status and reason from the table argument at index 2 */
8131 ret = lua_getfield(L, 2, "status");
8132 if (ret == LUA_TNIL)
8133 goto reason;
8134 else if (ret != LUA_TNUMBER) {
8135 /* invalid status: ignore the reason */
8136 goto body;
8137 }
8138 status = lua_tointeger(L, -1);
8139
8140 reason:
8141 lua_pop(L, 1); /* restore the stack: remove status */
8142 ret = lua_getfield(L, 2, "reason");
8143 if (ret == LUA_TSTRING)
8144 reason = lua_tostring(L, -1);
8145
8146 body:
8147 lua_pop(L, 1); /* restore the stack: remove invalid status or reason */
8148 ret = lua_getfield(L, 2, "body");
8149 if (ret == LUA_TSTRING)
8150 body = lua_tostring(L, -1);
8151 lua_pop(L, 1); /* restore the stack: remove body */
8152 }
8153
8154 /* Create the Reply table */
8155 lua_newtable(L);
8156
8157 /* Add status element */
8158 lua_pushstring(L, "status");
8159 lua_pushinteger(L, status);
8160 lua_settable(L, -3);
8161
8162 /* Add reason element */
8163 reason = http_get_reason(status);
8164 lua_pushstring(L, "reason");
8165 lua_pushstring(L, reason);
8166 lua_settable(L, -3);
8167
8168 /* Add body element, nil if undefined */
8169 lua_pushstring(L, "body");
8170 if (body)
8171 lua_pushstring(L, body);
8172 else
8173 lua_pushnil(L);
8174 lua_settable(L, -3);
8175
8176 /* Add headers element */
8177 lua_pushstring(L, "headers");
8178 lua_newtable(L);
8179
8180 /* stack: [ txn, <Arg:table>, <Reply:table>, "headers", <headers:table> ] */
8181 if (lua_istable(L, 2)) {
8182 /* load headers from the table argument at index 2. If it is a table, copy it. */
8183 ret = lua_getfield(L, 2, "headers");
8184 if (ret == LUA_TTABLE) {
8185 /* stack: [ ... <headers:table>, <table> ] */
8186 lua_pushnil(L);
8187 while (lua_next(L, -2) != 0) {
8188 /* stack: [ ... <headers:table>, <table>, k, v] */
8189 if (!lua_isstring(L, -1) && !lua_istable(L, -1)) {
8190 /* invalid value type, skip it */
8191 lua_pop(L, 1);
8192 continue;
8193 }
8194
8195
8196 /* Duplicate the key and swap it with the value. */
8197 lua_pushvalue(L, -2);
8198 lua_insert(L, -2);
8199 /* stack: [ ... <headers:table>, <table>, k, k, v ] */
8200
8201 lua_newtable(L);
8202 lua_insert(L, -2);
8203 /* stack: [ ... <headers:table>, <table>, k, k, <inner:table>, v ] */
8204
8205 if (lua_isstring(L, -1)) {
8206 /* push the value in the inner table */
8207 lua_rawseti(L, -2, 1);
8208 }
8209 else { /* table */
8210 lua_pushnil(L);
8211 while (lua_next(L, -2) != 0) {
8212 /* stack: [ ... <headers:table>, <table>, k, k, <inner:table>, <v:table>, k2, v2 ] */
8213 if (!lua_isstring(L, -1)) {
8214 /* invalid value type, skip it*/
8215 lua_pop(L, 1);
8216 continue;
8217 }
8218 /* push the value in the inner table */
8219 lua_rawseti(L, -4, lua_rawlen(L, -4) + 1);
8220 /* stack: [ ... <headers:table>, <table>, k, k, <inner:table>, <v:table>, k2 ] */
8221 }
8222 lua_pop(L, 1);
8223 /* stack: [ ... <headers:table>, <table>, k, k, <inner:table> ] */
8224 }
8225
8226 /* push (k,v) on the stack in the headers table:
8227 * stack: [ ... <headers:table>, <table>, k, k, v ]
8228 */
8229 lua_settable(L, -5);
8230 /* stack: [ ... <headers:table>, <table>, k ] */
8231 }
8232 }
8233 lua_pop(L, 1);
8234 }
8235 /* stack: [ txn, <Arg:table>, <Reply:table>, "headers", <headers:table> ] */
8236 lua_settable(L, -3);
8237 /* stack: [ txn, <Arg:table>, <Reply:table> ] */
8238
8239 /* Pop a class sesison metatable and affect it to the userdata. */
8240 lua_rawgeti(L, LUA_REGISTRYINDEX, class_txn_reply_ref);
8241 lua_setmetatable(L, -2);
8242 return 1;
8243}
8244
8245/* Set the reply status code, and optionally the reason. If no reason is
8246 * provided, the default one corresponding to the status code is used.
8247 */
8248__LJMP static int hlua_txn_reply_set_status(lua_State *L)
8249{
8250 int status = MAY_LJMP(luaL_checkinteger(L, 2));
8251 const char *reason = MAY_LJMP(luaL_optlstring(L, 3, NULL, NULL));
8252
8253 /* First argument (self) must be a table */
Aurelien DARRAGONd83d0452022-10-05 11:46:45 +02008254 MAY_LJMP(luaL_checktype(L, 1, LUA_TTABLE));
Christopher Faulet700d9e82020-01-31 12:21:52 +01008255
8256 if (status < 100 || status > 599) {
8257 lua_pushboolean(L, 0);
8258 return 1;
8259 }
8260 if (!reason)
8261 reason = http_get_reason(status);
8262
8263 lua_pushinteger(L, status);
8264 lua_setfield(L, 1, "status");
8265
8266 lua_pushstring(L, reason);
8267 lua_setfield(L, 1, "reason");
8268
8269 lua_pushboolean(L, 1);
8270 return 1;
8271}
8272
8273/* Add a header into the reply object. Each header name is associated to an
8274 * array of values in the "headers" table. If the header name is not found, a
8275 * new entry is created.
8276 */
8277__LJMP static int hlua_txn_reply_add_header(lua_State *L)
8278{
8279 const char *name = MAY_LJMP(luaL_checkstring(L, 2));
8280 const char *value = MAY_LJMP(luaL_checkstring(L, 3));
8281 int ret;
8282
8283 /* First argument (self) must be a table */
Aurelien DARRAGONd83d0452022-10-05 11:46:45 +02008284 MAY_LJMP(luaL_checktype(L, 1, LUA_TTABLE));
Christopher Faulet700d9e82020-01-31 12:21:52 +01008285
8286 /* Push in the stack the "headers" entry. */
8287 ret = lua_getfield(L, 1, "headers");
8288 if (ret != LUA_TTABLE) {
8289 hlua_pusherror(L, "Reply['headers'] is expected to a an array. %s found", lua_typename(L, ret));
8290 WILL_LJMP(lua_error(L));
8291 }
8292
8293 /* check if the header is already registered. If not, register it. */
8294 ret = lua_getfield(L, -1, name);
8295 if (ret == LUA_TNIL) {
8296 /* Entry not found. */
8297 lua_pop(L, 1); /* remove the nil. The "headers" table is the top of the stack. */
8298
8299 /* Insert the new header name in the array in the top of the stack.
8300 * It left the new array in the top of the stack.
8301 */
8302 lua_newtable(L);
8303 lua_pushstring(L, name);
8304 lua_pushvalue(L, -2);
8305 lua_settable(L, -4);
8306 }
8307 else if (ret != LUA_TTABLE) {
8308 hlua_pusherror(L, "Reply['headers']['%s'] is expected to be an array. %s found", name, lua_typename(L, ret));
8309 WILL_LJMP(lua_error(L));
8310 }
8311
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -07008312 /* Now the top of thestack is an array of values. We push
Christopher Faulet700d9e82020-01-31 12:21:52 +01008313 * the header value as new entry.
8314 */
8315 lua_pushstring(L, value);
8316 ret = lua_rawlen(L, -2);
8317 lua_rawseti(L, -2, ret + 1);
8318
8319 lua_pushboolean(L, 1);
8320 return 1;
8321}
8322
8323/* Remove all occurrences of a given header name. */
8324__LJMP static int hlua_txn_reply_del_header(lua_State *L)
8325{
8326 const char *name = MAY_LJMP(luaL_checkstring(L, 2));
8327 int ret;
8328
8329 /* First argument (self) must be a table */
Aurelien DARRAGONd83d0452022-10-05 11:46:45 +02008330 MAY_LJMP(luaL_checktype(L, 1, LUA_TTABLE));
Christopher Faulet700d9e82020-01-31 12:21:52 +01008331
8332 /* Push in the stack the "headers" entry. */
8333 ret = lua_getfield(L, 1, "headers");
8334 if (ret != LUA_TTABLE) {
8335 hlua_pusherror(L, "Reply['headers'] is expected to be an array. %s found", lua_typename(L, ret));
8336 WILL_LJMP(lua_error(L));
8337 }
8338
8339 lua_pushstring(L, name);
8340 lua_pushnil(L);
8341 lua_settable(L, -3);
8342
8343 lua_pushboolean(L, 1);
8344 return 1;
8345}
8346
8347/* Set the reply's body. Overwrite any existing entry. */
8348__LJMP static int hlua_txn_reply_set_body(lua_State *L)
8349{
8350 const char *payload = MAY_LJMP(luaL_checkstring(L, 2));
8351
8352 /* First argument (self) must be a table */
Aurelien DARRAGONd83d0452022-10-05 11:46:45 +02008353 MAY_LJMP(luaL_checktype(L, 1, LUA_TTABLE));
Christopher Faulet700d9e82020-01-31 12:21:52 +01008354
8355 lua_pushstring(L, payload);
8356 lua_setfield(L, 1, "body");
8357
8358 lua_pushboolean(L, 1);
8359 return 1;
8360}
8361
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01008362__LJMP static int hlua_log(lua_State *L)
8363{
8364 int level;
8365 const char *msg;
8366
8367 MAY_LJMP(check_args(L, 2, "log"));
8368 level = MAY_LJMP(luaL_checkinteger(L, 1));
8369 msg = MAY_LJMP(luaL_checkstring(L, 2));
8370
8371 if (level < 0 || level >= NB_LOG_LEVELS)
8372 WILL_LJMP(luaL_argerror(L, 1, "Invalid loglevel."));
8373
8374 hlua_sendlog(NULL, level, msg);
8375 return 0;
8376}
8377
8378__LJMP static int hlua_log_debug(lua_State *L)
8379{
8380 const char *msg;
8381
8382 MAY_LJMP(check_args(L, 1, "debug"));
8383 msg = MAY_LJMP(luaL_checkstring(L, 1));
8384 hlua_sendlog(NULL, LOG_DEBUG, msg);
8385 return 0;
8386}
8387
8388__LJMP static int hlua_log_info(lua_State *L)
8389{
8390 const char *msg;
8391
8392 MAY_LJMP(check_args(L, 1, "info"));
8393 msg = MAY_LJMP(luaL_checkstring(L, 1));
8394 hlua_sendlog(NULL, LOG_INFO, msg);
8395 return 0;
8396}
8397
8398__LJMP static int hlua_log_warning(lua_State *L)
8399{
8400 const char *msg;
8401
8402 MAY_LJMP(check_args(L, 1, "warning"));
8403 msg = MAY_LJMP(luaL_checkstring(L, 1));
8404 hlua_sendlog(NULL, LOG_WARNING, msg);
8405 return 0;
8406}
8407
8408__LJMP static int hlua_log_alert(lua_State *L)
8409{
8410 const char *msg;
8411
8412 MAY_LJMP(check_args(L, 1, "alert"));
8413 msg = MAY_LJMP(luaL_checkstring(L, 1));
8414 hlua_sendlog(NULL, LOG_ALERT, msg);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01008415 return 0;
8416}
8417
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01008418__LJMP static int hlua_sleep_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008419{
8420 int wakeup_ms = lua_tointeger(L, -1);
Willy Tarreau12c02702021-09-30 16:12:31 +02008421 if (!tick_is_expired(wakeup_ms, now_ms))
Willy Tarreau9635e032018-10-16 17:52:55 +02008422 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008423 return 0;
8424}
8425
8426__LJMP static int hlua_sleep(lua_State *L)
8427{
8428 unsigned int delay;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008429 unsigned int wakeup_ms;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008430
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008431 MAY_LJMP(check_args(L, 1, "sleep"));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008432
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01008433 delay = MAY_LJMP(luaL_checkinteger(L, 1)) * 1000;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008434 wakeup_ms = tick_add(now_ms, delay);
8435 lua_pushinteger(L, wakeup_ms);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008436
Willy Tarreau9635e032018-10-16 17:52:55 +02008437 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008438 return 0;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008439}
8440
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008441__LJMP static int hlua_msleep(lua_State *L)
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008442{
8443 unsigned int delay;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008444 unsigned int wakeup_ms;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008445
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008446 MAY_LJMP(check_args(L, 1, "msleep"));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008447
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01008448 delay = MAY_LJMP(luaL_checkinteger(L, 1));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008449 wakeup_ms = tick_add(now_ms, delay);
8450 lua_pushinteger(L, wakeup_ms);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008451
Willy Tarreau9635e032018-10-16 17:52:55 +02008452 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008453 return 0;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008454}
8455
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01008456/* This functionis an LUA binding. it permits to give back
8457 * the hand at the HAProxy scheduler. It is used when the
8458 * LUA processing consumes a lot of time.
8459 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01008460__LJMP static int hlua_yield_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008461{
8462 return 0;
8463}
8464
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01008465__LJMP static int hlua_yield(lua_State *L)
8466{
Willy Tarreau9635e032018-10-16 17:52:55 +02008467 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_yield_yield, TICK_ETERNITY, HLUA_CTRLYIELD));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008468 return 0;
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01008469}
8470
Thierry FOURNIER37196f42015-02-16 19:34:56 +01008471/* This function change the nice of the currently executed
8472 * task. It is used set low or high priority at the current
8473 * task.
8474 */
Willy Tarreau59551662015-03-10 14:23:13 +01008475__LJMP static int hlua_set_nice(lua_State *L)
Thierry FOURNIER37196f42015-02-16 19:34:56 +01008476{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01008477 struct hlua *hlua;
8478 int nice;
Thierry FOURNIER37196f42015-02-16 19:34:56 +01008479
Willy Tarreau80f5fae2015-02-27 16:38:20 +01008480 MAY_LJMP(check_args(L, 1, "set_nice"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01008481 nice = MAY_LJMP(luaL_checkinteger(L, 1));
Thierry FOURNIER37196f42015-02-16 19:34:56 +01008482
Thierry Fournier4234dbd2020-11-28 13:18:23 +01008483 /* Get hlua struct, or NULL if we execute from main lua state */
8484 hlua = hlua_gethlua(L);
8485
8486 /* If the task is not set, I'm in a start mode. */
Thierry FOURNIER37196f42015-02-16 19:34:56 +01008487 if (!hlua || !hlua->task)
8488 return 0;
8489
8490 if (nice < -1024)
8491 nice = -1024;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01008492 else if (nice > 1024)
Thierry FOURNIER37196f42015-02-16 19:34:56 +01008493 nice = 1024;
8494
8495 hlua->task->nice = nice;
8496 return 0;
8497}
8498
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08008499/* This function is used as a callback of a task. It is called by the
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008500 * HAProxy task subsystem when the task is awaked. The LUA runtime can
8501 * return an E_AGAIN signal, the emmiter of this signal must set a
8502 * signal to wake the task.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008503 *
8504 * Task wrapper are longjmp safe because the only one Lua code
8505 * executed is the safe hlua_ctx_resume();
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008506 */
Willy Tarreau144f84a2021-03-02 16:09:26 +01008507struct task *hlua_process_task(struct task *task, void *context, unsigned int state)
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008508{
Olivier Houchard9f6af332018-05-25 14:04:04 +02008509 struct hlua *hlua = context;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008510 enum hlua_exec status;
8511
Willy Tarreau6ef52f42022-06-15 14:19:48 +02008512 if (task->tid < 0)
8513 task->tid = tid;
8514
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008515 /* If it is the first call to the task, we must initialize the
8516 * execution timeouts.
8517 */
8518 if (!HLUA_IS_RUNNING(hlua))
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02008519 hlua->max_time = hlua_timeout_task;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008520
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008521 /* Execute the Lua code. */
8522 status = hlua_ctx_resume(hlua, 1);
8523
8524 switch (status) {
8525 /* finished or yield */
8526 case HLUA_E_OK:
8527 hlua_ctx_destroy(hlua);
Olivier Houchard3f795f72019-04-17 22:51:06 +02008528 task_destroy(task);
Tim Duesterhuscd235c62018-04-24 13:56:01 +02008529 task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008530 break;
8531
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01008532 case HLUA_E_AGAIN: /* co process or timeout wake me later. */
Thierry FOURNIERcb146882017-12-10 17:10:57 +01008533 notification_gc(&hlua->com);
PiBa-NLfe971b32018-05-02 22:27:14 +02008534 task->expire = hlua->wake_time;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008535 break;
8536
8537 /* finished with error. */
8538 case HLUA_E_ERRMSG:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008539 SEND_ERR(NULL, "Lua task: %s.\n", lua_tostring(hlua->T, -1));
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008540 hlua_ctx_destroy(hlua);
Olivier Houchard3f795f72019-04-17 22:51:06 +02008541 task_destroy(task);
Emeric Brun253e53e2017-10-17 18:58:40 +02008542 task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008543 break;
8544
8545 case HLUA_E_ERR:
8546 default:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008547 SEND_ERR(NULL, "Lua task: unknown error.\n");
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008548 hlua_ctx_destroy(hlua);
Olivier Houchard3f795f72019-04-17 22:51:06 +02008549 task_destroy(task);
Emeric Brun253e53e2017-10-17 18:58:40 +02008550 task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008551 break;
8552 }
Emeric Brun253e53e2017-10-17 18:58:40 +02008553 return task;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008554}
8555
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008556/* This function is an LUA binding that register LUA function to be
8557 * executed after the HAProxy configuration parsing and before the
8558 * HAProxy scheduler starts. This function expect only one LUA
8559 * argument that is a function. This function returns nothing, but
8560 * throws if an error is encountered.
8561 */
8562__LJMP static int hlua_register_init(lua_State *L)
8563{
8564 struct hlua_init_function *init;
8565 int ref;
8566
8567 MAY_LJMP(check_args(L, 1, "register_init"));
8568
8569 ref = MAY_LJMP(hlua_checkfunction(L, 1));
8570
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02008571 init = calloc(1, sizeof(*init));
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008572 if (!init)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01008573 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008574
8575 init->function_ref = ref;
Willy Tarreau2b718102021-04-21 07:32:39 +02008576 LIST_APPEND(&hlua_init_functions[hlua_state_id], &init->l);
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008577 return 0;
8578}
8579
Ilya Shipitsin6f86eaa2022-11-30 16:22:42 +05008580/* This function is an LUA binding. It permits to register a task
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008581 * executed in parallel of the main HAroxy activity. The task is
8582 * created and it is set in the HAProxy scheduler. It can be called
8583 * from the "init" section, "post init" or during the runtime.
8584 *
8585 * Lua prototype:
8586 *
8587 * <none> core.register_task(<function>)
8588 */
8589static int hlua_register_task(lua_State *L)
8590{
Christopher Faulet5294ec02021-04-12 12:24:47 +02008591 struct hlua *hlua = NULL;
8592 struct task *task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008593 int ref;
Thierry Fournier021d9862020-11-28 23:42:03 +01008594 int state_id;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008595
8596 MAY_LJMP(check_args(L, 1, "register_task"));
8597
8598 ref = MAY_LJMP(hlua_checkfunction(L, 1));
8599
Thierry Fournier75fc0292020-11-28 13:18:56 +01008600 /* Get the reference state. If the reference is NULL, L is the master
8601 * state, otherwise hlua->T is.
8602 */
8603 hlua = hlua_gethlua(L);
8604 if (hlua)
Thierry Fournier021d9862020-11-28 23:42:03 +01008605 /* we are in runtime processing */
8606 state_id = hlua->state_id;
Thierry Fournier75fc0292020-11-28 13:18:56 +01008607 else
Thierry Fournier021d9862020-11-28 23:42:03 +01008608 /* we are in initialization mode */
Thierry Fournierc7492592020-11-28 23:57:24 +01008609 state_id = hlua_state_id;
Thierry Fournier75fc0292020-11-28 13:18:56 +01008610
Willy Tarreaubafbe012017-11-24 17:34:44 +01008611 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008612 if (!hlua)
Christopher Faulet5294ec02021-04-12 12:24:47 +02008613 goto alloc_error;
Christopher Faulet1e8433f2021-03-24 15:03:01 +01008614 HLUA_INIT(hlua);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008615
Thierry Fournier59f11be2020-11-29 00:37:41 +01008616 /* We are in the common lua state, execute the task anywhere,
8617 * otherwise, inherit the current thread identifier
8618 */
8619 if (state_id == 0)
Willy Tarreaubeeabf52021-10-01 18:23:30 +02008620 task = task_new_anywhere();
Thierry Fournier59f11be2020-11-29 00:37:41 +01008621 else
Willy Tarreaubeeabf52021-10-01 18:23:30 +02008622 task = task_new_here();
Willy Tarreaue09101e2018-10-16 17:37:12 +02008623 if (!task)
Christopher Faulet5294ec02021-04-12 12:24:47 +02008624 goto alloc_error;
Willy Tarreaue09101e2018-10-16 17:37:12 +02008625
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008626 task->context = hlua;
8627 task->process = hlua_process_task;
8628
Thierry Fournier021d9862020-11-28 23:42:03 +01008629 if (!hlua_ctx_init(hlua, state_id, task, 1))
Christopher Faulet5294ec02021-04-12 12:24:47 +02008630 goto alloc_error;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008631
8632 /* Restore the function in the stack. */
8633 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ref);
8634 hlua->nargs = 0;
8635
8636 /* Schedule task. */
Willy Tarreaue3957f82021-09-30 16:17:37 +02008637 task_wakeup(task, TASK_WOKEN_INIT);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008638
8639 return 0;
Christopher Faulet5294ec02021-04-12 12:24:47 +02008640
8641 alloc_error:
8642 task_destroy(task);
8643 hlua_ctx_destroy(hlua);
8644 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
8645 return 0; /* Never reached */
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008646}
8647
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008648/* Wrapper called by HAProxy to execute an LUA converter. This wrapper
8649 * doesn't allow "yield" functions because the HAProxy engine cannot
8650 * resume converters.
8651 */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02008652static int hlua_sample_conv_wrapper(const struct arg *arg_p, struct sample *smp, void *private)
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008653{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02008654 struct hlua_function *fcn = private;
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02008655 struct stream *stream = smp->strm;
Thierry Fournierfd107a22016-02-19 19:57:23 +01008656 const char *error;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008657
Willy Tarreaube508f12016-03-10 11:47:01 +01008658 if (!stream)
8659 return 0;
8660
Willy Tarreau87b09662015-04-03 00:22:06 +02008661 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01008662 * Lua context can be not initialized. This behavior
8663 * permits to save performances because a systematic
8664 * Lua initialization cause 5% performances loss.
8665 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008666 if (!stream->hlua) {
Christopher Faulet1e8433f2021-03-24 15:03:01 +01008667 struct hlua *hlua;
8668
8669 hlua = pool_alloc(pool_head_hlua);
8670 if (!hlua) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008671 SEND_ERR(stream->be, "Lua converter '%s': can't initialize Lua context.\n", fcn->name);
8672 return 0;
8673 }
Christopher Faulet1e8433f2021-03-24 15:03:01 +01008674 HLUA_INIT(hlua);
8675 stream->hlua = hlua;
Thierry Fournierc7492592020-11-28 23:57:24 +01008676 if (!hlua_ctx_init(stream->hlua, fcn_ref_to_stack_id(fcn), stream->task, 0)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008677 SEND_ERR(stream->be, "Lua converter '%s': can't initialize Lua context.\n", fcn->name);
8678 return 0;
8679 }
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01008680 }
8681
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008682 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008683 if (!HLUA_IS_RUNNING(stream->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008684
8685 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008686 if (!SET_SAFE_LJMP(stream->hlua)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008687 if (lua_type(stream->hlua->T, -1) == LUA_TSTRING)
8688 error = lua_tostring(stream->hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +01008689 else
8690 error = "critical error";
8691 SEND_ERR(stream->be, "Lua converter '%s': %s.\n", fcn->name, error);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008692 return 0;
8693 }
8694
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008695 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008696 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008697 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008698 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008699 return 0;
8700 }
8701
8702 /* Restore the function in the stack. */
Thierry Fournierc7492592020-11-28 23:57:24 +01008703 lua_rawgeti(stream->hlua->T, LUA_REGISTRYINDEX, fcn->function_ref[stream->hlua->state_id]);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008704
8705 /* convert input sample and pust-it in the stack. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008706 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008707 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008708 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008709 return 0;
8710 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008711 hlua_smp2lua(stream->hlua->T, smp);
8712 stream->hlua->nargs = 1;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008713
8714 /* push keywords in the stack. */
8715 if (arg_p) {
8716 for (; arg_p->type != ARGT_STOP; arg_p++) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008717 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008718 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008719 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008720 return 0;
8721 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008722 hlua_arg2lua(stream->hlua->T, arg_p);
8723 stream->hlua->nargs++;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008724 }
8725 }
8726
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008727 /* We must initialize the execution timeouts. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008728 stream->hlua->max_time = hlua_timeout_session;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008729
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008730 /* At this point the execution is safe. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008731 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008732 }
8733
8734 /* Execute the function. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008735 switch (hlua_ctx_resume(stream->hlua, 0)) {
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008736 /* finished. */
8737 case HLUA_E_OK:
Thierry FOURNIERfd80df12017-05-12 16:32:20 +02008738 /* If the stack is empty, the function fails. */
8739 if (lua_gettop(stream->hlua->T) <= 0)
8740 return 0;
8741
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008742 /* Convert the returned value in sample. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008743 hlua_lua2smp(stream->hlua->T, -1, smp);
8744 lua_pop(stream->hlua->T, 1);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008745 return 1;
8746
8747 /* yield. */
8748 case HLUA_E_AGAIN:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008749 SEND_ERR(stream->be, "Lua converter '%s': cannot use yielded functions.\n", fcn->name);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008750 return 0;
8751
8752 /* finished with error. */
8753 case HLUA_E_ERRMSG:
8754 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008755 SEND_ERR(stream->be, "Lua converter '%s': %s.\n",
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008756 fcn->name, lua_tostring(stream->hlua->T, -1));
8757 lua_pop(stream->hlua->T, 1);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008758 return 0;
8759
Thierry Fournierd5b073c2018-05-21 19:42:47 +02008760 case HLUA_E_ETMOUT:
8761 SEND_ERR(stream->be, "Lua converter '%s': execution timeout.\n", fcn->name);
8762 return 0;
8763
8764 case HLUA_E_NOMEM:
8765 SEND_ERR(stream->be, "Lua converter '%s': out of memory error.\n", fcn->name);
8766 return 0;
8767
8768 case HLUA_E_YIELD:
8769 SEND_ERR(stream->be, "Lua converter '%s': yield functions like core.tcp() or core.sleep() are not allowed.\n", fcn->name);
8770 return 0;
8771
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008772 case HLUA_E_ERR:
8773 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008774 SEND_ERR(stream->be, "Lua converter '%s' returns an unknown error.\n", fcn->name);
Willy Tarreau14de3952022-11-14 07:08:28 +01008775 __fallthrough;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008776
8777 default:
8778 return 0;
8779 }
8780}
8781
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008782/* Wrapper called by HAProxy to execute a sample-fetch. this wrapper
8783 * doesn't allow "yield" functions because the HAProxy engine cannot
Willy Tarreaube508f12016-03-10 11:47:01 +01008784 * resume sample-fetches. This function will be called by the sample
8785 * fetch engine to call lua-based fetch operations.
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008786 */
Thierry FOURNIER0786d052015-05-11 15:42:45 +02008787static int hlua_sample_fetch_wrapper(const struct arg *arg_p, struct sample *smp,
8788 const char *kw, void *private)
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008789{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02008790 struct hlua_function *fcn = private;
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02008791 struct stream *stream = smp->strm;
Thierry Fournierfd107a22016-02-19 19:57:23 +01008792 const char *error;
Christopher Faulet8c9e6bb2021-08-06 16:29:41 +02008793 unsigned int hflags = HLUA_TXN_NOTERM | HLUA_TXN_SMP_CTX;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008794
Willy Tarreaube508f12016-03-10 11:47:01 +01008795 if (!stream)
8796 return 0;
Christopher Fauletafd8f102018-11-08 11:34:21 +01008797
Willy Tarreau87b09662015-04-03 00:22:06 +02008798 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01008799 * Lua context can be not initialized. This behavior
8800 * permits to save performances because a systematic
8801 * Lua initialization cause 5% performances loss.
8802 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008803 if (!stream->hlua) {
Christopher Faulet1e8433f2021-03-24 15:03:01 +01008804 struct hlua *hlua;
8805
8806 hlua = pool_alloc(pool_head_hlua);
8807 if (!hlua) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008808 SEND_ERR(stream->be, "Lua sample-fetch '%s': can't initialize Lua context.\n", fcn->name);
8809 return 0;
8810 }
Christopher Faulet1e8433f2021-03-24 15:03:01 +01008811 hlua->T = NULL;
8812 stream->hlua = hlua;
Thierry Fournierc7492592020-11-28 23:57:24 +01008813 if (!hlua_ctx_init(stream->hlua, fcn_ref_to_stack_id(fcn), stream->task, 0)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008814 SEND_ERR(stream->be, "Lua sample-fetch '%s': can't initialize Lua context.\n", fcn->name);
8815 return 0;
8816 }
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01008817 }
8818
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008819 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008820 if (!HLUA_IS_RUNNING(stream->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008821
8822 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008823 if (!SET_SAFE_LJMP(stream->hlua)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008824 if (lua_type(stream->hlua->T, -1) == LUA_TSTRING)
8825 error = lua_tostring(stream->hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +01008826 else
8827 error = "critical error";
8828 SEND_ERR(smp->px, "Lua sample-fetch '%s': %s.\n", fcn->name, error);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008829 return 0;
8830 }
8831
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008832 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008833 if (!lua_checkstack(stream->hlua->T, 2)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008834 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008835 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008836 return 0;
8837 }
8838
8839 /* Restore the function in the stack. */
Thierry Fournierc7492592020-11-28 23:57:24 +01008840 lua_rawgeti(stream->hlua->T, LUA_REGISTRYINDEX, fcn->function_ref[stream->hlua->state_id]);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008841
8842 /* push arguments in the stack. */
Christopher Fauletbfab2dd2019-07-26 15:09:53 +02008843 if (!hlua_txn_new(stream->hlua->T, stream, smp->px, smp->opt & SMP_OPT_DIR, hflags)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008844 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008845 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008846 return 0;
8847 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008848 stream->hlua->nargs = 1;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008849
8850 /* push keywords in the stack. */
8851 for (; arg_p && arg_p->type != ARGT_STOP; arg_p++) {
8852 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008853 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008854 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008855 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008856 return 0;
8857 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008858 hlua_arg2lua(stream->hlua->T, arg_p);
8859 stream->hlua->nargs++;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008860 }
8861
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008862 /* We must initialize the execution timeouts. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008863 stream->hlua->max_time = hlua_timeout_session;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008864
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008865 /* At this point the execution is safe. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008866 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008867 }
8868
8869 /* Execute the function. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008870 switch (hlua_ctx_resume(stream->hlua, 0)) {
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008871 /* finished. */
8872 case HLUA_E_OK:
Thierry FOURNIERfd80df12017-05-12 16:32:20 +02008873 /* If the stack is empty, the function fails. */
8874 if (lua_gettop(stream->hlua->T) <= 0)
8875 return 0;
8876
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008877 /* Convert the returned value in sample. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008878 hlua_lua2smp(stream->hlua->T, -1, smp);
8879 lua_pop(stream->hlua->T, 1);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008880
8881 /* Set the end of execution flag. */
8882 smp->flags &= ~SMP_F_MAY_CHANGE;
8883 return 1;
8884
8885 /* yield. */
8886 case HLUA_E_AGAIN:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008887 SEND_ERR(smp->px, "Lua sample-fetch '%s': cannot use yielded functions.\n", fcn->name);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008888 return 0;
8889
8890 /* finished with error. */
8891 case HLUA_E_ERRMSG:
8892 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008893 SEND_ERR(smp->px, "Lua sample-fetch '%s': %s.\n",
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008894 fcn->name, lua_tostring(stream->hlua->T, -1));
8895 lua_pop(stream->hlua->T, 1);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008896 return 0;
8897
Thierry Fournierd5b073c2018-05-21 19:42:47 +02008898 case HLUA_E_ETMOUT:
Thierry Fournierd5b073c2018-05-21 19:42:47 +02008899 SEND_ERR(smp->px, "Lua sample-fetch '%s': execution timeout.\n", fcn->name);
8900 return 0;
8901
8902 case HLUA_E_NOMEM:
Thierry Fournierd5b073c2018-05-21 19:42:47 +02008903 SEND_ERR(smp->px, "Lua sample-fetch '%s': out of memory error.\n", fcn->name);
8904 return 0;
8905
8906 case HLUA_E_YIELD:
Thierry Fournierd5b073c2018-05-21 19:42:47 +02008907 SEND_ERR(smp->px, "Lua sample-fetch '%s': yield not allowed.\n", fcn->name);
8908 return 0;
8909
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008910 case HLUA_E_ERR:
8911 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008912 SEND_ERR(smp->px, "Lua sample-fetch '%s' returns an unknown error.\n", fcn->name);
Willy Tarreau14de3952022-11-14 07:08:28 +01008913 __fallthrough;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008914
8915 default:
8916 return 0;
8917 }
8918}
8919
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008920/* This function is an LUA binding used for registering
8921 * "sample-conv" functions. It expects a converter name used
8922 * in the haproxy configuration file, and an LUA function.
8923 */
8924__LJMP static int hlua_register_converters(lua_State *L)
8925{
8926 struct sample_conv_kw_list *sck;
8927 const char *name;
8928 int ref;
8929 int len;
Christopher Fauletaa224302021-04-12 14:08:21 +02008930 struct hlua_function *fcn = NULL;
Thierry Fournierf67442e2020-11-28 20:41:07 +01008931 struct sample_conv *sc;
8932 struct buffer *trash;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008933
8934 MAY_LJMP(check_args(L, 2, "register_converters"));
8935
8936 /* First argument : converter name. */
8937 name = MAY_LJMP(luaL_checkstring(L, 1));
8938
8939 /* Second argument : lua function. */
8940 ref = MAY_LJMP(hlua_checkfunction(L, 2));
8941
Thierry Fournierf67442e2020-11-28 20:41:07 +01008942 /* Check if the converter is already registered */
8943 trash = get_trash_chunk();
8944 chunk_printf(trash, "lua.%s", name);
8945 sc = find_sample_conv(trash->area, trash->data);
8946 if (sc != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +01008947 fcn = sc->private;
8948 if (fcn->function_ref[hlua_state_id] != -1) {
8949 ha_warning("Trying to register converter 'lua.%s' more than once. "
8950 "This will become a hard error in version 2.5.\n", name);
8951 }
8952 fcn->function_ref[hlua_state_id] = ref;
8953 return 0;
Thierry Fournierf67442e2020-11-28 20:41:07 +01008954 }
8955
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008956 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02008957 sck = calloc(1, sizeof(*sck) + sizeof(struct sample_conv) * 2);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008958 if (!sck)
Christopher Fauletaa224302021-04-12 14:08:21 +02008959 goto alloc_error;
Thierry Fournier62a22aa2020-11-28 21:06:35 +01008960 fcn = new_hlua_function();
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008961 if (!fcn)
Christopher Fauletaa224302021-04-12 14:08:21 +02008962 goto alloc_error;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008963
8964 /* Fill fcn. */
8965 fcn->name = strdup(name);
8966 if (!fcn->name)
Christopher Fauletaa224302021-04-12 14:08:21 +02008967 goto alloc_error;
Thierry Fournierc7492592020-11-28 23:57:24 +01008968 fcn->function_ref[hlua_state_id] = ref;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008969
8970 /* List head */
8971 sck->list.n = sck->list.p = NULL;
8972
8973 /* converter keyword. */
8974 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02008975 sck->kw[0].kw = calloc(1, len);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008976 if (!sck->kw[0].kw)
Christopher Fauletaa224302021-04-12 14:08:21 +02008977 goto alloc_error;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008978
8979 snprintf((char *)sck->kw[0].kw, len, "lua.%s", name);
8980 sck->kw[0].process = hlua_sample_conv_wrapper;
David Carlier0c437f42016-04-27 16:21:56 +01008981 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 +01008982 sck->kw[0].val_args = NULL;
8983 sck->kw[0].in_type = SMP_T_STR;
8984 sck->kw[0].out_type = SMP_T_STR;
8985 sck->kw[0].private = fcn;
8986
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008987 /* Register this new converter */
8988 sample_register_convs(sck);
8989
8990 return 0;
Christopher Fauletaa224302021-04-12 14:08:21 +02008991
8992 alloc_error:
8993 release_hlua_function(fcn);
8994 ha_free(&sck);
8995 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
8996 return 0; /* Never reached */
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008997}
8998
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08008999/* This function is an LUA binding used for registering
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009000 * "sample-fetch" functions. It expects a converter name used
9001 * in the haproxy configuration file, and an LUA function.
9002 */
9003__LJMP static int hlua_register_fetches(lua_State *L)
9004{
9005 const char *name;
9006 int ref;
9007 int len;
9008 struct sample_fetch_kw_list *sfk;
Christopher Faulet2567f182021-04-12 14:11:50 +02009009 struct hlua_function *fcn = NULL;
Thierry Fournierf67442e2020-11-28 20:41:07 +01009010 struct sample_fetch *sf;
9011 struct buffer *trash;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009012
9013 MAY_LJMP(check_args(L, 2, "register_fetches"));
9014
9015 /* First argument : sample-fetch name. */
9016 name = MAY_LJMP(luaL_checkstring(L, 1));
9017
9018 /* Second argument : lua function. */
9019 ref = MAY_LJMP(hlua_checkfunction(L, 2));
9020
Thierry Fournierf67442e2020-11-28 20:41:07 +01009021 /* Check if the sample-fetch is already registered */
9022 trash = get_trash_chunk();
9023 chunk_printf(trash, "lua.%s", name);
9024 sf = find_sample_fetch(trash->area, trash->data);
9025 if (sf != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +01009026 fcn = sf->private;
9027 if (fcn->function_ref[hlua_state_id] != -1) {
9028 ha_warning("Trying to register sample-fetch 'lua.%s' more than once. "
9029 "This will become a hard error in version 2.5.\n", name);
9030 }
9031 fcn->function_ref[hlua_state_id] = ref;
9032 return 0;
Thierry Fournierf67442e2020-11-28 20:41:07 +01009033 }
9034
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009035 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02009036 sfk = calloc(1, sizeof(*sfk) + sizeof(struct sample_fetch) * 2);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009037 if (!sfk)
Christopher Faulet2567f182021-04-12 14:11:50 +02009038 goto alloc_error;
Thierry Fournier62a22aa2020-11-28 21:06:35 +01009039 fcn = new_hlua_function();
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009040 if (!fcn)
Christopher Faulet2567f182021-04-12 14:11:50 +02009041 goto alloc_error;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009042
9043 /* Fill fcn. */
9044 fcn->name = strdup(name);
9045 if (!fcn->name)
Christopher Faulet2567f182021-04-12 14:11:50 +02009046 goto alloc_error;
Thierry Fournierc7492592020-11-28 23:57:24 +01009047 fcn->function_ref[hlua_state_id] = ref;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009048
9049 /* List head */
9050 sfk->list.n = sfk->list.p = NULL;
9051
9052 /* sample-fetch keyword. */
9053 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02009054 sfk->kw[0].kw = calloc(1, len);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009055 if (!sfk->kw[0].kw)
Christopher Faulet2567f182021-04-12 14:11:50 +02009056 goto alloc_error;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009057
9058 snprintf((char *)sfk->kw[0].kw, len, "lua.%s", name);
9059 sfk->kw[0].process = hlua_sample_fetch_wrapper;
David Carlier0c437f42016-04-27 16:21:56 +01009060 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 +01009061 sfk->kw[0].val_args = NULL;
9062 sfk->kw[0].out_type = SMP_T_STR;
9063 sfk->kw[0].use = SMP_USE_HTTP_ANY;
9064 sfk->kw[0].val = 0;
9065 sfk->kw[0].private = fcn;
9066
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009067 /* Register this new fetch. */
9068 sample_register_fetches(sfk);
9069
9070 return 0;
Christopher Faulet2567f182021-04-12 14:11:50 +02009071
9072 alloc_error:
9073 release_hlua_function(fcn);
9074 ha_free(&sfk);
9075 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
9076 return 0; /* Never reached */
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009077}
9078
Christopher Faulet501465d2020-02-26 14:54:16 +01009079/* This function is a lua binding to set the wake_time.
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01009080 */
Christopher Faulet501465d2020-02-26 14:54:16 +01009081__LJMP static int hlua_set_wake_time(lua_State *L)
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01009082{
Thierry Fournier4234dbd2020-11-28 13:18:23 +01009083 struct hlua *hlua;
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01009084 unsigned int delay;
9085 unsigned int wakeup_ms;
9086
Thierry Fournier4234dbd2020-11-28 13:18:23 +01009087 /* Get hlua struct, or NULL if we execute from main lua state */
9088 hlua = hlua_gethlua(L);
9089 if (!hlua) {
9090 return 0;
9091 }
9092
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01009093 MAY_LJMP(check_args(L, 1, "wake_time"));
9094
9095 delay = MAY_LJMP(luaL_checkinteger(L, 1));
9096 wakeup_ms = tick_add(now_ms, delay);
9097 hlua->wake_time = wakeup_ms;
9098 return 0;
9099}
9100
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009101/* This function is a wrapper to execute each LUA function declared as an action
9102 * wrapper during the initialisation period. This function may return any
9103 * ACT_RET_* value. On error ACT_RET_CONT is returned and the action is
9104 * ignored. If the lua action yields, ACT_RET_YIELD is returned. On success, the
9105 * return value is the first element on the stack.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009106 */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009107static enum act_return hlua_action(struct act_rule *rule, struct proxy *px,
Willy Tarreau658b85b2015-09-27 10:00:49 +02009108 struct session *sess, struct stream *s, int flags)
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009109{
9110 char **arg;
Christopher Faulet8c9e6bb2021-08-06 16:29:41 +02009111 unsigned int hflags = HLUA_TXN_ACT_CTX;
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009112 int dir, act_ret = ACT_RET_CONT;
Thierry Fournierfd107a22016-02-19 19:57:23 +01009113 const char *error;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009114
9115 switch (rule->from) {
Christopher Fauletd8f0e072020-02-25 09:45:51 +01009116 case ACT_F_TCP_REQ_CNT: dir = SMP_OPT_DIR_REQ; break;
9117 case ACT_F_TCP_RES_CNT: dir = SMP_OPT_DIR_RES; break;
9118 case ACT_F_HTTP_REQ: dir = SMP_OPT_DIR_REQ; break;
9119 case ACT_F_HTTP_RES: dir = SMP_OPT_DIR_RES; break;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009120 default:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009121 SEND_ERR(px, "Lua: internal error while execute action.\n");
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009122 goto end;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009123 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009124
Willy Tarreau87b09662015-04-03 00:22:06 +02009125 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01009126 * Lua context can be not initialized. This behavior
9127 * permits to save performances because a systematic
9128 * Lua initialization cause 5% performances loss.
9129 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009130 if (!s->hlua) {
Christopher Faulet1e8433f2021-03-24 15:03:01 +01009131 struct hlua *hlua;
9132
9133 hlua = pool_alloc(pool_head_hlua);
9134 if (!hlua) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009135 SEND_ERR(px, "Lua action '%s': can't initialize Lua context.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009136 rule->arg.hlua_rule->fcn->name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009137 goto end;
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009138 }
Christopher Faulet1e8433f2021-03-24 15:03:01 +01009139 HLUA_INIT(hlua);
9140 s->hlua = hlua;
Thierry Fournierc7492592020-11-28 23:57:24 +01009141 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 +01009142 SEND_ERR(px, "Lua action '%s': can't initialize Lua context.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009143 rule->arg.hlua_rule->fcn->name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009144 goto end;
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009145 }
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01009146 }
9147
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009148 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009149 if (!HLUA_IS_RUNNING(s->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02009150
9151 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009152 if (!SET_SAFE_LJMP(s->hlua)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009153 if (lua_type(s->hlua->T, -1) == LUA_TSTRING)
9154 error = lua_tostring(s->hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +01009155 else
9156 error = "critical error";
9157 SEND_ERR(px, "Lua function '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009158 rule->arg.hlua_rule->fcn->name, error);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009159 goto end;
Thierry FOURNIERbabae282015-09-17 11:36:37 +02009160 }
9161
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009162 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009163 if (!lua_checkstack(s->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009164 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009165 rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009166 RESET_SAFE_LJMP(s->hlua);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009167 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009168 }
9169
9170 /* Restore the function in the stack. */
Thierry Fournierc7492592020-11-28 23:57:24 +01009171 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 +01009172
Willy Tarreau87b09662015-04-03 00:22:06 +02009173 /* Create and and push object stream in the stack. */
Christopher Fauletbfab2dd2019-07-26 15:09:53 +02009174 if (!hlua_txn_new(s->hlua->T, s, px, dir, hflags)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009175 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009176 rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009177 RESET_SAFE_LJMP(s->hlua);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009178 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009179 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009180 s->hlua->nargs = 1;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009181
9182 /* push keywords in the stack. */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009183 for (arg = rule->arg.hlua_rule->args; arg && *arg; arg++) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009184 if (!lua_checkstack(s->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009185 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009186 rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009187 RESET_SAFE_LJMP(s->hlua);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009188 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009189 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009190 lua_pushstring(s->hlua->T, *arg);
9191 s->hlua->nargs++;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009192 }
9193
Thierry FOURNIERbabae282015-09-17 11:36:37 +02009194 /* Now the execution is safe. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009195 RESET_SAFE_LJMP(s->hlua);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02009196
Thierry FOURNIERbd413492015-03-03 16:52:26 +01009197 /* We must initialize the execution timeouts. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009198 s->hlua->max_time = hlua_timeout_session;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009199 }
9200
9201 /* Execute the function. */
Christopher Faulet105ba6c2019-12-18 14:41:51 +01009202 switch (hlua_ctx_resume(s->hlua, !(flags & ACT_OPT_FINAL))) {
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009203 /* finished. */
9204 case HLUA_E_OK:
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009205 /* Catch the return value */
9206 if (lua_gettop(s->hlua->T) > 0)
9207 act_ret = lua_tointeger(s->hlua->T, -1);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009208
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01009209 /* Set timeout in the required channel. */
Christopher Faulet498c4832020-07-28 11:59:58 +02009210 if (act_ret == ACT_RET_YIELD) {
9211 if (flags & ACT_OPT_FINAL)
9212 goto err_yield;
9213
Christopher Faulet8f587ea2020-07-28 12:01:55 +02009214 if (dir == SMP_OPT_DIR_REQ)
9215 s->req.analyse_exp = tick_first((tick_is_expired(s->req.analyse_exp, now_ms) ? 0 : s->req.analyse_exp),
9216 s->hlua->wake_time);
9217 else
9218 s->res.analyse_exp = tick_first((tick_is_expired(s->res.analyse_exp, now_ms) ? 0 : s->res.analyse_exp),
9219 s->hlua->wake_time);
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01009220 }
9221 goto end;
9222
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009223 /* yield. */
9224 case HLUA_E_AGAIN:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01009225 /* Set timeout in the required channel. */
Christopher Faulet8f587ea2020-07-28 12:01:55 +02009226 if (dir == SMP_OPT_DIR_REQ)
9227 s->req.analyse_exp = tick_first((tick_is_expired(s->req.analyse_exp, now_ms) ? 0 : s->req.analyse_exp),
9228 s->hlua->wake_time);
9229 else
9230 s->res.analyse_exp = tick_first((tick_is_expired(s->res.analyse_exp, now_ms) ? 0 : s->res.analyse_exp),
9231 s->hlua->wake_time);
9232
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009233 /* Some actions can be wake up when a "write" event
9234 * is detected on a response channel. This is useful
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08009235 * only for actions targeted on the requests.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009236 */
Christopher Faulet51fa3582019-07-26 14:54:52 +02009237 if (HLUA_IS_WAKERESWR(s->hlua))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01009238 s->res.flags |= CF_WAKE_WRITE;
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009239 if (HLUA_IS_WAKEREQWR(s->hlua))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01009240 s->req.flags |= CF_WAKE_WRITE;
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009241 act_ret = ACT_RET_YIELD;
9242 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009243
9244 /* finished with error. */
9245 case HLUA_E_ERRMSG:
9246 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009247 SEND_ERR(px, "Lua function '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009248 rule->arg.hlua_rule->fcn->name, lua_tostring(s->hlua->T, -1));
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009249 lua_pop(s->hlua->T, 1);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009250 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009251
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009252 case HLUA_E_ETMOUT:
Thierry Fournierad5345f2020-11-29 02:05:57 +01009253 SEND_ERR(px, "Lua function '%s': execution timeout.\n", rule->arg.hlua_rule->fcn->name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009254 goto end;
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009255
9256 case HLUA_E_NOMEM:
Thierry Fournierad5345f2020-11-29 02:05:57 +01009257 SEND_ERR(px, "Lua function '%s': out of memory error.\n", rule->arg.hlua_rule->fcn->name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009258 goto end;
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009259
9260 case HLUA_E_YIELD:
Christopher Faulet498c4832020-07-28 11:59:58 +02009261 err_yield:
9262 act_ret = ACT_RET_CONT;
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009263 SEND_ERR(px, "Lua function '%s': aborting Lua processing on expired timeout.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009264 rule->arg.hlua_rule->fcn->name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009265 goto end;
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009266
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009267 case HLUA_E_ERR:
9268 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009269 SEND_ERR(px, "Lua function '%s' return an unknown error.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009270 rule->arg.hlua_rule->fcn->name);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009271
9272 default:
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009273 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009274 }
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009275
9276 end:
Christopher Faulet2361fd92020-07-30 10:40:58 +02009277 if (act_ret != ACT_RET_YIELD && s->hlua)
Christopher Faulet8f587ea2020-07-28 12:01:55 +02009278 s->hlua->wake_time = TICK_ETERNITY;
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009279 return act_ret;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009280}
9281
Willy Tarreau144f84a2021-03-02 16:09:26 +01009282struct task *hlua_applet_wakeup(struct task *t, void *context, unsigned int state)
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009283{
Olivier Houchard9f6af332018-05-25 14:04:04 +02009284 struct appctx *ctx = context;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009285
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009286 appctx_wakeup(ctx);
Willy Tarreaud9587412017-08-23 16:07:33 +02009287 t->expire = TICK_ETERNITY;
Willy Tarreaud1aa41f2017-07-21 16:41:56 +02009288 return t;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009289}
9290
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009291static int hlua_applet_tcp_init(struct appctx *ctx)
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009292{
Willy Tarreaue23f33b2022-05-06 14:07:13 +02009293 struct hlua_tcp_ctx *tcp_ctx = applet_reserve_svcctx(ctx, sizeof(*tcp_ctx));
Willy Tarreauc12b3212022-05-27 11:08:15 +02009294 struct stconn *sc = appctx_sc(ctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02009295 struct stream *strm = __sc_strm(sc);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009296 struct hlua *hlua;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009297 struct task *task;
9298 char **arg;
Thierry Fournierfd107a22016-02-19 19:57:23 +01009299 const char *error;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009300
Willy Tarreaubafbe012017-11-24 17:34:44 +01009301 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009302 if (!hlua) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009303 SEND_ERR(strm->be, "Lua applet tcp '%s': out of memory.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009304 ctx->rule->arg.hlua_rule->fcn->name);
Christopher Fauletc9929382022-05-12 11:52:27 +02009305 return -1;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009306 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009307 HLUA_INIT(hlua);
Willy Tarreaue23f33b2022-05-06 14:07:13 +02009308 tcp_ctx->hlua = hlua;
9309 tcp_ctx->flags = 0;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009310
9311 /* Create task used by signal to wakeup applets. */
Willy Tarreaubeeabf52021-10-01 18:23:30 +02009312 task = task_new_here();
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009313 if (!task) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009314 SEND_ERR(strm->be, "Lua applet tcp '%s': out of memory.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009315 ctx->rule->arg.hlua_rule->fcn->name);
Christopher Fauletc9929382022-05-12 11:52:27 +02009316 return -1;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009317 }
9318 task->nice = 0;
9319 task->context = ctx;
9320 task->process = hlua_applet_wakeup;
Willy Tarreaue23f33b2022-05-06 14:07:13 +02009321 tcp_ctx->task = task;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009322
9323 /* In the execution wrappers linked with a stream, the
9324 * Lua context can be not initialized. This behavior
9325 * permits to save performances because a systematic
9326 * Lua initialization cause 5% performances loss.
9327 */
Thierry Fournierc7492592020-11-28 23:57:24 +01009328 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 +01009329 SEND_ERR(strm->be, "Lua applet tcp '%s': can't initialize Lua context.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009330 ctx->rule->arg.hlua_rule->fcn->name);
Christopher Fauletc9929382022-05-12 11:52:27 +02009331 return -1;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009332 }
9333
9334 /* Set timeout according with the applet configuration. */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02009335 hlua->max_time = ctx->applet->timeout;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009336
9337 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009338 if (!SET_SAFE_LJMP(hlua)) {
Thierry Fournierfd107a22016-02-19 19:57:23 +01009339 if (lua_type(hlua->T, -1) == LUA_TSTRING)
9340 error = lua_tostring(hlua->T, -1);
9341 else
9342 error = "critical error";
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009343 SEND_ERR(strm->be, "Lua applet tcp '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009344 ctx->rule->arg.hlua_rule->fcn->name, error);
Christopher Fauletc9929382022-05-12 11:52:27 +02009345 return -1;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009346 }
9347
9348 /* Check stack available size. */
9349 if (!lua_checkstack(hlua->T, 1)) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009350 SEND_ERR(strm->be, "Lua applet tcp '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009351 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009352 RESET_SAFE_LJMP(hlua);
Christopher Fauletc9929382022-05-12 11:52:27 +02009353 return -1;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009354 }
9355
9356 /* Restore the function in the stack. */
Thierry Fournierc7492592020-11-28 23:57:24 +01009357 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ctx->rule->arg.hlua_rule->fcn->function_ref[hlua->state_id]);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009358
9359 /* Create and and push object stream in the stack. */
9360 if (!hlua_applet_tcp_new(hlua->T, ctx)) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009361 SEND_ERR(strm->be, "Lua applet tcp '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009362 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009363 RESET_SAFE_LJMP(hlua);
Christopher Fauletc9929382022-05-12 11:52:27 +02009364 return -1;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009365 }
9366 hlua->nargs = 1;
9367
9368 /* push keywords in the stack. */
9369 for (arg = ctx->rule->arg.hlua_rule->args; arg && *arg; arg++) {
9370 if (!lua_checkstack(hlua->T, 1)) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009371 SEND_ERR(strm->be, "Lua applet tcp '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009372 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009373 RESET_SAFE_LJMP(hlua);
Christopher Fauletc9929382022-05-12 11:52:27 +02009374 return -1;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009375 }
9376 lua_pushstring(hlua->T, *arg);
9377 hlua->nargs++;
9378 }
9379
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009380 RESET_SAFE_LJMP(hlua);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009381
9382 /* Wakeup the applet ASAP. */
Willy Tarreau90e8b452022-05-25 18:21:43 +02009383 applet_need_more_data(ctx);
Willy Tarreau4164eb92022-05-25 15:42:03 +02009384 applet_have_more_data(ctx);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009385
Christopher Fauletc9929382022-05-12 11:52:27 +02009386 return 0;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009387}
9388
Willy Tarreau60409db2019-08-21 14:14:50 +02009389void hlua_applet_tcp_fct(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 = ctx->svcctx;
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);
9394 struct channel *res = sc_ic(sc);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009395 struct act_rule *rule = ctx->rule;
9396 struct proxy *px = strm->be;
Willy Tarreaue23f33b2022-05-06 14:07:13 +02009397 struct hlua *hlua = tcp_ctx->hlua;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009398
9399 /* The applet execution is already done. */
Willy Tarreaue23f33b2022-05-06 14:07:13 +02009400 if (tcp_ctx->flags & APPLET_DONE) {
Olivier Houchard594c8c52018-08-28 14:41:31 +02009401 /* eat the whole request */
Willy Tarreau3e7be362022-05-27 10:35:27 +02009402 co_skip(sc_oc(sc), co_data(sc_oc(sc)));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009403 return;
Olivier Houchard594c8c52018-08-28 14:41:31 +02009404 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009405
9406 /* If the stream is disconnect or closed, ldo nothing. */
Willy Tarreau3e7be362022-05-27 10:35:27 +02009407 if (unlikely(sc->state == SC_ST_DIS || sc->state == SC_ST_CLO))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009408 return;
9409
9410 /* Execute the function. */
9411 switch (hlua_ctx_resume(hlua, 1)) {
9412 /* finished. */
9413 case HLUA_E_OK:
Willy Tarreaue23f33b2022-05-06 14:07:13 +02009414 tcp_ctx->flags |= APPLET_DONE;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009415
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009416 /* eat the whole request */
Willy Tarreau3e7be362022-05-27 10:35:27 +02009417 co_skip(sc_oc(sc), co_data(sc_oc(sc)));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009418 res->flags |= CF_READ_NULL;
Willy Tarreau3e7be362022-05-27 10:35:27 +02009419 sc_shutr(sc);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009420 return;
9421
9422 /* yield. */
9423 case HLUA_E_AGAIN:
Thierry Fournier0164f202016-02-20 17:47:43 +01009424 if (hlua->wake_time != TICK_ETERNITY)
Willy Tarreaue23f33b2022-05-06 14:07:13 +02009425 task_schedule(tcp_ctx->task, hlua->wake_time);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009426 return;
9427
9428 /* finished with error. */
9429 case HLUA_E_ERRMSG:
9430 /* Display log. */
9431 SEND_ERR(px, "Lua applet tcp '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009432 rule->arg.hlua_rule->fcn->name, lua_tostring(hlua->T, -1));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009433 lua_pop(hlua->T, 1);
9434 goto error;
9435
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009436 case HLUA_E_ETMOUT:
9437 SEND_ERR(px, "Lua applet tcp '%s': execution timeout.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009438 rule->arg.hlua_rule->fcn->name);
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009439 goto error;
9440
9441 case HLUA_E_NOMEM:
9442 SEND_ERR(px, "Lua applet tcp '%s': out of memory error.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009443 rule->arg.hlua_rule->fcn->name);
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009444 goto error;
9445
9446 case HLUA_E_YIELD: /* unexpected */
9447 SEND_ERR(px, "Lua applet tcp '%s': yield not allowed.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009448 rule->arg.hlua_rule->fcn->name);
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009449 goto error;
9450
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009451 case HLUA_E_ERR:
9452 /* Display log. */
9453 SEND_ERR(px, "Lua applet tcp '%s' return an unknown error.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009454 rule->arg.hlua_rule->fcn->name);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009455 goto error;
9456
9457 default:
9458 goto error;
9459 }
9460
9461error:
9462
9463 /* For all other cases, just close the stream. */
Willy Tarreau3e7be362022-05-27 10:35:27 +02009464 sc_shutw(sc);
9465 sc_shutr(sc);
Willy Tarreaue23f33b2022-05-06 14:07:13 +02009466 tcp_ctx->flags |= APPLET_DONE;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009467}
9468
9469static void hlua_applet_tcp_release(struct appctx *ctx)
9470{
Willy Tarreaue23f33b2022-05-06 14:07:13 +02009471 struct hlua_tcp_ctx *tcp_ctx = ctx->svcctx;
9472
9473 task_destroy(tcp_ctx->task);
9474 tcp_ctx->task = NULL;
9475 hlua_ctx_destroy(tcp_ctx->hlua);
9476 tcp_ctx->hlua = NULL;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009477}
9478
Christopher Fauletc9929382022-05-12 11:52:27 +02009479/* The function returns 0 if the initialisation is complete or -1 if
9480 * an errors occurs. It also reserves the appctx for an hlua_http_ctx.
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009481 */
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009482static int hlua_applet_http_init(struct appctx *ctx)
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009483{
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009484 struct hlua_http_ctx *http_ctx = applet_reserve_svcctx(ctx, sizeof(*http_ctx));
Willy Tarreauc12b3212022-05-27 11:08:15 +02009485 struct stconn *sc = appctx_sc(ctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02009486 struct stream *strm = __sc_strm(sc);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009487 struct http_txn *txn;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009488 struct hlua *hlua;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009489 char **arg;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009490 struct task *task;
Thierry Fournierfd107a22016-02-19 19:57:23 +01009491 const char *error;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009492
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009493 txn = strm->txn;
Willy Tarreaubafbe012017-11-24 17:34:44 +01009494 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009495 if (!hlua) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009496 SEND_ERR(strm->be, "Lua applet http '%s': out of memory.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009497 ctx->rule->arg.hlua_rule->fcn->name);
Christopher Fauletc9929382022-05-12 11:52:27 +02009498 return -1;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009499 }
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009500 HLUA_INIT(hlua);
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009501 http_ctx->hlua = hlua;
9502 http_ctx->left_bytes = -1;
9503 http_ctx->flags = 0;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009504
Thierry FOURNIERd93ea2b2015-12-20 19:14:52 +01009505 if (txn->req.flags & HTTP_MSGF_VER_11)
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009506 http_ctx->flags |= APPLET_HTTP11;
Thierry FOURNIERd93ea2b2015-12-20 19:14:52 +01009507
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009508 /* Create task used by signal to wakeup applets. */
Willy Tarreaubeeabf52021-10-01 18:23:30 +02009509 task = task_new_here();
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009510 if (!task) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009511 SEND_ERR(strm->be, "Lua applet http '%s': out of memory.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009512 ctx->rule->arg.hlua_rule->fcn->name);
Christopher Fauletc9929382022-05-12 11:52:27 +02009513 return -1;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009514 }
9515 task->nice = 0;
9516 task->context = ctx;
9517 task->process = hlua_applet_wakeup;
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009518 http_ctx->task = task;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009519
9520 /* In the execution wrappers linked with a stream, the
9521 * Lua context can be not initialized. This behavior
9522 * permits to save performances because a systematic
9523 * Lua initialization cause 5% performances loss.
9524 */
Thierry Fournierc7492592020-11-28 23:57:24 +01009525 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 +01009526 SEND_ERR(strm->be, "Lua applet http '%s': can't initialize Lua context.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009527 ctx->rule->arg.hlua_rule->fcn->name);
Christopher Fauletc9929382022-05-12 11:52:27 +02009528 return -1;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009529 }
9530
9531 /* Set timeout according with the applet configuration. */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02009532 hlua->max_time = ctx->applet->timeout;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009533
9534 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009535 if (!SET_SAFE_LJMP(hlua)) {
Thierry Fournierfd107a22016-02-19 19:57:23 +01009536 if (lua_type(hlua->T, -1) == LUA_TSTRING)
9537 error = lua_tostring(hlua->T, -1);
9538 else
9539 error = "critical error";
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009540 SEND_ERR(strm->be, "Lua applet http '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009541 ctx->rule->arg.hlua_rule->fcn->name, error);
Christopher Fauletc9929382022-05-12 11:52:27 +02009542 return -1;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009543 }
9544
9545 /* Check stack available size. */
9546 if (!lua_checkstack(hlua->T, 1)) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009547 SEND_ERR(strm->be, "Lua applet http '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009548 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009549 RESET_SAFE_LJMP(hlua);
Christopher Fauletc9929382022-05-12 11:52:27 +02009550 return -1;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009551 }
9552
9553 /* Restore the function in the stack. */
Thierry Fournierc7492592020-11-28 23:57:24 +01009554 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ctx->rule->arg.hlua_rule->fcn->function_ref[hlua->state_id]);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009555
9556 /* Create and and push object stream in the stack. */
9557 if (!hlua_applet_http_new(hlua->T, ctx)) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009558 SEND_ERR(strm->be, "Lua applet http '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009559 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009560 RESET_SAFE_LJMP(hlua);
Christopher Fauletc9929382022-05-12 11:52:27 +02009561 return -1;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009562 }
9563 hlua->nargs = 1;
9564
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009565 /* push keywords in the stack. */
9566 for (arg = ctx->rule->arg.hlua_rule->args; arg && *arg; arg++) {
9567 if (!lua_checkstack(hlua->T, 1)) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009568 SEND_ERR(strm->be, "Lua applet http '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009569 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009570 RESET_SAFE_LJMP(hlua);
Christopher Fauletc9929382022-05-12 11:52:27 +02009571 return -1;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009572 }
9573 lua_pushstring(hlua->T, *arg);
9574 hlua->nargs++;
9575 }
9576
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009577 RESET_SAFE_LJMP(hlua);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009578
9579 /* Wakeup the applet when data is ready for read. */
Willy Tarreau90e8b452022-05-25 18:21:43 +02009580 applet_need_more_data(ctx);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009581
Christopher Fauletc9929382022-05-12 11:52:27 +02009582 return 0;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009583}
9584
Willy Tarreau60409db2019-08-21 14:14:50 +02009585void hlua_applet_http_fct(struct appctx *ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009586{
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009587 struct hlua_http_ctx *http_ctx = ctx->svcctx;
Willy Tarreauc12b3212022-05-27 11:08:15 +02009588 struct stconn *sc = appctx_sc(ctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02009589 struct stream *strm = __sc_strm(sc);
9590 struct channel *req = sc_oc(sc);
9591 struct channel *res = sc_ic(sc);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009592 struct act_rule *rule = ctx->rule;
9593 struct proxy *px = strm->be;
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009594 struct hlua *hlua = http_ctx->hlua;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009595 struct htx *req_htx, *res_htx;
9596
9597 res_htx = htx_from_buf(&res->buf);
9598
9599 /* If the stream is disconnect or closed, ldo nothing. */
Willy Tarreau3e7be362022-05-27 10:35:27 +02009600 if (unlikely(sc->state == SC_ST_DIS || sc->state == SC_ST_CLO))
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009601 goto out;
9602
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05009603 /* Check if the input buffer is available. */
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009604 if (!b_size(&res->buf)) {
Willy Tarreau3e7be362022-05-27 10:35:27 +02009605 sc_need_room(sc);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009606 goto out;
9607 }
9608 /* check that the output is not closed */
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01009609 if (res->flags & (CF_SHUTW|CF_SHUTW_NOW|CF_SHUTR))
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009610 http_ctx->flags |= APPLET_DONE;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009611
9612 /* Set the currently running flag. */
9613 if (!HLUA_IS_RUNNING(hlua) &&
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009614 !(http_ctx->flags & APPLET_DONE)) {
Christopher Fauletbd878d22021-04-28 10:50:21 +02009615 if (!co_data(req)) {
Willy Tarreau90e8b452022-05-25 18:21:43 +02009616 applet_need_more_data(ctx);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009617 goto out;
9618 }
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009619 }
9620
9621 /* Executes The applet if it is not done. */
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009622 if (!(http_ctx->flags & APPLET_DONE)) {
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009623
9624 /* Execute the function. */
9625 switch (hlua_ctx_resume(hlua, 1)) {
9626 /* finished. */
9627 case HLUA_E_OK:
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009628 http_ctx->flags |= APPLET_DONE;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009629 break;
9630
9631 /* yield. */
9632 case HLUA_E_AGAIN:
9633 if (hlua->wake_time != TICK_ETERNITY)
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009634 task_schedule(http_ctx->task, hlua->wake_time);
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01009635 goto out;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009636
9637 /* finished with error. */
9638 case HLUA_E_ERRMSG:
9639 /* Display log. */
9640 SEND_ERR(px, "Lua applet http '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009641 rule->arg.hlua_rule->fcn->name, lua_tostring(hlua->T, -1));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009642 lua_pop(hlua->T, 1);
9643 goto error;
9644
9645 case HLUA_E_ETMOUT:
9646 SEND_ERR(px, "Lua applet http '%s': execution timeout.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009647 rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009648 goto error;
9649
9650 case HLUA_E_NOMEM:
9651 SEND_ERR(px, "Lua applet http '%s': out of memory error.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009652 rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009653 goto error;
9654
9655 case HLUA_E_YIELD: /* unexpected */
9656 SEND_ERR(px, "Lua applet http '%s': yield not allowed.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009657 rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009658 goto error;
9659
9660 case HLUA_E_ERR:
9661 /* Display log. */
9662 SEND_ERR(px, "Lua applet http '%s' return an unknown error.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009663 rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009664 goto error;
9665
9666 default:
9667 goto error;
9668 }
9669 }
9670
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009671 if (http_ctx->flags & APPLET_DONE) {
9672 if (http_ctx->flags & APPLET_RSP_SENT)
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01009673 goto done;
9674
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009675 if (!(http_ctx->flags & APPLET_HDR_SENT))
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009676 goto error;
9677
Christopher Fauletf89af9c2022-04-07 10:07:18 +02009678 /* no more data are expected. If the response buffer is empty
9679 * for a chunked message, be sure to add something (EOT block in
9680 * this case) to have something to send. It is important to be
9681 * sure the EOM flags will be handled by the endpoint.
9682 */
9683 if (htx_is_empty(res_htx) && (strm->txn->rsp.flags & (HTTP_MSGF_XFER_LEN|HTTP_MSGF_CNT_LEN)) == HTTP_MSGF_XFER_LEN) {
9684 if (!htx_add_endof(res_htx, HTX_BLK_EOT)) {
Willy Tarreau3e7be362022-05-27 10:35:27 +02009685 sc_need_room(sc);
Christopher Fauletf89af9c2022-04-07 10:07:18 +02009686 goto out;
9687 }
9688 channel_add_input(res, 1);
9689 }
9690
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01009691 res_htx->flags |= HTX_FL_EOM;
Christopher Fauletd8d27082022-03-07 15:50:54 +01009692 res->flags |= CF_EOI;
Willy Tarreaud869e132022-05-17 18:05:31 +02009693 se_fl_set(ctx->sedesc, SE_FL_EOI);
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009694 strm->txn->status = http_ctx->status;
9695 http_ctx->flags |= APPLET_RSP_SENT;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009696 }
9697
9698 done:
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009699 if (http_ctx->flags & APPLET_DONE) {
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01009700 if (!(res->flags & CF_SHUTR)) {
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009701 res->flags |= CF_READ_NULL;
Willy Tarreau3e7be362022-05-27 10:35:27 +02009702 sc_shutr(sc);
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01009703 }
9704
9705 /* eat the whole request */
9706 if (co_data(req)) {
9707 req_htx = htx_from_buf(&req->buf);
9708 co_htx_skip(req, req_htx, co_data(req));
9709 htx_to_buf(req_htx, &req->buf);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009710 }
9711 }
9712
9713 out:
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009714 htx_to_buf(res_htx, &res->buf);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009715 return;
9716
9717 error:
9718
9719 /* If we are in HTTP mode, and we are not send any
9720 * data, return a 500 server error in best effort:
9721 * if there is no room available in the buffer,
9722 * just close the connection.
9723 */
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009724 if (!(http_ctx->flags & APPLET_HDR_SENT)) {
Christopher Fauletf7346382019-07-17 22:02:08 +02009725 struct buffer *err = &http_err_chunks[HTTP_ERR_500];
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009726
9727 channel_erase(res);
9728 res->buf.data = b_data(err);
9729 memcpy(res->buf.area, b_head(err), b_data(err));
9730 res_htx = htx_from_buf(&res->buf);
Christopher Fauletf6cce3f2019-02-27 21:20:09 +01009731 channel_add_input(res, res_htx->data);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009732 }
9733 if (!(strm->flags & SF_ERR_MASK))
9734 strm->flags |= SF_ERR_RESOURCE;
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009735 http_ctx->flags |= APPLET_DONE;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009736 goto done;
9737}
9738
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009739static void hlua_applet_http_release(struct appctx *ctx)
9740{
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009741 struct hlua_http_ctx *http_ctx = ctx->svcctx;
9742
9743 task_destroy(http_ctx->task);
9744 http_ctx->task = NULL;
9745 hlua_ctx_destroy(http_ctx->hlua);
9746 http_ctx->hlua = NULL;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009747}
9748
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009749/* global {tcp|http}-request parser. Return ACT_RET_PRS_OK in
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05009750 * success case, else return ACT_RET_PRS_ERR.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02009751 *
9752 * This function can fail with an abort() due to an Lua critical error.
9753 * We are in the configuration parsing process of HAProxy, this abort() is
9754 * tolerated.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009755 */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009756static enum act_parse_ret action_register_lua(const char **args, int *cur_arg, struct proxy *px,
9757 struct act_rule *rule, char **err)
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009758{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02009759 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009760 int i;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009761
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009762 /* Memory for the rule. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02009763 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009764 if (!rule->arg.hlua_rule) {
9765 memprintf(err, "out of memory error");
Christopher Faulet528526f2021-04-12 14:37:32 +02009766 goto error;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009767 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009768
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009769 /* Memory for arguments. */
Tim Duesterhuse52b6e52020-09-12 20:26:43 +02009770 rule->arg.hlua_rule->args = calloc(fcn->nargs + 1,
9771 sizeof(*rule->arg.hlua_rule->args));
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009772 if (!rule->arg.hlua_rule->args) {
9773 memprintf(err, "out of memory error");
Christopher Faulet528526f2021-04-12 14:37:32 +02009774 goto error;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009775 }
9776
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009777 /* Reference the Lua function and store the reference. */
Thierry Fournierad5345f2020-11-29 02:05:57 +01009778 rule->arg.hlua_rule->fcn = fcn;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009779
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009780 /* Expect some arguments */
9781 for (i = 0; i < fcn->nargs; i++) {
Thierry FOURNIER1725c2e2019-01-06 19:38:49 +01009782 if (*args[*cur_arg] == '\0') {
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009783 memprintf(err, "expect %d arguments", fcn->nargs);
Christopher Faulet528526f2021-04-12 14:37:32 +02009784 goto error;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009785 }
Thierry FOURNIER1725c2e2019-01-06 19:38:49 +01009786 rule->arg.hlua_rule->args[i] = strdup(args[*cur_arg]);
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009787 if (!rule->arg.hlua_rule->args[i]) {
9788 memprintf(err, "out of memory error");
Christopher Faulet528526f2021-04-12 14:37:32 +02009789 goto error;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009790 }
9791 (*cur_arg)++;
9792 }
9793 rule->arg.hlua_rule->args[i] = NULL;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009794
Thierry FOURNIER42148732015-09-02 17:17:33 +02009795 rule->action = ACT_CUSTOM;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009796 rule->action_ptr = hlua_action;
Thierry FOURNIERafa80492015-08-19 09:04:15 +02009797 return ACT_RET_PRS_OK;
Christopher Faulet528526f2021-04-12 14:37:32 +02009798
9799 error:
9800 if (rule->arg.hlua_rule) {
9801 if (rule->arg.hlua_rule->args) {
9802 for (i = 0; i < fcn->nargs; i++)
9803 ha_free(&rule->arg.hlua_rule->args[i]);
9804 ha_free(&rule->arg.hlua_rule->args);
9805 }
9806 ha_free(&rule->arg.hlua_rule);
9807 }
9808 return ACT_RET_PRS_ERR;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009809}
9810
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009811static enum act_parse_ret action_register_service_http(const char **args, int *cur_arg, struct proxy *px,
9812 struct act_rule *rule, char **err)
9813{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02009814 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009815
Thierry FOURNIER718e2a72015-12-20 20:13:14 +01009816 /* HTTP applets are forbidden in tcp-request rules.
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05009817 * HTTP applet request requires everything initialized by
Thierry FOURNIER718e2a72015-12-20 20:13:14 +01009818 * "http_process_request" (analyzer flag AN_REQ_HTTP_INNER).
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05009819 * The applet will be immediately initialized, but its before
Thierry FOURNIER718e2a72015-12-20 20:13:14 +01009820 * the call of this analyzer.
9821 */
9822 if (rule->from != ACT_F_HTTP_REQ) {
9823 memprintf(err, "HTTP applets are forbidden from 'tcp-request' rulesets");
9824 return ACT_RET_PRS_ERR;
9825 }
9826
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009827 /* Memory for the rule. */
9828 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
9829 if (!rule->arg.hlua_rule) {
9830 memprintf(err, "out of memory error");
9831 return ACT_RET_PRS_ERR;
9832 }
9833
9834 /* Reference the Lua function and store the reference. */
Thierry Fournierad5345f2020-11-29 02:05:57 +01009835 rule->arg.hlua_rule->fcn = fcn;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009836
9837 /* TODO: later accept arguments. */
9838 rule->arg.hlua_rule->args = NULL;
9839
9840 /* Add applet pointer in the rule. */
9841 rule->applet.obj_type = OBJ_TYPE_APPLET;
9842 rule->applet.name = fcn->name;
9843 rule->applet.init = hlua_applet_http_init;
9844 rule->applet.fct = hlua_applet_http_fct;
9845 rule->applet.release = hlua_applet_http_release;
9846 rule->applet.timeout = hlua_timeout_applet;
9847
9848 return ACT_RET_PRS_OK;
9849}
9850
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009851/* This function is an LUA binding used for registering
9852 * "sample-conv" functions. It expects a converter name used
9853 * in the haproxy configuration file, and an LUA function.
9854 */
9855__LJMP static int hlua_register_action(lua_State *L)
9856{
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009857 struct action_kw_list *akl = NULL;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009858 const char *name;
9859 int ref;
9860 int len;
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009861 struct hlua_function *fcn = NULL;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009862 int nargs;
Thierry Fournierf67442e2020-11-28 20:41:07 +01009863 struct buffer *trash;
9864 struct action_kw *akw;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009865
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009866 /* Initialise the number of expected arguments at 0. */
9867 nargs = 0;
9868
9869 if (lua_gettop(L) < 3 || lua_gettop(L) > 4)
9870 WILL_LJMP(luaL_error(L, "'register_action' needs between 3 and 4 arguments"));
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009871
9872 /* First argument : converter name. */
9873 name = MAY_LJMP(luaL_checkstring(L, 1));
9874
9875 /* Second argument : environment. */
9876 if (lua_type(L, 2) != LUA_TTABLE)
9877 WILL_LJMP(luaL_error(L, "register_action: second argument must be a table of strings"));
9878
9879 /* Third argument : lua function. */
9880 ref = MAY_LJMP(hlua_checkfunction(L, 3));
9881
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08009882 /* Fourth argument : number of mandatory arguments expected on the configuration line. */
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009883 if (lua_gettop(L) >= 4)
9884 nargs = MAY_LJMP(luaL_checkinteger(L, 4));
9885
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08009886 /* browse the second argument as an array. */
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009887 lua_pushnil(L);
9888 while (lua_next(L, 2) != 0) {
9889 if (lua_type(L, -1) != LUA_TSTRING)
9890 WILL_LJMP(luaL_error(L, "register_action: second argument must be a table of strings"));
9891
Thierry Fournierf67442e2020-11-28 20:41:07 +01009892 /* Check if action exists */
9893 trash = get_trash_chunk();
9894 chunk_printf(trash, "lua.%s", name);
9895 if (strcmp(lua_tostring(L, -1), "tcp-req") == 0) {
9896 akw = tcp_req_cont_action(trash->area);
9897 } else if (strcmp(lua_tostring(L, -1), "tcp-res") == 0) {
9898 akw = tcp_res_cont_action(trash->area);
9899 } else if (strcmp(lua_tostring(L, -1), "http-req") == 0) {
9900 akw = action_http_req_custom(trash->area);
9901 } else if (strcmp(lua_tostring(L, -1), "http-res") == 0) {
9902 akw = action_http_res_custom(trash->area);
9903 } else {
9904 akw = NULL;
9905 }
9906 if (akw != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +01009907 fcn = akw->private;
9908 if (fcn->function_ref[hlua_state_id] != -1) {
9909 ha_warning("Trying to register action 'lua.%s' more than once. "
9910 "This will become a hard error in version 2.5.\n", name);
9911 }
9912 fcn->function_ref[hlua_state_id] = ref;
9913
9914 /* pop the environment string. */
9915 lua_pop(L, 1);
9916 continue;
Thierry Fournierf67442e2020-11-28 20:41:07 +01009917 }
9918
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009919 /* Check required environment. Only accepted "http" or "tcp". */
9920 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02009921 akl = calloc(1, sizeof(*akl) + sizeof(struct action_kw) * 2);
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009922 if (!akl)
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009923 goto alloc_error;;
Thierry Fournier62a22aa2020-11-28 21:06:35 +01009924 fcn = new_hlua_function();
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009925 if (!fcn)
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009926 goto alloc_error;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009927
9928 /* Fill fcn. */
9929 fcn->name = strdup(name);
9930 if (!fcn->name)
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009931 goto alloc_error;
Thierry Fournierc7492592020-11-28 23:57:24 +01009932 fcn->function_ref[hlua_state_id] = ref;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009933
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -07009934 /* Set the expected number of arguments. */
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009935 fcn->nargs = nargs;
9936
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009937 /* List head */
9938 akl->list.n = akl->list.p = NULL;
9939
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009940 /* action keyword. */
9941 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02009942 akl->kw[0].kw = calloc(1, len);
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009943 if (!akl->kw[0].kw)
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009944 goto alloc_error;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009945
9946 snprintf((char *)akl->kw[0].kw, len, "lua.%s", name);
9947
Amaury Denoyellee4a617c2021-05-06 15:33:09 +02009948 akl->kw[0].flags = 0;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009949 akl->kw[0].private = fcn;
9950 akl->kw[0].parse = action_register_lua;
9951
9952 /* select the action registering point. */
9953 if (strcmp(lua_tostring(L, -1), "tcp-req") == 0)
9954 tcp_req_cont_keywords_register(akl);
9955 else if (strcmp(lua_tostring(L, -1), "tcp-res") == 0)
9956 tcp_res_cont_keywords_register(akl);
9957 else if (strcmp(lua_tostring(L, -1), "http-req") == 0)
9958 http_req_keywords_register(akl);
9959 else if (strcmp(lua_tostring(L, -1), "http-res") == 0)
9960 http_res_keywords_register(akl);
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009961 else {
9962 release_hlua_function(fcn);
9963 if (akl)
9964 ha_free((char **)&(akl->kw[0].kw));
9965 ha_free(&akl);
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01009966 WILL_LJMP(luaL_error(L, "Lua action environment '%s' is unknown. "
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009967 "'tcp-req', 'tcp-res', 'http-req' or 'http-res' "
9968 "are expected.", lua_tostring(L, -1)));
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009969 }
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009970
9971 /* pop the environment string. */
9972 lua_pop(L, 1);
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009973
9974 /* reset for next loop */
9975 akl = NULL;
9976 fcn = NULL;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009977 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009978 return ACT_RET_PRS_OK;
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009979
9980 alloc_error:
9981 release_hlua_function(fcn);
9982 ha_free(&akl);
9983 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
9984 return 0; /* Never reached */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009985}
9986
9987static enum act_parse_ret action_register_service_tcp(const char **args, int *cur_arg, struct proxy *px,
9988 struct act_rule *rule, char **err)
9989{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02009990 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009991
Christopher Faulet280f85b2019-07-15 15:02:04 +02009992 if (px->mode == PR_MODE_HTTP) {
9993 memprintf(err, "Lua TCP services cannot be used on HTTP proxies");
Christopher Fauletafd8f102018-11-08 11:34:21 +01009994 return ACT_RET_PRS_ERR;
9995 }
9996
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009997 /* Memory for the rule. */
9998 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
9999 if (!rule->arg.hlua_rule) {
10000 memprintf(err, "out of memory error");
10001 return ACT_RET_PRS_ERR;
10002 }
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010003
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010004 /* Reference the Lua function and store the reference. */
Thierry Fournierad5345f2020-11-29 02:05:57 +010010005 rule->arg.hlua_rule->fcn = fcn;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010006
10007 /* TODO: later accept arguments. */
10008 rule->arg.hlua_rule->args = NULL;
10009
10010 /* Add applet pointer in the rule. */
10011 rule->applet.obj_type = OBJ_TYPE_APPLET;
10012 rule->applet.name = fcn->name;
10013 rule->applet.init = hlua_applet_tcp_init;
10014 rule->applet.fct = hlua_applet_tcp_fct;
10015 rule->applet.release = hlua_applet_tcp_release;
10016 rule->applet.timeout = hlua_timeout_applet;
10017
10018 return 0;
10019}
10020
10021/* This function is an LUA binding used for registering
10022 * "sample-conv" functions. It expects a converter name used
10023 * in the haproxy configuration file, and an LUA function.
10024 */
10025__LJMP static int hlua_register_service(lua_State *L)
10026{
10027 struct action_kw_list *akl;
10028 const char *name;
10029 const char *env;
10030 int ref;
10031 int len;
Christopher Faulet5c028d72021-04-12 15:11:44 +020010032 struct hlua_function *fcn = NULL;
Thierry Fournierf67442e2020-11-28 20:41:07 +010010033 struct buffer *trash;
10034 struct action_kw *akw;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010035
10036 MAY_LJMP(check_args(L, 3, "register_service"));
10037
10038 /* First argument : converter name. */
10039 name = MAY_LJMP(luaL_checkstring(L, 1));
10040
10041 /* Second argument : environment. */
10042 env = MAY_LJMP(luaL_checkstring(L, 2));
10043
10044 /* Third argument : lua function. */
10045 ref = MAY_LJMP(hlua_checkfunction(L, 3));
10046
Thierry Fournierf67442e2020-11-28 20:41:07 +010010047 /* Check for service already registered */
10048 trash = get_trash_chunk();
10049 chunk_printf(trash, "lua.%s", name);
10050 akw = service_find(trash->area);
10051 if (akw != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +010010052 fcn = akw->private;
10053 if (fcn->function_ref[hlua_state_id] != -1) {
10054 ha_warning("Trying to register service 'lua.%s' more than once. "
10055 "This will become a hard error in version 2.5.\n", name);
10056 }
10057 fcn->function_ref[hlua_state_id] = ref;
10058 return 0;
Thierry Fournierf67442e2020-11-28 20:41:07 +010010059 }
10060
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010061 /* Allocate and fill the sample fetch keyword struct. */
10062 akl = calloc(1, sizeof(*akl) + sizeof(struct action_kw) * 2);
10063 if (!akl)
Christopher Faulet5c028d72021-04-12 15:11:44 +020010064 goto alloc_error;
Thierry Fournier62a22aa2020-11-28 21:06:35 +010010065 fcn = new_hlua_function();
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010066 if (!fcn)
Christopher Faulet5c028d72021-04-12 15:11:44 +020010067 goto alloc_error;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010068
10069 /* Fill fcn. */
10070 len = strlen("<lua.>") + strlen(name) + 1;
10071 fcn->name = calloc(1, len);
10072 if (!fcn->name)
Christopher Faulet5c028d72021-04-12 15:11:44 +020010073 goto alloc_error;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010074 snprintf((char *)fcn->name, len, "<lua.%s>", name);
Thierry Fournierc7492592020-11-28 23:57:24 +010010075 fcn->function_ref[hlua_state_id] = ref;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010076
10077 /* List head */
10078 akl->list.n = akl->list.p = NULL;
10079
10080 /* converter keyword. */
10081 len = strlen("lua.") + strlen(name) + 1;
10082 akl->kw[0].kw = calloc(1, len);
10083 if (!akl->kw[0].kw)
Christopher Faulet5c028d72021-04-12 15:11:44 +020010084 goto alloc_error;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010085
10086 snprintf((char *)akl->kw[0].kw, len, "lua.%s", name);
10087
Thierry FOURNIER / OZON.IO02564fd2016-11-12 11:07:05 +010010088 /* Check required environment. Only accepted "http" or "tcp". */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010089 if (strcmp(env, "tcp") == 0)
10090 akl->kw[0].parse = action_register_service_tcp;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010091 else if (strcmp(env, "http") == 0)
10092 akl->kw[0].parse = action_register_service_http;
Christopher Faulet5c028d72021-04-12 15:11:44 +020010093 else {
10094 release_hlua_function(fcn);
10095 if (akl)
10096 ha_free((char **)&(akl->kw[0].kw));
10097 ha_free(&akl);
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +010010098 WILL_LJMP(luaL_error(L, "Lua service environment '%s' is unknown. "
Eric Salamafe7456f2017-12-21 14:30:07 +010010099 "'tcp' or 'http' are expected.", env));
Christopher Faulet5c028d72021-04-12 15:11:44 +020010100 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010101
Amaury Denoyellee4a617c2021-05-06 15:33:09 +020010102 akl->kw[0].flags = 0;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010103 akl->kw[0].private = fcn;
10104
10105 /* End of array. */
10106 memset(&akl->kw[1], 0, sizeof(*akl->kw));
10107
10108 /* Register this new converter */
10109 service_keywords_register(akl);
10110
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010111 return 0;
Christopher Faulet5c028d72021-04-12 15:11:44 +020010112
10113 alloc_error:
10114 release_hlua_function(fcn);
10115 ha_free(&akl);
10116 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
10117 return 0; /* Never reached */
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010118}
10119
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010120/* This function initialises Lua cli handler. It copies the
10121 * arguments in the Lua stack and create channel IO objects.
10122 */
Aurélien Nephtaliabbf6072018-04-18 13:26:46 +020010123static int hlua_cli_parse_fct(char **args, char *payload, struct appctx *appctx, void *private)
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010124{
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010125 struct hlua_cli_ctx *ctx = applet_reserve_svcctx(appctx, sizeof(*ctx));
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010126 struct hlua *hlua;
10127 struct hlua_function *fcn;
10128 int i;
10129 const char *error;
10130
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010131 fcn = private;
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010132 ctx->fcn = private;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +010010133
Willy Tarreaubafbe012017-11-24 17:34:44 +010010134 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +010010135 if (!hlua) {
10136 SEND_ERR(NULL, "Lua cli '%s': out of memory.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +010010137 return 1;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +010010138 }
10139 HLUA_INIT(hlua);
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010140 ctx->hlua = hlua;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010141
10142 /* Create task used by signal to wakeup applets.
Ilya Shipitsind4259502020-04-08 01:07:56 +050010143 * We use the same wakeup function than the Lua applet_tcp and
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010144 * applet_http. It is absolutely compatible.
10145 */
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010146 ctx->task = task_new_here();
10147 if (!ctx->task) {
Thierry FOURNIERffbf5692016-12-16 11:14:06 +010010148 SEND_ERR(NULL, "Lua cli '%s': out of memory.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +010010149 goto error;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010150 }
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010151 ctx->task->nice = 0;
10152 ctx->task->context = appctx;
10153 ctx->task->process = hlua_applet_wakeup;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010154
10155 /* Initialises the Lua context */
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010156 if (!hlua_ctx_init(hlua, fcn_ref_to_stack_id(fcn), ctx->task, 0)) {
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010157 SEND_ERR(NULL, "Lua cli '%s': can't initialize Lua context.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +010010158 goto error;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010159 }
10160
10161 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010162 if (!SET_SAFE_LJMP(hlua)) {
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010163 if (lua_type(hlua->T, -1) == LUA_TSTRING)
10164 error = lua_tostring(hlua->T, -1);
10165 else
10166 error = "critical error";
10167 SEND_ERR(NULL, "Lua cli '%s': %s.\n", fcn->name, error);
10168 goto error;
10169 }
10170
10171 /* Check stack available size. */
10172 if (!lua_checkstack(hlua->T, 2)) {
10173 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
10174 goto error;
10175 }
10176
10177 /* Restore the function in the stack. */
Thierry Fournierc7492592020-11-28 23:57:24 +010010178 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, fcn->function_ref[hlua->state_id]);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010179
10180 /* Once the arguments parsed, the CLI is like an AppletTCP,
10181 * so push AppletTCP in the stack.
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010182 */
10183 if (!hlua_applet_tcp_new(hlua->T, appctx)) {
10184 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
10185 goto error;
10186 }
10187 hlua->nargs = 1;
10188
10189 /* push keywords in the stack. */
10190 for (i = 0; *args[i]; i++) {
10191 /* Check stack available size. */
10192 if (!lua_checkstack(hlua->T, 1)) {
10193 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
10194 goto error;
10195 }
10196 lua_pushstring(hlua->T, args[i]);
10197 hlua->nargs++;
10198 }
10199
10200 /* We must initialize the execution timeouts. */
10201 hlua->max_time = hlua_timeout_session;
10202
10203 /* At this point the execution is safe. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010204 RESET_SAFE_LJMP(hlua);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010205
10206 /* It's ok */
10207 return 0;
10208
10209 /* It's not ok. */
10210error:
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010211 RESET_SAFE_LJMP(hlua);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010212 hlua_ctx_destroy(hlua);
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010213 ctx->hlua = NULL;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010214 return 1;
10215}
10216
10217static int hlua_cli_io_handler_fct(struct appctx *appctx)
10218{
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010219 struct hlua_cli_ctx *ctx = appctx->svcctx;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010220 struct hlua *hlua;
Willy Tarreau475e4632022-05-27 10:26:46 +020010221 struct stconn *sc;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010222 struct hlua_function *fcn;
10223
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010224 hlua = ctx->hlua;
Willy Tarreauc12b3212022-05-27 11:08:15 +020010225 sc = appctx_sc(appctx);
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010226 fcn = ctx->fcn;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010227
10228 /* If the stream is disconnect or closed, ldo nothing. */
Willy Tarreau475e4632022-05-27 10:26:46 +020010229 if (unlikely(sc->state == SC_ST_DIS || sc->state == SC_ST_CLO))
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010230 return 1;
10231
10232 /* Execute the function. */
10233 switch (hlua_ctx_resume(hlua, 1)) {
10234
10235 /* finished. */
10236 case HLUA_E_OK:
10237 return 1;
10238
10239 /* yield. */
10240 case HLUA_E_AGAIN:
10241 /* We want write. */
10242 if (HLUA_IS_WAKERESWR(hlua))
Willy Tarreau475e4632022-05-27 10:26:46 +020010243 sc_need_room(sc);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010244 /* Set the timeout. */
10245 if (hlua->wake_time != TICK_ETERNITY)
10246 task_schedule(hlua->task, hlua->wake_time);
10247 return 0;
10248
10249 /* finished with error. */
10250 case HLUA_E_ERRMSG:
10251 /* Display log. */
10252 SEND_ERR(NULL, "Lua cli '%s': %s.\n",
10253 fcn->name, lua_tostring(hlua->T, -1));
10254 lua_pop(hlua->T, 1);
10255 return 1;
10256
Thierry Fournierd5b073c2018-05-21 19:42:47 +020010257 case HLUA_E_ETMOUT:
10258 SEND_ERR(NULL, "Lua converter '%s': execution timeout.\n",
10259 fcn->name);
10260 return 1;
10261
10262 case HLUA_E_NOMEM:
10263 SEND_ERR(NULL, "Lua converter '%s': out of memory error.\n",
10264 fcn->name);
10265 return 1;
10266
10267 case HLUA_E_YIELD: /* unexpected */
10268 SEND_ERR(NULL, "Lua converter '%s': yield not allowed.\n",
10269 fcn->name);
10270 return 1;
10271
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010272 case HLUA_E_ERR:
10273 /* Display log. */
10274 SEND_ERR(NULL, "Lua cli '%s' return an unknown error.\n",
10275 fcn->name);
10276 return 1;
10277
10278 default:
10279 return 1;
10280 }
10281
10282 return 1;
10283}
10284
10285static void hlua_cli_io_release_fct(struct appctx *appctx)
10286{
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010287 struct hlua_cli_ctx *ctx = appctx->svcctx;
10288
10289 hlua_ctx_destroy(ctx->hlua);
10290 ctx->hlua = NULL;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010291}
10292
10293/* This function is an LUA binding used for registering
10294 * new keywords in the cli. It expects a list of keywords
10295 * which are the "path". It is limited to 5 keywords. A
10296 * description of the command, a function to be executed
10297 * for the parsing and a function for io handlers.
10298 */
10299__LJMP static int hlua_register_cli(lua_State *L)
10300{
10301 struct cli_kw_list *cli_kws;
10302 const char *message;
10303 int ref_io;
10304 int len;
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010305 struct hlua_function *fcn = NULL;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010306 int index;
10307 int i;
Thierry Fournierf67442e2020-11-28 20:41:07 +010010308 struct buffer *trash;
10309 const char *kw[5];
10310 struct cli_kw *cli_kw;
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010311 const char *errmsg;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010312
10313 MAY_LJMP(check_args(L, 3, "register_cli"));
10314
10315 /* First argument : an array of maximum 5 keywords. */
10316 if (!lua_istable(L, 1))
10317 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table"));
10318
10319 /* Second argument : string with contextual message. */
10320 message = MAY_LJMP(luaL_checkstring(L, 2));
10321
10322 /* Third and fourth argument : lua function. */
10323 ref_io = MAY_LJMP(hlua_checkfunction(L, 3));
10324
Thierry Fournierf67442e2020-11-28 20:41:07 +010010325 /* Check for CLI service already registered */
10326 trash = get_trash_chunk();
10327 index = 0;
10328 lua_pushnil(L);
10329 memset(kw, 0, sizeof(kw));
10330 while (lua_next(L, 1) != 0) {
10331 if (index >= CLI_PREFIX_KW_NB)
10332 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table with a maximum of 5 entries"));
10333 if (lua_type(L, -1) != LUA_TSTRING)
10334 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table filled with strings"));
10335 kw[index] = lua_tostring(L, -1);
10336 if (index == 0)
10337 chunk_printf(trash, "%s", kw[index]);
10338 else
10339 chunk_appendf(trash, " %s", kw[index]);
10340 index++;
10341 lua_pop(L, 1);
10342 }
10343 cli_kw = cli_find_kw_exact((char **)kw);
10344 if (cli_kw != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +010010345 fcn = cli_kw->private;
10346 if (fcn->function_ref[hlua_state_id] != -1) {
10347 ha_warning("Trying to register CLI keyword 'lua.%s' more than once. "
10348 "This will become a hard error in version 2.5.\n", trash->area);
10349 }
10350 fcn->function_ref[hlua_state_id] = ref_io;
10351 return 0;
Thierry Fournierf67442e2020-11-28 20:41:07 +010010352 }
10353
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010354 /* Allocate and fill the sample fetch keyword struct. */
10355 cli_kws = calloc(1, sizeof(*cli_kws) + sizeof(struct cli_kw) * 2);
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010356 if (!cli_kws) {
10357 errmsg = "Lua out of memory error.";
10358 goto error;
10359 }
Thierry Fournier62a22aa2020-11-28 21:06:35 +010010360 fcn = new_hlua_function();
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010361 if (!fcn) {
10362 errmsg = "Lua out of memory error.";
10363 goto error;
10364 }
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010365
10366 /* Fill path. */
10367 index = 0;
10368 lua_pushnil(L);
10369 while(lua_next(L, 1) != 0) {
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010370 if (index >= 5) {
10371 errmsg = "1st argument must be a table with a maximum of 5 entries";
10372 goto error;
10373 }
10374 if (lua_type(L, -1) != LUA_TSTRING) {
10375 errmsg = "1st argument must be a table filled with strings";
10376 goto error;
10377 }
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010378 cli_kws->kw[0].str_kw[index] = strdup(lua_tostring(L, -1));
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010379 if (!cli_kws->kw[0].str_kw[index]) {
10380 errmsg = "Lua out of memory error.";
10381 goto error;
10382 }
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010383 index++;
10384 lua_pop(L, 1);
10385 }
10386
10387 /* Copy help message. */
10388 cli_kws->kw[0].usage = strdup(message);
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010389 if (!cli_kws->kw[0].usage) {
10390 errmsg = "Lua out of memory error.";
10391 goto error;
10392 }
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010393
10394 /* Fill fcn io handler. */
10395 len = strlen("<lua.cli>") + 1;
10396 for (i = 0; i < index; i++)
10397 len += strlen(cli_kws->kw[0].str_kw[i]) + 1;
10398 fcn->name = calloc(1, len);
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010399 if (!fcn->name) {
10400 errmsg = "Lua out of memory error.";
10401 goto error;
10402 }
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010403 strncat((char *)fcn->name, "<lua.cli", len);
10404 for (i = 0; i < index; i++) {
10405 strncat((char *)fcn->name, ".", len);
10406 strncat((char *)fcn->name, cli_kws->kw[0].str_kw[i], len);
10407 }
10408 strncat((char *)fcn->name, ">", len);
Thierry Fournierc7492592020-11-28 23:57:24 +010010409 fcn->function_ref[hlua_state_id] = ref_io;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010410
10411 /* Fill last entries. */
10412 cli_kws->kw[0].private = fcn;
10413 cli_kws->kw[0].parse = hlua_cli_parse_fct;
10414 cli_kws->kw[0].io_handler = hlua_cli_io_handler_fct;
10415 cli_kws->kw[0].io_release = hlua_cli_io_release_fct;
10416
10417 /* Register this new converter */
10418 cli_register_kw(cli_kws);
10419
10420 return 0;
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010421
10422 error:
10423 release_hlua_function(fcn);
10424 if (cli_kws) {
10425 for (i = 0; i < index; i++)
10426 ha_free((char **)&(cli_kws->kw[0].str_kw[i]));
10427 ha_free((char **)&(cli_kws->kw[0].usage));
10428 }
10429 ha_free(&cli_kws);
10430 WILL_LJMP(luaL_error(L, errmsg));
10431 return 0; /* Never reached */
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010432}
10433
Christopher Faulet69c581a2021-05-31 08:54:04 +020010434static int hlua_filter_init_per_thread(struct proxy *px, struct flt_conf *fconf)
10435{
10436 struct hlua_flt_config *conf = fconf->conf;
10437 lua_State *L;
10438 int error, pos, state_id, flt_ref;
10439
10440 state_id = reg_flt_to_stack_id(conf->reg);
10441 L = hlua_states[state_id];
10442 pos = lua_gettop(L);
10443
10444 /* The filter parsing function */
10445 lua_rawgeti(L, LUA_REGISTRYINDEX, conf->reg->fun_ref[state_id]);
10446
10447 /* Push the filter class on the stack and resolve all callbacks */
10448 lua_rawgeti(L, LUA_REGISTRYINDEX, conf->reg->flt_ref[state_id]);
10449
10450 /* Duplicate the filter class so each filter will have its own copy */
10451 lua_newtable(L);
10452 lua_pushnil(L);
10453
10454 while (lua_next(L, pos+2)) {
10455 lua_pushvalue(L, -2);
10456 lua_insert(L, -2);
10457 lua_settable(L, -4);
10458 }
10459 flt_ref = luaL_ref(L, LUA_REGISTRYINDEX);
10460
10461 /* Remove the original lua filter class from the stack */
10462 lua_pop(L, 1);
10463
10464 /* Push the copy on the stack */
10465 lua_rawgeti(L, LUA_REGISTRYINDEX, flt_ref);
10466
10467 /* extra args are pushed in a table */
10468 lua_newtable(L);
10469 for (pos = 0; conf->args[pos]; pos++) {
10470 /* Check stack available size. */
10471 if (!lua_checkstack(L, 1)) {
10472 ha_alert("Lua filter '%s' : Lua error : full stack.", conf->reg->name);
10473 goto error;
10474 }
10475 lua_pushstring(L, conf->args[pos]);
10476 lua_rawseti(L, -2, lua_rawlen(L, -2) + 1);
10477 }
10478
10479 error = lua_pcall(L, 2, LUA_MULTRET, 0);
10480 switch (error) {
10481 case LUA_OK:
10482 /* replace the filter ref */
10483 conf->ref[state_id] = flt_ref;
10484 break;
10485 case LUA_ERRRUN:
10486 ha_alert("Lua filter '%s' : runtime error : %s", conf->reg->name, lua_tostring(L, -1));
10487 goto error;
10488 case LUA_ERRMEM:
10489 ha_alert("Lua filter '%s' : out of memory error", conf->reg->name);
10490 goto error;
10491 case LUA_ERRERR:
10492 ha_alert("Lua filter '%s' : message handler error : %s", conf->reg->name, lua_tostring(L, -1));
10493 goto error;
10494#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM <= 503
10495 case LUA_ERRGCMM:
10496 ha_alert("Lua filter '%s' : garbage collector error : %s", conf->reg->name, lua_tostring(L, -1));
10497 goto error;
10498#endif
10499 default:
Ilya Shipitsinff0f2782021-08-22 22:18:07 +050010500 ha_alert("Lua filter '%s' : unknown error : %s", conf->reg->name, lua_tostring(L, -1));
Christopher Faulet69c581a2021-05-31 08:54:04 +020010501 goto error;
10502 }
10503
10504 lua_settop(L, 0);
10505 return 0;
10506
10507 error:
10508 lua_settop(L, 0);
10509 return -1;
10510}
10511
10512static void hlua_filter_deinit_per_thread(struct proxy *px, struct flt_conf *fconf)
10513{
10514 struct hlua_flt_config *conf = fconf->conf;
10515 lua_State *L;
10516 int state_id;
10517
10518 if (!conf)
10519 return;
10520
10521 state_id = reg_flt_to_stack_id(conf->reg);
10522 L = hlua_states[state_id];
10523 luaL_unref(L, LUA_REGISTRYINDEX, conf->ref[state_id]);
10524}
10525
10526static int hlua_filter_init(struct proxy *px, struct flt_conf *fconf)
10527{
10528 struct hlua_flt_config *conf = fconf->conf;
10529 int state_id = reg_flt_to_stack_id(conf->reg);
10530
10531 /* Rely on per-thread init for global scripts */
10532 if (!state_id)
10533 return hlua_filter_init_per_thread(px, fconf);
10534 return 0;
10535}
10536
10537static void hlua_filter_deinit(struct proxy *px, struct flt_conf *fconf)
10538{
10539
10540 if (fconf->conf) {
10541 struct hlua_flt_config *conf = fconf->conf;
10542 int state_id = reg_flt_to_stack_id(conf->reg);
10543 int pos;
10544
10545 /* Rely on per-thread deinit for global scripts */
10546 if (!state_id)
10547 hlua_filter_deinit_per_thread(px, fconf);
10548
10549 for (pos = 0; conf->args[pos]; pos++)
10550 free(conf->args[pos]);
10551 free(conf->args);
10552 }
10553 ha_free(&fconf->conf);
10554 ha_free((char **)&fconf->id);
10555 ha_free(&fconf->ops);
10556}
10557
10558static int hlua_filter_new(struct stream *s, struct filter *filter)
10559{
10560 struct hlua_flt_config *conf = FLT_CONF(filter);
10561 struct hlua_flt_ctx *flt_ctx = NULL;
10562 int ret = 1;
10563
10564 /* In the execution wrappers linked with a stream, the
10565 * Lua context can be not initialized. This behavior
10566 * permits to save performances because a systematic
10567 * Lua initialization cause 5% performances loss.
10568 */
10569 if (!s->hlua) {
10570 struct hlua *hlua;
10571
10572 hlua = pool_alloc(pool_head_hlua);
10573 if (!hlua) {
10574 SEND_ERR(s->be, "Lua filter '%s': can't initialize Lua context.\n",
10575 conf->reg->name);
10576 ret = 0;
10577 goto end;
10578 }
10579 HLUA_INIT(hlua);
10580 s->hlua = hlua;
10581 if (!hlua_ctx_init(s->hlua, reg_flt_to_stack_id(conf->reg), s->task, 0)) {
10582 SEND_ERR(s->be, "Lua filter '%s': can't initialize Lua context.\n",
10583 conf->reg->name);
10584 ret = 0;
10585 goto end;
10586 }
10587 }
10588
10589 flt_ctx = pool_zalloc(pool_head_hlua_flt_ctx);
10590 if (!flt_ctx) {
10591 SEND_ERR(s->be, "Lua filter '%s': can't initialize filter Lua context.\n",
10592 conf->reg->name);
10593 ret = 0;
10594 goto end;
10595 }
10596 flt_ctx->hlua[0] = pool_alloc(pool_head_hlua);
10597 flt_ctx->hlua[1] = pool_alloc(pool_head_hlua);
10598 if (!flt_ctx->hlua[0] || !flt_ctx->hlua[1]) {
10599 SEND_ERR(s->be, "Lua filter '%s': can't initialize filter Lua context.\n",
10600 conf->reg->name);
10601 ret = 0;
10602 goto end;
10603 }
10604 HLUA_INIT(flt_ctx->hlua[0]);
10605 HLUA_INIT(flt_ctx->hlua[1]);
10606 if (!hlua_ctx_init(flt_ctx->hlua[0], reg_flt_to_stack_id(conf->reg), s->task, 0) ||
10607 !hlua_ctx_init(flt_ctx->hlua[1], reg_flt_to_stack_id(conf->reg), s->task, 0)) {
10608 SEND_ERR(s->be, "Lua filter '%s': can't initialize filter Lua context.\n",
10609 conf->reg->name);
10610 ret = 0;
10611 goto end;
10612 }
10613
10614 if (!HLUA_IS_RUNNING(s->hlua)) {
10615 /* The following Lua calls can fail. */
10616 if (!SET_SAFE_LJMP(s->hlua)) {
10617 const char *error;
10618
10619 if (lua_type(s->hlua->T, -1) == LUA_TSTRING)
10620 error = lua_tostring(s->hlua->T, -1);
10621 else
10622 error = "critical error";
10623 SEND_ERR(s->be, "Lua filter '%s': %s.\n", conf->reg->name, error);
10624 ret = 0;
10625 goto end;
10626 }
10627
10628 /* Check stack size. */
10629 if (!lua_checkstack(s->hlua->T, 1)) {
10630 SEND_ERR(s->be, "Lua filter '%s': full stack.\n", conf->reg->name);
Tim Duesterhus22817382021-09-11 23:17:25 +020010631 RESET_SAFE_LJMP(s->hlua);
Christopher Faulet69c581a2021-05-31 08:54:04 +020010632 ret = 0;
10633 goto end;
10634 }
10635
10636 lua_rawgeti(s->hlua->T, LUA_REGISTRYINDEX, conf->ref[s->hlua->state_id]);
10637 if (lua_getfield(s->hlua->T, -1, "new") != LUA_TFUNCTION) {
10638 SEND_ERR(s->be, "Lua filter '%s': 'new' field is not a function.\n",
10639 conf->reg->name);
10640 RESET_SAFE_LJMP(s->hlua);
10641 ret = 0;
10642 goto end;
10643 }
10644 lua_insert(s->hlua->T, -2);
10645
10646 /* Push the copy on the stack */
10647 s->hlua->nargs = 1;
10648
10649 /* We must initialize the execution timeouts. */
10650 s->hlua->max_time = hlua_timeout_session;
10651
10652 /* At this point the execution is safe. */
10653 RESET_SAFE_LJMP(s->hlua);
10654 }
10655
10656 switch (hlua_ctx_resume(s->hlua, 0)) {
10657 case HLUA_E_OK:
10658 /* Nothing returned or not a table, ignore the filter for current stream */
10659 if (!lua_gettop(s->hlua->T) || !lua_istable(s->hlua->T, 1)) {
10660 ret = 0;
10661 goto end;
10662 }
10663
10664 /* Attached the filter pointer to the ctx */
10665 lua_pushstring(s->hlua->T, "__filter");
10666 lua_pushlightuserdata(s->hlua->T, filter);
10667 lua_settable(s->hlua->T, -3);
10668
10669 /* Save a ref on the filter ctx */
10670 lua_pushvalue(s->hlua->T, 1);
10671 flt_ctx->ref = luaL_ref(s->hlua->T, LUA_REGISTRYINDEX);
10672 filter->ctx = flt_ctx;
10673 break;
10674 case HLUA_E_ERRMSG:
10675 SEND_ERR(s->be, "Lua filter '%s' : %s.\n", conf->reg->name, lua_tostring(s->hlua->T, -1));
10676 ret = -1;
10677 goto end;
10678 case HLUA_E_ETMOUT:
10679 SEND_ERR(s->be, "Lua filter '%s' : 'new' execution timeout.\n", conf->reg->name);
10680 ret = 0;
10681 goto end;
10682 case HLUA_E_NOMEM:
10683 SEND_ERR(s->be, "Lua filter '%s' : out of memory error.\n", conf->reg->name);
10684 ret = 0;
10685 goto end;
10686 case HLUA_E_AGAIN:
10687 case HLUA_E_YIELD:
10688 SEND_ERR(s->be, "Lua filter '%s': yield functions like core.tcp() or core.sleep()"
10689 " are not allowed from 'new' function.\n", conf->reg->name);
10690 ret = 0;
10691 goto end;
10692 case HLUA_E_ERR:
10693 SEND_ERR(s->be, "Lua filter '%s': 'new' returns an unknown error.\n", conf->reg->name);
10694 ret = 0;
10695 goto end;
10696 default:
10697 ret = 0;
10698 goto end;
10699 }
10700
10701 end:
10702 if (s->hlua)
10703 lua_settop(s->hlua->T, 0);
10704 if (ret <= 0) {
10705 if (flt_ctx) {
10706 hlua_ctx_destroy(flt_ctx->hlua[0]);
10707 hlua_ctx_destroy(flt_ctx->hlua[1]);
10708 pool_free(pool_head_hlua_flt_ctx, flt_ctx);
10709 }
10710 }
10711 return ret;
10712}
10713
10714static void hlua_filter_delete(struct stream *s, struct filter *filter)
10715{
10716 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10717
10718 luaL_unref(s->hlua->T, LUA_REGISTRYINDEX, flt_ctx->ref);
10719 hlua_ctx_destroy(flt_ctx->hlua[0]);
10720 hlua_ctx_destroy(flt_ctx->hlua[1]);
10721 pool_free(pool_head_hlua_flt_ctx, flt_ctx);
10722 filter->ctx = NULL;
10723}
10724
Christopher Faulet9f55a502020-02-25 15:21:02 +010010725static int hlua_filter_from_payload(struct filter *filter)
10726{
10727 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10728
10729 return (flt_ctx && !!(flt_ctx->flags & HLUA_FLT_CTX_FL_PAYLOAD));
10730}
10731
Christopher Fauletc404f112020-02-26 15:03:09 +010010732static int hlua_filter_callback(struct stream *s, struct filter *filter, const char *fun,
10733 int dir, unsigned int flags)
10734{
10735 struct hlua *flt_hlua;
10736 struct hlua_flt_config *conf = FLT_CONF(filter);
10737 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10738 unsigned int hflags = HLUA_TXN_FLT_CTX;
10739 int ret = 1;
10740
10741 flt_hlua = flt_ctx->hlua[(dir == SMP_OPT_DIR_REQ ? 0 : 1)];
10742 if (!flt_hlua)
10743 goto end;
10744
10745 if (!HLUA_IS_RUNNING(flt_hlua)) {
10746 int extra_idx = lua_gettop(flt_hlua->T);
10747
10748 /* The following Lua calls can fail. */
10749 if (!SET_SAFE_LJMP(flt_hlua)) {
10750 const char *error;
10751
10752 if (lua_type(flt_hlua->T, -1) == LUA_TSTRING)
10753 error = lua_tostring(flt_hlua->T, -1);
10754 else
10755 error = "critical error";
10756 SEND_ERR(s->be, "Lua filter '%s': %s.\n", conf->reg->name, error);
10757 goto end;
10758 }
10759
10760 /* Check stack size. */
10761 if (!lua_checkstack(flt_hlua->T, 3)) {
10762 SEND_ERR(s->be, "Lua filter '%s': full stack.\n", conf->reg->name);
10763 RESET_SAFE_LJMP(flt_hlua);
10764 goto end;
10765 }
10766
10767 lua_rawgeti(flt_hlua->T, LUA_REGISTRYINDEX, flt_ctx->ref);
10768 if (lua_getfield(flt_hlua->T, -1, fun) != LUA_TFUNCTION) {
10769 RESET_SAFE_LJMP(flt_hlua);
10770 goto end;
10771 }
10772 lua_insert(flt_hlua->T, -2);
10773
10774 if (!hlua_txn_new(flt_hlua->T, s, s->be, dir, hflags)) {
10775 SEND_ERR(s->be, "Lua filter '%s': full stack.\n", conf->reg->name);
10776 RESET_SAFE_LJMP(flt_hlua);
10777 goto end;
10778 }
10779 flt_hlua->nargs = 2;
10780
10781 if (flags & HLUA_FLT_CB_ARG_CHN) {
10782 if (dir == SMP_OPT_DIR_REQ)
10783 lua_getfield(flt_hlua->T, -1, "req");
10784 else
10785 lua_getfield(flt_hlua->T, -1, "res");
10786 if (lua_type(flt_hlua->T, -1) == LUA_TTABLE) {
10787 lua_pushstring(flt_hlua->T, "__filter");
10788 lua_pushlightuserdata(flt_hlua->T, filter);
10789 lua_settable(flt_hlua->T, -3);
10790 }
10791 flt_hlua->nargs++;
10792 }
10793 else if (flags & HLUA_FLT_CB_ARG_HTTP_MSG) {
Christopher Fauleteae8afa2020-02-26 17:15:48 +010010794 if (dir == SMP_OPT_DIR_REQ)
10795 lua_getfield(flt_hlua->T, -1, "http_req");
10796 else
10797 lua_getfield(flt_hlua->T, -1, "http_res");
10798 if (lua_type(flt_hlua->T, -1) == LUA_TTABLE) {
10799 lua_pushstring(flt_hlua->T, "__filter");
10800 lua_pushlightuserdata(flt_hlua->T, filter);
10801 lua_settable(flt_hlua->T, -3);
10802 }
10803 flt_hlua->nargs++;
Christopher Fauletc404f112020-02-26 15:03:09 +010010804 }
10805
10806 /* Check stack size. */
10807 if (!lua_checkstack(flt_hlua->T, 1)) {
10808 SEND_ERR(s->be, "Lua filter '%s': full stack.\n", conf->reg->name);
10809 RESET_SAFE_LJMP(flt_hlua);
10810 goto end;
10811 }
10812
10813 while (extra_idx--) {
10814 lua_pushvalue(flt_hlua->T, 1);
10815 lua_remove(flt_hlua->T, 1);
10816 flt_hlua->nargs++;
10817 }
10818
10819 /* We must initialize the execution timeouts. */
10820 flt_hlua->max_time = hlua_timeout_session;
10821
10822 /* At this point the execution is safe. */
10823 RESET_SAFE_LJMP(flt_hlua);
10824 }
10825
10826 switch (hlua_ctx_resume(flt_hlua, !(flags & HLUA_FLT_CB_FINAL))) {
10827 case HLUA_E_OK:
10828 /* Catch the return value if it required */
10829 if ((flags & HLUA_FLT_CB_RETVAL) && lua_gettop(flt_hlua->T) > 0) {
10830 ret = lua_tointeger(flt_hlua->T, -1);
10831 lua_settop(flt_hlua->T, 0); /* Empty the stack. */
10832 }
10833
10834 /* Set timeout in the required channel. */
10835 if (flt_hlua->wake_time != TICK_ETERNITY) {
10836 if (dir == SMP_OPT_DIR_REQ)
10837 s->req.analyse_exp = flt_hlua->wake_time;
10838 else
10839 s->res.analyse_exp = flt_hlua->wake_time;
10840 }
10841 break;
10842 case HLUA_E_AGAIN:
10843 /* Set timeout in the required channel. */
10844 if (flt_hlua->wake_time != TICK_ETERNITY) {
10845 if (dir == SMP_OPT_DIR_REQ)
10846 s->req.analyse_exp = flt_hlua->wake_time;
10847 else
10848 s->res.analyse_exp = flt_hlua->wake_time;
10849 }
10850 /* Some actions can be wake up when a "write" event
10851 * is detected on a response channel. This is useful
10852 * only for actions targeted on the requests.
10853 */
10854 if (HLUA_IS_WAKERESWR(flt_hlua))
10855 s->res.flags |= CF_WAKE_WRITE;
10856 if (HLUA_IS_WAKEREQWR(flt_hlua))
10857 s->req.flags |= CF_WAKE_WRITE;
10858 ret = 0;
10859 goto end;
10860 case HLUA_E_ERRMSG:
10861 SEND_ERR(s->be, "Lua filter '%s' : %s.\n", conf->reg->name, lua_tostring(flt_hlua->T, -1));
10862 ret = -1;
10863 goto end;
10864 case HLUA_E_ETMOUT:
10865 SEND_ERR(s->be, "Lua filter '%s' : '%s' callback execution timeout.\n", conf->reg->name, fun);
10866 goto end;
10867 case HLUA_E_NOMEM:
10868 SEND_ERR(s->be, "Lua filter '%s' : out of memory error.\n", conf->reg->name);
10869 goto end;
10870 case HLUA_E_YIELD:
10871 SEND_ERR(s->be, "Lua filter '%s': yield functions like core.tcp() or core.sleep()"
10872 " are not allowed from '%s' callback.\n", conf->reg->name, fun);
10873 goto end;
10874 case HLUA_E_ERR:
10875 SEND_ERR(s->be, "Lua filter '%s': '%s' returns an unknown error.\n", conf->reg->name, fun);
10876 goto end;
10877 default:
10878 goto end;
10879 }
10880
10881
10882 end:
10883 return ret;
10884}
10885
10886static int hlua_filter_start_analyze(struct stream *s, struct filter *filter, struct channel *chn)
10887{
10888 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10889
10890 flt_ctx->flags = 0;
10891 return hlua_filter_callback(s, filter, "start_analyze",
10892 (!(chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES),
10893 (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_RETVAL | HLUA_FLT_CB_ARG_CHN));
10894}
10895
10896static int hlua_filter_end_analyze(struct stream *s, struct filter *filter, struct channel *chn)
10897{
10898 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10899
10900 flt_ctx->flags &= ~HLUA_FLT_CTX_FL_PAYLOAD;
10901 return hlua_filter_callback(s, filter, "end_analyze",
10902 (!(chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES),
10903 (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_RETVAL | HLUA_FLT_CB_ARG_CHN));
10904}
10905
Christopher Fauleteae8afa2020-02-26 17:15:48 +010010906static int hlua_filter_http_headers(struct stream *s, struct filter *filter, struct http_msg *msg)
10907{
10908 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10909
10910 flt_ctx->flags &= ~HLUA_FLT_CTX_FL_PAYLOAD;
10911 return hlua_filter_callback(s, filter, "http_headers",
10912 (!(msg->chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES),
10913 (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_RETVAL | HLUA_FLT_CB_ARG_HTTP_MSG));
10914}
10915
10916static int hlua_filter_http_payload(struct stream *s, struct filter *filter, struct http_msg *msg,
10917 unsigned int offset, unsigned int len)
10918{
10919 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10920 struct hlua *flt_hlua;
10921 int dir = (!(msg->chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES);
10922 int idx = (dir == SMP_OPT_DIR_REQ ? 0 : 1);
10923 int ret;
10924
10925 flt_hlua = flt_ctx->hlua[idx];
10926 flt_ctx->cur_off[idx] = offset;
10927 flt_ctx->cur_len[idx] = len;
10928 flt_ctx->flags |= HLUA_FLT_CTX_FL_PAYLOAD;
10929 ret = hlua_filter_callback(s, filter, "http_payload", dir, (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_ARG_HTTP_MSG));
10930 if (ret != -1) {
10931 ret = flt_ctx->cur_len[idx];
10932 if (lua_gettop(flt_hlua->T) > 0) {
10933 ret = lua_tointeger(flt_hlua->T, -1);
10934 if (ret > flt_ctx->cur_len[idx])
10935 ret = flt_ctx->cur_len[idx];
10936 lua_settop(flt_hlua->T, 0); /* Empty the stack. */
10937 }
10938 }
10939 return ret;
10940}
10941
10942static int hlua_filter_http_end(struct stream *s, struct filter *filter, struct http_msg *msg)
10943{
10944 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10945
10946 flt_ctx->flags &= ~HLUA_FLT_CTX_FL_PAYLOAD;
10947 return hlua_filter_callback(s, filter, "http_end",
10948 (!(msg->chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES),
10949 (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_RETVAL | HLUA_FLT_CB_ARG_HTTP_MSG));
10950}
10951
Christopher Fauletc404f112020-02-26 15:03:09 +010010952static int hlua_filter_tcp_payload(struct stream *s, struct filter *filter, struct channel *chn,
10953 unsigned int offset, unsigned int len)
10954{
10955 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10956 struct hlua *flt_hlua;
10957 int dir = (!(chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES);
10958 int idx = (dir == SMP_OPT_DIR_REQ ? 0 : 1);
10959 int ret;
10960
10961 flt_hlua = flt_ctx->hlua[idx];
10962 flt_ctx->cur_off[idx] = offset;
10963 flt_ctx->cur_len[idx] = len;
10964 flt_ctx->flags |= HLUA_FLT_CTX_FL_PAYLOAD;
10965 ret = hlua_filter_callback(s, filter, "tcp_payload", dir, (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_ARG_CHN));
10966 if (ret != -1) {
10967 ret = flt_ctx->cur_len[idx];
10968 if (lua_gettop(flt_hlua->T) > 0) {
10969 ret = lua_tointeger(flt_hlua->T, -1);
10970 if (ret > flt_ctx->cur_len[idx])
10971 ret = flt_ctx->cur_len[idx];
10972 lua_settop(flt_hlua->T, 0); /* Empty the stack. */
10973 }
10974 }
10975 return ret;
10976}
10977
Christopher Faulet69c581a2021-05-31 08:54:04 +020010978static int hlua_filter_parse_fct(char **args, int *cur_arg, struct proxy *px,
10979 struct flt_conf *fconf, char **err, void *private)
10980{
10981 struct hlua_reg_filter *reg_flt = private;
10982 lua_State *L;
10983 struct hlua_flt_config *conf = NULL;
10984 const char *flt_id = NULL;
10985 int state_id, pos, flt_flags = 0;
10986 struct flt_ops *hlua_flt_ops = NULL;
10987
10988 state_id = reg_flt_to_stack_id(reg_flt);
10989 L = hlua_states[state_id];
10990
10991 /* Initialize the filter ops with default callbacks */
10992 hlua_flt_ops = calloc(1, sizeof(*hlua_flt_ops));
Christopher Fauletc86bb872021-08-13 08:33:57 +020010993 if (!hlua_flt_ops)
10994 goto error;
Christopher Faulet69c581a2021-05-31 08:54:04 +020010995 hlua_flt_ops->init = hlua_filter_init;
10996 hlua_flt_ops->deinit = hlua_filter_deinit;
10997 if (state_id) {
10998 /* Set per-thread callback if script is loaded per-thread */
10999 hlua_flt_ops->init_per_thread = hlua_filter_init_per_thread;
11000 hlua_flt_ops->deinit_per_thread = hlua_filter_deinit_per_thread;
11001 }
11002 hlua_flt_ops->attach = hlua_filter_new;
11003 hlua_flt_ops->detach = hlua_filter_delete;
11004
11005 /* Push the filter class on the stack and resolve all callbacks */
11006 lua_rawgeti(L, LUA_REGISTRYINDEX, reg_flt->flt_ref[state_id]);
11007
Christopher Fauletc404f112020-02-26 15:03:09 +010011008 if (lua_getfield(L, -1, "start_analyze") == LUA_TFUNCTION)
11009 hlua_flt_ops->channel_start_analyze = hlua_filter_start_analyze;
11010 lua_pop(L, 1);
11011 if (lua_getfield(L, -1, "end_analyze") == LUA_TFUNCTION)
11012 hlua_flt_ops->channel_end_analyze = hlua_filter_end_analyze;
11013 lua_pop(L, 1);
Christopher Fauleteae8afa2020-02-26 17:15:48 +010011014 if (lua_getfield(L, -1, "http_headers") == LUA_TFUNCTION)
11015 hlua_flt_ops->http_headers = hlua_filter_http_headers;
11016 lua_pop(L, 1);
11017 if (lua_getfield(L, -1, "http_payload") == LUA_TFUNCTION)
11018 hlua_flt_ops->http_payload = hlua_filter_http_payload;
11019 lua_pop(L, 1);
11020 if (lua_getfield(L, -1, "http_end") == LUA_TFUNCTION)
11021 hlua_flt_ops->http_end = hlua_filter_http_end;
11022 lua_pop(L, 1);
Christopher Fauletc404f112020-02-26 15:03:09 +010011023 if (lua_getfield(L, -1, "tcp_payload") == LUA_TFUNCTION)
11024 hlua_flt_ops->tcp_payload = hlua_filter_tcp_payload;
11025 lua_pop(L, 1);
Christopher Faulet69c581a2021-05-31 08:54:04 +020011026
11027 /* Get id and flags of the filter class */
11028 if (lua_getfield(L, -1, "id") == LUA_TSTRING)
11029 flt_id = lua_tostring(L, -1);
11030 lua_pop(L, 1);
11031 if (lua_getfield(L, -1, "flags") == LUA_TNUMBER)
11032 flt_flags = lua_tointeger(L, -1);
11033 lua_pop(L, 1);
11034
11035 /* Create the filter config */
11036 conf = calloc(1, sizeof(*conf));
Christopher Fauletc86bb872021-08-13 08:33:57 +020011037 if (!conf)
Christopher Faulet69c581a2021-05-31 08:54:04 +020011038 goto error;
Christopher Faulet69c581a2021-05-31 08:54:04 +020011039 conf->reg = reg_flt;
11040
11041 /* duplicate args */
11042 for (pos = 0; *args[*cur_arg + 1 + pos]; pos++);
11043 conf->args = calloc(pos + 1, sizeof(*conf->args));
Christopher Fauletc86bb872021-08-13 08:33:57 +020011044 if (!conf->args)
11045 goto error;
11046 for (pos = 0; *args[*cur_arg + 1 + pos]; pos++) {
Christopher Faulet69c581a2021-05-31 08:54:04 +020011047 conf->args[pos] = strdup(args[*cur_arg + 1 + pos]);
Christopher Fauletc86bb872021-08-13 08:33:57 +020011048 if (!conf->args[pos])
11049 goto error;
11050 }
Christopher Faulet69c581a2021-05-31 08:54:04 +020011051 conf->args[pos] = NULL;
11052 *cur_arg += pos + 1;
11053
Christopher Fauletc86bb872021-08-13 08:33:57 +020011054 if (flt_id) {
11055 fconf->id = strdup(flt_id);
11056 if (!fconf->id)
11057 goto error;
11058 }
Christopher Faulet69c581a2021-05-31 08:54:04 +020011059 fconf->flags = flt_flags;
11060 fconf->conf = conf;
11061 fconf->ops = hlua_flt_ops;
11062
11063 lua_settop(L, 0);
11064 return 0;
11065
11066 error:
Christopher Fauletc86bb872021-08-13 08:33:57 +020011067 memprintf(err, "Lua filter '%s' : Lua out of memory error", reg_flt->name);
Christopher Faulet69c581a2021-05-31 08:54:04 +020011068 free(hlua_flt_ops);
Christopher Fauletc86bb872021-08-13 08:33:57 +020011069 if (conf && conf->args) {
11070 for (pos = 0; conf->args[pos]; pos++)
11071 free(conf->args[pos]);
11072 free(conf->args);
11073 }
Christopher Faulet69c581a2021-05-31 08:54:04 +020011074 free(conf);
Christopher Fauletc86bb872021-08-13 08:33:57 +020011075 free((char *)fconf->id);
Christopher Faulet69c581a2021-05-31 08:54:04 +020011076 lua_settop(L, 0);
11077 return -1;
11078}
11079
Christopher Fauletc404f112020-02-26 15:03:09 +010011080__LJMP static int hlua_register_data_filter(lua_State *L)
11081{
11082 struct filter *filter;
11083 struct channel *chn;
11084
11085 MAY_LJMP(check_args(L, 2, "register_data_filter"));
11086 MAY_LJMP(luaL_checktype(L, 1, LUA_TTABLE));
11087 chn = MAY_LJMP(hlua_checkchannel(L, 2));
11088
11089 lua_getfield(L, 1, "__filter");
11090 MAY_LJMP(luaL_checktype(L, -1, LUA_TLIGHTUSERDATA));
11091 filter = lua_touserdata (L, -1);
11092 lua_pop(L, 1);
11093
11094 register_data_filter(chn_strm(chn), chn, filter);
11095 return 1;
11096}
11097
11098__LJMP static int hlua_unregister_data_filter(lua_State *L)
11099{
11100 struct filter *filter;
11101 struct channel *chn;
11102
11103 MAY_LJMP(check_args(L, 2, "unregister_data_filter"));
11104 MAY_LJMP(luaL_checktype(L, 1, LUA_TTABLE));
11105 chn = MAY_LJMP(hlua_checkchannel(L, 2));
11106
11107 lua_getfield(L, 1, "__filter");
11108 MAY_LJMP(luaL_checktype(L, -1, LUA_TLIGHTUSERDATA));
11109 filter = lua_touserdata (L, -1);
11110 lua_pop(L, 1);
11111
11112 unregister_data_filter(chn_strm(chn), chn, filter);
11113 return 1;
11114}
11115
Christopher Faulet69c581a2021-05-31 08:54:04 +020011116/* This function is an LUA binding used for registering a filter. It expects a
Ilya Shipitsinff0f2782021-08-22 22:18:07 +050011117 * filter name used in the haproxy configuration file and a LUA function to
Christopher Faulet69c581a2021-05-31 08:54:04 +020011118 * parse configuration arguments.
11119 */
11120__LJMP static int hlua_register_filter(lua_State *L)
11121{
11122 struct buffer *trash;
11123 struct flt_kw_list *fkl;
11124 struct flt_kw *fkw;
11125 const char *name;
11126 struct hlua_reg_filter *reg_flt= NULL;
11127 int flt_ref, fun_ref;
11128 int len;
11129
11130 MAY_LJMP(check_args(L, 3, "register_filter"));
11131
11132 /* First argument : filter name. */
11133 name = MAY_LJMP(luaL_checkstring(L, 1));
11134
11135 /* Second argument : The filter class */
11136 flt_ref = MAY_LJMP(hlua_checktable(L, 2));
11137
11138 /* Third argument : lua function. */
11139 fun_ref = MAY_LJMP(hlua_checkfunction(L, 3));
11140
11141 trash = get_trash_chunk();
11142 chunk_printf(trash, "lua.%s", name);
11143 fkw = flt_find_kw(trash->area);
11144 if (fkw != NULL) {
11145 reg_flt = fkw->private;
11146 if (reg_flt->flt_ref[hlua_state_id] != -1 || reg_flt->fun_ref[hlua_state_id] != -1) {
11147 ha_warning("Trying to register filter 'lua.%s' more than once. "
11148 "This will become a hard error in version 2.5.\n", name);
11149 }
11150 reg_flt->flt_ref[hlua_state_id] = flt_ref;
11151 reg_flt->fun_ref[hlua_state_id] = fun_ref;
11152 return 0;
11153 }
11154
11155 fkl = calloc(1, sizeof(*fkl) + sizeof(struct flt_kw) * 2);
11156 if (!fkl)
11157 goto alloc_error;
11158 fkl->scope = "HLUA";
11159
11160 reg_flt = new_hlua_reg_filter(name);
11161 if (!reg_flt)
11162 goto alloc_error;
11163
11164 reg_flt->flt_ref[hlua_state_id] = flt_ref;
11165 reg_flt->fun_ref[hlua_state_id] = fun_ref;
11166
11167 /* The filter keyword */
11168 len = strlen("lua.") + strlen(name) + 1;
11169 fkl->kw[0].kw = calloc(1, len);
11170 if (!fkl->kw[0].kw)
11171 goto alloc_error;
11172
11173 snprintf((char *)fkl->kw[0].kw, len, "lua.%s", name);
11174
11175 fkl->kw[0].parse = hlua_filter_parse_fct;
11176 fkl->kw[0].private = reg_flt;
11177 memset(&fkl->kw[1], 0, sizeof(*fkl->kw));
11178
11179 /* Register this new filter */
11180 flt_register_keywords(fkl);
11181
11182 return 0;
11183
11184 alloc_error:
11185 release_hlua_reg_filter(reg_flt);
11186 ha_free(&fkl);
11187 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
11188 return 0; /* Never reached */
11189}
11190
Thierry FOURNIERbd413492015-03-03 16:52:26 +010011191static int hlua_read_timeout(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011192 const struct proxy *defpx, const char *file, int line,
Thierry FOURNIERbd413492015-03-03 16:52:26 +010011193 char **err, unsigned int *timeout)
11194{
11195 const char *error;
11196
11197 error = parse_time_err(args[1], timeout, TIME_UNIT_MS);
Willy Tarreau9faebe32019-06-07 19:00:37 +020011198 if (error == PARSE_TIME_OVER) {
11199 memprintf(err, "timer overflow in argument <%s> to <%s> (maximum value is 2147483647 ms or ~24.8 days)",
11200 args[1], args[0]);
11201 return -1;
11202 }
11203 else if (error == PARSE_TIME_UNDER) {
11204 memprintf(err, "timer underflow in argument <%s> to <%s> (minimum non-null value is 1 ms)",
11205 args[1], args[0]);
11206 return -1;
11207 }
11208 else if (error) {
Thierry FOURNIERbd413492015-03-03 16:52:26 +010011209 memprintf(err, "%s: invalid timeout", args[0]);
11210 return -1;
11211 }
11212 return 0;
11213}
11214
11215static int hlua_session_timeout(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011216 const struct proxy *defpx, const char *file, int line,
Thierry FOURNIERbd413492015-03-03 16:52:26 +010011217 char **err)
11218{
11219 return hlua_read_timeout(args, section_type, curpx, defpx,
11220 file, line, err, &hlua_timeout_session);
11221}
11222
11223static int hlua_task_timeout(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011224 const struct proxy *defpx, const char *file, int line,
Thierry FOURNIERbd413492015-03-03 16:52:26 +010011225 char **err)
11226{
11227 return hlua_read_timeout(args, section_type, curpx, defpx,
11228 file, line, err, &hlua_timeout_task);
11229}
11230
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020011231static int hlua_applet_timeout(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011232 const struct proxy *defpx, const char *file, int line,
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020011233 char **err)
11234{
11235 return hlua_read_timeout(args, section_type, curpx, defpx,
11236 file, line, err, &hlua_timeout_applet);
11237}
11238
Thierry FOURNIERee9f8022015-03-03 17:37:37 +010011239static int hlua_forced_yield(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011240 const struct proxy *defpx, const char *file, int line,
Thierry FOURNIERee9f8022015-03-03 17:37:37 +010011241 char **err)
11242{
11243 char *error;
11244
11245 hlua_nb_instruction = strtoll(args[1], &error, 10);
11246 if (*error != '\0') {
11247 memprintf(err, "%s: invalid number", args[0]);
11248 return -1;
11249 }
11250 return 0;
11251}
11252
Willy Tarreau32f61e22015-03-18 17:54:59 +010011253static int hlua_parse_maxmem(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011254 const struct proxy *defpx, const char *file, int line,
Willy Tarreau32f61e22015-03-18 17:54:59 +010011255 char **err)
11256{
11257 char *error;
11258
11259 if (*(args[1]) == 0) {
Thierry Fournier70e38e92022-09-19 09:01:53 +020011260 memprintf(err, "'%s' expects an integer argument (Lua memory size in MB).", args[0]);
Willy Tarreau32f61e22015-03-18 17:54:59 +010011261 return -1;
11262 }
11263 hlua_global_allocator.limit = strtoll(args[1], &error, 10) * 1024L * 1024L;
11264 if (*error != '\0') {
11265 memprintf(err, "%s: invalid number %s (error at '%c')", args[0], args[1], *error);
11266 return -1;
11267 }
11268 return 0;
11269}
11270
11271
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011272/* This function is called by the main configuration key "lua-load". It loads and
11273 * execute an lua file during the parsing of the HAProxy configuration file. It is
11274 * the main lua entry point.
11275 *
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -080011276 * This function runs with the HAProxy keywords API. It returns -1 if an error
11277 * occurs, otherwise it returns 0.
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011278 *
11279 * In some error case, LUA set an error message in top of the stack. This function
11280 * returns this error message in the HAProxy logs and pop it from the stack.
Thierry FOURNIERbabae282015-09-17 11:36:37 +020011281 *
11282 * This function can fail with an abort() due to an Lua critical error.
11283 * We are in the configuration parsing process of HAProxy, this abort() is
11284 * tolerated.
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011285 */
Thierry Fournierae6b5682022-09-19 09:04:16 +020011286static int hlua_load_state(char **args, lua_State *L, char **err)
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011287{
11288 int error;
Thierry Fournierae6b5682022-09-19 09:04:16 +020011289 int nargs;
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011290
11291 /* Just load and compile the file. */
Thierry Fournierae6b5682022-09-19 09:04:16 +020011292 error = luaL_loadfile(L, args[0]);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011293 if (error) {
Thierry Fournierae6b5682022-09-19 09:04:16 +020011294 memprintf(err, "error in Lua file '%s': %s", args[0], lua_tostring(L, -1));
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011295 lua_pop(L, 1);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011296 return -1;
11297 }
Thierry Fournierae6b5682022-09-19 09:04:16 +020011298
11299 /* Push args in the Lua stack, except the first one which is the filename */
11300 for (nargs = 1; *(args[nargs]) != 0; nargs++) {
Aurelien DARRAGON4d7aefe2022-09-23 10:22:14 +020011301 /* Check stack size. */
11302 if (!lua_checkstack(L, 1)) {
11303 memprintf(err, "Lua runtime error while loading arguments: stack is full.");
11304 return -1;
11305 }
Thierry Fournierae6b5682022-09-19 09:04:16 +020011306 lua_pushstring(L, args[nargs]);
11307 }
11308 nargs--;
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011309
11310 /* If no syntax error where detected, execute the code. */
Thierry Fournierae6b5682022-09-19 09:04:16 +020011311 error = lua_pcall(L, nargs, LUA_MULTRET, 0);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011312 switch (error) {
11313 case LUA_OK:
11314 break;
11315 case LUA_ERRRUN:
Thierry Fournier70e38e92022-09-19 09:01:53 +020011316 memprintf(err, "Lua runtime error: %s", lua_tostring(L, -1));
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011317 lua_pop(L, 1);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011318 return -1;
11319 case LUA_ERRMEM:
Thierry Fournier70e38e92022-09-19 09:01:53 +020011320 memprintf(err, "Lua out of memory error");
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011321 return -1;
11322 case LUA_ERRERR:
Thierry Fournier70e38e92022-09-19 09:01:53 +020011323 memprintf(err, "Lua message handler error: %s", lua_tostring(L, -1));
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011324 lua_pop(L, 1);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011325 return -1;
Christopher Faulet08ed98f2020-07-28 10:33:25 +020011326#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM <= 503
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011327 case LUA_ERRGCMM:
Thierry Fournier70e38e92022-09-19 09:01:53 +020011328 memprintf(err, "Lua garbage collector error: %s", lua_tostring(L, -1));
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011329 lua_pop(L, 1);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011330 return -1;
Christopher Faulet08ed98f2020-07-28 10:33:25 +020011331#endif
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011332 default:
Thierry Fournier70e38e92022-09-19 09:01:53 +020011333 memprintf(err, "Lua unknown error: %s", lua_tostring(L, -1));
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011334 lua_pop(L, 1);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011335 return -1;
11336 }
11337
11338 return 0;
11339}
11340
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011341static int hlua_load(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 Fournierc93c15c2020-11-28 15:02:13 +010011343 char **err)
11344{
11345 if (*(args[1]) == 0) {
Thierry Fournier70e38e92022-09-19 09:01:53 +020011346 memprintf(err, "'%s' expects a file name as parameter.", args[0]);
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011347 return -1;
11348 }
11349
Thierry Fournier59f11be2020-11-29 00:37:41 +010011350 /* loading for global state */
Thierry Fournierc7492592020-11-28 23:57:24 +010011351 hlua_state_id = 0;
Willy Tarreau43ab05b2021-09-28 09:43:11 +020011352 ha_set_thread(NULL);
Thierry Fournierae6b5682022-09-19 09:04:16 +020011353 return hlua_load_state(&args[1], hlua_states[0], err);
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011354}
11355
Thierry Fournier59f11be2020-11-29 00:37:41 +010011356static int hlua_load_per_thread(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011357 const struct proxy *defpx, const char *file, int line,
Thierry Fournier59f11be2020-11-29 00:37:41 +010011358 char **err)
11359{
11360 int len;
Thierry Fournierae6b5682022-09-19 09:04:16 +020011361 int i;
Thierry Fournier59f11be2020-11-29 00:37:41 +010011362
11363 if (*(args[1]) == 0) {
Thierry Fournier70e38e92022-09-19 09:01:53 +020011364 memprintf(err, "'%s' expects a file as parameter.", args[0]);
Thierry Fournier59f11be2020-11-29 00:37:41 +010011365 return -1;
11366 }
11367
11368 if (per_thread_load == NULL) {
11369 /* allocate the first entry large enough to store the final NULL */
11370 per_thread_load = calloc(1, sizeof(*per_thread_load));
11371 if (per_thread_load == NULL) {
11372 memprintf(err, "out of memory error");
11373 return -1;
11374 }
11375 }
11376
11377 /* count used entries */
11378 for (len = 0; per_thread_load[len] != NULL; len++)
11379 ;
11380
11381 per_thread_load = realloc(per_thread_load, (len + 2) * sizeof(*per_thread_load));
11382 if (per_thread_load == NULL) {
11383 memprintf(err, "out of memory error");
11384 return -1;
11385 }
Thierry Fournier59f11be2020-11-29 00:37:41 +010011386 per_thread_load[len + 1] = NULL;
11387
Thierry Fournierae6b5682022-09-19 09:04:16 +020011388 /* count args excepting the first, allocate array and copy args */
11389 for (i = 0; *(args[i + 1]) != 0; i++);
Aurelien DARRAGONb12d1692022-09-23 08:48:34 +020011390 per_thread_load[len] = calloc(i + 1, sizeof(*per_thread_load[len]));
Thierry Fournier59f11be2020-11-29 00:37:41 +010011391 if (per_thread_load[len] == NULL) {
11392 memprintf(err, "out of memory error");
11393 return -1;
11394 }
Thierry Fournierae6b5682022-09-19 09:04:16 +020011395 for (i = 1; *(args[i]) != 0; i++) {
11396 per_thread_load[len][i - 1] = strdup(args[i]);
11397 if (per_thread_load[len][i - 1] == NULL) {
11398 memprintf(err, "out of memory error");
11399 return -1;
11400 }
11401 }
11402 per_thread_load[len][i - 1] = strdup("");
11403 if (per_thread_load[len][i - 1] == NULL) {
11404 memprintf(err, "out of memory error");
11405 return -1;
11406 }
Thierry Fournier59f11be2020-11-29 00:37:41 +010011407
11408 /* loading for thread 1 only */
11409 hlua_state_id = 1;
Willy Tarreau43ab05b2021-09-28 09:43:11 +020011410 ha_set_thread(NULL);
Thierry Fournierae6b5682022-09-19 09:04:16 +020011411 return hlua_load_state(per_thread_load[len], hlua_states[1], err);
Thierry Fournier59f11be2020-11-29 00:37:41 +010011412}
11413
Tim Duesterhusc9fc9f22020-01-12 13:55:39 +010011414/* Prepend the given <path> followed by a semicolon to the `package.<type>` variable
11415 * in the given <ctx>.
11416 */
Thierry Fournier3fb9e512020-11-28 10:13:12 +010011417static int hlua_prepend_path(lua_State *L, char *type, char *path)
Tim Duesterhusc9fc9f22020-01-12 13:55:39 +010011418{
Thierry Fournier3fb9e512020-11-28 10:13:12 +010011419 lua_getglobal(L, "package"); /* push package variable */
11420 lua_pushstring(L, path); /* push given path */
11421 lua_pushstring(L, ";"); /* push semicolon */
11422 lua_getfield(L, -3, type); /* push old path */
11423 lua_concat(L, 3); /* concatenate to new path */
11424 lua_setfield(L, -2, type); /* store new path */
11425 lua_pop(L, 1); /* pop package variable */
Tim Duesterhusc9fc9f22020-01-12 13:55:39 +010011426
11427 return 0;
11428}
11429
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010011430static int hlua_config_prepend_path(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011431 const struct proxy *defpx, const char *file, int line,
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010011432 char **err)
11433{
11434 char *path;
11435 char *type = "path";
Tim Duesterhus621e74a2021-01-03 20:04:36 +010011436 struct prepend_path *p = NULL;
Bertrand Jacquin7fbc7702021-11-24 21:16:06 +000011437 size_t i;
Thierry Fournier59f11be2020-11-29 00:37:41 +010011438
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010011439 if (too_many_args(2, args, err, NULL)) {
Tim Duesterhus621e74a2021-01-03 20:04:36 +010011440 goto err;
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010011441 }
11442
11443 if (!(*args[1])) {
11444 memprintf(err, "'%s' expects to receive a <path> as argument", args[0]);
Tim Duesterhus621e74a2021-01-03 20:04:36 +010011445 goto err;
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010011446 }
11447 path = args[1];
11448
11449 if (*args[2]) {
11450 if (strcmp(args[2], "path") != 0 && strcmp(args[2], "cpath") != 0) {
11451 memprintf(err, "'%s' expects <type> to either be 'path' or 'cpath'", args[0]);
Tim Duesterhus621e74a2021-01-03 20:04:36 +010011452 goto err;
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010011453 }
11454 type = args[2];
11455 }
11456
Thierry Fournier59f11be2020-11-29 00:37:41 +010011457 p = calloc(1, sizeof(*p));
11458 if (p == NULL) {
Tim Duesterhusf89d43a2021-01-03 20:04:37 +010011459 memprintf(err, "memory allocation failed");
Tim Duesterhus621e74a2021-01-03 20:04:36 +010011460 goto err;
Thierry Fournier59f11be2020-11-29 00:37:41 +010011461 }
11462 p->path = strdup(path);
11463 if (p->path == NULL) {
Tim Duesterhusf89d43a2021-01-03 20:04:37 +010011464 memprintf(err, "memory allocation failed");
Tim Duesterhus621e74a2021-01-03 20:04:36 +010011465 goto err2;
Thierry Fournier59f11be2020-11-29 00:37:41 +010011466 }
11467 p->type = strdup(type);
11468 if (p->type == NULL) {
Tim Duesterhusf89d43a2021-01-03 20:04:37 +010011469 memprintf(err, "memory allocation failed");
Tim Duesterhus621e74a2021-01-03 20:04:36 +010011470 goto err2;
Thierry Fournier59f11be2020-11-29 00:37:41 +010011471 }
Willy Tarreau2b718102021-04-21 07:32:39 +020011472 LIST_APPEND(&prepend_path_list, &p->l);
Thierry Fournier59f11be2020-11-29 00:37:41 +010011473
Tim Duesterhus9e5e5862021-10-11 18:51:08 +020011474 /* Handle the global state and the per-thread state for the first
11475 * thread. The remaining threads will be initialized based on
11476 * prepend_path_list.
11477 */
Bertrand Jacquin7fbc7702021-11-24 21:16:06 +000011478 for (i = 0; i < 2; i++) {
Tim Duesterhus9e5e5862021-10-11 18:51:08 +020011479 lua_State *L = hlua_states[i];
11480 const char *error;
11481
11482 if (setjmp(safe_ljmp_env) != 0) {
11483 lua_atpanic(L, hlua_panic_safe);
11484 if (lua_type(L, -1) == LUA_TSTRING)
11485 error = lua_tostring(L, -1);
11486 else
11487 error = "critical error";
11488 fprintf(stderr, "lua-prepend-path: %s.\n", error);
11489 exit(1);
11490 } else {
11491 lua_atpanic(L, hlua_panic_ljmp);
11492 }
11493
11494 hlua_prepend_path(L, type, path);
11495
11496 lua_atpanic(L, hlua_panic_safe);
11497 }
11498
Thierry Fournier59f11be2020-11-29 00:37:41 +010011499 return 0;
Tim Duesterhus621e74a2021-01-03 20:04:36 +010011500
11501err2:
11502 free(p->type);
11503 free(p->path);
11504err:
11505 free(p);
11506 return -1;
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010011507}
11508
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011509/* configuration keywords declaration */
11510static struct cfg_kw_list cfg_kws = {{ },{
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010011511 { CFG_GLOBAL, "lua-prepend-path", hlua_config_prepend_path },
Thierry FOURNIERbd413492015-03-03 16:52:26 +010011512 { CFG_GLOBAL, "lua-load", hlua_load },
Thierry Fournier59f11be2020-11-29 00:37:41 +010011513 { CFG_GLOBAL, "lua-load-per-thread", hlua_load_per_thread },
Thierry FOURNIERbd413492015-03-03 16:52:26 +010011514 { CFG_GLOBAL, "tune.lua.session-timeout", hlua_session_timeout },
11515 { CFG_GLOBAL, "tune.lua.task-timeout", hlua_task_timeout },
Thierry FOURNIER56da1012015-10-01 08:42:31 +020011516 { CFG_GLOBAL, "tune.lua.service-timeout", hlua_applet_timeout },
Thierry FOURNIERee9f8022015-03-03 17:37:37 +010011517 { CFG_GLOBAL, "tune.lua.forced-yield", hlua_forced_yield },
Willy Tarreau32f61e22015-03-18 17:54:59 +010011518 { CFG_GLOBAL, "tune.lua.maxmem", hlua_parse_maxmem },
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011519 { 0, NULL, NULL },
11520}};
11521
Willy Tarreau0108d902018-11-25 19:14:37 +010011522INITCALL1(STG_REGISTER, cfg_register_keywords, &cfg_kws);
11523
William Lallemand52139182022-03-30 15:05:42 +020011524#ifdef USE_OPENSSL
Christopher Fauletafd8f102018-11-08 11:34:21 +010011525
William Lallemand30fcca12022-03-30 12:03:12 +020011526/*
11527 * This function replace a ckch_store by another one, and rebuild the ckch_inst and all its dependencies.
11528 * It does the sam as "cli_io_handler_commit_cert" but for lua, the major
11529 * difference is that the yield in lua and for the CLI is not handled the same
11530 * way.
11531 */
11532__LJMP static int hlua_ckch_commit_yield(lua_State *L, int status, lua_KContext ctx)
11533{
11534 struct ckch_inst **lua_ckchi = lua_touserdata(L, -1);
11535 struct ckch_store **lua_ckchs = lua_touserdata(L, -2);
11536 struct ckch_inst *ckchi = *lua_ckchi;
11537 struct ckch_store *old_ckchs = lua_ckchs[0];
11538 struct ckch_store *new_ckchs = lua_ckchs[1];
11539 struct hlua *hlua;
11540 char *err = NULL;
11541 int y = 1;
11542
11543 hlua = hlua_gethlua(L);
11544
11545 /* get the first ckchi to copy */
11546 if (ckchi == NULL)
11547 ckchi = LIST_ELEM(old_ckchs->ckch_inst.n, typeof(ckchi), by_ckchs);
11548
11549 /* walk through the old ckch_inst and creates new ckch_inst using the updated ckchs */
11550 list_for_each_entry_from(ckchi, &old_ckchs->ckch_inst, by_ckchs) {
11551 struct ckch_inst *new_inst;
11552
11553 /* it takes a lot of CPU to creates SSL_CTXs, so we yield every 10 CKCH instances */
11554 if (y % 10 == 0) {
11555
11556 *lua_ckchi = ckchi;
11557
11558 task_wakeup(hlua->task, TASK_WOKEN_MSG);
11559 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_ckch_commit_yield, TICK_ETERNITY, 0));
11560 }
11561
11562 if (ckch_inst_rebuild(new_ckchs, ckchi, &new_inst, &err))
11563 goto error;
11564
11565 /* link the new ckch_inst to the duplicate */
11566 LIST_APPEND(&new_ckchs->ckch_inst, &new_inst->by_ckchs);
11567 y++;
11568 }
11569
11570 /* The generation is finished, we can insert everything */
11571 ckch_store_replace(old_ckchs, new_ckchs);
11572
11573 lua_pop(L, 2); /* pop the lua_ckchs and ckchi */
11574
11575 HA_SPIN_UNLOCK(CKCH_LOCK, &ckch_lock);
11576
11577 return 0;
11578
11579error:
11580 ckch_store_free(new_ckchs);
11581 HA_SPIN_UNLOCK(CKCH_LOCK, &ckch_lock);
11582 WILL_LJMP(luaL_error(L, "%s", err));
11583 free(err);
11584
11585 return 0;
11586}
11587
11588/*
11589 * Replace a ckch_store <filename> in the ckchs_tree with a ckch_store created
11590 * from the table in parameter.
11591 *
11592 * This is equivalent to "set ssl cert" + "commit ssl cert" over the CLI, which
11593 * means it does not need to have a transaction since everything is done in the
11594 * same function.
11595 *
11596 * CertCache.set{filename="", crt="", key="", sctl="", ocsp="", issuer=""}
11597 *
11598 */
11599__LJMP static int hlua_ckch_set(lua_State *L)
11600{
11601 struct hlua *hlua;
11602 struct ckch_inst **lua_ckchi;
11603 struct ckch_store **lua_ckchs;
11604 struct ckch_store *old_ckchs = NULL;
11605 struct ckch_store *new_ckchs = NULL;
11606 int errcode = 0;
11607 char *err = NULL;
11608 struct cert_exts *cert_ext = NULL;
11609 char *filename;
William Lallemand52ddd992022-11-22 11:51:53 +010011610 struct ckch_data *data;
William Lallemand30fcca12022-03-30 12:03:12 +020011611 int ret;
11612
11613 if (lua_type(L, -1) != LUA_TTABLE)
11614 WILL_LJMP(luaL_error(L, "'CertCache.set' needs a table as argument"));
11615
11616 hlua = hlua_gethlua(L);
11617
11618 /* FIXME: this should not return an error but should come back later */
11619 if (HA_SPIN_TRYLOCK(CKCH_LOCK, &ckch_lock))
11620 WILL_LJMP(luaL_error(L, "CertCache already under lock"));
11621
11622 ret = lua_getfield(L, -1, "filename");
11623 if (ret != LUA_TSTRING) {
Thierry Fournier70e38e92022-09-19 09:01:53 +020011624 memprintf(&err, "%sNo filename specified!", err ? err : "");
William Lallemand30fcca12022-03-30 12:03:12 +020011625 errcode |= ERR_ALERT | ERR_FATAL;
11626 goto end;
11627 }
11628 filename = (char *)lua_tostring(L, -1);
11629
11630
11631 /* look for the filename in the tree */
11632 old_ckchs = ckchs_lookup(filename);
11633 if (!old_ckchs) {
Thierry Fournier70e38e92022-09-19 09:01:53 +020011634 memprintf(&err, "%sCan't replace a certificate which is not referenced by the configuration!", err ? err : "");
William Lallemand30fcca12022-03-30 12:03:12 +020011635 errcode |= ERR_ALERT | ERR_FATAL;
11636 goto end;
11637 }
11638 /* TODO: handle extra_files_noext */
11639
11640 new_ckchs = ckchs_dup(old_ckchs);
11641 if (!new_ckchs) {
Thierry Fournier70e38e92022-09-19 09:01:53 +020011642 memprintf(&err, "%sCannot allocate memory!", err ? err : "");
William Lallemand30fcca12022-03-30 12:03:12 +020011643 errcode |= ERR_ALERT | ERR_FATAL;
11644 goto end;
11645 }
11646
William Lallemand52ddd992022-11-22 11:51:53 +010011647 data = new_ckchs->data;
William Lallemand30fcca12022-03-30 12:03:12 +020011648
11649 /* loop on the field in the table, which have the same name as the
11650 * possible extensions of files */
11651 lua_pushnil(L);
11652 while (lua_next(L, 1)) {
11653 int i;
11654 const char *field = lua_tostring(L, -2);
11655 char *payload = (char *)lua_tostring(L, -1);
11656
11657 if (!field || strcmp(field, "filename") == 0) {
11658 lua_pop(L, 1);
11659 continue;
11660 }
11661
11662 for (i = 0; field && cert_exts[i].ext != NULL; i++) {
11663 if (strcmp(field, cert_exts[i].ext) == 0) {
11664 cert_ext = &cert_exts[i];
11665 break;
11666 }
11667 }
11668
11669 /* this is the default type, the field is not supported */
11670 if (cert_ext == NULL) {
Thierry Fournier70e38e92022-09-19 09:01:53 +020011671 memprintf(&err, "%sUnsupported field '%s'", err ? err : "", field);
William Lallemand30fcca12022-03-30 12:03:12 +020011672 errcode |= ERR_ALERT | ERR_FATAL;
11673 goto end;
11674 }
11675
11676 /* appply the change on the duplicate */
William Lallemand52ddd992022-11-22 11:51:53 +010011677 if (cert_ext->load(filename, payload, data, &err) != 0) {
Thierry Fournier70e38e92022-09-19 09:01:53 +020011678 memprintf(&err, "%sCan't load the payload for '%s'", err ? err : "", cert_ext->ext);
William Lallemand30fcca12022-03-30 12:03:12 +020011679 errcode |= ERR_ALERT | ERR_FATAL;
11680 goto end;
11681 }
11682 lua_pop(L, 1);
11683 }
11684
11685 /* store the pointers on the lua stack */
11686 lua_ckchs = lua_newuserdata(L, sizeof(struct ckch_store *) * 2);
11687 lua_ckchs[0] = old_ckchs;
11688 lua_ckchs[1] = new_ckchs;
11689 lua_ckchi = lua_newuserdata(L, sizeof(struct ckch_inst *));
11690 *lua_ckchi = NULL;
11691
11692 task_wakeup(hlua->task, TASK_WOKEN_MSG);
11693 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_ckch_commit_yield, TICK_ETERNITY, 0));
11694
11695end:
11696 HA_SPIN_UNLOCK(CKCH_LOCK, &ckch_lock);
11697
11698 if (errcode & ERR_CODE) {
11699 ckch_store_free(new_ckchs);
11700 WILL_LJMP(luaL_error(L, "%s", err));
11701 }
11702 free(err);
11703
11704 return 0;
11705}
11706
William Lallemand52139182022-03-30 15:05:42 +020011707#else
11708
11709__LJMP static int hlua_ckch_set(lua_State *L)
11710{
11711 WILL_LJMP(luaL_error(L, "'CertCache.set' needs an HAProxy built with OpenSSL"));
11712
11713 return 0;
11714}
11715#endif /* ! USE_OPENSSL */
11716
11717
11718
Thierry FOURNIERbabae282015-09-17 11:36:37 +020011719/* This function can fail with an abort() due to an Lua critical error.
11720 * We are in the initialisation process of HAProxy, this abort() is
11721 * tolerated.
11722 */
Thierry Fournierb8cef172020-11-28 15:37:17 +010011723int hlua_post_init_state(lua_State *L)
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010011724{
11725 struct hlua_init_function *init;
11726 const char *msg;
11727 enum hlua_exec ret;
Thierry Fournierfd107a22016-02-19 19:57:23 +010011728 const char *error;
Thierry Fournier670db242020-11-28 10:49:59 +010011729 const char *kind;
11730 const char *trace;
11731 int return_status = 1;
11732#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM >= 504
11733 int nres;
11734#endif
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010011735
Willy Tarreaucdb53462020-12-02 12:12:00 +010011736 /* disable memory limit checks if limit is not set */
11737 if (!hlua_global_allocator.limit)
11738 hlua_global_allocator.limit = ~hlua_global_allocator.limit;
11739
Ilya Shipitsin856aabc2020-04-16 23:51:34 +050011740 /* Call post initialisation function in safe environment. */
Thierry Fournier3c539322020-11-28 16:05:05 +010011741 if (setjmp(safe_ljmp_env) != 0) {
11742 lua_atpanic(L, hlua_panic_safe);
Thierry Fournierb8cef172020-11-28 15:37:17 +010011743 if (lua_type(L, -1) == LUA_TSTRING)
11744 error = lua_tostring(L, -1);
Thierry Fournier3d4a6752016-02-19 20:53:30 +010011745 else
11746 error = "critical error";
11747 fprintf(stderr, "Lua post-init: %s.\n", error);
11748 exit(1);
Thierry Fournier3c539322020-11-28 16:05:05 +010011749 } else {
11750 lua_atpanic(L, hlua_panic_ljmp);
Thierry Fournier3d4a6752016-02-19 20:53:30 +010011751 }
Frédéric Lécaille54f2bcf2018-08-29 13:46:24 +020011752
Thierry Fournierb8cef172020-11-28 15:37:17 +010011753 hlua_fcn_post_init(L);
Thierry Fournier3d4a6752016-02-19 20:53:30 +010011754
Thierry Fournierc7492592020-11-28 23:57:24 +010011755 list_for_each_entry(init, &hlua_init_functions[hlua_state_id], l) {
Thierry Fournierb8cef172020-11-28 15:37:17 +010011756 lua_rawgeti(L, LUA_REGISTRYINDEX, init->function_ref);
Thierry Fournier670db242020-11-28 10:49:59 +010011757
11758#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM >= 504
Thierry Fournierb8cef172020-11-28 15:37:17 +010011759 ret = lua_resume(L, L, 0, &nres);
Thierry Fournier670db242020-11-28 10:49:59 +010011760#else
Thierry Fournierb8cef172020-11-28 15:37:17 +010011761 ret = lua_resume(L, L, 0);
Thierry Fournier670db242020-11-28 10:49:59 +010011762#endif
11763 kind = NULL;
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010011764 switch (ret) {
Thierry Fournier670db242020-11-28 10:49:59 +010011765
11766 case LUA_OK:
Thierry Fournierb8cef172020-11-28 15:37:17 +010011767 lua_pop(L, -1);
Thierry Fournier13d08b72020-11-28 11:02:58 +010011768 break;
Thierry Fournier670db242020-11-28 10:49:59 +010011769
11770 case LUA_ERRERR:
11771 kind = "message handler error";
Willy Tarreau14de3952022-11-14 07:08:28 +010011772 __fallthrough;
Thierry Fournier670db242020-11-28 10:49:59 +010011773 case LUA_ERRRUN:
11774 if (!kind)
11775 kind = "runtime error";
Thierry Fournierb8cef172020-11-28 15:37:17 +010011776 msg = lua_tostring(L, -1);
11777 lua_settop(L, 0); /* Empty the stack. */
11778 lua_pop(L, 1);
Christopher Fauletd09cc512021-03-24 14:48:45 +010011779 trace = hlua_traceback(L, ", ");
Thierry Fournier670db242020-11-28 10:49:59 +010011780 if (msg)
11781 ha_alert("Lua init: %s: '%s' from %s\n", kind, msg, trace);
11782 else
11783 ha_alert("Lua init: unknown %s from %s\n", kind, trace);
11784 return_status = 0;
11785 break;
11786
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010011787 default:
Thierry Fournier670db242020-11-28 10:49:59 +010011788 /* Unknown error */
11789 kind = "Unknown error";
Willy Tarreau14de3952022-11-14 07:08:28 +010011790 __fallthrough;
Thierry Fournier670db242020-11-28 10:49:59 +010011791 case LUA_YIELD:
11792 /* yield is not configured at this step, this state doesn't happen */
11793 if (!kind)
11794 kind = "yield not allowed";
Willy Tarreau14de3952022-11-14 07:08:28 +010011795 __fallthrough;
Thierry Fournier670db242020-11-28 10:49:59 +010011796 case LUA_ERRMEM:
11797 if (!kind)
11798 kind = "out of memory error";
Thierry Fournierb8cef172020-11-28 15:37:17 +010011799 lua_settop(L, 0);
11800 lua_pop(L, 1);
Christopher Fauletd09cc512021-03-24 14:48:45 +010011801 trace = hlua_traceback(L, ", ");
Thierry Fournier670db242020-11-28 10:49:59 +010011802 ha_alert("Lua init: %s: %s\n", kind, trace);
11803 return_status = 0;
11804 break;
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010011805 }
Thierry Fournier670db242020-11-28 10:49:59 +010011806 if (!return_status)
11807 break;
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010011808 }
Thierry Fournier3c539322020-11-28 16:05:05 +010011809
11810 lua_atpanic(L, hlua_panic_safe);
Thierry Fournier670db242020-11-28 10:49:59 +010011811 return return_status;
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010011812}
11813
Thierry Fournierb8cef172020-11-28 15:37:17 +010011814int hlua_post_init()
11815{
Thierry Fournier59f11be2020-11-29 00:37:41 +010011816 int ret;
11817 int i;
11818 int errors;
11819 char *err = NULL;
11820 struct hlua_function *fcn;
Christopher Faulet69c581a2021-05-31 08:54:04 +020011821 struct hlua_reg_filter *reg_flt;
Thierry Fournier59f11be2020-11-29 00:37:41 +010011822
Willy Tarreaub1310492021-08-30 09:35:18 +020011823#if defined(USE_OPENSSL)
Thierry Fournierb8cef172020-11-28 15:37:17 +010011824 /* Initialize SSL server. */
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010011825 if (socket_ssl->xprt->prepare_srv) {
Thierry Fournierb8cef172020-11-28 15:37:17 +010011826 int saved_used_backed = global.ssl_used_backend;
11827 // don't affect maxconn automatic computation
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010011828 socket_ssl->xprt->prepare_srv(socket_ssl);
Thierry Fournierb8cef172020-11-28 15:37:17 +010011829 global.ssl_used_backend = saved_used_backed;
11830 }
11831#endif
11832
Thierry Fournierc7492592020-11-28 23:57:24 +010011833 /* Perform post init of common thread */
11834 hlua_state_id = 0;
Willy Tarreau43ab05b2021-09-28 09:43:11 +020011835 ha_set_thread(&ha_thread_info[0]);
Thierry Fournier59f11be2020-11-29 00:37:41 +010011836 ret = hlua_post_init_state(hlua_states[hlua_state_id]);
11837 if (ret == 0)
11838 return 0;
11839
11840 /* init remaining lua states and load files */
11841 for (hlua_state_id = 2; hlua_state_id < global.nbthread + 1; hlua_state_id++) {
11842
11843 /* set thread context */
Willy Tarreau43ab05b2021-09-28 09:43:11 +020011844 ha_set_thread(&ha_thread_info[hlua_state_id - 1]);
Thierry Fournier59f11be2020-11-29 00:37:41 +010011845
11846 /* Init lua state */
11847 hlua_states[hlua_state_id] = hlua_init_state(hlua_state_id);
11848
11849 /* Load lua files */
11850 for (i = 0; per_thread_load && per_thread_load[i]; i++) {
11851 ret = hlua_load_state(per_thread_load[i], hlua_states[hlua_state_id], &err);
11852 if (ret != 0) {
11853 ha_alert("Lua init: %s\n", err);
11854 return 0;
11855 }
11856 }
11857 }
11858
11859 /* Reset thread context */
Willy Tarreau43ab05b2021-09-28 09:43:11 +020011860 ha_set_thread(NULL);
Thierry Fournier59f11be2020-11-29 00:37:41 +010011861
11862 /* Execute post init for all states */
11863 for (hlua_state_id = 1; hlua_state_id < global.nbthread + 1; hlua_state_id++) {
11864
11865 /* set thread context */
Willy Tarreau43ab05b2021-09-28 09:43:11 +020011866 ha_set_thread(&ha_thread_info[hlua_state_id - 1]);
Thierry Fournier59f11be2020-11-29 00:37:41 +010011867
11868 /* run post init */
11869 ret = hlua_post_init_state(hlua_states[hlua_state_id]);
11870 if (ret == 0)
11871 return 0;
11872 }
11873
11874 /* Reset thread context */
Willy Tarreau43ab05b2021-09-28 09:43:11 +020011875 ha_set_thread(NULL);
Thierry Fournier59f11be2020-11-29 00:37:41 +010011876
11877 /* control functions registering. Each function must have:
11878 * - only the function_ref[0] set positive and all other to -1
11879 * - only the function_ref[0] set to -1 and all other positive
11880 * This ensure a same reference is not used both in shared
11881 * lua state and thread dedicated lua state. Note: is the case
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +050011882 * reach, the shared state is priority, but the bug will be
Thierry Fournier59f11be2020-11-29 00:37:41 +010011883 * complicated to found for the end user.
11884 */
11885 errors = 0;
11886 list_for_each_entry(fcn, &referenced_functions, l) {
11887 ret = 0;
11888 for (i = 1; i < global.nbthread + 1; i++) {
11889 if (fcn->function_ref[i] == -1)
11890 ret--;
11891 else
11892 ret++;
11893 }
11894 if (abs(ret) != global.nbthread) {
11895 ha_alert("Lua function '%s' is not referenced in all thread. "
11896 "Expect function in all thread or in none thread.\n", fcn->name);
11897 errors++;
11898 continue;
11899 }
11900
11901 if ((fcn->function_ref[0] == -1) == (ret < 0)) {
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +050011902 ha_alert("Lua function '%s' is referenced both ins shared Lua context (through lua-load) "
11903 "and per-thread Lua context (through lua-load-per-thread). these two context "
Thierry Fournier59f11be2020-11-29 00:37:41 +010011904 "exclusive.\n", fcn->name);
11905 errors++;
11906 }
11907 }
11908
Christopher Faulet69c581a2021-05-31 08:54:04 +020011909 /* Do the same with registered filters */
11910 list_for_each_entry(reg_flt, &referenced_filters, l) {
11911 ret = 0;
11912 for (i = 1; i < global.nbthread + 1; i++) {
11913 if (reg_flt->flt_ref[i] == -1)
11914 ret--;
11915 else
11916 ret++;
11917 }
11918 if (abs(ret) != global.nbthread) {
11919 ha_alert("Lua filter '%s' is not referenced in all thread. "
11920 "Expect function in all thread or in none thread.\n", reg_flt->name);
11921 errors++;
11922 continue;
11923 }
11924
11925 if ((reg_flt->flt_ref[0] == -1) == (ret < 0)) {
11926 ha_alert("Lua filter '%s' is referenced both ins shared Lua context (through lua-load) "
11927 "and per-thread Lua context (through lua-load-per-thread). these two context "
11928 "exclusive.\n", fcn->name);
11929 errors++;
11930 }
11931 }
11932
11933
Thierry Fournier59f11be2020-11-29 00:37:41 +010011934 if (errors > 0)
11935 return 0;
11936
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +050011937 /* after this point, this global will no longer be used, so set to
Thierry Fournier59f11be2020-11-29 00:37:41 +010011938 * -1 in order to have probably a segfault if someone use it
11939 */
11940 hlua_state_id = -1;
11941
11942 return 1;
Thierry Fournierb8cef172020-11-28 15:37:17 +010011943}
11944
Willy Tarreau32f61e22015-03-18 17:54:59 +010011945/* The memory allocator used by the Lua stack. <ud> is a pointer to the
11946 * allocator's context. <ptr> is the pointer to alloc/free/realloc. <osize>
11947 * is the previously allocated size or the kind of object in case of a new
Willy Tarreaud36c7fa2020-12-02 12:26:29 +010011948 * allocation. <nsize> is the requested new size. A new allocation is
11949 * indicated by <ptr> being NULL. A free is indicated by <nsize> being
Willy Tarreaucdb53462020-12-02 12:12:00 +010011950 * zero. This one verifies that the limits are respected but is optimized
11951 * for the fast case where limits are not used, hence stats are not updated.
Willy Tarreaua5efdff2021-10-22 16:00:02 +020011952 *
11953 * Warning: while this API ressembles glibc's realloc() a lot, glibc surpasses
11954 * POSIX by making realloc(ptr,0) an effective free(), but others do not do
11955 * that and will simply allocate zero as if it were the result of malloc(0),
11956 * so mapping this onto realloc() will lead to memory leaks on non-glibc
11957 * systems.
Willy Tarreau32f61e22015-03-18 17:54:59 +010011958 */
11959static void *hlua_alloc(void *ud, void *ptr, size_t osize, size_t nsize)
11960{
11961 struct hlua_mem_allocator *zone = ud;
Willy Tarreaucdb53462020-12-02 12:12:00 +010011962 size_t limit, old, new;
11963
11964 /* a limit of ~0 means unlimited and boot complete, so there's no need
11965 * for accounting anymore.
11966 */
Willy Tarreaua5efdff2021-10-22 16:00:02 +020011967 if (likely(~zone->limit == 0)) {
11968 if (!nsize)
11969 ha_free(&ptr);
11970 else
11971 ptr = realloc(ptr, nsize);
11972 return ptr;
11973 }
Willy Tarreau32f61e22015-03-18 17:54:59 +010011974
Willy Tarreaud36c7fa2020-12-02 12:26:29 +010011975 if (!ptr)
11976 osize = 0;
Willy Tarreau32f61e22015-03-18 17:54:59 +010011977
Willy Tarreaucdb53462020-12-02 12:12:00 +010011978 /* enforce strict limits across all threads */
11979 limit = zone->limit;
11980 old = _HA_ATOMIC_LOAD(&zone->allocated);
11981 do {
11982 new = old + nsize - osize;
11983 if (unlikely(nsize && limit && new > limit))
11984 return NULL;
11985 } while (!_HA_ATOMIC_CAS(&zone->allocated, &old, new));
Willy Tarreau32f61e22015-03-18 17:54:59 +010011986
Willy Tarreaua5efdff2021-10-22 16:00:02 +020011987 if (!nsize)
11988 ha_free(&ptr);
11989 else
11990 ptr = realloc(ptr, nsize);
Willy Tarreaucdb53462020-12-02 12:12:00 +010011991
11992 if (unlikely(!ptr && nsize)) // failed
11993 _HA_ATOMIC_SUB(&zone->allocated, nsize - osize);
11994
11995 __ha_barrier_atomic_store();
Willy Tarreau32f61e22015-03-18 17:54:59 +010011996 return ptr;
11997}
11998
Thierry Fournierecb83c22020-11-28 15:49:44 +010011999/* This function can fail with an abort() due to a Lua critical error.
Thierry FOURNIERbabae282015-09-17 11:36:37 +020012000 * We are in the initialisation process of HAProxy, this abort() is
12001 * tolerated.
12002 */
Thierry Fournierecb83c22020-11-28 15:49:44 +010012003lua_State *hlua_init_state(int thread_num)
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +010012004{
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010012005 int i;
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010012006 int idx;
12007 struct sample_fetch *sf;
Thierry FOURNIER594afe72015-03-10 23:58:30 +010012008 struct sample_conv *sc;
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010012009 char *p;
Thierry Fournierfd107a22016-02-19 19:57:23 +010012010 const char *error_msg;
Thierry Fournier4234dbd2020-11-28 13:18:23 +010012011 void **context;
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012012 lua_State *L;
Thierry Fournier59f11be2020-11-29 00:37:41 +010012013 struct prepend_path *pp;
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010012014
Thierry FOURNIER380d0932015-01-23 14:27:52 +010012015 /* Init main lua stack. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012016 L = lua_newstate(hlua_alloc, &hlua_global_allocator);
Thierry FOURNIER380d0932015-01-23 14:27:52 +010012017
Thierry Fournier4234dbd2020-11-28 13:18:23 +010012018 /* Initialise Lua context to NULL */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012019 context = lua_getextraspace(L);
Thierry Fournier4234dbd2020-11-28 13:18:23 +010012020 *context = NULL;
12021
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -080012022 /* From this point, until the end of the initialisation function,
Thierry FOURNIERbabae282015-09-17 11:36:37 +020012023 * the Lua function can fail with an abort. We are in the initialisation
12024 * process of HAProxy, this abort() is tolerated.
12025 */
12026
Thierry Fournier3c539322020-11-28 16:05:05 +010012027 /* Call post initialisation function in safe environment. */
12028 if (setjmp(safe_ljmp_env) != 0) {
12029 lua_atpanic(L, hlua_panic_safe);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012030 if (lua_type(L, -1) == LUA_TSTRING)
12031 error_msg = lua_tostring(L, -1);
Thierry Fournier2f05cc62020-11-28 16:08:02 +010012032 else
12033 error_msg = "critical error";
12034 fprintf(stderr, "Lua init: %s.\n", error_msg);
12035 exit(1);
Thierry Fournier3c539322020-11-28 16:05:05 +010012036 } else {
12037 lua_atpanic(L, hlua_panic_ljmp);
Thierry Fournier2f05cc62020-11-28 16:08:02 +010012038 }
12039
Thierry FOURNIER380d0932015-01-23 14:27:52 +010012040 /* Initialise lua. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012041 luaL_openlibs(L);
Tim Duesterhus541fe1e2020-01-12 13:55:41 +010012042#define HLUA_PREPEND_PATH_TOSTRING1(x) #x
12043#define HLUA_PREPEND_PATH_TOSTRING(x) HLUA_PREPEND_PATH_TOSTRING1(x)
12044#ifdef HLUA_PREPEND_PATH
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012045 hlua_prepend_path(L, "path", HLUA_PREPEND_PATH_TOSTRING(HLUA_PREPEND_PATH));
Tim Duesterhus541fe1e2020-01-12 13:55:41 +010012046#endif
12047#ifdef HLUA_PREPEND_CPATH
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012048 hlua_prepend_path(L, "cpath", HLUA_PREPEND_PATH_TOSTRING(HLUA_PREPEND_CPATH));
Tim Duesterhus541fe1e2020-01-12 13:55:41 +010012049#endif
12050#undef HLUA_PREPEND_PATH_TOSTRING
12051#undef HLUA_PREPEND_PATH_TOSTRING1
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010012052
Thierry Fournier59f11be2020-11-29 00:37:41 +010012053 /* Apply configured prepend path */
12054 list_for_each_entry(pp, &prepend_path_list, l)
12055 hlua_prepend_path(L, pp->type, pp->path);
12056
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010012057 /*
12058 *
12059 * Create "core" object.
12060 *
12061 */
12062
Thierry FOURNIERa2d8c652015-03-11 17:29:39 +010012063 /* This table entry is the object "core" base. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012064 lua_newtable(L);
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010012065
Thierry Fournierecb83c22020-11-28 15:49:44 +010012066 /* set the thread id */
12067 hlua_class_const_int(L, "thread", thread_num);
12068
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010012069 /* Push the loglevel constants. */
Willy Tarreau80f5fae2015-02-27 16:38:20 +010012070 for (i = 0; i < NB_LOG_LEVELS; i++)
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012071 hlua_class_const_int(L, log_levels[i], i);
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010012072
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010012073 /* Register special functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012074 hlua_class_function(L, "register_init", hlua_register_init);
12075 hlua_class_function(L, "register_task", hlua_register_task);
12076 hlua_class_function(L, "register_fetches", hlua_register_fetches);
12077 hlua_class_function(L, "register_converters", hlua_register_converters);
12078 hlua_class_function(L, "register_action", hlua_register_action);
12079 hlua_class_function(L, "register_service", hlua_register_service);
12080 hlua_class_function(L, "register_cli", hlua_register_cli);
Christopher Faulet69c581a2021-05-31 08:54:04 +020012081 hlua_class_function(L, "register_filter", hlua_register_filter);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012082 hlua_class_function(L, "yield", hlua_yield);
12083 hlua_class_function(L, "set_nice", hlua_set_nice);
12084 hlua_class_function(L, "sleep", hlua_sleep);
12085 hlua_class_function(L, "msleep", hlua_msleep);
12086 hlua_class_function(L, "add_acl", hlua_add_acl);
12087 hlua_class_function(L, "del_acl", hlua_del_acl);
12088 hlua_class_function(L, "set_map", hlua_set_map);
12089 hlua_class_function(L, "del_map", hlua_del_map);
12090 hlua_class_function(L, "tcp", hlua_socket_new);
William Lallemand3956c4e2021-09-21 16:25:15 +020012091 hlua_class_function(L, "httpclient", hlua_httpclient_new);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012092 hlua_class_function(L, "log", hlua_log);
12093 hlua_class_function(L, "Debug", hlua_log_debug);
12094 hlua_class_function(L, "Info", hlua_log_info);
12095 hlua_class_function(L, "Warning", hlua_log_warning);
12096 hlua_class_function(L, "Alert", hlua_log_alert);
12097 hlua_class_function(L, "done", hlua_done);
12098 hlua_fcn_reg_core_fcn(L);
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010012099
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012100 lua_setglobal(L, "core");
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010012101
12102 /*
12103 *
Christopher Faulet0f3c8902020-01-31 18:57:12 +010012104 * Create "act" object.
12105 *
12106 */
12107
12108 /* This table entry is the object "act" base. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012109 lua_newtable(L);
Christopher Faulet0f3c8902020-01-31 18:57:12 +010012110
12111 /* push action return constants */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012112 hlua_class_const_int(L, "CONTINUE", ACT_RET_CONT);
12113 hlua_class_const_int(L, "STOP", ACT_RET_STOP);
12114 hlua_class_const_int(L, "YIELD", ACT_RET_YIELD);
12115 hlua_class_const_int(L, "ERROR", ACT_RET_ERR);
12116 hlua_class_const_int(L, "DONE", ACT_RET_DONE);
12117 hlua_class_const_int(L, "DENY", ACT_RET_DENY);
12118 hlua_class_const_int(L, "ABORT", ACT_RET_ABRT);
12119 hlua_class_const_int(L, "INVALID", ACT_RET_INV);
Christopher Faulet0f3c8902020-01-31 18:57:12 +010012120
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012121 hlua_class_function(L, "wake_time", hlua_set_wake_time);
Christopher Faulet2c2c2e32020-01-31 19:07:52 +010012122
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012123 lua_setglobal(L, "act");
Christopher Faulet0f3c8902020-01-31 18:57:12 +010012124
12125 /*
12126 *
Christopher Faulet69c581a2021-05-31 08:54:04 +020012127 * Create "Filter" object.
12128 *
12129 */
12130
12131 /* This table entry is the object "filter" base. */
12132 lua_newtable(L);
12133
12134 /* push flags and constants */
12135 hlua_class_const_int(L, "CONTINUE", 1);
12136 hlua_class_const_int(L, "WAIT", 0);
12137 hlua_class_const_int(L, "ERROR", -1);
12138
12139 hlua_class_const_int(L, "FLT_CFG_FL_HTX", FLT_CFG_FL_HTX);
12140
Christopher Fauletc404f112020-02-26 15:03:09 +010012141 hlua_class_function(L, "wake_time", hlua_set_wake_time);
12142 hlua_class_function(L, "register_data_filter", hlua_register_data_filter);
12143 hlua_class_function(L, "unregister_data_filter", hlua_unregister_data_filter);
12144
Christopher Faulet69c581a2021-05-31 08:54:04 +020012145 lua_setglobal(L, "filter");
12146
12147 /*
12148 *
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012149 * Register class Map
12150 *
12151 */
12152
12153 /* This table entry is the object "Map" base. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012154 lua_newtable(L);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012155
12156 /* register pattern types. */
12157 for (i=0; i<PAT_MATCH_NUM; i++)
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012158 hlua_class_const_int(L, pat_match_names[i], i);
Thierry FOURNIER4dc71972017-01-28 08:33:08 +010012159 for (i=0; i<PAT_MATCH_NUM; i++) {
Willy Tarreau843b7cb2018-07-13 10:54:26 +020012160 snprintf(trash.area, trash.size, "_%s", pat_match_names[i]);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012161 hlua_class_const_int(L, trash.area, i);
Thierry FOURNIER4dc71972017-01-28 08:33:08 +010012162 }
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012163
12164 /* register constructor. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012165 hlua_class_function(L, "new", hlua_map_new);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012166
12167 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012168 lua_newtable(L);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012169
Ilya Shipitsind4259502020-04-08 01:07:56 +050012170 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012171 lua_pushstring(L, "__index");
12172 lua_newtable(L);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012173
12174 /* Register . */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012175 hlua_class_function(L, "lookup", hlua_map_lookup);
12176 hlua_class_function(L, "slookup", hlua_map_slookup);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012177
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012178 lua_rawset(L, -3);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012179
Thierry Fournier45e78d72016-02-19 18:34:46 +010012180 /* Register previous table in the registry with reference and named entry.
12181 * The function hlua_register_metatable() pops the stack, so we
12182 * previously create a copy of the table.
12183 */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012184 lua_pushvalue(L, -1); /* Copy the -1 entry and push it on the stack. */
12185 class_map_ref = hlua_register_metatable(L, CLASS_MAP);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012186
12187 /* Assign the metatable to the mai Map object. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012188 lua_setmetatable(L, -2);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012189
12190 /* Set a name to the table. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012191 lua_setglobal(L, "Map");
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012192
12193 /*
12194 *
William Lallemand30fcca12022-03-30 12:03:12 +020012195 * Register "CertCache" class
12196 *
12197 */
12198
12199 /* Create and fill the metatable. */
12200 lua_newtable(L);
12201 /* Register */
12202 hlua_class_function(L, "set", hlua_ckch_set);
12203 lua_setglobal(L, CLASS_CERTCACHE); /* Create global object called Regex */
12204
12205 /*
12206 *
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010012207 * Register class Channel
12208 *
12209 */
12210
12211 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012212 lua_newtable(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010012213
Ilya Shipitsind4259502020-04-08 01:07:56 +050012214 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012215 lua_pushstring(L, "__index");
12216 lua_newtable(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010012217
12218 /* Register . */
Christopher Faulet6a79fc12021-08-06 16:02:36 +020012219 hlua_class_function(L, "data", hlua_channel_get_data);
12220 hlua_class_function(L, "line", hlua_channel_get_line);
12221 hlua_class_function(L, "set", hlua_channel_set_data);
12222 hlua_class_function(L, "remove", hlua_channel_del_data);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012223 hlua_class_function(L, "append", hlua_channel_append);
Christopher Faulet6a79fc12021-08-06 16:02:36 +020012224 hlua_class_function(L, "prepend", hlua_channel_prepend);
12225 hlua_class_function(L, "insert", hlua_channel_insert_data);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012226 hlua_class_function(L, "send", hlua_channel_send);
12227 hlua_class_function(L, "forward", hlua_channel_forward);
Christopher Faulet6a79fc12021-08-06 16:02:36 +020012228 hlua_class_function(L, "input", hlua_channel_get_in_len);
12229 hlua_class_function(L, "output", hlua_channel_get_out_len);
12230 hlua_class_function(L, "may_recv", hlua_channel_may_recv);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012231 hlua_class_function(L, "is_full", hlua_channel_is_full);
12232 hlua_class_function(L, "is_resp", hlua_channel_is_resp);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010012233
Christopher Faulet6a79fc12021-08-06 16:02:36 +020012234 /* Deprecated API */
12235 hlua_class_function(L, "get", hlua_channel_get);
12236 hlua_class_function(L, "dup", hlua_channel_dup);
12237 hlua_class_function(L, "getline", hlua_channel_getline);
12238 hlua_class_function(L, "get_in_len", hlua_channel_get_in_len);
12239 hlua_class_function(L, "get_out_len", hlua_channel_get_out_len);
12240
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012241 lua_rawset(L, -3);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010012242
12243 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012244 class_channel_ref = hlua_register_metatable(L, CLASS_CHANNEL);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010012245
12246 /*
12247 *
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010012248 * Register class Fetches
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010012249 *
12250 */
12251
12252 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012253 lua_newtable(L);
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010012254
Ilya Shipitsind4259502020-04-08 01:07:56 +050012255 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012256 lua_pushstring(L, "__index");
12257 lua_newtable(L);
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010012258
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010012259 /* Browse existing fetches and create the associated
12260 * object method.
12261 */
12262 sf = NULL;
12263 while ((sf = sample_fetch_getnext(sf, &idx)) != NULL) {
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010012264 /* gL.Tua doesn't support '.' and '-' in the function names, replace it
12265 * by an underscore.
12266 */
Willy Tarreau5ef96562021-08-26 16:48:53 +020012267 strlcpy2(trash.area, sf->kw, trash.size);
Willy Tarreau843b7cb2018-07-13 10:54:26 +020012268 for (p = trash.area; *p; p++)
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010012269 if (*p == '.' || *p == '-' || *p == '+')
12270 *p = '_';
12271
12272 /* Register the function. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012273 lua_pushstring(L, trash.area);
12274 lua_pushlightuserdata(L, sf);
12275 lua_pushcclosure(L, hlua_run_sample_fetch, 1);
12276 lua_rawset(L, -3);
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010012277 }
12278
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012279 lua_rawset(L, -3);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010012280
12281 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012282 class_fetches_ref = hlua_register_metatable(L, CLASS_FETCHES);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010012283
12284 /*
12285 *
Thierry FOURNIER594afe72015-03-10 23:58:30 +010012286 * Register class Converters
12287 *
12288 */
12289
12290 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012291 lua_newtable(L);
Thierry FOURNIER594afe72015-03-10 23:58:30 +010012292
12293 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012294 lua_pushstring(L, "__index");
12295 lua_newtable(L);
Thierry FOURNIER594afe72015-03-10 23:58:30 +010012296
12297 /* Browse existing converters and create the associated
12298 * object method.
12299 */
12300 sc = NULL;
12301 while ((sc = sample_conv_getnext(sc, &idx)) != NULL) {
Thierry FOURNIER594afe72015-03-10 23:58:30 +010012302 /* gL.Tua doesn't support '.' and '-' in the function names, replace it
12303 * by an underscore.
12304 */
Willy Tarreau5ef96562021-08-26 16:48:53 +020012305 strlcpy2(trash.area, sc->kw, trash.size);
Willy Tarreau843b7cb2018-07-13 10:54:26 +020012306 for (p = trash.area; *p; p++)
Thierry FOURNIER594afe72015-03-10 23:58:30 +010012307 if (*p == '.' || *p == '-' || *p == '+')
12308 *p = '_';
12309
12310 /* Register the function. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012311 lua_pushstring(L, trash.area);
12312 lua_pushlightuserdata(L, sc);
12313 lua_pushcclosure(L, hlua_run_sample_conv, 1);
12314 lua_rawset(L, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +010012315 }
12316
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012317 lua_rawset(L, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +010012318
12319 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012320 class_converters_ref = hlua_register_metatable(L, CLASS_CONVERTERS);
Thierry FOURNIER594afe72015-03-10 23:58:30 +010012321
12322 /*
12323 *
Thierry FOURNIER08504f42015-03-16 14:17:08 +010012324 * Register class HTTP
12325 *
12326 */
12327
12328 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012329 lua_newtable(L);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010012330
Ilya Shipitsind4259502020-04-08 01:07:56 +050012331 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012332 lua_pushstring(L, "__index");
12333 lua_newtable(L);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010012334
12335 /* Register Lua functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012336 hlua_class_function(L, "req_get_headers",hlua_http_req_get_headers);
12337 hlua_class_function(L, "req_del_header", hlua_http_req_del_hdr);
12338 hlua_class_function(L, "req_rep_header", hlua_http_req_rep_hdr);
12339 hlua_class_function(L, "req_rep_value", hlua_http_req_rep_val);
12340 hlua_class_function(L, "req_add_header", hlua_http_req_add_hdr);
12341 hlua_class_function(L, "req_set_header", hlua_http_req_set_hdr);
12342 hlua_class_function(L, "req_set_method", hlua_http_req_set_meth);
12343 hlua_class_function(L, "req_set_path", hlua_http_req_set_path);
12344 hlua_class_function(L, "req_set_query", hlua_http_req_set_query);
12345 hlua_class_function(L, "req_set_uri", hlua_http_req_set_uri);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010012346
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012347 hlua_class_function(L, "res_get_headers",hlua_http_res_get_headers);
12348 hlua_class_function(L, "res_del_header", hlua_http_res_del_hdr);
12349 hlua_class_function(L, "res_rep_header", hlua_http_res_rep_hdr);
12350 hlua_class_function(L, "res_rep_value", hlua_http_res_rep_val);
12351 hlua_class_function(L, "res_add_header", hlua_http_res_add_hdr);
12352 hlua_class_function(L, "res_set_header", hlua_http_res_set_hdr);
12353 hlua_class_function(L, "res_set_status", hlua_http_res_set_status);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010012354
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012355 lua_rawset(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010012356
12357 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012358 class_http_ref = hlua_register_metatable(L, CLASS_HTTP);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010012359
Christopher Fauletdf97ac42020-02-26 16:57:19 +010012360 /*
12361 *
12362 * Register class HTTPMessage
12363 *
12364 */
12365
12366 /* Create and fill the metatable. */
12367 lua_newtable(L);
12368
Ilya Shipitsinff0f2782021-08-22 22:18:07 +050012369 /* Create and fill the __index entry. */
Christopher Fauletdf97ac42020-02-26 16:57:19 +010012370 lua_pushstring(L, "__index");
12371 lua_newtable(L);
12372
12373 /* Register Lua functions. */
12374 hlua_class_function(L, "is_resp", hlua_http_msg_is_resp);
12375 hlua_class_function(L, "get_stline", hlua_http_msg_get_stline);
12376 hlua_class_function(L, "get_headers", hlua_http_msg_get_headers);
12377 hlua_class_function(L, "del_header", hlua_http_msg_del_hdr);
12378 hlua_class_function(L, "rep_header", hlua_http_msg_rep_hdr);
12379 hlua_class_function(L, "rep_value", hlua_http_msg_rep_val);
12380 hlua_class_function(L, "add_header", hlua_http_msg_add_hdr);
12381 hlua_class_function(L, "set_header", hlua_http_msg_set_hdr);
12382 hlua_class_function(L, "set_method", hlua_http_msg_set_meth);
12383 hlua_class_function(L, "set_path", hlua_http_msg_set_path);
12384 hlua_class_function(L, "set_query", hlua_http_msg_set_query);
12385 hlua_class_function(L, "set_uri", hlua_http_msg_set_uri);
12386 hlua_class_function(L, "set_status", hlua_http_msg_set_status);
12387 hlua_class_function(L, "is_full", hlua_http_msg_is_full);
12388 hlua_class_function(L, "may_recv", hlua_http_msg_may_recv);
12389 hlua_class_function(L, "eom", hlua_http_msg_is_eom);
12390 hlua_class_function(L, "input", hlua_http_msg_get_in_len);
12391 hlua_class_function(L, "output", hlua_http_msg_get_out_len);
12392
12393 hlua_class_function(L, "body", hlua_http_msg_get_body);
12394 hlua_class_function(L, "set", hlua_http_msg_set_data);
12395 hlua_class_function(L, "remove", hlua_http_msg_del_data);
12396 hlua_class_function(L, "append", hlua_http_msg_append);
12397 hlua_class_function(L, "prepend", hlua_http_msg_prepend);
12398 hlua_class_function(L, "insert", hlua_http_msg_insert_data);
12399 hlua_class_function(L, "set_eom", hlua_http_msg_set_eom);
12400 hlua_class_function(L, "unset_eom", hlua_http_msg_unset_eom);
12401
12402 hlua_class_function(L, "send", hlua_http_msg_send);
12403 hlua_class_function(L, "forward", hlua_http_msg_forward);
12404
12405 lua_rawset(L, -3);
12406
12407 /* Register previous table in the registry with reference and named entry. */
12408 class_http_msg_ref = hlua_register_metatable(L, CLASS_HTTP_MSG);
William Lallemand3956c4e2021-09-21 16:25:15 +020012409
12410 /*
12411 *
12412 * Register class HTTPClient
12413 *
12414 */
12415
12416 /* Create and fill the metatable. */
12417 lua_newtable(L);
12418 lua_pushstring(L, "__index");
12419 lua_newtable(L);
12420 hlua_class_function(L, "get", hlua_httpclient_get);
William Lallemanddc2cc902021-10-26 11:43:26 +020012421 hlua_class_function(L, "head", hlua_httpclient_head);
12422 hlua_class_function(L, "put", hlua_httpclient_put);
12423 hlua_class_function(L, "post", hlua_httpclient_post);
12424 hlua_class_function(L, "delete", hlua_httpclient_delete);
William Lallemand3956c4e2021-09-21 16:25:15 +020012425 lua_settable(L, -3); /* Sets the __index entry. */
William Lallemandf77f1de2021-09-28 19:10:38 +020012426 /* Register the garbage collector entry. */
12427 lua_pushstring(L, "__gc");
12428 lua_pushcclosure(L, hlua_httpclient_gc, 0);
12429 lua_settable(L, -3); /* Push the last 2 entries in the table at index -3 */
12430
William Lallemand3956c4e2021-09-21 16:25:15 +020012431
12432
12433 class_httpclient_ref = hlua_register_metatable(L, CLASS_HTTPCLIENT);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010012434 /*
12435 *
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020012436 * Register class AppletTCP
12437 *
12438 */
12439
12440 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012441 lua_newtable(L);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020012442
Ilya Shipitsind4259502020-04-08 01:07:56 +050012443 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012444 lua_pushstring(L, "__index");
12445 lua_newtable(L);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020012446
12447 /* Register Lua functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012448 hlua_class_function(L, "getline", hlua_applet_tcp_getline);
12449 hlua_class_function(L, "receive", hlua_applet_tcp_recv);
12450 hlua_class_function(L, "send", hlua_applet_tcp_send);
12451 hlua_class_function(L, "set_priv", hlua_applet_tcp_set_priv);
12452 hlua_class_function(L, "get_priv", hlua_applet_tcp_get_priv);
12453 hlua_class_function(L, "set_var", hlua_applet_tcp_set_var);
12454 hlua_class_function(L, "unset_var", hlua_applet_tcp_unset_var);
12455 hlua_class_function(L, "get_var", hlua_applet_tcp_get_var);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020012456
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012457 lua_settable(L, -3);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020012458
12459 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012460 class_applet_tcp_ref = hlua_register_metatable(L, CLASS_APPLET_TCP);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020012461
12462 /*
12463 *
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020012464 * Register class AppletHTTP
12465 *
12466 */
12467
12468 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012469 lua_newtable(L);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020012470
Ilya Shipitsind4259502020-04-08 01:07:56 +050012471 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012472 lua_pushstring(L, "__index");
12473 lua_newtable(L);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020012474
12475 /* Register Lua functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012476 hlua_class_function(L, "set_priv", hlua_applet_http_set_priv);
12477 hlua_class_function(L, "get_priv", hlua_applet_http_get_priv);
12478 hlua_class_function(L, "set_var", hlua_applet_http_set_var);
12479 hlua_class_function(L, "unset_var", hlua_applet_http_unset_var);
12480 hlua_class_function(L, "get_var", hlua_applet_http_get_var);
12481 hlua_class_function(L, "getline", hlua_applet_http_getline);
12482 hlua_class_function(L, "receive", hlua_applet_http_recv);
12483 hlua_class_function(L, "send", hlua_applet_http_send);
12484 hlua_class_function(L, "add_header", hlua_applet_http_addheader);
12485 hlua_class_function(L, "set_status", hlua_applet_http_status);
12486 hlua_class_function(L, "start_response", hlua_applet_http_start_response);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020012487
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012488 lua_settable(L, -3);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020012489
12490 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012491 class_applet_http_ref = hlua_register_metatable(L, CLASS_APPLET_HTTP);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020012492
12493 /*
12494 *
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010012495 * Register class TXN
12496 *
12497 */
12498
12499 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012500 lua_newtable(L);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010012501
Ilya Shipitsind4259502020-04-08 01:07:56 +050012502 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012503 lua_pushstring(L, "__index");
12504 lua_newtable(L);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010012505
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +010012506 /* Register Lua functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012507 hlua_class_function(L, "set_priv", hlua_set_priv);
12508 hlua_class_function(L, "get_priv", hlua_get_priv);
12509 hlua_class_function(L, "set_var", hlua_set_var);
12510 hlua_class_function(L, "unset_var", hlua_unset_var);
12511 hlua_class_function(L, "get_var", hlua_get_var);
12512 hlua_class_function(L, "done", hlua_txn_done);
12513 hlua_class_function(L, "reply", hlua_txn_reply_new);
12514 hlua_class_function(L, "set_loglevel", hlua_txn_set_loglevel);
12515 hlua_class_function(L, "set_tos", hlua_txn_set_tos);
12516 hlua_class_function(L, "set_mark", hlua_txn_set_mark);
12517 hlua_class_function(L, "set_priority_class", hlua_txn_set_priority_class);
12518 hlua_class_function(L, "set_priority_offset", hlua_txn_set_priority_offset);
12519 hlua_class_function(L, "deflog", hlua_txn_deflog);
12520 hlua_class_function(L, "log", hlua_txn_log);
12521 hlua_class_function(L, "Debug", hlua_txn_log_debug);
12522 hlua_class_function(L, "Info", hlua_txn_log_info);
12523 hlua_class_function(L, "Warning", hlua_txn_log_warning);
12524 hlua_class_function(L, "Alert", hlua_txn_log_alert);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +010012525
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012526 lua_rawset(L, -3);
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010012527
12528 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012529 class_txn_ref = hlua_register_metatable(L, CLASS_TXN);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012530
12531 /*
12532 *
Christopher Faulet700d9e82020-01-31 12:21:52 +010012533 * Register class reply
12534 *
12535 */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012536 lua_newtable(L);
12537 lua_pushstring(L, "__index");
12538 lua_newtable(L);
12539 hlua_class_function(L, "set_status", hlua_txn_reply_set_status);
12540 hlua_class_function(L, "add_header", hlua_txn_reply_add_header);
12541 hlua_class_function(L, "del_header", hlua_txn_reply_del_header);
12542 hlua_class_function(L, "set_body", hlua_txn_reply_set_body);
12543 lua_settable(L, -3); /* Sets the __index entry. */
12544 class_txn_reply_ref = luaL_ref(L, LUA_REGISTRYINDEX);
Christopher Faulet700d9e82020-01-31 12:21:52 +010012545
12546
12547 /*
12548 *
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012549 * Register class Socket
12550 *
12551 */
12552
12553 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012554 lua_newtable(L);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012555
Ilya Shipitsind4259502020-04-08 01:07:56 +050012556 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012557 lua_pushstring(L, "__index");
12558 lua_newtable(L);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012559
Baptiste Assmann84bb4932015-03-02 21:40:06 +010012560#ifdef USE_OPENSSL
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012561 hlua_class_function(L, "connect_ssl", hlua_socket_connect_ssl);
Baptiste Assmann84bb4932015-03-02 21:40:06 +010012562#endif
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012563 hlua_class_function(L, "connect", hlua_socket_connect);
12564 hlua_class_function(L, "send", hlua_socket_send);
12565 hlua_class_function(L, "receive", hlua_socket_receive);
12566 hlua_class_function(L, "close", hlua_socket_close);
12567 hlua_class_function(L, "getpeername", hlua_socket_getpeername);
12568 hlua_class_function(L, "getsockname", hlua_socket_getsockname);
12569 hlua_class_function(L, "setoption", hlua_socket_setoption);
12570 hlua_class_function(L, "settimeout", hlua_socket_settimeout);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012571
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012572 lua_rawset(L, -3); /* Push the last 2 entries in the table at index -3 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012573
12574 /* Register the garbage collector entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012575 lua_pushstring(L, "__gc");
12576 lua_pushcclosure(L, hlua_socket_gc, 0);
12577 lua_rawset(L, -3); /* Push the last 2 entries in the table at index -3 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012578
12579 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012580 class_socket_ref = hlua_register_metatable(L, CLASS_SOCKET);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012581
Thierry Fournieraafc7772020-12-04 11:47:47 +010012582 lua_atpanic(L, hlua_panic_safe);
12583
12584 return L;
12585}
12586
12587void hlua_init(void) {
12588 int i;
Amaury Denoyelle239fdbf2021-03-24 10:22:03 +010012589 char *errmsg;
Thierry Fournieraafc7772020-12-04 11:47:47 +010012590#ifdef USE_OPENSSL
12591 struct srv_kw *kw;
12592 int tmp_error;
12593 char *error;
12594 char *args[] = { /* SSL client configuration. */
12595 "ssl",
12596 "verify",
12597 "none",
12598 NULL
12599 };
12600#endif
12601
12602 /* Init post init function list head */
12603 for (i = 0; i < MAX_THREADS + 1; i++)
12604 LIST_INIT(&hlua_init_functions[i]);
12605
12606 /* Init state for common/shared lua parts */
12607 hlua_state_id = 0;
Willy Tarreau43ab05b2021-09-28 09:43:11 +020012608 ha_set_thread(NULL);
Thierry Fournieraafc7772020-12-04 11:47:47 +010012609 hlua_states[0] = hlua_init_state(0);
12610
12611 /* Init state 1 for thread 0. We have at least one thread. */
12612 hlua_state_id = 1;
Willy Tarreau43ab05b2021-09-28 09:43:11 +020012613 ha_set_thread(NULL);
Thierry Fournieraafc7772020-12-04 11:47:47 +010012614 hlua_states[1] = hlua_init_state(1);
12615
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012616 /* Proxy and server configuration initialisation. */
William Lallemand6bb77b92021-07-28 15:48:16 +020012617 socket_proxy = alloc_new_proxy("LUA-SOCKET", PR_CAP_FE|PR_CAP_BE|PR_CAP_INT, &errmsg);
Amaury Denoyelle239fdbf2021-03-24 10:22:03 +010012618 if (!socket_proxy) {
12619 fprintf(stderr, "Lua init: %s\n", errmsg);
12620 exit(1);
12621 }
12622 proxy_preset_defaults(socket_proxy);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012623
12624 /* Init TCP server: unchanged parameters */
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010012625 socket_tcp = new_server(socket_proxy);
12626 if (!socket_tcp) {
12627 fprintf(stderr, "Lua init: failed to allocate tcp server socket\n");
12628 exit(1);
12629 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012630
12631#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012632 /* Init TCP server: unchanged parameters */
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010012633 socket_ssl = new_server(socket_proxy);
12634 if (!socket_ssl) {
12635 fprintf(stderr, "Lua init: failed to allocate ssl server socket\n");
12636 exit(1);
12637 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012638
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010012639 socket_ssl->use_ssl = 1;
12640 socket_ssl->xprt = xprt_get(XPRT_SSL);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012641
Bertrand Jacquin80839ff2021-01-21 19:14:46 +000012642 for (i = 0; args[i] != NULL; i++) {
12643 if ((kw = srv_find_kw(args[i])) != NULL) { /* Maybe it's registered server keyword */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012644 /*
12645 *
12646 * If the keyword is not known, we can search in the registered
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -080012647 * server keywords. This is useful to configure special SSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012648 * features like client certificates and ssl_verify.
12649 *
12650 */
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010012651 tmp_error = kw->parse(args, &i, socket_proxy, socket_ssl, &error);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012652 if (tmp_error != 0) {
12653 fprintf(stderr, "INTERNAL ERROR: %s\n", error);
12654 abort(); /* This must be never arrives because the command line
12655 not editable by the user. */
12656 }
Bertrand Jacquin80839ff2021-01-21 19:14:46 +000012657 i += kw->skip;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012658 }
12659 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012660#endif
Thierry Fournier75933d42016-01-21 09:30:18 +010012661
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +010012662}
Willy Tarreaubb57d942016-12-21 19:04:56 +010012663
Tim Duesterhusd0c0ca22020-07-04 11:53:26 +020012664static void hlua_deinit()
12665{
Willy Tarreau186f3762020-12-04 11:48:12 +010012666 int thr;
Christopher Faulet69c581a2021-05-31 08:54:04 +020012667 struct hlua_reg_filter *reg_flt, *reg_flt_bck;
12668
12669 list_for_each_entry_safe(reg_flt, reg_flt_bck, &referenced_filters, l)
12670 release_hlua_reg_filter(reg_flt);
Willy Tarreau186f3762020-12-04 11:48:12 +010012671
12672 for (thr = 0; thr < MAX_THREADS+1; thr++) {
12673 if (hlua_states[thr])
12674 lua_close(hlua_states[thr]);
12675 }
Willy Tarreau430bf4a2021-03-04 09:45:32 +010012676
Amaury Denoyellebc2ebfa2021-08-25 15:34:53 +020012677 srv_drop(socket_tcp);
Willy Tarreau430bf4a2021-03-04 09:45:32 +010012678
Willy Tarreau0f143af2021-03-05 10:41:48 +010012679#ifdef USE_OPENSSL
Amaury Denoyellebc2ebfa2021-08-25 15:34:53 +020012680 srv_drop(socket_ssl);
Willy Tarreau0f143af2021-03-05 10:41:48 +010012681#endif
Amaury Denoyelle239fdbf2021-03-24 10:22:03 +010012682
12683 free_proxy(socket_proxy);
Tim Duesterhusd0c0ca22020-07-04 11:53:26 +020012684}
12685
12686REGISTER_POST_DEINIT(hlua_deinit);
12687
Willy Tarreau80713382018-11-26 10:19:54 +010012688static void hlua_register_build_options(void)
12689{
Willy Tarreaubb57d942016-12-21 19:04:56 +010012690 char *ptr = NULL;
Willy Tarreau80713382018-11-26 10:19:54 +010012691
Willy Tarreaubb57d942016-12-21 19:04:56 +010012692 memprintf(&ptr, "Built with Lua version : %s", LUA_RELEASE);
12693 hap_register_build_opts(ptr, 1);
12694}
Willy Tarreau80713382018-11-26 10:19:54 +010012695
12696INITCALL0(STG_REGISTER, hlua_register_build_options);