blob: 2ea15b995438d5b91be86e2e0592c6718e75afd4 [file] [log] [blame]
Thierry Fourniere726b142016-02-11 17:57:57 +01001/*
2 * Lua unsafe core engine
3 *
4 * Copyright 2015-2016 Thierry Fournier <tfournier@arpalert.org>
5 *
6 * This program is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU General Public License
8 * as published by the Free Software Foundation; either version
9 * 2 of the License, or (at your option) any later version.
10 *
11 */
12
Bertrand Jacquinf4c12d42021-01-21 21:14:07 +000013#define _GNU_SOURCE
14
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +010015#include <ctype.h>
Thierry FOURNIERbabae282015-09-17 11:36:37 +020016#include <setjmp.h>
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +010017
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +010018#include <lauxlib.h>
19#include <lua.h>
20#include <lualib.h>
21
Thierry FOURNIER463119c2015-03-10 00:35:36 +010022#if !defined(LUA_VERSION_NUM) || LUA_VERSION_NUM < 503
23#error "Requires Lua 5.3 or later."
Cyril Bontédc0306e2015-03-02 00:08:40 +010024#endif
25
Willy Tarreau8d2b7772020-05-27 10:58:19 +020026#include <import/ebpttree.h>
Thierry FOURNIER380d0932015-01-23 14:27:52 +010027
Willy Tarreaub2551052020-06-09 09:07:15 +020028#include <haproxy/api.h>
29#include <haproxy/applet.h>
Willy Tarreaudfd3de82020-06-04 23:46:14 +020030#include <haproxy/arg.h>
Christopher Fauletd25d9262020-08-06 11:04:46 +020031#include <haproxy/auth.h>
Willy Tarreau6be78492020-06-05 00:00:29 +020032#include <haproxy/cfgparse.h>
Willy Tarreauf1d32c42020-06-04 21:07:02 +020033#include <haproxy/channel.h>
Willy Tarreau83487a82020-06-04 20:19:54 +020034#include <haproxy/cli.h>
Willy Tarreau55542642021-10-08 09:33:24 +020035#include <haproxy/clock.h>
Willy Tarreau7ea393d2020-06-04 18:02:10 +020036#include <haproxy/connection.h>
Christopher Faulet69c581a2021-05-31 08:54:04 +020037#include <haproxy/filters.h>
Willy Tarreau5413a872020-06-02 19:33:08 +020038#include <haproxy/h1.h>
Willy Tarreau86416052020-06-04 09:20:54 +020039#include <haproxy/hlua.h>
Willy Tarreau8c794002020-06-04 10:05:25 +020040#include <haproxy/hlua_fcn.h>
Willy Tarreauc2b1ff02020-06-04 21:21:03 +020041#include <haproxy/http_ana.h>
William Lallemand3956c4e2021-09-21 16:25:15 +020042#include <haproxy/http_client.h>
Willy Tarreau126ba3a2020-06-04 18:26:43 +020043#include <haproxy/http_fetch.h>
Willy Tarreaub2551052020-06-09 09:07:15 +020044#include <haproxy/http_htx.h>
Willy Tarreauc761f842020-06-04 11:40:28 +020045#include <haproxy/http_rules.h>
Willy Tarreau36979d92020-06-05 17:27:29 +020046#include <haproxy/log.h>
Willy Tarreau2cd58092020-06-04 15:10:43 +020047#include <haproxy/map.h>
Willy Tarreau8efbdfb2020-06-04 11:29:21 +020048#include <haproxy/obj_type.h>
Willy Tarreau225a90a2020-06-04 15:06:28 +020049#include <haproxy/pattern.h>
Willy Tarreau469509b2020-06-04 15:13:30 +020050#include <haproxy/payload.h>
Willy Tarreau3d6ee402021-05-08 20:28:07 +020051#include <haproxy/proxy.h>
Willy Tarreaub2551052020-06-09 09:07:15 +020052#include <haproxy/regex.h>
Willy Tarreaue6ce10b2020-06-04 15:33:47 +020053#include <haproxy/sample.h>
Willy Tarreau5edca2f2022-05-27 09:25:10 +020054#include <haproxy/sc_strm.h>
Willy Tarreau198e92a2021-03-05 10:23:32 +010055#include <haproxy/server.h>
Willy Tarreau48d25b32020-06-04 18:58:52 +020056#include <haproxy/session.h>
William Lallemand30fcca12022-03-30 12:03:12 +020057#include <haproxy/ssl_ckch.h>
58#include <haproxy/ssl_sock.h>
Willy Tarreau2eec9b52020-06-04 19:58:55 +020059#include <haproxy/stats-t.h>
Willy Tarreaucb086c62022-05-27 09:47:12 +020060#include <haproxy/stconn.h>
Willy Tarreaudfd3de82020-06-04 23:46:14 +020061#include <haproxy/stream.h>
Willy Tarreaucea0e1b2020-06-04 17:25:40 +020062#include <haproxy/task.h>
Willy Tarreau8b550af2020-06-04 17:42:48 +020063#include <haproxy/tcp_rules.h>
Willy Tarreaub2551052020-06-09 09:07:15 +020064#include <haproxy/thread.h>
Willy Tarreau48fbcae2020-06-03 18:09:46 +020065#include <haproxy/tools.h>
Willy Tarreaua1718922020-06-04 16:25:31 +020066#include <haproxy/vars.h>
Willy Tarreaub2551052020-06-09 09:07:15 +020067#include <haproxy/xref.h>
68
Thierry FOURNIER380d0932015-01-23 14:27:52 +010069
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +010070/* Lua uses longjmp to perform yield or throwing errors. This
71 * macro is used only for identifying the function that can
72 * not return because a longjmp is executed.
73 * __LJMP marks a prototype of hlua file that can use longjmp.
74 * WILL_LJMP() marks an lua function that will use longjmp.
75 * MAY_LJMP() marks an lua function that may use longjmp.
76 */
77#define __LJMP
Willy Tarreau4e7cc332018-10-20 17:45:48 +020078#define WILL_LJMP(func) do { func; my_unreachable(); } while(0)
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +010079#define MAY_LJMP(func) func
80
Thierry FOURNIERbabae282015-09-17 11:36:37 +020081/* This couple of function executes securely some Lua calls outside of
82 * the lua runtime environment. Each Lua call can return a longjmp
83 * if it encounter a memory error.
84 *
85 * Lua documentation extract:
86 *
87 * If an error happens outside any protected environment, Lua calls
88 * a panic function (see lua_atpanic) and then calls abort, thus
89 * exiting the host application. Your panic function can avoid this
90 * exit by never returning (e.g., doing a long jump to your own
91 * recovery point outside Lua).
92 *
93 * The panic function runs as if it were a message handler (see
Willy Tarreau3dfb7da2022-03-02 22:33:39 +010094 * #2.3); in particular, the error message is at the top of the
Thierry FOURNIERbabae282015-09-17 11:36:37 +020095 * stack. However, there is no guarantee about stack space. To push
96 * anything on the stack, the panic function must first check the
Willy Tarreau3dfb7da2022-03-02 22:33:39 +010097 * available space (see #4.2).
Thierry FOURNIERbabae282015-09-17 11:36:37 +020098 *
99 * We must check all the Lua entry point. This includes:
100 * - The include/proto/hlua.h exported functions
101 * - the task wrapper function
102 * - The action wrapper function
103 * - The converters wrapper function
104 * - The sample-fetch wrapper functions
105 *
Ilya Shipitsin46a030c2020-07-05 16:36:08 +0500106 * It is tolerated that the initialisation function returns an abort.
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -0800107 * Before each Lua abort, an error message is written on stderr.
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200108 *
109 * The macro SET_SAFE_LJMP initialise the longjmp. The Macro
110 * RESET_SAFE_LJMP reset the longjmp. These function must be macro
111 * because they must be exists in the program stack when the longjmp
112 * is called.
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +0200113 *
114 * Note that the Lua processing is not really thread safe. It provides
115 * heavy system which consists to add our own lock function in the Lua
116 * code and recompile the library. This system will probably not accepted
117 * by maintainers of various distribs.
118 *
Ilya Shipitsin856aabc2020-04-16 23:51:34 +0500119 * Our main execution point of the Lua is the function lua_resume(). A
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +0200120 * quick looking on the Lua sources displays a lua_lock() a the start
121 * of function and a lua_unlock() at the end of the function. So I
122 * conclude that the Lua thread safe mode just perform a mutex around
123 * all execution. So I prefer to do this in the HAProxy code, it will be
124 * easier for distro maintainers.
125 *
126 * Note that the HAProxy lua functions rounded by the macro SET_SAFE_LJMP
127 * and RESET_SAFE_LJMP manipulates the Lua stack, so it will be careful
128 * to set mutex around these functions.
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200129 */
Willy Tarreau86abe442018-11-25 20:12:18 +0100130__decl_spinlock(hlua_global_lock);
Thierry FOURNIERffbad792017-07-12 11:39:04 +0200131THREAD_LOCAL jmp_buf safe_ljmp_env;
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200132static int hlua_panic_safe(lua_State *L) { return 0; }
Willy Tarreau6a510902021-07-14 19:41:25 +0200133static int hlua_panic_ljmp(lua_State *L) { WILL_LJMP(longjmp(safe_ljmp_env, 1)); return 0; }
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200134
Thierry Fournier62a22aa2020-11-28 21:06:35 +0100135/* This is the chained list of struct hlua_function referenced
136 * for haproxy action, sample-fetches, converters, cli and
137 * applet bindings. It is used for a post-initialisation control.
138 */
139static struct list referenced_functions = LIST_HEAD_INIT(referenced_functions);
140
Thierry Fournierc7492592020-11-28 23:57:24 +0100141/* This variable is used only during initialization to identify the Lua state
142 * currently being initialized. 0 is the common lua state, 1 to n are the Lua
143 * states dedicated to each thread (in this case hlua_state_id==tid+1).
144 */
145static int hlua_state_id;
146
Thierry Fournier59f11be2020-11-29 00:37:41 +0100147/* This is a NULL-terminated list of lua file which are referenced to load per thread */
Thierry Fournierae6b5682022-09-19 09:04:16 +0200148static char ***per_thread_load = NULL;
Thierry Fournier59f11be2020-11-29 00:37:41 +0100149
150lua_State *hlua_init_state(int thread_id);
151
Willy Tarreau1e7bef12021-08-20 15:47:25 +0200152/* This function takes the Lua global lock. Keep this function's visibility
153 * global so that it can appear in stack dumps and performance profiles!
154 */
155void lua_take_global_lock()
156{
157 HA_SPIN_LOCK(LUA_LOCK, &hlua_global_lock);
158}
159
160static inline void lua_drop_global_lock()
161{
162 HA_SPIN_UNLOCK(LUA_LOCK, &hlua_global_lock);
163}
164
Thierry Fournier7cbe5042020-11-28 17:02:21 +0100165#define SET_SAFE_LJMP_L(__L, __HLUA) \
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200166 ({ \
167 int ret; \
Thierry Fournier021d9862020-11-28 23:42:03 +0100168 if ((__HLUA)->state_id == 0) \
Willy Tarreau1e7bef12021-08-20 15:47:25 +0200169 lua_take_global_lock(); \
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200170 if (setjmp(safe_ljmp_env) != 0) { \
171 lua_atpanic(__L, hlua_panic_safe); \
172 ret = 0; \
Thierry Fournier021d9862020-11-28 23:42:03 +0100173 if ((__HLUA)->state_id == 0) \
Willy Tarreau1e7bef12021-08-20 15:47:25 +0200174 lua_drop_global_lock(); \
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200175 } else { \
176 lua_atpanic(__L, hlua_panic_ljmp); \
177 ret = 1; \
178 } \
179 ret; \
180 })
181
182/* If we are the last function catching Lua errors, we
183 * must reset the panic function.
184 */
Thierry Fournier7cbe5042020-11-28 17:02:21 +0100185#define RESET_SAFE_LJMP_L(__L, __HLUA) \
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200186 do { \
187 lua_atpanic(__L, hlua_panic_safe); \
Thierry Fournier021d9862020-11-28 23:42:03 +0100188 if ((__HLUA)->state_id == 0) \
Willy Tarreau1e7bef12021-08-20 15:47:25 +0200189 lua_drop_global_lock(); \
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200190 } while(0)
191
Thierry Fournier7cbe5042020-11-28 17:02:21 +0100192#define SET_SAFE_LJMP(__HLUA) \
193 SET_SAFE_LJMP_L((__HLUA)->T, __HLUA)
194
195#define RESET_SAFE_LJMP(__HLUA) \
196 RESET_SAFE_LJMP_L((__HLUA)->T, __HLUA)
197
198#define SET_SAFE_LJMP_PARENT(__HLUA) \
Thierry Fournier021d9862020-11-28 23:42:03 +0100199 SET_SAFE_LJMP_L(hlua_states[(__HLUA)->state_id], __HLUA)
Thierry Fournier7cbe5042020-11-28 17:02:21 +0100200
201#define RESET_SAFE_LJMP_PARENT(__HLUA) \
Thierry Fournier021d9862020-11-28 23:42:03 +0100202 RESET_SAFE_LJMP_L(hlua_states[(__HLUA)->state_id], __HLUA)
Thierry Fournier7cbe5042020-11-28 17:02:21 +0100203
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +0200204/* Applet status flags */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200205#define APPLET_DONE 0x01 /* applet processing is done. */
Christopher Faulet18c2e8d2019-03-01 12:02:08 +0100206/* unused: 0x02 */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200207#define APPLET_HDR_SENT 0x04 /* Response header sent. */
Christopher Fauleta2097962019-07-15 16:25:33 +0200208/* unused: 0x08, 0x10 */
Thierry FOURNIERd93ea2b2015-12-20 19:14:52 +0100209#define APPLET_HTTP11 0x20 /* Last chunk sent. */
Christopher Faulet56a3d6e2019-02-27 22:06:23 +0100210#define APPLET_RSP_SENT 0x40 /* The response was fully sent */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200211
Thierry Fournierafc63e22020-11-28 17:06:51 +0100212/* The main Lua execution context. The 0 index is the
213 * common state shared by all threads.
214 */
Willy Tarreau186f3762020-12-04 11:48:12 +0100215static lua_State *hlua_states[MAX_THREADS + 1];
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100216
Christopher Fauletc404f112020-02-26 15:03:09 +0100217#define HLUA_FLT_CB_FINAL 0x00000001
218#define HLUA_FLT_CB_RETVAL 0x00000002
219#define HLUA_FLT_CB_ARG_CHN 0x00000004
220#define HLUA_FLT_CB_ARG_HTTP_MSG 0x00000008
221
Christopher Faulet9f55a502020-02-25 15:21:02 +0100222#define HLUA_FLT_CTX_FL_PAYLOAD 0x00000001
223
Christopher Faulet69c581a2021-05-31 08:54:04 +0200224struct hlua_reg_filter {
225 char *name;
226 int flt_ref[MAX_THREADS + 1];
227 int fun_ref[MAX_THREADS + 1];
228 struct list l;
229};
230
231struct hlua_flt_config {
232 struct hlua_reg_filter *reg;
233 int ref[MAX_THREADS + 1];
234 char **args;
235};
236
237struct hlua_flt_ctx {
238 int ref; /* ref to the filter lua object */
239 struct hlua *hlua[2]; /* lua runtime context (0: request, 1: response) */
240 unsigned int cur_off[2]; /* current offset (0: request, 1: response) */
241 unsigned int cur_len[2]; /* current forwardable length (0: request, 1: response) */
242 unsigned int flags; /* HLUA_FLT_CTX_FL_* */
243};
244
Willy Tarreau5321da92022-05-06 11:57:34 +0200245/* appctx context used by the cosockets */
246struct hlua_csk_ctx {
247 int connected;
248 struct xref xref; /* cross reference with the Lua object owner. */
249 struct list wake_on_read;
250 struct list wake_on_write;
251 struct appctx *appctx;
252 int die;
253};
254
Willy Tarreaue23f33b2022-05-06 14:07:13 +0200255/* appctx context used by TCP services */
256struct hlua_tcp_ctx {
257 struct hlua *hlua;
258 int flags;
259 struct task *task;
260};
261
Willy Tarreauaa229cc2022-05-06 14:26:10 +0200262/* appctx context used by HTTP services */
263struct hlua_http_ctx {
264 struct hlua *hlua;
265 int left_bytes; /* The max amount of bytes that we can read. */
266 int flags;
267 int status;
268 const char *reason;
269 struct task *task;
270};
271
Willy Tarreaubcda5f62022-05-03 18:13:39 +0200272/* used by registered CLI keywords */
273struct hlua_cli_ctx {
274 struct hlua *hlua;
275 struct task *task;
276 struct hlua_function *fcn;
277};
278
Christopher Faulet69c581a2021-05-31 08:54:04 +0200279DECLARE_STATIC_POOL(pool_head_hlua_flt_ctx, "hlua_flt_ctx", sizeof(struct hlua_flt_ctx));
280
Christopher Faulet9f55a502020-02-25 15:21:02 +0100281static int hlua_filter_from_payload(struct filter *filter);
282
Christopher Faulet69c581a2021-05-31 08:54:04 +0200283/* This is the chained list of struct hlua_flt referenced
284 * for haproxy filters. It is used for a post-initialisation control.
285 */
286static struct list referenced_filters = LIST_HEAD_INIT(referenced_filters);
287
288
Thierry FOURNIERebed6e92016-12-16 11:54:07 +0100289/* This is the memory pool containing struct lua for applets
290 * (including cli).
291 */
Willy Tarreau8ceae722018-11-26 11:58:30 +0100292DECLARE_STATIC_POOL(pool_head_hlua, "hlua", sizeof(struct hlua));
Thierry FOURNIERebed6e92016-12-16 11:54:07 +0100293
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +0100294/* Used for Socket connection. */
Amaury Denoyelle239fdbf2021-03-24 10:22:03 +0100295static struct proxy *socket_proxy;
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +0100296static struct server *socket_tcp;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +0100297#ifdef USE_OPENSSL
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +0100298static struct server *socket_ssl;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +0100299#endif
300
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +0100301/* List head of the function called at the initialisation time. */
Thierry Fournierc7492592020-11-28 23:57:24 +0100302struct list hlua_init_functions[MAX_THREADS + 1];
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +0100303
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +0100304/* The following variables contains the reference of the different
305 * Lua classes. These references are useful for identify metadata
306 * associated with an object.
307 */
Thierry FOURNIER65f34c62015-02-16 20:11:43 +0100308static int class_txn_ref;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +0100309static int class_socket_ref;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +0100310static int class_channel_ref;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +0100311static int class_fetches_ref;
Thierry FOURNIER594afe72015-03-10 23:58:30 +0100312static int class_converters_ref;
Thierry FOURNIER08504f42015-03-16 14:17:08 +0100313static int class_http_ref;
Christopher Fauletdf97ac42020-02-26 16:57:19 +0100314static int class_http_msg_ref;
William Lallemand3956c4e2021-09-21 16:25:15 +0200315static int class_httpclient_ref;
Thierry FOURNIER3def3932015-04-07 11:27:54 +0200316static int class_map_ref;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +0200317static int class_applet_tcp_ref;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200318static int class_applet_http_ref;
Christopher Faulet700d9e82020-01-31 12:21:52 +0100319static int class_txn_reply_ref;
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +0100320
Thierry FOURNIERbd413492015-03-03 16:52:26 +0100321/* Global Lua execution timeout. By default Lua, execution linked
Willy Tarreau87b09662015-04-03 00:22:06 +0200322 * with stream (actions, sample-fetches and converters) have a
Thierry FOURNIERbd413492015-03-03 16:52:26 +0100323 * short timeout. Lua linked with tasks doesn't have a timeout
324 * because a task may remain alive during all the haproxy execution.
325 */
326static unsigned int hlua_timeout_session = 4000; /* session timeout. */
327static unsigned int hlua_timeout_task = TICK_ETERNITY; /* task timeout. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +0200328static unsigned int hlua_timeout_applet = 4000; /* applet timeout. */
Thierry FOURNIERbd413492015-03-03 16:52:26 +0100329
Thierry FOURNIERee9f8022015-03-03 17:37:37 +0100330/* Interrupts the Lua processing each "hlua_nb_instruction" instructions.
331 * it is used for preventing infinite loops.
332 *
333 * I test the scheer with an infinite loop containing one incrementation
334 * and one test. I run this loop between 10 seconds, I raise a ceil of
335 * 710M loops from one interrupt each 9000 instructions, so I fix the value
336 * to one interrupt each 10 000 instructions.
337 *
338 * configured | Number of
339 * instructions | loops executed
340 * between two | in milions
341 * forced yields |
342 * ---------------+---------------
343 * 10 | 160
344 * 500 | 670
345 * 1000 | 680
346 * 5000 | 700
347 * 7000 | 700
348 * 8000 | 700
349 * 9000 | 710 <- ceil
350 * 10000 | 710
351 * 100000 | 710
352 * 1000000 | 710
353 *
354 */
355static unsigned int hlua_nb_instruction = 10000;
356
Willy Tarreaucdb53462020-12-02 12:12:00 +0100357/* Descriptor for the memory allocation state. The limit is pre-initialised to
358 * 0 until it is replaced by "tune.lua.maxmem" during the config parsing, or it
359 * is replaced with ~0 during post_init after everything was loaded. This way
360 * it is guaranteed that if limit is ~0 the boot is complete and that if it's
361 * zero it's not yet limited and proper accounting is required.
Willy Tarreau32f61e22015-03-18 17:54:59 +0100362 */
363struct hlua_mem_allocator {
364 size_t allocated;
365 size_t limit;
366};
367
Willy Tarreaucdb53462020-12-02 12:12:00 +0100368static struct hlua_mem_allocator hlua_global_allocator THREAD_ALIGNED(64);
Willy Tarreau32f61e22015-03-18 17:54:59 +0100369
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100370/* These functions converts types between HAProxy internal args or
371 * sample and LUA types. Another function permits to check if the
372 * LUA stack contains arguments according with an required ARG_T
373 * format.
374 */
375static int hlua_arg2lua(lua_State *L, const struct arg *arg);
376static int hlua_lua2arg(lua_State *L, int ud, struct arg *arg);
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100377__LJMP static int hlua_lua2arg_check(lua_State *L, int first, struct arg *argp,
David Carlier0c437f42016-04-27 16:21:56 +0100378 uint64_t mask, struct proxy *p);
Willy Tarreau5eadada2015-03-10 17:28:54 +0100379static int hlua_smp2lua(lua_State *L, struct sample *smp);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100380static int hlua_smp2lua_str(lua_State *L, struct sample *smp);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100381static int hlua_lua2smp(lua_State *L, int ud, struct sample *smp);
382
Christopher Faulet9d1332b2020-02-24 16:46:16 +0100383__LJMP static int hlua_http_get_headers(lua_State *L, struct http_msg *msg);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200384
Thierry Fournier59f11be2020-11-29 00:37:41 +0100385struct prepend_path {
386 struct list l;
387 char *type;
388 char *path;
389};
390
391static struct list prepend_path_list = LIST_HEAD_INIT(prepend_path_list);
392
Thierry FOURNIER23bc3752015-09-11 19:15:43 +0200393#define SEND_ERR(__be, __fmt, __args...) \
394 do { \
395 send_log(__be, LOG_ERR, __fmt, ## __args); \
396 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE)) \
Christopher Faulet767a84b2017-11-24 16:50:31 +0100397 ha_alert(__fmt, ## __args); \
Thierry FOURNIER23bc3752015-09-11 19:15:43 +0200398 } while (0)
399
Thierry Fournier62a22aa2020-11-28 21:06:35 +0100400static inline struct hlua_function *new_hlua_function()
401{
402 struct hlua_function *fcn;
Thierry Fournierc7492592020-11-28 23:57:24 +0100403 int i;
Thierry Fournier62a22aa2020-11-28 21:06:35 +0100404
405 fcn = calloc(1, sizeof(*fcn));
406 if (!fcn)
407 return NULL;
Willy Tarreau2b718102021-04-21 07:32:39 +0200408 LIST_APPEND(&referenced_functions, &fcn->l);
Thierry Fournierc7492592020-11-28 23:57:24 +0100409 for (i = 0; i < MAX_THREADS + 1; i++)
410 fcn->function_ref[i] = -1;
Thierry Fournier62a22aa2020-11-28 21:06:35 +0100411 return fcn;
412}
413
Christopher Fauletdda44442021-04-12 14:05:43 +0200414static inline void release_hlua_function(struct hlua_function *fcn)
415{
416 if (!fcn)
417 return;
418 if (fcn->name)
419 ha_free(&fcn->name);
Willy Tarreau2b718102021-04-21 07:32:39 +0200420 LIST_DELETE(&fcn->l);
Christopher Fauletdda44442021-04-12 14:05:43 +0200421 ha_free(&fcn);
422}
423
Thierry Fournierc7492592020-11-28 23:57:24 +0100424/* If the common state is set, the stack id is 0, otherwise it is the tid + 1 */
425static inline int fcn_ref_to_stack_id(struct hlua_function *fcn)
426{
427 if (fcn->function_ref[0] == -1)
428 return tid + 1;
429 return 0;
430}
431
Christopher Faulet69c581a2021-05-31 08:54:04 +0200432/* Create a new registered filter. Only its name is filled */
433static inline struct hlua_reg_filter *new_hlua_reg_filter(const char *name)
434{
435 struct hlua_reg_filter *reg_flt;
436 int i;
437
438 reg_flt = calloc(1, sizeof(*reg_flt));
439 if (!reg_flt)
440 return NULL;
441 reg_flt->name = strdup(name);
442 if (!reg_flt->name) {
443 free(reg_flt);
444 return NULL;
445 }
446 LIST_APPEND(&referenced_filters, &reg_flt->l);
447 for (i = 0; i < MAX_THREADS + 1; i++) {
448 reg_flt->flt_ref[i] = -1;
449 reg_flt->fun_ref[i] = -1;
450 }
451 return reg_flt;
452}
453
454/* Release a registered filter */
455static inline void release_hlua_reg_filter(struct hlua_reg_filter *reg_flt)
456{
457 if (!reg_flt)
458 return;
459 if (reg_flt->name)
460 ha_free(&reg_flt->name);
461 LIST_DELETE(&reg_flt->l);
462 ha_free(&reg_flt);
463}
464
465/* If the common state is set, the stack id is 0, otherwise it is the tid + 1 */
466static inline int reg_flt_to_stack_id(struct hlua_reg_filter *reg_flt)
467{
468 if (reg_flt->fun_ref[0] == -1)
469 return tid + 1;
470 return 0;
471}
472
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100473/* Used to check an Lua function type in the stack. It creates and
474 * returns a reference of the function. This function throws an
475 * error if the rgument is not a "function".
476 */
477__LJMP unsigned int hlua_checkfunction(lua_State *L, int argno)
478{
479 if (!lua_isfunction(L, argno)) {
Thierry FOURNIERfd1e9552018-02-23 18:41:18 +0100480 const char *msg = lua_pushfstring(L, "function expected, got %s", luaL_typename(L, argno));
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100481 WILL_LJMP(luaL_argerror(L, argno, msg));
482 }
483 lua_pushvalue(L, argno);
484 return luaL_ref(L, LUA_REGISTRYINDEX);
485}
486
Christopher Fauletba9e21d2020-02-25 10:20:04 +0100487/* Used to check an Lua table type in the stack. It creates and
488 * returns a reference of the table. This function throws an
489 * error if the rgument is not a "table".
490 */
491__LJMP unsigned int hlua_checktable(lua_State *L, int argno)
492{
493 if (!lua_istable(L, argno)) {
494 const char *msg = lua_pushfstring(L, "table expected, got %s", luaL_typename(L, argno));
495 WILL_LJMP(luaL_argerror(L, argno, msg));
496 }
497 lua_pushvalue(L, argno);
498 return luaL_ref(L, LUA_REGISTRYINDEX);
499}
500
Christopher Fauletd09cc512021-03-24 14:48:45 +0100501__LJMP const char *hlua_traceback(lua_State *L, const char* sep)
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200502{
503 lua_Debug ar;
504 int level = 0;
Willy Tarreau83061a82018-07-13 11:56:34 +0200505 struct buffer *msg = get_trash_chunk();
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200506
507 while (lua_getstack(L, level++, &ar)) {
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200508 /* Fill fields:
509 * 'S': fills in the fields source, short_src, linedefined, lastlinedefined, and what;
510 * 'l': fills in the field currentline;
511 * 'n': fills in the field name and namewhat;
512 * 't': fills in the field istailcall;
513 */
514 lua_getinfo(L, "Slnt", &ar);
515
Willy Tarreau5c143402022-06-19 17:35:53 +0200516 /* skip these empty entries, usually they come from deep C functions */
517 if (ar.currentline < 0 && *ar.what == 'C' && !*ar.namewhat && !ar.name)
518 continue;
519
520 /* Add separator */
521 if (b_data(msg))
522 chunk_appendf(msg, "%s", sep);
523
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200524 /* Append code localisation */
525 if (ar.currentline > 0)
Christopher Fauletd09cc512021-03-24 14:48:45 +0100526 chunk_appendf(msg, "%s:%d: ", ar.short_src, ar.currentline);
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200527 else
Christopher Fauletd09cc512021-03-24 14:48:45 +0100528 chunk_appendf(msg, "%s: ", ar.short_src);
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200529
530 /*
531 * Get function name
532 *
533 * if namewhat is no empty, name is defined.
534 * what contains "Lua" for Lua function, "C" for C function,
535 * or "main" for main code.
536 */
537 if (*ar.namewhat != '\0' && ar.name != NULL) /* is there a name from code? */
Christopher Fauletd09cc512021-03-24 14:48:45 +0100538 chunk_appendf(msg, "in %s '%s'", ar.namewhat, ar.name); /* use it */
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200539
540 else if (*ar.what == 'm') /* "main", the code is not executed in a function */
Christopher Fauletd09cc512021-03-24 14:48:45 +0100541 chunk_appendf(msg, "in main chunk");
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200542
543 else if (*ar.what != 'C') /* for Lua functions, use <file:line> */
Christopher Fauletd09cc512021-03-24 14:48:45 +0100544 chunk_appendf(msg, "in function line %d", ar.linedefined);
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200545
546 else /* nothing left... */
547 chunk_appendf(msg, "?");
548
549
550 /* Display tailed call */
551 if (ar.istailcall)
552 chunk_appendf(msg, " ...");
553 }
554
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200555 return msg->area;
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200556}
557
558
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100559/* This function check the number of arguments available in the
560 * stack. If the number of arguments available is not the same
Ilya Shipitsinc02a23f2020-05-06 00:53:22 +0500561 * then <nb> an error is thrown.
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100562 */
563__LJMP static inline void check_args(lua_State *L, int nb, char *fcn)
564{
565 if (lua_gettop(L) == nb)
566 return;
567 WILL_LJMP(luaL_error(L, "'%s' needs %d arguments", fcn, nb));
568}
569
Mark Lakes22154b42018-01-29 14:38:40 -0800570/* This function pushes an error string prefixed by the file name
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100571 * and the line number where the error is encountered.
572 */
573static int hlua_pusherror(lua_State *L, const char *fmt, ...)
574{
575 va_list argp;
576 va_start(argp, fmt);
577 luaL_where(L, 1);
578 lua_pushvfstring(L, fmt, argp);
579 va_end(argp);
580 lua_concat(L, 2);
581 return 1;
582}
583
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100584/* This functions is used with sample fetch and converters. It
585 * converts the HAProxy configuration argument in a lua stack
586 * values.
587 *
588 * It takes an array of "arg", and each entry of the array is
589 * converted and pushed in the LUA stack.
590 */
591static int hlua_arg2lua(lua_State *L, const struct arg *arg)
592{
593 switch (arg->type) {
594 case ARGT_SINT:
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100595 case ARGT_TIME:
596 case ARGT_SIZE:
Thierry FOURNIERf90838b2015-03-06 13:48:32 +0100597 lua_pushinteger(L, arg->data.sint);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100598 break;
599
600 case ARGT_STR:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200601 lua_pushlstring(L, arg->data.str.area, arg->data.str.data);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100602 break;
603
604 case ARGT_IPV4:
605 case ARGT_IPV6:
606 case ARGT_MSK4:
607 case ARGT_MSK6:
608 case ARGT_FE:
609 case ARGT_BE:
610 case ARGT_TAB:
611 case ARGT_SRV:
612 case ARGT_USR:
613 case ARGT_MAP:
614 default:
615 lua_pushnil(L);
616 break;
617 }
618 return 1;
619}
620
Ilya Shipitsinc02a23f2020-05-06 00:53:22 +0500621/* This function take one entry in an LUA stack at the index "ud",
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100622 * and try to convert it in an HAProxy argument entry. This is useful
Ilya Shipitsind4259502020-04-08 01:07:56 +0500623 * with sample fetch wrappers. The input arguments are given to the
624 * lua wrapper and converted as arg list by the function.
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100625 */
626static int hlua_lua2arg(lua_State *L, int ud, struct arg *arg)
627{
628 switch (lua_type(L, ud)) {
629
630 case LUA_TNUMBER:
631 case LUA_TBOOLEAN:
632 arg->type = ARGT_SINT;
633 arg->data.sint = lua_tointeger(L, ud);
634 break;
635
636 case LUA_TSTRING:
637 arg->type = ARGT_STR;
Tim Duesterhus2e89dec2019-09-29 23:03:08 +0200638 arg->data.str.area = (char *)lua_tolstring(L, ud, &arg->data.str.data);
Tim Duesterhus29d2e8a2019-09-29 23:03:07 +0200639 /* We don't know the actual size of the underlying allocation, so be conservative. */
Christopher Fauletfdea1b62020-08-06 08:29:18 +0200640 arg->data.str.size = arg->data.str.data+1; /* count the terminating null byte */
Tim Duesterhus29d2e8a2019-09-29 23:03:07 +0200641 arg->data.str.head = 0;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100642 break;
643
644 case LUA_TUSERDATA:
645 case LUA_TNIL:
646 case LUA_TTABLE:
647 case LUA_TFUNCTION:
648 case LUA_TTHREAD:
649 case LUA_TLIGHTUSERDATA:
650 arg->type = ARGT_SINT;
Thierry FOURNIERbf65cd42015-07-20 17:45:02 +0200651 arg->data.sint = 0;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100652 break;
653 }
654 return 1;
655}
656
657/* the following functions are used to convert a struct sample
658 * in Lua type. This useful to convert the return of the
Ilya Shipitsind4259502020-04-08 01:07:56 +0500659 * fetches or converters.
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100660 */
Willy Tarreau5eadada2015-03-10 17:28:54 +0100661static int hlua_smp2lua(lua_State *L, struct sample *smp)
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100662{
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200663 switch (smp->data.type) {
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100664 case SMP_T_SINT:
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100665 case SMP_T_BOOL:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200666 lua_pushinteger(L, smp->data.u.sint);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100667 break;
668
669 case SMP_T_BIN:
670 case SMP_T_STR:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200671 lua_pushlstring(L, smp->data.u.str.area, smp->data.u.str.data);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100672 break;
673
674 case SMP_T_METH:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200675 switch (smp->data.u.meth.meth) {
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100676 case HTTP_METH_OPTIONS: lua_pushstring(L, "OPTIONS"); break;
677 case HTTP_METH_GET: lua_pushstring(L, "GET"); break;
678 case HTTP_METH_HEAD: lua_pushstring(L, "HEAD"); break;
679 case HTTP_METH_POST: lua_pushstring(L, "POST"); break;
680 case HTTP_METH_PUT: lua_pushstring(L, "PUT"); break;
681 case HTTP_METH_DELETE: lua_pushstring(L, "DELETE"); break;
682 case HTTP_METH_TRACE: lua_pushstring(L, "TRACE"); break;
683 case HTTP_METH_CONNECT: lua_pushstring(L, "CONNECT"); break;
684 case HTTP_METH_OTHER:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200685 lua_pushlstring(L, smp->data.u.meth.str.area, smp->data.u.meth.str.data);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100686 break;
687 default:
688 lua_pushnil(L);
689 break;
690 }
691 break;
692
693 case SMP_T_IPV4:
694 case SMP_T_IPV6:
695 case SMP_T_ADDR: /* This type is never used to qualify a sample. */
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200696 if (sample_casts[smp->data.type][SMP_T_STR] &&
697 sample_casts[smp->data.type][SMP_T_STR](smp))
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200698 lua_pushlstring(L, smp->data.u.str.area, smp->data.u.str.data);
Willy Tarreau5eadada2015-03-10 17:28:54 +0100699 else
700 lua_pushnil(L);
701 break;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100702 default:
703 lua_pushnil(L);
704 break;
705 }
706 return 1;
707}
708
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100709/* the following functions are used to convert a struct sample
710 * in Lua strings. This is useful to convert the return of the
Ilya Shipitsind4259502020-04-08 01:07:56 +0500711 * fetches or converters.
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100712 */
713static int hlua_smp2lua_str(lua_State *L, struct sample *smp)
714{
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200715 switch (smp->data.type) {
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100716
717 case SMP_T_BIN:
718 case SMP_T_STR:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200719 lua_pushlstring(L, smp->data.u.str.area, smp->data.u.str.data);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100720 break;
721
722 case SMP_T_METH:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200723 switch (smp->data.u.meth.meth) {
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100724 case HTTP_METH_OPTIONS: lua_pushstring(L, "OPTIONS"); break;
725 case HTTP_METH_GET: lua_pushstring(L, "GET"); break;
726 case HTTP_METH_HEAD: lua_pushstring(L, "HEAD"); break;
727 case HTTP_METH_POST: lua_pushstring(L, "POST"); break;
728 case HTTP_METH_PUT: lua_pushstring(L, "PUT"); break;
729 case HTTP_METH_DELETE: lua_pushstring(L, "DELETE"); break;
730 case HTTP_METH_TRACE: lua_pushstring(L, "TRACE"); break;
731 case HTTP_METH_CONNECT: lua_pushstring(L, "CONNECT"); break;
732 case HTTP_METH_OTHER:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200733 lua_pushlstring(L, smp->data.u.meth.str.area, smp->data.u.meth.str.data);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100734 break;
735 default:
736 lua_pushstring(L, "");
737 break;
738 }
739 break;
740
741 case SMP_T_SINT:
742 case SMP_T_BOOL:
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100743 case SMP_T_IPV4:
744 case SMP_T_IPV6:
745 case SMP_T_ADDR: /* This type is never used to qualify a sample. */
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200746 if (sample_casts[smp->data.type][SMP_T_STR] &&
747 sample_casts[smp->data.type][SMP_T_STR](smp))
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200748 lua_pushlstring(L, smp->data.u.str.area, smp->data.u.str.data);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100749 else
750 lua_pushstring(L, "");
751 break;
752 default:
753 lua_pushstring(L, "");
754 break;
755 }
756 return 1;
757}
758
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100759/* the following functions are used to convert an Lua type in a
760 * struct sample. This is useful to provide data from a converter
761 * to the LUA code.
762 */
763static int hlua_lua2smp(lua_State *L, int ud, struct sample *smp)
764{
765 switch (lua_type(L, ud)) {
766
767 case LUA_TNUMBER:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200768 smp->data.type = SMP_T_SINT;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200769 smp->data.u.sint = lua_tointeger(L, ud);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100770 break;
771
772
773 case LUA_TBOOLEAN:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200774 smp->data.type = SMP_T_BOOL;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200775 smp->data.u.sint = lua_toboolean(L, ud);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100776 break;
777
778 case LUA_TSTRING:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200779 smp->data.type = SMP_T_STR;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100780 smp->flags |= SMP_F_CONST;
Tim Duesterhus2e89dec2019-09-29 23:03:08 +0200781 smp->data.u.str.area = (char *)lua_tolstring(L, ud, &smp->data.u.str.data);
Tim Duesterhus29d2e8a2019-09-29 23:03:07 +0200782 /* We don't know the actual size of the underlying allocation, so be conservative. */
Christopher Fauletfdea1b62020-08-06 08:29:18 +0200783 smp->data.u.str.size = smp->data.u.str.data+1; /* count the terminating null byte */
Tim Duesterhus29d2e8a2019-09-29 23:03:07 +0200784 smp->data.u.str.head = 0;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100785 break;
786
787 case LUA_TUSERDATA:
788 case LUA_TNIL:
789 case LUA_TTABLE:
790 case LUA_TFUNCTION:
791 case LUA_TTHREAD:
792 case LUA_TLIGHTUSERDATA:
Thierry FOURNIER93405e12015-08-26 14:19:03 +0200793 case LUA_TNONE:
794 default:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200795 smp->data.type = SMP_T_BOOL;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200796 smp->data.u.sint = 0;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100797 break;
798 }
799 return 1;
800}
801
Ilya Shipitsind4259502020-04-08 01:07:56 +0500802/* This function check the "argp" built by another conversion function
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -0800803 * is in accord with the expected argp defined by the "mask". The function
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100804 * returns true or false. It can be adjust the types if there compatibles.
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100805 *
Ilya Shipitsinc02a23f2020-05-06 00:53:22 +0500806 * This function assumes that the argp argument contains ARGM_NBARGS + 1
Willy Tarreauee0d7272021-07-16 10:26:56 +0200807 * entries and that there is at least one stop at the last position.
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100808 */
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100809__LJMP int hlua_lua2arg_check(lua_State *L, int first, struct arg *argp,
David Carlier0c437f42016-04-27 16:21:56 +0100810 uint64_t mask, struct proxy *p)
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100811{
812 int min_arg;
Willy Tarreauee0d7272021-07-16 10:26:56 +0200813 int idx;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100814 struct proxy *px;
Christopher Fauletd25d9262020-08-06 11:04:46 +0200815 struct userlist *ul;
Christopher Fauletfd2e9062020-08-06 11:10:57 +0200816 struct my_regex *reg;
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200817 const char *msg = NULL;
Christopher Fauletfd2e9062020-08-06 11:10:57 +0200818 char *sname, *pname, *err = NULL;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100819
820 idx = 0;
821 min_arg = ARGM(mask);
822 mask >>= ARGM_BITS;
823
824 while (1) {
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200825 struct buffer tmp = BUF_NULL;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100826
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100827 /* Check for mandatory arguments. */
828 if (argp[idx].type == ARGT_STOP) {
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100829 if (idx < min_arg) {
830
831 /* If miss other argument than the first one, we return an error. */
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200832 if (idx > 0) {
833 msg = "Mandatory argument expected";
834 goto error;
835 }
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100836
837 /* If first argument have a certain type, some default values
838 * may be used. See the function smp_resolve_args().
839 */
840 switch (mask & ARGT_MASK) {
841
842 case ARGT_FE:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200843 if (!(p->cap & PR_CAP_FE)) {
844 msg = "Mandatory argument expected";
845 goto error;
846 }
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100847 argp[idx].data.prx = p;
848 argp[idx].type = ARGT_FE;
849 argp[idx+1].type = ARGT_STOP;
850 break;
851
852 case ARGT_BE:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200853 if (!(p->cap & PR_CAP_BE)) {
854 msg = "Mandatory argument expected";
855 goto error;
856 }
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100857 argp[idx].data.prx = p;
858 argp[idx].type = ARGT_BE;
859 argp[idx+1].type = ARGT_STOP;
860 break;
861
862 case ARGT_TAB:
Olivier Houchard14f62682022-09-13 00:35:53 +0200863 if (!p->table) {
864 msg = "Mandatory argument expected";
865 goto error;
866 }
867 argp[idx].data.t = p->table;
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100868 argp[idx].type = ARGT_TAB;
869 argp[idx+1].type = ARGT_STOP;
870 break;
871
872 default:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200873 msg = "Mandatory argument expected";
874 goto error;
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100875 break;
876 }
877 }
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200878 break;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100879 }
880
Ilya Shipitsin856aabc2020-04-16 23:51:34 +0500881 /* Check for exceed the number of required argument. */
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100882 if ((mask & ARGT_MASK) == ARGT_STOP &&
883 argp[idx].type != ARGT_STOP) {
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200884 msg = "Last argument expected";
885 goto error;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100886 }
887
888 if ((mask & ARGT_MASK) == ARGT_STOP &&
889 argp[idx].type == ARGT_STOP) {
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200890 break;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100891 }
892
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200893 /* Convert some argument types. All string in argp[] are for not
894 * duplicated yet.
895 */
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100896 switch (mask & ARGT_MASK) {
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100897 case ARGT_SINT:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200898 if (argp[idx].type != ARGT_SINT) {
899 msg = "integer expected";
900 goto error;
901 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100902 argp[idx].type = ARGT_SINT;
903 break;
904
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100905 case ARGT_TIME:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200906 if (argp[idx].type != ARGT_SINT) {
907 msg = "integer expected";
908 goto error;
909 }
Thierry FOURNIER29176f32015-07-07 00:41:29 +0200910 argp[idx].type = ARGT_TIME;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100911 break;
912
913 case ARGT_SIZE:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200914 if (argp[idx].type != ARGT_SINT) {
915 msg = "integer expected";
916 goto error;
917 }
Thierry FOURNIER29176f32015-07-07 00:41:29 +0200918 argp[idx].type = ARGT_SIZE;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100919 break;
920
921 case ARGT_FE:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200922 if (argp[idx].type != ARGT_STR) {
923 msg = "string expected";
924 goto error;
925 }
Christopher Fauletfdea1b62020-08-06 08:29:18 +0200926 argp[idx].data.prx = proxy_fe_by_name(argp[idx].data.str.area);
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200927 if (!argp[idx].data.prx) {
928 msg = "frontend doesn't exist";
929 goto error;
930 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100931 argp[idx].type = ARGT_FE;
932 break;
933
934 case ARGT_BE:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200935 if (argp[idx].type != ARGT_STR) {
936 msg = "string expected";
937 goto error;
938 }
Christopher Fauletfdea1b62020-08-06 08:29:18 +0200939 argp[idx].data.prx = proxy_be_by_name(argp[idx].data.str.area);
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200940 if (!argp[idx].data.prx) {
941 msg = "backend doesn't exist";
942 goto error;
943 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100944 argp[idx].type = ARGT_BE;
945 break;
946
947 case ARGT_TAB:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200948 if (argp[idx].type != ARGT_STR) {
949 msg = "string expected";
950 goto error;
951 }
Christopher Fauletfdea1b62020-08-06 08:29:18 +0200952 argp[idx].data.t = stktable_find_by_name(argp[idx].data.str.area);
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200953 if (!argp[idx].data.t) {
954 msg = "table doesn't exist";
955 goto error;
956 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100957 argp[idx].type = ARGT_TAB;
958 break;
959
960 case ARGT_SRV:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200961 if (argp[idx].type != ARGT_STR) {
962 msg = "string expected";
963 goto error;
964 }
Christopher Fauletfdea1b62020-08-06 08:29:18 +0200965 sname = strrchr(argp[idx].data.str.area, '/');
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100966 if (sname) {
967 *sname++ = '\0';
Christopher Fauletfdea1b62020-08-06 08:29:18 +0200968 pname = argp[idx].data.str.area;
Willy Tarreau9e0bb102015-05-26 11:24:42 +0200969 px = proxy_be_by_name(pname);
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200970 if (!px) {
971 msg = "backend doesn't exist";
972 goto error;
973 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100974 }
975 else {
Christopher Fauletfdea1b62020-08-06 08:29:18 +0200976 sname = argp[idx].data.str.area;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100977 px = p;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100978 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100979 argp[idx].data.srv = findserver(px, sname);
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200980 if (!argp[idx].data.srv) {
981 msg = "server doesn't exist";
982 goto error;
983 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100984 argp[idx].type = ARGT_SRV;
985 break;
986
987 case ARGT_IPV4:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200988 if (argp[idx].type != ARGT_STR) {
989 msg = "string expected";
990 goto error;
991 }
992 if (inet_pton(AF_INET, argp[idx].data.str.area, &argp[idx].data.ipv4)) {
993 msg = "invalid IPv4 address";
994 goto error;
995 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100996 argp[idx].type = ARGT_IPV4;
997 break;
998
999 case ARGT_MSK4:
Christopher Faulete663a6e2020-08-07 09:11:22 +02001000 if (argp[idx].type == ARGT_SINT)
1001 len2mask4(argp[idx].data.sint, &argp[idx].data.ipv4);
1002 else if (argp[idx].type == ARGT_STR) {
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001003 if (!str2mask(argp[idx].data.str.area, &argp[idx].data.ipv4)) {
1004 msg = "invalid IPv4 mask";
1005 goto error;
1006 }
1007 }
1008 else {
1009 msg = "integer or string expected";
1010 goto error;
Christopher Faulete663a6e2020-08-07 09:11:22 +02001011 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001012 argp[idx].type = ARGT_MSK4;
1013 break;
1014
1015 case ARGT_IPV6:
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001016 if (argp[idx].type != ARGT_STR) {
1017 msg = "string expected";
1018 goto error;
1019 }
1020 if (inet_pton(AF_INET6, argp[idx].data.str.area, &argp[idx].data.ipv6)) {
1021 msg = "invalid IPv6 address";
1022 goto error;
1023 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001024 argp[idx].type = ARGT_IPV6;
1025 break;
1026
1027 case ARGT_MSK6:
Christopher Faulete663a6e2020-08-07 09:11:22 +02001028 if (argp[idx].type == ARGT_SINT)
1029 len2mask6(argp[idx].data.sint, &argp[idx].data.ipv6);
1030 else if (argp[idx].type == ARGT_STR) {
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001031 if (!str2mask6(argp[idx].data.str.area, &argp[idx].data.ipv6)) {
1032 msg = "invalid IPv6 mask";
1033 goto error;
1034 }
1035 }
1036 else {
1037 msg = "integer or string expected";
1038 goto error;
Christopher Faulete663a6e2020-08-07 09:11:22 +02001039 }
Tim Duesterhusb814da62018-01-25 16:24:50 +01001040 argp[idx].type = ARGT_MSK6;
1041 break;
1042
Christopher Fauletfd2e9062020-08-06 11:10:57 +02001043 case ARGT_REG:
1044 if (argp[idx].type != ARGT_STR) {
1045 msg = "string expected";
1046 goto error;
1047 }
1048 reg = regex_comp(argp[idx].data.str.area, !(argp[idx].type_flags & ARGF_REG_ICASE), 1, &err);
1049 if (!reg) {
1050 msg = lua_pushfstring(L, "error compiling regex '%s' : '%s'",
1051 argp[idx].data.str.area, err);
1052 free(err);
1053 goto error;
1054 }
1055 argp[idx].type = ARGT_REG;
1056 argp[idx].data.reg = reg;
1057 break;
1058
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001059 case ARGT_USR:
Christopher Fauletd25d9262020-08-06 11:04:46 +02001060 if (argp[idx].type != ARGT_STR) {
1061 msg = "string expected";
1062 goto error;
1063 }
1064 if (p->uri_auth && p->uri_auth->userlist &&
Tim Duesterhuse5ff1412021-01-02 22:31:53 +01001065 strcmp(p->uri_auth->userlist->name, argp[idx].data.str.area) == 0)
Christopher Fauletd25d9262020-08-06 11:04:46 +02001066 ul = p->uri_auth->userlist;
1067 else
1068 ul = auth_find_userlist(argp[idx].data.str.area);
1069
1070 if (!ul) {
1071 msg = lua_pushfstring(L, "unable to find userlist '%s'", argp[idx].data.str.area);
1072 goto error;
1073 }
1074 argp[idx].type = ARGT_USR;
1075 argp[idx].data.usr = ul;
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001076 break;
1077
1078 case ARGT_STR:
1079 if (!chunk_dup(&tmp, &argp[idx].data.str)) {
1080 msg = "unable to duplicate string arg";
1081 goto error;
1082 }
1083 argp[idx].data.str = tmp;
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001084 break;
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001085
Christopher Fauletd25d9262020-08-06 11:04:46 +02001086 case ARGT_MAP:
Christopher Fauletd25d9262020-08-06 11:04:46 +02001087 msg = "type not yet supported";
1088 goto error;
1089 break;
1090
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001091 }
1092
1093 /* Check for type of argument. */
1094 if ((mask & ARGT_MASK) != argp[idx].type) {
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001095 msg = lua_pushfstring(L, "'%s' expected, got '%s'",
1096 arg_type_names[(mask & ARGT_MASK)],
1097 arg_type_names[argp[idx].type & ARGT_MASK]);
1098 goto error;
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001099 }
1100
1101 /* Next argument. */
1102 mask >>= ARGT_BITS;
1103 idx++;
1104 }
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001105 return 0;
1106
1107 error:
Olivier Houchardca431612022-09-13 00:31:17 +02001108 argp[idx].type = ARGT_STOP;
Willy Tarreauee0d7272021-07-16 10:26:56 +02001109 free_args(argp);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001110 WILL_LJMP(luaL_argerror(L, first + idx, msg));
1111 return 0; /* Never reached */
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001112}
1113
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001114/*
Ilya Shipitsinc02a23f2020-05-06 00:53:22 +05001115 * The following functions are used to make correspondence between the the
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001116 * executed lua pointer and the "struct hlua *" that contain the context.
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001117 *
1118 * - hlua_gethlua : return the hlua context associated with an lua_State.
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001119 * - hlua_sethlua : create the association between hlua context and lua_state.
1120 */
1121static inline struct hlua *hlua_gethlua(lua_State *L)
1122{
Thierry FOURNIER38c5fd62015-03-10 02:40:29 +01001123 struct hlua **hlua = lua_getextraspace(L);
1124 return *hlua;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001125}
1126static inline void hlua_sethlua(struct hlua *hlua)
1127{
Thierry FOURNIER38c5fd62015-03-10 02:40:29 +01001128 struct hlua **hlua_store = lua_getextraspace(hlua->T);
1129 *hlua_store = hlua;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001130}
1131
Willy Tarreau0b7b6392022-06-19 17:39:33 +02001132/* Will return a non-NULL string indicating the Lua call trace if the caller
1133 * currently is executing from within a Lua function. One line per entry will
1134 * be emitted, and each extra line will be prefixed with <pfx>. If a current
1135 * Lua function is not detected, NULL is returned.
1136 */
1137const char *hlua_show_current_location(const char *pfx)
1138{
1139 lua_State *L;
1140 lua_Debug ar;
1141
1142 /* global or per-thread stack initializing ? */
1143 if (hlua_state_id != -1 && (L = hlua_states[hlua_state_id]) && lua_getstack(L, 0, &ar))
1144 return hlua_traceback(L, pfx);
1145
1146 /* per-thread stack running ? */
1147 if (hlua_states[tid + 1] && (L = hlua_states[tid + 1]) && lua_getstack(L, 0, &ar))
1148 return hlua_traceback(L, pfx);
1149
1150 /* global stack running ? */
1151 if (hlua_states[0] && (L = hlua_states[0]) && lua_getstack(L, 0, &ar))
1152 return hlua_traceback(L, pfx);
1153
1154 return NULL;
1155}
1156
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01001157/* This function is used to send logs. It try to send on screen (stderr)
1158 * and on the default syslog server.
1159 */
1160static inline void hlua_sendlog(struct proxy *px, int level, const char *msg)
1161{
1162 struct tm tm;
1163 char *p;
1164
1165 /* Cleanup the log message. */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001166 p = trash.area;
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01001167 for (; *msg != '\0'; msg++, p++) {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001168 if (p >= trash.area + trash.size - 1) {
Thierry FOURNIERccf00632015-09-16 12:47:03 +02001169 /* Break the message if exceed the buffer size. */
1170 *(p-4) = ' ';
1171 *(p-3) = '.';
1172 *(p-2) = '.';
1173 *(p-1) = '.';
1174 break;
1175 }
Willy Tarreau90807112020-02-25 08:16:33 +01001176 if (isprint((unsigned char)*msg))
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01001177 *p = *msg;
1178 else
1179 *p = '.';
1180 }
1181 *p = '\0';
1182
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001183 send_log(px, level, "%s\n", trash.area);
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01001184 if (!(global.mode & MODE_QUIET) || (global.mode & (MODE_VERBOSE | MODE_STARTING))) {
Christopher Fauletf98d8212020-10-02 18:13:52 +02001185 if (level == LOG_DEBUG && !(global.mode & MODE_DEBUG))
1186 return;
1187
Willy Tarreaua678b432015-08-28 10:14:59 +02001188 get_localtime(date.tv_sec, &tm);
1189 fprintf(stderr, "[%s] %03d/%02d%02d%02d (%d) : %s\n",
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01001190 log_levels[level], tm.tm_yday, tm.tm_hour, tm.tm_min, tm.tm_sec,
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001191 (int)getpid(), trash.area);
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01001192 fflush(stderr);
1193 }
1194}
1195
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001196/* This function just ensure that the yield will be always
1197 * returned with a timeout and permit to set some flags
1198 */
1199__LJMP void hlua_yieldk(lua_State *L, int nresults, int ctx,
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001200 lua_KFunction k, int timeout, unsigned int flags)
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001201{
Thierry Fournier4234dbd2020-11-28 13:18:23 +01001202 struct hlua *hlua;
1203
1204 /* Get hlua struct, or NULL if we execute from main lua state */
1205 hlua = hlua_gethlua(L);
1206 if (!hlua) {
1207 return;
1208 }
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001209
1210 /* Set the wake timeout. If timeout is required, we set
1211 * the expiration time.
1212 */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001213 hlua->wake_time = timeout;
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001214
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01001215 hlua->flags |= flags;
1216
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001217 /* Process the yield. */
Willy Tarreau9635e032018-10-16 17:52:55 +02001218 MAY_LJMP(lua_yieldk(L, nresults, ctx, k));
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001219}
1220
Willy Tarreau87b09662015-04-03 00:22:06 +02001221/* This function initialises the Lua environment stored in the stream.
1222 * It must be called at the start of the stream. This function creates
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001223 * an LUA coroutine. It can not be use to crete the main LUA context.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02001224 *
1225 * This function is particular. it initialises a new Lua thread. If the
1226 * initialisation fails (example: out of memory error), the lua function
1227 * throws an error (longjmp).
1228 *
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +01001229 * In some case (at least one), this function can be called from safe
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001230 * environment, so we must not initialise it. While the support of
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +01001231 * threads appear, the safe environment set a lock to ensure only one
1232 * Lua execution at a time. If we initialize safe environment in another
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001233 * safe environment, we have a dead lock.
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +01001234 *
1235 * set "already_safe" true if the context is initialized form safe
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001236 * Lua function.
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +01001237 *
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001238 * This function manipulates two Lua stacks: the main and the thread. Only
Thierry FOURNIERbabae282015-09-17 11:36:37 +02001239 * the main stack can fail. The thread is not manipulated. This function
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001240 * MUST NOT manipulate the created thread stack state, because it is not
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001241 * protected against errors thrown by the thread stack.
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001242 */
Thierry Fournier021d9862020-11-28 23:42:03 +01001243int hlua_ctx_init(struct hlua *lua, int state_id, struct task *task, int already_safe)
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001244{
1245 lua->Mref = LUA_REFNIL;
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001246 lua->flags = 0;
Willy Tarreauf31af932020-01-14 09:59:38 +01001247 lua->gc_count = 0;
Christopher Fauletbc275a92020-02-26 14:55:16 +01001248 lua->wake_time = TICK_ETERNITY;
Thierry Fournier021d9862020-11-28 23:42:03 +01001249 lua->state_id = state_id;
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01001250 LIST_INIT(&lua->com);
Aurelien DARRAGON3ffbf382023-02-09 17:02:57 +01001251 MT_LIST_INIT(&lua->hc_list);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001252 if (!already_safe) {
1253 if (!SET_SAFE_LJMP_PARENT(lua)) {
1254 lua->Tref = LUA_REFNIL;
1255 return 0;
1256 }
1257 }
Thierry Fournier021d9862020-11-28 23:42:03 +01001258 lua->T = lua_newthread(hlua_states[state_id]);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001259 if (!lua->T) {
1260 lua->Tref = LUA_REFNIL;
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +01001261 if (!already_safe)
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001262 RESET_SAFE_LJMP_PARENT(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001263 return 0;
1264 }
1265 hlua_sethlua(lua);
Thierry Fournier021d9862020-11-28 23:42:03 +01001266 lua->Tref = luaL_ref(hlua_states[state_id], LUA_REGISTRYINDEX);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001267 lua->task = task;
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +01001268 if (!already_safe)
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001269 RESET_SAFE_LJMP_PARENT(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001270 return 1;
1271}
1272
Aurelien DARRAGON3ffbf382023-02-09 17:02:57 +01001273/* kill all associated httpclient to this hlua task
1274 * We must take extra precautions as we're manipulating lua-exposed
1275 * objects without the main lua lock.
1276 */
William Lallemandbb581422022-10-20 10:57:28 +02001277static void hlua_httpclient_destroy_all(struct hlua *hlua)
1278{
Aurelien DARRAGON3ffbf382023-02-09 17:02:57 +01001279 struct hlua_httpclient *hlua_hc;
William Lallemandbb581422022-10-20 10:57:28 +02001280
Aurelien DARRAGON3ffbf382023-02-09 17:02:57 +01001281 /* use thread-safe accessors for hc_list since GC cycle initiated by
1282 * another thread sharing the same main lua stack (lua coroutine)
1283 * could execute hlua_httpclient_gc() on the hlua->hc_list items
1284 * in parallel: Lua GC applies on the main stack, it is not limited to
1285 * a single coroutine stack, see Github issue #2037 for reference.
1286 * Remember, coroutines created using lua_newthread() are not meant to
1287 * be thread safe in Lua. (From lua co-author:
1288 * http://lua-users.org/lists/lua-l/2011-07/msg00072.html)
1289 *
1290 * This security measure is superfluous when 'lua-load-per-thread' is used
1291 * since in this case coroutines exclusively run on the same thread
1292 * (main stack is not shared between OS threads).
1293 */
1294 while ((hlua_hc = MT_LIST_POP(&hlua->hc_list, typeof(hlua_hc), by_hlua))) {
1295 httpclient_stop_and_destroy(hlua_hc->hc);
William Lallemandbb581422022-10-20 10:57:28 +02001296 hlua_hc->hc = NULL;
William Lallemandbb581422022-10-20 10:57:28 +02001297 }
1298}
1299
1300
Willy Tarreau87b09662015-04-03 00:22:06 +02001301/* Used to destroy the Lua coroutine when the attached stream or task
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001302 * is destroyed. The destroy also the memory context. The struct "lua"
1303 * is not freed.
1304 */
1305void hlua_ctx_destroy(struct hlua *lua)
1306{
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01001307 if (!lua)
Thierry FOURNIERa718b292015-03-04 16:48:34 +01001308 return;
1309
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01001310 if (!lua->T)
1311 goto end;
1312
William Lallemandbb581422022-10-20 10:57:28 +02001313 /* clean all running httpclient */
1314 hlua_httpclient_destroy_all(lua);
1315
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01001316 /* Purge all the pending signals. */
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001317 notification_purge(&lua->com);
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01001318
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001319 if (!SET_SAFE_LJMP(lua))
Thierry FOURNIER75d02082017-07-12 13:41:33 +02001320 return;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001321 luaL_unref(lua->T, LUA_REGISTRYINDEX, lua->Mref);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001322 RESET_SAFE_LJMP(lua);
Thierry FOURNIER5a50a852015-09-23 16:59:28 +02001323
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001324 if (!SET_SAFE_LJMP_PARENT(lua))
Thierry FOURNIER75d02082017-07-12 13:41:33 +02001325 return;
Thierry Fournier021d9862020-11-28 23:42:03 +01001326 luaL_unref(hlua_states[lua->state_id], LUA_REGISTRYINDEX, lua->Tref);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001327 RESET_SAFE_LJMP_PARENT(lua);
Thierry FOURNIER5a50a852015-09-23 16:59:28 +02001328 /* Forces a garbage collecting process. If the Lua program is finished
1329 * without error, we run the GC on the thread pointer. Its freed all
1330 * the unused memory.
1331 * If the thread is finnish with an error or is currently yielded,
1332 * it seems that the GC applied on the thread doesn't clean anything,
1333 * so e run the GC on the main thread.
1334 * NOTE: maybe this action locks all the Lua threads untiml the en of
1335 * the garbage collection.
1336 */
Willy Tarreauf31af932020-01-14 09:59:38 +01001337 if (lua->gc_count) {
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001338 if (!SET_SAFE_LJMP_PARENT(lua))
Thierry FOURNIER75d02082017-07-12 13:41:33 +02001339 return;
Thierry Fournier021d9862020-11-28 23:42:03 +01001340 lua_gc(hlua_states[lua->state_id], LUA_GCCOLLECT, 0);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001341 RESET_SAFE_LJMP_PARENT(lua);
Thierry FOURNIER7c39ab42015-09-27 22:53:33 +02001342 }
Thierry FOURNIER5a50a852015-09-23 16:59:28 +02001343
Thierry FOURNIERa7b536b2015-09-21 22:50:24 +02001344 lua->T = NULL;
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01001345
1346end:
Willy Tarreaubafbe012017-11-24 17:34:44 +01001347 pool_free(pool_head_hlua, lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001348}
1349
1350/* This function is used to restore the Lua context when a coroutine
1351 * fails. This function copy the common memory between old coroutine
1352 * and the new coroutine. The old coroutine is destroyed, and its
1353 * replaced by the new coroutine.
1354 * If the flag "keep_msg" is set, the last entry of the old is assumed
1355 * as string error message and it is copied in the new stack.
1356 */
1357static int hlua_ctx_renew(struct hlua *lua, int keep_msg)
1358{
1359 lua_State *T;
1360 int new_ref;
1361
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001362 /* New Lua coroutine. */
Thierry Fournier021d9862020-11-28 23:42:03 +01001363 T = lua_newthread(hlua_states[lua->state_id]);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001364 if (!T)
1365 return 0;
1366
1367 /* Copy last error message. */
1368 if (keep_msg)
1369 lua_xmove(lua->T, T, 1);
1370
1371 /* Copy data between the coroutines. */
1372 lua_rawgeti(lua->T, LUA_REGISTRYINDEX, lua->Mref);
1373 lua_xmove(lua->T, T, 1);
Ilya Shipitsin46a030c2020-07-05 16:36:08 +05001374 new_ref = luaL_ref(T, LUA_REGISTRYINDEX); /* Value popped. */
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001375
1376 /* Destroy old data. */
1377 luaL_unref(lua->T, LUA_REGISTRYINDEX, lua->Mref);
1378
1379 /* The thread is garbage collected by Lua. */
Thierry Fournier021d9862020-11-28 23:42:03 +01001380 luaL_unref(hlua_states[lua->state_id], LUA_REGISTRYINDEX, lua->Tref);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001381
1382 /* Fill the struct with the new coroutine values. */
1383 lua->Mref = new_ref;
1384 lua->T = T;
Thierry Fournier021d9862020-11-28 23:42:03 +01001385 lua->Tref = luaL_ref(hlua_states[lua->state_id], LUA_REGISTRYINDEX);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001386
1387 /* Set context. */
1388 hlua_sethlua(lua);
1389
1390 return 1;
1391}
1392
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001393void hlua_hook(lua_State *L, lua_Debug *ar)
1394{
Thierry Fournier4234dbd2020-11-28 13:18:23 +01001395 struct hlua *hlua;
1396
1397 /* Get hlua struct, or NULL if we execute from main lua state */
1398 hlua = hlua_gethlua(L);
1399 if (!hlua)
1400 return;
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001401
1402 /* Lua cannot yield when its returning from a function,
1403 * so, we can fix the interrupt hook to 1 instruction,
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001404 * expecting that the function is finished.
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001405 */
1406 if (lua_gethookmask(L) & LUA_MASKRET) {
1407 lua_sethook(hlua->T, hlua_hook, LUA_MASKCOUNT, 1);
1408 return;
1409 }
1410
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001411 /* If we interrupt the Lua processing in yieldable state, we yield.
1412 * If the state is not yieldable, trying yield causes an error.
1413 */
Aurelien DARRAGON0ebd41f2022-11-24 09:51:40 +01001414 if (lua_isyieldable(L)) {
1415 /* note: for converters/fetches.. where yielding is not allowed
1416 * hlua_ctx_resume() will simply perform a goto resume_execution
1417 * instead of rescheduling hlua->task.
1418 * also: hlua_ctx_resume() will take care of checking execution
1419 * timeout and re-applying the hook as needed.
1420 */
Willy Tarreau9635e032018-10-16 17:52:55 +02001421 MAY_LJMP(hlua_yieldk(L, 0, 0, NULL, TICK_ETERNITY, HLUA_CTRLYIELD));
Aurelien DARRAGON0ebd41f2022-11-24 09:51:40 +01001422 /* lua docs says that the hook should return immediately after lua_yieldk
1423 *
1424 * From: https://www.lua.org/manual/5.3/manual.html#lua_yieldk
1425 *
1426 * Moreover, it seems that we don't want to continue after the yield
1427 * because the end of the function is about handling unyieldable function,
1428 * which is not the case here.
1429 *
1430 * ->if we don't return lua_sethook gets incorrectly set with MASKRET later
1431 * in the function.
1432 */
1433 return;
1434 }
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001435
Thierry FOURNIERa85cfb12015-03-13 14:50:06 +01001436 /* If we cannot yield, update the clock and check the timeout. */
Willy Tarreau55542642021-10-08 09:33:24 +02001437 clock_update_date(0, 1);
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001438 hlua->run_time += now_ms - hlua->start_time;
1439 if (hlua->max_time && hlua->run_time >= hlua->max_time) {
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001440 lua_pushfstring(L, "execution timeout");
1441 WILL_LJMP(lua_error(L));
1442 }
1443
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001444 /* Update the start time. */
1445 hlua->start_time = now_ms;
1446
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001447 /* Try to interrupt the process at the end of the current
1448 * unyieldable function.
1449 */
1450 lua_sethook(hlua->T, hlua_hook, LUA_MASKRET|LUA_MASKCOUNT, hlua_nb_instruction);
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001451}
1452
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001453/* This function start or resumes the Lua stack execution. If the flag
1454 * "yield_allowed" if no set and the LUA stack execution returns a yield
1455 * The function return an error.
1456 *
1457 * The function can returns 4 values:
1458 * - HLUA_E_OK : The execution is terminated without any errors.
1459 * - HLUA_E_AGAIN : The execution must continue at the next associated
1460 * task wakeup.
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001461 * - HLUA_E_ERRMSG : An error has occurred, an error message is set in
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001462 * the top of the stack.
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001463 * - HLUA_E_ERR : An error has occurred without error message.
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001464 *
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001465 * If an error occurred, the stack is renewed and it is ready to run new
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001466 * LUA code.
1467 */
1468static enum hlua_exec hlua_ctx_resume(struct hlua *lua, int yield_allowed)
1469{
Christopher Faulet08ed98f2020-07-28 10:33:25 +02001470#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM >= 504
1471 int nres;
1472#endif
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001473 int ret;
1474 const char *msg;
Thierry FOURNIERfc044c92018-06-07 14:40:48 +02001475 const char *trace;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001476
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001477 /* Initialise run time counter. */
1478 if (!HLUA_IS_RUNNING(lua))
1479 lua->run_time = 0;
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001480
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +02001481 /* Lock the whole Lua execution. This lock must be before the
1482 * label "resume_execution".
1483 */
Thierry Fournier021d9862020-11-28 23:42:03 +01001484 if (lua->state_id == 0)
Willy Tarreau1e7bef12021-08-20 15:47:25 +02001485 lua_take_global_lock();
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +02001486
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001487resume_execution:
1488
1489 /* This hook interrupts the Lua processing each 'hlua_nb_instruction'
1490 * instructions. it is used for preventing infinite loops.
1491 */
1492 lua_sethook(lua->T, hlua_hook, LUA_MASKCOUNT, hlua_nb_instruction);
1493
Thierry FOURNIER1bfc09b2015-03-05 17:10:14 +01001494 /* Remove all flags except the running flags. */
Thierry FOURNIER2f3867f2015-09-28 01:02:01 +02001495 HLUA_SET_RUN(lua);
1496 HLUA_CLR_CTRLYIELD(lua);
1497 HLUA_CLR_WAKERESWR(lua);
1498 HLUA_CLR_WAKEREQWR(lua);
Christopher Faulet1f43a342021-08-04 17:58:21 +02001499 HLUA_CLR_NOYIELD(lua);
1500 if (!yield_allowed)
1501 HLUA_SET_NOYIELD(lua);
Thierry FOURNIER1bfc09b2015-03-05 17:10:14 +01001502
Christopher Fauletbc275a92020-02-26 14:55:16 +01001503 /* Update the start time and reset wake_time. */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001504 lua->start_time = now_ms;
Christopher Fauletbc275a92020-02-26 14:55:16 +01001505 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001506
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001507 /* Call the function. */
Christopher Faulet08ed98f2020-07-28 10:33:25 +02001508#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM >= 504
Thierry Fournier021d9862020-11-28 23:42:03 +01001509 ret = lua_resume(lua->T, hlua_states[lua->state_id], lua->nargs, &nres);
Christopher Faulet08ed98f2020-07-28 10:33:25 +02001510#else
Thierry Fournier021d9862020-11-28 23:42:03 +01001511 ret = lua_resume(lua->T, hlua_states[lua->state_id], lua->nargs);
Christopher Faulet08ed98f2020-07-28 10:33:25 +02001512#endif
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001513 switch (ret) {
1514
1515 case LUA_OK:
1516 ret = HLUA_E_OK;
1517 break;
1518
1519 case LUA_YIELD:
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001520 /* Check if the execution timeout is expired. It it is the case, we
1521 * break the Lua execution.
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001522 */
Willy Tarreau55542642021-10-08 09:33:24 +02001523 clock_update_date(0, 1);
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001524 lua->run_time += now_ms - lua->start_time;
1525 if (lua->max_time && lua->run_time > lua->max_time) {
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001526 lua_settop(lua->T, 0); /* Empty the stack. */
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001527 ret = HLUA_E_ETMOUT;
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001528 break;
1529 }
1530 /* Process the forced yield. if the general yield is not allowed or
1531 * if no task were associated this the current Lua execution
1532 * coroutine, we resume the execution. Else we want to return in the
1533 * scheduler and we want to be waked up again, to continue the
1534 * current Lua execution. So we schedule our own task.
1535 */
1536 if (HLUA_IS_CTRLYIELDING(lua)) {
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001537 if (!yield_allowed || !lua->task)
1538 goto resume_execution;
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001539 task_wakeup(lua->task, TASK_WOKEN_MSG);
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001540 }
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001541 if (!yield_allowed) {
1542 lua_settop(lua->T, 0); /* Empty the stack. */
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001543 ret = HLUA_E_YIELD;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001544 break;
1545 }
1546 ret = HLUA_E_AGAIN;
1547 break;
1548
1549 case LUA_ERRRUN:
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001550
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001551 /* Special exit case. The traditional exit is returned as an error
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001552 * because the errors ares the only one mean to return immediately
1553 * from and lua execution.
1554 */
1555 if (lua->flags & HLUA_EXIT) {
1556 ret = HLUA_E_OK;
Christopher Faulet7716cdf2020-01-29 11:53:30 +01001557 hlua_ctx_renew(lua, 1);
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001558 break;
1559 }
1560
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001561 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001562 if (!lua_checkstack(lua->T, 1)) {
1563 ret = HLUA_E_ERR;
1564 break;
1565 }
1566 msg = lua_tostring(lua->T, -1);
1567 lua_settop(lua->T, 0); /* Empty the stack. */
1568 lua_pop(lua->T, 1);
Christopher Fauletd09cc512021-03-24 14:48:45 +01001569 trace = hlua_traceback(lua->T, ", ");
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001570 if (msg)
Thierry Fournier46278ff2020-11-29 11:48:12 +01001571 lua_pushfstring(lua->T, "[state-id %d] runtime error: %s from %s", lua->state_id, msg, trace);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001572 else
Thierry Fournier46278ff2020-11-29 11:48:12 +01001573 lua_pushfstring(lua->T, "[state-id %d] unknown runtime error from %s", lua->state_id, trace);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001574 ret = HLUA_E_ERRMSG;
1575 break;
1576
1577 case LUA_ERRMEM:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001578 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001579 lua_settop(lua->T, 0); /* Empty the stack. */
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001580 ret = HLUA_E_NOMEM;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001581 break;
1582
1583 case LUA_ERRERR:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001584 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001585 if (!lua_checkstack(lua->T, 1)) {
1586 ret = HLUA_E_ERR;
1587 break;
1588 }
1589 msg = lua_tostring(lua->T, -1);
1590 lua_settop(lua->T, 0); /* Empty the stack. */
1591 lua_pop(lua->T, 1);
1592 if (msg)
Thierry Fournier46278ff2020-11-29 11:48:12 +01001593 lua_pushfstring(lua->T, "[state-id %d] message handler error: %s", lua->state_id, msg);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001594 else
Thierry Fournier46278ff2020-11-29 11:48:12 +01001595 lua_pushfstring(lua->T, "[state-id %d] message handler error", lua->state_id);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001596 ret = HLUA_E_ERRMSG;
1597 break;
1598
1599 default:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001600 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001601 lua_settop(lua->T, 0); /* Empty the stack. */
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001602 ret = HLUA_E_ERR;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001603 break;
1604 }
1605
1606 switch (ret) {
1607 case HLUA_E_AGAIN:
1608 break;
1609
1610 case HLUA_E_ERRMSG:
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001611 notification_purge(&lua->com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001612 hlua_ctx_renew(lua, 1);
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001613 HLUA_CLR_RUN(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001614 break;
1615
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001616 case HLUA_E_ETMOUT:
1617 case HLUA_E_NOMEM:
1618 case HLUA_E_YIELD:
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001619 case HLUA_E_ERR:
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001620 HLUA_CLR_RUN(lua);
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001621 notification_purge(&lua->com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001622 hlua_ctx_renew(lua, 0);
1623 break;
1624
1625 case HLUA_E_OK:
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001626 HLUA_CLR_RUN(lua);
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001627 notification_purge(&lua->com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001628 break;
1629 }
1630
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +02001631 /* This is the main exit point, remove the Lua lock. */
Thierry Fournier021d9862020-11-28 23:42:03 +01001632 if (lua->state_id == 0)
Willy Tarreau1e7bef12021-08-20 15:47:25 +02001633 lua_drop_global_lock();
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +02001634
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001635 return ret;
1636}
1637
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001638/* This function exit the current code. */
1639__LJMP static int hlua_done(lua_State *L)
1640{
Thierry Fournier4234dbd2020-11-28 13:18:23 +01001641 struct hlua *hlua;
1642
1643 /* Get hlua struct, or NULL if we execute from main lua state */
1644 hlua = hlua_gethlua(L);
1645 if (!hlua)
1646 return 0;
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001647
1648 hlua->flags |= HLUA_EXIT;
1649 WILL_LJMP(lua_error(L));
1650
1651 return 0;
1652}
1653
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001654/* This function is an LUA binding. It provides a function
1655 * for deleting ACL from a referenced ACL file.
1656 */
1657__LJMP static int hlua_del_acl(lua_State *L)
1658{
1659 const char *name;
1660 const char *key;
1661 struct pat_ref *ref;
1662
1663 MAY_LJMP(check_args(L, 2, "del_acl"));
1664
1665 name = MAY_LJMP(luaL_checkstring(L, 1));
1666 key = MAY_LJMP(luaL_checkstring(L, 2));
1667
1668 ref = pat_ref_lookup(name);
1669 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001670 WILL_LJMP(luaL_error(L, "'del_acl': unknown acl file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001671
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001672 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001673 pat_ref_delete(ref, key);
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001674 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001675 return 0;
1676}
1677
1678/* This function is an LUA binding. It provides a function
1679 * for deleting map entry from a referenced map file.
1680 */
1681static int hlua_del_map(lua_State *L)
1682{
1683 const char *name;
1684 const char *key;
1685 struct pat_ref *ref;
1686
1687 MAY_LJMP(check_args(L, 2, "del_map"));
1688
1689 name = MAY_LJMP(luaL_checkstring(L, 1));
1690 key = MAY_LJMP(luaL_checkstring(L, 2));
1691
1692 ref = pat_ref_lookup(name);
1693 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001694 WILL_LJMP(luaL_error(L, "'del_map': unknown acl file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001695
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001696 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001697 pat_ref_delete(ref, key);
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001698 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001699 return 0;
1700}
1701
1702/* This function is an LUA binding. It provides a function
1703 * for adding ACL pattern from a referenced ACL file.
1704 */
1705static int hlua_add_acl(lua_State *L)
1706{
1707 const char *name;
1708 const char *key;
1709 struct pat_ref *ref;
1710
1711 MAY_LJMP(check_args(L, 2, "add_acl"));
1712
1713 name = MAY_LJMP(luaL_checkstring(L, 1));
1714 key = MAY_LJMP(luaL_checkstring(L, 2));
1715
1716 ref = pat_ref_lookup(name);
1717 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001718 WILL_LJMP(luaL_error(L, "'add_acl': unknown acl file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001719
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001720 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001721 if (pat_ref_find_elt(ref, key) == NULL)
1722 pat_ref_add(ref, key, NULL, 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
1727/* This function is an LUA binding. It provides a function
1728 * for setting map pattern and sample from a referenced map
1729 * file.
1730 */
1731static int hlua_set_map(lua_State *L)
1732{
1733 const char *name;
1734 const char *key;
1735 const char *value;
1736 struct pat_ref *ref;
1737
1738 MAY_LJMP(check_args(L, 3, "set_map"));
1739
1740 name = MAY_LJMP(luaL_checkstring(L, 1));
1741 key = MAY_LJMP(luaL_checkstring(L, 2));
1742 value = MAY_LJMP(luaL_checkstring(L, 3));
1743
1744 ref = pat_ref_lookup(name);
1745 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001746 WILL_LJMP(luaL_error(L, "'set_map': unknown map file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001747
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001748 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001749 if (pat_ref_find_elt(ref, key) != NULL)
1750 pat_ref_set(ref, key, value, NULL);
1751 else
1752 pat_ref_add(ref, key, value, NULL);
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001753 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001754 return 0;
1755}
1756
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01001757/* A class is a lot of memory that contain data. This data can be a table,
1758 * an integer or user data. This data is associated with a metatable. This
Ilya Shipitsinc02a23f2020-05-06 00:53:22 +05001759 * metatable have an original version registered in the global context with
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01001760 * the name of the object (_G[<name>] = <metable> ).
1761 *
1762 * A metable is a table that modify the standard behavior of a standard
1763 * access to the associated data. The entries of this new metatable are
1764 * defined as is:
1765 *
1766 * http://lua-users.org/wiki/MetatableEvents
1767 *
1768 * __index
1769 *
1770 * we access an absent field in a table, the result is nil. This is
1771 * true, but it is not the whole truth. Actually, such access triggers
1772 * the interpreter to look for an __index metamethod: If there is no
1773 * such method, as usually happens, then the access results in nil;
1774 * otherwise, the metamethod will provide the result.
1775 *
1776 * Control 'prototype' inheritance. When accessing "myTable[key]" and
1777 * the key does not appear in the table, but the metatable has an __index
1778 * property:
1779 *
1780 * - if the value is a function, the function is called, passing in the
1781 * table and the key; the return value of that function is returned as
1782 * the result.
1783 *
1784 * - if the value is another table, the value of the key in that table is
1785 * asked for and returned (and if it doesn't exist in that table, but that
1786 * table's metatable has an __index property, then it continues on up)
1787 *
1788 * - Use "rawget(myTable,key)" to skip this metamethod.
1789 *
1790 * http://www.lua.org/pil/13.4.1.html
1791 *
1792 * __newindex
1793 *
1794 * Like __index, but control property assignment.
1795 *
1796 * __mode - Control weak references. A string value with one or both
1797 * of the characters 'k' and 'v' which specifies that the the
1798 * keys and/or values in the table are weak references.
1799 *
1800 * __call - Treat a table like a function. When a table is followed by
1801 * parenthesis such as "myTable( 'foo' )" and the metatable has
1802 * a __call key pointing to a function, that function is invoked
1803 * (passing any specified arguments) and the return value is
1804 * returned.
1805 *
1806 * __metatable - Hide the metatable. When "getmetatable( myTable )" is
1807 * called, if the metatable for myTable has a __metatable
1808 * key, the value of that key is returned instead of the
1809 * actual metatable.
1810 *
1811 * __tostring - Control string representation. When the builtin
1812 * "tostring( myTable )" function is called, if the metatable
1813 * for myTable has a __tostring property set to a function,
1814 * that function is invoked (passing myTable to it) and the
1815 * return value is used as the string representation.
1816 *
1817 * __len - Control table length. When the table length is requested using
1818 * the length operator ( '#' ), if the metatable for myTable has
1819 * a __len key pointing to a function, that function is invoked
1820 * (passing myTable to it) and the return value used as the value
1821 * of "#myTable".
1822 *
1823 * __gc - Userdata finalizer code. When userdata is set to be garbage
1824 * collected, if the metatable has a __gc field pointing to a
1825 * function, that function is first invoked, passing the userdata
1826 * to it. The __gc metamethod is not called for tables.
1827 * (See http://lua-users.org/lists/lua-l/2006-11/msg00508.html)
1828 *
1829 * Special metamethods for redefining standard operators:
1830 * http://www.lua.org/pil/13.1.html
1831 *
1832 * __add "+"
1833 * __sub "-"
1834 * __mul "*"
1835 * __div "/"
1836 * __unm "!"
1837 * __pow "^"
1838 * __concat ".."
1839 *
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001840 * Special methods for redefining standard relations
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01001841 * http://www.lua.org/pil/13.2.html
1842 *
1843 * __eq "=="
1844 * __lt "<"
1845 * __le "<="
1846 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001847
1848/*
1849 *
1850 *
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001851 * Class Map
1852 *
1853 *
1854 */
1855
1856/* Returns a struct hlua_map if the stack entry "ud" is
1857 * a class session, otherwise it throws an error.
1858 */
1859__LJMP static struct map_descriptor *hlua_checkmap(lua_State *L, int ud)
1860{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02001861 return MAY_LJMP(hlua_checkudata(L, ud, class_map_ref));
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001862}
1863
1864/* This function is the map constructor. It don't need
1865 * the class Map object. It creates and return a new Map
1866 * object. It must be called only during "body" or "init"
1867 * context because it process some filesystem accesses.
1868 */
1869__LJMP static int hlua_map_new(struct lua_State *L)
1870{
1871 const char *fn;
1872 int match = PAT_MATCH_STR;
1873 struct sample_conv conv;
1874 const char *file = "";
1875 int line = 0;
1876 lua_Debug ar;
1877 char *err = NULL;
1878 struct arg args[2];
1879
1880 if (lua_gettop(L) < 1 || lua_gettop(L) > 2)
1881 WILL_LJMP(luaL_error(L, "'new' needs at least 1 argument."));
1882
1883 fn = MAY_LJMP(luaL_checkstring(L, 1));
1884
1885 if (lua_gettop(L) >= 2) {
1886 match = MAY_LJMP(luaL_checkinteger(L, 2));
1887 if (match < 0 || match >= PAT_MATCH_NUM)
1888 WILL_LJMP(luaL_error(L, "'new' needs a valid match method."));
1889 }
1890
1891 /* Get Lua filename and line number. */
1892 if (lua_getstack(L, 1, &ar)) { /* check function at level */
1893 lua_getinfo(L, "Sl", &ar); /* get info about it */
1894 if (ar.currentline > 0) { /* is there info? */
1895 file = ar.short_src;
1896 line = ar.currentline;
1897 }
1898 }
1899
1900 /* fill fake sample_conv struct. */
1901 conv.kw = ""; /* unused. */
1902 conv.process = NULL; /* unused. */
1903 conv.arg_mask = 0; /* unused. */
1904 conv.val_args = NULL; /* unused. */
1905 conv.out_type = SMP_T_STR;
1906 conv.private = (void *)(long)match;
1907 switch (match) {
1908 case PAT_MATCH_STR: conv.in_type = SMP_T_STR; break;
1909 case PAT_MATCH_BEG: conv.in_type = SMP_T_STR; break;
1910 case PAT_MATCH_SUB: conv.in_type = SMP_T_STR; break;
1911 case PAT_MATCH_DIR: conv.in_type = SMP_T_STR; break;
1912 case PAT_MATCH_DOM: conv.in_type = SMP_T_STR; break;
1913 case PAT_MATCH_END: conv.in_type = SMP_T_STR; break;
1914 case PAT_MATCH_REG: conv.in_type = SMP_T_STR; break;
Thierry FOURNIER07ee64e2015-07-06 23:43:03 +02001915 case PAT_MATCH_INT: conv.in_type = SMP_T_SINT; break;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001916 case PAT_MATCH_IP: conv.in_type = SMP_T_ADDR; break;
1917 default:
1918 WILL_LJMP(luaL_error(L, "'new' doesn't support this match mode."));
1919 }
1920
1921 /* fill fake args. */
1922 args[0].type = ARGT_STR;
Christopher Faulet73292e92020-08-06 08:40:09 +02001923 args[0].data.str.area = strdup(fn);
1924 args[0].data.str.data = strlen(fn);
1925 args[0].data.str.size = args[0].data.str.data+1;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001926 args[1].type = ARGT_STOP;
1927
1928 /* load the map. */
1929 if (!sample_load_map(args, &conv, file, line, &err)) {
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +05001930 /* error case: we can't use luaL_error because we must
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001931 * free the err variable.
1932 */
1933 luaL_where(L, 1);
1934 lua_pushfstring(L, "'new': %s.", err);
1935 lua_concat(L, 2);
1936 free(err);
Christopher Faulet6ad7df42020-08-07 11:45:18 +02001937 chunk_destroy(&args[0].data.str);
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001938 WILL_LJMP(lua_error(L));
1939 }
1940
1941 /* create the lua object. */
1942 lua_newtable(L);
1943 lua_pushlightuserdata(L, args[0].data.map);
1944 lua_rawseti(L, -2, 0);
1945
1946 /* Pop a class Map metatable and affect it to the userdata. */
1947 lua_rawgeti(L, LUA_REGISTRYINDEX, class_map_ref);
1948 lua_setmetatable(L, -2);
1949
1950
1951 return 1;
1952}
1953
1954__LJMP static inline int _hlua_map_lookup(struct lua_State *L, int str)
1955{
1956 struct map_descriptor *desc;
1957 struct pattern *pat;
1958 struct sample smp;
1959
1960 MAY_LJMP(check_args(L, 2, "lookup"));
1961 desc = MAY_LJMP(hlua_checkmap(L, 1));
Thierry FOURNIER07ee64e2015-07-06 23:43:03 +02001962 if (desc->pat.expect_type == SMP_T_SINT) {
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02001963 smp.data.type = SMP_T_SINT;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +02001964 smp.data.u.sint = MAY_LJMP(luaL_checkinteger(L, 2));
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001965 }
1966 else {
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02001967 smp.data.type = SMP_T_STR;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001968 smp.flags = SMP_F_CONST;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001969 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 +01001970 smp.data.u.str.size = smp.data.u.str.data + 1;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001971 }
1972
1973 pat = pattern_exec_match(&desc->pat, &smp, 1);
Thierry FOURNIER503bb092015-08-19 08:35:43 +02001974 if (!pat || !pat->data) {
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001975 if (str)
1976 lua_pushstring(L, "");
1977 else
1978 lua_pushnil(L);
1979 return 1;
1980 }
1981
1982 /* The Lua pattern must return a string, so we can't check the returned type */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001983 lua_pushlstring(L, pat->data->u.str.area, pat->data->u.str.data);
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001984 return 1;
1985}
1986
1987__LJMP static int hlua_map_lookup(struct lua_State *L)
1988{
1989 return _hlua_map_lookup(L, 0);
1990}
1991
1992__LJMP static int hlua_map_slookup(struct lua_State *L)
1993{
1994 return _hlua_map_lookup(L, 1);
1995}
1996
1997/*
1998 *
1999 *
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002000 * Class Socket
2001 *
2002 *
2003 */
2004
2005__LJMP static struct hlua_socket *hlua_checksocket(lua_State *L, int ud)
2006{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02002007 return MAY_LJMP(hlua_checkudata(L, ud, class_socket_ref));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002008}
2009
2010/* This function is the handler called for each I/O on the established
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002011 * connection. It is used for notify space available to send or data
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002012 * received.
2013 */
Willy Tarreau00a37f02015-04-13 12:05:19 +02002014static void hlua_socket_handler(struct appctx *appctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002015{
Willy Tarreau5321da92022-05-06 11:57:34 +02002016 struct hlua_csk_ctx *ctx = appctx->svcctx;
Willy Tarreauc12b3212022-05-27 11:08:15 +02002017 struct stconn *sc = appctx_sc(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002018
Christopher Faulet31572222023-03-31 11:13:48 +02002019 if (unlikely(se_fl_test(appctx->sedesc, (SE_FL_EOS|SE_FL_ERROR|SE_FL_SHR|SE_FL_SHW)))) {
2020 notification_wake(&ctx->wake_on_read);
2021 notification_wake(&ctx->wake_on_write);
2022 return;
2023 }
2024
Willy Tarreau5321da92022-05-06 11:57:34 +02002025 if (ctx->die) {
Christopher Faulet31572222023-03-31 11:13:48 +02002026 se_fl_set(appctx->sedesc, SE_FL_EOI|SE_FL_EOS);
Willy Tarreau5321da92022-05-06 11:57:34 +02002027 notification_wake(&ctx->wake_on_read);
2028 notification_wake(&ctx->wake_on_write);
Christopher Faulet31572222023-03-31 11:13:48 +02002029 return;
Thierry FOURNIERb13b20a2017-07-16 20:48:54 +02002030 }
2031
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +05002032 /* If we can't write, wakeup the pending write signals. */
Willy Tarreau3e7be362022-05-27 10:35:27 +02002033 if (channel_output_closed(sc_ic(sc)))
Willy Tarreau5321da92022-05-06 11:57:34 +02002034 notification_wake(&ctx->wake_on_write);
Thierry FOURNIER6d695e62015-09-27 19:29:38 +02002035
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +05002036 /* If we can't read, wakeup the pending read signals. */
Willy Tarreau3e7be362022-05-27 10:35:27 +02002037 if (channel_input_closed(sc_oc(sc)))
Willy Tarreau5321da92022-05-06 11:57:34 +02002038 notification_wake(&ctx->wake_on_read);
Thierry FOURNIER6d695e62015-09-27 19:29:38 +02002039
Willy Tarreau5a0b25d2019-07-18 18:01:14 +02002040 /* if the connection is not established, inform the stream that we want
Thierry FOURNIER316e3192015-09-04 18:25:53 +02002041 * to be notified whenever the connection completes.
2042 */
Willy Tarreau3e7be362022-05-27 10:35:27 +02002043 if (sc_opposite(sc)->state < SC_ST_EST) {
Willy Tarreau90e8b452022-05-25 18:21:43 +02002044 applet_need_more_data(appctx);
Willy Tarreaub23edc82022-05-24 16:49:03 +02002045 se_need_remote_conn(appctx->sedesc);
Willy Tarreau4164eb92022-05-25 15:42:03 +02002046 applet_have_more_data(appctx);
Willy Tarreaud4da1962015-04-20 01:31:23 +02002047 return;
Thierry FOURNIER316e3192015-09-04 18:25:53 +02002048 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002049
2050 /* This function is called after the connect. */
Willy Tarreau5321da92022-05-06 11:57:34 +02002051 ctx->connected = 1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002052
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002053 /* Wake the tasks which wants to write if the buffer have available space. */
Willy Tarreau3e7be362022-05-27 10:35:27 +02002054 if (channel_may_recv(sc_ic(sc)))
Willy Tarreau5321da92022-05-06 11:57:34 +02002055 notification_wake(&ctx->wake_on_write);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002056
2057 /* Wake the tasks which wants to read if the buffer contains data. */
Willy Tarreau3e7be362022-05-27 10:35:27 +02002058 if (!channel_is_empty(sc_oc(sc)))
Willy Tarreau5321da92022-05-06 11:57:34 +02002059 notification_wake(&ctx->wake_on_read);
Thierry FOURNIER101b9762018-05-27 01:27:40 +02002060
Thierry FOURNIER101b9762018-05-27 01:27:40 +02002061 /* If write notifications are registered, we considers we want
Willy Tarreau3367d412018-11-15 10:57:41 +01002062 * to write, so we clear the blocking flag.
Thierry FOURNIER101b9762018-05-27 01:27:40 +02002063 */
Willy Tarreau5321da92022-05-06 11:57:34 +02002064 if (notification_registered(&ctx->wake_on_write))
Willy Tarreau4164eb92022-05-25 15:42:03 +02002065 applet_have_more_data(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002066}
2067
Christopher Faulet5f35a3e2022-05-12 15:31:05 +02002068static int hlua_socket_init(struct appctx *appctx)
2069{
2070 struct hlua_csk_ctx *ctx = appctx->svcctx;
2071 struct stream *s;
2072
2073 if (appctx_finalize_startup(appctx, socket_proxy, &BUF_NULL) == -1)
2074 goto error;
2075
2076 s = appctx_strm(appctx);
2077
Willy Tarreau4596fe22022-05-17 19:07:51 +02002078 /* Configure "right" stream connector. This stconn is used to connect
Christopher Faulet5f35a3e2022-05-12 15:31:05 +02002079 * and retrieve data from the server. The connection is initialized
2080 * with the "struct server".
2081 */
Willy Tarreau74568cf2022-05-27 09:03:30 +02002082 sc_set_state(s->scb, SC_ST_ASS);
Christopher Faulet5f35a3e2022-05-12 15:31:05 +02002083
2084 /* Force destination server. */
2085 s->flags |= SF_DIRECT | SF_ASSIGNED | SF_BE_ASSIGNED;
2086 s->target = &socket_tcp->obj_type;
2087
2088 ctx->appctx = appctx;
2089 return 0;
2090
2091 error:
2092 return -1;
2093}
2094
Willy Tarreau87b09662015-04-03 00:22:06 +02002095/* This function is called when the "struct stream" is destroyed.
2096 * Remove the link from the object to this stream.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002097 * Wake all the pending signals.
2098 */
Willy Tarreau00a37f02015-04-13 12:05:19 +02002099static void hlua_socket_release(struct appctx *appctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002100{
Willy Tarreau5321da92022-05-06 11:57:34 +02002101 struct hlua_csk_ctx *ctx = appctx->svcctx;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002102 struct xref *peer;
2103
Christopher Faulet5f35a3e2022-05-12 15:31:05 +02002104 /* Remove my link in the original objects. */
Willy Tarreau5321da92022-05-06 11:57:34 +02002105 peer = xref_get_peer_and_lock(&ctx->xref);
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002106 if (peer)
Willy Tarreau5321da92022-05-06 11:57:34 +02002107 xref_disconnect(&ctx->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002108
2109 /* Wake all the task waiting for me. */
Willy Tarreau5321da92022-05-06 11:57:34 +02002110 notification_wake(&ctx->wake_on_read);
2111 notification_wake(&ctx->wake_on_write);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002112}
2113
2114/* If the garbage collectio of the object is launch, nobody
Willy Tarreau87b09662015-04-03 00:22:06 +02002115 * uses this object. If the stream does not exists, just quit.
2116 * Send the shutdown signal to the stream. In some cases,
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002117 * pending signal can rest in the read and write lists. destroy
2118 * it.
2119 */
2120__LJMP static int hlua_socket_gc(lua_State *L)
2121{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002122 struct hlua_socket *socket;
Willy Tarreau5321da92022-05-06 11:57:34 +02002123 struct hlua_csk_ctx *ctx;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002124 struct xref *peer;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002125
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002126 MAY_LJMP(check_args(L, 1, "__gc"));
2127
2128 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002129 peer = xref_get_peer_and_lock(&socket->xref);
2130 if (!peer)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002131 return 0;
Willy Tarreau5321da92022-05-06 11:57:34 +02002132
2133 ctx = container_of(peer, struct hlua_csk_ctx, xref);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002134
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002135 /* Set the flag which destroy the session. */
Willy Tarreau5321da92022-05-06 11:57:34 +02002136 ctx->die = 1;
2137 appctx_wakeup(ctx->appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002138
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002139 /* Remove all reference between the Lua stack and the coroutine stream. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002140 xref_disconnect(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002141 return 0;
2142}
2143
2144/* The close function send shutdown signal and break the
Willy Tarreau87b09662015-04-03 00:22:06 +02002145 * links between the stream and the object.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002146 */
sada05ed3302018-05-11 11:48:18 -07002147__LJMP static int hlua_socket_close_helper(lua_State *L)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002148{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002149 struct hlua_socket *socket;
Willy Tarreau5321da92022-05-06 11:57:34 +02002150 struct hlua_csk_ctx *ctx;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002151 struct xref *peer;
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002152 struct hlua *hlua;
2153
2154 /* Get hlua struct, or NULL if we execute from main lua state */
2155 hlua = hlua_gethlua(L);
2156 if (!hlua)
2157 return 0;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002158
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002159 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002160
2161 /* Check if we run on the same thread than the xreator thread.
2162 * We cannot access to the socket if the thread is different.
2163 */
2164 if (socket->tid != tid)
2165 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2166
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002167 peer = xref_get_peer_and_lock(&socket->xref);
2168 if (!peer)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002169 return 0;
Willy Tarreauf31af932020-01-14 09:59:38 +01002170
2171 hlua->gc_count--;
Willy Tarreau5321da92022-05-06 11:57:34 +02002172 ctx = container_of(peer, struct hlua_csk_ctx, xref);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002173
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002174 /* Set the flag which destroy the session. */
Willy Tarreau5321da92022-05-06 11:57:34 +02002175 ctx->die = 1;
2176 appctx_wakeup(ctx->appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002177
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002178 /* Remove all reference between the Lua stack and the coroutine stream. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002179 xref_disconnect(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002180 return 0;
2181}
2182
sada05ed3302018-05-11 11:48:18 -07002183/* The close function calls close_helper.
2184 */
2185__LJMP static int hlua_socket_close(lua_State *L)
2186{
2187 MAY_LJMP(check_args(L, 1, "close"));
2188 return hlua_socket_close_helper(L);
2189}
2190
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002191/* This Lua function assumes that the stack contain three parameters.
2192 * 1 - USERDATA containing a struct socket
2193 * 2 - INTEGER with values of the macro defined below
2194 * If the integer is -1, we must read at most one line.
2195 * If the integer is -2, we ust read all the data until the
2196 * end of the stream.
2197 * If the integer is positive value, we must read a number of
2198 * bytes corresponding to this value.
2199 */
2200#define HLSR_READ_LINE (-1)
2201#define HLSR_READ_ALL (-2)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002202__LJMP static int hlua_socket_receive_yield(struct lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002203{
2204 struct hlua_socket *socket = MAY_LJMP(hlua_checksocket(L, 1));
2205 int wanted = lua_tointeger(L, 2);
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002206 struct hlua *hlua;
Willy Tarreau5321da92022-05-06 11:57:34 +02002207 struct hlua_csk_ctx *csk_ctx;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002208 struct appctx *appctx;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02002209 size_t len;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002210 int nblk;
Willy Tarreau206ba832018-06-14 15:27:31 +02002211 const char *blk1;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02002212 size_t len1;
Willy Tarreau206ba832018-06-14 15:27:31 +02002213 const char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02002214 size_t len2;
Thierry FOURNIER00543922015-03-09 18:35:06 +01002215 int skip_at_end = 0;
Willy Tarreau81389672015-03-10 12:03:52 +01002216 struct channel *oc;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002217 struct stream *s;
2218 struct xref *peer;
Thierry FOURNIER8c126c72018-05-25 16:27:44 +02002219 int missing_bytes;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002220
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002221 /* Get hlua struct, or NULL if we execute from main lua state */
2222 hlua = hlua_gethlua(L);
2223
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002224 /* Check if this lua stack is schedulable. */
2225 if (!hlua || !hlua->task)
2226 WILL_LJMP(luaL_error(L, "The 'receive' function is only allowed in "
2227 "'frontend', 'backend' or 'task'"));
2228
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002229 /* Check if we run on the same thread than the xreator thread.
2230 * We cannot access to the socket if the thread is different.
2231 */
2232 if (socket->tid != tid)
2233 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2234
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002235 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002236 peer = xref_get_peer_and_lock(&socket->xref);
2237 if (!peer)
2238 goto no_peer;
Willy Tarreau5321da92022-05-06 11:57:34 +02002239
2240 csk_ctx = container_of(peer, struct hlua_csk_ctx, xref);
2241 appctx = csk_ctx->appctx;
Willy Tarreau0698c802022-05-11 14:09:57 +02002242 s = appctx_strm(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002243
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002244 oc = &s->res;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002245 if (wanted == HLSR_READ_LINE) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002246 /* Read line. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02002247 nblk = co_getline_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002248 if (nblk < 0) /* Connection close. */
2249 goto connection_closed;
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002250 if (nblk == 0) /* No data available. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002251 goto connection_empty;
Thierry FOURNIER00543922015-03-09 18:35:06 +01002252
2253 /* remove final \r\n. */
2254 if (nblk == 1) {
2255 if (blk1[len1-1] == '\n') {
2256 len1--;
2257 skip_at_end++;
2258 if (blk1[len1-1] == '\r') {
2259 len1--;
2260 skip_at_end++;
2261 }
2262 }
2263 }
2264 else {
2265 if (blk2[len2-1] == '\n') {
2266 len2--;
2267 skip_at_end++;
2268 if (blk2[len2-1] == '\r') {
2269 len2--;
2270 skip_at_end++;
2271 }
2272 }
2273 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002274 }
2275
2276 else if (wanted == HLSR_READ_ALL) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002277 /* Read all the available data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02002278 nblk = co_getblk_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002279 if (nblk < 0) /* Connection close. */
2280 goto connection_closed;
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002281 if (nblk == 0) /* No data available. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002282 goto connection_empty;
2283 }
2284
2285 else {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002286 /* Read a block of data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02002287 nblk = co_getblk_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002288 if (nblk < 0) /* Connection close. */
2289 goto connection_closed;
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002290 if (nblk == 0) /* No data available. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002291 goto connection_empty;
2292
Thierry FOURNIER8c126c72018-05-25 16:27:44 +02002293 missing_bytes = wanted - socket->b.n;
2294 if (len1 > missing_bytes) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002295 nblk = 1;
Thierry FOURNIER8c126c72018-05-25 16:27:44 +02002296 len1 = missing_bytes;
2297 } if (nblk == 2 && len1 + len2 > missing_bytes)
2298 len2 = missing_bytes - len1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002299 }
2300
2301 len = len1;
2302
2303 luaL_addlstring(&socket->b, blk1, len1);
2304 if (nblk == 2) {
2305 len += len2;
2306 luaL_addlstring(&socket->b, blk2, len2);
2307 }
2308
2309 /* Consume data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02002310 co_skip(oc, len + skip_at_end);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002311
2312 /* Don't wait anything. */
Thierry FOURNIER7e4ee472018-05-25 15:03:50 +02002313 appctx_wakeup(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002314
2315 /* If the pattern reclaim to read all the data
2316 * in the connection, got out.
2317 */
2318 if (wanted == HLSR_READ_ALL)
2319 goto connection_empty;
Thierry FOURNIER8c126c72018-05-25 16:27:44 +02002320 else if (wanted >= 0 && socket->b.n < wanted)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002321 goto connection_empty;
2322
2323 /* Return result. */
2324 luaL_pushresult(&socket->b);
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002325 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002326 return 1;
2327
2328connection_closed:
2329
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002330 xref_unlock(&socket->xref, peer);
2331
2332no_peer:
2333
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002334 /* If the buffer containds data. */
2335 if (socket->b.n > 0) {
2336 luaL_pushresult(&socket->b);
2337 return 1;
2338 }
2339 lua_pushnil(L);
2340 lua_pushstring(L, "connection closed.");
2341 return 2;
2342
2343connection_empty:
2344
Willy Tarreau5321da92022-05-06 11:57:34 +02002345 if (!notification_new(&hlua->com, &csk_ctx->wake_on_read, hlua->task)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002346 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002347 WILL_LJMP(luaL_error(L, "out of memory"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002348 }
2349 xref_unlock(&socket->xref, peer);
Willy Tarreau9635e032018-10-16 17:52:55 +02002350 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_receive_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002351 return 0;
2352}
2353
Tim Duesterhusb33754c2018-01-04 19:32:14 +01002354/* This Lua function gets two parameters. The first one can be string
2355 * or a number. If the string is "*l", the user requires one line. If
2356 * the string is "*a", the user requires all the contents of the stream.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002357 * If the value is a number, the user require a number of bytes equal
2358 * to the value. The default value is "*l" (a line).
2359 *
Tim Duesterhusb33754c2018-01-04 19:32:14 +01002360 * This parameter with a variable type is converted in integer. This
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002361 * integer takes this values:
2362 * -1 : read a line
2363 * -2 : read all the stream
Tim Duesterhusb33754c2018-01-04 19:32:14 +01002364 * >0 : amount of bytes.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002365 *
Tim Duesterhusb33754c2018-01-04 19:32:14 +01002366 * The second parameter is optional. It contains a string that must be
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002367 * concatenated with the read data.
2368 */
2369__LJMP static int hlua_socket_receive(struct lua_State *L)
2370{
2371 int wanted = HLSR_READ_LINE;
2372 const char *pattern;
Christopher Fauletc31b2002021-05-03 10:11:13 +02002373 int lastarg, type;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002374 char *error;
2375 size_t len;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002376 struct hlua_socket *socket;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002377
2378 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
2379 WILL_LJMP(luaL_error(L, "The 'receive' function requires between 1 and 3 arguments."));
2380
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002381 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002382
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002383 /* Check if we run on the same thread than the xreator thread.
2384 * We cannot access to the socket if the thread is different.
2385 */
2386 if (socket->tid != tid)
2387 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2388
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002389 /* check for pattern. */
2390 if (lua_gettop(L) >= 2) {
2391 type = lua_type(L, 2);
2392 if (type == LUA_TSTRING) {
2393 pattern = lua_tostring(L, 2);
2394 if (strcmp(pattern, "*a") == 0)
2395 wanted = HLSR_READ_ALL;
2396 else if (strcmp(pattern, "*l") == 0)
2397 wanted = HLSR_READ_LINE;
2398 else {
2399 wanted = strtoll(pattern, &error, 10);
2400 if (*error != '\0')
2401 WILL_LJMP(luaL_error(L, "Unsupported pattern."));
2402 }
2403 }
2404 else if (type == LUA_TNUMBER) {
2405 wanted = lua_tointeger(L, 2);
2406 if (wanted < 0)
2407 WILL_LJMP(luaL_error(L, "Unsupported size."));
2408 }
2409 }
2410
2411 /* Set pattern. */
2412 lua_pushinteger(L, wanted);
Tim Duesterhusc6e377e2018-01-04 19:32:13 +01002413
2414 /* Check if we would replace the top by itself. */
2415 if (lua_gettop(L) != 2)
2416 lua_replace(L, 2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002417
Christopher Fauletc31b2002021-05-03 10:11:13 +02002418 /* Save index of the top of the stack because since buffers are used, it
2419 * may change
2420 */
2421 lastarg = lua_gettop(L);
2422
Tim Duesterhusb33754c2018-01-04 19:32:14 +01002423 /* init buffer, and fill it with prefix. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002424 luaL_buffinit(L, &socket->b);
2425
2426 /* Check prefix. */
Christopher Fauletc31b2002021-05-03 10:11:13 +02002427 if (lastarg >= 3) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002428 if (lua_type(L, 3) != LUA_TSTRING)
2429 WILL_LJMP(luaL_error(L, "Expect a 'string' for the prefix"));
2430 pattern = lua_tolstring(L, 3, &len);
2431 luaL_addlstring(&socket->b, pattern, len);
2432 }
2433
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002434 return __LJMP(hlua_socket_receive_yield(L, 0, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002435}
2436
2437/* Write the Lua input string in the output buffer.
Mark Lakes22154b42018-01-29 14:38:40 -08002438 * This function returns a yield if no space is available.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002439 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002440static int hlua_socket_write_yield(struct lua_State *L,int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002441{
2442 struct hlua_socket *socket;
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002443 struct hlua *hlua;
Willy Tarreau5321da92022-05-06 11:57:34 +02002444 struct hlua_csk_ctx *csk_ctx;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002445 struct appctx *appctx;
2446 size_t buf_len;
2447 const char *buf;
2448 int len;
2449 int send_len;
2450 int sent;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002451 struct xref *peer;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002452 struct stream *s;
Willy Tarreau3e7be362022-05-27 10:35:27 +02002453 struct stconn *sc;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002454
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002455 /* Get hlua struct, or NULL if we execute from main lua state */
2456 hlua = hlua_gethlua(L);
2457
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002458 /* Check if this lua stack is schedulable. */
2459 if (!hlua || !hlua->task)
2460 WILL_LJMP(luaL_error(L, "The 'write' function is only allowed in "
2461 "'frontend', 'backend' or 'task'"));
2462
2463 /* Get object */
2464 socket = MAY_LJMP(hlua_checksocket(L, 1));
2465 buf = MAY_LJMP(luaL_checklstring(L, 2, &buf_len));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002466 sent = MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002467
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002468 /* Check if we run on the same thread than the xreator thread.
2469 * We cannot access to the socket if the thread is different.
2470 */
2471 if (socket->tid != tid)
2472 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2473
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002474 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002475 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002476 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002477 lua_pushinteger(L, -1);
2478 return 1;
2479 }
Willy Tarreau5321da92022-05-06 11:57:34 +02002480
2481 csk_ctx = container_of(peer, struct hlua_csk_ctx, xref);
2482 appctx = csk_ctx->appctx;
Willy Tarreauc12b3212022-05-27 11:08:15 +02002483 sc = appctx_sc(appctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02002484 s = __sc_strm(sc);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002485
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002486 /* Check for connection close. */
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002487 if (channel_output_closed(&s->req)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002488 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002489 lua_pushinteger(L, -1);
2490 return 1;
2491 }
2492
2493 /* Update the input buffer data. */
2494 buf += sent;
2495 send_len = buf_len - sent;
2496
2497 /* All the data are sent. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002498 if (sent >= buf_len) {
2499 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002500 return 1; /* Implicitly return the length sent. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002501 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002502
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002503 /* Check if the buffer is available because HAProxy doesn't allocate
Thierry FOURNIER486d52a2015-03-09 17:51:43 +01002504 * the request buffer if its not required.
2505 */
Willy Tarreauc9fa0482018-07-10 17:43:27 +02002506 if (s->req.buf.size == 0) {
Willy Tarreau3e7be362022-05-27 10:35:27 +02002507 if (!sc_alloc_ibuf(sc, &appctx->buffer_wait))
Christopher Faulet33834b12016-12-19 09:29:06 +01002508 goto hlua_socket_write_yield_return;
Thierry FOURNIER486d52a2015-03-09 17:51:43 +01002509 }
2510
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002511 /* Check for available space. */
Willy Tarreauc9fa0482018-07-10 17:43:27 +02002512 len = b_room(&s->req.buf);
Christopher Faulet33834b12016-12-19 09:29:06 +01002513 if (len <= 0) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002514 goto hlua_socket_write_yield_return;
Christopher Faulet33834b12016-12-19 09:29:06 +01002515 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002516
2517 /* send data */
2518 if (len < send_len)
2519 send_len = len;
Thierry FOURNIER66b89192018-05-27 01:14:47 +02002520 len = ci_putblk(&s->req, buf, send_len);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002521
2522 /* "Not enough space" (-1), "Buffer too little to contain
2523 * the data" (-2) are not expected because the available length
2524 * is tested.
2525 * Other unknown error are also not expected.
2526 */
2527 if (len <= 0) {
Willy Tarreaubc18da12015-03-13 14:00:47 +01002528 if (len == -1)
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002529 s->req.flags |= CF_WAKE_WRITE;
Willy Tarreaubc18da12015-03-13 14:00:47 +01002530
sada05ed3302018-05-11 11:48:18 -07002531 MAY_LJMP(hlua_socket_close_helper(L));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002532 lua_pop(L, 1);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002533 lua_pushinteger(L, -1);
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002534 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002535 return 1;
2536 }
2537
2538 /* update buffers. */
Thierry FOURNIER101b9762018-05-27 01:27:40 +02002539 appctx_wakeup(appctx);
Willy Tarreaude70fa12015-09-26 11:25:05 +02002540
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002541 /* Update length sent. */
2542 lua_pop(L, 1);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002543 lua_pushinteger(L, sent + len);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002544
2545 /* All the data buffer is sent ? */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002546 if (sent + len >= buf_len) {
2547 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002548 return 1;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002549 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002550
2551hlua_socket_write_yield_return:
Willy Tarreau5321da92022-05-06 11:57:34 +02002552 if (!notification_new(&hlua->com, &csk_ctx->wake_on_write, hlua->task)) {
Thierry FOURNIERba42fcd2018-05-27 00:59:48 +02002553 xref_unlock(&socket->xref, peer);
2554 WILL_LJMP(luaL_error(L, "out of memory"));
2555 }
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002556 xref_unlock(&socket->xref, peer);
Willy Tarreau9635e032018-10-16 17:52:55 +02002557 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_write_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002558 return 0;
2559}
2560
2561/* This function initiate the send of data. It just check the input
2562 * parameters and push an integer in the Lua stack that contain the
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002563 * amount of data written to the buffer. This is used by the function
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002564 * "hlua_socket_write_yield" that can yield.
2565 *
2566 * The Lua function gets between 3 and 4 parameters. The first one is
2567 * the associated object. The second is a string buffer. The third is
2568 * a facultative integer that represents where is the buffer position
2569 * of the start of the data that can send. The first byte is the
2570 * position "1". The default value is "1". The fourth argument is a
2571 * facultative integer that represents where is the buffer position
2572 * of the end of the data that can send. The default is the last byte.
2573 */
2574static int hlua_socket_send(struct lua_State *L)
2575{
2576 int i;
2577 int j;
2578 const char *buf;
2579 size_t buf_len;
2580
2581 /* Check number of arguments. */
2582 if (lua_gettop(L) < 2 || lua_gettop(L) > 4)
2583 WILL_LJMP(luaL_error(L, "'send' needs between 2 and 4 arguments"));
2584
2585 /* Get the string. */
2586 buf = MAY_LJMP(luaL_checklstring(L, 2, &buf_len));
2587
2588 /* Get and check j. */
2589 if (lua_gettop(L) == 4) {
2590 j = MAY_LJMP(luaL_checkinteger(L, 4));
2591 if (j < 0)
2592 j = buf_len + j + 1;
2593 if (j > buf_len)
2594 j = buf_len + 1;
2595 lua_pop(L, 1);
2596 }
2597 else
2598 j = buf_len;
2599
2600 /* Get and check i. */
2601 if (lua_gettop(L) == 3) {
2602 i = MAY_LJMP(luaL_checkinteger(L, 3));
2603 if (i < 0)
2604 i = buf_len + i + 1;
2605 if (i > buf_len)
2606 i = buf_len + 1;
2607 lua_pop(L, 1);
2608 } else
2609 i = 1;
2610
2611 /* Check bth i and j. */
2612 if (i > j) {
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002613 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002614 return 1;
2615 }
2616 if (i == 0 && j == 0) {
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002617 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002618 return 1;
2619 }
2620 if (i == 0)
2621 i = 1;
2622 if (j == 0)
2623 j = 1;
2624
2625 /* Pop the string. */
2626 lua_pop(L, 1);
2627
2628 /* Update the buffer length. */
2629 buf += i - 1;
2630 buf_len = j - i + 1;
2631 lua_pushlstring(L, buf, buf_len);
2632
2633 /* This unsigned is used to remember the amount of sent data. */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002634 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002635
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002636 return MAY_LJMP(hlua_socket_write_yield(L, 0, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002637}
2638
Willy Tarreau22b0a682015-06-17 19:43:49 +02002639#define SOCKET_INFO_MAX_LEN sizeof("[0000:0000:0000:0000:0000:0000:0000:0000]:12345")
Christopher Faulete6465b32021-10-22 15:36:08 +02002640__LJMP static inline int hlua_socket_info(struct lua_State *L, const struct sockaddr_storage *addr)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002641{
2642 static char buffer[SOCKET_INFO_MAX_LEN];
2643 int ret;
2644 int len;
2645 char *p;
2646
2647 ret = addr_to_str(addr, buffer+1, SOCKET_INFO_MAX_LEN-1);
2648 if (ret <= 0) {
2649 lua_pushnil(L);
2650 return 1;
2651 }
2652
2653 if (ret == AF_UNIX) {
2654 lua_pushstring(L, buffer+1);
2655 return 1;
2656 }
2657 else if (ret == AF_INET6) {
2658 buffer[0] = '[';
2659 len = strlen(buffer);
2660 buffer[len] = ']';
2661 len++;
2662 buffer[len] = ':';
2663 len++;
2664 p = buffer;
2665 }
2666 else if (ret == AF_INET) {
2667 p = buffer + 1;
2668 len = strlen(p);
2669 p[len] = ':';
2670 len++;
2671 }
2672 else {
2673 lua_pushnil(L);
2674 return 1;
2675 }
2676
2677 if (port_to_str(addr, p + len, SOCKET_INFO_MAX_LEN-1 - len) <= 0) {
2678 lua_pushnil(L);
2679 return 1;
2680 }
2681
2682 lua_pushstring(L, p);
2683 return 1;
2684}
2685
2686/* Returns information about the peer of the connection. */
2687__LJMP static int hlua_socket_getpeername(struct lua_State *L)
2688{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002689 struct hlua_socket *socket;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002690 struct xref *peer;
2691 struct appctx *appctx;
Willy Tarreau3e7be362022-05-27 10:35:27 +02002692 struct stconn *sc;
Christopher Faulet16f16af2021-10-27 09:34:56 +02002693 const struct sockaddr_storage *dst;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002694 int ret;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002695
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002696 MAY_LJMP(check_args(L, 1, "getpeername"));
2697
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002698 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002699
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002700 /* Check if we run on the same thread than the xreator thread.
2701 * We cannot access to the socket if the thread is different.
2702 */
2703 if (socket->tid != tid)
2704 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2705
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002706 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002707 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002708 if (!peer) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002709 lua_pushnil(L);
2710 return 1;
2711 }
Willy Tarreau5321da92022-05-06 11:57:34 +02002712
2713 appctx = container_of(peer, struct hlua_csk_ctx, xref)->appctx;
Willy Tarreauc12b3212022-05-27 11:08:15 +02002714 sc = appctx_sc(appctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02002715 dst = sc_dst(sc_opposite(sc));
Christopher Faulet16f16af2021-10-27 09:34:56 +02002716 if (!dst) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002717 xref_unlock(&socket->xref, peer);
Willy Tarreaua71f6422016-11-16 17:00:14 +01002718 lua_pushnil(L);
2719 return 1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002720 }
2721
Christopher Faulet16f16af2021-10-27 09:34:56 +02002722 ret = MAY_LJMP(hlua_socket_info(L, dst));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002723 xref_unlock(&socket->xref, peer);
2724 return ret;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002725}
2726
2727/* Returns information about my connection side. */
2728static int hlua_socket_getsockname(struct lua_State *L)
2729{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002730 struct hlua_socket *socket;
2731 struct connection *conn;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002732 struct appctx *appctx;
2733 struct xref *peer;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002734 struct stream *s;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002735 int ret;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002736
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002737 MAY_LJMP(check_args(L, 1, "getsockname"));
2738
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002739 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002740
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002741 /* Check if we run on the same thread than the xreator thread.
2742 * We cannot access to the socket if the thread is different.
2743 */
2744 if (socket->tid != tid)
2745 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2746
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002747 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002748 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002749 if (!peer) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002750 lua_pushnil(L);
2751 return 1;
2752 }
Willy Tarreau5321da92022-05-06 11:57:34 +02002753
2754 appctx = container_of(peer, struct hlua_csk_ctx, xref)->appctx;
Willy Tarreau0698c802022-05-11 14:09:57 +02002755 s = appctx_strm(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002756
Willy Tarreaufd9417b2022-05-18 16:23:22 +02002757 conn = sc_conn(s->scb);
Willy Tarreau5a0b25d2019-07-18 18:01:14 +02002758 if (!conn || !conn_get_src(conn)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002759 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002760 lua_pushnil(L);
2761 return 1;
2762 }
2763
Willy Tarreau9da9a6f2019-07-17 14:49:44 +02002764 ret = hlua_socket_info(L, conn->src);
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002765 xref_unlock(&socket->xref, peer);
2766 return ret;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002767}
2768
2769/* This struct define the applet. */
Willy Tarreau30576452015-04-13 13:50:30 +02002770static struct applet update_applet = {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002771 .obj_type = OBJ_TYPE_APPLET,
2772 .name = "<LUA_TCP>",
2773 .fct = hlua_socket_handler,
Christopher Faulet5f35a3e2022-05-12 15:31:05 +02002774 .init = hlua_socket_init,
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002775 .release = hlua_socket_release,
2776};
2777
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002778__LJMP static int hlua_socket_connect_yield(struct lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002779{
2780 struct hlua_socket *socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002781 struct hlua *hlua;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002782 struct xref *peer;
Willy Tarreau5321da92022-05-06 11:57:34 +02002783 struct hlua_csk_ctx *csk_ctx;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002784 struct appctx *appctx;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002785 struct stream *s;
2786
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002787 /* Get hlua struct, or NULL if we execute from main lua state */
2788 hlua = hlua_gethlua(L);
2789 if (!hlua)
2790 return 0;
2791
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002792 /* Check if we run on the same thread than the xreator thread.
2793 * We cannot access to the socket if the thread is different.
2794 */
2795 if (socket->tid != tid)
2796 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2797
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002798 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002799 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002800 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002801 lua_pushnil(L);
2802 lua_pushstring(L, "Can't connect");
2803 return 2;
2804 }
Willy Tarreau5321da92022-05-06 11:57:34 +02002805
2806 csk_ctx = container_of(peer, struct hlua_csk_ctx, xref);
2807 appctx = csk_ctx->appctx;
Willy Tarreau0698c802022-05-11 14:09:57 +02002808 s = appctx_strm(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002809
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002810 /* Check if we run on the same thread than the xreator thread.
2811 * We cannot access to the socket if the thread is different.
2812 */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002813 if (socket->tid != tid) {
2814 xref_unlock(&socket->xref, peer);
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002815 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002816 }
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002817
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002818 /* Check for connection close. */
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002819 if (!hlua || channel_output_closed(&s->req)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002820 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002821 lua_pushnil(L);
2822 lua_pushstring(L, "Can't connect");
2823 return 2;
2824 }
2825
Willy Tarreau8e7c6e62022-05-18 17:58:02 +02002826 appctx = __sc_appctx(s->scf);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002827
2828 /* Check for connection established. */
Willy Tarreau5321da92022-05-06 11:57:34 +02002829 if (csk_ctx->connected) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002830 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002831 lua_pushinteger(L, 1);
2832 return 1;
2833 }
2834
Willy Tarreau5321da92022-05-06 11:57:34 +02002835 if (!notification_new(&hlua->com, &csk_ctx->wake_on_write, hlua->task)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002836 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002837 WILL_LJMP(luaL_error(L, "out of memory error"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002838 }
2839 xref_unlock(&socket->xref, peer);
Willy Tarreau9635e032018-10-16 17:52:55 +02002840 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_connect_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002841 return 0;
2842}
2843
2844/* This function fail or initite the connection. */
2845__LJMP static int hlua_socket_connect(struct lua_State *L)
2846{
2847 struct hlua_socket *socket;
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002848 int port = -1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002849 const char *ip;
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002850 struct hlua *hlua;
Willy Tarreau5321da92022-05-06 11:57:34 +02002851 struct hlua_csk_ctx *csk_ctx;
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002852 struct appctx *appctx;
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002853 int low, high;
2854 struct sockaddr_storage *addr;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002855 struct xref *peer;
Willy Tarreau3e7be362022-05-27 10:35:27 +02002856 struct stconn *sc;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002857 struct stream *s;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002858
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002859 if (lua_gettop(L) < 2)
2860 WILL_LJMP(luaL_error(L, "connect: need at least 2 arguments"));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002861
2862 /* Get args. */
2863 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002864
2865 /* Check if we run on the same thread than the xreator thread.
2866 * We cannot access to the socket if the thread is different.
2867 */
2868 if (socket->tid != tid)
2869 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2870
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002871 ip = MAY_LJMP(luaL_checkstring(L, 2));
Tim Duesterhus6edab862018-01-06 19:04:45 +01002872 if (lua_gettop(L) >= 3) {
2873 luaL_Buffer b;
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002874 port = MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002875
Tim Duesterhus6edab862018-01-06 19:04:45 +01002876 /* Force the ip to end with a colon, to support IPv6 addresses
2877 * that are not enclosed within square brackets.
2878 */
2879 if (port > 0) {
2880 luaL_buffinit(L, &b);
2881 luaL_addstring(&b, ip);
2882 luaL_addchar(&b, ':');
2883 luaL_pushresult(&b);
2884 ip = lua_tolstring(L, lua_gettop(L), NULL);
2885 }
2886 }
2887
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002888 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002889 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002890 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002891 lua_pushnil(L);
2892 return 1;
2893 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002894
2895 /* Parse ip address. */
Willy Tarreau5fc93282020-09-16 18:25:03 +02002896 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 +02002897 if (!addr) {
2898 xref_unlock(&socket->xref, peer);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002899 WILL_LJMP(luaL_error(L, "connect: cannot parse destination address '%s'", ip));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002900 }
Willy Tarreau9da9a6f2019-07-17 14:49:44 +02002901
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002902 /* Set port. */
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002903 if (low == 0) {
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02002904 if (addr->ss_family == AF_INET) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002905 if (port == -1) {
2906 xref_unlock(&socket->xref, peer);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002907 WILL_LJMP(luaL_error(L, "connect: port missing"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002908 }
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02002909 ((struct sockaddr_in *)addr)->sin_port = htons(port);
2910 } else if (addr->ss_family == AF_INET6) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002911 if (port == -1) {
2912 xref_unlock(&socket->xref, peer);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002913 WILL_LJMP(luaL_error(L, "connect: port missing"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002914 }
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02002915 ((struct sockaddr_in6 *)addr)->sin6_port = htons(port);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002916 }
2917 }
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02002918
Willy Tarreau5321da92022-05-06 11:57:34 +02002919 csk_ctx = container_of(peer, struct hlua_csk_ctx, xref);
2920 appctx = csk_ctx->appctx;
Willy Tarreauc12b3212022-05-27 11:08:15 +02002921 sc = appctx_sc(appctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02002922 s = __sc_strm(sc);
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02002923
Willy Tarreau3e7be362022-05-27 10:35:27 +02002924 if (!sockaddr_alloc(&sc_opposite(sc)->dst, addr, sizeof(*addr))) {
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02002925 xref_unlock(&socket->xref, peer);
2926 WILL_LJMP(luaL_error(L, "connect: internal error"));
2927 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002928
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002929 /* Get hlua struct, or NULL if we execute from main lua state */
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002930 hlua = hlua_gethlua(L);
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002931 if (!hlua)
2932 return 0;
Willy Tarreaubdc97a82015-08-24 15:42:28 +02002933
2934 /* inform the stream that we want to be notified whenever the
2935 * connection completes.
2936 */
Willy Tarreau90e8b452022-05-25 18:21:43 +02002937 applet_need_more_data(appctx);
Willy Tarreau4164eb92022-05-25 15:42:03 +02002938 applet_have_more_data(appctx);
Thierry FOURNIER8c8fbbe2015-09-26 17:02:35 +02002939 appctx_wakeup(appctx);
Willy Tarreaubdc97a82015-08-24 15:42:28 +02002940
Willy Tarreauf31af932020-01-14 09:59:38 +01002941 hlua->gc_count++;
Thierry FOURNIER7c39ab42015-09-27 22:53:33 +02002942
Willy Tarreau5321da92022-05-06 11:57:34 +02002943 if (!notification_new(&hlua->com, &csk_ctx->wake_on_write, hlua->task)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002944 xref_unlock(&socket->xref, peer);
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002945 WILL_LJMP(luaL_error(L, "out of memory"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002946 }
2947 xref_unlock(&socket->xref, peer);
PiBa-NL706d5ee2018-05-05 23:51:42 +02002948
2949 task_wakeup(s->task, TASK_WOKEN_INIT);
2950 /* Return yield waiting for connection. */
2951
Willy Tarreau9635e032018-10-16 17:52:55 +02002952 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_connect_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002953
2954 return 0;
2955}
2956
Baptiste Assmann84bb4932015-03-02 21:40:06 +01002957#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002958__LJMP static int hlua_socket_connect_ssl(struct lua_State *L)
2959{
2960 struct hlua_socket *socket;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002961 struct xref *peer;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002962 struct stream *s;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002963
2964 MAY_LJMP(check_args(L, 3, "connect_ssl"));
2965 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002966
2967 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002968 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002969 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002970 lua_pushnil(L);
2971 return 1;
2972 }
Willy Tarreau5321da92022-05-06 11:57:34 +02002973
Willy Tarreau0698c802022-05-11 14:09:57 +02002974 s = appctx_strm(container_of(peer, struct hlua_csk_ctx, xref)->appctx);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002975
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +01002976 s->target = &socket_ssl->obj_type;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002977 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002978 return MAY_LJMP(hlua_socket_connect(L));
2979}
Baptiste Assmann84bb4932015-03-02 21:40:06 +01002980#endif
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002981
2982__LJMP static int hlua_socket_setoption(struct lua_State *L)
2983{
2984 return 0;
2985}
2986
2987__LJMP static int hlua_socket_settimeout(struct lua_State *L)
2988{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002989 struct hlua_socket *socket;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002990 int tmout;
Mark Lakes56cc1252018-03-27 09:48:06 +02002991 double dtmout;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002992 struct xref *peer;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002993 struct stream *s;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002994
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002995 MAY_LJMP(check_args(L, 2, "settimeout"));
2996
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002997 socket = MAY_LJMP(hlua_checksocket(L, 1));
Mark Lakes56cc1252018-03-27 09:48:06 +02002998
Cyril Bonté7ee465f2018-08-19 22:08:50 +02002999 /* convert the timeout to millis */
3000 dtmout = MAY_LJMP(luaL_checknumber(L, 2)) * 1000;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003001
Thierry Fournier17a921b2018-03-08 09:59:02 +01003002 /* Check for negative values */
Mark Lakes56cc1252018-03-27 09:48:06 +02003003 if (dtmout < 0)
Thierry Fournier17a921b2018-03-08 09:59:02 +01003004 WILL_LJMP(luaL_error(L, "settimeout: cannot set negatives values"));
3005
Mark Lakes56cc1252018-03-27 09:48:06 +02003006 if (dtmout > INT_MAX) /* overflow check */
Cyril Bonté7ee465f2018-08-19 22:08:50 +02003007 WILL_LJMP(luaL_error(L, "settimeout: cannot set values larger than %d ms", INT_MAX));
Mark Lakes56cc1252018-03-27 09:48:06 +02003008
3009 tmout = MS_TO_TICKS((int)dtmout);
Cyril Bonté7ee465f2018-08-19 22:08:50 +02003010 if (tmout == 0)
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05003011 tmout++; /* very small timeouts are adjusted to a minimum of 1ms */
Mark Lakes56cc1252018-03-27 09:48:06 +02003012
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02003013 /* Check if we run on the same thread than the xreator thread.
3014 * We cannot access to the socket if the thread is different.
3015 */
3016 if (socket->tid != tid)
3017 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
3018
Mark Lakes56cc1252018-03-27 09:48:06 +02003019 /* check for connection break. If some data were read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02003020 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003021 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003022 hlua_pusherror(L, "socket: not yet initialised, you can't set timeouts.");
3023 WILL_LJMP(lua_error(L));
3024 return 0;
3025 }
Willy Tarreau5321da92022-05-06 11:57:34 +02003026
Willy Tarreau0698c802022-05-11 14:09:57 +02003027 s = appctx_strm(container_of(peer, struct hlua_csk_ctx, xref)->appctx);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003028
Cyril Bonté7bb63452018-08-17 23:51:02 +02003029 s->sess->fe->timeout.connect = tmout;
Christopher Faulet5aaacfb2023-02-15 08:13:33 +01003030 s->scf->ioto = tmout;
3031 s->scb->ioto = tmout;
Cyril Bonté7bb63452018-08-17 23:51:02 +02003032
3033 s->task->expire = tick_add_ifset(now_ms, tmout);
3034 task_queue(s->task);
3035
Thierry FOURNIER952939d2017-09-01 14:17:32 +02003036 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003037
Thierry Fourniere9636f12018-03-08 09:54:32 +01003038 lua_pushinteger(L, 1);
Tim Duesterhus119a5f12018-01-06 19:16:25 +01003039 return 1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003040}
3041
3042__LJMP static int hlua_socket_new(lua_State *L)
3043{
3044 struct hlua_socket *socket;
Willy Tarreau5321da92022-05-06 11:57:34 +02003045 struct hlua_csk_ctx *ctx;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003046 struct appctx *appctx;
3047
3048 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003049 if (!lua_checkstack(L, 3)) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003050 hlua_pusherror(L, "socket: full stack");
3051 goto out_fail_conf;
3052 }
3053
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003054 /* Create the object: obj[0] = userdata. */
3055 lua_newtable(L);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003056 socket = MAY_LJMP(lua_newuserdata(L, sizeof(*socket)));
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003057 lua_rawseti(L, -2, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003058 memset(socket, 0, sizeof(*socket));
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02003059 socket->tid = tid;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003060
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05003061 /* Check if the various memory pools are initialized. */
Willy Tarreaubafbe012017-11-24 17:34:44 +01003062 if (!pool_head_stream || !pool_head_buffer) {
Thierry FOURNIER4a6170c2015-03-09 17:07:10 +01003063 hlua_pusherror(L, "socket: uninitialized pools.");
3064 goto out_fail_conf;
3065 }
3066
Willy Tarreau87b09662015-04-03 00:22:06 +02003067 /* Pop a class stream metatable and affect it to the userdata. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003068 lua_rawgeti(L, LUA_REGISTRYINDEX, class_socket_ref);
3069 lua_setmetatable(L, -2);
3070
Willy Tarreaud420a972015-04-06 00:39:18 +02003071 /* Create the applet context */
Christopher Faulet6095d572022-05-16 17:09:48 +02003072 appctx = appctx_new_here(&update_applet, NULL);
Willy Tarreau61cf7c82015-04-06 00:48:33 +02003073 if (!appctx) {
3074 hlua_pusherror(L, "socket: out of memory");
Christopher Fauleta9e8b392022-03-23 11:01:09 +01003075 goto out_fail_conf;
Willy Tarreau61cf7c82015-04-06 00:48:33 +02003076 }
Willy Tarreau5321da92022-05-06 11:57:34 +02003077 ctx = applet_reserve_svcctx(appctx, sizeof(*ctx));
3078 ctx->connected = 0;
Willy Tarreau5321da92022-05-06 11:57:34 +02003079 ctx->die = 0;
3080 LIST_INIT(&ctx->wake_on_write);
3081 LIST_INIT(&ctx->wake_on_read);
Willy Tarreaub2bf8332015-04-04 15:58:58 +02003082
Christopher Faulet5f35a3e2022-05-12 15:31:05 +02003083 if (appctx_init(appctx) == -1) {
3084 hlua_pusherror(L, "socket: fail to init applet.");
Christopher Faulet13a35e52021-12-20 15:34:16 +01003085 goto out_fail_appctx;
3086 }
3087
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003088 /* Initialise cross reference between stream and Lua socket object. */
Willy Tarreau5321da92022-05-06 11:57:34 +02003089 xref_create(&socket->xref, &ctx->xref);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003090 return 1;
3091
Christopher Faulet13a35e52021-12-20 15:34:16 +01003092 out_fail_appctx:
Christopher Faulet5f35a3e2022-05-12 15:31:05 +02003093 appctx_free_on_early_error(appctx);
Willy Tarreaud420a972015-04-06 00:39:18 +02003094 out_fail_conf:
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003095 WILL_LJMP(lua_error(L));
3096 return 0;
3097}
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01003098
3099/*
3100 *
3101 *
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003102 * Class Channel
3103 *
3104 *
3105 */
3106
3107/* Returns the struct hlua_channel join to the class channel in the
3108 * stack entry "ud" or throws an argument error.
3109 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01003110__LJMP static struct channel *hlua_checkchannel(lua_State *L, int ud)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003111{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003112 return MAY_LJMP(hlua_checkudata(L, ud, class_channel_ref));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003113}
3114
Willy Tarreau47860ed2015-03-10 14:07:50 +01003115/* Pushes the channel onto the top of the stack. If the stask does not have a
3116 * free slots, the function fails and returns 0;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003117 */
Willy Tarreau2a71af42015-03-10 13:51:50 +01003118static int hlua_channel_new(lua_State *L, struct channel *channel)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003119{
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003120 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003121 if (!lua_checkstack(L, 3))
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003122 return 0;
3123
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003124 lua_newtable(L);
Willy Tarreau47860ed2015-03-10 14:07:50 +01003125 lua_pushlightuserdata(L, channel);
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003126 lua_rawseti(L, -2, 0);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003127
3128 /* Pop a class sesison metatable and affect it to the userdata. */
3129 lua_rawgeti(L, LUA_REGISTRYINDEX, class_channel_ref);
3130 lua_setmetatable(L, -2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003131 return 1;
3132}
3133
Christopher Faulet9f55a502020-02-25 15:21:02 +01003134/* Helper function returning a filter attached to a channel at the position <ud>
3135 * in the stack, filling the current offset and length of the filter. If no
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05003136 * filter is attached, NULL is returned and <offset> and <len> are not
Christopher Faulet9f55a502020-02-25 15:21:02 +01003137 * initialized.
3138 */
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003139static 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 +01003140{
3141 struct filter *filter = NULL;
3142
3143 if (lua_getfield(L, ud, "__filter") == LUA_TLIGHTUSERDATA) {
3144 struct hlua_flt_ctx *flt_ctx;
3145
3146 filter = lua_touserdata (L, -1);
3147 flt_ctx = filter->ctx;
3148 if (hlua_filter_from_payload(filter)) {
3149 *offset = flt_ctx->cur_off[CHN_IDX(chn)];
3150 *len = flt_ctx->cur_len[CHN_IDX(chn)];
3151 }
3152 }
3153
3154 lua_pop(L, 1);
3155 return filter;
3156}
3157
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003158/* Copies <len> bytes of data present in the channel's buffer, starting at the
3159* offset <offset>, and put it in a LUA string variable. It is the caller
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003160* responsibility to ensure <len> and <offset> are valid. It always return the
3161* length of the built string. <len> may be 0, in this case, an empty string is
3162* created and 0 is returned.
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003163*/
3164static inline int _hlua_channel_dup(struct channel *chn, lua_State *L, size_t offset, size_t len)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003165{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003166 size_t block1, block2;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003167 luaL_Buffer b;
3168
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003169 block1 = len;
3170 if (block1 > b_contig_data(&chn->buf, b_peek_ofs(&chn->buf, offset)))
3171 block1 = b_contig_data(&chn->buf, b_peek_ofs(&chn->buf, offset));
3172 block2 = len - block1;
3173
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003174 luaL_buffinit(L, &b);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003175 luaL_addlstring(&b, b_peek(&chn->buf, offset), block1);
3176 if (block2)
3177 luaL_addlstring(&b, b_orig(&chn->buf), block2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003178 luaL_pushresult(&b);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003179 return len;
3180}
3181
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003182/* Inserts the string <str> to the channel's buffer at the offset <offset>. This
3183 * function returns -1 if data cannot be copied. Otherwise, it returns the
3184 * number of bytes copied.
3185 */
3186static int _hlua_channel_insert(struct channel *chn, lua_State *L, struct ist str, size_t offset)
3187{
3188 int ret = 0;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003189
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003190 /* Nothing to do, just return */
3191 if (unlikely(istlen(str) == 0))
3192 goto end;
3193
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003194 if (istlen(str) > c_room(chn)) {
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003195 ret = -1;
3196 goto end;
3197 }
3198 ret = b_insert_blk(&chn->buf, offset, istptr(str), istlen(str));
3199
3200 end:
3201 return ret;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003202}
3203
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003204/* Removes <len> bytes of data at the absolute position <offset>.
3205 */
3206static void _hlua_channel_delete(struct channel *chn, size_t offset, size_t len)
3207{
3208 size_t end = offset + len;
3209
3210 if (b_peek(&chn->buf, end) != b_tail(&chn->buf))
3211 b_move(&chn->buf, b_peek_ofs(&chn->buf, end),
3212 b_data(&chn->buf) - end, -len);
3213 b_sub(&chn->buf, len);
3214}
3215
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003216/* Copies input data in the channel's buffer. It is possible to set a specific
3217 * offset (0 by default) and a length (all remaining input data starting for the
3218 * offset by default). If there is not enough input data and more data can be
3219 * received, this function yields.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003220 *
3221 * From an action, All input data are considered. For a filter, the offset and
3222 * the length of input data to consider are retrieved from the filter context.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003223 */
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003224__LJMP static int hlua_channel_get_data_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003225{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003226 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003227 struct filter *filter;
3228 size_t input, output;
3229 int offset, len;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003230
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003231 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003232
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003233 output = co_data(chn);
3234 input = ci_data(chn);
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003235
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003236 filter = hlua_channel_filter(L, 1, chn, &output, &input);
3237 if (filter && !hlua_filter_from_payload(filter))
3238 WILL_LJMP(lua_error(L));
3239
3240 offset = output;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003241 if (lua_gettop(L) > 1) {
3242 offset = MAY_LJMP(luaL_checkinteger(L, 2));
3243 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02003244 offset = MAX(0, (int)input + offset);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003245 offset += output;
3246 if (offset < output || offset > input + output) {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003247 lua_pushfstring(L, "offset out of range.");
3248 WILL_LJMP(lua_error(L));
3249 }
3250 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003251 len = output + input - offset;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003252 if (lua_gettop(L) == 3) {
3253 len = MAY_LJMP(luaL_checkinteger(L, 3));
3254 if (!len)
3255 goto dup;
3256 if (len == -1)
3257 len = global.tune.bufsize;
3258 if (len < 0) {
3259 lua_pushfstring(L, "length out of range.");
3260 WILL_LJMP(lua_error(L));
3261 }
3262 }
3263
Christopher Faulet0ae2e632023-01-10 15:29:54 +01003264 /* Wait for more data if possible if no length was specified and there
3265 * is no data or not enough data was received.
3266 */
3267 if (!len || offset + len > output + input) {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003268 if (!HLUA_CANT_YIELD(hlua_gethlua(L)) && !channel_input_closed(chn) && channel_may_recv(chn)) {
3269 /* Yield waiting for more data, as requested */
3270 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_get_data_yield, TICK_ETERNITY, 0));
3271 }
Christopher Faulet0ae2e632023-01-10 15:29:54 +01003272
3273 /* Return 'nil' if there is no data and the channel can't receive more data */
3274 if (!len) {
3275 lua_pushnil(L);
3276 return -1;
3277 }
3278
3279 /* Otherwise, return all data */
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003280 len = output + input - offset;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003281 }
3282
3283 dup:
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003284 _hlua_channel_dup(chn, L, offset, len);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003285 return 1;
3286}
3287
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003288/* Copies the first line (including the trailing LF) of input data in the
3289 * channel's buffer. It is possible to set a specific offset (0 by default) and
3290 * a length (all remaining input data starting for the offset by default). If
3291 * there is not enough input data and more data can be received, the function
3292 * yields. If a length is explicitly specified, no more data are
3293 * copied. Otherwise, if no LF is found and more data can be received, this
3294 * function yields.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003295 *
3296 * From an action, All input data are considered. For a filter, the offset and
3297 * the length of input data to consider are retrieved from the filter context.
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003298 */
3299__LJMP static int hlua_channel_get_line_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003300{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003301 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003302 struct filter *filter;
3303 size_t l, input, output;
3304 int offset, len;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003305
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003306 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003307 output = co_data(chn);
3308 input = ci_data(chn);
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003309
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003310 filter = hlua_channel_filter(L, 1, chn, &output, &input);
3311 if (filter && !hlua_filter_from_payload(filter))
3312 WILL_LJMP(lua_error(L));
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003313
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003314 offset = output;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003315 if (lua_gettop(L) > 1) {
3316 offset = MAY_LJMP(luaL_checkinteger(L, 2));
3317 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02003318 offset = MAX(0, (int)input + offset);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003319 offset += output;
3320 if (offset < output || offset > input + output) {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003321 lua_pushfstring(L, "offset out of range.");
3322 WILL_LJMP(lua_error(L));
3323 }
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003324 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003325
3326 len = output + input - offset;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003327 if (lua_gettop(L) == 3) {
3328 len = MAY_LJMP(luaL_checkinteger(L, 3));
3329 if (!len)
3330 goto dup;
3331 if (len == -1)
3332 len = global.tune.bufsize;
3333 if (len < 0) {
3334 lua_pushfstring(L, "length out of range.");
3335 WILL_LJMP(lua_error(L));
3336 }
3337 }
3338
3339 for (l = 0; l < len; l++) {
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003340 if (l + offset >= output + input)
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003341 break;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003342 if (*(b_peek(&chn->buf, offset + l)) == '\n') {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003343 len = l+1;
3344 goto dup;
3345 }
3346 }
3347
Christopher Faulet0ae2e632023-01-10 15:29:54 +01003348 /* Wait for more data if possible if no line is found and no length was
3349 * specified or not enough data was received.
3350 */
3351 if (lua_gettop(L) != 3 || offset + len > output + input) {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003352 if (!HLUA_CANT_YIELD(hlua_gethlua(L)) && !channel_input_closed(chn) && channel_may_recv(chn)) {
3353 /* Yield waiting for more data */
3354 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_get_line_yield, TICK_ETERNITY, 0));
3355 }
Christopher Faulet0ae2e632023-01-10 15:29:54 +01003356
3357 /* Return 'nil' if there is no data and the channel can't receive more data */
3358 if (!len) {
3359 lua_pushnil(L);
3360 return -1;
3361 }
3362
3363 /* Otherwise, return all data */
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003364 len = output + input - offset;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003365 }
3366
3367 dup:
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003368 _hlua_channel_dup(chn, L, offset, len);
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003369 return 1;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003370}
3371
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003372/* [ DEPRECATED ]
3373 *
3374 * Duplicate all input data foud in the channel's buffer. The data are not
3375 * removed from the buffer. This function relies on _hlua_channel_dup().
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003376 *
3377 * From an action, All input data are considered. For a filter, the offset and
3378 * the length of input data to consider are retrieved from the filter context.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003379 */
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003380__LJMP static int hlua_channel_dup(lua_State *L)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003381{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003382 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003383 struct filter *filter;
3384 size_t offset, len;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003385
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003386 MAY_LJMP(check_args(L, 1, "dup"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003387 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003388 if (IS_HTX_STRM(chn_strm(chn))) {
3389 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3390 WILL_LJMP(lua_error(L));
3391 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003392
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003393 offset = co_data(chn);
3394 len = ci_data(chn);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003395
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003396 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3397 if (filter && !hlua_filter_from_payload(filter))
3398 WILL_LJMP(lua_error(L));
3399
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003400 if (!ci_data(chn) && channel_input_closed(chn)) {
3401 lua_pushnil(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003402 return 1;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003403 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003404
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003405 _hlua_channel_dup(chn, L, offset, len);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003406 return 1;
3407}
3408
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003409/* [ DEPRECATED ]
3410 *
3411 * Get all input data foud in the channel's buffer. The data are removed from
3412 * the buffer after the copy. This function relies on _hlua_channel_dup() and
3413 * _hlua_channel_delete().
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003414 *
3415 * From an action, All input data are considered. For a filter, the offset and
3416 * the length of input data to consider are retrieved from the filter context.
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003417 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003418__LJMP static int hlua_channel_get(lua_State *L)
3419{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003420 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003421 struct filter *filter;
3422 size_t offset, len;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003423 int ret;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003424
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003425 MAY_LJMP(check_args(L, 1, "get"));
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003426 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3427 if (IS_HTX_STRM(chn_strm(chn))) {
3428 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3429 WILL_LJMP(lua_error(L));
3430 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003431
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003432 offset = co_data(chn);
3433 len = ci_data(chn);
3434
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003435 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3436 if (filter && !hlua_filter_from_payload(filter))
3437 WILL_LJMP(lua_error(L));
3438
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003439 if (!ci_data(chn) && channel_input_closed(chn)) {
3440 lua_pushnil(L);
3441 return 1;
3442 }
3443
3444 ret = _hlua_channel_dup(chn, L, offset, len);
3445 _hlua_channel_delete(chn, offset, ret);
3446 return 1;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003447}
3448
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003449/* This functions consumes and returns one line. If the channel is closed,
3450 * and the last data does not contains a final '\n', the data are returned
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003451 * without the final '\n'. When no more data are available, it returns nil
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003452 * value.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003453 *
3454 * From an action, All input data are considered. For a filter, the offset and
3455 * the length of input data to consider are retrieved from the filter context.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003456 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003457__LJMP static int hlua_channel_getline_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003458{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003459 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003460 struct filter *filter;
3461 size_t l, offset, len;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003462 int ret;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003463
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003464 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003465
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003466 offset = co_data(chn);
3467 len = ci_data(chn);
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003468
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003469 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3470 if (filter && !hlua_filter_from_payload(filter))
3471 WILL_LJMP(lua_error(L));
3472
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003473 if (!ci_data(chn) && channel_input_closed(chn)) {
3474 lua_pushnil(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003475 return 1;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003476 }
3477
3478 for (l = 0; l < len; l++) {
3479 if (*(b_peek(&chn->buf, offset+l)) == '\n') {
3480 len = l+1;
3481 goto dup;
3482 }
3483 }
3484
3485 if (!HLUA_CANT_YIELD(hlua_gethlua(L)) && !channel_input_closed(chn) && channel_may_recv(chn)) {
3486 /* Yield waiting for more data */
3487 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_getline_yield, TICK_ETERNITY, 0));
3488 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003489
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003490 dup:
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003491 ret = _hlua_channel_dup(chn, L, offset, len);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003492 _hlua_channel_delete(chn, offset, ret);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003493 return 1;
3494}
3495
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003496/* [ DEPRECATED ]
3497 *
3498 * Check arguments for the function "hlua_channel_getline_yield".
3499 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003500__LJMP static int hlua_channel_getline(lua_State *L)
3501{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003502 struct channel *chn;
3503
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003504 MAY_LJMP(check_args(L, 1, "getline"));
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003505 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3506 if (IS_HTX_STRM(chn_strm(chn))) {
3507 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3508 WILL_LJMP(lua_error(L));
3509 }
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003510 return MAY_LJMP(hlua_channel_getline_yield(L, 0, 0));
3511}
3512
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003513/* Retrieves a given amount of input data at the given offset. By default all
3514 * available input data are returned. The offset may be negactive to start from
3515 * the end of input data. The length may be -1 to set it to the maximum buffer
3516 * size.
3517 */
3518__LJMP static int hlua_channel_get_data(lua_State *L)
3519{
3520 struct channel *chn;
3521
3522 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
3523 WILL_LJMP(luaL_error(L, "'data' expects at most 2 arguments"));
3524 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3525 if (IS_HTX_STRM(chn_strm(chn))) {
3526 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3527 WILL_LJMP(lua_error(L));
3528 }
3529 return MAY_LJMP(hlua_channel_get_data_yield(L, 0, 0));
3530}
3531
3532/* Retrieves a given amount of input data at the given offset. By default all
3533 * available input data are returned. The offset may be negactive to start from
3534 * the end of input data. The length may be -1 to set it to the maximum buffer
3535 * size.
3536 */
3537__LJMP static int hlua_channel_get_line(lua_State *L)
3538{
3539 struct channel *chn;
3540
3541 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
3542 WILL_LJMP(luaL_error(L, "'line' expects at most 2 arguments"));
3543 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3544 if (IS_HTX_STRM(chn_strm(chn))) {
3545 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3546 WILL_LJMP(lua_error(L));
3547 }
3548 return MAY_LJMP(hlua_channel_get_line_yield(L, 0, 0));
3549}
3550
3551/* Appends 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 Faulet23976d92021-08-06 09:59:49 +02003558__LJMP static int hlua_channel_append(lua_State *L)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003559{
Christopher Faulet23976d92021-08-06 09:59:49 +02003560 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;
Christopher Faulet23976d92021-08-06 09:59:49 +02003565
3566 MAY_LJMP(check_args(L, 2, "append"));
3567 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003568 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
Christopher Faulet1bb6afa2021-03-08 17:57:53 +01003569 if (IS_HTX_STRM(chn_strm(chn))) {
Thierry Fournier77016da2020-08-15 14:35:51 +02003570 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
Christopher Faulet3f829a42018-12-13 21:56:45 +01003571 WILL_LJMP(lua_error(L));
Thierry Fournier77016da2020-08-15 14:35:51 +02003572 }
Christopher Faulet3f829a42018-12-13 21:56:45 +01003573
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 }
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003588 lua_pushinteger(L, ret);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003589 return 1;
3590}
3591
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003592/* Prepends a string into the input side of channel. It returns the length of the
3593 * written string, or -1 if the channel is closed or if the buffer size is too
3594 * little for the data. 0 may be returned if nothing is copied. This function
3595 * does not yield.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003596 *
3597 * For a filter, the context is updated on success.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003598 */
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003599__LJMP static int hlua_channel_prepend(lua_State *L)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003600{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003601 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003602 struct filter *filter;
Christopher Faulet23976d92021-08-06 09:59:49 +02003603 const char *str;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003604 size_t sz, offset, len;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003605 int ret;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003606
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003607 MAY_LJMP(check_args(L, 2, "prepend"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003608 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003609 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
3610 if (IS_HTX_STRM(chn_strm(chn))) {
3611 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3612 WILL_LJMP(lua_error(L));
3613 }
3614
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003615 offset = co_data(chn);
3616 len = ci_data(chn);
3617
3618 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3619 if (filter && !hlua_filter_from_payload(filter))
3620 WILL_LJMP(lua_error(L));
3621
3622 ret = _hlua_channel_insert(chn, L, ist2(str, sz), offset);
3623 if (ret > 0 && filter) {
3624 struct hlua_flt_ctx *flt_ctx = filter->ctx;
3625
3626 flt_update_offsets(filter, chn, ret);
3627 flt_ctx->cur_len[CHN_IDX(chn)] += ret;
3628 }
3629
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003630 lua_pushinteger(L, ret);
3631 return 1;
3632}
3633
3634/* Inserts a given amount of input data at the given offset by a string
Aurelien DARRAGONafb7daf2022-10-04 12:16:05 +02003635 * content. By default the string is appended in front of input data. It
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003636 * returns the length of the written string, or -1 if the channel is closed or
3637 * if the buffer size is too little for the data.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003638 *
3639 * For a filter, the context is updated on success.
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003640 */
3641__LJMP static int hlua_channel_insert_data(lua_State *L)
3642{
3643 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003644 struct filter *filter;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003645 const char *str;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003646 size_t sz, input, output;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003647 int ret, offset;
3648
3649 if (lua_gettop(L) < 2 || lua_gettop(L) > 3)
3650 WILL_LJMP(luaL_error(L, "'insert' expects at least 1 argument and at most 2 arguments"));
3651 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3652 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003653
3654 output = co_data(chn);
3655 input = ci_data(chn);
3656
3657 filter = hlua_channel_filter(L, 1, chn, &output, &input);
3658 if (filter && !hlua_filter_from_payload(filter))
3659 WILL_LJMP(lua_error(L));
3660
Aurelien DARRAGONafb7daf2022-10-04 12:16:05 +02003661 offset = output;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003662 if (lua_gettop(L) > 2) {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003663 offset = MAY_LJMP(luaL_checkinteger(L, 3));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003664 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02003665 offset = MAX(0, (int)input + offset);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003666 offset += output;
Aurelien DARRAGONafb7daf2022-10-04 12:16:05 +02003667 if (offset > output + input) {
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003668 lua_pushfstring(L, "offset out of range.");
3669 WILL_LJMP(lua_error(L));
3670 }
3671 }
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003672 if (IS_HTX_STRM(chn_strm(chn))) {
3673 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3674 WILL_LJMP(lua_error(L));
3675 }
3676
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003677 ret = _hlua_channel_insert(chn, L, ist2(str, sz), offset);
3678 if (ret > 0 && filter) {
3679 struct hlua_flt_ctx *flt_ctx = filter->ctx;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003680
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003681 flt_update_offsets(filter, chn, ret);
3682 flt_ctx->cur_len[CHN_IDX(chn)] += ret;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003683 }
3684
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003685 lua_pushinteger(L, ret);
3686 return 1;
3687}
3688/* Replaces a given amount of input data at the given offset by a string
3689 * content. By default all remaining data are removed (offset = 0 and len =
3690 * -1). It returns the length of the written string, or -1 if the channel is
3691 * closed or if the buffer size is too little for the data.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003692 *
3693 * For a filter, the context is updated on success.
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003694 */
3695__LJMP static int hlua_channel_set_data(lua_State *L)
3696{
3697 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003698 struct filter *filter;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003699 const char *str;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003700 size_t sz, input, output;
3701 int ret, offset, len;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003702
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003703 if (lua_gettop(L) < 2 || lua_gettop(L) > 4)
3704 WILL_LJMP(luaL_error(L, "'set' expects at least 1 argument and at most 3 arguments"));
3705 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3706 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003707
Christopher Faulet1bb6afa2021-03-08 17:57:53 +01003708 if (IS_HTX_STRM(chn_strm(chn))) {
Thierry Fournier77016da2020-08-15 14:35:51 +02003709 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
Christopher Faulet3f829a42018-12-13 21:56:45 +01003710 WILL_LJMP(lua_error(L));
Thierry Fournier77016da2020-08-15 14:35:51 +02003711 }
Christopher Faulet3f829a42018-12-13 21:56:45 +01003712
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003713 output = co_data(chn);
3714 input = ci_data(chn);
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003715
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003716 filter = hlua_channel_filter(L, 1, chn, &output, &input);
3717 if (filter && !hlua_filter_from_payload(filter))
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003718 WILL_LJMP(lua_error(L));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003719
3720 offset = output;
3721 if (lua_gettop(L) > 2) {
3722 offset = MAY_LJMP(luaL_checkinteger(L, 3));
3723 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02003724 offset = MAX(0, (int)input + offset);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003725 offset += output;
3726 if (offset < output || offset > input + output) {
3727 lua_pushfstring(L, "offset out of range.");
3728 WILL_LJMP(lua_error(L));
3729 }
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003730 }
3731
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003732 len = output + input - offset;
3733 if (lua_gettop(L) == 4) {
3734 len = MAY_LJMP(luaL_checkinteger(L, 4));
3735 if (!len)
3736 goto set;
3737 if (len == -1)
3738 len = output + input - offset;
3739 if (len < 0 || offset + len > output + input) {
3740 lua_pushfstring(L, "length out of range.");
3741 WILL_LJMP(lua_error(L));
3742 }
3743 }
3744
3745 set:
Christopher Faulet23976d92021-08-06 09:59:49 +02003746 /* Be sure we can copied the string once input data will be removed. */
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003747 if (sz > c_room(chn) + len)
Christopher Faulet23976d92021-08-06 09:59:49 +02003748 lua_pushinteger(L, -1);
3749 else {
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003750 _hlua_channel_delete(chn, offset, len);
3751 ret = _hlua_channel_insert(chn, L, ist2(str, sz), offset);
3752 if (filter) {
3753 struct hlua_flt_ctx *flt_ctx = filter->ctx;
3754
3755 len -= (ret > 0 ? ret : 0);
3756 flt_update_offsets(filter, chn, -len);
3757 flt_ctx->cur_len[CHN_IDX(chn)] -= len;
3758 }
3759
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003760 lua_pushinteger(L, ret);
Christopher Faulet23976d92021-08-06 09:59:49 +02003761 }
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003762 return 1;
3763}
3764
3765/* Removes a given amount of input data at the given offset. By default all
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003766 * input data are removed (offset = 0 and len = -1). It returns the amount of
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003767 * the removed data.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003768 *
3769 * For a filter, the context is updated on success.
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003770 */
3771__LJMP static int hlua_channel_del_data(lua_State *L)
3772{
3773 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003774 struct filter *filter;
3775 size_t input, output;
3776 int offset, len;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003777
3778 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
3779 WILL_LJMP(luaL_error(L, "'remove' expects at most 2 arguments"));
3780 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003781
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003782 if (IS_HTX_STRM(chn_strm(chn))) {
3783 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3784 WILL_LJMP(lua_error(L));
3785 }
3786
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003787 output = co_data(chn);
3788 input = ci_data(chn);
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003789
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003790 filter = hlua_channel_filter(L, 1, chn, &output, &input);
3791 if (filter && !hlua_filter_from_payload(filter))
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003792 WILL_LJMP(lua_error(L));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003793
3794 offset = output;
Boyang Lie0c54352022-05-10 17:47:23 +00003795 if (lua_gettop(L) > 1) {
3796 offset = MAY_LJMP(luaL_checkinteger(L, 2));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003797 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02003798 offset = MAX(0, (int)input + offset);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003799 offset += output;
3800 if (offset < output || offset > input + output) {
3801 lua_pushfstring(L, "offset out of range.");
3802 WILL_LJMP(lua_error(L));
3803 }
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003804 }
3805
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003806 len = output + input - offset;
Boyang Lie0c54352022-05-10 17:47:23 +00003807 if (lua_gettop(L) == 3) {
3808 len = MAY_LJMP(luaL_checkinteger(L, 3));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003809 if (!len)
3810 goto end;
3811 if (len == -1)
3812 len = output + input - offset;
3813 if (len < 0 || offset + len > output + input) {
3814 lua_pushfstring(L, "length out of range.");
3815 WILL_LJMP(lua_error(L));
3816 }
3817 }
3818
3819 _hlua_channel_delete(chn, offset, len);
3820 if (filter) {
3821 struct hlua_flt_ctx *flt_ctx = filter->ctx;
3822
3823 flt_update_offsets(filter, chn, -len);
3824 flt_ctx->cur_len[CHN_IDX(chn)] -= len;
3825 }
3826
3827 end:
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003828 lua_pushinteger(L, len);
Christopher Faulet23976d92021-08-06 09:59:49 +02003829 return 1;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003830}
3831
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003832/* Append data in the output side of the buffer. This data is immediately
3833 * sent. The function returns the amount of data written. If the buffer
3834 * cannot contain the data, the function yields. The function returns -1
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003835 * if the channel is closed.
3836 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003837__LJMP static int hlua_channel_send_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003838{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003839 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003840 struct filter *filter;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003841 const char *str;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003842 size_t offset, len, sz;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003843 int l, ret;
Thierry Fournier4234dbd2020-11-28 13:18:23 +01003844 struct hlua *hlua;
3845
3846 /* Get hlua struct, or NULL if we execute from main lua state */
3847 hlua = hlua_gethlua(L);
3848 if (!hlua) {
3849 lua_pushnil(L);
3850 return 1;
3851 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003852
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003853 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3854 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
3855 l = MAY_LJMP(luaL_checkinteger(L, 3));
Christopher Faulet3f829a42018-12-13 21:56:45 +01003856
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003857 offset = co_data(chn);
3858 len = ci_data(chn);
3859
3860 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3861 if (filter && !hlua_filter_from_payload(filter))
3862 WILL_LJMP(lua_error(L));
3863
3864
Willy Tarreau47860ed2015-03-10 14:07:50 +01003865 if (unlikely(channel_output_closed(chn))) {
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003866 lua_pushinteger(L, -1);
3867 return 1;
3868 }
3869
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003870 len = c_room(chn);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003871 if (len > sz -l) {
3872 if (filter) {
3873 lua_pushinteger(L, -1);
3874 return 1;
3875 }
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003876 len = sz - l;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003877 }
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01003878
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003879 ret = _hlua_channel_insert(chn, L, ist2(str, len), offset);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003880 if (ret == -1) {
3881 lua_pop(L, 1);
3882 lua_pushinteger(L, -1);
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01003883 return 1;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003884 }
3885 if (ret) {
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003886 if (filter) {
3887 struct hlua_flt_ctx *flt_ctx = filter->ctx;
3888
3889
3890 flt_update_offsets(filter, chn, ret);
3891 FLT_OFF(filter, chn) += ret;
3892 flt_ctx->cur_off[CHN_IDX(chn)] += ret;
3893 }
3894 else
3895 c_adv(chn, ret);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003896
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003897 l += ret;
3898 lua_pop(L, 1);
3899 lua_pushinteger(L, l);
3900 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003901
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003902 if (l < sz) {
3903 /* Yield only if the channel's output is not empty.
3904 * Otherwise it means we cannot add more data. */
3905 if (co_data(chn) == 0 || HLUA_CANT_YIELD(hlua_gethlua(L)))
Christopher Faulet2e60aa42021-08-05 11:58:37 +02003906 return 1;
3907
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003908 /* If we are waiting for space in the response buffer, we
3909 * must set the flag WAKERESWR. This flag required the task
3910 * wake up if any activity is detected on the response buffer.
3911 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01003912 if (chn->flags & CF_ISRESP)
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003913 HLUA_SET_WAKERESWR(hlua);
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01003914 else
3915 HLUA_SET_WAKEREQWR(hlua);
Willy Tarreau9635e032018-10-16 17:52:55 +02003916 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003917 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003918
3919 return 1;
3920}
3921
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05003922/* Just a wrapper of "_hlua_channel_send". This wrapper permits
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003923 * yield the LUA process, and resume it without checking the
3924 * input arguments.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003925 *
3926 * This function cannot be called from a filter.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003927 */
3928__LJMP static int hlua_channel_send(lua_State *L)
3929{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003930 struct channel *chn;
3931
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003932 MAY_LJMP(check_args(L, 2, "send"));
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003933 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3934 if (IS_HTX_STRM(chn_strm(chn))) {
3935 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3936 WILL_LJMP(lua_error(L));
3937 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003938 lua_pushinteger(L, 0);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003939 return MAY_LJMP(hlua_channel_send_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003940}
3941
3942/* This function forward and amount of butes. The data pass from
3943 * the input side of the buffer to the output side, and can be
3944 * forwarded. This function never fails.
3945 *
3946 * The Lua function takes an amount of bytes to be forwarded in
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05003947 * input. It returns the number of bytes forwarded.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003948 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003949__LJMP static int hlua_channel_forward_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003950{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003951 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003952 struct filter *filter;
3953 size_t offset, len, fwd;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003954 int l, max;
Thierry Fournier4234dbd2020-11-28 13:18:23 +01003955 struct hlua *hlua;
3956
3957 /* Get hlua struct, or NULL if we execute from main lua state */
3958 hlua = hlua_gethlua(L);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003959 if (!hlua) {
3960 lua_pushnil(L);
Thierry Fournier4234dbd2020-11-28 13:18:23 +01003961 return 1;
Thierry Fournier77016da2020-08-15 14:35:51 +02003962 }
Christopher Faulet3f829a42018-12-13 21:56:45 +01003963
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003964 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003965 fwd = MAY_LJMP(luaL_checkinteger(L, 2));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003966 l = MAY_LJMP(luaL_checkinteger(L, -1));
3967
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003968 offset = co_data(chn);
3969 len = ci_data(chn);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003970
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003971 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3972 if (filter && !hlua_filter_from_payload(filter))
3973 WILL_LJMP(lua_error(L));
3974
3975 max = fwd - l;
3976 if (max > len)
3977 max = len;
3978
3979 if (filter) {
3980 struct hlua_flt_ctx *flt_ctx = filter->ctx;
3981
3982 FLT_OFF(filter, chn) += max;
3983 flt_ctx->cur_off[CHN_IDX(chn)] += max;
3984 flt_ctx->cur_len[CHN_IDX(chn)] -= max;
3985 }
3986 else
3987 channel_forward(chn, max);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003988
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003989 l += max;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003990 lua_pop(L, 1);
3991 lua_pushinteger(L, l);
3992
3993 /* Check if it miss bytes to forward. */
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003994 if (l < fwd) {
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003995 /* The the input channel or the output channel are closed, we
3996 * must return the amount of data forwarded.
3997 */
Christopher Faulet2e60aa42021-08-05 11:58:37 +02003998 if (channel_input_closed(chn) || channel_output_closed(chn) || HLUA_CANT_YIELD(hlua_gethlua(L)))
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003999 return 1;
4000
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01004001 /* If we are waiting for space data in the response buffer, we
4002 * must set the flag WAKERESWR. This flag required the task
4003 * wake up if any activity is detected on the response buffer.
4004 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01004005 if (chn->flags & CF_ISRESP)
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01004006 HLUA_SET_WAKERESWR(hlua);
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01004007 else
4008 HLUA_SET_WAKEREQWR(hlua);
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01004009
Ilya Shipitsin4a689da2022-10-29 09:34:32 +05004010 /* Otherwise, we can yield waiting for new data in the input side. */
Willy Tarreau9635e032018-10-16 17:52:55 +02004011 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_forward_yield, TICK_ETERNITY, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004012 }
4013
4014 return 1;
4015}
4016
4017/* Just check the input and prepare the stack for the previous
4018 * function "hlua_channel_forward_yield"
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004019 *
4020 * This function cannot be called from a filter.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004021 */
4022__LJMP static int hlua_channel_forward(lua_State *L)
4023{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02004024 struct channel *chn;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004025
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02004026 MAY_LJMP(check_args(L, 2, "forward"));
4027 chn = MAY_LJMP(hlua_checkchannel(L, 1));
4028 if (IS_HTX_STRM(chn_strm(chn))) {
4029 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
4030 WILL_LJMP(lua_error(L));
4031 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004032 lua_pushinteger(L, 0);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01004033 return MAY_LJMP(hlua_channel_forward_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004034}
4035
4036/* Just returns the number of bytes available in the input
4037 * side of the buffer. This function never fails.
4038 */
4039__LJMP static int hlua_channel_get_in_len(lua_State *L)
4040{
Willy Tarreau47860ed2015-03-10 14:07:50 +01004041 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004042 struct filter *filter;
4043 size_t output, input;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004044
Christopher Faulet6a79fc12021-08-06 16:02:36 +02004045 MAY_LJMP(check_args(L, 1, "input"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004046 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004047
4048 output = co_data(chn);
4049 input = ci_data(chn);
4050 filter = hlua_channel_filter(L, 1, chn, &output, &input);
4051 if (filter || !IS_HTX_STRM(chn_strm(chn)))
4052 lua_pushinteger(L, input);
4053 else {
Christopher Fauleta3ceac12018-12-14 13:39:09 +01004054 struct htx *htx = htxbuf(&chn->buf);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004055
Christopher Fauleta3ceac12018-12-14 13:39:09 +01004056 lua_pushinteger(L, htx->data - co_data(chn));
4057 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004058 return 1;
4059}
4060
Thierry FOURNIER / OZON.IO65192f32016-11-07 15:28:40 +01004061/* Returns true if the channel is full. */
4062__LJMP static int hlua_channel_is_full(lua_State *L)
4063{
4064 struct channel *chn;
Thierry FOURNIER / OZON.IO65192f32016-11-07 15:28:40 +01004065
4066 MAY_LJMP(check_args(L, 1, "is_full"));
4067 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Faulet0ec740e2020-02-26 11:59:19 +01004068 /* ignore the reserve, we are not on a producer side (ie in an
4069 * applet).
4070 */
4071 lua_pushboolean(L, channel_full(chn, 0));
Thierry FOURNIER / OZON.IO65192f32016-11-07 15:28:40 +01004072 return 1;
4073}
4074
Christopher Faulet6a79fc12021-08-06 16:02:36 +02004075/* Returns true if the channel may still receive data. */
4076__LJMP static int hlua_channel_may_recv(lua_State *L)
4077{
4078 struct channel *chn;
4079
4080 MAY_LJMP(check_args(L, 1, "may_recv"));
4081 chn = MAY_LJMP(hlua_checkchannel(L, 1));
4082 lua_pushboolean(L, (!channel_input_closed(chn) && channel_may_recv(chn)));
4083 return 1;
4084}
4085
Christopher Faulet2ac9ba22020-02-25 10:15:50 +01004086/* Returns true if the channel is the response channel. */
4087__LJMP static int hlua_channel_is_resp(lua_State *L)
4088{
4089 struct channel *chn;
4090
4091 MAY_LJMP(check_args(L, 1, "is_resp"));
4092 chn = MAY_LJMP(hlua_checkchannel(L, 1));
4093
4094 lua_pushboolean(L, !!(chn->flags & CF_ISRESP));
4095 return 1;
4096}
4097
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004098/* Just returns the number of bytes available in the output
4099 * side of the buffer. This function never fails.
4100 */
4101__LJMP static int hlua_channel_get_out_len(lua_State *L)
4102{
Willy Tarreau47860ed2015-03-10 14:07:50 +01004103 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004104 size_t output, input;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004105
Christopher Faulet6a79fc12021-08-06 16:02:36 +02004106 MAY_LJMP(check_args(L, 1, "output"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004107 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004108
4109 output = co_data(chn);
4110 input = ci_data(chn);
4111 hlua_channel_filter(L, 1, chn, &output, &input);
4112
4113 lua_pushinteger(L, output);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004114 return 1;
4115}
4116
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004117/*
4118 *
4119 *
4120 * Class Fetches
4121 *
4122 *
4123 */
4124
4125/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02004126 * a class stream, otherwise it throws an error.
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004127 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004128__LJMP static struct hlua_smp *hlua_checkfetches(lua_State *L, int ud)
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004129{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004130 return MAY_LJMP(hlua_checkudata(L, ud, class_fetches_ref));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004131}
4132
4133/* This function creates and push in the stack a fetch object according
4134 * with a current TXN.
4135 */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004136static int hlua_fetches_new(lua_State *L, struct hlua_txn *txn, unsigned int flags)
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004137{
Willy Tarreau7073c472015-04-06 11:15:40 +02004138 struct hlua_smp *hsmp;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004139
4140 /* Check stack size. */
4141 if (!lua_checkstack(L, 3))
4142 return 0;
4143
4144 /* Create the object: obj[0] = userdata.
4145 * Note that the base of the Fetches object is the
4146 * transaction object.
4147 */
4148 lua_newtable(L);
Willy Tarreau7073c472015-04-06 11:15:40 +02004149 hsmp = lua_newuserdata(L, sizeof(*hsmp));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004150 lua_rawseti(L, -2, 0);
4151
Willy Tarreau7073c472015-04-06 11:15:40 +02004152 hsmp->s = txn->s;
4153 hsmp->p = txn->p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01004154 hsmp->dir = txn->dir;
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004155 hsmp->flags = flags;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004156
4157 /* Pop a class sesison metatable and affect it to the userdata. */
4158 lua_rawgeti(L, LUA_REGISTRYINDEX, class_fetches_ref);
4159 lua_setmetatable(L, -2);
4160
4161 return 1;
4162}
4163
4164/* This function is an LUA binding. It is called with each sample-fetch.
4165 * It uses closure argument to store the associated sample-fetch. It
4166 * returns only one argument or throws an error. An error is thrown
4167 * only if an error is encountered during the argument parsing. If
4168 * the "sample-fetch" function fails, nil is returned.
4169 */
4170__LJMP static int hlua_run_sample_fetch(lua_State *L)
4171{
Willy Tarreaub2ccb562015-04-06 11:11:15 +02004172 struct hlua_smp *hsmp;
Willy Tarreau2ec22742015-03-10 14:27:20 +01004173 struct sample_fetch *f;
Frédéric Lécaillef874a832018-06-15 13:56:04 +02004174 struct arg args[ARGM_NBARGS + 1] = {{0}};
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004175 int i;
4176 struct sample smp;
4177
4178 /* Get closure arguments. */
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004179 f = lua_touserdata(L, lua_upvalueindex(1));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004180
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004181 /* Get traditional arguments. */
Willy Tarreaub2ccb562015-04-06 11:11:15 +02004182 hsmp = MAY_LJMP(hlua_checkfetches(L, 1));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004183
Thierry FOURNIERca988662015-12-20 18:43:03 +01004184 /* Check execution authorization. */
4185 if (f->use & SMP_USE_HTTP_ANY &&
4186 !(hsmp->flags & HLUA_F_MAY_USE_HTTP)) {
4187 lua_pushfstring(L, "the sample-fetch '%s' needs an HTTP parser which "
4188 "is not available in Lua services", f->kw);
4189 WILL_LJMP(lua_error(L));
4190 }
4191
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004192 /* Get extra arguments. */
4193 for (i = 0; i < lua_gettop(L) - 1; i++) {
4194 if (i >= ARGM_NBARGS)
4195 break;
4196 hlua_lua2arg(L, i + 2, &args[i]);
4197 }
4198 args[i].type = ARGT_STOP;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004199 args[i].data.str.area = NULL;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004200
4201 /* Check arguments. */
Willy Tarreaub2ccb562015-04-06 11:11:15 +02004202 MAY_LJMP(hlua_lua2arg_check(L, 2, args, f->arg_mask, hsmp->p));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004203
4204 /* Run the special args checker. */
Willy Tarreau2ec22742015-03-10 14:27:20 +01004205 if (f->val_args && !f->val_args(args, NULL)) {
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004206 lua_pushfstring(L, "error in arguments");
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004207 goto error;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004208 }
4209
4210 /* Initialise the sample. */
4211 memset(&smp, 0, sizeof(smp));
4212
4213 /* Run the sample fetch process. */
Willy Tarreau1777ea62016-03-10 16:15:46 +01004214 smp_set_owner(&smp, hsmp->p, hsmp->s->sess, hsmp->s, hsmp->dir & SMP_OPT_DIR);
Thierry FOURNIER0786d052015-05-11 15:42:45 +02004215 if (!f->process(args, &smp, f->kw, f->private)) {
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004216 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004217 lua_pushstring(L, "");
4218 else
4219 lua_pushnil(L);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004220 goto end;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004221 }
4222
4223 /* Convert the returned sample in lua value. */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004224 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004225 hlua_smp2lua_str(L, &smp);
4226 else
4227 hlua_smp2lua(L, &smp);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004228
4229 end:
Willy Tarreauee0d7272021-07-16 10:26:56 +02004230 free_args(args);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004231 return 1;
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004232
4233 error:
Willy Tarreauee0d7272021-07-16 10:26:56 +02004234 free_args(args);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004235 WILL_LJMP(lua_error(L));
4236 return 0; /* Never reached */
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004237}
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004238
4239/*
4240 *
4241 *
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004242 * Class Converters
4243 *
4244 *
4245 */
4246
4247/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02004248 * a class stream, otherwise it throws an error.
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004249 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004250__LJMP static struct hlua_smp *hlua_checkconverters(lua_State *L, int ud)
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004251{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004252 return MAY_LJMP(hlua_checkudata(L, ud, class_converters_ref));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004253}
4254
4255/* This function creates and push in the stack a Converters object
4256 * according with a current TXN.
4257 */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004258static int hlua_converters_new(lua_State *L, struct hlua_txn *txn, unsigned int flags)
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004259{
Willy Tarreau7073c472015-04-06 11:15:40 +02004260 struct hlua_smp *hsmp;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004261
4262 /* Check stack size. */
4263 if (!lua_checkstack(L, 3))
4264 return 0;
4265
4266 /* Create the object: obj[0] = userdata.
4267 * Note that the base of the Converters object is the
4268 * same than the TXN object.
4269 */
4270 lua_newtable(L);
Willy Tarreau7073c472015-04-06 11:15:40 +02004271 hsmp = lua_newuserdata(L, sizeof(*hsmp));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004272 lua_rawseti(L, -2, 0);
4273
Willy Tarreau7073c472015-04-06 11:15:40 +02004274 hsmp->s = txn->s;
4275 hsmp->p = txn->p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01004276 hsmp->dir = txn->dir;
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004277 hsmp->flags = flags;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004278
Willy Tarreau87b09662015-04-03 00:22:06 +02004279 /* Pop a class stream metatable and affect it to the table. */
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004280 lua_rawgeti(L, LUA_REGISTRYINDEX, class_converters_ref);
4281 lua_setmetatable(L, -2);
4282
4283 return 1;
4284}
4285
4286/* This function is an LUA binding. It is called with each converter.
4287 * It uses closure argument to store the associated converter. It
4288 * returns only one argument or throws an error. An error is thrown
4289 * only if an error is encountered during the argument parsing. If
4290 * the converter function function fails, nil is returned.
4291 */
4292__LJMP static int hlua_run_sample_conv(lua_State *L)
4293{
Willy Tarreauda5f1082015-04-06 11:17:13 +02004294 struct hlua_smp *hsmp;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004295 struct sample_conv *conv;
Frédéric Lécaillef874a832018-06-15 13:56:04 +02004296 struct arg args[ARGM_NBARGS + 1] = {{0}};
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004297 int i;
4298 struct sample smp;
4299
4300 /* Get closure arguments. */
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004301 conv = lua_touserdata(L, lua_upvalueindex(1));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004302
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004303 /* Get traditional arguments. */
Willy Tarreauda5f1082015-04-06 11:17:13 +02004304 hsmp = MAY_LJMP(hlua_checkconverters(L, 1));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004305
4306 /* Get extra arguments. */
4307 for (i = 0; i < lua_gettop(L) - 2; i++) {
4308 if (i >= ARGM_NBARGS)
4309 break;
4310 hlua_lua2arg(L, i + 3, &args[i]);
4311 }
4312 args[i].type = ARGT_STOP;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004313 args[i].data.str.area = NULL;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004314
4315 /* Check arguments. */
Willy Tarreauda5f1082015-04-06 11:17:13 +02004316 MAY_LJMP(hlua_lua2arg_check(L, 3, args, conv->arg_mask, hsmp->p));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004317
4318 /* Run the special args checker. */
4319 if (conv->val_args && !conv->val_args(args, conv, "", 0, NULL)) {
4320 hlua_pusherror(L, "error in arguments");
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004321 goto error;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004322 }
4323
4324 /* Initialise the sample. */
Amaury Denoyellebc0af6a2020-10-29 17:21:20 +01004325 memset(&smp, 0, sizeof(smp));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004326 if (!hlua_lua2smp(L, 2, &smp)) {
4327 hlua_pusherror(L, "error in the input argument");
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004328 goto error;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004329 }
4330
Willy Tarreau1777ea62016-03-10 16:15:46 +01004331 smp_set_owner(&smp, hsmp->p, hsmp->s->sess, hsmp->s, hsmp->dir & SMP_OPT_DIR);
4332
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004333 /* Apply expected cast. */
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02004334 if (!sample_casts[smp.data.type][conv->in_type]) {
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004335 hlua_pusherror(L, "invalid input argument: cannot cast '%s' to '%s'",
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02004336 smp_to_type[smp.data.type], smp_to_type[conv->in_type]);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004337 goto error;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004338 }
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02004339 if (sample_casts[smp.data.type][conv->in_type] != c_none &&
4340 !sample_casts[smp.data.type][conv->in_type](&smp)) {
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004341 hlua_pusherror(L, "error during the input argument casting");
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004342 goto error;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004343 }
4344
4345 /* Run the sample conversion process. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02004346 if (!conv->process(args, &smp, conv->private)) {
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004347 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004348 lua_pushstring(L, "");
4349 else
Willy Tarreaua678b432015-08-28 10:14:59 +02004350 lua_pushnil(L);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004351 goto end;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004352 }
4353
4354 /* Convert the returned sample in lua value. */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004355 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004356 hlua_smp2lua_str(L, &smp);
4357 else
4358 hlua_smp2lua(L, &smp);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004359 end:
Willy Tarreauee0d7272021-07-16 10:26:56 +02004360 free_args(args);
Willy Tarreaua678b432015-08-28 10:14:59 +02004361 return 1;
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004362
4363 error:
Willy Tarreauee0d7272021-07-16 10:26:56 +02004364 free_args(args);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004365 WILL_LJMP(lua_error(L));
4366 return 0; /* Never reached */
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004367}
4368
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004369/*
4370 *
4371 *
4372 * Class AppletTCP
4373 *
4374 *
4375 */
4376
4377/* Returns a struct hlua_txn if the stack entry "ud" is
4378 * a class stream, otherwise it throws an error.
4379 */
4380__LJMP static struct hlua_appctx *hlua_checkapplet_tcp(lua_State *L, int ud)
4381{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004382 return MAY_LJMP(hlua_checkudata(L, ud, class_applet_tcp_ref));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004383}
4384
4385/* This function creates and push in the stack an Applet object
4386 * according with a current TXN.
4387 */
4388static int hlua_applet_tcp_new(lua_State *L, struct appctx *ctx)
4389{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004390 struct hlua_appctx *luactx;
Willy Tarreau0698c802022-05-11 14:09:57 +02004391 struct stream *s = appctx_strm(ctx);
Christopher Faulet2da02ae2022-02-24 13:45:27 +01004392 struct proxy *p;
4393
4394 ALREADY_CHECKED(s);
4395 p = s->be;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004396
4397 /* Check stack size. */
4398 if (!lua_checkstack(L, 3))
4399 return 0;
4400
4401 /* Create the object: obj[0] = userdata.
4402 * Note that the base of the Converters object is the
4403 * same than the TXN object.
4404 */
4405 lua_newtable(L);
Willy Tarreau7e702d12021-04-28 17:59:21 +02004406 luactx = lua_newuserdata(L, sizeof(*luactx));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004407 lua_rawseti(L, -2, 0);
Willy Tarreau7e702d12021-04-28 17:59:21 +02004408 luactx->appctx = ctx;
4409 luactx->htxn.s = s;
4410 luactx->htxn.p = p;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004411
4412 /* Create the "f" field that contains a list of fetches. */
4413 lua_pushstring(L, "f");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004414 if (!hlua_fetches_new(L, &luactx->htxn, 0))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004415 return 0;
4416 lua_settable(L, -3);
4417
4418 /* Create the "sf" field that contains a list of stringsafe fetches. */
4419 lua_pushstring(L, "sf");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004420 if (!hlua_fetches_new(L, &luactx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004421 return 0;
4422 lua_settable(L, -3);
4423
4424 /* Create the "c" field that contains a list of converters. */
4425 lua_pushstring(L, "c");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004426 if (!hlua_converters_new(L, &luactx->htxn, 0))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004427 return 0;
4428 lua_settable(L, -3);
4429
4430 /* Create the "sc" field that contains a list of stringsafe converters. */
4431 lua_pushstring(L, "sc");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004432 if (!hlua_converters_new(L, &luactx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004433 return 0;
4434 lua_settable(L, -3);
4435
4436 /* Pop a class stream metatable and affect it to the table. */
4437 lua_rawgeti(L, LUA_REGISTRYINDEX, class_applet_tcp_ref);
4438 lua_setmetatable(L, -2);
4439
4440 return 1;
4441}
4442
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004443__LJMP static int hlua_applet_tcp_set_var(lua_State *L)
4444{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004445 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004446 struct stream *s;
4447 const char *name;
4448 size_t len;
4449 struct sample smp;
4450
Tim Duesterhus4e172c92020-05-19 13:49:42 +02004451 if (lua_gettop(L) < 3 || lua_gettop(L) > 4)
4452 WILL_LJMP(luaL_error(L, "'set_var' needs between 3 and 4 arguments"));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004453
4454 /* It is useles to retrieve the stream, but this function
4455 * runs only in a stream context.
4456 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004457 luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004458 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02004459 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004460
4461 /* Converts the third argument in a sample. */
Amaury Denoyellebc0af6a2020-10-29 17:21:20 +01004462 memset(&smp, 0, sizeof(smp));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004463 hlua_lua2smp(L, 3, &smp);
4464
4465 /* Store the sample in a variable. */
4466 smp_set_owner(&smp, s->be, s->sess, s, 0);
Tim Duesterhus4e172c92020-05-19 13:49:42 +02004467
4468 if (lua_gettop(L) == 4 && lua_toboolean(L, 4))
4469 lua_pushboolean(L, vars_set_by_name_ifexist(name, len, &smp) != 0);
4470 else
4471 lua_pushboolean(L, vars_set_by_name(name, len, &smp) != 0);
4472
Tim Duesterhus84ebc132020-05-19 13:49:41 +02004473 return 1;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004474}
4475
4476__LJMP static int hlua_applet_tcp_unset_var(lua_State *L)
4477{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004478 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004479 struct stream *s;
4480 const char *name;
4481 size_t len;
4482 struct sample smp;
4483
4484 MAY_LJMP(check_args(L, 2, "unset_var"));
4485
4486 /* It is useles to retrieve the stream, but this function
4487 * runs only in a stream context.
4488 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004489 luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004490 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02004491 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004492
4493 /* Unset the variable. */
4494 smp_set_owner(&smp, s->be, s->sess, s, 0);
Tim Duesterhus84ebc132020-05-19 13:49:41 +02004495 lua_pushboolean(L, vars_unset_by_name_ifexist(name, len, &smp) != 0);
4496 return 1;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004497}
4498
4499__LJMP static int hlua_applet_tcp_get_var(lua_State *L)
4500{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004501 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004502 struct stream *s;
4503 const char *name;
4504 size_t len;
4505 struct sample smp;
4506
4507 MAY_LJMP(check_args(L, 2, "get_var"));
4508
4509 /* It is useles to retrieve the stream, but this function
4510 * runs only in a stream context.
4511 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004512 luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004513 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02004514 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004515
4516 smp_set_owner(&smp, s->be, s->sess, s, 0);
Willy Tarreaue352b9d2021-09-03 11:52:38 +02004517 if (!vars_get_by_name(name, len, &smp, NULL)) {
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004518 lua_pushnil(L);
4519 return 1;
4520 }
4521
4522 return hlua_smp2lua(L, &smp);
4523}
4524
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004525__LJMP static int hlua_applet_tcp_set_priv(lua_State *L)
4526{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004527 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
4528 struct stream *s = luactx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01004529 struct hlua *hlua;
4530
4531 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01004532 if (!s->hlua)
4533 return 0;
4534 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004535
4536 MAY_LJMP(check_args(L, 2, "set_priv"));
4537
4538 /* Remove previous value. */
Thierry FOURNIERe068b602017-04-26 13:27:05 +02004539 luaL_unref(L, LUA_REGISTRYINDEX, hlua->Mref);
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004540
4541 /* Get and store new value. */
4542 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
4543 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
4544
4545 return 0;
4546}
4547
4548__LJMP static int hlua_applet_tcp_get_priv(lua_State *L)
4549{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004550 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
4551 struct stream *s = luactx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01004552 struct hlua *hlua;
4553
4554 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01004555 if (!s->hlua) {
4556 lua_pushnil(L);
4557 return 1;
4558 }
4559 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004560
4561 /* Push configuration index in the stack. */
4562 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
4563
4564 return 1;
4565}
4566
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004567/* If expected data not yet available, it returns a yield. This function
4568 * consumes the data in the buffer. It returns a string containing the
4569 * data. This string can be empty.
4570 */
4571__LJMP static int hlua_applet_tcp_getline_yield(lua_State *L, int status, lua_KContext ctx)
4572{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004573 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Willy Tarreauc12b3212022-05-27 11:08:15 +02004574 struct stconn *sc = appctx_sc(luactx->appctx);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004575 int ret;
Willy Tarreau206ba832018-06-14 15:27:31 +02004576 const char *blk1;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004577 size_t len1;
Willy Tarreau206ba832018-06-14 15:27:31 +02004578 const char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004579 size_t len2;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004580
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004581 /* Read the maximum amount of data available. */
Willy Tarreau3e7be362022-05-27 10:35:27 +02004582 ret = co_getline_nc(sc_oc(sc), &blk1, &len1, &blk2, &len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004583
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004584 /* Data not yet available. return yield. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004585 if (ret == 0) {
Willy Tarreau90e8b452022-05-25 18:21:43 +02004586 applet_need_more_data(luactx->appctx);
Willy Tarreau9635e032018-10-16 17:52:55 +02004587 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_getline_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004588 }
4589
4590 /* End of data: commit the total strings and return. */
4591 if (ret < 0) {
Willy Tarreau7e702d12021-04-28 17:59:21 +02004592 luaL_pushresult(&luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004593 return 1;
4594 }
4595
4596 /* Ensure that the block 2 length is usable. */
4597 if (ret == 1)
4598 len2 = 0;
4599
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -07004600 /* don't check the max length read and don't check. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004601 luaL_addlstring(&luactx->b, blk1, len1);
4602 luaL_addlstring(&luactx->b, blk2, len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004603
4604 /* Consume input channel output buffer data. */
Willy Tarreau3e7be362022-05-27 10:35:27 +02004605 co_skip(sc_oc(sc), len1 + len2);
Willy Tarreau7e702d12021-04-28 17:59:21 +02004606 luaL_pushresult(&luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004607 return 1;
4608}
4609
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004610/* Check arguments for the function "hlua_channel_get_yield". */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004611__LJMP static int hlua_applet_tcp_getline(lua_State *L)
4612{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004613 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004614
4615 /* Initialise the string catenation. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004616 luaL_buffinit(L, &luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004617
4618 return MAY_LJMP(hlua_applet_tcp_getline_yield(L, 0, 0));
4619}
4620
4621/* If expected data not yet available, it returns a yield. This function
4622 * consumes the data in the buffer. It returns a string containing the
4623 * data. This string can be empty.
4624 */
4625__LJMP static int hlua_applet_tcp_recv_yield(lua_State *L, int status, lua_KContext ctx)
4626{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004627 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Willy Tarreauc12b3212022-05-27 11:08:15 +02004628 struct stconn *sc = appctx_sc(luactx->appctx);
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004629 size_t len = MAY_LJMP(luaL_checkinteger(L, 2));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004630 int ret;
Willy Tarreau206ba832018-06-14 15:27:31 +02004631 const char *blk1;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004632 size_t len1;
Willy Tarreau206ba832018-06-14 15:27:31 +02004633 const char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004634 size_t len2;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004635
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004636 /* Read the maximum amount of data available. */
Willy Tarreau3e7be362022-05-27 10:35:27 +02004637 ret = co_getblk_nc(sc_oc(sc), &blk1, &len1, &blk2, &len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004638
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004639 /* Data not yet available. return yield. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004640 if (ret == 0) {
Willy Tarreau90e8b452022-05-25 18:21:43 +02004641 applet_need_more_data(luactx->appctx);
Willy Tarreau9635e032018-10-16 17:52:55 +02004642 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004643 }
4644
4645 /* End of data: commit the total strings and return. */
4646 if (ret < 0) {
Willy Tarreau7e702d12021-04-28 17:59:21 +02004647 luaL_pushresult(&luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004648 return 1;
4649 }
4650
4651 /* Ensure that the block 2 length is usable. */
4652 if (ret == 1)
4653 len2 = 0;
4654
4655 if (len == -1) {
4656
4657 /* If len == -1, catenate all the data avalaile and
4658 * yield because we want to get all the data until
4659 * the end of data stream.
4660 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004661 luaL_addlstring(&luactx->b, blk1, len1);
4662 luaL_addlstring(&luactx->b, blk2, len2);
Willy Tarreau3e7be362022-05-27 10:35:27 +02004663 co_skip(sc_oc(sc), len1 + len2);
Willy Tarreau90e8b452022-05-25 18:21:43 +02004664 applet_need_more_data(luactx->appctx);
Willy Tarreau9635e032018-10-16 17:52:55 +02004665 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004666
4667 } else {
4668
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05004669 /* Copy the first block caping to the length required. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004670 if (len1 > len)
4671 len1 = len;
Willy Tarreau7e702d12021-04-28 17:59:21 +02004672 luaL_addlstring(&luactx->b, blk1, len1);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004673 len -= len1;
4674
4675 /* Copy the second block. */
4676 if (len2 > len)
4677 len2 = len;
Willy Tarreau7e702d12021-04-28 17:59:21 +02004678 luaL_addlstring(&luactx->b, blk2, len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004679 len -= len2;
4680
4681 /* Consume input channel output buffer data. */
Willy Tarreau3e7be362022-05-27 10:35:27 +02004682 co_skip(sc_oc(sc), len1 + len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004683
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004684 /* If there is no other data available, yield waiting for new data. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004685 if (len > 0) {
4686 lua_pushinteger(L, len);
4687 lua_replace(L, 2);
Willy Tarreau90e8b452022-05-25 18:21:43 +02004688 applet_need_more_data(luactx->appctx);
Willy Tarreau9635e032018-10-16 17:52:55 +02004689 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004690 }
4691
4692 /* return the result. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004693 luaL_pushresult(&luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004694 return 1;
4695 }
4696
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004697 /* we never execute this */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004698 hlua_pusherror(L, "Lua: internal error");
4699 WILL_LJMP(lua_error(L));
4700 return 0;
4701}
4702
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004703/* Check arguments for the function "hlua_channel_get_yield". */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004704__LJMP static int hlua_applet_tcp_recv(lua_State *L)
4705{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004706 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004707 int len = -1;
4708
4709 if (lua_gettop(L) > 2)
4710 WILL_LJMP(luaL_error(L, "The 'recv' function requires between 1 and 2 arguments."));
4711 if (lua_gettop(L) >= 2) {
4712 len = MAY_LJMP(luaL_checkinteger(L, 2));
4713 lua_pop(L, 1);
4714 }
4715
4716 /* Confirm or set the required length */
4717 lua_pushinteger(L, len);
4718
4719 /* Initialise the string catenation. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004720 luaL_buffinit(L, &luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004721
4722 return MAY_LJMP(hlua_applet_tcp_recv_yield(L, 0, 0));
4723}
4724
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004725/* Append data in the output side of the buffer. This data is immediately
4726 * sent. The function returns the amount of data written. If the buffer
4727 * cannot contain the data, the function yields. The function returns -1
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004728 * if the channel is closed.
4729 */
4730__LJMP static int hlua_applet_tcp_send_yield(lua_State *L, int status, lua_KContext ctx)
4731{
4732 size_t len;
Willy Tarreau7e702d12021-04-28 17:59:21 +02004733 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004734 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
4735 int l = MAY_LJMP(luaL_checkinteger(L, 3));
Willy Tarreauc12b3212022-05-27 11:08:15 +02004736 struct stconn *sc = appctx_sc(luactx->appctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02004737 struct channel *chn = sc_ic(sc);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004738 int max;
4739
4740 /* Get the max amount of data which can write as input in the channel. */
4741 max = channel_recv_max(chn);
4742 if (max > (len - l))
4743 max = len - l;
4744
4745 /* Copy data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02004746 ci_putblk(chn, str + l, max);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004747
4748 /* update counters. */
4749 l += max;
4750 lua_pop(L, 1);
4751 lua_pushinteger(L, l);
4752
4753 /* If some data is not send, declares the situation to the
4754 * applet, and returns a yield.
4755 */
4756 if (l < len) {
Willy Tarreau3e7be362022-05-27 10:35:27 +02004757 sc_need_room(sc);
Willy Tarreau9635e032018-10-16 17:52:55 +02004758 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004759 }
4760
4761 return 1;
4762}
4763
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05004764/* Just a wrapper of "hlua_applet_tcp_send_yield". This wrapper permits
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004765 * yield the LUA process, and resume it without checking the
4766 * input arguments.
4767 */
4768__LJMP static int hlua_applet_tcp_send(lua_State *L)
4769{
4770 MAY_LJMP(check_args(L, 2, "send"));
4771 lua_pushinteger(L, 0);
4772
4773 return MAY_LJMP(hlua_applet_tcp_send_yield(L, 0, 0));
4774}
4775
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004776/*
4777 *
4778 *
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004779 * Class AppletHTTP
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004780 *
4781 *
4782 */
4783
4784/* Returns a struct hlua_txn if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02004785 * a class stream, otherwise it throws an error.
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004786 */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004787__LJMP static struct hlua_appctx *hlua_checkapplet_http(lua_State *L, int ud)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004788{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004789 return MAY_LJMP(hlua_checkudata(L, ud, class_applet_http_ref));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004790}
4791
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004792/* This function creates and push in the stack an Applet object
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004793 * according with a current TXN.
Willy Tarreauaa229cc2022-05-06 14:26:10 +02004794 * It relies on the caller to have already reserved the room in ctx->svcctx
4795 * for the local storage of hlua_http_ctx.
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004796 */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004797static int hlua_applet_http_new(lua_State *L, struct appctx *ctx)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004798{
Willy Tarreauaa229cc2022-05-06 14:26:10 +02004799 struct hlua_http_ctx *http_ctx = ctx->svcctx;
Willy Tarreau7e702d12021-04-28 17:59:21 +02004800 struct hlua_appctx *luactx;
Thierry FOURNIER841475e2015-12-11 17:10:09 +01004801 struct hlua_txn htxn;
Willy Tarreau0698c802022-05-11 14:09:57 +02004802 struct stream *s = appctx_strm(ctx);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004803 struct proxy *px = s->be;
Christopher Fauleta2097962019-07-15 16:25:33 +02004804 struct htx *htx;
4805 struct htx_blk *blk;
4806 struct htx_sl *sl;
4807 struct ist path;
4808 unsigned long long len = 0;
4809 int32_t pos;
Amaury Denoyellec453f952021-07-06 11:40:12 +02004810 struct http_uri_parser parser;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004811
4812 /* Check stack size. */
4813 if (!lua_checkstack(L, 3))
4814 return 0;
4815
4816 /* Create the object: obj[0] = userdata.
4817 * Note that the base of the Converters object is the
4818 * same than the TXN object.
4819 */
4820 lua_newtable(L);
Willy Tarreau7e702d12021-04-28 17:59:21 +02004821 luactx = lua_newuserdata(L, sizeof(*luactx));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004822 lua_rawseti(L, -2, 0);
Willy Tarreau7e702d12021-04-28 17:59:21 +02004823 luactx->appctx = ctx;
Willy Tarreauaa229cc2022-05-06 14:26:10 +02004824 http_ctx->status = 200; /* Default status code returned. */
4825 http_ctx->reason = NULL; /* Use default reason based on status */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004826 luactx->htxn.s = s;
4827 luactx->htxn.p = px;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004828
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004829 /* Create the "f" field that contains a list of fetches. */
4830 lua_pushstring(L, "f");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004831 if (!hlua_fetches_new(L, &luactx->htxn, 0))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004832 return 0;
4833 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004834
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004835 /* Create the "sf" field that contains a list of stringsafe fetches. */
4836 lua_pushstring(L, "sf");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004837 if (!hlua_fetches_new(L, &luactx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004838 return 0;
4839 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004840
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004841 /* Create the "c" field that contains a list of converters. */
4842 lua_pushstring(L, "c");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004843 if (!hlua_converters_new(L, &luactx->htxn, 0))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004844 return 0;
4845 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004846
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004847 /* Create the "sc" field that contains a list of stringsafe converters. */
4848 lua_pushstring(L, "sc");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004849 if (!hlua_converters_new(L, &luactx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004850 return 0;
4851 lua_settable(L, -3);
Willy Tarreaueee5b512015-04-03 23:46:31 +02004852
Christopher Fauleta2097962019-07-15 16:25:33 +02004853 htx = htxbuf(&s->req.buf);
4854 blk = htx_get_first_blk(htx);
Christopher Fauletea009732019-11-18 15:50:25 +01004855 BUG_ON(!blk || htx_get_blk_type(blk) != HTX_BLK_REQ_SL);
Christopher Fauleta2097962019-07-15 16:25:33 +02004856 sl = htx_get_blk_ptr(htx, blk);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004857
Christopher Fauleta2097962019-07-15 16:25:33 +02004858 /* Stores the request method. */
4859 lua_pushstring(L, "method");
4860 lua_pushlstring(L, HTX_SL_REQ_MPTR(sl), HTX_SL_REQ_MLEN(sl));
4861 lua_settable(L, -3);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004862
Christopher Fauleta2097962019-07-15 16:25:33 +02004863 /* Stores the http version. */
4864 lua_pushstring(L, "version");
4865 lua_pushlstring(L, HTX_SL_REQ_VPTR(sl), HTX_SL_REQ_VLEN(sl));
4866 lua_settable(L, -3);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004867
Christopher Fauleta2097962019-07-15 16:25:33 +02004868 /* creates an array of headers. hlua_http_get_headers() crates and push
4869 * the array on the top of the stack.
4870 */
4871 lua_pushstring(L, "headers");
4872 htxn.s = s;
4873 htxn.p = px;
4874 htxn.dir = SMP_OPT_DIR_REQ;
Christopher Faulet9d1332b2020-02-24 16:46:16 +01004875 if (!hlua_http_get_headers(L, &htxn.s->txn->req))
Christopher Fauleta2097962019-07-15 16:25:33 +02004876 return 0;
4877 lua_settable(L, -3);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004878
Amaury Denoyellec453f952021-07-06 11:40:12 +02004879 parser = http_uri_parser_init(htx_sl_req_uri(sl));
4880 path = http_parse_path(&parser);
Tim Duesterhused526372020-03-05 17:56:33 +01004881 if (isttest(path)) {
Christopher Fauleta2097962019-07-15 16:25:33 +02004882 char *p, *q, *end;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004883
Christopher Fauleta2097962019-07-15 16:25:33 +02004884 p = path.ptr;
Tim Duesterhus4c8f75f2021-11-06 15:14:44 +01004885 end = istend(path);
Christopher Fauleta2097962019-07-15 16:25:33 +02004886 q = p;
4887 while (q < end && *q != '?')
4888 q++;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004889
Thierry FOURNIER7d388632017-02-22 02:06:16 +01004890 /* Stores the request path. */
Christopher Fauleta2097962019-07-15 16:25:33 +02004891 lua_pushstring(L, "path");
4892 lua_pushlstring(L, p, q - p);
Thierry FOURNIER7d388632017-02-22 02:06:16 +01004893 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01004894
Christopher Fauleta2097962019-07-15 16:25:33 +02004895 /* Stores the query string. */
4896 lua_pushstring(L, "qs");
4897 if (*q == '?')
4898 q++;
4899 lua_pushlstring(L, q, end - q);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004900 lua_settable(L, -3);
Christopher Fauleta2097962019-07-15 16:25:33 +02004901 }
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004902
Christopher Fauleta2097962019-07-15 16:25:33 +02004903 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
4904 struct htx_blk *blk = htx_get_blk(htx, pos);
4905 enum htx_blk_type type = htx_get_blk_type(blk);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004906
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01004907 if (type == HTX_BLK_TLR || type == HTX_BLK_EOT)
Christopher Fauleta2097962019-07-15 16:25:33 +02004908 break;
4909 if (type == HTX_BLK_DATA)
4910 len += htx_get_blksz(blk);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004911 }
Christopher Faulet2e47e3a2023-01-13 11:40:24 +01004912 if (htx->extra != HTX_UNKOWN_PAYLOAD_LENGTH)
Christopher Fauleta2097962019-07-15 16:25:33 +02004913 len += htx->extra;
4914
4915 /* Stores the request path. */
4916 lua_pushstring(L, "length");
4917 lua_pushinteger(L, len);
4918 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01004919
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004920 /* Create an empty array of HTTP request headers. */
4921 lua_pushstring(L, "response");
4922 lua_newtable(L);
4923 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01004924
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004925 /* Pop a class stream metatable and affect it to the table. */
4926 lua_rawgeti(L, LUA_REGISTRYINDEX, class_applet_http_ref);
4927 lua_setmetatable(L, -2);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004928
4929 return 1;
4930}
4931
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004932__LJMP static int hlua_applet_http_set_var(lua_State *L)
4933{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004934 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004935 struct stream *s;
4936 const char *name;
4937 size_t len;
4938 struct sample smp;
4939
Tim Duesterhus4e172c92020-05-19 13:49:42 +02004940 if (lua_gettop(L) < 3 || lua_gettop(L) > 4)
4941 WILL_LJMP(luaL_error(L, "'set_var' needs between 3 and 4 arguments"));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004942
4943 /* It is useles to retrieve the stream, but this function
4944 * runs only in a stream context.
4945 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004946 luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004947 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02004948 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004949
4950 /* Converts the third argument in a sample. */
Amaury Denoyellebc0af6a2020-10-29 17:21:20 +01004951 memset(&smp, 0, sizeof(smp));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004952 hlua_lua2smp(L, 3, &smp);
4953
4954 /* Store the sample in a variable. */
4955 smp_set_owner(&smp, s->be, s->sess, s, 0);
Tim Duesterhus4e172c92020-05-19 13:49:42 +02004956
4957 if (lua_gettop(L) == 4 && lua_toboolean(L, 4))
4958 lua_pushboolean(L, vars_set_by_name_ifexist(name, len, &smp) != 0);
4959 else
4960 lua_pushboolean(L, vars_set_by_name(name, len, &smp) != 0);
4961
Tim Duesterhus84ebc132020-05-19 13:49:41 +02004962 return 1;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004963}
4964
4965__LJMP static int hlua_applet_http_unset_var(lua_State *L)
4966{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004967 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004968 struct stream *s;
4969 const char *name;
4970 size_t len;
4971 struct sample smp;
4972
4973 MAY_LJMP(check_args(L, 2, "unset_var"));
4974
4975 /* It is useles to retrieve the stream, but this function
4976 * runs only in a stream context.
4977 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004978 luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004979 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02004980 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004981
4982 /* Unset the variable. */
4983 smp_set_owner(&smp, s->be, s->sess, s, 0);
Tim Duesterhus84ebc132020-05-19 13:49:41 +02004984 lua_pushboolean(L, vars_unset_by_name_ifexist(name, len, &smp) != 0);
4985 return 1;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004986}
4987
4988__LJMP static int hlua_applet_http_get_var(lua_State *L)
4989{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004990 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004991 struct stream *s;
4992 const char *name;
4993 size_t len;
4994 struct sample smp;
4995
4996 MAY_LJMP(check_args(L, 2, "get_var"));
4997
4998 /* It is useles to retrieve the stream, but this function
4999 * runs only in a stream context.
5000 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005001 luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01005002 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02005003 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01005004
5005 smp_set_owner(&smp, s->be, s->sess, s, 0);
Willy Tarreaue352b9d2021-09-03 11:52:38 +02005006 if (!vars_get_by_name(name, len, &smp, NULL)) {
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01005007 lua_pushnil(L);
5008 return 1;
5009 }
5010
5011 return hlua_smp2lua(L, &smp);
5012}
5013
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01005014__LJMP static int hlua_applet_http_set_priv(lua_State *L)
5015{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005016 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
5017 struct stream *s = luactx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01005018 struct hlua *hlua;
5019
5020 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005021 if (!s->hlua)
5022 return 0;
5023 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01005024
5025 MAY_LJMP(check_args(L, 2, "set_priv"));
5026
5027 /* Remove previous value. */
Thierry FOURNIERe068b602017-04-26 13:27:05 +02005028 luaL_unref(L, LUA_REGISTRYINDEX, hlua->Mref);
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01005029
5030 /* Get and store new value. */
5031 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
5032 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
5033
5034 return 0;
5035}
5036
5037__LJMP static int hlua_applet_http_get_priv(lua_State *L)
5038{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005039 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
5040 struct stream *s = luactx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01005041 struct hlua *hlua;
5042
5043 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005044 if (!s->hlua) {
5045 lua_pushnil(L);
5046 return 1;
5047 }
5048 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01005049
5050 /* Push configuration index in the stack. */
5051 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
5052
5053 return 1;
5054}
5055
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005056/* If expected data not yet available, it returns a yield. This function
5057 * consumes the data in the buffer. It returns a string containing the
5058 * data. This string can be empty.
5059 */
Christopher Fauleta2097962019-07-15 16:25:33 +02005060__LJMP static int hlua_applet_http_getline_yield(lua_State *L, int status, lua_KContext ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005061{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005062 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Willy Tarreauc12b3212022-05-27 11:08:15 +02005063 struct stconn *sc = appctx_sc(luactx->appctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02005064 struct channel *req = sc_oc(sc);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005065 struct htx *htx;
5066 struct htx_blk *blk;
5067 size_t count;
5068 int stop = 0;
5069
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005070 htx = htx_from_buf(&req->buf);
5071 count = co_data(req);
Christopher Fauleta3f15502019-05-13 15:27:23 +02005072 blk = htx_get_first_blk(htx);
Christopher Fauletcc26b132018-12-18 21:20:57 +01005073
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005074 while (count && !stop && blk) {
5075 enum htx_blk_type type = htx_get_blk_type(blk);
5076 uint32_t sz = htx_get_blksz(blk);
5077 struct ist v;
5078 uint32_t vlen;
5079 char *nl;
5080
5081 vlen = sz;
5082 if (vlen > count) {
5083 if (type != HTX_BLK_DATA)
5084 break;
5085 vlen = count;
5086 }
5087
5088 switch (type) {
5089 case HTX_BLK_UNUSED:
5090 break;
5091
5092 case HTX_BLK_DATA:
5093 v = htx_get_blk_value(htx, blk);
5094 v.len = vlen;
5095 nl = istchr(v, '\n');
5096 if (nl != NULL) {
5097 stop = 1;
5098 vlen = nl - v.ptr + 1;
5099 }
Willy Tarreau7e702d12021-04-28 17:59:21 +02005100 luaL_addlstring(&luactx->b, v.ptr, vlen);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005101 break;
5102
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005103 case HTX_BLK_TLR:
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01005104 case HTX_BLK_EOT:
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005105 stop = 1;
5106 break;
5107
5108 default:
5109 break;
5110 }
5111
Willy Tarreau84240042022-02-28 16:51:23 +01005112 c_rew(req, vlen);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005113 count -= vlen;
5114 if (sz == vlen)
5115 blk = htx_remove_blk(htx, blk);
5116 else {
5117 htx_cut_data_blk(htx, blk, vlen);
5118 break;
5119 }
5120 }
5121
Christopher Fauleteccb31c2021-04-02 14:24:56 +02005122 /* The message was fully consumed and no more data are expected
5123 * (EOM flag set).
5124 */
Christopher Faulet904763f2023-03-22 14:53:11 +01005125 if (htx_is_empty(htx) && (sc->flags & SC_FL_EOI))
Christopher Fauleteccb31c2021-04-02 14:24:56 +02005126 stop = 1;
5127
Christopher Faulet0ae79d02019-02-27 21:36:59 +01005128 htx_to_buf(htx, &req->buf);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005129 if (!stop) {
Willy Tarreau90e8b452022-05-25 18:21:43 +02005130 applet_need_more_data(luactx->appctx);
Christopher Fauleta2097962019-07-15 16:25:33 +02005131 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_getline_yield, TICK_ETERNITY, 0));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005132 }
5133
5134 /* return the result. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005135 luaL_pushresult(&luactx->b);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005136 return 1;
5137}
5138
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005139
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08005140/* Check arguments for the function "hlua_channel_get_yield". */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005141__LJMP static int hlua_applet_http_getline(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005142{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005143 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005144
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005145 /* Initialise the string catenation. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005146 luaL_buffinit(L, &luactx->b);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005147
Christopher Fauleta2097962019-07-15 16:25:33 +02005148 return MAY_LJMP(hlua_applet_http_getline_yield(L, 0, 0));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005149}
5150
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005151/* If expected data not yet available, it returns a yield. This function
5152 * consumes the data in the buffer. It returns a string containing the
5153 * data. This string can be empty.
5154 */
Christopher Fauleta2097962019-07-15 16:25:33 +02005155__LJMP static int hlua_applet_http_recv_yield(lua_State *L, int status, lua_KContext ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005156{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005157 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Willy Tarreauc12b3212022-05-27 11:08:15 +02005158 struct stconn *sc = appctx_sc(luactx->appctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02005159 struct channel *req = sc_oc(sc);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005160 struct htx *htx;
5161 struct htx_blk *blk;
5162 size_t count;
5163 int len;
5164
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005165 htx = htx_from_buf(&req->buf);
5166 len = MAY_LJMP(luaL_checkinteger(L, 2));
5167 count = co_data(req);
Christopher Faulet29f17582019-05-23 11:03:26 +02005168 blk = htx_get_head_blk(htx);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005169 while (count && len && blk) {
5170 enum htx_blk_type type = htx_get_blk_type(blk);
5171 uint32_t sz = htx_get_blksz(blk);
5172 struct ist v;
5173 uint32_t vlen;
5174
5175 vlen = sz;
5176 if (len > 0 && vlen > len)
5177 vlen = len;
5178 if (vlen > count) {
5179 if (type != HTX_BLK_DATA)
5180 break;
5181 vlen = count;
5182 }
5183
5184 switch (type) {
5185 case HTX_BLK_UNUSED:
5186 break;
5187
5188 case HTX_BLK_DATA:
5189 v = htx_get_blk_value(htx, blk);
Willy Tarreau7e702d12021-04-28 17:59:21 +02005190 luaL_addlstring(&luactx->b, v.ptr, vlen);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005191 break;
5192
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005193 case HTX_BLK_TLR:
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01005194 case HTX_BLK_EOT:
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005195 len = 0;
5196 break;
5197
5198 default:
5199 break;
5200 }
5201
Willy Tarreau84240042022-02-28 16:51:23 +01005202 c_rew(req, vlen);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005203 count -= vlen;
5204 if (len > 0)
5205 len -= vlen;
5206 if (sz == vlen)
5207 blk = htx_remove_blk(htx, blk);
5208 else {
5209 htx_cut_data_blk(htx, blk, vlen);
5210 break;
5211 }
5212 }
5213
Christopher Fauleteccb31c2021-04-02 14:24:56 +02005214 /* The message was fully consumed and no more data are expected
5215 * (EOM flag set).
5216 */
Christopher Faulet904763f2023-03-22 14:53:11 +01005217 if (htx_is_empty(htx) && (sc->flags & SC_FL_EOI))
Christopher Fauleteccb31c2021-04-02 14:24:56 +02005218 len = 0;
5219
Christopher Faulet0ae79d02019-02-27 21:36:59 +01005220 htx_to_buf(htx, &req->buf);
5221
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005222 /* If we are no other data available, yield waiting for new data. */
5223 if (len) {
5224 if (len > 0) {
5225 lua_pushinteger(L, len);
5226 lua_replace(L, 2);
5227 }
Willy Tarreau90e8b452022-05-25 18:21:43 +02005228 applet_need_more_data(luactx->appctx);
Willy Tarreau9635e032018-10-16 17:52:55 +02005229 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005230 }
5231
5232 /* return the result. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005233 luaL_pushresult(&luactx->b);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005234 return 1;
5235}
5236
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08005237/* Check arguments for the function "hlua_channel_get_yield". */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005238__LJMP static int hlua_applet_http_recv(lua_State *L)
5239{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005240 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005241 int len = -1;
5242
5243 /* Check arguments. */
5244 if (lua_gettop(L) > 2)
5245 WILL_LJMP(luaL_error(L, "The 'recv' function requires between 1 and 2 arguments."));
5246 if (lua_gettop(L) >= 2) {
5247 len = MAY_LJMP(luaL_checkinteger(L, 2));
5248 lua_pop(L, 1);
5249 }
5250
Christopher Fauleta2097962019-07-15 16:25:33 +02005251 lua_pushinteger(L, len);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005252
Christopher Fauleta2097962019-07-15 16:25:33 +02005253 /* Initialise the string catenation. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005254 luaL_buffinit(L, &luactx->b);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005255
Christopher Fauleta2097962019-07-15 16:25:33 +02005256 return MAY_LJMP(hlua_applet_http_recv_yield(L, 0, 0));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005257}
5258
5259/* Append data in the output side of the buffer. This data is immediately
5260 * sent. The function returns the amount of data written. If the buffer
5261 * cannot contain the data, the function yields. The function returns -1
5262 * if the channel is closed.
5263 */
Christopher Fauleta2097962019-07-15 16:25:33 +02005264__LJMP static int hlua_applet_http_send_yield(lua_State *L, int status, lua_KContext ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005265{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005266 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Willy Tarreauc12b3212022-05-27 11:08:15 +02005267 struct stconn *sc = appctx_sc(luactx->appctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02005268 struct channel *res = sc_ic(sc);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005269 struct htx *htx = htx_from_buf(&res->buf);
5270 const char *data;
5271 size_t len;
5272 int l = MAY_LJMP(luaL_checkinteger(L, 3));
5273 int max;
5274
Christopher Faulet9060fc02019-07-03 11:39:30 +02005275 max = htx_get_max_blksz(htx, channel_htx_recv_max(res, htx));
Christopher Faulet4b0e9b22019-01-09 12:16:58 +01005276 if (!max)
5277 goto snd_yield;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005278
5279 data = MAY_LJMP(luaL_checklstring(L, 2, &len));
5280
5281 /* Get the max amount of data which can write as input in the channel. */
5282 if (max > (len - l))
5283 max = len - l;
5284
5285 /* Copy data. */
Willy Tarreau0a7ef022019-05-28 10:30:11 +02005286 max = htx_add_data(htx, ist2(data + l, max));
Christopher Fauletf6cce3f2019-02-27 21:20:09 +01005287 channel_add_input(res, max);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005288
5289 /* update counters. */
5290 l += max;
5291 lua_pop(L, 1);
5292 lua_pushinteger(L, l);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005293
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005294 /* If some data is not send, declares the situation to the
5295 * applet, and returns a yield.
5296 */
5297 if (l < len) {
Christopher Faulet4b0e9b22019-01-09 12:16:58 +01005298 snd_yield:
Christopher Faulet0ae79d02019-02-27 21:36:59 +01005299 htx_to_buf(htx, &res->buf);
Willy Tarreau3e7be362022-05-27 10:35:27 +02005300 sc_need_room(sc);
Willy Tarreau9635e032018-10-16 17:52:55 +02005301 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005302 }
5303
Christopher Fauleta2097962019-07-15 16:25:33 +02005304 htx_to_buf(htx, &res->buf);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005305 return 1;
5306}
5307
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05005308/* Just a wrapper of "hlua_applet_send_yield". This wrapper permits
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005309 * yield the LUA process, and resume it without checking the
5310 * input arguments.
5311 */
5312__LJMP static int hlua_applet_http_send(lua_State *L)
5313{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005314 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005315 struct hlua_http_ctx *http_ctx = luactx->appctx->svcctx;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005316
5317 /* We want to send some data. Headers must be sent. */
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005318 if (!(http_ctx->flags & APPLET_HDR_SENT)) {
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005319 hlua_pusherror(L, "Lua: 'send' you must call start_response() before sending data.");
5320 WILL_LJMP(lua_error(L));
5321 }
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005322
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05005323 /* This integer is used for followinf the amount of data sent. */
Christopher Fauleta2097962019-07-15 16:25:33 +02005324 lua_pushinteger(L, 0);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005325
Christopher Fauleta2097962019-07-15 16:25:33 +02005326 return MAY_LJMP(hlua_applet_http_send_yield(L, 0, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005327}
5328
5329__LJMP static int hlua_applet_http_addheader(lua_State *L)
5330{
5331 const char *name;
5332 int ret;
5333
5334 MAY_LJMP(hlua_checkapplet_http(L, 1));
5335 name = MAY_LJMP(luaL_checkstring(L, 2));
5336 MAY_LJMP(luaL_checkstring(L, 3));
5337
5338 /* Push in the stack the "response" entry. */
5339 ret = lua_getfield(L, 1, "response");
5340 if (ret != LUA_TTABLE) {
5341 hlua_pusherror(L, "Lua: 'add_header' internal error: AppletHTTP['response'] "
5342 "is expected as an array. %s found", lua_typename(L, ret));
5343 WILL_LJMP(lua_error(L));
5344 }
5345
5346 /* check if the header is already registered if it is not
5347 * the case, register it.
5348 */
5349 ret = lua_getfield(L, -1, name);
5350 if (ret == LUA_TNIL) {
5351
5352 /* Entry not found. */
5353 lua_pop(L, 1); /* remove the nil. The "response" table is the top of the stack. */
5354
5355 /* Insert the new header name in the array in the top of the stack.
5356 * It left the new array in the top of the stack.
5357 */
5358 lua_newtable(L);
5359 lua_pushvalue(L, 2);
5360 lua_pushvalue(L, -2);
5361 lua_settable(L, -4);
5362
5363 } else if (ret != LUA_TTABLE) {
5364
5365 /* corruption error. */
5366 hlua_pusherror(L, "Lua: 'add_header' internal error: AppletHTTP['response']['%s'] "
5367 "is expected as an array. %s found", name, lua_typename(L, ret));
5368 WILL_LJMP(lua_error(L));
5369 }
5370
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -07005371 /* Now the top of thestack is an array of values. We push
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005372 * the header value as new entry.
5373 */
5374 lua_pushvalue(L, 3);
5375 ret = lua_rawlen(L, -2);
5376 lua_rawseti(L, -2, ret + 1);
5377 lua_pushboolean(L, 1);
5378 return 1;
5379}
5380
5381__LJMP static int hlua_applet_http_status(lua_State *L)
5382{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005383 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005384 int status = MAY_LJMP(luaL_checkinteger(L, 2));
Robin H. Johnson52f5db22017-01-01 13:10:52 -08005385 const char *reason = MAY_LJMP(luaL_optlstring(L, 3, NULL, NULL));
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005386 struct hlua_http_ctx *http_ctx = luactx->appctx->svcctx;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005387
5388 if (status < 100 || status > 599) {
5389 lua_pushboolean(L, 0);
5390 return 1;
5391 }
5392
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005393 http_ctx->status = status;
5394 http_ctx->reason = reason;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005395 lua_pushboolean(L, 1);
5396 return 1;
5397}
5398
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005399
Christopher Fauleta2097962019-07-15 16:25:33 +02005400__LJMP static int hlua_applet_http_send_response(lua_State *L)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005401{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005402 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005403 struct hlua_http_ctx *http_ctx = luactx->appctx->svcctx;
Willy Tarreauc12b3212022-05-27 11:08:15 +02005404 struct stconn *sc = appctx_sc(luactx->appctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02005405 struct channel *res = sc_ic(sc);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005406 struct htx *htx;
5407 struct htx_sl *sl;
5408 struct h1m h1m;
5409 const char *status, *reason;
5410 const char *name, *value;
5411 size_t nlen, vlen;
5412 unsigned int flags;
5413
5414 /* Send the message at once. */
5415 htx = htx_from_buf(&res->buf);
5416 h1m_init_res(&h1m);
5417
5418 /* Use the same http version than the request. */
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005419 status = ultoa_r(http_ctx->status, trash.area, trash.size);
5420 reason = http_ctx->reason;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005421 if (reason == NULL)
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005422 reason = http_get_reason(http_ctx->status);
5423 if (http_ctx->flags & APPLET_HTTP11) {
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005424 flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11);
5425 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.1"), ist(status), ist(reason));
5426 }
5427 else {
5428 flags = HTX_SL_F_IS_RESP;
5429 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.0"), ist(status), ist(reason));
5430 }
5431 if (!sl) {
5432 hlua_pusherror(L, "Lua applet http '%s': Failed to create response.\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 WILL_LJMP(lua_error(L));
5435 }
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005436 sl->info.res.status = http_ctx->status;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005437
5438 /* Get the array associated to the field "response" in the object AppletHTTP. */
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005439 if (lua_getfield(L, 1, "response") != LUA_TTABLE) {
5440 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response'] missing.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005441 luactx->appctx->rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005442 WILL_LJMP(lua_error(L));
5443 }
5444
5445 /* Browse the list of headers. */
5446 lua_pushnil(L);
5447 while(lua_next(L, -2) != 0) {
5448 /* We expect a string as -2. */
5449 if (lua_type(L, -2) != LUA_TSTRING) {
5450 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response'][] element must be a string. got %s.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005451 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005452 lua_typename(L, lua_type(L, -2)));
5453 WILL_LJMP(lua_error(L));
5454 }
5455 name = lua_tolstring(L, -2, &nlen);
5456
5457 /* We expect an array as -1. */
5458 if (lua_type(L, -1) != LUA_TTABLE) {
5459 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 +02005460 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005461 name,
5462 lua_typename(L, lua_type(L, -1)));
5463 WILL_LJMP(lua_error(L));
5464 }
5465
5466 /* Browse the table who is on the top of the stack. */
5467 lua_pushnil(L);
5468 while(lua_next(L, -2) != 0) {
5469 int id;
5470
5471 /* We expect a number as -2. */
5472 if (lua_type(L, -2) != LUA_TNUMBER) {
5473 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 +02005474 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005475 name,
5476 lua_typename(L, lua_type(L, -2)));
5477 WILL_LJMP(lua_error(L));
5478 }
5479 id = lua_tointeger(L, -2);
5480
5481 /* We expect a string as -2. */
5482 if (lua_type(L, -1) != LUA_TSTRING) {
5483 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 +02005484 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005485 name, id,
5486 lua_typename(L, lua_type(L, -1)));
5487 WILL_LJMP(lua_error(L));
5488 }
5489 value = lua_tolstring(L, -1, &vlen);
5490
5491 /* Simple Protocol checks. */
Christopher Faulet545fbba2021-09-28 09:36:25 +02005492 if (isteqi(ist2(name, nlen), ist("transfer-encoding"))) {
5493 int ret;
5494
5495 ret = h1_parse_xfer_enc_header(&h1m, ist2(value, vlen));
5496 if (ret < 0) {
5497 hlua_pusherror(L, "Lua applet http '%s': Invalid '%s' header.\n",
5498 luactx->appctx->rule->arg.hlua_rule->fcn->name,
5499 name);
5500 WILL_LJMP(lua_error(L));
5501 }
5502 else if (ret == 0)
5503 goto next; /* Skip it */
5504 }
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005505 else if (isteqi(ist2(name, nlen), ist("content-length"))) {
5506 struct ist v = ist2(value, vlen);
5507 int ret;
5508
5509 ret = h1_parse_cont_len_header(&h1m, &v);
5510 if (ret < 0) {
5511 hlua_pusherror(L, "Lua applet http '%s': Invalid '%s' header.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005512 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005513 name);
5514 WILL_LJMP(lua_error(L));
5515 }
5516 else if (ret == 0)
5517 goto next; /* Skip it */
5518 }
5519
5520 /* Add a new header */
5521 if (!htx_add_header(htx, ist2(name, nlen), ist2(value, vlen))) {
5522 hlua_pusherror(L, "Lua applet http '%s': Failed to add header '%s' in the response.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005523 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005524 name);
5525 WILL_LJMP(lua_error(L));
5526 }
5527 next:
5528 /* Remove the array from the stack, and get next element with a remaining string. */
5529 lua_pop(L, 1);
5530 }
5531
5532 /* Remove the array from the stack, and get next element with a remaining string. */
5533 lua_pop(L, 1);
5534 }
5535
5536 if (h1m.flags & H1_MF_CHNK)
5537 h1m.flags &= ~H1_MF_CLEN;
5538 if (h1m.flags & (H1_MF_CLEN|H1_MF_CHNK))
5539 h1m.flags |= H1_MF_XFER_LEN;
5540
5541 /* Uset HTX start-line flags */
5542 if (h1m.flags & H1_MF_XFER_ENC)
5543 flags |= HTX_SL_F_XFER_ENC;
5544 if (h1m.flags & H1_MF_XFER_LEN) {
5545 flags |= HTX_SL_F_XFER_LEN;
5546 if (h1m.flags & H1_MF_CHNK)
5547 flags |= HTX_SL_F_CHNK;
5548 else if (h1m.flags & H1_MF_CLEN)
5549 flags |= HTX_SL_F_CLEN;
5550 if (h1m.body_len == 0)
5551 flags |= HTX_SL_F_BODYLESS;
5552 }
5553 sl->flags |= flags;
5554
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -07005555 /* If we don't have a content-length set, and the HTTP version is 1.1
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005556 * and the status code implies the presence of a message body, we must
5557 * announce a transfer encoding chunked. This is required by haproxy
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05005558 * for the keepalive compliance. If the applet announces a transfer-encoding
5559 * chunked itself, don't do anything.
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005560 */
5561 if ((flags & (HTX_SL_F_VER_11|HTX_SL_F_XFER_LEN)) == HTX_SL_F_VER_11 &&
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005562 http_ctx->status >= 200 && http_ctx->status != 204 && http_ctx->status != 304) {
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005563 /* Add a new header */
5564 sl->flags |= (HTX_SL_F_XFER_ENC|H1_MF_CHNK|H1_MF_XFER_LEN);
5565 if (!htx_add_header(htx, ist("transfer-encoding"), ist("chunked"))) {
5566 hlua_pusherror(L, "Lua applet http '%s': Failed to add header 'transfer-encoding' in the response.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005567 luactx->appctx->rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005568 WILL_LJMP(lua_error(L));
5569 }
5570 }
5571
5572 /* Finalize headers. */
5573 if (!htx_add_endof(htx, HTX_BLK_EOH)) {
5574 hlua_pusherror(L, "Lua applet http '%s': Failed create the response.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005575 luactx->appctx->rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005576 WILL_LJMP(lua_error(L));
5577 }
5578
5579 if (htx_used_space(htx) > b_size(&res->buf) - global.tune.maxrewrite) {
5580 b_reset(&res->buf);
5581 hlua_pusherror(L, "Lua: 'start_response': response header block too big");
5582 WILL_LJMP(lua_error(L));
5583 }
5584
5585 htx_to_buf(htx, &res->buf);
Christopher Fauletf6cce3f2019-02-27 21:20:09 +01005586 channel_add_input(res, htx->data);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005587
5588 /* Headers sent, set the flag. */
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005589 http_ctx->flags |= APPLET_HDR_SENT;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005590 return 0;
5591
5592}
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005593/* We will build the status line and the headers of the HTTP response.
5594 * We will try send at once if its not possible, we give back the hand
5595 * waiting for more room.
5596 */
Christopher Fauleta2097962019-07-15 16:25:33 +02005597__LJMP static int hlua_applet_http_start_response_yield(lua_State *L, int status, lua_KContext ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005598{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005599 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Willy Tarreauc12b3212022-05-27 11:08:15 +02005600 struct stconn *sc = appctx_sc(luactx->appctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02005601 struct channel *res = sc_ic(sc);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005602
5603 if (co_data(res)) {
Willy Tarreau3e7be362022-05-27 10:35:27 +02005604 sc_need_room(sc);
Christopher Fauleta2097962019-07-15 16:25:33 +02005605 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_start_response_yield, TICK_ETERNITY, 0));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005606 }
Christopher Fauleta2097962019-07-15 16:25:33 +02005607 return MAY_LJMP(hlua_applet_http_send_response(L));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005608}
5609
5610
Christopher Fauleta2097962019-07-15 16:25:33 +02005611__LJMP static int hlua_applet_http_start_response(lua_State *L)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005612{
Christopher Fauleta2097962019-07-15 16:25:33 +02005613 return MAY_LJMP(hlua_applet_http_start_response_yield(L, 0, 0));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005614}
5615
Christopher Fauleta2097962019-07-15 16:25:33 +02005616/*
5617 *
5618 *
5619 * Class HTTP
5620 *
5621 *
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005622 */
Christopher Fauleta2097962019-07-15 16:25:33 +02005623
5624/* Returns a struct hlua_txn if the stack entry "ud" is
5625 * a class stream, otherwise it throws an error.
5626 */
5627__LJMP static struct hlua_txn *hlua_checkhttp(lua_State *L, int ud)
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005628{
Christopher Fauleta2097962019-07-15 16:25:33 +02005629 return MAY_LJMP(hlua_checkudata(L, ud, class_http_ref));
5630}
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005631
Christopher Fauleta2097962019-07-15 16:25:33 +02005632/* This function creates and push in the stack a HTTP object
5633 * according with a current TXN.
5634 */
5635static int hlua_http_new(lua_State *L, struct hlua_txn *txn)
5636{
5637 struct hlua_txn *htxn;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005638
Christopher Fauleta2097962019-07-15 16:25:33 +02005639 /* Check stack size. */
5640 if (!lua_checkstack(L, 3))
5641 return 0;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005642
Christopher Fauleta2097962019-07-15 16:25:33 +02005643 /* Create the object: obj[0] = userdata.
5644 * Note that the base of the Converters object is the
5645 * same than the TXN object.
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005646 */
Christopher Fauleta2097962019-07-15 16:25:33 +02005647 lua_newtable(L);
5648 htxn = lua_newuserdata(L, sizeof(*htxn));
5649 lua_rawseti(L, -2, 0);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005650
5651 htxn->s = txn->s;
5652 htxn->p = txn->p;
Christopher Faulet256b69a2019-05-23 11:14:21 +02005653 htxn->dir = txn->dir;
5654 htxn->flags = txn->flags;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005655
5656 /* Pop a class stream metatable and affect it to the table. */
5657 lua_rawgeti(L, LUA_REGISTRYINDEX, class_http_ref);
5658 lua_setmetatable(L, -2);
5659
5660 return 1;
5661}
5662
Christopher Fauletdf97ac42020-02-26 16:57:19 +01005663/* This function creates and returns an array containing the status-line
5664 * elements. This function does not fails.
5665 */
5666__LJMP static int hlua_http_get_stline(lua_State *L, struct htx_sl *sl)
5667{
5668 /* Create the table. */
5669 lua_newtable(L);
5670
5671 if (sl->flags & HTX_SL_F_IS_RESP) {
5672 lua_pushstring(L, "version");
5673 lua_pushlstring(L, HTX_SL_RES_VPTR(sl), HTX_SL_RES_VLEN(sl));
5674 lua_settable(L, -3);
5675 lua_pushstring(L, "code");
5676 lua_pushlstring(L, HTX_SL_RES_CPTR(sl), HTX_SL_RES_CLEN(sl));
5677 lua_settable(L, -3);
5678 lua_pushstring(L, "reason");
5679 lua_pushlstring(L, HTX_SL_RES_RPTR(sl), HTX_SL_RES_RLEN(sl));
5680 lua_settable(L, -3);
5681 }
5682 else {
5683 lua_pushstring(L, "method");
5684 lua_pushlstring(L, HTX_SL_REQ_MPTR(sl), HTX_SL_REQ_MLEN(sl));
5685 lua_settable(L, -3);
5686 lua_pushstring(L, "uri");
5687 lua_pushlstring(L, HTX_SL_REQ_UPTR(sl), HTX_SL_REQ_ULEN(sl));
5688 lua_settable(L, -3);
5689 lua_pushstring(L, "version");
5690 lua_pushlstring(L, HTX_SL_REQ_VPTR(sl), HTX_SL_REQ_VLEN(sl));
5691 lua_settable(L, -3);
5692 }
5693 return 1;
5694}
5695
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005696/* This function creates ans returns an array of HTTP headers.
5697 * This function does not fails. It is used as wrapper with the
5698 * 2 following functions.
5699 */
Christopher Faulet9d1332b2020-02-24 16:46:16 +01005700__LJMP static int hlua_http_get_headers(lua_State *L, struct http_msg *msg)
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005701{
Christopher Fauleta2097962019-07-15 16:25:33 +02005702 struct htx *htx;
5703 int32_t pos;
5704
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005705 /* Create the table. */
5706 lua_newtable(L);
5707
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005708
Christopher Fauleta2097962019-07-15 16:25:33 +02005709 htx = htxbuf(&msg->chn->buf);
5710 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
5711 struct htx_blk *blk = htx_get_blk(htx, pos);
5712 enum htx_blk_type type = htx_get_blk_type(blk);
5713 struct ist n, v;
5714 int len;
Christopher Faulet724a12c2018-12-13 22:12:15 +01005715
Christopher Fauleta2097962019-07-15 16:25:33 +02005716 if (type == HTX_BLK_HDR) {
5717 n = htx_get_blk_name(htx,blk);
5718 v = htx_get_blk_value(htx, blk);
Christopher Faulet724a12c2018-12-13 22:12:15 +01005719 }
Christopher Fauleta2097962019-07-15 16:25:33 +02005720 else if (type == HTX_BLK_EOH)
5721 break;
5722 else
5723 continue;
Christopher Faulet724a12c2018-12-13 22:12:15 +01005724
Christopher Fauleta2097962019-07-15 16:25:33 +02005725 /* Check for existing entry:
5726 * assume that the table is on the top of the stack, and
5727 * push the key in the stack, the function lua_gettable()
5728 * perform the lookup.
5729 */
5730 lua_pushlstring(L, n.ptr, n.len);
5731 lua_gettable(L, -2);
Christopher Faulet724a12c2018-12-13 22:12:15 +01005732
Christopher Fauleta2097962019-07-15 16:25:33 +02005733 switch (lua_type(L, -1)) {
5734 case LUA_TNIL:
5735 /* Table not found, create it. */
5736 lua_pop(L, 1); /* remove the nil value. */
5737 lua_pushlstring(L, n.ptr, n.len); /* push the header name as key. */
5738 lua_newtable(L); /* create and push empty table. */
5739 lua_pushlstring(L, v.ptr, v.len); /* push header value. */
5740 lua_rawseti(L, -2, 0); /* index header value (pop it). */
5741 lua_rawset(L, -3); /* index new table with header name (pop the values). */
Christopher Faulet724a12c2018-12-13 22:12:15 +01005742 break;
Christopher Faulet724a12c2018-12-13 22:12:15 +01005743
Christopher Fauleta2097962019-07-15 16:25:33 +02005744 case LUA_TTABLE:
5745 /* Entry found: push the value in the table. */
5746 len = lua_rawlen(L, -1);
5747 lua_pushlstring(L, v.ptr, v.len); /* push header value. */
5748 lua_rawseti(L, -2, len+1); /* index header value (pop it). */
5749 lua_pop(L, 1); /* remove the table (it is stored in the main table). */
5750 break;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005751
Christopher Fauleta2097962019-07-15 16:25:33 +02005752 default:
5753 /* Other cases are errors. */
5754 hlua_pusherror(L, "internal error during the parsing of headers.");
5755 WILL_LJMP(lua_error(L));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005756 }
5757 }
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005758 return 1;
5759}
5760
5761__LJMP static int hlua_http_req_get_headers(lua_State *L)
5762{
5763 struct hlua_txn *htxn;
5764
5765 MAY_LJMP(check_args(L, 1, "req_get_headers"));
5766 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5767
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005768 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005769 WILL_LJMP(lua_error(L));
5770
Christopher Faulet9d1332b2020-02-24 16:46:16 +01005771 return hlua_http_get_headers(L, &htxn->s->txn->req);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005772}
5773
5774__LJMP static int hlua_http_res_get_headers(lua_State *L)
5775{
5776 struct hlua_txn *htxn;
5777
5778 MAY_LJMP(check_args(L, 1, "res_get_headers"));
5779 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5780
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005781 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005782 WILL_LJMP(lua_error(L));
5783
Christopher Faulet9d1332b2020-02-24 16:46:16 +01005784 return hlua_http_get_headers(L, &htxn->s->txn->rsp);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005785}
5786
5787/* This function replace full header, or just a value in
5788 * the request or in the response. It is a wrapper fir the
5789 * 4 following functions.
5790 */
Christopher Fauletd1914aa2020-02-24 16:52:46 +01005791__LJMP static inline int hlua_http_rep_hdr(lua_State *L, struct http_msg *msg, int full)
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005792{
5793 size_t name_len;
5794 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
5795 const char *reg = MAY_LJMP(luaL_checkstring(L, 3));
5796 const char *value = MAY_LJMP(luaL_checkstring(L, 4));
Christopher Fauleta2097962019-07-15 16:25:33 +02005797 struct htx *htx;
Dragan Dosen26743032019-04-30 15:54:36 +02005798 struct my_regex *re;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005799
Dragan Dosen26743032019-04-30 15:54:36 +02005800 if (!(re = regex_comp(reg, 1, 1, NULL)))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005801 WILL_LJMP(luaL_argerror(L, 3, "invalid regex"));
5802
Christopher Fauleta2097962019-07-15 16:25:33 +02005803 htx = htxbuf(&msg->chn->buf);
Christopher Fauletd1914aa2020-02-24 16:52:46 +01005804 http_replace_hdrs(chn_strm(msg->chn), htx, ist2(name, name_len), value, re, full);
Dragan Dosen26743032019-04-30 15:54:36 +02005805 regex_free(re);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005806 return 0;
5807}
5808
5809__LJMP static int hlua_http_req_rep_hdr(lua_State *L)
5810{
5811 struct hlua_txn *htxn;
5812
5813 MAY_LJMP(check_args(L, 4, "req_rep_hdr"));
5814 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5815
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005816 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005817 WILL_LJMP(lua_error(L));
5818
Christopher Fauletd1914aa2020-02-24 16:52:46 +01005819 return MAY_LJMP(hlua_http_rep_hdr(L, &htxn->s->txn->req, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005820}
5821
5822__LJMP static int hlua_http_res_rep_hdr(lua_State *L)
5823{
5824 struct hlua_txn *htxn;
5825
5826 MAY_LJMP(check_args(L, 4, "res_rep_hdr"));
5827 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5828
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005829 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005830 WILL_LJMP(lua_error(L));
5831
Christopher Fauletd1914aa2020-02-24 16:52:46 +01005832 return MAY_LJMP(hlua_http_rep_hdr(L, &htxn->s->txn->rsp, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005833}
5834
5835__LJMP static int hlua_http_req_rep_val(lua_State *L)
5836{
5837 struct hlua_txn *htxn;
5838
5839 MAY_LJMP(check_args(L, 4, "req_rep_hdr"));
5840 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5841
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005842 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005843 WILL_LJMP(lua_error(L));
5844
Christopher Fauletd1914aa2020-02-24 16:52:46 +01005845 return MAY_LJMP(hlua_http_rep_hdr(L, &htxn->s->txn->req, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005846}
5847
5848__LJMP static int hlua_http_res_rep_val(lua_State *L)
5849{
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005850 struct hlua_txn *htxn;
5851
5852 MAY_LJMP(check_args(L, 4, "res_rep_val"));
5853 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5854
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005855 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005856 WILL_LJMP(lua_error(L));
5857
Christopher Fauletd1914aa2020-02-24 16:52:46 +01005858 return MAY_LJMP(hlua_http_rep_hdr(L, &htxn->s->txn->rsp, 0));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005859}
5860
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08005861/* This function deletes all the occurrences of an header.
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005862 * It is a wrapper for the 2 following functions.
5863 */
Christopher Fauletd31c7b32020-02-25 09:37:57 +01005864__LJMP static inline int hlua_http_del_hdr(lua_State *L, struct http_msg *msg)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005865{
5866 size_t len;
5867 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Christopher Fauleta2097962019-07-15 16:25:33 +02005868 struct htx *htx = htxbuf(&msg->chn->buf);
5869 struct http_hdr_ctx ctx;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005870
Christopher Fauleta2097962019-07-15 16:25:33 +02005871 ctx.blk = NULL;
5872 while (http_find_header(htx, ist2(name, len), &ctx, 1))
5873 http_remove_header(htx, &ctx);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005874 return 0;
5875}
5876
5877__LJMP static int hlua_http_req_del_hdr(lua_State *L)
5878{
5879 struct hlua_txn *htxn;
5880
5881 MAY_LJMP(check_args(L, 2, "req_del_hdr"));
5882 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5883
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005884 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005885 WILL_LJMP(lua_error(L));
5886
Christopher Fauletd31c7b32020-02-25 09:37:57 +01005887 return hlua_http_del_hdr(L, &htxn->s->txn->req);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005888}
5889
5890__LJMP static int hlua_http_res_del_hdr(lua_State *L)
5891{
5892 struct hlua_txn *htxn;
5893
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005894 MAY_LJMP(check_args(L, 2, "res_del_hdr"));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005895 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5896
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005897 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005898 WILL_LJMP(lua_error(L));
5899
Christopher Fauletd31c7b32020-02-25 09:37:57 +01005900 return hlua_http_del_hdr(L, &htxn->s->txn->rsp);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005901}
5902
5903/* This function adds an header. It is a wrapper used by
5904 * the 2 following functions.
5905 */
Christopher Fauletd31c7b32020-02-25 09:37:57 +01005906__LJMP static inline int hlua_http_add_hdr(lua_State *L, struct http_msg *msg)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005907{
5908 size_t name_len;
5909 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
5910 size_t value_len;
5911 const char *value = MAY_LJMP(luaL_checklstring(L, 3, &value_len));
Christopher Fauleta2097962019-07-15 16:25:33 +02005912 struct htx *htx = htxbuf(&msg->chn->buf);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005913
Christopher Fauleta2097962019-07-15 16:25:33 +02005914 lua_pushboolean(L, http_add_header(htx, ist2(name, name_len),
5915 ist2(value, value_len)));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005916 return 0;
5917}
5918
Christopher Fauletdf97ac42020-02-26 16:57:19 +01005919__LJMP static int hlua_http_req_add_hdr(lua_State *L)
5920{
5921 struct hlua_txn *htxn;
5922
5923 MAY_LJMP(check_args(L, 3, "req_add_hdr"));
5924 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5925
5926 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
5927 WILL_LJMP(lua_error(L));
5928
5929 return hlua_http_add_hdr(L, &htxn->s->txn->req);
5930}
5931
5932__LJMP static int hlua_http_res_add_hdr(lua_State *L)
5933{
5934 struct hlua_txn *htxn;
5935
5936 MAY_LJMP(check_args(L, 3, "res_add_hdr"));
5937 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5938
5939 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
5940 WILL_LJMP(lua_error(L));
5941
5942 return hlua_http_add_hdr(L, &htxn->s->txn->rsp);
5943}
5944
5945static int hlua_http_req_set_hdr(lua_State *L)
5946{
5947 struct hlua_txn *htxn;
5948
5949 MAY_LJMP(check_args(L, 3, "req_set_hdr"));
5950 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5951
5952 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
5953 WILL_LJMP(lua_error(L));
5954
5955 hlua_http_del_hdr(L, &htxn->s->txn->req);
5956 return hlua_http_add_hdr(L, &htxn->s->txn->req);
5957}
5958
5959static int hlua_http_res_set_hdr(lua_State *L)
5960{
5961 struct hlua_txn *htxn;
5962
5963 MAY_LJMP(check_args(L, 3, "res_set_hdr"));
5964 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5965
5966 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
5967 WILL_LJMP(lua_error(L));
5968
5969 hlua_http_del_hdr(L, &htxn->s->txn->rsp);
5970 return hlua_http_add_hdr(L, &htxn->s->txn->rsp);
5971}
5972
5973/* This function set the method. */
5974static int hlua_http_req_set_meth(lua_State *L)
5975{
5976 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5977 size_t name_len;
5978 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
5979
5980 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
5981 WILL_LJMP(lua_error(L));
5982
5983 lua_pushboolean(L, http_req_replace_stline(0, name, name_len, htxn->p, htxn->s) != -1);
5984 return 1;
5985}
5986
5987/* This function set the method. */
5988static int hlua_http_req_set_path(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(1, name, name_len, htxn->p, htxn->s) != -1);
5998 return 1;
5999}
6000
6001/* This function set the query-string. */
6002static int hlua_http_req_set_query(lua_State *L)
6003{
6004 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
6005 size_t name_len;
6006 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
6007
6008 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
6009 WILL_LJMP(lua_error(L));
6010
6011 /* Check length. */
6012 if (name_len > trash.size - 1) {
6013 lua_pushboolean(L, 0);
6014 return 1;
6015 }
6016
6017 /* Add the mark question as prefix. */
6018 chunk_reset(&trash);
6019 trash.area[trash.data++] = '?';
6020 memcpy(trash.area + trash.data, name, name_len);
6021 trash.data += name_len;
6022
6023 lua_pushboolean(L,
6024 http_req_replace_stline(2, trash.area, trash.data, htxn->p, htxn->s) != -1);
6025 return 1;
6026}
6027
6028/* This function set the uri. */
6029static int hlua_http_req_set_uri(lua_State *L)
6030{
6031 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
6032 size_t name_len;
6033 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
6034
6035 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
6036 WILL_LJMP(lua_error(L));
6037
6038 lua_pushboolean(L, http_req_replace_stline(3, name, name_len, htxn->p, htxn->s) != -1);
6039 return 1;
6040}
6041
6042/* This function set the response code & optionally reason. */
6043static int hlua_http_res_set_status(lua_State *L)
6044{
6045 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
6046 unsigned int code = MAY_LJMP(luaL_checkinteger(L, 2));
6047 const char *str = MAY_LJMP(luaL_optlstring(L, 3, NULL, NULL));
6048 const struct ist reason = ist2(str, (str ? strlen(str) : 0));
6049
6050 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
6051 WILL_LJMP(lua_error(L));
6052
6053 http_res_set_status(code, reason, htxn->s);
6054 return 0;
6055}
6056
6057/*
6058 *
6059 *
6060 * Class HTTPMessage
6061 *
6062 *
6063 */
6064
6065/* Returns a struct http_msg if the stack entry "ud" is a class HTTPMessage,
6066 * otherwise it throws an error.
6067 */
6068__LJMP static struct http_msg *hlua_checkhttpmsg(lua_State *L, int ud)
6069{
6070 return MAY_LJMP(hlua_checkudata(L, ud, class_http_msg_ref));
6071}
6072
6073/* Creates and pushes on the stack a HTTP object according with a current TXN.
6074 */
Christopher Faulet78c35472020-02-26 17:14:08 +01006075static int hlua_http_msg_new(lua_State *L, struct http_msg *msg)
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006076{
6077 /* Check stack size. */
6078 if (!lua_checkstack(L, 3))
6079 return 0;
6080
6081 lua_newtable(L);
6082 lua_pushlightuserdata(L, msg);
6083 lua_rawseti(L, -2, 0);
6084
6085 /* Create the "channel" field that contains the request channel object. */
6086 lua_pushstring(L, "channel");
6087 if (!hlua_channel_new(L, msg->chn))
6088 return 0;
6089 lua_rawset(L, -3);
6090
6091 /* Pop a class stream metatable and affect it to the table. */
6092 lua_rawgeti(L, LUA_REGISTRYINDEX, class_http_msg_ref);
6093 lua_setmetatable(L, -2);
6094
6095 return 1;
6096}
6097
6098/* Helper function returning a filter attached to the HTTP message at the
6099 * position <ud> in the stack, filling the current offset and length of the
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006100 * filter. If no filter is attached, NULL is returned and <offset> and <len> are
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006101 * filled with output and input length respectively.
6102 */
6103static struct filter *hlua_http_msg_filter(lua_State *L, int ud, struct http_msg *msg, size_t *offset, size_t *len)
6104{
6105 struct channel *chn = msg->chn;
6106 struct htx *htx = htxbuf(&chn->buf);
6107 struct filter *filter = NULL;
6108
6109 *offset = co_data(msg->chn);
6110 *len = htx->data - co_data(msg->chn);
6111
6112 if (lua_getfield(L, ud, "__filter") == LUA_TLIGHTUSERDATA) {
6113 filter = lua_touserdata (L, -1);
6114 if (msg->msg_state >= HTTP_MSG_DATA) {
6115 struct hlua_flt_ctx *flt_ctx = filter->ctx;
6116
6117 *offset = flt_ctx->cur_off[CHN_IDX(chn)];
6118 *len = flt_ctx->cur_len[CHN_IDX(chn)];
6119 }
6120 }
6121
6122 lua_pop(L, 1);
6123 return filter;
6124}
6125
6126/* Returns true if the channel attached to the HTTP message is the response
6127 * channel.
6128 */
6129__LJMP static int hlua_http_msg_is_resp(lua_State *L)
6130{
6131 struct http_msg *msg;
6132
6133 MAY_LJMP(check_args(L, 1, "is_resp"));
6134 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6135
6136 lua_pushboolean(L, !!(msg->chn->flags & CF_ISRESP));
6137 return 1;
6138}
6139
6140/* Returns an array containing the elements status-line of the HTTP message. It relies
6141 * on hlua_http_get_stline().
6142 */
6143__LJMP static int hlua_http_msg_get_stline(lua_State *L)
6144{
6145 struct http_msg *msg;
6146 struct htx *htx;
6147 struct htx_sl *sl;
6148
6149 MAY_LJMP(check_args(L, 1, "get_stline"));
6150 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6151
6152 if (msg->msg_state > HTTP_MSG_BODY)
6153 WILL_LJMP(lua_error(L));
6154
6155 htx = htxbuf(&msg->chn->buf);
6156 sl = http_get_stline(htx);
6157 if (!sl)
6158 return 0;
6159 return hlua_http_get_stline(L, sl);
6160}
6161
6162/* Returns an array containing all headers of the HTTP message. it relies on
6163 * hlua_http_get_headers().
6164 */
6165__LJMP static int hlua_http_msg_get_headers(lua_State *L)
6166{
6167 struct http_msg *msg;
6168
6169 MAY_LJMP(check_args(L, 1, "get_headers"));
6170 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6171
6172 if (msg->msg_state > HTTP_MSG_BODY)
6173 WILL_LJMP(lua_error(L));
6174
6175 return hlua_http_get_headers(L, msg);
6176}
6177
6178/* Deletes all occurrences of an header in the HTTP message matching on its
6179 * name. It relies on hlua_http_del_hdr().
6180 */
6181__LJMP static int hlua_http_msg_del_hdr(lua_State *L)
6182{
6183 struct http_msg *msg;
6184
6185 MAY_LJMP(check_args(L, 2, "del_header"));
6186 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6187
6188 if (msg->msg_state > HTTP_MSG_BODY)
6189 WILL_LJMP(lua_error(L));
6190
6191 return hlua_http_del_hdr(L, msg);
6192}
6193
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006194/* Matches the full value line of all occurrences of an header in the HTTP
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006195 * message given its name against a regex and replaces it if it matches. It
6196 * relies on hlua_http_rep_hdr().
6197 */
6198__LJMP static int hlua_http_msg_rep_hdr(lua_State *L)
6199{
6200 struct http_msg *msg;
6201
6202 MAY_LJMP(check_args(L, 4, "rep_header"));
6203 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6204
6205 if (msg->msg_state > HTTP_MSG_BODY)
6206 WILL_LJMP(lua_error(L));
6207
6208 return hlua_http_rep_hdr(L, msg, 1);
6209}
6210
Ilya Shipitsinbd6b4be2021-10-15 16:18:21 +05006211/* Matches all comma-separated values of all occurrences of an header in the HTTP
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006212 * message given its name against a regex and replaces it if it matches. It
6213 * relies on hlua_http_rep_hdr().
6214 */
6215__LJMP static int hlua_http_msg_rep_val(lua_State *L)
6216{
6217 struct http_msg *msg;
6218
6219 MAY_LJMP(check_args(L, 4, "rep_value"));
6220 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6221
6222 if (msg->msg_state > HTTP_MSG_BODY)
6223 WILL_LJMP(lua_error(L));
6224
6225 return hlua_http_rep_hdr(L, msg, 0);
6226}
6227
6228/* Add an header in the HTTP message. It relies on hlua_http_add_hdr() */
6229__LJMP static int hlua_http_msg_add_hdr(lua_State *L)
6230{
6231 struct http_msg *msg;
6232
6233 MAY_LJMP(check_args(L, 3, "add_header"));
6234 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6235
6236 if (msg->msg_state > HTTP_MSG_BODY)
6237 WILL_LJMP(lua_error(L));
6238
6239 return hlua_http_add_hdr(L, msg);
6240}
6241
6242/* Add an header in the HTTP message removing existing headers with the same
6243 * name. It relies on hlua_http_del_hdr() and hlua_http_add_hdr().
6244 */
6245__LJMP static int hlua_http_msg_set_hdr(lua_State *L)
6246{
6247 struct http_msg *msg;
6248
6249 MAY_LJMP(check_args(L, 3, "set_header"));
6250 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6251
6252 if (msg->msg_state > HTTP_MSG_BODY)
6253 WILL_LJMP(lua_error(L));
6254
6255 hlua_http_del_hdr(L, msg);
6256 return hlua_http_add_hdr(L, msg);
6257}
6258
6259/* Rewrites the request method. It relies on http_req_replace_stline(). */
6260__LJMP static int hlua_http_msg_set_meth(lua_State *L)
6261{
6262 struct stream *s;
6263 struct http_msg *msg;
6264 const char *name;
6265 size_t name_len;
6266
6267 MAY_LJMP(check_args(L, 2, "set_method"));
6268 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6269 name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
6270
6271 if ((msg->chn->flags & CF_ISRESP) || msg->msg_state > HTTP_MSG_BODY)
6272 WILL_LJMP(lua_error(L));
6273
6274 s = chn_strm(msg->chn);
6275 lua_pushboolean(L, http_req_replace_stline(0, name, name_len, s->be, s) != -1);
6276 return 1;
6277}
6278
6279/* Rewrites the request path. It relies on http_req_replace_stline(). */
6280__LJMP static int hlua_http_msg_set_path(lua_State *L)
6281{
6282 struct stream *s;
6283 struct http_msg *msg;
6284 const char *name;
6285 size_t name_len;
6286
6287 MAY_LJMP(check_args(L, 2, "set_path"));
6288 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6289 name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
6290
6291 if ((msg->chn->flags & CF_ISRESP) || msg->msg_state > HTTP_MSG_BODY)
6292 WILL_LJMP(lua_error(L));
6293
6294 s = chn_strm(msg->chn);
6295 lua_pushboolean(L, http_req_replace_stline(1, name, name_len, s->be, s) != -1);
6296 return 1;
6297}
6298
6299/* Rewrites the request query-string. It relies on http_req_replace_stline(). */
6300__LJMP static int hlua_http_msg_set_query(lua_State *L)
6301{
6302 struct stream *s;
6303 struct http_msg *msg;
6304 const char *name;
6305 size_t name_len;
6306
6307 MAY_LJMP(check_args(L, 2, "set_query"));
6308 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6309 name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
6310
6311 if ((msg->chn->flags & CF_ISRESP) || msg->msg_state > HTTP_MSG_BODY)
6312 WILL_LJMP(lua_error(L));
6313
6314 /* Check length. */
6315 if (name_len > trash.size - 1) {
6316 lua_pushboolean(L, 0);
6317 return 1;
6318 }
6319
6320 /* Add the mark question as prefix. */
6321 chunk_reset(&trash);
6322 trash.area[trash.data++] = '?';
6323 memcpy(trash.area + trash.data, name, name_len);
6324 trash.data += name_len;
6325
6326 s = chn_strm(msg->chn);
6327 lua_pushboolean(L, http_req_replace_stline(2, trash.area, trash.data, s->be, s) != -1);
6328 return 1;
6329}
6330
6331/* Rewrites the request URI. It relies on http_req_replace_stline(). */
6332__LJMP static int hlua_http_msg_set_uri(lua_State *L)
6333{
6334 struct stream *s;
6335 struct http_msg *msg;
6336 const char *name;
6337 size_t name_len;
6338
6339 MAY_LJMP(check_args(L, 2, "set_uri"));
6340 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6341 name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
6342
6343 if ((msg->chn->flags & CF_ISRESP) || msg->msg_state > HTTP_MSG_BODY)
6344 WILL_LJMP(lua_error(L));
6345
6346 s = chn_strm(msg->chn);
6347 lua_pushboolean(L, http_req_replace_stline(3, name, name_len, s->be, s) != -1);
6348 return 1;
6349}
6350
6351/* Rewrites the response status code. It relies on http_res_set_status(). */
6352__LJMP static int hlua_http_msg_set_status(lua_State *L)
6353{
6354 struct http_msg *msg;
6355 unsigned int code;
6356 const char *reason;
6357 size_t reason_len;
6358
6359 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6360 code = MAY_LJMP(luaL_checkinteger(L, 2));
6361 reason = MAY_LJMP(luaL_optlstring(L, 3, NULL, &reason_len));
6362
6363 if (!(msg->chn->flags & CF_ISRESP) || msg->msg_state > HTTP_MSG_BODY)
6364 WILL_LJMP(lua_error(L));
6365
6366 lua_pushboolean(L, http_res_set_status(code, ist2(reason, reason_len), chn_strm(msg->chn)) != -1);
6367 return 1;
6368}
6369
6370/* Returns true if the HTTP message is full. */
6371__LJMP static int hlua_http_msg_is_full(lua_State *L)
6372{
6373 struct http_msg *msg;
6374
6375 MAY_LJMP(check_args(L, 1, "is_full"));
6376 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6377 lua_pushboolean(L, channel_full(msg->chn, 0));
6378 return 1;
6379}
6380
6381/* Returns true if the HTTP message may still receive data. */
6382__LJMP static int hlua_http_msg_may_recv(lua_State *L)
6383{
6384 struct http_msg *msg;
6385 struct htx *htx;
6386
6387 MAY_LJMP(check_args(L, 1, "may_recv"));
6388 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6389 htx = htxbuf(&msg->chn->buf);
6390 lua_pushboolean(L, (htx_expect_more(htx) && !channel_input_closed(msg->chn) && channel_may_recv(msg->chn)));
6391 return 1;
6392}
6393
6394/* Returns true if the HTTP message EOM was received */
6395__LJMP static int hlua_http_msg_is_eom(lua_State *L)
6396{
6397 struct http_msg *msg;
6398 struct htx *htx;
6399
6400 MAY_LJMP(check_args(L, 1, "may_recv"));
6401 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6402 htx = htxbuf(&msg->chn->buf);
6403 lua_pushboolean(L, !htx_expect_more(htx));
6404 return 1;
6405}
6406
6407/* Returns the number of bytes available in the input side of the HTTP
6408 * message. This function never fails.
6409 */
6410__LJMP static int hlua_http_msg_get_in_len(lua_State *L)
6411{
6412 struct http_msg *msg;
Christopher Fauleteae8afa2020-02-26 17:15:48 +01006413 size_t output, input;
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006414
6415 MAY_LJMP(check_args(L, 1, "input"));
6416 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
Christopher Fauleteae8afa2020-02-26 17:15:48 +01006417 hlua_http_msg_filter(L, 1, msg, &output, &input);
6418 lua_pushinteger(L, input);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006419 return 1;
6420}
6421
6422/* Returns the number of bytes available in the output side of the HTTP
6423 * message. This function never fails.
6424 */
6425__LJMP static int hlua_http_msg_get_out_len(lua_State *L)
6426{
6427 struct http_msg *msg;
Christopher Fauleteae8afa2020-02-26 17:15:48 +01006428 size_t output, input;
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006429
6430 MAY_LJMP(check_args(L, 1, "output"));
6431 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
Christopher Fauleteae8afa2020-02-26 17:15:48 +01006432 hlua_http_msg_filter(L, 1, msg, &output, &input);
6433 lua_pushinteger(L, output);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006434 return 1;
6435}
6436
6437/* Copies at most <len> bytes of DATA blocks from the HTTP message <msg>
6438 * starting at the offset <offset> and put it in a string LUA variables. It
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006439 * returns the built string length. It stops on the first non-DATA HTX
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006440 * block. This function is called during the payload filtering, so the headers
6441 * are already scheduled for output (from the filter point of view).
6442 */
6443static int _hlua_http_msg_dup(struct http_msg *msg, lua_State *L, size_t offset, size_t len)
6444{
6445 struct htx *htx = htxbuf(&msg->chn->buf);
6446 struct htx_blk *blk;
6447 struct htx_ret htxret;
6448 luaL_Buffer b;
6449 int ret = 0;
6450
6451 luaL_buffinit(L, &b);
6452 htxret = htx_find_offset(htx, offset);
6453 for (blk = htxret.blk, offset = htxret.ret; blk && len; blk = htx_get_next_blk(htx, blk)) {
6454 enum htx_blk_type type = htx_get_blk_type(blk);
6455 struct ist v;
6456
6457 switch (type) {
6458 case HTX_BLK_UNUSED:
6459 break;
6460
6461 case HTX_BLK_DATA:
6462 v = htx_get_blk_value(htx, blk);
Tim Duesterhusb113b5c2021-09-15 13:58:44 +02006463 v = istadv(v, offset);
Tim Duesterhus2471f5c2021-11-08 09:05:01 +01006464 v = isttrim(v, len);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006465
6466 luaL_addlstring(&b, v.ptr, v.len);
6467 ret += v.len;
6468 break;
6469
6470 default:
vishnu0af4bd72021-10-24 06:46:24 +05306471 if (!ret)
6472 goto no_data;
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006473 goto end;
6474 }
6475 offset = 0;
6476 }
6477
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006478end:
vishnu0af4bd72021-10-24 06:46:24 +05306479 if (!ret && (htx->flags & HTX_FL_EOM))
6480 goto no_data;
6481 luaL_pushresult(&b);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006482 return ret;
vishnu0af4bd72021-10-24 06:46:24 +05306483
6484 no_data:
6485 /* Remove the empty string and push nil on the stack */
6486 lua_pop(L, 1);
6487 lua_pushnil(L);
6488 return 0;
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006489}
6490
6491/* Copies the string <str> to the HTTP message <msg> at the offset
6492 * <offset>. This function returns -1 if data cannot be copied. Otherwise, it
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006493 * returns the amount of data written. This function is responsible to update
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006494 * the filter context.
6495 */
6496static int _hlua_http_msg_insert(struct http_msg *msg, struct filter *filter, struct ist str, size_t offset)
6497{
6498 struct htx *htx = htx_from_buf(&msg->chn->buf);
6499 struct htx_ret htxret;
6500 int /*max, */ret = 0;
6501
6502 /* Nothing to do, just return */
6503 if (unlikely(istlen(str) == 0))
6504 goto end;
6505
6506 if (istlen(str) > htx_free_data_space(htx)) {
6507 ret = -1;
6508 goto end;
6509 }
6510
6511 htxret = htx_find_offset(htx, offset);
6512 if (!htxret.blk || htx_get_blk_type(htxret.blk) != HTX_BLK_DATA) {
6513 if (!htx_add_last_data(htx, str))
6514 goto end;
6515 }
6516 else {
6517 struct ist v = htx_get_blk_value(htx, htxret.blk);
6518 v.ptr += htxret.ret;
6519 v.len = 0;
6520 if (!htx_replace_blk_value(htx, htxret.blk, v, str))
6521 goto end;
6522 }
6523 ret = str.len;
6524 if (ret) {
6525 struct hlua_flt_ctx *flt_ctx = filter->ctx;
6526 flt_update_offsets(filter, msg->chn, ret);
6527 flt_ctx->cur_len[CHN_IDX(msg->chn)] += ret;
6528 }
6529
6530 end:
6531 htx_to_buf(htx, &msg->chn->buf);
6532 return ret;
6533}
6534
6535/* Helper function removing at most <len> bytes of DATA blocks at the absolute
6536 * position <offset>. It stops on the first non-DATA HTX block. This function is
6537 * called during the payload filtering, so the headers are already scheduled for
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006538 * output (from the filter point of view). This function is responsible to
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006539 * update the filter context.
6540 */
6541static void _hlua_http_msg_delete(struct http_msg *msg, struct filter *filter, size_t offset, size_t len)
6542{
6543 struct hlua_flt_ctx *flt_ctx = filter->ctx;
6544 struct htx *htx = htx_from_buf(&msg->chn->buf);
6545 struct htx_blk *blk;
6546 struct htx_ret htxret;
6547 size_t ret = 0;
6548
6549 /* Be sure <len> is always the amount of DATA to remove */
6550 if (htx->data == offset+len && htx_get_tail_type(htx) == HTX_BLK_DATA) {
Aurelien DARRAGONbcbcf982022-09-28 19:08:15 +02006551 /* When htx tail type == HTX_BLK_DATA, no need to take care
6552 * of special blocks like HTX_BLK_EOT.
6553 * We simply truncate after offset
6554 * (truncate targeted blk and discard the following ones)
6555 */
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006556 htx_truncate(htx, offset);
6557 ret = len;
6558 goto end;
6559 }
6560
6561 htxret = htx_find_offset(htx, offset);
6562 blk = htxret.blk;
6563 if (htxret.ret) {
Aurelien DARRAGONbcbcf982022-09-28 19:08:15 +02006564 /* dealing with offset: we need to trim targeted blk */
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006565 struct ist v;
6566
6567 if (htx_get_blk_type(blk) != HTX_BLK_DATA)
6568 goto end;
Aurelien DARRAGONbcbcf982022-09-28 19:08:15 +02006569
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006570 v = htx_get_blk_value(htx, blk);
Tim Duesterhusa029d782022-10-08 12:33:18 +02006571 v = istadv(v, htxret.ret);
Aurelien DARRAGONbcbcf982022-09-28 19:08:15 +02006572
Tim Duesterhus2471f5c2021-11-08 09:05:01 +01006573 v = isttrim(v, len);
Aurelien DARRAGONbcbcf982022-09-28 19:08:15 +02006574 /* trimming data in blk: discard everything after the offset
6575 * (replace 'v' with 'IST_NULL')
6576 */
Tim Duesterhusb113b5c2021-09-15 13:58:44 +02006577 blk = htx_replace_blk_value(htx, blk, v, IST_NULL);
Aurelien DARRAGONbcbcf982022-09-28 19:08:15 +02006578 if (blk && v.len < len) {
6579 /* In this case, caller wants to keep removing data,
6580 * but we need to spare current blk
6581 * because it was already trimmed
6582 */
6583 blk = htx_get_next_blk(htx, blk);
6584 }
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006585 len -= v.len;
6586 ret += v.len;
6587 }
6588
6589
6590 while (blk && len) {
Aurelien DARRAGONbcbcf982022-09-28 19:08:15 +02006591 /* there is more data that needs to be discarded */
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006592 enum htx_blk_type type = htx_get_blk_type(blk);
6593 uint32_t sz = htx_get_blksz(blk);
6594
6595 switch (type) {
6596 case HTX_BLK_UNUSED:
6597 break;
6598
6599 case HTX_BLK_DATA:
6600 if (len < sz) {
Aurelien DARRAGONbcbcf982022-09-28 19:08:15 +02006601 /* don't discard whole blk, only part of it
6602 * (from the beginning)
6603 */
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006604 htx_cut_data_blk(htx, blk, len);
6605 ret += len;
6606 goto end;
6607 }
6608 break;
6609
6610 default:
Aurelien DARRAGONbcbcf982022-09-28 19:08:15 +02006611 /* HTX_BLK_EOT blk won't be removed */
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006612 goto end;
6613 }
6614
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006615 /* Remove all the data block */
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006616 len -= sz;
6617 ret += sz;
6618 blk = htx_remove_blk(htx, blk);
6619 }
6620
6621end:
6622 flt_update_offsets(filter, msg->chn, -ret);
6623 flt_ctx->cur_len[CHN_IDX(msg->chn)] -= ret;
6624 /* WARNING: we don't call htx_to_buf() on purpose, because we don't want
6625 * to loose the EOM flag if the message is empty.
6626 */
6627}
6628
6629/* Copies input data found in an HTTP message. Unlike the channel function used
6630 * to duplicate raw data, this one can only be called inside a filter, from
6631 * http_payload callback. So it cannot yield. An exception is returned if it is
6632 * called from another callback. If nothing was copied, a nil value is pushed on
6633 * the stack.
6634 */
6635__LJMP static int hlua_http_msg_get_body(lua_State *L)
6636{
6637 struct http_msg *msg;
6638 struct filter *filter;
6639 size_t output, input;
6640 int offset, len;
6641
6642 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
6643 WILL_LJMP(luaL_error(L, "'data' expects at most 2 arguments"));
6644 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6645
6646 if (msg->msg_state < HTTP_MSG_DATA)
6647 WILL_LJMP(lua_error(L));
6648
6649 filter = hlua_http_msg_filter(L, 1, msg, &output, &input);
6650 if (!filter || !hlua_filter_from_payload(filter))
6651 WILL_LJMP(lua_error(L));
6652
6653 if (!ci_data(msg->chn) && channel_input_closed(msg->chn)) {
6654 lua_pushnil(L);
6655 return 1;
6656 }
6657
6658 offset = output;
6659 if (lua_gettop(L) > 1) {
6660 offset = MAY_LJMP(luaL_checkinteger(L, 2));
6661 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02006662 offset = MAX(0, (int)input + offset);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006663 offset += output;
6664 if (offset < output || offset > input + output) {
6665 lua_pushfstring(L, "offset out of range.");
6666 WILL_LJMP(lua_error(L));
6667 }
6668 }
6669 len = output + input - offset;
6670 if (lua_gettop(L) == 3) {
6671 len = MAY_LJMP(luaL_checkinteger(L, 3));
6672 if (!len)
6673 goto dup;
6674 if (len == -1)
6675 len = global.tune.bufsize;
6676 if (len < 0) {
6677 lua_pushfstring(L, "length out of range.");
6678 WILL_LJMP(lua_error(L));
6679 }
6680 }
6681
6682 dup:
6683 _hlua_http_msg_dup(msg, L, offset, len);
6684 return 1;
6685}
6686
6687/* Appends a string to the HTTP message, after all existing DATA blocks but
6688 * before the trailers, if any. It returns the amount of data written or -1 if
6689 * nothing was copied. Unlike the channel function used to append data, this one
6690 * can only be called inside a filter, from http_payload callback. So it cannot
6691 * yield. An exception is returned if it is called from another callback.
6692 */
6693__LJMP static int hlua_http_msg_append(lua_State *L)
6694{
6695 struct http_msg *msg;
6696 struct filter *filter;
6697 const char *str;
6698 size_t offset, len, sz;
6699 int ret;
6700
6701 MAY_LJMP(check_args(L, 2, "append"));
6702 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6703
6704 if (msg->msg_state < HTTP_MSG_DATA)
6705 WILL_LJMP(lua_error(L));
6706
6707 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
6708 filter = hlua_http_msg_filter(L, 1, msg, &offset, &len);
6709 if (!filter || !hlua_filter_from_payload(filter))
6710 WILL_LJMP(lua_error(L));
6711
6712 ret = _hlua_http_msg_insert(msg, filter, ist2(str, sz), offset+len);
6713 lua_pushinteger(L, ret);
6714 return 1;
6715}
6716
6717/* Prepends a string to the HTTP message, before all existing DATA blocks. It
6718 * returns the amount of data written or -1 if nothing was copied. Unlike the
6719 * channel function used to prepend data, this one can only be called inside a
6720 * filter, from http_payload callback. So it cannot yield. An exception is
6721 * returned if it is called from another callback.
6722 */
6723__LJMP static int hlua_http_msg_prepend(lua_State *L)
6724{
6725 struct http_msg *msg;
6726 struct filter *filter;
6727 const char *str;
6728 size_t offset, len, sz;
6729 int ret;
6730
6731 MAY_LJMP(check_args(L, 2, "prepend"));
6732 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006733
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006734 if (msg->msg_state < HTTP_MSG_DATA)
6735 WILL_LJMP(lua_error(L));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006736
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006737 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
6738 filter = hlua_http_msg_filter(L, 1, msg, &offset, &len);
6739 if (!filter || !hlua_filter_from_payload(filter))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006740 WILL_LJMP(lua_error(L));
6741
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006742 ret = _hlua_http_msg_insert(msg, filter, ist2(str, sz), offset);
6743 lua_pushinteger(L, ret);
6744 return 1;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006745}
6746
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006747/* Inserts a string to the HTTP message at a given offset. By default the string
6748 * is appended at the end of DATA blocks. It returns the amount of data written
6749 * or -1 if nothing was copied. Unlike the channel function used to insert data,
6750 * this one can only be called inside a filter, from http_payload callback. So
6751 * it cannot yield. An exception is returned if it is called from another
6752 * callback.
6753 */
6754__LJMP static int hlua_http_msg_insert_data(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006755{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006756 struct http_msg *msg;
6757 struct filter *filter;
6758 const char *str;
6759 size_t input, output, sz;
6760 int offset;
6761 int ret;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006762
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006763 if (lua_gettop(L) < 2 || lua_gettop(L) > 3)
6764 WILL_LJMP(luaL_error(L, "'insert' expects at least 1 argument and at most 2 arguments"));
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006765 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006766
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006767 if (msg->msg_state < HTTP_MSG_DATA)
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006768 WILL_LJMP(lua_error(L));
6769
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006770 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
Aurelien DARRAGON7fdba0a2022-09-28 16:03:45 +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 DARRAGON7fdba0a2022-09-28 16:03:45 +02006775 offset = output;
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006776 if (lua_gettop(L) > 2) {
6777 offset = MAY_LJMP(luaL_checkinteger(L, 3));
6778 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 DARRAGON7fdba0a2022-09-28 16:03:45 +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 ret = _hlua_http_msg_insert(msg, filter, ist2(str, sz), offset);
6788 lua_pushinteger(L, ret);
6789 return 1;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006790}
6791
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006792/* Removes a given amount of data from the HTTP message at a given offset. By
6793 * default all DATA blocks are removed. It returns the amount of data
6794 * removed. Unlike the channel function used to remove data, this one can only
6795 * be called inside a filter, from http_payload callback. So it cannot yield. An
6796 * exception is returned if it is called from another callback.
6797 */
6798__LJMP static int hlua_http_msg_del_data(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006799{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006800 struct http_msg *msg;
6801 struct filter *filter;
6802 size_t input, output;
6803 int offset, len;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006804
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006805 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
Boyang Lie0c54352022-05-10 17:47:23 +00006806 WILL_LJMP(luaL_error(L, "'remove' expects at most 2 arguments"));
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006807 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006808
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006809 if (msg->msg_state < HTTP_MSG_DATA)
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006810 WILL_LJMP(lua_error(L));
6811
Aurelien DARRAGONd7c71b02022-09-28 15:52:18 +02006812 filter = hlua_http_msg_filter(L, 1, msg, &output, &input);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006813 if (!filter || !hlua_filter_from_payload(filter))
6814 WILL_LJMP(lua_error(L));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006815
Aurelien DARRAGONd7c71b02022-09-28 15:52:18 +02006816 offset = output;
Boyang Lie0c54352022-05-10 17:47:23 +00006817 if (lua_gettop(L) > 1) {
6818 offset = MAY_LJMP(luaL_checkinteger(L, 2));
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006819 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02006820 offset = MAX(0, (int)input + offset);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006821 offset += output;
Aurelien DARRAGONd7c71b02022-09-28 15:52:18 +02006822 if (offset > output + input) {
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006823 lua_pushfstring(L, "offset out of range.");
6824 WILL_LJMP(lua_error(L));
6825 }
6826 }
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006827
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006828 len = output + input - offset;
Boyang Lie0c54352022-05-10 17:47:23 +00006829 if (lua_gettop(L) == 3) {
6830 len = MAY_LJMP(luaL_checkinteger(L, 3));
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006831 if (!len)
6832 goto end;
6833 if (len == -1)
6834 len = output + input - offset;
6835 if (len < 0 || offset + len > output + input) {
6836 lua_pushfstring(L, "length out of range.");
6837 WILL_LJMP(lua_error(L));
6838 }
6839 }
6840
6841 _hlua_http_msg_delete(msg, filter, offset, len);
6842
6843 end:
6844 lua_pushinteger(L, len);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006845 return 1;
6846}
6847
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006848/* Replaces a given amount of data at the given offset by a string. By default,
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006849 * all remaining data are removed, accordingly to the filter context. It returns
6850 * the amount of data written or -1 if nothing was copied. Unlike the channel
6851 * function used to replace data, this one can only be called inside a filter,
6852 * from http_payload callback. So it cannot yield. An exception is returned if
6853 * it is called from another callback.
6854 */
6855__LJMP static int hlua_http_msg_set_data(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006856{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006857 struct http_msg *msg;
6858 struct filter *filter;
6859 struct htx *htx;
6860 const char *str;
6861 size_t input, output, sz;
6862 int offset, len;
6863 int ret;
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02006864
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006865 if (lua_gettop(L) < 2 || lua_gettop(L) > 4)
6866 WILL_LJMP(luaL_error(L, "'set' expects at least 1 argument and at most 3 arguments"));
6867 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6868
6869 if (msg->msg_state < HTTP_MSG_DATA)
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006870 WILL_LJMP(lua_error(L));
6871
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006872 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
6873 filter = hlua_http_msg_filter(L, 1, msg, &output, &input);
6874 if (!filter || !hlua_filter_from_payload(filter))
6875 WILL_LJMP(lua_error(L));
6876
6877 offset = output;
6878 if (lua_gettop(L) > 2) {
6879 offset = MAY_LJMP(luaL_checkinteger(L, 3));
6880 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02006881 offset = MAX(0, (int)input + offset);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006882 offset += output;
6883 if (offset < output || offset > input + output) {
6884 lua_pushfstring(L, "offset out of range.");
6885 WILL_LJMP(lua_error(L));
6886 }
6887 }
6888
6889 len = output + input - offset;
6890 if (lua_gettop(L) == 4) {
6891 len = MAY_LJMP(luaL_checkinteger(L, 4));
6892 if (!len)
6893 goto set;
6894 if (len == -1)
6895 len = output + input - offset;
6896 if (len < 0 || offset + len > output + input) {
6897 lua_pushfstring(L, "length out of range.");
6898 WILL_LJMP(lua_error(L));
6899 }
6900 }
6901
6902 set:
6903 /* Be sure we can copied the string once input data will be removed. */
6904 htx = htx_from_buf(&msg->chn->buf);
6905 if (sz > htx_free_data_space(htx) + len)
6906 lua_pushinteger(L, -1);
6907 else {
6908 _hlua_http_msg_delete(msg, filter, offset, len);
6909 ret = _hlua_http_msg_insert(msg, filter, ist2(str, sz), offset);
6910 lua_pushinteger(L, ret);
6911 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006912 return 1;
6913}
6914
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006915/* Prepends data into an HTTP message and forward it, from the filter point of
6916 * view. It returns the amount of data written or -1 if nothing was sent. Unlike
6917 * the channel function used to send data, this one can only be called inside a
6918 * filter, from http_payload callback. So it cannot yield. An exception is
6919 * returned if it is called from another callback.
6920 */
6921__LJMP static int hlua_http_msg_send(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006922{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006923 struct http_msg *msg;
6924 struct filter *filter;
6925 struct htx *htx;
6926 const char *str;
6927 size_t offset, len, sz;
6928 int ret;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006929
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006930 MAY_LJMP(check_args(L, 2, "send"));
6931 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6932
6933 if (msg->msg_state < HTTP_MSG_DATA)
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006934 WILL_LJMP(lua_error(L));
6935
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006936 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
6937 filter = hlua_http_msg_filter(L, 1, msg, &offset, &len);
6938 if (!filter || !hlua_filter_from_payload(filter))
6939 WILL_LJMP(lua_error(L));
6940
6941 /* Return an error if the channel's output is closed */
6942 if (unlikely(channel_output_closed(msg->chn))) {
6943 lua_pushinteger(L, -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006944 return 1;
6945 }
6946
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006947 htx = htx_from_buf(&msg->chn->buf);
6948 if (sz > htx_free_data_space(htx)) {
6949 lua_pushinteger(L, -1);
6950 return 1;
6951 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006952
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006953 ret = _hlua_http_msg_insert(msg, filter, ist2(str, sz), offset);
6954 if (ret > 0) {
6955 struct hlua_flt_ctx *flt_ctx = filter->ctx;
6956
6957 FLT_OFF(filter, msg->chn) += ret;
6958 flt_ctx->cur_len[CHN_IDX(msg->chn)] -= ret;
6959 flt_ctx->cur_off[CHN_IDX(msg->chn)] += ret;
6960 }
6961
6962 lua_pushinteger(L, ret);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006963 return 1;
6964}
6965
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006966/* Forwards a given amount of bytes. It return -1 if the channel's output is
6967 * closed. Otherwise, it returns the number of bytes forwarded. Unlike the
6968 * channel function used to forward data, this one can only be called inside a
6969 * filter, from http_payload callback. So it cannot yield. An exception is
6970 * returned if it is called from another callback. All other functions deal with
6971 * DATA block, this one not.
6972*/
6973__LJMP static int hlua_http_msg_forward(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006974{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006975 struct http_msg *msg;
6976 struct filter *filter;
6977 size_t offset, len;
6978 int fwd, ret = 0;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006979
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006980 MAY_LJMP(check_args(L, 2, "forward"));
6981 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6982
6983 if (msg->msg_state < HTTP_MSG_DATA)
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006984 WILL_LJMP(lua_error(L));
6985
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006986 fwd = MAY_LJMP(luaL_checkinteger(L, 2));
6987 filter = hlua_http_msg_filter(L, 1, msg, &offset, &len);
6988 if (!filter || !hlua_filter_from_payload(filter))
6989 WILL_LJMP(lua_error(L));
6990
6991 /* Nothing to do, just return */
6992 if (!fwd)
6993 goto end;
6994
6995 /* Return an error if the channel's output is closed */
6996 if (unlikely(channel_output_closed(msg->chn))) {
6997 ret = -1;
6998 goto end;
6999 }
7000
7001 ret = fwd;
7002 if (ret > len)
7003 ret = len;
7004
7005 if (ret) {
7006 struct hlua_flt_ctx *flt_ctx = filter->ctx;
7007
7008 FLT_OFF(filter, msg->chn) += ret;
7009 flt_ctx->cur_off[CHN_IDX(msg->chn)] += ret;
7010 flt_ctx->cur_len[CHN_IDX(msg->chn)] -= ret;
7011 }
7012
7013 end:
7014 lua_pushinteger(L, ret);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007015 return 1;
7016}
7017
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007018/* Set EOM flag on the HTX message.
7019 *
7020 * NOTE: Not sure it is a good idea to manipulate this flag but for now I don't
7021 * really know how to do without this feature.
7022 */
7023__LJMP static int hlua_http_msg_set_eom(lua_State *L)
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02007024{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007025 struct http_msg *msg;
7026 struct htx *htx;
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02007027
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007028 MAY_LJMP(check_args(L, 1, "set_eom"));
7029 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
7030 htx = htxbuf(&msg->chn->buf);
7031 htx->flags |= HTX_FL_EOM;
7032 return 0;
7033}
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02007034
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007035/* Unset EOM flag on the HTX message.
7036 *
7037 * NOTE: Not sure it is a good idea to manipulate this flag but for now I don't
7038 * really know how to do without this feature.
7039 */
7040__LJMP static int hlua_http_msg_unset_eom(lua_State *L)
7041{
7042 struct http_msg *msg;
7043 struct htx *htx;
7044
7045 MAY_LJMP(check_args(L, 1, "set_eom"));
7046 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
7047 htx = htxbuf(&msg->chn->buf);
7048 htx->flags &= ~HTX_FL_EOM;
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02007049 return 0;
7050}
7051
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007052/*
7053 *
7054 *
William Lallemand3956c4e2021-09-21 16:25:15 +02007055 * Class HTTPClient
7056 *
7057 *
7058 */
7059__LJMP static struct hlua_httpclient *hlua_checkhttpclient(lua_State *L, int ud)
7060{
7061 return MAY_LJMP(hlua_checkudata(L, ud, class_httpclient_ref));
7062}
7063
William Lallemandf77f1de2021-09-28 19:10:38 +02007064
7065/* stops the httpclient and ask it to kill itself */
7066__LJMP static int hlua_httpclient_gc(lua_State *L)
7067{
7068 struct hlua_httpclient *hlua_hc;
7069
7070 MAY_LJMP(check_args(L, 1, "__gc"));
7071
7072 hlua_hc = MAY_LJMP(hlua_checkhttpclient(L, 1));
7073
Aurelien DARRAGON3ffbf382023-02-09 17:02:57 +01007074 if (MT_LIST_DELETE(&hlua_hc->by_hlua)) {
7075 /* we won the race against hlua_httpclient_destroy_all() */
William Lallemandbb581422022-10-20 10:57:28 +02007076 httpclient_stop_and_destroy(hlua_hc->hc);
Aurelien DARRAGON3ffbf382023-02-09 17:02:57 +01007077 hlua_hc->hc = NULL;
7078 }
William Lallemandf77f1de2021-09-28 19:10:38 +02007079
7080 return 0;
7081}
7082
7083
William Lallemand3956c4e2021-09-21 16:25:15 +02007084__LJMP static int hlua_httpclient_new(lua_State *L)
7085{
7086 struct hlua_httpclient *hlua_hc;
7087 struct hlua *hlua;
7088
7089 /* Get hlua struct, or NULL if we execute from main lua state */
7090 hlua = hlua_gethlua(L);
7091 if (!hlua)
7092 return 0;
7093
7094 /* Check stack size. */
7095 if (!lua_checkstack(L, 3)) {
7096 hlua_pusherror(L, "httpclient: full stack");
7097 goto err;
7098 }
7099 /* Create the object: obj[0] = userdata. */
7100 lua_newtable(L);
7101 hlua_hc = MAY_LJMP(lua_newuserdata(L, sizeof(*hlua_hc)));
7102 lua_rawseti(L, -2, 0);
7103 memset(hlua_hc, 0, sizeof(*hlua_hc));
7104
7105 hlua_hc->hc = httpclient_new(hlua, 0, IST_NULL);
7106 if (!hlua_hc->hc)
7107 goto err;
7108
Aurelien DARRAGON3ffbf382023-02-09 17:02:57 +01007109 MT_LIST_APPEND(&hlua->hc_list, &hlua_hc->by_hlua);
William Lallemandbb581422022-10-20 10:57:28 +02007110
William Lallemand3956c4e2021-09-21 16:25:15 +02007111 /* Pop a class stream metatable and affect it to the userdata. */
7112 lua_rawgeti(L, LUA_REGISTRYINDEX, class_httpclient_ref);
7113 lua_setmetatable(L, -2);
7114
7115 return 1;
7116
7117 err:
7118 WILL_LJMP(lua_error(L));
7119 return 0;
7120}
7121
7122
7123/*
7124 * Callback of the httpclient, this callback wakes the lua task up, once the
7125 * httpclient receives some data
7126 *
7127 */
7128
William Lallemandbd5739e2021-10-28 15:41:38 +02007129static void hlua_httpclient_cb(struct httpclient *hc)
William Lallemand3956c4e2021-09-21 16:25:15 +02007130{
7131 struct hlua *hlua = hc->caller;
7132
7133 if (!hlua || !hlua->task)
7134 return;
7135
7136 task_wakeup(hlua->task, TASK_WOKEN_MSG);
7137}
7138
7139/*
William Lallemandd7df73a2021-09-23 17:54:00 +02007140 * Fill the lua stack with headers from the httpclient response
7141 * This works the same way as the hlua_http_get_headers() function
7142 */
7143__LJMP static int hlua_httpclient_get_headers(lua_State *L, struct hlua_httpclient *hlua_hc)
7144{
7145 struct http_hdr *hdr;
7146
7147 lua_newtable(L);
7148
William Lallemandef574b22021-10-05 16:19:31 +02007149 for (hdr = hlua_hc->hc->res.hdrs; hdr && isttest(hdr->n); hdr++) {
William Lallemandd7df73a2021-09-23 17:54:00 +02007150 struct ist n, v;
7151 int len;
7152
7153 n = hdr->n;
7154 v = hdr->v;
7155
7156 /* Check for existing entry:
7157 * assume that the table is on the top of the stack, and
7158 * push the key in the stack, the function lua_gettable()
7159 * perform the lookup.
7160 */
7161
7162 lua_pushlstring(L, n.ptr, n.len);
7163 lua_gettable(L, -2);
7164
7165 switch (lua_type(L, -1)) {
7166 case LUA_TNIL:
7167 /* Table not found, create it. */
7168 lua_pop(L, 1); /* remove the nil value. */
7169 lua_pushlstring(L, n.ptr, n.len); /* push the header name as key. */
7170 lua_newtable(L); /* create and push empty table. */
7171 lua_pushlstring(L, v.ptr, v.len); /* push header value. */
7172 lua_rawseti(L, -2, 0); /* index header value (pop it). */
7173 lua_rawset(L, -3); /* index new table with header name (pop the values). */
7174 break;
7175
7176 case LUA_TTABLE:
7177 /* Entry found: push the value in the table. */
7178 len = lua_rawlen(L, -1);
7179 lua_pushlstring(L, v.ptr, v.len); /* push header value. */
7180 lua_rawseti(L, -2, len+1); /* index header value (pop it). */
7181 lua_pop(L, 1); /* remove the table (it is stored in the main table). */
7182 break;
7183
7184 default:
7185 /* Other cases are errors. */
7186 hlua_pusherror(L, "internal error during the parsing of headers.");
7187 WILL_LJMP(lua_error(L));
7188 }
7189 }
7190 return 1;
7191}
7192
7193/*
William Lallemand746e6f32021-10-06 10:57:44 +02007194 * Allocate and return an array of http_hdr ist extracted from the <headers> lua table
7195 *
7196 * Caller must free the result
7197 */
7198struct http_hdr *hlua_httpclient_table_to_hdrs(lua_State *L)
7199{
7200 struct http_hdr hdrs[global.tune.max_http_hdr];
7201 struct http_hdr *result = NULL;
7202 uint32_t hdr_num = 0;
7203
7204 lua_pushnil(L);
7205 while (lua_next(L, -2) != 0) {
7206 struct ist name, value;
7207 const char *n, *v;
7208 size_t nlen, vlen;
7209
7210 if (!lua_isstring(L, -2) || !lua_istable(L, -1)) {
7211 /* Skip element if the key is not a string or if the value is not a table */
7212 goto next_hdr;
7213 }
7214
7215 n = lua_tolstring(L, -2, &nlen);
7216 name = ist2(n, nlen);
7217
7218 /* Loop on header's values */
7219 lua_pushnil(L);
7220 while (lua_next(L, -2)) {
7221 if (!lua_isstring(L, -1)) {
7222 /* Skip the value if it is not a string */
7223 goto next_value;
7224 }
7225
7226 v = lua_tolstring(L, -1, &vlen);
7227 value = ist2(v, vlen);
7228 name = ist2(n, nlen);
7229
7230 hdrs[hdr_num].n = istdup(name);
7231 hdrs[hdr_num].v = istdup(value);
7232
7233 hdr_num++;
7234
7235 next_value:
7236 lua_pop(L, 1);
7237 }
7238
7239 next_hdr:
7240 lua_pop(L, 1);
7241
7242 }
7243
7244 if (hdr_num) {
7245 /* alloc and copy the headers in the httpclient struct */
Tim Duesterhus16cc16d2021-11-06 15:14:45 +01007246 result = calloc((hdr_num + 1), sizeof(*result));
William Lallemand746e6f32021-10-06 10:57:44 +02007247 if (!result)
7248 goto skip_headers;
7249 memcpy(result, hdrs, sizeof(struct http_hdr) * (hdr_num + 1));
7250
7251 result[hdr_num].n = IST_NULL;
7252 result[hdr_num].v = IST_NULL;
7253 }
7254
7255skip_headers:
William Lallemand746e6f32021-10-06 10:57:44 +02007256
7257 return result;
7258}
7259
7260
William Lallemandbd5739e2021-10-28 15:41:38 +02007261/*
7262 * For each yield, checks if there is some data in the httpclient and push them
7263 * in the lua buffer, once the httpclient finished its job, push the result on
7264 * the stack
7265 */
7266__LJMP static int hlua_httpclient_rcv_yield(lua_State *L, int status, lua_KContext ctx)
7267{
7268 struct buffer *tr;
7269 int res;
7270 struct hlua *hlua = hlua_gethlua(L);
7271 struct hlua_httpclient *hlua_hc = hlua_checkhttpclient(L, 1);
7272
7273
7274 tr = get_trash_chunk();
7275
7276 res = httpclient_res_xfer(hlua_hc->hc, tr);
7277 luaL_addlstring(&hlua_hc->b, b_orig(tr), res);
7278
7279 if (!httpclient_data(hlua_hc->hc) && httpclient_ended(hlua_hc->hc)) {
7280
7281 luaL_pushresult(&hlua_hc->b);
7282 lua_settable(L, -3);
7283
7284 lua_pushstring(L, "status");
7285 lua_pushinteger(L, hlua_hc->hc->res.status);
7286 lua_settable(L, -3);
7287
7288
7289 lua_pushstring(L, "reason");
7290 lua_pushlstring(L, hlua_hc->hc->res.reason.ptr, hlua_hc->hc->res.reason.len);
7291 lua_settable(L, -3);
7292
7293 lua_pushstring(L, "headers");
7294 hlua_httpclient_get_headers(L, hlua_hc);
7295 lua_settable(L, -3);
7296
7297 return 1;
7298 }
7299
7300 if (httpclient_data(hlua_hc->hc))
7301 task_wakeup(hlua->task, TASK_WOKEN_MSG);
7302
7303 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_httpclient_rcv_yield, TICK_ETERNITY, 0));
7304
7305 return 0;
7306}
7307
7308/*
7309 * Call this when trying to stream a body during a request
7310 */
7311__LJMP static int hlua_httpclient_snd_yield(lua_State *L, int status, lua_KContext ctx)
7312{
7313 struct hlua *hlua;
7314 struct hlua_httpclient *hlua_hc = hlua_checkhttpclient(L, 1);
7315 const char *body_str = NULL;
7316 int ret;
7317 int end = 0;
7318 size_t buf_len;
7319 size_t to_send = 0;
7320
7321 hlua = hlua_gethlua(L);
7322
7323 if (!hlua || !hlua->task)
7324 WILL_LJMP(luaL_error(L, "The 'get' function is only allowed in "
7325 "'frontend', 'backend' or 'task'"));
7326
7327 ret = lua_getfield(L, -1, "body");
7328 if (ret != LUA_TSTRING)
7329 goto rcv;
7330
7331 body_str = lua_tolstring(L, -1, &buf_len);
7332 lua_pop(L, 1);
7333
Christopher Fauletfc591292022-01-12 14:46:03 +01007334 to_send = buf_len - hlua_hc->sent;
William Lallemandbd5739e2021-10-28 15:41:38 +02007335
7336 if ((hlua_hc->sent + to_send) >= buf_len)
7337 end = 1;
7338
7339 /* the end flag is always set since we are using the whole remaining size */
7340 hlua_hc->sent += httpclient_req_xfer(hlua_hc->hc, ist2(body_str + hlua_hc->sent, to_send), end);
7341
7342 if (buf_len > hlua_hc->sent) {
7343 /* still need to process the buffer */
7344 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_httpclient_snd_yield, TICK_ETERNITY, 0));
7345 } else {
7346 goto rcv;
7347 /* we sent the whole request buffer we can recv */
7348 }
7349 return 0;
7350
7351rcv:
7352
7353 /* we return a "res" object */
7354 lua_newtable(L);
7355
William Lallemandbd5739e2021-10-28 15:41:38 +02007356 lua_pushstring(L, "body");
William Lallemandd1187eb2021-11-02 10:40:06 +01007357 luaL_buffinit(L, &hlua_hc->b);
William Lallemandbd5739e2021-10-28 15:41:38 +02007358
William Lallemand933fe392021-11-04 09:45:58 +01007359 task_wakeup(hlua->task, TASK_WOKEN_MSG);
William Lallemandbd5739e2021-10-28 15:41:38 +02007360 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_httpclient_rcv_yield, TICK_ETERNITY, 0));
7361
7362 return 1;
7363}
William Lallemand746e6f32021-10-06 10:57:44 +02007364
William Lallemand3956c4e2021-09-21 16:25:15 +02007365/*
William Lallemanddc2cc902021-10-26 11:43:26 +02007366 * Send an HTTP request and wait for a response
William Lallemand3956c4e2021-09-21 16:25:15 +02007367 */
7368
William Lallemanddc2cc902021-10-26 11:43:26 +02007369__LJMP static int hlua_httpclient_send(lua_State *L, enum http_meth_t meth)
William Lallemand3956c4e2021-09-21 16:25:15 +02007370{
7371 struct hlua_httpclient *hlua_hc;
William Lallemand746e6f32021-10-06 10:57:44 +02007372 struct http_hdr *hdrs = NULL;
7373 struct http_hdr *hdrs_i = NULL;
William Lallemand3956c4e2021-09-21 16:25:15 +02007374 struct hlua *hlua;
William Lallemand746e6f32021-10-06 10:57:44 +02007375 const char *url_str = NULL;
William Lallemanddec25c32021-10-25 19:48:37 +02007376 const char *body_str = NULL;
Christopher Faulet380ae9c2022-10-14 14:57:04 +02007377 size_t buf_len = 0;
William Lallemand746e6f32021-10-06 10:57:44 +02007378 int ret;
William Lallemand3956c4e2021-09-21 16:25:15 +02007379
7380 hlua = hlua_gethlua(L);
7381
7382 if (!hlua || !hlua->task)
7383 WILL_LJMP(luaL_error(L, "The 'get' function is only allowed in "
7384 "'frontend', 'backend' or 'task'"));
7385
William Lallemand746e6f32021-10-06 10:57:44 +02007386 if (lua_gettop(L) != 2 || lua_type(L, -1) != LUA_TTABLE)
7387 WILL_LJMP(luaL_error(L, "'get' needs a table as argument"));
7388
William Lallemand4f4f2b72022-02-17 20:00:23 +01007389 hlua_hc = hlua_checkhttpclient(L, 1);
7390
William Lallemand7177a952022-03-03 15:33:12 +01007391 lua_pushnil(L); /* first key */
7392 while (lua_next(L, 2)) {
7393 if (strcmp(lua_tostring(L, -2), "dst") == 0) {
7394 if (httpclient_set_dst(hlua_hc->hc, lua_tostring(L, -1)) < 0)
7395 WILL_LJMP(luaL_error(L, "Can't use the 'dst' argument"));
William Lallemand4f4f2b72022-02-17 20:00:23 +01007396
William Lallemand7177a952022-03-03 15:33:12 +01007397 } else if (strcmp(lua_tostring(L, -2), "url") == 0) {
7398 if (lua_type(L, -1) != LUA_TSTRING)
7399 WILL_LJMP(luaL_error(L, "invalid parameter in 'url', must be a string"));
7400 url_str = lua_tostring(L, -1);
William Lallemand3956c4e2021-09-21 16:25:15 +02007401
William Lallemand7177a952022-03-03 15:33:12 +01007402 } else if (strcmp(lua_tostring(L, -2), "timeout") == 0) {
7403 if (lua_type(L, -1) != LUA_TNUMBER)
7404 WILL_LJMP(luaL_error(L, "invalid parameter in 'timeout', must be a number"));
7405 httpclient_set_timeout(hlua_hc->hc, lua_tointeger(L, -1));
William Lallemandb4a4ef62022-02-23 14:18:16 +01007406
William Lallemand7177a952022-03-03 15:33:12 +01007407 } else if (strcmp(lua_tostring(L, -2), "headers") == 0) {
7408 if (lua_type(L, -1) != LUA_TTABLE)
7409 WILL_LJMP(luaL_error(L, "invalid parameter in 'headers', must be a table"));
7410 hdrs = hlua_httpclient_table_to_hdrs(L);
William Lallemand79416cb2021-09-24 14:51:44 +02007411
William Lallemand7177a952022-03-03 15:33:12 +01007412 } else if (strcmp(lua_tostring(L, -2), "body") == 0) {
7413 if (lua_type(L, -1) != LUA_TSTRING)
7414 WILL_LJMP(luaL_error(L, "invalid parameter in 'body', must be a string"));
7415 body_str = lua_tolstring(L, -1, &buf_len);
William Lallemandbd5739e2021-10-28 15:41:38 +02007416
William Lallemand7177a952022-03-03 15:33:12 +01007417 } else {
7418 WILL_LJMP(luaL_error(L, "'%s' invalid parameter name", lua_tostring(L, -2)));
7419 }
7420 /* removes 'value'; keeps 'key' for next iteration */
7421 lua_pop(L, 1);
7422 }
William Lallemanddec25c32021-10-25 19:48:37 +02007423
William Lallemand746e6f32021-10-06 10:57:44 +02007424 if (!url_str) {
7425 WILL_LJMP(luaL_error(L, "'get' need a 'url' argument"));
7426 return 0;
7427 }
William Lallemand3956c4e2021-09-21 16:25:15 +02007428
William Lallemand10a37362022-03-02 16:18:26 +01007429 hlua_hc->sent = 0;
William Lallemand3956c4e2021-09-21 16:25:15 +02007430
Aurelien DARRAGON03564072023-02-09 15:26:25 +01007431 istfree(&hlua_hc->hc->req.url);
William Lallemand3956c4e2021-09-21 16:25:15 +02007432 hlua_hc->hc->req.url = istdup(ist(url_str));
William Lallemanddc2cc902021-10-26 11:43:26 +02007433 hlua_hc->hc->req.meth = meth;
William Lallemand3956c4e2021-09-21 16:25:15 +02007434
7435 /* update the httpclient callbacks */
William Lallemandbd5739e2021-10-28 15:41:38 +02007436 hlua_hc->hc->ops.res_stline = hlua_httpclient_cb;
7437 hlua_hc->hc->ops.res_headers = hlua_httpclient_cb;
7438 hlua_hc->hc->ops.res_payload = hlua_httpclient_cb;
William Lallemand8f170c72022-03-15 10:52:07 +01007439 hlua_hc->hc->ops.res_end = hlua_httpclient_cb;
William Lallemand3956c4e2021-09-21 16:25:15 +02007440
William Lallemandbd5739e2021-10-28 15:41:38 +02007441 /* a body is available, it will use the request callback */
Christopher Faulet380ae9c2022-10-14 14:57:04 +02007442 if (body_str && buf_len) {
William Lallemandbd5739e2021-10-28 15:41:38 +02007443 hlua_hc->hc->ops.req_payload = hlua_httpclient_cb;
7444 }
William Lallemand3956c4e2021-09-21 16:25:15 +02007445
William Lallemandbd5739e2021-10-28 15:41:38 +02007446 ret = httpclient_req_gen(hlua_hc->hc, hlua_hc->hc->req.url, meth, hdrs, IST_NULL);
William Lallemand3956c4e2021-09-21 16:25:15 +02007447
William Lallemand746e6f32021-10-06 10:57:44 +02007448 /* free the temporary headers array */
7449 hdrs_i = hdrs;
7450 while (hdrs_i && isttest(hdrs_i->n)) {
7451 istfree(&hdrs_i->n);
7452 istfree(&hdrs_i->v);
7453 hdrs_i++;
7454 }
7455 ha_free(&hdrs);
7456
7457
William Lallemand6137a9e2021-10-26 15:01:53 +02007458 if (ret != ERR_NONE) {
7459 WILL_LJMP(luaL_error(L, "Can't generate the HTTP request"));
7460 return 0;
7461 }
7462
William Lallemandc2d3db42022-04-26 11:46:13 +02007463 if (!httpclient_start(hlua_hc->hc))
7464 WILL_LJMP(luaL_error(L, "couldn't start the httpclient"));
William Lallemand6137a9e2021-10-26 15:01:53 +02007465
William Lallemandbd5739e2021-10-28 15:41:38 +02007466 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_httpclient_snd_yield, TICK_ETERNITY, 0));
William Lallemand3956c4e2021-09-21 16:25:15 +02007467
William Lallemand3956c4e2021-09-21 16:25:15 +02007468 return 0;
7469}
7470
7471/*
William Lallemanddc2cc902021-10-26 11:43:26 +02007472 * Sends an HTTP HEAD request and wait for a response
7473 *
7474 * httpclient:head(url, headers, payload)
7475 */
7476__LJMP static int hlua_httpclient_head(lua_State *L)
7477{
7478 return hlua_httpclient_send(L, HTTP_METH_HEAD);
7479}
7480
7481/*
7482 * Send an HTTP GET request and wait for a response
7483 *
7484 * httpclient:get(url, headers, payload)
7485 */
7486__LJMP static int hlua_httpclient_get(lua_State *L)
7487{
7488 return hlua_httpclient_send(L, HTTP_METH_GET);
7489
7490}
7491
7492/*
7493 * Sends an HTTP PUT request and wait for a response
7494 *
7495 * httpclient:put(url, headers, payload)
7496 */
7497__LJMP static int hlua_httpclient_put(lua_State *L)
7498{
7499 return hlua_httpclient_send(L, HTTP_METH_PUT);
7500}
7501
7502/*
7503 * Send an HTTP POST request and wait for a response
7504 *
7505 * httpclient:post(url, headers, payload)
7506 */
7507__LJMP static int hlua_httpclient_post(lua_State *L)
7508{
7509 return hlua_httpclient_send(L, HTTP_METH_POST);
7510}
7511
7512
7513/*
7514 * Sends an HTTP DELETE request and wait for a response
7515 *
7516 * httpclient:delete(url, headers, payload)
7517 */
7518__LJMP static int hlua_httpclient_delete(lua_State *L)
7519{
7520 return hlua_httpclient_send(L, HTTP_METH_DELETE);
7521}
7522
7523/*
William Lallemand3956c4e2021-09-21 16:25:15 +02007524 *
7525 *
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007526 * Class TXN
7527 *
7528 *
7529 */
7530
7531/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02007532 * a class stream, otherwise it throws an error.
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007533 */
7534__LJMP static struct hlua_txn *hlua_checktxn(lua_State *L, int ud)
7535{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02007536 return MAY_LJMP(hlua_checkudata(L, ud, class_txn_ref));
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007537}
7538
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007539__LJMP static int hlua_set_var(lua_State *L)
7540{
7541 struct hlua_txn *htxn;
7542 const char *name;
7543 size_t len;
7544 struct sample smp;
7545
Tim Duesterhus4e172c92020-05-19 13:49:42 +02007546 if (lua_gettop(L) < 3 || lua_gettop(L) > 4)
7547 WILL_LJMP(luaL_error(L, "'set_var' needs between 3 and 4 arguments"));
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007548
7549 /* It is useles to retrieve the stream, but this function
7550 * runs only in a stream context.
7551 */
7552 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7553 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
7554
7555 /* Converts the third argument in a sample. */
Amaury Denoyellebc0af6a2020-10-29 17:21:20 +01007556 memset(&smp, 0, sizeof(smp));
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007557 hlua_lua2smp(L, 3, &smp);
7558
7559 /* Store the sample in a variable. */
Willy Tarreau7560dd42016-03-10 16:28:58 +01007560 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
Tim Duesterhus4e172c92020-05-19 13:49:42 +02007561
7562 if (lua_gettop(L) == 4 && lua_toboolean(L, 4))
7563 lua_pushboolean(L, vars_set_by_name_ifexist(name, len, &smp) != 0);
7564 else
7565 lua_pushboolean(L, vars_set_by_name(name, len, &smp) != 0);
7566
Tim Duesterhus84ebc132020-05-19 13:49:41 +02007567 return 1;
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007568}
7569
Christopher Faulet85d79c92016-11-09 16:54:56 +01007570__LJMP static int hlua_unset_var(lua_State *L)
7571{
7572 struct hlua_txn *htxn;
7573 const char *name;
7574 size_t len;
7575 struct sample smp;
7576
7577 MAY_LJMP(check_args(L, 2, "unset_var"));
7578
7579 /* It is useles to retrieve the stream, but this function
7580 * runs only in a stream context.
7581 */
7582 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7583 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
7584
7585 /* Unset the variable. */
7586 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
Tim Duesterhus84ebc132020-05-19 13:49:41 +02007587 lua_pushboolean(L, vars_unset_by_name_ifexist(name, len, &smp) != 0);
7588 return 1;
Christopher Faulet85d79c92016-11-09 16:54:56 +01007589}
7590
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007591__LJMP static int hlua_get_var(lua_State *L)
7592{
7593 struct hlua_txn *htxn;
7594 const char *name;
7595 size_t len;
7596 struct sample smp;
7597
7598 MAY_LJMP(check_args(L, 2, "get_var"));
7599
7600 /* It is useles to retrieve the stream, but this function
7601 * runs only in a stream context.
7602 */
7603 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7604 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
7605
Willy Tarreau7560dd42016-03-10 16:28:58 +01007606 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
Willy Tarreaue352b9d2021-09-03 11:52:38 +02007607 if (!vars_get_by_name(name, len, &smp, NULL)) {
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007608 lua_pushnil(L);
7609 return 1;
7610 }
7611
7612 return hlua_smp2lua(L, &smp);
7613}
7614
Willy Tarreau59551662015-03-10 14:23:13 +01007615__LJMP static int hlua_set_priv(lua_State *L)
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007616{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007617 struct hlua *hlua;
7618
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007619 MAY_LJMP(check_args(L, 2, "set_priv"));
7620
Willy Tarreau87b09662015-04-03 00:22:06 +02007621 /* It is useles to retrieve the stream, but this function
7622 * runs only in a stream context.
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007623 */
7624 MAY_LJMP(hlua_checktxn(L, 1));
Thierry Fournier4234dbd2020-11-28 13:18:23 +01007625
7626 /* Get hlua struct, or NULL if we execute from main lua state */
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007627 hlua = hlua_gethlua(L);
Thierry Fournier4234dbd2020-11-28 13:18:23 +01007628 if (!hlua)
7629 return 0;
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007630
7631 /* Remove previous value. */
Thierry FOURNIERe068b602017-04-26 13:27:05 +02007632 luaL_unref(L, LUA_REGISTRYINDEX, hlua->Mref);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007633
7634 /* Get and store new value. */
7635 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
7636 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
7637
7638 return 0;
7639}
7640
Willy Tarreau59551662015-03-10 14:23:13 +01007641__LJMP static int hlua_get_priv(lua_State *L)
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007642{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007643 struct hlua *hlua;
7644
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007645 MAY_LJMP(check_args(L, 1, "get_priv"));
7646
Willy Tarreau87b09662015-04-03 00:22:06 +02007647 /* It is useles to retrieve the stream, but this function
7648 * runs only in a stream context.
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007649 */
7650 MAY_LJMP(hlua_checktxn(L, 1));
Thierry Fournier4234dbd2020-11-28 13:18:23 +01007651
7652 /* Get hlua struct, or NULL if we execute from main lua state */
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007653 hlua = hlua_gethlua(L);
Thierry Fournier4234dbd2020-11-28 13:18:23 +01007654 if (!hlua) {
7655 lua_pushnil(L);
7656 return 1;
7657 }
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007658
7659 /* Push configuration index in the stack. */
7660 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
7661
7662 return 1;
7663}
7664
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007665/* Create stack entry containing a class TXN. This function
7666 * return 0 if the stack does not contains free slots,
7667 * otherwise it returns 1.
7668 */
Thierry FOURNIERab00df62016-07-14 11:42:37 +02007669static int hlua_txn_new(lua_State *L, struct stream *s, struct proxy *p, int dir, int flags)
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007670{
Willy Tarreaude491382015-04-06 11:04:28 +02007671 struct hlua_txn *htxn;
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007672
7673 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01007674 if (!lua_checkstack(L, 3))
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007675 return 0;
7676
7677 /* NOTE: The allocation never fails. The failure
7678 * throw an error, and the function never returns.
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08007679 * if the throw is not available, the process is aborted.
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007680 */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01007681 /* Create the object: obj[0] = userdata. */
7682 lua_newtable(L);
Willy Tarreaude491382015-04-06 11:04:28 +02007683 htxn = lua_newuserdata(L, sizeof(*htxn));
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01007684 lua_rawseti(L, -2, 0);
7685
Willy Tarreaude491382015-04-06 11:04:28 +02007686 htxn->s = s;
7687 htxn->p = p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01007688 htxn->dir = dir;
Thierry FOURNIERab00df62016-07-14 11:42:37 +02007689 htxn->flags = flags;
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007690
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01007691 /* Create the "f" field that contains a list of fetches. */
7692 lua_pushstring(L, "f");
Thierry FOURNIERca988662015-12-20 18:43:03 +01007693 if (!hlua_fetches_new(L, htxn, HLUA_F_MAY_USE_HTTP))
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01007694 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007695 lua_rawset(L, -3);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01007696
7697 /* Create the "sf" field that contains a list of stringsafe fetches. */
7698 lua_pushstring(L, "sf");
Thierry FOURNIERca988662015-12-20 18:43:03 +01007699 if (!hlua_fetches_new(L, htxn, HLUA_F_MAY_USE_HTTP | HLUA_F_AS_STRING))
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01007700 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007701 lua_rawset(L, -3);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01007702
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007703 /* Create the "c" field that contains a list of converters. */
7704 lua_pushstring(L, "c");
Willy Tarreaude491382015-04-06 11:04:28 +02007705 if (!hlua_converters_new(L, htxn, 0))
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01007706 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007707 lua_rawset(L, -3);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01007708
7709 /* Create the "sc" field that contains a list of stringsafe converters. */
7710 lua_pushstring(L, "sc");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01007711 if (!hlua_converters_new(L, htxn, HLUA_F_AS_STRING))
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007712 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007713 lua_rawset(L, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007714
Thierry FOURNIER397826a2015-03-11 19:39:09 +01007715 /* Create the "req" field that contains the request channel object. */
7716 lua_pushstring(L, "req");
Willy Tarreau2a71af42015-03-10 13:51:50 +01007717 if (!hlua_channel_new(L, &s->req))
Thierry FOURNIER397826a2015-03-11 19:39:09 +01007718 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007719 lua_rawset(L, -3);
Thierry FOURNIER397826a2015-03-11 19:39:09 +01007720
7721 /* Create the "res" field that contains the response channel object. */
7722 lua_pushstring(L, "res");
Willy Tarreau2a71af42015-03-10 13:51:50 +01007723 if (!hlua_channel_new(L, &s->res))
Thierry FOURNIER397826a2015-03-11 19:39:09 +01007724 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007725 lua_rawset(L, -3);
Thierry FOURNIER397826a2015-03-11 19:39:09 +01007726
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007727 /* Creates the HTTP object is the current proxy allows http. */
7728 lua_pushstring(L, "http");
Christopher Faulet1bb6afa2021-03-08 17:57:53 +01007729 if (IS_HTX_STRM(s)) {
Willy Tarreaude491382015-04-06 11:04:28 +02007730 if (!hlua_http_new(L, htxn))
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007731 return 0;
7732 }
7733 else
7734 lua_pushnil(L);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007735 lua_rawset(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007736
Christopher Faulet78c35472020-02-26 17:14:08 +01007737 if ((htxn->flags & HLUA_TXN_CTX_MASK) == HLUA_TXN_FLT_CTX) {
7738 /* HTTPMessage object are created when a lua TXN is created from
7739 * a filter context only
7740 */
7741
7742 /* Creates the HTTP-Request object is the current proxy allows http. */
7743 lua_pushstring(L, "http_req");
7744 if (p->mode == PR_MODE_HTTP) {
7745 if (!hlua_http_msg_new(L, &s->txn->req))
7746 return 0;
7747 }
7748 else
7749 lua_pushnil(L);
7750 lua_rawset(L, -3);
7751
7752 /* Creates the HTTP-Response object is the current proxy allows http. */
7753 lua_pushstring(L, "http_res");
7754 if (p->mode == PR_MODE_HTTP) {
7755 if (!hlua_http_msg_new(L, &s->txn->rsp))
7756 return 0;
7757 }
7758 else
7759 lua_pushnil(L);
7760 lua_rawset(L, -3);
7761 }
7762
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007763 /* Pop a class sesison metatable and affect it to the userdata. */
7764 lua_rawgeti(L, LUA_REGISTRYINDEX, class_txn_ref);
7765 lua_setmetatable(L, -2);
7766
7767 return 1;
7768}
7769
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01007770__LJMP static int hlua_txn_deflog(lua_State *L)
7771{
7772 const char *msg;
7773 struct hlua_txn *htxn;
7774
7775 MAY_LJMP(check_args(L, 2, "deflog"));
7776 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7777 msg = MAY_LJMP(luaL_checkstring(L, 2));
7778
7779 hlua_sendlog(htxn->s->be, htxn->s->logs.level, msg);
7780 return 0;
7781}
7782
7783__LJMP static int hlua_txn_log(lua_State *L)
7784{
7785 int level;
7786 const char *msg;
7787 struct hlua_txn *htxn;
7788
7789 MAY_LJMP(check_args(L, 3, "log"));
7790 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7791 level = MAY_LJMP(luaL_checkinteger(L, 2));
7792 msg = MAY_LJMP(luaL_checkstring(L, 3));
7793
7794 if (level < 0 || level >= NB_LOG_LEVELS)
7795 WILL_LJMP(luaL_argerror(L, 1, "Invalid loglevel."));
7796
7797 hlua_sendlog(htxn->s->be, level, msg);
7798 return 0;
7799}
7800
7801__LJMP static int hlua_txn_log_debug(lua_State *L)
7802{
7803 const char *msg;
7804 struct hlua_txn *htxn;
7805
7806 MAY_LJMP(check_args(L, 2, "Debug"));
7807 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7808 msg = MAY_LJMP(luaL_checkstring(L, 2));
7809 hlua_sendlog(htxn->s->be, LOG_DEBUG, msg);
7810 return 0;
7811}
7812
7813__LJMP static int hlua_txn_log_info(lua_State *L)
7814{
7815 const char *msg;
7816 struct hlua_txn *htxn;
7817
7818 MAY_LJMP(check_args(L, 2, "Info"));
7819 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7820 msg = MAY_LJMP(luaL_checkstring(L, 2));
7821 hlua_sendlog(htxn->s->be, LOG_INFO, msg);
7822 return 0;
7823}
7824
7825__LJMP static int hlua_txn_log_warning(lua_State *L)
7826{
7827 const char *msg;
7828 struct hlua_txn *htxn;
7829
7830 MAY_LJMP(check_args(L, 2, "Warning"));
7831 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7832 msg = MAY_LJMP(luaL_checkstring(L, 2));
7833 hlua_sendlog(htxn->s->be, LOG_WARNING, msg);
7834 return 0;
7835}
7836
7837__LJMP static int hlua_txn_log_alert(lua_State *L)
7838{
7839 const char *msg;
7840 struct hlua_txn *htxn;
7841
7842 MAY_LJMP(check_args(L, 2, "Alert"));
7843 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7844 msg = MAY_LJMP(luaL_checkstring(L, 2));
7845 hlua_sendlog(htxn->s->be, LOG_ALERT, msg);
7846 return 0;
7847}
7848
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01007849__LJMP static int hlua_txn_set_loglevel(lua_State *L)
7850{
7851 struct hlua_txn *htxn;
7852 int ll;
7853
7854 MAY_LJMP(check_args(L, 2, "set_loglevel"));
7855 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7856 ll = MAY_LJMP(luaL_checkinteger(L, 2));
7857
7858 if (ll < 0 || ll > 7)
7859 WILL_LJMP(luaL_argerror(L, 2, "Bad log level. It must be between 0 and 7"));
7860
7861 htxn->s->logs.level = ll;
7862 return 0;
7863}
7864
7865__LJMP static int hlua_txn_set_tos(lua_State *L)
7866{
7867 struct hlua_txn *htxn;
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01007868 int tos;
7869
7870 MAY_LJMP(check_args(L, 2, "set_tos"));
7871 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7872 tos = MAY_LJMP(luaL_checkinteger(L, 2));
7873
Willy Tarreau1a18b542018-12-11 16:37:42 +01007874 conn_set_tos(objt_conn(htxn->s->sess->origin), tos);
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01007875 return 0;
7876}
7877
7878__LJMP static int hlua_txn_set_mark(lua_State *L)
7879{
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01007880 struct hlua_txn *htxn;
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01007881 int mark;
7882
7883 MAY_LJMP(check_args(L, 2, "set_mark"));
7884 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7885 mark = MAY_LJMP(luaL_checkinteger(L, 2));
7886
Lukas Tribus579e3e32019-08-11 18:03:45 +02007887 conn_set_mark(objt_conn(htxn->s->sess->origin), mark);
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01007888 return 0;
7889}
7890
Patrick Hemmer268a7072018-05-11 12:52:31 -04007891__LJMP static int hlua_txn_set_priority_class(lua_State *L)
7892{
7893 struct hlua_txn *htxn;
7894
7895 MAY_LJMP(check_args(L, 2, "set_priority_class"));
7896 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7897 htxn->s->priority_class = queue_limit_class(MAY_LJMP(luaL_checkinteger(L, 2)));
7898 return 0;
7899}
7900
7901__LJMP static int hlua_txn_set_priority_offset(lua_State *L)
7902{
7903 struct hlua_txn *htxn;
7904
7905 MAY_LJMP(check_args(L, 2, "set_priority_offset"));
7906 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7907 htxn->s->priority_offset = queue_limit_offset(MAY_LJMP(luaL_checkinteger(L, 2)));
7908 return 0;
7909}
7910
Christopher Faulet700d9e82020-01-31 12:21:52 +01007911/* Forward the Reply object to the client. This function converts the reply in
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05007912 * HTX an push it to into the response channel. It is response to forward the
Christopher Faulet700d9e82020-01-31 12:21:52 +01007913 * message and terminate the transaction. It returns 1 on success and 0 on
7914 * error. The Reply must be on top of the stack.
7915 */
7916__LJMP static int hlua_txn_forward_reply(lua_State *L, struct stream *s)
7917{
7918 struct htx *htx;
7919 struct htx_sl *sl;
7920 struct h1m h1m;
7921 const char *status, *reason, *body;
7922 size_t status_len, reason_len, body_len;
7923 int ret, code, flags;
7924
7925 code = 200;
7926 status = "200";
7927 status_len = 3;
7928 ret = lua_getfield(L, -1, "status");
7929 if (ret == LUA_TNUMBER) {
7930 code = lua_tointeger(L, -1);
7931 status = lua_tolstring(L, -1, &status_len);
7932 }
7933 lua_pop(L, 1);
7934
7935 reason = http_get_reason(code);
7936 reason_len = strlen(reason);
7937 ret = lua_getfield(L, -1, "reason");
7938 if (ret == LUA_TSTRING)
7939 reason = lua_tolstring(L, -1, &reason_len);
7940 lua_pop(L, 1);
7941
7942 body = NULL;
7943 body_len = 0;
7944 ret = lua_getfield(L, -1, "body");
7945 if (ret == LUA_TSTRING)
7946 body = lua_tolstring(L, -1, &body_len);
7947 lua_pop(L, 1);
7948
7949 /* Prepare the response before inserting the headers */
7950 h1m_init_res(&h1m);
7951 htx = htx_from_buf(&s->res.buf);
7952 channel_htx_truncate(&s->res, htx);
7953 if (s->txn->req.flags & HTTP_MSGF_VER_11) {
7954 flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11);
7955 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.1"),
7956 ist2(status, status_len), ist2(reason, reason_len));
7957 }
7958 else {
7959 flags = HTX_SL_F_IS_RESP;
7960 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.0"),
7961 ist2(status, status_len), ist2(reason, reason_len));
7962 }
7963 if (!sl)
7964 goto fail;
7965 sl->info.res.status = code;
7966
7967 /* Push in the stack the "headers" entry. */
7968 ret = lua_getfield(L, -1, "headers");
7969 if (ret != LUA_TTABLE)
7970 goto skip_headers;
7971
7972 lua_pushnil(L);
7973 while (lua_next(L, -2) != 0) {
7974 struct ist name, value;
7975 const char *n, *v;
7976 size_t nlen, vlen;
7977
7978 if (!lua_isstring(L, -2) || !lua_istable(L, -1)) {
7979 /* Skip element if the key is not a string or if the value is not a table */
7980 goto next_hdr;
7981 }
7982
7983 n = lua_tolstring(L, -2, &nlen);
7984 name = ist2(n, nlen);
7985 if (isteqi(name, ist("content-length"))) {
7986 /* Always skip content-length header. It will be added
7987 * later with the correct len
7988 */
7989 goto next_hdr;
7990 }
7991
7992 /* Loop on header's values */
7993 lua_pushnil(L);
7994 while (lua_next(L, -2)) {
7995 if (!lua_isstring(L, -1)) {
7996 /* Skip the value if it is not a string */
7997 goto next_value;
7998 }
7999
8000 v = lua_tolstring(L, -1, &vlen);
8001 value = ist2(v, vlen);
8002
8003 if (isteqi(name, ist("transfer-encoding")))
8004 h1_parse_xfer_enc_header(&h1m, value);
8005 if (!htx_add_header(htx, ist2(n, nlen), ist2(v, vlen)))
8006 goto fail;
8007
8008 next_value:
8009 lua_pop(L, 1);
8010 }
8011
8012 next_hdr:
8013 lua_pop(L, 1);
8014 }
8015 skip_headers:
8016 lua_pop(L, 1);
8017
8018 /* Update h1m flags: CLEN is set if CHNK is not present */
8019 if (!(h1m.flags & H1_MF_CHNK)) {
8020 const char *clen = ultoa(body_len);
8021
8022 h1m.flags |= H1_MF_CLEN;
8023 if (!htx_add_header(htx, ist("content-length"), ist(clen)))
8024 goto fail;
8025 }
8026 if (h1m.flags & (H1_MF_CLEN|H1_MF_CHNK))
8027 h1m.flags |= H1_MF_XFER_LEN;
8028
8029 /* Update HTX start-line flags */
8030 if (h1m.flags & H1_MF_XFER_ENC)
8031 flags |= HTX_SL_F_XFER_ENC;
8032 if (h1m.flags & H1_MF_XFER_LEN) {
8033 flags |= HTX_SL_F_XFER_LEN;
8034 if (h1m.flags & H1_MF_CHNK)
8035 flags |= HTX_SL_F_CHNK;
8036 else if (h1m.flags & H1_MF_CLEN)
8037 flags |= HTX_SL_F_CLEN;
8038 if (h1m.body_len == 0)
8039 flags |= HTX_SL_F_BODYLESS;
8040 }
8041 sl->flags |= flags;
8042
8043
8044 if (!htx_add_endof(htx, HTX_BLK_EOH) ||
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01008045 (body_len && !htx_add_data_atonce(htx, ist2(body, body_len))))
Christopher Faulet700d9e82020-01-31 12:21:52 +01008046 goto fail;
8047
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01008048 htx->flags |= HTX_FL_EOM;
8049
Christopher Faulet700d9e82020-01-31 12:21:52 +01008050 /* Now, forward the response and terminate the transaction */
8051 s->txn->status = code;
8052 htx_to_buf(htx, &s->res.buf);
8053 if (!http_forward_proxy_resp(s, 1))
8054 goto fail;
8055
8056 return 1;
8057
8058 fail:
8059 channel_htx_truncate(&s->res, htx);
8060 return 0;
8061}
8062
8063/* Terminate a transaction if called from a lua action. For TCP streams,
8064 * processing is just aborted. Nothing is returned to the client and all
8065 * arguments are ignored. For HTTP streams, if a reply is passed as argument, it
8066 * is forwarded to the client before terminating the transaction. On success,
8067 * the function exits with ACT_RET_DONE code. If an error occurred, it exits
8068 * with ACT_RET_ERR code. If this function is not called from a lua action, it
8069 * just exits without any processing.
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01008070 */
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02008071__LJMP static int hlua_txn_done(lua_State *L)
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01008072{
Willy Tarreaub2ccb562015-04-06 11:11:15 +02008073 struct hlua_txn *htxn;
Christopher Faulet700d9e82020-01-31 12:21:52 +01008074 struct stream *s;
8075 int finst;
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01008076
Willy Tarreaub2ccb562015-04-06 11:11:15 +02008077 htxn = MAY_LJMP(hlua_checktxn(L, 1));
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01008078
Christopher Faulet700d9e82020-01-31 12:21:52 +01008079 /* If the flags NOTERM is set, we cannot terminate the session, so we
8080 * just end the execution of the current lua code. */
8081 if (htxn->flags & HLUA_TXN_NOTERM)
Thierry FOURNIERab00df62016-07-14 11:42:37 +02008082 WILL_LJMP(hlua_done(L));
Thierry FOURNIERab00df62016-07-14 11:42:37 +02008083
Christopher Faulet700d9e82020-01-31 12:21:52 +01008084 s = htxn->s;
Christopher Fauletd8f0e072020-02-25 09:45:51 +01008085 if (!IS_HTX_STRM(htxn->s)) {
Christopher Faulet700d9e82020-01-31 12:21:52 +01008086 struct channel *req = &s->req;
8087 struct channel *res = &s->res;
Willy Tarreau81389672015-03-10 12:03:52 +01008088
Christopher Faulet700d9e82020-01-31 12:21:52 +01008089 channel_auto_read(req);
8090 channel_abort(req);
8091 channel_auto_close(req);
8092 channel_erase(req);
8093
Christopher Faulet700d9e82020-01-31 12:21:52 +01008094 channel_auto_read(res);
8095 channel_auto_close(res);
8096 channel_shutr_now(res);
8097
8098 finst = ((htxn->dir == SMP_OPT_DIR_REQ) ? SF_FINST_R : SF_FINST_D);
8099 goto done;
Christopher Fauletfe6a71b2019-07-26 16:40:24 +02008100 }
Thierry FOURNIER10ec2142015-08-24 17:23:45 +02008101
Christopher Faulet700d9e82020-01-31 12:21:52 +01008102 if (lua_gettop(L) == 1 || !lua_istable(L, 2)) {
8103 /* No reply or invalid reply */
8104 s->txn->status = 0;
8105 http_reply_and_close(s, 0, NULL);
8106 }
8107 else {
8108 /* Remove extra args to have the reply on top of the stack */
8109 if (lua_gettop(L) > 2)
8110 lua_pop(L, lua_gettop(L) - 2);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01008111
Christopher Faulet700d9e82020-01-31 12:21:52 +01008112 if (!hlua_txn_forward_reply(L, s)) {
8113 if (!(s->flags & SF_ERR_MASK))
8114 s->flags |= SF_ERR_PRXCOND;
8115 lua_pushinteger(L, ACT_RET_ERR);
8116 WILL_LJMP(hlua_done(L));
8117 return 0; /* Never reached */
8118 }
Christopher Faulet4d0e2632019-07-16 10:52:40 +02008119 }
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02008120
Christopher Faulet700d9e82020-01-31 12:21:52 +01008121 finst = ((htxn->dir == SMP_OPT_DIR_REQ) ? SF_FINST_R : SF_FINST_H);
8122 if (htxn->dir == SMP_OPT_DIR_REQ) {
8123 /* let's log the request time */
8124 s->logs.tv_request = now;
8125 if (s->sess->fe == s->be) /* report it if the request was intercepted by the frontend */
Willy Tarreau4781b152021-04-06 13:53:36 +02008126 _HA_ATOMIC_INC(&s->sess->fe->fe_counters.intercepted_req);
Christopher Faulet700d9e82020-01-31 12:21:52 +01008127 }
Christopher Fauletfe6a71b2019-07-26 16:40:24 +02008128
Christopher Faulet700d9e82020-01-31 12:21:52 +01008129 done:
8130 if (!(s->flags & SF_ERR_MASK))
8131 s->flags |= SF_ERR_LOCAL;
8132 if (!(s->flags & SF_FINST_MASK))
8133 s->flags |= finst;
Christopher Fauletfe6a71b2019-07-26 16:40:24 +02008134
Christopher Faulete48d1dc2021-08-13 14:11:17 +02008135 if ((htxn->flags & HLUA_TXN_CTX_MASK) == HLUA_TXN_FLT_CTX)
8136 lua_pushinteger(L, -1);
8137 else
8138 lua_pushinteger(L, ACT_RET_ABRT);
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02008139 WILL_LJMP(hlua_done(L));
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01008140 return 0;
8141}
8142
Christopher Faulet700d9e82020-01-31 12:21:52 +01008143/*
8144 *
8145 *
8146 * Class REPLY
8147 *
8148 *
8149 */
8150
8151/* Pushes the TXN reply onto the top of the stack. If the stask does not have a
8152 * free slots, the function fails and returns 0;
8153 */
8154static int hlua_txn_reply_new(lua_State *L)
8155{
8156 struct hlua_txn *htxn;
8157 const char *reason, *body = NULL;
8158 int ret, status;
8159
8160 htxn = MAY_LJMP(hlua_checktxn(L, 1));
Christopher Fauletd8f0e072020-02-25 09:45:51 +01008161 if (!IS_HTX_STRM(htxn->s)) {
Christopher Faulet700d9e82020-01-31 12:21:52 +01008162 hlua_pusherror(L, "txn object is not an HTTP transaction.");
8163 WILL_LJMP(lua_error(L));
8164 }
8165
8166 /* Default value */
8167 status = 200;
8168 reason = http_get_reason(status);
8169
8170 if (lua_istable(L, 2)) {
8171 /* load status and reason from the table argument at index 2 */
8172 ret = lua_getfield(L, 2, "status");
8173 if (ret == LUA_TNIL)
8174 goto reason;
8175 else if (ret != LUA_TNUMBER) {
8176 /* invalid status: ignore the reason */
8177 goto body;
8178 }
8179 status = lua_tointeger(L, -1);
8180
8181 reason:
8182 lua_pop(L, 1); /* restore the stack: remove status */
8183 ret = lua_getfield(L, 2, "reason");
8184 if (ret == LUA_TSTRING)
8185 reason = lua_tostring(L, -1);
8186
8187 body:
8188 lua_pop(L, 1); /* restore the stack: remove invalid status or reason */
8189 ret = lua_getfield(L, 2, "body");
8190 if (ret == LUA_TSTRING)
8191 body = lua_tostring(L, -1);
8192 lua_pop(L, 1); /* restore the stack: remove body */
8193 }
8194
8195 /* Create the Reply table */
8196 lua_newtable(L);
8197
8198 /* Add status element */
8199 lua_pushstring(L, "status");
8200 lua_pushinteger(L, status);
8201 lua_settable(L, -3);
8202
8203 /* Add reason element */
8204 reason = http_get_reason(status);
8205 lua_pushstring(L, "reason");
8206 lua_pushstring(L, reason);
8207 lua_settable(L, -3);
8208
8209 /* Add body element, nil if undefined */
8210 lua_pushstring(L, "body");
8211 if (body)
8212 lua_pushstring(L, body);
8213 else
8214 lua_pushnil(L);
8215 lua_settable(L, -3);
8216
8217 /* Add headers element */
8218 lua_pushstring(L, "headers");
8219 lua_newtable(L);
8220
8221 /* stack: [ txn, <Arg:table>, <Reply:table>, "headers", <headers:table> ] */
8222 if (lua_istable(L, 2)) {
8223 /* load headers from the table argument at index 2. If it is a table, copy it. */
8224 ret = lua_getfield(L, 2, "headers");
8225 if (ret == LUA_TTABLE) {
8226 /* stack: [ ... <headers:table>, <table> ] */
8227 lua_pushnil(L);
8228 while (lua_next(L, -2) != 0) {
8229 /* stack: [ ... <headers:table>, <table>, k, v] */
8230 if (!lua_isstring(L, -1) && !lua_istable(L, -1)) {
8231 /* invalid value type, skip it */
8232 lua_pop(L, 1);
8233 continue;
8234 }
8235
8236
8237 /* Duplicate the key and swap it with the value. */
8238 lua_pushvalue(L, -2);
8239 lua_insert(L, -2);
8240 /* stack: [ ... <headers:table>, <table>, k, k, v ] */
8241
8242 lua_newtable(L);
8243 lua_insert(L, -2);
8244 /* stack: [ ... <headers:table>, <table>, k, k, <inner:table>, v ] */
8245
8246 if (lua_isstring(L, -1)) {
8247 /* push the value in the inner table */
8248 lua_rawseti(L, -2, 1);
8249 }
8250 else { /* table */
8251 lua_pushnil(L);
8252 while (lua_next(L, -2) != 0) {
8253 /* stack: [ ... <headers:table>, <table>, k, k, <inner:table>, <v:table>, k2, v2 ] */
8254 if (!lua_isstring(L, -1)) {
8255 /* invalid value type, skip it*/
8256 lua_pop(L, 1);
8257 continue;
8258 }
8259 /* push the value in the inner table */
8260 lua_rawseti(L, -4, lua_rawlen(L, -4) + 1);
8261 /* stack: [ ... <headers:table>, <table>, k, k, <inner:table>, <v:table>, k2 ] */
8262 }
8263 lua_pop(L, 1);
8264 /* stack: [ ... <headers:table>, <table>, k, k, <inner:table> ] */
8265 }
8266
8267 /* push (k,v) on the stack in the headers table:
8268 * stack: [ ... <headers:table>, <table>, k, k, v ]
8269 */
8270 lua_settable(L, -5);
8271 /* stack: [ ... <headers:table>, <table>, k ] */
8272 }
8273 }
8274 lua_pop(L, 1);
8275 }
8276 /* stack: [ txn, <Arg:table>, <Reply:table>, "headers", <headers:table> ] */
8277 lua_settable(L, -3);
8278 /* stack: [ txn, <Arg:table>, <Reply:table> ] */
8279
8280 /* Pop a class sesison metatable and affect it to the userdata. */
8281 lua_rawgeti(L, LUA_REGISTRYINDEX, class_txn_reply_ref);
8282 lua_setmetatable(L, -2);
8283 return 1;
8284}
8285
8286/* Set the reply status code, and optionally the reason. If no reason is
8287 * provided, the default one corresponding to the status code is used.
8288 */
8289__LJMP static int hlua_txn_reply_set_status(lua_State *L)
8290{
8291 int status = MAY_LJMP(luaL_checkinteger(L, 2));
8292 const char *reason = MAY_LJMP(luaL_optlstring(L, 3, NULL, NULL));
8293
8294 /* First argument (self) must be a table */
Aurelien DARRAGONd83d0452022-10-05 11:46:45 +02008295 MAY_LJMP(luaL_checktype(L, 1, LUA_TTABLE));
Christopher Faulet700d9e82020-01-31 12:21:52 +01008296
8297 if (status < 100 || status > 599) {
8298 lua_pushboolean(L, 0);
8299 return 1;
8300 }
8301 if (!reason)
8302 reason = http_get_reason(status);
8303
8304 lua_pushinteger(L, status);
8305 lua_setfield(L, 1, "status");
8306
8307 lua_pushstring(L, reason);
8308 lua_setfield(L, 1, "reason");
8309
8310 lua_pushboolean(L, 1);
8311 return 1;
8312}
8313
8314/* Add a header into the reply object. Each header name is associated to an
8315 * array of values in the "headers" table. If the header name is not found, a
8316 * new entry is created.
8317 */
8318__LJMP static int hlua_txn_reply_add_header(lua_State *L)
8319{
8320 const char *name = MAY_LJMP(luaL_checkstring(L, 2));
8321 const char *value = MAY_LJMP(luaL_checkstring(L, 3));
8322 int ret;
8323
8324 /* First argument (self) must be a table */
Aurelien DARRAGONd83d0452022-10-05 11:46:45 +02008325 MAY_LJMP(luaL_checktype(L, 1, LUA_TTABLE));
Christopher Faulet700d9e82020-01-31 12:21:52 +01008326
8327 /* Push in the stack the "headers" entry. */
8328 ret = lua_getfield(L, 1, "headers");
8329 if (ret != LUA_TTABLE) {
8330 hlua_pusherror(L, "Reply['headers'] is expected to a an array. %s found", lua_typename(L, ret));
8331 WILL_LJMP(lua_error(L));
8332 }
8333
8334 /* check if the header is already registered. If not, register it. */
8335 ret = lua_getfield(L, -1, name);
8336 if (ret == LUA_TNIL) {
8337 /* Entry not found. */
8338 lua_pop(L, 1); /* remove the nil. The "headers" table is the top of the stack. */
8339
8340 /* Insert the new header name in the array in the top of the stack.
8341 * It left the new array in the top of the stack.
8342 */
8343 lua_newtable(L);
8344 lua_pushstring(L, name);
8345 lua_pushvalue(L, -2);
8346 lua_settable(L, -4);
8347 }
8348 else if (ret != LUA_TTABLE) {
8349 hlua_pusherror(L, "Reply['headers']['%s'] is expected to be an array. %s found", name, lua_typename(L, ret));
8350 WILL_LJMP(lua_error(L));
8351 }
8352
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -07008353 /* Now the top of thestack is an array of values. We push
Christopher Faulet700d9e82020-01-31 12:21:52 +01008354 * the header value as new entry.
8355 */
8356 lua_pushstring(L, value);
8357 ret = lua_rawlen(L, -2);
8358 lua_rawseti(L, -2, ret + 1);
8359
8360 lua_pushboolean(L, 1);
8361 return 1;
8362}
8363
8364/* Remove all occurrences of a given header name. */
8365__LJMP static int hlua_txn_reply_del_header(lua_State *L)
8366{
8367 const char *name = MAY_LJMP(luaL_checkstring(L, 2));
8368 int ret;
8369
8370 /* First argument (self) must be a table */
Aurelien DARRAGONd83d0452022-10-05 11:46:45 +02008371 MAY_LJMP(luaL_checktype(L, 1, LUA_TTABLE));
Christopher Faulet700d9e82020-01-31 12:21:52 +01008372
8373 /* Push in the stack the "headers" entry. */
8374 ret = lua_getfield(L, 1, "headers");
8375 if (ret != LUA_TTABLE) {
8376 hlua_pusherror(L, "Reply['headers'] is expected to be an array. %s found", lua_typename(L, ret));
8377 WILL_LJMP(lua_error(L));
8378 }
8379
8380 lua_pushstring(L, name);
8381 lua_pushnil(L);
8382 lua_settable(L, -3);
8383
8384 lua_pushboolean(L, 1);
8385 return 1;
8386}
8387
8388/* Set the reply's body. Overwrite any existing entry. */
8389__LJMP static int hlua_txn_reply_set_body(lua_State *L)
8390{
8391 const char *payload = MAY_LJMP(luaL_checkstring(L, 2));
8392
8393 /* First argument (self) must be a table */
Aurelien DARRAGONd83d0452022-10-05 11:46:45 +02008394 MAY_LJMP(luaL_checktype(L, 1, LUA_TTABLE));
Christopher Faulet700d9e82020-01-31 12:21:52 +01008395
8396 lua_pushstring(L, payload);
8397 lua_setfield(L, 1, "body");
8398
8399 lua_pushboolean(L, 1);
8400 return 1;
8401}
8402
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01008403__LJMP static int hlua_log(lua_State *L)
8404{
8405 int level;
8406 const char *msg;
8407
8408 MAY_LJMP(check_args(L, 2, "log"));
8409 level = MAY_LJMP(luaL_checkinteger(L, 1));
8410 msg = MAY_LJMP(luaL_checkstring(L, 2));
8411
8412 if (level < 0 || level >= NB_LOG_LEVELS)
8413 WILL_LJMP(luaL_argerror(L, 1, "Invalid loglevel."));
8414
8415 hlua_sendlog(NULL, level, msg);
8416 return 0;
8417}
8418
8419__LJMP static int hlua_log_debug(lua_State *L)
8420{
8421 const char *msg;
8422
8423 MAY_LJMP(check_args(L, 1, "debug"));
8424 msg = MAY_LJMP(luaL_checkstring(L, 1));
8425 hlua_sendlog(NULL, LOG_DEBUG, msg);
8426 return 0;
8427}
8428
8429__LJMP static int hlua_log_info(lua_State *L)
8430{
8431 const char *msg;
8432
8433 MAY_LJMP(check_args(L, 1, "info"));
8434 msg = MAY_LJMP(luaL_checkstring(L, 1));
8435 hlua_sendlog(NULL, LOG_INFO, msg);
8436 return 0;
8437}
8438
8439__LJMP static int hlua_log_warning(lua_State *L)
8440{
8441 const char *msg;
8442
8443 MAY_LJMP(check_args(L, 1, "warning"));
8444 msg = MAY_LJMP(luaL_checkstring(L, 1));
8445 hlua_sendlog(NULL, LOG_WARNING, msg);
8446 return 0;
8447}
8448
8449__LJMP static int hlua_log_alert(lua_State *L)
8450{
8451 const char *msg;
8452
8453 MAY_LJMP(check_args(L, 1, "alert"));
8454 msg = MAY_LJMP(luaL_checkstring(L, 1));
8455 hlua_sendlog(NULL, LOG_ALERT, msg);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01008456 return 0;
8457}
8458
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01008459__LJMP static int hlua_sleep_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008460{
8461 int wakeup_ms = lua_tointeger(L, -1);
Willy Tarreau12c02702021-09-30 16:12:31 +02008462 if (!tick_is_expired(wakeup_ms, now_ms))
Willy Tarreau9635e032018-10-16 17:52:55 +02008463 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008464 return 0;
8465}
8466
8467__LJMP static int hlua_sleep(lua_State *L)
8468{
8469 unsigned int delay;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008470 unsigned int wakeup_ms;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008471
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008472 MAY_LJMP(check_args(L, 1, "sleep"));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008473
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01008474 delay = MAY_LJMP(luaL_checkinteger(L, 1)) * 1000;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008475 wakeup_ms = tick_add(now_ms, delay);
8476 lua_pushinteger(L, wakeup_ms);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008477
Willy Tarreau9635e032018-10-16 17:52:55 +02008478 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008479 return 0;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008480}
8481
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008482__LJMP static int hlua_msleep(lua_State *L)
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008483{
8484 unsigned int delay;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008485 unsigned int wakeup_ms;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008486
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008487 MAY_LJMP(check_args(L, 1, "msleep"));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008488
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01008489 delay = MAY_LJMP(luaL_checkinteger(L, 1));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008490 wakeup_ms = tick_add(now_ms, delay);
8491 lua_pushinteger(L, wakeup_ms);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008492
Willy Tarreau9635e032018-10-16 17:52:55 +02008493 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008494 return 0;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008495}
8496
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01008497/* This functionis an LUA binding. it permits to give back
8498 * the hand at the HAProxy scheduler. It is used when the
8499 * LUA processing consumes a lot of time.
8500 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01008501__LJMP static int hlua_yield_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008502{
8503 return 0;
8504}
8505
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01008506__LJMP static int hlua_yield(lua_State *L)
8507{
Willy Tarreau9635e032018-10-16 17:52:55 +02008508 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_yield_yield, TICK_ETERNITY, HLUA_CTRLYIELD));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008509 return 0;
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01008510}
8511
Thierry FOURNIER37196f42015-02-16 19:34:56 +01008512/* This function change the nice of the currently executed
8513 * task. It is used set low or high priority at the current
8514 * task.
8515 */
Willy Tarreau59551662015-03-10 14:23:13 +01008516__LJMP static int hlua_set_nice(lua_State *L)
Thierry FOURNIER37196f42015-02-16 19:34:56 +01008517{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01008518 struct hlua *hlua;
8519 int nice;
Thierry FOURNIER37196f42015-02-16 19:34:56 +01008520
Willy Tarreau80f5fae2015-02-27 16:38:20 +01008521 MAY_LJMP(check_args(L, 1, "set_nice"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01008522 nice = MAY_LJMP(luaL_checkinteger(L, 1));
Thierry FOURNIER37196f42015-02-16 19:34:56 +01008523
Thierry Fournier4234dbd2020-11-28 13:18:23 +01008524 /* Get hlua struct, or NULL if we execute from main lua state */
8525 hlua = hlua_gethlua(L);
8526
8527 /* If the task is not set, I'm in a start mode. */
Thierry FOURNIER37196f42015-02-16 19:34:56 +01008528 if (!hlua || !hlua->task)
8529 return 0;
8530
8531 if (nice < -1024)
8532 nice = -1024;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01008533 else if (nice > 1024)
Thierry FOURNIER37196f42015-02-16 19:34:56 +01008534 nice = 1024;
8535
8536 hlua->task->nice = nice;
8537 return 0;
8538}
8539
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08008540/* This function is used as a callback of a task. It is called by the
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008541 * HAProxy task subsystem when the task is awaked. The LUA runtime can
8542 * return an E_AGAIN signal, the emmiter of this signal must set a
8543 * signal to wake the task.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008544 *
8545 * Task wrapper are longjmp safe because the only one Lua code
8546 * executed is the safe hlua_ctx_resume();
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008547 */
Willy Tarreau144f84a2021-03-02 16:09:26 +01008548struct task *hlua_process_task(struct task *task, void *context, unsigned int state)
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008549{
Olivier Houchard9f6af332018-05-25 14:04:04 +02008550 struct hlua *hlua = context;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008551 enum hlua_exec status;
8552
Willy Tarreau6ef52f42022-06-15 14:19:48 +02008553 if (task->tid < 0)
8554 task->tid = tid;
8555
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008556 /* If it is the first call to the task, we must initialize the
8557 * execution timeouts.
8558 */
8559 if (!HLUA_IS_RUNNING(hlua))
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02008560 hlua->max_time = hlua_timeout_task;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008561
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008562 /* Execute the Lua code. */
8563 status = hlua_ctx_resume(hlua, 1);
8564
8565 switch (status) {
8566 /* finished or yield */
8567 case HLUA_E_OK:
8568 hlua_ctx_destroy(hlua);
Olivier Houchard3f795f72019-04-17 22:51:06 +02008569 task_destroy(task);
Tim Duesterhuscd235c62018-04-24 13:56:01 +02008570 task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008571 break;
8572
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01008573 case HLUA_E_AGAIN: /* co process or timeout wake me later. */
Thierry FOURNIERcb146882017-12-10 17:10:57 +01008574 notification_gc(&hlua->com);
PiBa-NLfe971b32018-05-02 22:27:14 +02008575 task->expire = hlua->wake_time;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008576 break;
8577
8578 /* finished with error. */
Aurelien DARRAGON79544102022-11-24 14:27:15 +01008579 case HLUA_E_ETMOUT:
8580 SEND_ERR(NULL, "Lua task: execution timeout.\n");
8581 goto err_task_abort;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008582 case HLUA_E_ERRMSG:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008583 SEND_ERR(NULL, "Lua task: %s.\n", lua_tostring(hlua->T, -1));
Aurelien DARRAGON79544102022-11-24 14:27:15 +01008584 goto err_task_abort;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008585 case HLUA_E_ERR:
8586 default:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008587 SEND_ERR(NULL, "Lua task: unknown error.\n");
Aurelien DARRAGON79544102022-11-24 14:27:15 +01008588 err_task_abort:
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008589 hlua_ctx_destroy(hlua);
Olivier Houchard3f795f72019-04-17 22:51:06 +02008590 task_destroy(task);
Emeric Brun253e53e2017-10-17 18:58:40 +02008591 task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008592 break;
8593 }
Emeric Brun253e53e2017-10-17 18:58:40 +02008594 return task;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008595}
8596
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008597/* This function is an LUA binding that register LUA function to be
8598 * executed after the HAProxy configuration parsing and before the
8599 * HAProxy scheduler starts. This function expect only one LUA
8600 * argument that is a function. This function returns nothing, but
8601 * throws if an error is encountered.
8602 */
8603__LJMP static int hlua_register_init(lua_State *L)
8604{
8605 struct hlua_init_function *init;
8606 int ref;
8607
8608 MAY_LJMP(check_args(L, 1, "register_init"));
8609
8610 ref = MAY_LJMP(hlua_checkfunction(L, 1));
8611
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02008612 init = calloc(1, sizeof(*init));
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008613 if (!init)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01008614 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008615
8616 init->function_ref = ref;
Willy Tarreau2b718102021-04-21 07:32:39 +02008617 LIST_APPEND(&hlua_init_functions[hlua_state_id], &init->l);
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008618 return 0;
8619}
8620
Ilya Shipitsin6f86eaa2022-11-30 16:22:42 +05008621/* This function is an LUA binding. It permits to register a task
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008622 * executed in parallel of the main HAroxy activity. The task is
8623 * created and it is set in the HAProxy scheduler. It can be called
8624 * from the "init" section, "post init" or during the runtime.
8625 *
8626 * Lua prototype:
8627 *
8628 * <none> core.register_task(<function>)
8629 */
8630static int hlua_register_task(lua_State *L)
8631{
Christopher Faulet5294ec02021-04-12 12:24:47 +02008632 struct hlua *hlua = NULL;
8633 struct task *task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008634 int ref;
Thierry Fournier021d9862020-11-28 23:42:03 +01008635 int state_id;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008636
8637 MAY_LJMP(check_args(L, 1, "register_task"));
8638
8639 ref = MAY_LJMP(hlua_checkfunction(L, 1));
8640
Thierry Fournier75fc0292020-11-28 13:18:56 +01008641 /* Get the reference state. If the reference is NULL, L is the master
8642 * state, otherwise hlua->T is.
8643 */
8644 hlua = hlua_gethlua(L);
8645 if (hlua)
Thierry Fournier021d9862020-11-28 23:42:03 +01008646 /* we are in runtime processing */
8647 state_id = hlua->state_id;
Thierry Fournier75fc0292020-11-28 13:18:56 +01008648 else
Thierry Fournier021d9862020-11-28 23:42:03 +01008649 /* we are in initialization mode */
Thierry Fournierc7492592020-11-28 23:57:24 +01008650 state_id = hlua_state_id;
Thierry Fournier75fc0292020-11-28 13:18:56 +01008651
Willy Tarreaubafbe012017-11-24 17:34:44 +01008652 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008653 if (!hlua)
Christopher Faulet5294ec02021-04-12 12:24:47 +02008654 goto alloc_error;
Christopher Faulet1e8433f2021-03-24 15:03:01 +01008655 HLUA_INIT(hlua);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008656
Thierry Fournier59f11be2020-11-29 00:37:41 +01008657 /* We are in the common lua state, execute the task anywhere,
8658 * otherwise, inherit the current thread identifier
8659 */
8660 if (state_id == 0)
Willy Tarreaubeeabf52021-10-01 18:23:30 +02008661 task = task_new_anywhere();
Thierry Fournier59f11be2020-11-29 00:37:41 +01008662 else
Willy Tarreaubeeabf52021-10-01 18:23:30 +02008663 task = task_new_here();
Willy Tarreaue09101e2018-10-16 17:37:12 +02008664 if (!task)
Christopher Faulet5294ec02021-04-12 12:24:47 +02008665 goto alloc_error;
Willy Tarreaue09101e2018-10-16 17:37:12 +02008666
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008667 task->context = hlua;
8668 task->process = hlua_process_task;
8669
Thierry Fournier021d9862020-11-28 23:42:03 +01008670 if (!hlua_ctx_init(hlua, state_id, task, 1))
Christopher Faulet5294ec02021-04-12 12:24:47 +02008671 goto alloc_error;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008672
8673 /* Restore the function in the stack. */
8674 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ref);
8675 hlua->nargs = 0;
8676
8677 /* Schedule task. */
Willy Tarreaue3957f82021-09-30 16:17:37 +02008678 task_wakeup(task, TASK_WOKEN_INIT);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008679
8680 return 0;
Christopher Faulet5294ec02021-04-12 12:24:47 +02008681
8682 alloc_error:
8683 task_destroy(task);
8684 hlua_ctx_destroy(hlua);
8685 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
8686 return 0; /* Never reached */
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008687}
8688
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008689/* Wrapper called by HAProxy to execute an LUA converter. This wrapper
8690 * doesn't allow "yield" functions because the HAProxy engine cannot
8691 * resume converters.
8692 */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02008693static int hlua_sample_conv_wrapper(const struct arg *arg_p, struct sample *smp, void *private)
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008694{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02008695 struct hlua_function *fcn = private;
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02008696 struct stream *stream = smp->strm;
Thierry Fournierfd107a22016-02-19 19:57:23 +01008697 const char *error;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008698
Willy Tarreaube508f12016-03-10 11:47:01 +01008699 if (!stream)
8700 return 0;
8701
Willy Tarreau87b09662015-04-03 00:22:06 +02008702 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01008703 * Lua context can be not initialized. This behavior
8704 * permits to save performances because a systematic
8705 * Lua initialization cause 5% performances loss.
8706 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008707 if (!stream->hlua) {
Christopher Faulet1e8433f2021-03-24 15:03:01 +01008708 struct hlua *hlua;
8709
8710 hlua = pool_alloc(pool_head_hlua);
8711 if (!hlua) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008712 SEND_ERR(stream->be, "Lua converter '%s': can't initialize Lua context.\n", fcn->name);
8713 return 0;
8714 }
Christopher Faulet1e8433f2021-03-24 15:03:01 +01008715 HLUA_INIT(hlua);
8716 stream->hlua = hlua;
Thierry Fournierc7492592020-11-28 23:57:24 +01008717 if (!hlua_ctx_init(stream->hlua, fcn_ref_to_stack_id(fcn), stream->task, 0)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008718 SEND_ERR(stream->be, "Lua converter '%s': can't initialize Lua context.\n", fcn->name);
8719 return 0;
8720 }
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01008721 }
8722
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008723 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008724 if (!HLUA_IS_RUNNING(stream->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008725
8726 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008727 if (!SET_SAFE_LJMP(stream->hlua)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008728 if (lua_type(stream->hlua->T, -1) == LUA_TSTRING)
8729 error = lua_tostring(stream->hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +01008730 else
8731 error = "critical error";
8732 SEND_ERR(stream->be, "Lua converter '%s': %s.\n", fcn->name, error);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008733 return 0;
8734 }
8735
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008736 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008737 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008738 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008739 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008740 return 0;
8741 }
8742
8743 /* Restore the function in the stack. */
Thierry Fournierc7492592020-11-28 23:57:24 +01008744 lua_rawgeti(stream->hlua->T, LUA_REGISTRYINDEX, fcn->function_ref[stream->hlua->state_id]);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008745
8746 /* convert input sample and pust-it in the stack. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008747 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008748 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008749 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008750 return 0;
8751 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008752 hlua_smp2lua(stream->hlua->T, smp);
8753 stream->hlua->nargs = 1;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008754
8755 /* push keywords in the stack. */
8756 if (arg_p) {
8757 for (; arg_p->type != ARGT_STOP; arg_p++) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008758 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008759 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008760 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008761 return 0;
8762 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008763 hlua_arg2lua(stream->hlua->T, arg_p);
8764 stream->hlua->nargs++;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008765 }
8766 }
8767
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008768 /* We must initialize the execution timeouts. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008769 stream->hlua->max_time = hlua_timeout_session;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008770
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008771 /* At this point the execution is safe. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008772 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008773 }
8774
8775 /* Execute the function. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008776 switch (hlua_ctx_resume(stream->hlua, 0)) {
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008777 /* finished. */
8778 case HLUA_E_OK:
Thierry FOURNIERfd80df12017-05-12 16:32:20 +02008779 /* If the stack is empty, the function fails. */
8780 if (lua_gettop(stream->hlua->T) <= 0)
8781 return 0;
8782
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008783 /* Convert the returned value in sample. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008784 hlua_lua2smp(stream->hlua->T, -1, smp);
8785 lua_pop(stream->hlua->T, 1);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008786 return 1;
8787
8788 /* yield. */
8789 case HLUA_E_AGAIN:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008790 SEND_ERR(stream->be, "Lua converter '%s': cannot use yielded functions.\n", fcn->name);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008791 return 0;
8792
8793 /* finished with error. */
8794 case HLUA_E_ERRMSG:
8795 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008796 SEND_ERR(stream->be, "Lua converter '%s': %s.\n",
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008797 fcn->name, lua_tostring(stream->hlua->T, -1));
8798 lua_pop(stream->hlua->T, 1);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008799 return 0;
8800
Thierry Fournierd5b073c2018-05-21 19:42:47 +02008801 case HLUA_E_ETMOUT:
8802 SEND_ERR(stream->be, "Lua converter '%s': execution timeout.\n", fcn->name);
8803 return 0;
8804
8805 case HLUA_E_NOMEM:
8806 SEND_ERR(stream->be, "Lua converter '%s': out of memory error.\n", fcn->name);
8807 return 0;
8808
8809 case HLUA_E_YIELD:
8810 SEND_ERR(stream->be, "Lua converter '%s': yield functions like core.tcp() or core.sleep() are not allowed.\n", fcn->name);
8811 return 0;
8812
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008813 case HLUA_E_ERR:
8814 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008815 SEND_ERR(stream->be, "Lua converter '%s' returns an unknown error.\n", fcn->name);
Willy Tarreau14de3952022-11-14 07:08:28 +01008816 __fallthrough;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008817
8818 default:
8819 return 0;
8820 }
8821}
8822
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008823/* Wrapper called by HAProxy to execute a sample-fetch. this wrapper
8824 * doesn't allow "yield" functions because the HAProxy engine cannot
Willy Tarreaube508f12016-03-10 11:47:01 +01008825 * resume sample-fetches. This function will be called by the sample
8826 * fetch engine to call lua-based fetch operations.
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008827 */
Thierry FOURNIER0786d052015-05-11 15:42:45 +02008828static int hlua_sample_fetch_wrapper(const struct arg *arg_p, struct sample *smp,
8829 const char *kw, void *private)
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008830{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02008831 struct hlua_function *fcn = private;
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02008832 struct stream *stream = smp->strm;
Thierry Fournierfd107a22016-02-19 19:57:23 +01008833 const char *error;
Christopher Faulet8c9e6bb2021-08-06 16:29:41 +02008834 unsigned int hflags = HLUA_TXN_NOTERM | HLUA_TXN_SMP_CTX;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008835
Willy Tarreaube508f12016-03-10 11:47:01 +01008836 if (!stream)
8837 return 0;
Christopher Fauletafd8f102018-11-08 11:34:21 +01008838
Willy Tarreau87b09662015-04-03 00:22:06 +02008839 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01008840 * Lua context can be not initialized. This behavior
8841 * permits to save performances because a systematic
8842 * Lua initialization cause 5% performances loss.
8843 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008844 if (!stream->hlua) {
Christopher Faulet1e8433f2021-03-24 15:03:01 +01008845 struct hlua *hlua;
8846
8847 hlua = pool_alloc(pool_head_hlua);
8848 if (!hlua) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008849 SEND_ERR(stream->be, "Lua sample-fetch '%s': can't initialize Lua context.\n", fcn->name);
8850 return 0;
8851 }
Christopher Faulet1e8433f2021-03-24 15:03:01 +01008852 hlua->T = NULL;
8853 stream->hlua = hlua;
Thierry Fournierc7492592020-11-28 23:57:24 +01008854 if (!hlua_ctx_init(stream->hlua, fcn_ref_to_stack_id(fcn), stream->task, 0)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008855 SEND_ERR(stream->be, "Lua sample-fetch '%s': can't initialize Lua context.\n", fcn->name);
8856 return 0;
8857 }
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01008858 }
8859
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008860 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008861 if (!HLUA_IS_RUNNING(stream->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008862
8863 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008864 if (!SET_SAFE_LJMP(stream->hlua)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008865 if (lua_type(stream->hlua->T, -1) == LUA_TSTRING)
8866 error = lua_tostring(stream->hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +01008867 else
8868 error = "critical error";
8869 SEND_ERR(smp->px, "Lua sample-fetch '%s': %s.\n", fcn->name, error);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008870 return 0;
8871 }
8872
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008873 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008874 if (!lua_checkstack(stream->hlua->T, 2)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008875 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008876 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008877 return 0;
8878 }
8879
8880 /* Restore the function in the stack. */
Thierry Fournierc7492592020-11-28 23:57:24 +01008881 lua_rawgeti(stream->hlua->T, LUA_REGISTRYINDEX, fcn->function_ref[stream->hlua->state_id]);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008882
8883 /* push arguments in the stack. */
Christopher Fauletbfab2dd2019-07-26 15:09:53 +02008884 if (!hlua_txn_new(stream->hlua->T, stream, smp->px, smp->opt & SMP_OPT_DIR, hflags)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008885 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008886 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008887 return 0;
8888 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008889 stream->hlua->nargs = 1;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008890
8891 /* push keywords in the stack. */
8892 for (; arg_p && arg_p->type != ARGT_STOP; arg_p++) {
8893 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008894 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008895 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008896 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008897 return 0;
8898 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008899 hlua_arg2lua(stream->hlua->T, arg_p);
8900 stream->hlua->nargs++;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008901 }
8902
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008903 /* We must initialize the execution timeouts. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008904 stream->hlua->max_time = hlua_timeout_session;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008905
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008906 /* At this point the execution is safe. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008907 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008908 }
8909
8910 /* Execute the function. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008911 switch (hlua_ctx_resume(stream->hlua, 0)) {
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008912 /* finished. */
8913 case HLUA_E_OK:
Thierry FOURNIERfd80df12017-05-12 16:32:20 +02008914 /* If the stack is empty, the function fails. */
8915 if (lua_gettop(stream->hlua->T) <= 0)
8916 return 0;
8917
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008918 /* Convert the returned value in sample. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008919 hlua_lua2smp(stream->hlua->T, -1, smp);
8920 lua_pop(stream->hlua->T, 1);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008921
8922 /* Set the end of execution flag. */
8923 smp->flags &= ~SMP_F_MAY_CHANGE;
8924 return 1;
8925
8926 /* yield. */
8927 case HLUA_E_AGAIN:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008928 SEND_ERR(smp->px, "Lua sample-fetch '%s': cannot use yielded functions.\n", fcn->name);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008929 return 0;
8930
8931 /* finished with error. */
8932 case HLUA_E_ERRMSG:
8933 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008934 SEND_ERR(smp->px, "Lua sample-fetch '%s': %s.\n",
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008935 fcn->name, lua_tostring(stream->hlua->T, -1));
8936 lua_pop(stream->hlua->T, 1);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008937 return 0;
8938
Thierry Fournierd5b073c2018-05-21 19:42:47 +02008939 case HLUA_E_ETMOUT:
Thierry Fournierd5b073c2018-05-21 19:42:47 +02008940 SEND_ERR(smp->px, "Lua sample-fetch '%s': execution timeout.\n", fcn->name);
8941 return 0;
8942
8943 case HLUA_E_NOMEM:
Thierry Fournierd5b073c2018-05-21 19:42:47 +02008944 SEND_ERR(smp->px, "Lua sample-fetch '%s': out of memory error.\n", fcn->name);
8945 return 0;
8946
8947 case HLUA_E_YIELD:
Thierry Fournierd5b073c2018-05-21 19:42:47 +02008948 SEND_ERR(smp->px, "Lua sample-fetch '%s': yield not allowed.\n", fcn->name);
8949 return 0;
8950
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008951 case HLUA_E_ERR:
8952 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008953 SEND_ERR(smp->px, "Lua sample-fetch '%s' returns an unknown error.\n", fcn->name);
Willy Tarreau14de3952022-11-14 07:08:28 +01008954 __fallthrough;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008955
8956 default:
8957 return 0;
8958 }
8959}
8960
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008961/* This function is an LUA binding used for registering
8962 * "sample-conv" functions. It expects a converter name used
8963 * in the haproxy configuration file, and an LUA function.
8964 */
8965__LJMP static int hlua_register_converters(lua_State *L)
8966{
8967 struct sample_conv_kw_list *sck;
8968 const char *name;
8969 int ref;
8970 int len;
Christopher Fauletaa224302021-04-12 14:08:21 +02008971 struct hlua_function *fcn = NULL;
Thierry Fournierf67442e2020-11-28 20:41:07 +01008972 struct sample_conv *sc;
8973 struct buffer *trash;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008974
8975 MAY_LJMP(check_args(L, 2, "register_converters"));
8976
8977 /* First argument : converter name. */
8978 name = MAY_LJMP(luaL_checkstring(L, 1));
8979
8980 /* Second argument : lua function. */
8981 ref = MAY_LJMP(hlua_checkfunction(L, 2));
8982
Thierry Fournierf67442e2020-11-28 20:41:07 +01008983 /* Check if the converter is already registered */
8984 trash = get_trash_chunk();
8985 chunk_printf(trash, "lua.%s", name);
8986 sc = find_sample_conv(trash->area, trash->data);
8987 if (sc != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +01008988 fcn = sc->private;
8989 if (fcn->function_ref[hlua_state_id] != -1) {
8990 ha_warning("Trying to register converter 'lua.%s' more than once. "
8991 "This will become a hard error in version 2.5.\n", name);
8992 }
8993 fcn->function_ref[hlua_state_id] = ref;
8994 return 0;
Thierry Fournierf67442e2020-11-28 20:41:07 +01008995 }
8996
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008997 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02008998 sck = calloc(1, sizeof(*sck) + sizeof(struct sample_conv) * 2);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008999 if (!sck)
Christopher Fauletaa224302021-04-12 14:08:21 +02009000 goto alloc_error;
Thierry Fournier62a22aa2020-11-28 21:06:35 +01009001 fcn = new_hlua_function();
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009002 if (!fcn)
Christopher Fauletaa224302021-04-12 14:08:21 +02009003 goto alloc_error;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009004
9005 /* Fill fcn. */
9006 fcn->name = strdup(name);
9007 if (!fcn->name)
Christopher Fauletaa224302021-04-12 14:08:21 +02009008 goto alloc_error;
Thierry Fournierc7492592020-11-28 23:57:24 +01009009 fcn->function_ref[hlua_state_id] = ref;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009010
9011 /* List head */
9012 sck->list.n = sck->list.p = NULL;
9013
9014 /* converter keyword. */
9015 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02009016 sck->kw[0].kw = calloc(1, len);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009017 if (!sck->kw[0].kw)
Christopher Fauletaa224302021-04-12 14:08:21 +02009018 goto alloc_error;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009019
9020 snprintf((char *)sck->kw[0].kw, len, "lua.%s", name);
9021 sck->kw[0].process = hlua_sample_conv_wrapper;
David Carlier0c437f42016-04-27 16:21:56 +01009022 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 +01009023 sck->kw[0].val_args = NULL;
9024 sck->kw[0].in_type = SMP_T_STR;
9025 sck->kw[0].out_type = SMP_T_STR;
9026 sck->kw[0].private = fcn;
9027
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009028 /* Register this new converter */
9029 sample_register_convs(sck);
9030
9031 return 0;
Christopher Fauletaa224302021-04-12 14:08:21 +02009032
9033 alloc_error:
9034 release_hlua_function(fcn);
9035 ha_free(&sck);
9036 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
9037 return 0; /* Never reached */
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009038}
9039
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08009040/* This function is an LUA binding used for registering
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009041 * "sample-fetch" functions. It expects a converter name used
9042 * in the haproxy configuration file, and an LUA function.
9043 */
9044__LJMP static int hlua_register_fetches(lua_State *L)
9045{
9046 const char *name;
9047 int ref;
9048 int len;
9049 struct sample_fetch_kw_list *sfk;
Christopher Faulet2567f182021-04-12 14:11:50 +02009050 struct hlua_function *fcn = NULL;
Thierry Fournierf67442e2020-11-28 20:41:07 +01009051 struct sample_fetch *sf;
9052 struct buffer *trash;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009053
9054 MAY_LJMP(check_args(L, 2, "register_fetches"));
9055
9056 /* First argument : sample-fetch name. */
9057 name = MAY_LJMP(luaL_checkstring(L, 1));
9058
9059 /* Second argument : lua function. */
9060 ref = MAY_LJMP(hlua_checkfunction(L, 2));
9061
Thierry Fournierf67442e2020-11-28 20:41:07 +01009062 /* Check if the sample-fetch is already registered */
9063 trash = get_trash_chunk();
9064 chunk_printf(trash, "lua.%s", name);
9065 sf = find_sample_fetch(trash->area, trash->data);
9066 if (sf != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +01009067 fcn = sf->private;
9068 if (fcn->function_ref[hlua_state_id] != -1) {
9069 ha_warning("Trying to register sample-fetch 'lua.%s' more than once. "
9070 "This will become a hard error in version 2.5.\n", name);
9071 }
9072 fcn->function_ref[hlua_state_id] = ref;
9073 return 0;
Thierry Fournierf67442e2020-11-28 20:41:07 +01009074 }
9075
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009076 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02009077 sfk = calloc(1, sizeof(*sfk) + sizeof(struct sample_fetch) * 2);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009078 if (!sfk)
Christopher Faulet2567f182021-04-12 14:11:50 +02009079 goto alloc_error;
Thierry Fournier62a22aa2020-11-28 21:06:35 +01009080 fcn = new_hlua_function();
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009081 if (!fcn)
Christopher Faulet2567f182021-04-12 14:11:50 +02009082 goto alloc_error;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009083
9084 /* Fill fcn. */
9085 fcn->name = strdup(name);
9086 if (!fcn->name)
Christopher Faulet2567f182021-04-12 14:11:50 +02009087 goto alloc_error;
Thierry Fournierc7492592020-11-28 23:57:24 +01009088 fcn->function_ref[hlua_state_id] = ref;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009089
9090 /* List head */
9091 sfk->list.n = sfk->list.p = NULL;
9092
9093 /* sample-fetch keyword. */
9094 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02009095 sfk->kw[0].kw = calloc(1, len);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009096 if (!sfk->kw[0].kw)
Christopher Faulet2567f182021-04-12 14:11:50 +02009097 goto alloc_error;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009098
9099 snprintf((char *)sfk->kw[0].kw, len, "lua.%s", name);
9100 sfk->kw[0].process = hlua_sample_fetch_wrapper;
David Carlier0c437f42016-04-27 16:21:56 +01009101 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 +01009102 sfk->kw[0].val_args = NULL;
9103 sfk->kw[0].out_type = SMP_T_STR;
9104 sfk->kw[0].use = SMP_USE_HTTP_ANY;
9105 sfk->kw[0].val = 0;
9106 sfk->kw[0].private = fcn;
9107
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009108 /* Register this new fetch. */
9109 sample_register_fetches(sfk);
9110
9111 return 0;
Christopher Faulet2567f182021-04-12 14:11:50 +02009112
9113 alloc_error:
9114 release_hlua_function(fcn);
9115 ha_free(&sfk);
9116 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
9117 return 0; /* Never reached */
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009118}
9119
Christopher Faulet501465d2020-02-26 14:54:16 +01009120/* This function is a lua binding to set the wake_time.
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01009121 */
Christopher Faulet501465d2020-02-26 14:54:16 +01009122__LJMP static int hlua_set_wake_time(lua_State *L)
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01009123{
Thierry Fournier4234dbd2020-11-28 13:18:23 +01009124 struct hlua *hlua;
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01009125 unsigned int delay;
9126 unsigned int wakeup_ms;
9127
Thierry Fournier4234dbd2020-11-28 13:18:23 +01009128 /* Get hlua struct, or NULL if we execute from main lua state */
9129 hlua = hlua_gethlua(L);
9130 if (!hlua) {
9131 return 0;
9132 }
9133
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01009134 MAY_LJMP(check_args(L, 1, "wake_time"));
9135
9136 delay = MAY_LJMP(luaL_checkinteger(L, 1));
9137 wakeup_ms = tick_add(now_ms, delay);
9138 hlua->wake_time = wakeup_ms;
9139 return 0;
9140}
9141
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009142/* This function is a wrapper to execute each LUA function declared as an action
9143 * wrapper during the initialisation period. This function may return any
9144 * ACT_RET_* value. On error ACT_RET_CONT is returned and the action is
9145 * ignored. If the lua action yields, ACT_RET_YIELD is returned. On success, the
9146 * return value is the first element on the stack.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009147 */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009148static enum act_return hlua_action(struct act_rule *rule, struct proxy *px,
Willy Tarreau658b85b2015-09-27 10:00:49 +02009149 struct session *sess, struct stream *s, int flags)
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009150{
9151 char **arg;
Christopher Faulet8c9e6bb2021-08-06 16:29:41 +02009152 unsigned int hflags = HLUA_TXN_ACT_CTX;
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009153 int dir, act_ret = ACT_RET_CONT;
Thierry Fournierfd107a22016-02-19 19:57:23 +01009154 const char *error;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009155
9156 switch (rule->from) {
Christopher Fauletd8f0e072020-02-25 09:45:51 +01009157 case ACT_F_TCP_REQ_CNT: dir = SMP_OPT_DIR_REQ; break;
9158 case ACT_F_TCP_RES_CNT: dir = SMP_OPT_DIR_RES; break;
9159 case ACT_F_HTTP_REQ: dir = SMP_OPT_DIR_REQ; break;
9160 case ACT_F_HTTP_RES: dir = SMP_OPT_DIR_RES; break;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009161 default:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009162 SEND_ERR(px, "Lua: internal error while execute action.\n");
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009163 goto end;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009164 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009165
Willy Tarreau87b09662015-04-03 00:22:06 +02009166 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01009167 * Lua context can be not initialized. This behavior
9168 * permits to save performances because a systematic
9169 * Lua initialization cause 5% performances loss.
9170 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009171 if (!s->hlua) {
Christopher Faulet1e8433f2021-03-24 15:03:01 +01009172 struct hlua *hlua;
9173
9174 hlua = pool_alloc(pool_head_hlua);
9175 if (!hlua) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009176 SEND_ERR(px, "Lua action '%s': can't initialize Lua context.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009177 rule->arg.hlua_rule->fcn->name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009178 goto end;
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009179 }
Christopher Faulet1e8433f2021-03-24 15:03:01 +01009180 HLUA_INIT(hlua);
9181 s->hlua = hlua;
Thierry Fournierc7492592020-11-28 23:57:24 +01009182 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 +01009183 SEND_ERR(px, "Lua action '%s': can't initialize Lua context.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009184 rule->arg.hlua_rule->fcn->name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009185 goto end;
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009186 }
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01009187 }
9188
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009189 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009190 if (!HLUA_IS_RUNNING(s->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02009191
9192 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009193 if (!SET_SAFE_LJMP(s->hlua)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009194 if (lua_type(s->hlua->T, -1) == LUA_TSTRING)
9195 error = lua_tostring(s->hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +01009196 else
9197 error = "critical error";
9198 SEND_ERR(px, "Lua function '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009199 rule->arg.hlua_rule->fcn->name, error);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009200 goto end;
Thierry FOURNIERbabae282015-09-17 11:36:37 +02009201 }
9202
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009203 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009204 if (!lua_checkstack(s->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009205 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009206 rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009207 RESET_SAFE_LJMP(s->hlua);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009208 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009209 }
9210
9211 /* Restore the function in the stack. */
Thierry Fournierc7492592020-11-28 23:57:24 +01009212 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 +01009213
Willy Tarreau87b09662015-04-03 00:22:06 +02009214 /* Create and and push object stream in the stack. */
Christopher Fauletbfab2dd2019-07-26 15:09:53 +02009215 if (!hlua_txn_new(s->hlua->T, s, px, dir, hflags)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009216 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009217 rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009218 RESET_SAFE_LJMP(s->hlua);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009219 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009220 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009221 s->hlua->nargs = 1;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009222
9223 /* push keywords in the stack. */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009224 for (arg = rule->arg.hlua_rule->args; arg && *arg; arg++) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009225 if (!lua_checkstack(s->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009226 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009227 rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009228 RESET_SAFE_LJMP(s->hlua);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009229 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009230 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009231 lua_pushstring(s->hlua->T, *arg);
9232 s->hlua->nargs++;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009233 }
9234
Thierry FOURNIERbabae282015-09-17 11:36:37 +02009235 /* Now the execution is safe. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009236 RESET_SAFE_LJMP(s->hlua);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02009237
Thierry FOURNIERbd413492015-03-03 16:52:26 +01009238 /* We must initialize the execution timeouts. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009239 s->hlua->max_time = hlua_timeout_session;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009240 }
9241
9242 /* Execute the function. */
Christopher Faulet105ba6c2019-12-18 14:41:51 +01009243 switch (hlua_ctx_resume(s->hlua, !(flags & ACT_OPT_FINAL))) {
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009244 /* finished. */
9245 case HLUA_E_OK:
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009246 /* Catch the return value */
9247 if (lua_gettop(s->hlua->T) > 0)
9248 act_ret = lua_tointeger(s->hlua->T, -1);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009249
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01009250 /* Set timeout in the required channel. */
Christopher Faulet498c4832020-07-28 11:59:58 +02009251 if (act_ret == ACT_RET_YIELD) {
9252 if (flags & ACT_OPT_FINAL)
9253 goto err_yield;
9254
Christopher Faulet8f587ea2020-07-28 12:01:55 +02009255 if (dir == SMP_OPT_DIR_REQ)
9256 s->req.analyse_exp = tick_first((tick_is_expired(s->req.analyse_exp, now_ms) ? 0 : s->req.analyse_exp),
9257 s->hlua->wake_time);
9258 else
9259 s->res.analyse_exp = tick_first((tick_is_expired(s->res.analyse_exp, now_ms) ? 0 : s->res.analyse_exp),
9260 s->hlua->wake_time);
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01009261 }
9262 goto end;
9263
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009264 /* yield. */
9265 case HLUA_E_AGAIN:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01009266 /* Set timeout in the required channel. */
Christopher Faulet8f587ea2020-07-28 12:01:55 +02009267 if (dir == SMP_OPT_DIR_REQ)
9268 s->req.analyse_exp = tick_first((tick_is_expired(s->req.analyse_exp, now_ms) ? 0 : s->req.analyse_exp),
9269 s->hlua->wake_time);
9270 else
9271 s->res.analyse_exp = tick_first((tick_is_expired(s->res.analyse_exp, now_ms) ? 0 : s->res.analyse_exp),
9272 s->hlua->wake_time);
9273
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009274 /* Some actions can be wake up when a "write" event
9275 * is detected on a response channel. This is useful
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08009276 * only for actions targeted on the requests.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009277 */
Christopher Faulet51fa3582019-07-26 14:54:52 +02009278 if (HLUA_IS_WAKERESWR(s->hlua))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01009279 s->res.flags |= CF_WAKE_WRITE;
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009280 if (HLUA_IS_WAKEREQWR(s->hlua))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01009281 s->req.flags |= CF_WAKE_WRITE;
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009282 act_ret = ACT_RET_YIELD;
9283 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009284
9285 /* finished with error. */
9286 case HLUA_E_ERRMSG:
9287 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009288 SEND_ERR(px, "Lua function '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009289 rule->arg.hlua_rule->fcn->name, lua_tostring(s->hlua->T, -1));
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009290 lua_pop(s->hlua->T, 1);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009291 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009292
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009293 case HLUA_E_ETMOUT:
Thierry Fournierad5345f2020-11-29 02:05:57 +01009294 SEND_ERR(px, "Lua function '%s': execution timeout.\n", rule->arg.hlua_rule->fcn->name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009295 goto end;
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009296
9297 case HLUA_E_NOMEM:
Thierry Fournierad5345f2020-11-29 02:05:57 +01009298 SEND_ERR(px, "Lua function '%s': out of memory error.\n", rule->arg.hlua_rule->fcn->name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009299 goto end;
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009300
9301 case HLUA_E_YIELD:
Christopher Faulet498c4832020-07-28 11:59:58 +02009302 err_yield:
9303 act_ret = ACT_RET_CONT;
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009304 SEND_ERR(px, "Lua function '%s': aborting Lua processing on expired timeout.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009305 rule->arg.hlua_rule->fcn->name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009306 goto end;
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009307
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009308 case HLUA_E_ERR:
9309 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009310 SEND_ERR(px, "Lua function '%s' return an unknown error.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009311 rule->arg.hlua_rule->fcn->name);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009312
9313 default:
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009314 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009315 }
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009316
9317 end:
Christopher Faulet2361fd92020-07-30 10:40:58 +02009318 if (act_ret != ACT_RET_YIELD && s->hlua)
Christopher Faulet8f587ea2020-07-28 12:01:55 +02009319 s->hlua->wake_time = TICK_ETERNITY;
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009320 return act_ret;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009321}
9322
Willy Tarreau144f84a2021-03-02 16:09:26 +01009323struct task *hlua_applet_wakeup(struct task *t, void *context, unsigned int state)
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009324{
Olivier Houchard9f6af332018-05-25 14:04:04 +02009325 struct appctx *ctx = context;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009326
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009327 appctx_wakeup(ctx);
Willy Tarreaud9587412017-08-23 16:07:33 +02009328 t->expire = TICK_ETERNITY;
Willy Tarreaud1aa41f2017-07-21 16:41:56 +02009329 return t;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009330}
9331
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009332static int hlua_applet_tcp_init(struct appctx *ctx)
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009333{
Willy Tarreaue23f33b2022-05-06 14:07:13 +02009334 struct hlua_tcp_ctx *tcp_ctx = applet_reserve_svcctx(ctx, sizeof(*tcp_ctx));
Willy Tarreauc12b3212022-05-27 11:08:15 +02009335 struct stconn *sc = appctx_sc(ctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02009336 struct stream *strm = __sc_strm(sc);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009337 struct hlua *hlua;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009338 struct task *task;
9339 char **arg;
Thierry Fournierfd107a22016-02-19 19:57:23 +01009340 const char *error;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009341
Willy Tarreaubafbe012017-11-24 17:34:44 +01009342 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009343 if (!hlua) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009344 SEND_ERR(strm->be, "Lua applet tcp '%s': out of memory.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009345 ctx->rule->arg.hlua_rule->fcn->name);
Christopher Fauletc9929382022-05-12 11:52:27 +02009346 return -1;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009347 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009348 HLUA_INIT(hlua);
Willy Tarreaue23f33b2022-05-06 14:07:13 +02009349 tcp_ctx->hlua = hlua;
9350 tcp_ctx->flags = 0;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009351
9352 /* Create task used by signal to wakeup applets. */
Willy Tarreaubeeabf52021-10-01 18:23:30 +02009353 task = task_new_here();
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009354 if (!task) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009355 SEND_ERR(strm->be, "Lua applet tcp '%s': out of memory.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009356 ctx->rule->arg.hlua_rule->fcn->name);
Christopher Fauletc9929382022-05-12 11:52:27 +02009357 return -1;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009358 }
9359 task->nice = 0;
9360 task->context = ctx;
9361 task->process = hlua_applet_wakeup;
Willy Tarreaue23f33b2022-05-06 14:07:13 +02009362 tcp_ctx->task = task;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009363
9364 /* In the execution wrappers linked with a stream, the
9365 * Lua context can be not initialized. This behavior
9366 * permits to save performances because a systematic
9367 * Lua initialization cause 5% performances loss.
9368 */
Thierry Fournierc7492592020-11-28 23:57:24 +01009369 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 +01009370 SEND_ERR(strm->be, "Lua applet tcp '%s': can't initialize Lua context.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009371 ctx->rule->arg.hlua_rule->fcn->name);
Christopher Fauletc9929382022-05-12 11:52:27 +02009372 return -1;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009373 }
9374
9375 /* Set timeout according with the applet configuration. */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02009376 hlua->max_time = ctx->applet->timeout;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009377
9378 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009379 if (!SET_SAFE_LJMP(hlua)) {
Thierry Fournierfd107a22016-02-19 19:57:23 +01009380 if (lua_type(hlua->T, -1) == LUA_TSTRING)
9381 error = lua_tostring(hlua->T, -1);
9382 else
9383 error = "critical error";
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009384 SEND_ERR(strm->be, "Lua applet tcp '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009385 ctx->rule->arg.hlua_rule->fcn->name, error);
Christopher Fauletc9929382022-05-12 11:52:27 +02009386 return -1;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009387 }
9388
9389 /* Check stack available size. */
9390 if (!lua_checkstack(hlua->T, 1)) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009391 SEND_ERR(strm->be, "Lua applet tcp '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009392 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009393 RESET_SAFE_LJMP(hlua);
Christopher Fauletc9929382022-05-12 11:52:27 +02009394 return -1;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009395 }
9396
9397 /* Restore the function in the stack. */
Thierry Fournierc7492592020-11-28 23:57:24 +01009398 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ctx->rule->arg.hlua_rule->fcn->function_ref[hlua->state_id]);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009399
9400 /* Create and and push object stream in the stack. */
9401 if (!hlua_applet_tcp_new(hlua->T, ctx)) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009402 SEND_ERR(strm->be, "Lua applet tcp '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009403 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009404 RESET_SAFE_LJMP(hlua);
Christopher Fauletc9929382022-05-12 11:52:27 +02009405 return -1;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009406 }
9407 hlua->nargs = 1;
9408
9409 /* push keywords in the stack. */
9410 for (arg = ctx->rule->arg.hlua_rule->args; arg && *arg; arg++) {
9411 if (!lua_checkstack(hlua->T, 1)) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009412 SEND_ERR(strm->be, "Lua applet tcp '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009413 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009414 RESET_SAFE_LJMP(hlua);
Christopher Fauletc9929382022-05-12 11:52:27 +02009415 return -1;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009416 }
9417 lua_pushstring(hlua->T, *arg);
9418 hlua->nargs++;
9419 }
9420
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009421 RESET_SAFE_LJMP(hlua);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009422
9423 /* Wakeup the applet ASAP. */
Willy Tarreau90e8b452022-05-25 18:21:43 +02009424 applet_need_more_data(ctx);
Willy Tarreau4164eb92022-05-25 15:42:03 +02009425 applet_have_more_data(ctx);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009426
Christopher Fauletc9929382022-05-12 11:52:27 +02009427 return 0;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009428}
9429
Willy Tarreau60409db2019-08-21 14:14:50 +02009430void hlua_applet_tcp_fct(struct appctx *ctx)
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009431{
Willy Tarreaue23f33b2022-05-06 14:07:13 +02009432 struct hlua_tcp_ctx *tcp_ctx = ctx->svcctx;
Willy Tarreauc12b3212022-05-27 11:08:15 +02009433 struct stconn *sc = appctx_sc(ctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02009434 struct stream *strm = __sc_strm(sc);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009435 struct act_rule *rule = ctx->rule;
9436 struct proxy *px = strm->be;
Willy Tarreaue23f33b2022-05-06 14:07:13 +02009437 struct hlua *hlua = tcp_ctx->hlua;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009438
Christopher Faulet31572222023-03-31 11:13:48 +02009439 if (unlikely(se_fl_test(ctx->sedesc, (SE_FL_EOS|SE_FL_ERROR|SE_FL_SHR|SE_FL_SHW))))
9440 goto out;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009441
Christopher Faulet31572222023-03-31 11:13:48 +02009442 /* The applet execution is already done. */
9443 if (tcp_ctx->flags & APPLET_DONE)
9444 goto out;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009445
9446 /* Execute the function. */
9447 switch (hlua_ctx_resume(hlua, 1)) {
9448 /* finished. */
9449 case HLUA_E_OK:
Willy Tarreaue23f33b2022-05-06 14:07:13 +02009450 tcp_ctx->flags |= APPLET_DONE;
Christopher Faulet31572222023-03-31 11:13:48 +02009451 se_fl_set(ctx->sedesc, SE_FL_EOI|SE_FL_EOS);
9452 break;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009453
9454 /* yield. */
9455 case HLUA_E_AGAIN:
Thierry Fournier0164f202016-02-20 17:47:43 +01009456 if (hlua->wake_time != TICK_ETERNITY)
Willy Tarreaue23f33b2022-05-06 14:07:13 +02009457 task_schedule(tcp_ctx->task, hlua->wake_time);
Christopher Faulet31572222023-03-31 11:13:48 +02009458 break;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009459
9460 /* finished with error. */
9461 case HLUA_E_ERRMSG:
9462 /* Display log. */
9463 SEND_ERR(px, "Lua applet tcp '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009464 rule->arg.hlua_rule->fcn->name, lua_tostring(hlua->T, -1));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009465 lua_pop(hlua->T, 1);
9466 goto error;
9467
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009468 case HLUA_E_ETMOUT:
9469 SEND_ERR(px, "Lua applet tcp '%s': execution timeout.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009470 rule->arg.hlua_rule->fcn->name);
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009471 goto error;
9472
9473 case HLUA_E_NOMEM:
9474 SEND_ERR(px, "Lua applet tcp '%s': out of memory error.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009475 rule->arg.hlua_rule->fcn->name);
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009476 goto error;
9477
9478 case HLUA_E_YIELD: /* unexpected */
9479 SEND_ERR(px, "Lua applet tcp '%s': yield not allowed.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009480 rule->arg.hlua_rule->fcn->name);
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009481 goto error;
9482
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009483 case HLUA_E_ERR:
9484 /* Display log. */
9485 SEND_ERR(px, "Lua applet tcp '%s' return an unknown error.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009486 rule->arg.hlua_rule->fcn->name);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009487 goto error;
9488
9489 default:
9490 goto error;
9491 }
9492
Christopher Faulet31572222023-03-31 11:13:48 +02009493out:
9494 /* eat the whole request */
9495 co_skip(sc_oc(sc), co_data(sc_oc(sc)));
9496 return;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009497
Christopher Faulet31572222023-03-31 11:13:48 +02009498error:
9499 se_fl_set(ctx->sedesc, SE_FL_ERROR);
Willy Tarreaue23f33b2022-05-06 14:07:13 +02009500 tcp_ctx->flags |= APPLET_DONE;
Christopher Faulet31572222023-03-31 11:13:48 +02009501 goto out;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009502}
9503
9504static void hlua_applet_tcp_release(struct appctx *ctx)
9505{
Willy Tarreaue23f33b2022-05-06 14:07:13 +02009506 struct hlua_tcp_ctx *tcp_ctx = ctx->svcctx;
9507
9508 task_destroy(tcp_ctx->task);
9509 tcp_ctx->task = NULL;
9510 hlua_ctx_destroy(tcp_ctx->hlua);
9511 tcp_ctx->hlua = NULL;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009512}
9513
Christopher Fauletc9929382022-05-12 11:52:27 +02009514/* The function returns 0 if the initialisation is complete or -1 if
9515 * an errors occurs. It also reserves the appctx for an hlua_http_ctx.
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009516 */
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009517static int hlua_applet_http_init(struct appctx *ctx)
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009518{
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009519 struct hlua_http_ctx *http_ctx = applet_reserve_svcctx(ctx, sizeof(*http_ctx));
Willy Tarreauc12b3212022-05-27 11:08:15 +02009520 struct stconn *sc = appctx_sc(ctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02009521 struct stream *strm = __sc_strm(sc);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009522 struct http_txn *txn;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009523 struct hlua *hlua;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009524 char **arg;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009525 struct task *task;
Thierry Fournierfd107a22016-02-19 19:57:23 +01009526 const char *error;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009527
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009528 txn = strm->txn;
Willy Tarreaubafbe012017-11-24 17:34:44 +01009529 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009530 if (!hlua) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009531 SEND_ERR(strm->be, "Lua applet http '%s': out of memory.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009532 ctx->rule->arg.hlua_rule->fcn->name);
Christopher Fauletc9929382022-05-12 11:52:27 +02009533 return -1;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009534 }
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009535 HLUA_INIT(hlua);
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009536 http_ctx->hlua = hlua;
9537 http_ctx->left_bytes = -1;
9538 http_ctx->flags = 0;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009539
Thierry FOURNIERd93ea2b2015-12-20 19:14:52 +01009540 if (txn->req.flags & HTTP_MSGF_VER_11)
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009541 http_ctx->flags |= APPLET_HTTP11;
Thierry FOURNIERd93ea2b2015-12-20 19:14:52 +01009542
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009543 /* Create task used by signal to wakeup applets. */
Willy Tarreaubeeabf52021-10-01 18:23:30 +02009544 task = task_new_here();
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009545 if (!task) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009546 SEND_ERR(strm->be, "Lua applet http '%s': out of memory.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009547 ctx->rule->arg.hlua_rule->fcn->name);
Christopher Fauletc9929382022-05-12 11:52:27 +02009548 return -1;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009549 }
9550 task->nice = 0;
9551 task->context = ctx;
9552 task->process = hlua_applet_wakeup;
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009553 http_ctx->task = task;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009554
9555 /* In the execution wrappers linked with a stream, the
9556 * Lua context can be not initialized. This behavior
9557 * permits to save performances because a systematic
9558 * Lua initialization cause 5% performances loss.
9559 */
Thierry Fournierc7492592020-11-28 23:57:24 +01009560 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 +01009561 SEND_ERR(strm->be, "Lua applet http '%s': can't initialize Lua context.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009562 ctx->rule->arg.hlua_rule->fcn->name);
Christopher Fauletc9929382022-05-12 11:52:27 +02009563 return -1;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009564 }
9565
9566 /* Set timeout according with the applet configuration. */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02009567 hlua->max_time = ctx->applet->timeout;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009568
9569 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009570 if (!SET_SAFE_LJMP(hlua)) {
Thierry Fournierfd107a22016-02-19 19:57:23 +01009571 if (lua_type(hlua->T, -1) == LUA_TSTRING)
9572 error = lua_tostring(hlua->T, -1);
9573 else
9574 error = "critical error";
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009575 SEND_ERR(strm->be, "Lua applet http '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009576 ctx->rule->arg.hlua_rule->fcn->name, error);
Christopher Fauletc9929382022-05-12 11:52:27 +02009577 return -1;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009578 }
9579
9580 /* Check stack available size. */
9581 if (!lua_checkstack(hlua->T, 1)) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009582 SEND_ERR(strm->be, "Lua applet http '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009583 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009584 RESET_SAFE_LJMP(hlua);
Christopher Fauletc9929382022-05-12 11:52:27 +02009585 return -1;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009586 }
9587
9588 /* Restore the function in the stack. */
Thierry Fournierc7492592020-11-28 23:57:24 +01009589 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ctx->rule->arg.hlua_rule->fcn->function_ref[hlua->state_id]);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009590
9591 /* Create and and push object stream in the stack. */
9592 if (!hlua_applet_http_new(hlua->T, ctx)) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009593 SEND_ERR(strm->be, "Lua applet http '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009594 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009595 RESET_SAFE_LJMP(hlua);
Christopher Fauletc9929382022-05-12 11:52:27 +02009596 return -1;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009597 }
9598 hlua->nargs = 1;
9599
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009600 /* push keywords in the stack. */
9601 for (arg = ctx->rule->arg.hlua_rule->args; arg && *arg; arg++) {
9602 if (!lua_checkstack(hlua->T, 1)) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009603 SEND_ERR(strm->be, "Lua applet http '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009604 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009605 RESET_SAFE_LJMP(hlua);
Christopher Fauletc9929382022-05-12 11:52:27 +02009606 return -1;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009607 }
9608 lua_pushstring(hlua->T, *arg);
9609 hlua->nargs++;
9610 }
9611
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009612 RESET_SAFE_LJMP(hlua);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009613
9614 /* Wakeup the applet when data is ready for read. */
Willy Tarreau90e8b452022-05-25 18:21:43 +02009615 applet_need_more_data(ctx);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009616
Christopher Fauletc9929382022-05-12 11:52:27 +02009617 return 0;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009618}
9619
Willy Tarreau60409db2019-08-21 14:14:50 +02009620void hlua_applet_http_fct(struct appctx *ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009621{
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009622 struct hlua_http_ctx *http_ctx = ctx->svcctx;
Willy Tarreauc12b3212022-05-27 11:08:15 +02009623 struct stconn *sc = appctx_sc(ctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02009624 struct stream *strm = __sc_strm(sc);
9625 struct channel *req = sc_oc(sc);
9626 struct channel *res = sc_ic(sc);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009627 struct act_rule *rule = ctx->rule;
9628 struct proxy *px = strm->be;
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009629 struct hlua *hlua = http_ctx->hlua;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009630 struct htx *req_htx, *res_htx;
9631
9632 res_htx = htx_from_buf(&res->buf);
9633
Christopher Faulet31572222023-03-31 11:13:48 +02009634 if (unlikely(se_fl_test(ctx->sedesc, (SE_FL_EOS|SE_FL_ERROR|SE_FL_SHR|SE_FL_SHW))))
9635 goto out;
9636
9637 /* The applet execution is already done. */
9638 if (http_ctx->flags & APPLET_DONE)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009639 goto out;
9640
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05009641 /* Check if the input buffer is available. */
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009642 if (!b_size(&res->buf)) {
Willy Tarreau3e7be362022-05-27 10:35:27 +02009643 sc_need_room(sc);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009644 goto out;
9645 }
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009646
9647 /* Set the currently running flag. */
9648 if (!HLUA_IS_RUNNING(hlua) &&
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009649 !(http_ctx->flags & APPLET_DONE)) {
Christopher Fauletbd878d22021-04-28 10:50:21 +02009650 if (!co_data(req)) {
Willy Tarreau90e8b452022-05-25 18:21:43 +02009651 applet_need_more_data(ctx);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009652 goto out;
9653 }
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009654 }
9655
Christopher Faulet31572222023-03-31 11:13:48 +02009656 /* Execute the function. */
9657 switch (hlua_ctx_resume(hlua, 1)) {
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009658 /* finished. */
9659 case HLUA_E_OK:
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009660 http_ctx->flags |= APPLET_DONE;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009661 break;
9662
9663 /* yield. */
9664 case HLUA_E_AGAIN:
9665 if (hlua->wake_time != TICK_ETERNITY)
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009666 task_schedule(http_ctx->task, hlua->wake_time);
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01009667 goto out;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009668
9669 /* finished with error. */
9670 case HLUA_E_ERRMSG:
9671 /* Display log. */
9672 SEND_ERR(px, "Lua applet http '%s': %s.\n",
Christopher Faulet31572222023-03-31 11:13:48 +02009673 rule->arg.hlua_rule->fcn->name, lua_tostring(hlua->T, -1));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009674 lua_pop(hlua->T, 1);
9675 goto error;
9676
9677 case HLUA_E_ETMOUT:
9678 SEND_ERR(px, "Lua applet http '%s': execution timeout.\n",
Christopher Faulet31572222023-03-31 11:13:48 +02009679 rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009680 goto error;
9681
9682 case HLUA_E_NOMEM:
9683 SEND_ERR(px, "Lua applet http '%s': out of memory error.\n",
Christopher Faulet31572222023-03-31 11:13:48 +02009684 rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009685 goto error;
9686
9687 case HLUA_E_YIELD: /* unexpected */
9688 SEND_ERR(px, "Lua applet http '%s': yield not allowed.\n",
Christopher Faulet31572222023-03-31 11:13:48 +02009689 rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009690 goto error;
9691
9692 case HLUA_E_ERR:
9693 /* Display log. */
9694 SEND_ERR(px, "Lua applet http '%s' return an unknown error.\n",
Christopher Faulet31572222023-03-31 11:13:48 +02009695 rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009696 goto error;
9697
9698 default:
9699 goto error;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009700 }
9701
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009702 if (http_ctx->flags & APPLET_DONE) {
9703 if (http_ctx->flags & APPLET_RSP_SENT)
Christopher Faulet31572222023-03-31 11:13:48 +02009704 goto out;
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01009705
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009706 if (!(http_ctx->flags & APPLET_HDR_SENT))
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009707 goto error;
9708
Christopher Fauletf89af9c2022-04-07 10:07:18 +02009709 /* no more data are expected. If the response buffer is empty
9710 * for a chunked message, be sure to add something (EOT block in
9711 * this case) to have something to send. It is important to be
9712 * sure the EOM flags will be handled by the endpoint.
9713 */
9714 if (htx_is_empty(res_htx) && (strm->txn->rsp.flags & (HTTP_MSGF_XFER_LEN|HTTP_MSGF_CNT_LEN)) == HTTP_MSGF_XFER_LEN) {
9715 if (!htx_add_endof(res_htx, HTX_BLK_EOT)) {
Willy Tarreau3e7be362022-05-27 10:35:27 +02009716 sc_need_room(sc);
Christopher Fauletf89af9c2022-04-07 10:07:18 +02009717 goto out;
9718 }
9719 channel_add_input(res, 1);
9720 }
9721
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01009722 res_htx->flags |= HTX_FL_EOM;
Christopher Faulet31572222023-03-31 11:13:48 +02009723 se_fl_set(ctx->sedesc, SE_FL_EOI|SE_FL_EOS);
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009724 strm->txn->status = http_ctx->status;
9725 http_ctx->flags |= APPLET_RSP_SENT;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009726 }
9727
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009728 out:
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009729 htx_to_buf(res_htx, &res->buf);
Christopher Faulet31572222023-03-31 11:13:48 +02009730 /* eat the whole request */
9731 if (co_data(req)) {
9732 req_htx = htx_from_buf(&req->buf);
9733 co_htx_skip(req, req_htx, co_data(req));
9734 htx_to_buf(req_htx, &req->buf);
9735 }
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009736 return;
9737
9738 error:
9739
9740 /* If we are in HTTP mode, and we are not send any
9741 * data, return a 500 server error in best effort:
9742 * if there is no room available in the buffer,
9743 * just close the connection.
9744 */
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009745 if (!(http_ctx->flags & APPLET_HDR_SENT)) {
Christopher Fauletf7346382019-07-17 22:02:08 +02009746 struct buffer *err = &http_err_chunks[HTTP_ERR_500];
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009747
9748 channel_erase(res);
9749 res->buf.data = b_data(err);
9750 memcpy(res->buf.area, b_head(err), b_data(err));
9751 res_htx = htx_from_buf(&res->buf);
Christopher Fauletf6cce3f2019-02-27 21:20:09 +01009752 channel_add_input(res, res_htx->data);
Christopher Faulet31572222023-03-31 11:13:48 +02009753 se_fl_set(ctx->sedesc, SE_FL_EOI|SE_FL_EOS);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009754 }
Christopher Faulet31572222023-03-31 11:13:48 +02009755 else
9756 se_fl_set(ctx->sedesc, SE_FL_ERROR);
9757
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009758 if (!(strm->flags & SF_ERR_MASK))
9759 strm->flags |= SF_ERR_RESOURCE;
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009760 http_ctx->flags |= APPLET_DONE;
Christopher Faulet31572222023-03-31 11:13:48 +02009761 goto out;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009762}
9763
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009764static void hlua_applet_http_release(struct appctx *ctx)
9765{
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009766 struct hlua_http_ctx *http_ctx = ctx->svcctx;
9767
9768 task_destroy(http_ctx->task);
9769 http_ctx->task = NULL;
9770 hlua_ctx_destroy(http_ctx->hlua);
9771 http_ctx->hlua = NULL;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009772}
9773
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009774/* global {tcp|http}-request parser. Return ACT_RET_PRS_OK in
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05009775 * success case, else return ACT_RET_PRS_ERR.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02009776 *
9777 * This function can fail with an abort() due to an Lua critical error.
9778 * We are in the configuration parsing process of HAProxy, this abort() is
9779 * tolerated.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009780 */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009781static enum act_parse_ret action_register_lua(const char **args, int *cur_arg, struct proxy *px,
9782 struct act_rule *rule, char **err)
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009783{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02009784 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009785 int i;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009786
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009787 /* Memory for the rule. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02009788 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009789 if (!rule->arg.hlua_rule) {
9790 memprintf(err, "out of memory error");
Christopher Faulet528526f2021-04-12 14:37:32 +02009791 goto error;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009792 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009793
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009794 /* Memory for arguments. */
Tim Duesterhuse52b6e52020-09-12 20:26:43 +02009795 rule->arg.hlua_rule->args = calloc(fcn->nargs + 1,
9796 sizeof(*rule->arg.hlua_rule->args));
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009797 if (!rule->arg.hlua_rule->args) {
9798 memprintf(err, "out of memory error");
Christopher Faulet528526f2021-04-12 14:37:32 +02009799 goto error;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009800 }
9801
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009802 /* Reference the Lua function and store the reference. */
Thierry Fournierad5345f2020-11-29 02:05:57 +01009803 rule->arg.hlua_rule->fcn = fcn;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009804
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009805 /* Expect some arguments */
9806 for (i = 0; i < fcn->nargs; i++) {
Thierry FOURNIER1725c2e2019-01-06 19:38:49 +01009807 if (*args[*cur_arg] == '\0') {
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009808 memprintf(err, "expect %d arguments", fcn->nargs);
Christopher Faulet528526f2021-04-12 14:37:32 +02009809 goto error;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009810 }
Thierry FOURNIER1725c2e2019-01-06 19:38:49 +01009811 rule->arg.hlua_rule->args[i] = strdup(args[*cur_arg]);
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009812 if (!rule->arg.hlua_rule->args[i]) {
9813 memprintf(err, "out of memory error");
Christopher Faulet528526f2021-04-12 14:37:32 +02009814 goto error;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009815 }
9816 (*cur_arg)++;
9817 }
9818 rule->arg.hlua_rule->args[i] = NULL;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009819
Thierry FOURNIER42148732015-09-02 17:17:33 +02009820 rule->action = ACT_CUSTOM;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009821 rule->action_ptr = hlua_action;
Thierry FOURNIERafa80492015-08-19 09:04:15 +02009822 return ACT_RET_PRS_OK;
Christopher Faulet528526f2021-04-12 14:37:32 +02009823
9824 error:
9825 if (rule->arg.hlua_rule) {
9826 if (rule->arg.hlua_rule->args) {
9827 for (i = 0; i < fcn->nargs; i++)
9828 ha_free(&rule->arg.hlua_rule->args[i]);
9829 ha_free(&rule->arg.hlua_rule->args);
9830 }
9831 ha_free(&rule->arg.hlua_rule);
9832 }
9833 return ACT_RET_PRS_ERR;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009834}
9835
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009836static enum act_parse_ret action_register_service_http(const char **args, int *cur_arg, struct proxy *px,
9837 struct act_rule *rule, char **err)
9838{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02009839 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009840
Thierry FOURNIER718e2a72015-12-20 20:13:14 +01009841 /* HTTP applets are forbidden in tcp-request rules.
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05009842 * HTTP applet request requires everything initialized by
Thierry FOURNIER718e2a72015-12-20 20:13:14 +01009843 * "http_process_request" (analyzer flag AN_REQ_HTTP_INNER).
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05009844 * The applet will be immediately initialized, but its before
Thierry FOURNIER718e2a72015-12-20 20:13:14 +01009845 * the call of this analyzer.
9846 */
9847 if (rule->from != ACT_F_HTTP_REQ) {
9848 memprintf(err, "HTTP applets are forbidden from 'tcp-request' rulesets");
9849 return ACT_RET_PRS_ERR;
9850 }
9851
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009852 /* Memory for the rule. */
9853 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
9854 if (!rule->arg.hlua_rule) {
9855 memprintf(err, "out of memory error");
9856 return ACT_RET_PRS_ERR;
9857 }
9858
9859 /* Reference the Lua function and store the reference. */
Thierry Fournierad5345f2020-11-29 02:05:57 +01009860 rule->arg.hlua_rule->fcn = fcn;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009861
9862 /* TODO: later accept arguments. */
9863 rule->arg.hlua_rule->args = NULL;
9864
9865 /* Add applet pointer in the rule. */
9866 rule->applet.obj_type = OBJ_TYPE_APPLET;
9867 rule->applet.name = fcn->name;
9868 rule->applet.init = hlua_applet_http_init;
9869 rule->applet.fct = hlua_applet_http_fct;
9870 rule->applet.release = hlua_applet_http_release;
9871 rule->applet.timeout = hlua_timeout_applet;
9872
9873 return ACT_RET_PRS_OK;
9874}
9875
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009876/* This function is an LUA binding used for registering
9877 * "sample-conv" functions. It expects a converter name used
9878 * in the haproxy configuration file, and an LUA function.
9879 */
9880__LJMP static int hlua_register_action(lua_State *L)
9881{
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009882 struct action_kw_list *akl = NULL;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009883 const char *name;
9884 int ref;
9885 int len;
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009886 struct hlua_function *fcn = NULL;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009887 int nargs;
Thierry Fournierf67442e2020-11-28 20:41:07 +01009888 struct buffer *trash;
9889 struct action_kw *akw;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009890
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009891 /* Initialise the number of expected arguments at 0. */
9892 nargs = 0;
9893
9894 if (lua_gettop(L) < 3 || lua_gettop(L) > 4)
9895 WILL_LJMP(luaL_error(L, "'register_action' needs between 3 and 4 arguments"));
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009896
9897 /* First argument : converter name. */
9898 name = MAY_LJMP(luaL_checkstring(L, 1));
9899
9900 /* Second argument : environment. */
9901 if (lua_type(L, 2) != LUA_TTABLE)
9902 WILL_LJMP(luaL_error(L, "register_action: second argument must be a table of strings"));
9903
9904 /* Third argument : lua function. */
9905 ref = MAY_LJMP(hlua_checkfunction(L, 3));
9906
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08009907 /* Fourth argument : number of mandatory arguments expected on the configuration line. */
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009908 if (lua_gettop(L) >= 4)
9909 nargs = MAY_LJMP(luaL_checkinteger(L, 4));
9910
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08009911 /* browse the second argument as an array. */
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009912 lua_pushnil(L);
9913 while (lua_next(L, 2) != 0) {
9914 if (lua_type(L, -1) != LUA_TSTRING)
9915 WILL_LJMP(luaL_error(L, "register_action: second argument must be a table of strings"));
9916
Thierry Fournierf67442e2020-11-28 20:41:07 +01009917 /* Check if action exists */
9918 trash = get_trash_chunk();
9919 chunk_printf(trash, "lua.%s", name);
9920 if (strcmp(lua_tostring(L, -1), "tcp-req") == 0) {
9921 akw = tcp_req_cont_action(trash->area);
9922 } else if (strcmp(lua_tostring(L, -1), "tcp-res") == 0) {
9923 akw = tcp_res_cont_action(trash->area);
9924 } else if (strcmp(lua_tostring(L, -1), "http-req") == 0) {
9925 akw = action_http_req_custom(trash->area);
9926 } else if (strcmp(lua_tostring(L, -1), "http-res") == 0) {
9927 akw = action_http_res_custom(trash->area);
9928 } else {
9929 akw = NULL;
9930 }
9931 if (akw != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +01009932 fcn = akw->private;
9933 if (fcn->function_ref[hlua_state_id] != -1) {
9934 ha_warning("Trying to register action 'lua.%s' more than once. "
9935 "This will become a hard error in version 2.5.\n", name);
9936 }
9937 fcn->function_ref[hlua_state_id] = ref;
9938
9939 /* pop the environment string. */
9940 lua_pop(L, 1);
9941 continue;
Thierry Fournierf67442e2020-11-28 20:41:07 +01009942 }
9943
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009944 /* Check required environment. Only accepted "http" or "tcp". */
9945 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02009946 akl = calloc(1, sizeof(*akl) + sizeof(struct action_kw) * 2);
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009947 if (!akl)
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009948 goto alloc_error;;
Thierry Fournier62a22aa2020-11-28 21:06:35 +01009949 fcn = new_hlua_function();
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009950 if (!fcn)
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009951 goto alloc_error;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009952
9953 /* Fill fcn. */
9954 fcn->name = strdup(name);
9955 if (!fcn->name)
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009956 goto alloc_error;
Thierry Fournierc7492592020-11-28 23:57:24 +01009957 fcn->function_ref[hlua_state_id] = ref;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009958
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -07009959 /* Set the expected number of arguments. */
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009960 fcn->nargs = nargs;
9961
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009962 /* List head */
9963 akl->list.n = akl->list.p = NULL;
9964
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009965 /* action keyword. */
9966 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02009967 akl->kw[0].kw = calloc(1, len);
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009968 if (!akl->kw[0].kw)
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009969 goto alloc_error;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009970
9971 snprintf((char *)akl->kw[0].kw, len, "lua.%s", name);
9972
Amaury Denoyellee4a617c2021-05-06 15:33:09 +02009973 akl->kw[0].flags = 0;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009974 akl->kw[0].private = fcn;
9975 akl->kw[0].parse = action_register_lua;
9976
9977 /* select the action registering point. */
9978 if (strcmp(lua_tostring(L, -1), "tcp-req") == 0)
9979 tcp_req_cont_keywords_register(akl);
9980 else if (strcmp(lua_tostring(L, -1), "tcp-res") == 0)
9981 tcp_res_cont_keywords_register(akl);
9982 else if (strcmp(lua_tostring(L, -1), "http-req") == 0)
9983 http_req_keywords_register(akl);
9984 else if (strcmp(lua_tostring(L, -1), "http-res") == 0)
9985 http_res_keywords_register(akl);
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009986 else {
9987 release_hlua_function(fcn);
9988 if (akl)
9989 ha_free((char **)&(akl->kw[0].kw));
9990 ha_free(&akl);
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01009991 WILL_LJMP(luaL_error(L, "Lua action environment '%s' is unknown. "
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009992 "'tcp-req', 'tcp-res', 'http-req' or 'http-res' "
9993 "are expected.", lua_tostring(L, -1)));
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009994 }
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009995
9996 /* pop the environment string. */
9997 lua_pop(L, 1);
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009998
9999 /* reset for next loop */
10000 akl = NULL;
10001 fcn = NULL;
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010002 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010003 return ACT_RET_PRS_OK;
Christopher Faulet4fc9da02021-04-12 15:08:12 +020010004
10005 alloc_error:
10006 release_hlua_function(fcn);
10007 ha_free(&akl);
10008 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
10009 return 0; /* Never reached */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010010}
10011
10012static enum act_parse_ret action_register_service_tcp(const char **args, int *cur_arg, struct proxy *px,
10013 struct act_rule *rule, char **err)
10014{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +020010015 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010016
Christopher Faulet280f85b2019-07-15 15:02:04 +020010017 if (px->mode == PR_MODE_HTTP) {
10018 memprintf(err, "Lua TCP services cannot be used on HTTP proxies");
Christopher Fauletafd8f102018-11-08 11:34:21 +010010019 return ACT_RET_PRS_ERR;
10020 }
10021
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010022 /* Memory for the rule. */
10023 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
10024 if (!rule->arg.hlua_rule) {
10025 memprintf(err, "out of memory error");
10026 return ACT_RET_PRS_ERR;
10027 }
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010028
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010029 /* Reference the Lua function and store the reference. */
Thierry Fournierad5345f2020-11-29 02:05:57 +010010030 rule->arg.hlua_rule->fcn = fcn;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010031
10032 /* TODO: later accept arguments. */
10033 rule->arg.hlua_rule->args = NULL;
10034
10035 /* Add applet pointer in the rule. */
10036 rule->applet.obj_type = OBJ_TYPE_APPLET;
10037 rule->applet.name = fcn->name;
10038 rule->applet.init = hlua_applet_tcp_init;
10039 rule->applet.fct = hlua_applet_tcp_fct;
10040 rule->applet.release = hlua_applet_tcp_release;
10041 rule->applet.timeout = hlua_timeout_applet;
10042
10043 return 0;
10044}
10045
10046/* This function is an LUA binding used for registering
10047 * "sample-conv" functions. It expects a converter name used
10048 * in the haproxy configuration file, and an LUA function.
10049 */
10050__LJMP static int hlua_register_service(lua_State *L)
10051{
10052 struct action_kw_list *akl;
10053 const char *name;
10054 const char *env;
10055 int ref;
10056 int len;
Christopher Faulet5c028d72021-04-12 15:11:44 +020010057 struct hlua_function *fcn = NULL;
Thierry Fournierf67442e2020-11-28 20:41:07 +010010058 struct buffer *trash;
10059 struct action_kw *akw;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010060
10061 MAY_LJMP(check_args(L, 3, "register_service"));
10062
10063 /* First argument : converter name. */
10064 name = MAY_LJMP(luaL_checkstring(L, 1));
10065
10066 /* Second argument : environment. */
10067 env = MAY_LJMP(luaL_checkstring(L, 2));
10068
10069 /* Third argument : lua function. */
10070 ref = MAY_LJMP(hlua_checkfunction(L, 3));
10071
Thierry Fournierf67442e2020-11-28 20:41:07 +010010072 /* Check for service already registered */
10073 trash = get_trash_chunk();
10074 chunk_printf(trash, "lua.%s", name);
10075 akw = service_find(trash->area);
10076 if (akw != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +010010077 fcn = akw->private;
10078 if (fcn->function_ref[hlua_state_id] != -1) {
10079 ha_warning("Trying to register service 'lua.%s' more than once. "
10080 "This will become a hard error in version 2.5.\n", name);
10081 }
10082 fcn->function_ref[hlua_state_id] = ref;
10083 return 0;
Thierry Fournierf67442e2020-11-28 20:41:07 +010010084 }
10085
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010086 /* Allocate and fill the sample fetch keyword struct. */
10087 akl = calloc(1, sizeof(*akl) + sizeof(struct action_kw) * 2);
10088 if (!akl)
Christopher Faulet5c028d72021-04-12 15:11:44 +020010089 goto alloc_error;
Thierry Fournier62a22aa2020-11-28 21:06:35 +010010090 fcn = new_hlua_function();
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010091 if (!fcn)
Christopher Faulet5c028d72021-04-12 15:11:44 +020010092 goto alloc_error;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010093
10094 /* Fill fcn. */
10095 len = strlen("<lua.>") + strlen(name) + 1;
10096 fcn->name = calloc(1, len);
10097 if (!fcn->name)
Christopher Faulet5c028d72021-04-12 15:11:44 +020010098 goto alloc_error;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010099 snprintf((char *)fcn->name, len, "<lua.%s>", name);
Thierry Fournierc7492592020-11-28 23:57:24 +010010100 fcn->function_ref[hlua_state_id] = ref;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010101
10102 /* List head */
10103 akl->list.n = akl->list.p = NULL;
10104
10105 /* converter keyword. */
10106 len = strlen("lua.") + strlen(name) + 1;
10107 akl->kw[0].kw = calloc(1, len);
10108 if (!akl->kw[0].kw)
Christopher Faulet5c028d72021-04-12 15:11:44 +020010109 goto alloc_error;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010110
10111 snprintf((char *)akl->kw[0].kw, len, "lua.%s", name);
10112
Thierry FOURNIER / OZON.IO02564fd2016-11-12 11:07:05 +010010113 /* Check required environment. Only accepted "http" or "tcp". */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010114 if (strcmp(env, "tcp") == 0)
10115 akl->kw[0].parse = action_register_service_tcp;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010116 else if (strcmp(env, "http") == 0)
10117 akl->kw[0].parse = action_register_service_http;
Christopher Faulet5c028d72021-04-12 15:11:44 +020010118 else {
10119 release_hlua_function(fcn);
10120 if (akl)
10121 ha_free((char **)&(akl->kw[0].kw));
10122 ha_free(&akl);
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +010010123 WILL_LJMP(luaL_error(L, "Lua service environment '%s' is unknown. "
Eric Salamafe7456f2017-12-21 14:30:07 +010010124 "'tcp' or 'http' are expected.", env));
Christopher Faulet5c028d72021-04-12 15:11:44 +020010125 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010126
Amaury Denoyellee4a617c2021-05-06 15:33:09 +020010127 akl->kw[0].flags = 0;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010128 akl->kw[0].private = fcn;
10129
10130 /* End of array. */
10131 memset(&akl->kw[1], 0, sizeof(*akl->kw));
10132
10133 /* Register this new converter */
10134 service_keywords_register(akl);
10135
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010136 return 0;
Christopher Faulet5c028d72021-04-12 15:11:44 +020010137
10138 alloc_error:
10139 release_hlua_function(fcn);
10140 ha_free(&akl);
10141 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
10142 return 0; /* Never reached */
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010143}
10144
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010145/* This function initialises Lua cli handler. It copies the
10146 * arguments in the Lua stack and create channel IO objects.
10147 */
Aurélien Nephtaliabbf6072018-04-18 13:26:46 +020010148static int hlua_cli_parse_fct(char **args, char *payload, struct appctx *appctx, void *private)
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010149{
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010150 struct hlua_cli_ctx *ctx = applet_reserve_svcctx(appctx, sizeof(*ctx));
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010151 struct hlua *hlua;
10152 struct hlua_function *fcn;
10153 int i;
10154 const char *error;
10155
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010156 fcn = private;
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010157 ctx->fcn = private;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +010010158
Willy Tarreaubafbe012017-11-24 17:34:44 +010010159 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +010010160 if (!hlua) {
10161 SEND_ERR(NULL, "Lua cli '%s': out of memory.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +010010162 return 1;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +010010163 }
10164 HLUA_INIT(hlua);
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010165 ctx->hlua = hlua;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010166
10167 /* Create task used by signal to wakeup applets.
Ilya Shipitsind4259502020-04-08 01:07:56 +050010168 * We use the same wakeup function than the Lua applet_tcp and
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010169 * applet_http. It is absolutely compatible.
10170 */
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010171 ctx->task = task_new_here();
10172 if (!ctx->task) {
Thierry FOURNIERffbf5692016-12-16 11:14:06 +010010173 SEND_ERR(NULL, "Lua cli '%s': out of memory.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +010010174 goto error;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010175 }
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010176 ctx->task->nice = 0;
10177 ctx->task->context = appctx;
10178 ctx->task->process = hlua_applet_wakeup;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010179
10180 /* Initialises the Lua context */
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010181 if (!hlua_ctx_init(hlua, fcn_ref_to_stack_id(fcn), ctx->task, 0)) {
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010182 SEND_ERR(NULL, "Lua cli '%s': can't initialize Lua context.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +010010183 goto error;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010184 }
10185
10186 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010187 if (!SET_SAFE_LJMP(hlua)) {
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010188 if (lua_type(hlua->T, -1) == LUA_TSTRING)
10189 error = lua_tostring(hlua->T, -1);
10190 else
10191 error = "critical error";
10192 SEND_ERR(NULL, "Lua cli '%s': %s.\n", fcn->name, error);
10193 goto error;
10194 }
10195
10196 /* Check stack available size. */
10197 if (!lua_checkstack(hlua->T, 2)) {
10198 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
10199 goto error;
10200 }
10201
10202 /* Restore the function in the stack. */
Thierry Fournierc7492592020-11-28 23:57:24 +010010203 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, fcn->function_ref[hlua->state_id]);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010204
10205 /* Once the arguments parsed, the CLI is like an AppletTCP,
10206 * so push AppletTCP in the stack.
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010207 */
10208 if (!hlua_applet_tcp_new(hlua->T, appctx)) {
10209 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
10210 goto error;
10211 }
10212 hlua->nargs = 1;
10213
10214 /* push keywords in the stack. */
10215 for (i = 0; *args[i]; i++) {
10216 /* Check stack available size. */
10217 if (!lua_checkstack(hlua->T, 1)) {
10218 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
10219 goto error;
10220 }
10221 lua_pushstring(hlua->T, args[i]);
10222 hlua->nargs++;
10223 }
10224
10225 /* We must initialize the execution timeouts. */
10226 hlua->max_time = hlua_timeout_session;
10227
10228 /* At this point the execution is safe. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010229 RESET_SAFE_LJMP(hlua);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010230
10231 /* It's ok */
10232 return 0;
10233
10234 /* It's not ok. */
10235error:
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010236 RESET_SAFE_LJMP(hlua);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010237 hlua_ctx_destroy(hlua);
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010238 ctx->hlua = NULL;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010239 return 1;
10240}
10241
10242static int hlua_cli_io_handler_fct(struct appctx *appctx)
10243{
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010244 struct hlua_cli_ctx *ctx = appctx->svcctx;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010245 struct hlua *hlua;
Willy Tarreau475e4632022-05-27 10:26:46 +020010246 struct stconn *sc;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010247 struct hlua_function *fcn;
10248
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010249 hlua = ctx->hlua;
Willy Tarreauc12b3212022-05-27 11:08:15 +020010250 sc = appctx_sc(appctx);
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010251 fcn = ctx->fcn;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010252
10253 /* If the stream is disconnect or closed, ldo nothing. */
Willy Tarreau475e4632022-05-27 10:26:46 +020010254 if (unlikely(sc->state == SC_ST_DIS || sc->state == SC_ST_CLO))
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010255 return 1;
10256
10257 /* Execute the function. */
10258 switch (hlua_ctx_resume(hlua, 1)) {
10259
10260 /* finished. */
10261 case HLUA_E_OK:
10262 return 1;
10263
10264 /* yield. */
10265 case HLUA_E_AGAIN:
10266 /* We want write. */
10267 if (HLUA_IS_WAKERESWR(hlua))
Willy Tarreau475e4632022-05-27 10:26:46 +020010268 sc_need_room(sc);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010269 /* Set the timeout. */
10270 if (hlua->wake_time != TICK_ETERNITY)
10271 task_schedule(hlua->task, hlua->wake_time);
10272 return 0;
10273
10274 /* finished with error. */
10275 case HLUA_E_ERRMSG:
10276 /* Display log. */
10277 SEND_ERR(NULL, "Lua cli '%s': %s.\n",
10278 fcn->name, lua_tostring(hlua->T, -1));
10279 lua_pop(hlua->T, 1);
10280 return 1;
10281
Thierry Fournierd5b073c2018-05-21 19:42:47 +020010282 case HLUA_E_ETMOUT:
10283 SEND_ERR(NULL, "Lua converter '%s': execution timeout.\n",
10284 fcn->name);
10285 return 1;
10286
10287 case HLUA_E_NOMEM:
10288 SEND_ERR(NULL, "Lua converter '%s': out of memory error.\n",
10289 fcn->name);
10290 return 1;
10291
10292 case HLUA_E_YIELD: /* unexpected */
10293 SEND_ERR(NULL, "Lua converter '%s': yield not allowed.\n",
10294 fcn->name);
10295 return 1;
10296
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010297 case HLUA_E_ERR:
10298 /* Display log. */
10299 SEND_ERR(NULL, "Lua cli '%s' return an unknown error.\n",
10300 fcn->name);
10301 return 1;
10302
10303 default:
10304 return 1;
10305 }
10306
10307 return 1;
10308}
10309
10310static void hlua_cli_io_release_fct(struct appctx *appctx)
10311{
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010312 struct hlua_cli_ctx *ctx = appctx->svcctx;
10313
10314 hlua_ctx_destroy(ctx->hlua);
10315 ctx->hlua = NULL;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010316}
10317
10318/* This function is an LUA binding used for registering
10319 * new keywords in the cli. It expects a list of keywords
10320 * which are the "path". It is limited to 5 keywords. A
10321 * description of the command, a function to be executed
10322 * for the parsing and a function for io handlers.
10323 */
10324__LJMP static int hlua_register_cli(lua_State *L)
10325{
10326 struct cli_kw_list *cli_kws;
10327 const char *message;
10328 int ref_io;
10329 int len;
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010330 struct hlua_function *fcn = NULL;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010331 int index;
10332 int i;
Thierry Fournierf67442e2020-11-28 20:41:07 +010010333 struct buffer *trash;
10334 const char *kw[5];
10335 struct cli_kw *cli_kw;
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010336 const char *errmsg;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010337
10338 MAY_LJMP(check_args(L, 3, "register_cli"));
10339
10340 /* First argument : an array of maximum 5 keywords. */
10341 if (!lua_istable(L, 1))
10342 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table"));
10343
10344 /* Second argument : string with contextual message. */
10345 message = MAY_LJMP(luaL_checkstring(L, 2));
10346
10347 /* Third and fourth argument : lua function. */
10348 ref_io = MAY_LJMP(hlua_checkfunction(L, 3));
10349
Thierry Fournierf67442e2020-11-28 20:41:07 +010010350 /* Check for CLI service already registered */
10351 trash = get_trash_chunk();
10352 index = 0;
10353 lua_pushnil(L);
10354 memset(kw, 0, sizeof(kw));
10355 while (lua_next(L, 1) != 0) {
10356 if (index >= CLI_PREFIX_KW_NB)
10357 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table with a maximum of 5 entries"));
10358 if (lua_type(L, -1) != LUA_TSTRING)
10359 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table filled with strings"));
10360 kw[index] = lua_tostring(L, -1);
10361 if (index == 0)
10362 chunk_printf(trash, "%s", kw[index]);
10363 else
10364 chunk_appendf(trash, " %s", kw[index]);
10365 index++;
10366 lua_pop(L, 1);
10367 }
10368 cli_kw = cli_find_kw_exact((char **)kw);
10369 if (cli_kw != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +010010370 fcn = cli_kw->private;
10371 if (fcn->function_ref[hlua_state_id] != -1) {
10372 ha_warning("Trying to register CLI keyword 'lua.%s' more than once. "
10373 "This will become a hard error in version 2.5.\n", trash->area);
10374 }
10375 fcn->function_ref[hlua_state_id] = ref_io;
10376 return 0;
Thierry Fournierf67442e2020-11-28 20:41:07 +010010377 }
10378
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010379 /* Allocate and fill the sample fetch keyword struct. */
10380 cli_kws = calloc(1, sizeof(*cli_kws) + sizeof(struct cli_kw) * 2);
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010381 if (!cli_kws) {
10382 errmsg = "Lua out of memory error.";
10383 goto error;
10384 }
Thierry Fournier62a22aa2020-11-28 21:06:35 +010010385 fcn = new_hlua_function();
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010386 if (!fcn) {
10387 errmsg = "Lua out of memory error.";
10388 goto error;
10389 }
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010390
10391 /* Fill path. */
10392 index = 0;
10393 lua_pushnil(L);
10394 while(lua_next(L, 1) != 0) {
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010395 if (index >= 5) {
10396 errmsg = "1st argument must be a table with a maximum of 5 entries";
10397 goto error;
10398 }
10399 if (lua_type(L, -1) != LUA_TSTRING) {
10400 errmsg = "1st argument must be a table filled with strings";
10401 goto error;
10402 }
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010403 cli_kws->kw[0].str_kw[index] = strdup(lua_tostring(L, -1));
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010404 if (!cli_kws->kw[0].str_kw[index]) {
10405 errmsg = "Lua out of memory error.";
10406 goto error;
10407 }
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010408 index++;
10409 lua_pop(L, 1);
10410 }
10411
10412 /* Copy help message. */
10413 cli_kws->kw[0].usage = strdup(message);
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010414 if (!cli_kws->kw[0].usage) {
10415 errmsg = "Lua out of memory error.";
10416 goto error;
10417 }
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010418
10419 /* Fill fcn io handler. */
10420 len = strlen("<lua.cli>") + 1;
10421 for (i = 0; i < index; i++)
10422 len += strlen(cli_kws->kw[0].str_kw[i]) + 1;
10423 fcn->name = calloc(1, len);
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010424 if (!fcn->name) {
10425 errmsg = "Lua out of memory error.";
10426 goto error;
10427 }
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010428 strncat((char *)fcn->name, "<lua.cli", len);
10429 for (i = 0; i < index; i++) {
10430 strncat((char *)fcn->name, ".", len);
10431 strncat((char *)fcn->name, cli_kws->kw[0].str_kw[i], len);
10432 }
10433 strncat((char *)fcn->name, ">", len);
Thierry Fournierc7492592020-11-28 23:57:24 +010010434 fcn->function_ref[hlua_state_id] = ref_io;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010435
10436 /* Fill last entries. */
10437 cli_kws->kw[0].private = fcn;
10438 cli_kws->kw[0].parse = hlua_cli_parse_fct;
10439 cli_kws->kw[0].io_handler = hlua_cli_io_handler_fct;
10440 cli_kws->kw[0].io_release = hlua_cli_io_release_fct;
10441
10442 /* Register this new converter */
10443 cli_register_kw(cli_kws);
10444
10445 return 0;
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010446
10447 error:
10448 release_hlua_function(fcn);
10449 if (cli_kws) {
10450 for (i = 0; i < index; i++)
10451 ha_free((char **)&(cli_kws->kw[0].str_kw[i]));
10452 ha_free((char **)&(cli_kws->kw[0].usage));
10453 }
10454 ha_free(&cli_kws);
10455 WILL_LJMP(luaL_error(L, errmsg));
10456 return 0; /* Never reached */
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010457}
10458
Christopher Faulet69c581a2021-05-31 08:54:04 +020010459static int hlua_filter_init_per_thread(struct proxy *px, struct flt_conf *fconf)
10460{
10461 struct hlua_flt_config *conf = fconf->conf;
10462 lua_State *L;
10463 int error, pos, state_id, flt_ref;
10464
10465 state_id = reg_flt_to_stack_id(conf->reg);
10466 L = hlua_states[state_id];
10467 pos = lua_gettop(L);
10468
10469 /* The filter parsing function */
10470 lua_rawgeti(L, LUA_REGISTRYINDEX, conf->reg->fun_ref[state_id]);
10471
10472 /* Push the filter class on the stack and resolve all callbacks */
10473 lua_rawgeti(L, LUA_REGISTRYINDEX, conf->reg->flt_ref[state_id]);
10474
10475 /* Duplicate the filter class so each filter will have its own copy */
10476 lua_newtable(L);
10477 lua_pushnil(L);
10478
10479 while (lua_next(L, pos+2)) {
10480 lua_pushvalue(L, -2);
10481 lua_insert(L, -2);
10482 lua_settable(L, -4);
10483 }
10484 flt_ref = luaL_ref(L, LUA_REGISTRYINDEX);
10485
10486 /* Remove the original lua filter class from the stack */
10487 lua_pop(L, 1);
10488
10489 /* Push the copy on the stack */
10490 lua_rawgeti(L, LUA_REGISTRYINDEX, flt_ref);
10491
10492 /* extra args are pushed in a table */
10493 lua_newtable(L);
10494 for (pos = 0; conf->args[pos]; pos++) {
10495 /* Check stack available size. */
10496 if (!lua_checkstack(L, 1)) {
10497 ha_alert("Lua filter '%s' : Lua error : full stack.", conf->reg->name);
10498 goto error;
10499 }
10500 lua_pushstring(L, conf->args[pos]);
10501 lua_rawseti(L, -2, lua_rawlen(L, -2) + 1);
10502 }
10503
10504 error = lua_pcall(L, 2, LUA_MULTRET, 0);
10505 switch (error) {
10506 case LUA_OK:
10507 /* replace the filter ref */
10508 conf->ref[state_id] = flt_ref;
10509 break;
10510 case LUA_ERRRUN:
10511 ha_alert("Lua filter '%s' : runtime error : %s", conf->reg->name, lua_tostring(L, -1));
10512 goto error;
10513 case LUA_ERRMEM:
10514 ha_alert("Lua filter '%s' : out of memory error", conf->reg->name);
10515 goto error;
10516 case LUA_ERRERR:
10517 ha_alert("Lua filter '%s' : message handler error : %s", conf->reg->name, lua_tostring(L, -1));
10518 goto error;
10519#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM <= 503
10520 case LUA_ERRGCMM:
10521 ha_alert("Lua filter '%s' : garbage collector error : %s", conf->reg->name, lua_tostring(L, -1));
10522 goto error;
10523#endif
10524 default:
Ilya Shipitsinff0f2782021-08-22 22:18:07 +050010525 ha_alert("Lua filter '%s' : unknown error : %s", conf->reg->name, lua_tostring(L, -1));
Christopher Faulet69c581a2021-05-31 08:54:04 +020010526 goto error;
10527 }
10528
10529 lua_settop(L, 0);
10530 return 0;
10531
10532 error:
10533 lua_settop(L, 0);
10534 return -1;
10535}
10536
10537static void hlua_filter_deinit_per_thread(struct proxy *px, struct flt_conf *fconf)
10538{
10539 struct hlua_flt_config *conf = fconf->conf;
10540 lua_State *L;
10541 int state_id;
10542
10543 if (!conf)
10544 return;
10545
10546 state_id = reg_flt_to_stack_id(conf->reg);
10547 L = hlua_states[state_id];
10548 luaL_unref(L, LUA_REGISTRYINDEX, conf->ref[state_id]);
10549}
10550
10551static int hlua_filter_init(struct proxy *px, struct flt_conf *fconf)
10552{
10553 struct hlua_flt_config *conf = fconf->conf;
10554 int state_id = reg_flt_to_stack_id(conf->reg);
10555
10556 /* Rely on per-thread init for global scripts */
10557 if (!state_id)
10558 return hlua_filter_init_per_thread(px, fconf);
10559 return 0;
10560}
10561
10562static void hlua_filter_deinit(struct proxy *px, struct flt_conf *fconf)
10563{
10564
10565 if (fconf->conf) {
10566 struct hlua_flt_config *conf = fconf->conf;
10567 int state_id = reg_flt_to_stack_id(conf->reg);
10568 int pos;
10569
10570 /* Rely on per-thread deinit for global scripts */
10571 if (!state_id)
10572 hlua_filter_deinit_per_thread(px, fconf);
10573
10574 for (pos = 0; conf->args[pos]; pos++)
10575 free(conf->args[pos]);
10576 free(conf->args);
10577 }
10578 ha_free(&fconf->conf);
10579 ha_free((char **)&fconf->id);
10580 ha_free(&fconf->ops);
10581}
10582
10583static int hlua_filter_new(struct stream *s, struct filter *filter)
10584{
10585 struct hlua_flt_config *conf = FLT_CONF(filter);
10586 struct hlua_flt_ctx *flt_ctx = NULL;
10587 int ret = 1;
10588
10589 /* In the execution wrappers linked with a stream, the
10590 * Lua context can be not initialized. This behavior
10591 * permits to save performances because a systematic
10592 * Lua initialization cause 5% performances loss.
10593 */
10594 if (!s->hlua) {
10595 struct hlua *hlua;
10596
10597 hlua = pool_alloc(pool_head_hlua);
10598 if (!hlua) {
10599 SEND_ERR(s->be, "Lua filter '%s': can't initialize Lua context.\n",
10600 conf->reg->name);
10601 ret = 0;
10602 goto end;
10603 }
10604 HLUA_INIT(hlua);
10605 s->hlua = hlua;
10606 if (!hlua_ctx_init(s->hlua, reg_flt_to_stack_id(conf->reg), s->task, 0)) {
10607 SEND_ERR(s->be, "Lua filter '%s': can't initialize Lua context.\n",
10608 conf->reg->name);
10609 ret = 0;
10610 goto end;
10611 }
10612 }
10613
10614 flt_ctx = pool_zalloc(pool_head_hlua_flt_ctx);
10615 if (!flt_ctx) {
10616 SEND_ERR(s->be, "Lua filter '%s': can't initialize filter Lua context.\n",
10617 conf->reg->name);
10618 ret = 0;
10619 goto end;
10620 }
10621 flt_ctx->hlua[0] = pool_alloc(pool_head_hlua);
10622 flt_ctx->hlua[1] = pool_alloc(pool_head_hlua);
10623 if (!flt_ctx->hlua[0] || !flt_ctx->hlua[1]) {
10624 SEND_ERR(s->be, "Lua filter '%s': can't initialize filter Lua context.\n",
10625 conf->reg->name);
10626 ret = 0;
10627 goto end;
10628 }
10629 HLUA_INIT(flt_ctx->hlua[0]);
10630 HLUA_INIT(flt_ctx->hlua[1]);
10631 if (!hlua_ctx_init(flt_ctx->hlua[0], reg_flt_to_stack_id(conf->reg), s->task, 0) ||
10632 !hlua_ctx_init(flt_ctx->hlua[1], reg_flt_to_stack_id(conf->reg), s->task, 0)) {
10633 SEND_ERR(s->be, "Lua filter '%s': can't initialize filter Lua context.\n",
10634 conf->reg->name);
10635 ret = 0;
10636 goto end;
10637 }
10638
10639 if (!HLUA_IS_RUNNING(s->hlua)) {
10640 /* The following Lua calls can fail. */
10641 if (!SET_SAFE_LJMP(s->hlua)) {
10642 const char *error;
10643
10644 if (lua_type(s->hlua->T, -1) == LUA_TSTRING)
10645 error = lua_tostring(s->hlua->T, -1);
10646 else
10647 error = "critical error";
10648 SEND_ERR(s->be, "Lua filter '%s': %s.\n", conf->reg->name, error);
10649 ret = 0;
10650 goto end;
10651 }
10652
10653 /* Check stack size. */
10654 if (!lua_checkstack(s->hlua->T, 1)) {
10655 SEND_ERR(s->be, "Lua filter '%s': full stack.\n", conf->reg->name);
Tim Duesterhus22817382021-09-11 23:17:25 +020010656 RESET_SAFE_LJMP(s->hlua);
Christopher Faulet69c581a2021-05-31 08:54:04 +020010657 ret = 0;
10658 goto end;
10659 }
10660
10661 lua_rawgeti(s->hlua->T, LUA_REGISTRYINDEX, conf->ref[s->hlua->state_id]);
10662 if (lua_getfield(s->hlua->T, -1, "new") != LUA_TFUNCTION) {
10663 SEND_ERR(s->be, "Lua filter '%s': 'new' field is not a function.\n",
10664 conf->reg->name);
10665 RESET_SAFE_LJMP(s->hlua);
10666 ret = 0;
10667 goto end;
10668 }
10669 lua_insert(s->hlua->T, -2);
10670
10671 /* Push the copy on the stack */
10672 s->hlua->nargs = 1;
10673
10674 /* We must initialize the execution timeouts. */
10675 s->hlua->max_time = hlua_timeout_session;
10676
10677 /* At this point the execution is safe. */
10678 RESET_SAFE_LJMP(s->hlua);
10679 }
10680
10681 switch (hlua_ctx_resume(s->hlua, 0)) {
10682 case HLUA_E_OK:
10683 /* Nothing returned or not a table, ignore the filter for current stream */
10684 if (!lua_gettop(s->hlua->T) || !lua_istable(s->hlua->T, 1)) {
10685 ret = 0;
10686 goto end;
10687 }
10688
10689 /* Attached the filter pointer to the ctx */
10690 lua_pushstring(s->hlua->T, "__filter");
10691 lua_pushlightuserdata(s->hlua->T, filter);
10692 lua_settable(s->hlua->T, -3);
10693
10694 /* Save a ref on the filter ctx */
10695 lua_pushvalue(s->hlua->T, 1);
10696 flt_ctx->ref = luaL_ref(s->hlua->T, LUA_REGISTRYINDEX);
10697 filter->ctx = flt_ctx;
10698 break;
10699 case HLUA_E_ERRMSG:
10700 SEND_ERR(s->be, "Lua filter '%s' : %s.\n", conf->reg->name, lua_tostring(s->hlua->T, -1));
10701 ret = -1;
10702 goto end;
10703 case HLUA_E_ETMOUT:
10704 SEND_ERR(s->be, "Lua filter '%s' : 'new' execution timeout.\n", conf->reg->name);
10705 ret = 0;
10706 goto end;
10707 case HLUA_E_NOMEM:
10708 SEND_ERR(s->be, "Lua filter '%s' : out of memory error.\n", conf->reg->name);
10709 ret = 0;
10710 goto end;
10711 case HLUA_E_AGAIN:
10712 case HLUA_E_YIELD:
10713 SEND_ERR(s->be, "Lua filter '%s': yield functions like core.tcp() or core.sleep()"
10714 " are not allowed from 'new' function.\n", conf->reg->name);
10715 ret = 0;
10716 goto end;
10717 case HLUA_E_ERR:
10718 SEND_ERR(s->be, "Lua filter '%s': 'new' returns an unknown error.\n", conf->reg->name);
10719 ret = 0;
10720 goto end;
10721 default:
10722 ret = 0;
10723 goto end;
10724 }
10725
10726 end:
10727 if (s->hlua)
10728 lua_settop(s->hlua->T, 0);
10729 if (ret <= 0) {
10730 if (flt_ctx) {
10731 hlua_ctx_destroy(flt_ctx->hlua[0]);
10732 hlua_ctx_destroy(flt_ctx->hlua[1]);
10733 pool_free(pool_head_hlua_flt_ctx, flt_ctx);
10734 }
10735 }
10736 return ret;
10737}
10738
10739static void hlua_filter_delete(struct stream *s, struct filter *filter)
10740{
10741 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10742
10743 luaL_unref(s->hlua->T, LUA_REGISTRYINDEX, flt_ctx->ref);
10744 hlua_ctx_destroy(flt_ctx->hlua[0]);
10745 hlua_ctx_destroy(flt_ctx->hlua[1]);
10746 pool_free(pool_head_hlua_flt_ctx, flt_ctx);
10747 filter->ctx = NULL;
10748}
10749
Christopher Faulet9f55a502020-02-25 15:21:02 +010010750static int hlua_filter_from_payload(struct filter *filter)
10751{
10752 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10753
10754 return (flt_ctx && !!(flt_ctx->flags & HLUA_FLT_CTX_FL_PAYLOAD));
10755}
10756
Christopher Fauletc404f112020-02-26 15:03:09 +010010757static int hlua_filter_callback(struct stream *s, struct filter *filter, const char *fun,
10758 int dir, unsigned int flags)
10759{
10760 struct hlua *flt_hlua;
10761 struct hlua_flt_config *conf = FLT_CONF(filter);
10762 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10763 unsigned int hflags = HLUA_TXN_FLT_CTX;
10764 int ret = 1;
10765
10766 flt_hlua = flt_ctx->hlua[(dir == SMP_OPT_DIR_REQ ? 0 : 1)];
10767 if (!flt_hlua)
10768 goto end;
10769
10770 if (!HLUA_IS_RUNNING(flt_hlua)) {
10771 int extra_idx = lua_gettop(flt_hlua->T);
10772
10773 /* The following Lua calls can fail. */
10774 if (!SET_SAFE_LJMP(flt_hlua)) {
10775 const char *error;
10776
10777 if (lua_type(flt_hlua->T, -1) == LUA_TSTRING)
10778 error = lua_tostring(flt_hlua->T, -1);
10779 else
10780 error = "critical error";
10781 SEND_ERR(s->be, "Lua filter '%s': %s.\n", conf->reg->name, error);
10782 goto end;
10783 }
10784
10785 /* Check stack size. */
10786 if (!lua_checkstack(flt_hlua->T, 3)) {
10787 SEND_ERR(s->be, "Lua filter '%s': full stack.\n", conf->reg->name);
10788 RESET_SAFE_LJMP(flt_hlua);
10789 goto end;
10790 }
10791
10792 lua_rawgeti(flt_hlua->T, LUA_REGISTRYINDEX, flt_ctx->ref);
10793 if (lua_getfield(flt_hlua->T, -1, fun) != LUA_TFUNCTION) {
10794 RESET_SAFE_LJMP(flt_hlua);
10795 goto end;
10796 }
10797 lua_insert(flt_hlua->T, -2);
10798
10799 if (!hlua_txn_new(flt_hlua->T, s, s->be, dir, hflags)) {
10800 SEND_ERR(s->be, "Lua filter '%s': full stack.\n", conf->reg->name);
10801 RESET_SAFE_LJMP(flt_hlua);
10802 goto end;
10803 }
10804 flt_hlua->nargs = 2;
10805
10806 if (flags & HLUA_FLT_CB_ARG_CHN) {
10807 if (dir == SMP_OPT_DIR_REQ)
10808 lua_getfield(flt_hlua->T, -1, "req");
10809 else
10810 lua_getfield(flt_hlua->T, -1, "res");
10811 if (lua_type(flt_hlua->T, -1) == LUA_TTABLE) {
10812 lua_pushstring(flt_hlua->T, "__filter");
10813 lua_pushlightuserdata(flt_hlua->T, filter);
10814 lua_settable(flt_hlua->T, -3);
10815 }
10816 flt_hlua->nargs++;
10817 }
10818 else if (flags & HLUA_FLT_CB_ARG_HTTP_MSG) {
Christopher Fauleteae8afa2020-02-26 17:15:48 +010010819 if (dir == SMP_OPT_DIR_REQ)
10820 lua_getfield(flt_hlua->T, -1, "http_req");
10821 else
10822 lua_getfield(flt_hlua->T, -1, "http_res");
10823 if (lua_type(flt_hlua->T, -1) == LUA_TTABLE) {
10824 lua_pushstring(flt_hlua->T, "__filter");
10825 lua_pushlightuserdata(flt_hlua->T, filter);
10826 lua_settable(flt_hlua->T, -3);
10827 }
10828 flt_hlua->nargs++;
Christopher Fauletc404f112020-02-26 15:03:09 +010010829 }
10830
10831 /* Check stack size. */
10832 if (!lua_checkstack(flt_hlua->T, 1)) {
10833 SEND_ERR(s->be, "Lua filter '%s': full stack.\n", conf->reg->name);
10834 RESET_SAFE_LJMP(flt_hlua);
10835 goto end;
10836 }
10837
10838 while (extra_idx--) {
10839 lua_pushvalue(flt_hlua->T, 1);
10840 lua_remove(flt_hlua->T, 1);
10841 flt_hlua->nargs++;
10842 }
10843
10844 /* We must initialize the execution timeouts. */
10845 flt_hlua->max_time = hlua_timeout_session;
10846
10847 /* At this point the execution is safe. */
10848 RESET_SAFE_LJMP(flt_hlua);
10849 }
10850
10851 switch (hlua_ctx_resume(flt_hlua, !(flags & HLUA_FLT_CB_FINAL))) {
10852 case HLUA_E_OK:
10853 /* Catch the return value if it required */
10854 if ((flags & HLUA_FLT_CB_RETVAL) && lua_gettop(flt_hlua->T) > 0) {
10855 ret = lua_tointeger(flt_hlua->T, -1);
10856 lua_settop(flt_hlua->T, 0); /* Empty the stack. */
10857 }
10858
10859 /* Set timeout in the required channel. */
10860 if (flt_hlua->wake_time != TICK_ETERNITY) {
10861 if (dir == SMP_OPT_DIR_REQ)
10862 s->req.analyse_exp = flt_hlua->wake_time;
10863 else
10864 s->res.analyse_exp = flt_hlua->wake_time;
10865 }
10866 break;
10867 case HLUA_E_AGAIN:
10868 /* Set timeout in the required channel. */
10869 if (flt_hlua->wake_time != TICK_ETERNITY) {
10870 if (dir == SMP_OPT_DIR_REQ)
10871 s->req.analyse_exp = flt_hlua->wake_time;
10872 else
10873 s->res.analyse_exp = flt_hlua->wake_time;
10874 }
10875 /* Some actions can be wake up when a "write" event
10876 * is detected on a response channel. This is useful
10877 * only for actions targeted on the requests.
10878 */
10879 if (HLUA_IS_WAKERESWR(flt_hlua))
10880 s->res.flags |= CF_WAKE_WRITE;
10881 if (HLUA_IS_WAKEREQWR(flt_hlua))
10882 s->req.flags |= CF_WAKE_WRITE;
10883 ret = 0;
10884 goto end;
10885 case HLUA_E_ERRMSG:
10886 SEND_ERR(s->be, "Lua filter '%s' : %s.\n", conf->reg->name, lua_tostring(flt_hlua->T, -1));
10887 ret = -1;
10888 goto end;
10889 case HLUA_E_ETMOUT:
10890 SEND_ERR(s->be, "Lua filter '%s' : '%s' callback execution timeout.\n", conf->reg->name, fun);
10891 goto end;
10892 case HLUA_E_NOMEM:
10893 SEND_ERR(s->be, "Lua filter '%s' : out of memory error.\n", conf->reg->name);
10894 goto end;
10895 case HLUA_E_YIELD:
10896 SEND_ERR(s->be, "Lua filter '%s': yield functions like core.tcp() or core.sleep()"
10897 " are not allowed from '%s' callback.\n", conf->reg->name, fun);
10898 goto end;
10899 case HLUA_E_ERR:
10900 SEND_ERR(s->be, "Lua filter '%s': '%s' returns an unknown error.\n", conf->reg->name, fun);
10901 goto end;
10902 default:
10903 goto end;
10904 }
10905
10906
10907 end:
10908 return ret;
10909}
10910
10911static int hlua_filter_start_analyze(struct stream *s, struct filter *filter, struct channel *chn)
10912{
10913 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10914
10915 flt_ctx->flags = 0;
10916 return hlua_filter_callback(s, filter, "start_analyze",
10917 (!(chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES),
10918 (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_RETVAL | HLUA_FLT_CB_ARG_CHN));
10919}
10920
10921static int hlua_filter_end_analyze(struct stream *s, struct filter *filter, struct channel *chn)
10922{
10923 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10924
10925 flt_ctx->flags &= ~HLUA_FLT_CTX_FL_PAYLOAD;
10926 return hlua_filter_callback(s, filter, "end_analyze",
10927 (!(chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES),
10928 (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_RETVAL | HLUA_FLT_CB_ARG_CHN));
10929}
10930
Christopher Fauleteae8afa2020-02-26 17:15:48 +010010931static int hlua_filter_http_headers(struct stream *s, struct filter *filter, struct http_msg *msg)
10932{
10933 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10934
10935 flt_ctx->flags &= ~HLUA_FLT_CTX_FL_PAYLOAD;
10936 return hlua_filter_callback(s, filter, "http_headers",
10937 (!(msg->chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES),
10938 (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_RETVAL | HLUA_FLT_CB_ARG_HTTP_MSG));
10939}
10940
10941static int hlua_filter_http_payload(struct stream *s, struct filter *filter, struct http_msg *msg,
10942 unsigned int offset, unsigned int len)
10943{
10944 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10945 struct hlua *flt_hlua;
10946 int dir = (!(msg->chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES);
10947 int idx = (dir == SMP_OPT_DIR_REQ ? 0 : 1);
10948 int ret;
10949
10950 flt_hlua = flt_ctx->hlua[idx];
10951 flt_ctx->cur_off[idx] = offset;
10952 flt_ctx->cur_len[idx] = len;
10953 flt_ctx->flags |= HLUA_FLT_CTX_FL_PAYLOAD;
10954 ret = hlua_filter_callback(s, filter, "http_payload", dir, (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_ARG_HTTP_MSG));
10955 if (ret != -1) {
10956 ret = flt_ctx->cur_len[idx];
10957 if (lua_gettop(flt_hlua->T) > 0) {
10958 ret = lua_tointeger(flt_hlua->T, -1);
10959 if (ret > flt_ctx->cur_len[idx])
10960 ret = flt_ctx->cur_len[idx];
10961 lua_settop(flt_hlua->T, 0); /* Empty the stack. */
10962 }
10963 }
10964 return ret;
10965}
10966
10967static int hlua_filter_http_end(struct stream *s, struct filter *filter, struct http_msg *msg)
10968{
10969 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10970
10971 flt_ctx->flags &= ~HLUA_FLT_CTX_FL_PAYLOAD;
10972 return hlua_filter_callback(s, filter, "http_end",
10973 (!(msg->chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES),
10974 (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_RETVAL | HLUA_FLT_CB_ARG_HTTP_MSG));
10975}
10976
Christopher Fauletc404f112020-02-26 15:03:09 +010010977static int hlua_filter_tcp_payload(struct stream *s, struct filter *filter, struct channel *chn,
10978 unsigned int offset, unsigned int len)
10979{
10980 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10981 struct hlua *flt_hlua;
10982 int dir = (!(chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES);
10983 int idx = (dir == SMP_OPT_DIR_REQ ? 0 : 1);
10984 int ret;
10985
10986 flt_hlua = flt_ctx->hlua[idx];
10987 flt_ctx->cur_off[idx] = offset;
10988 flt_ctx->cur_len[idx] = len;
10989 flt_ctx->flags |= HLUA_FLT_CTX_FL_PAYLOAD;
10990 ret = hlua_filter_callback(s, filter, "tcp_payload", dir, (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_ARG_CHN));
10991 if (ret != -1) {
10992 ret = flt_ctx->cur_len[idx];
10993 if (lua_gettop(flt_hlua->T) > 0) {
10994 ret = lua_tointeger(flt_hlua->T, -1);
10995 if (ret > flt_ctx->cur_len[idx])
10996 ret = flt_ctx->cur_len[idx];
10997 lua_settop(flt_hlua->T, 0); /* Empty the stack. */
10998 }
10999 }
11000 return ret;
11001}
11002
Christopher Faulet69c581a2021-05-31 08:54:04 +020011003static int hlua_filter_parse_fct(char **args, int *cur_arg, struct proxy *px,
11004 struct flt_conf *fconf, char **err, void *private)
11005{
11006 struct hlua_reg_filter *reg_flt = private;
11007 lua_State *L;
11008 struct hlua_flt_config *conf = NULL;
11009 const char *flt_id = NULL;
11010 int state_id, pos, flt_flags = 0;
11011 struct flt_ops *hlua_flt_ops = NULL;
11012
11013 state_id = reg_flt_to_stack_id(reg_flt);
11014 L = hlua_states[state_id];
11015
11016 /* Initialize the filter ops with default callbacks */
11017 hlua_flt_ops = calloc(1, sizeof(*hlua_flt_ops));
Christopher Fauletc86bb872021-08-13 08:33:57 +020011018 if (!hlua_flt_ops)
11019 goto error;
Christopher Faulet69c581a2021-05-31 08:54:04 +020011020 hlua_flt_ops->init = hlua_filter_init;
11021 hlua_flt_ops->deinit = hlua_filter_deinit;
11022 if (state_id) {
11023 /* Set per-thread callback if script is loaded per-thread */
11024 hlua_flt_ops->init_per_thread = hlua_filter_init_per_thread;
11025 hlua_flt_ops->deinit_per_thread = hlua_filter_deinit_per_thread;
11026 }
11027 hlua_flt_ops->attach = hlua_filter_new;
11028 hlua_flt_ops->detach = hlua_filter_delete;
11029
11030 /* Push the filter class on the stack and resolve all callbacks */
11031 lua_rawgeti(L, LUA_REGISTRYINDEX, reg_flt->flt_ref[state_id]);
11032
Christopher Fauletc404f112020-02-26 15:03:09 +010011033 if (lua_getfield(L, -1, "start_analyze") == LUA_TFUNCTION)
11034 hlua_flt_ops->channel_start_analyze = hlua_filter_start_analyze;
11035 lua_pop(L, 1);
11036 if (lua_getfield(L, -1, "end_analyze") == LUA_TFUNCTION)
11037 hlua_flt_ops->channel_end_analyze = hlua_filter_end_analyze;
11038 lua_pop(L, 1);
Christopher Fauleteae8afa2020-02-26 17:15:48 +010011039 if (lua_getfield(L, -1, "http_headers") == LUA_TFUNCTION)
11040 hlua_flt_ops->http_headers = hlua_filter_http_headers;
11041 lua_pop(L, 1);
11042 if (lua_getfield(L, -1, "http_payload") == LUA_TFUNCTION)
11043 hlua_flt_ops->http_payload = hlua_filter_http_payload;
11044 lua_pop(L, 1);
11045 if (lua_getfield(L, -1, "http_end") == LUA_TFUNCTION)
11046 hlua_flt_ops->http_end = hlua_filter_http_end;
11047 lua_pop(L, 1);
Christopher Fauletc404f112020-02-26 15:03:09 +010011048 if (lua_getfield(L, -1, "tcp_payload") == LUA_TFUNCTION)
11049 hlua_flt_ops->tcp_payload = hlua_filter_tcp_payload;
11050 lua_pop(L, 1);
Christopher Faulet69c581a2021-05-31 08:54:04 +020011051
11052 /* Get id and flags of the filter class */
11053 if (lua_getfield(L, -1, "id") == LUA_TSTRING)
11054 flt_id = lua_tostring(L, -1);
11055 lua_pop(L, 1);
11056 if (lua_getfield(L, -1, "flags") == LUA_TNUMBER)
11057 flt_flags = lua_tointeger(L, -1);
11058 lua_pop(L, 1);
11059
11060 /* Create the filter config */
11061 conf = calloc(1, sizeof(*conf));
Christopher Fauletc86bb872021-08-13 08:33:57 +020011062 if (!conf)
Christopher Faulet69c581a2021-05-31 08:54:04 +020011063 goto error;
Christopher Faulet69c581a2021-05-31 08:54:04 +020011064 conf->reg = reg_flt;
11065
11066 /* duplicate args */
11067 for (pos = 0; *args[*cur_arg + 1 + pos]; pos++);
11068 conf->args = calloc(pos + 1, sizeof(*conf->args));
Christopher Fauletc86bb872021-08-13 08:33:57 +020011069 if (!conf->args)
11070 goto error;
11071 for (pos = 0; *args[*cur_arg + 1 + pos]; pos++) {
Christopher Faulet69c581a2021-05-31 08:54:04 +020011072 conf->args[pos] = strdup(args[*cur_arg + 1 + pos]);
Christopher Fauletc86bb872021-08-13 08:33:57 +020011073 if (!conf->args[pos])
11074 goto error;
11075 }
Christopher Faulet69c581a2021-05-31 08:54:04 +020011076 conf->args[pos] = NULL;
11077 *cur_arg += pos + 1;
11078
Christopher Fauletc86bb872021-08-13 08:33:57 +020011079 if (flt_id) {
11080 fconf->id = strdup(flt_id);
11081 if (!fconf->id)
11082 goto error;
11083 }
Christopher Faulet69c581a2021-05-31 08:54:04 +020011084 fconf->flags = flt_flags;
11085 fconf->conf = conf;
11086 fconf->ops = hlua_flt_ops;
11087
11088 lua_settop(L, 0);
11089 return 0;
11090
11091 error:
Christopher Fauletc86bb872021-08-13 08:33:57 +020011092 memprintf(err, "Lua filter '%s' : Lua out of memory error", reg_flt->name);
Christopher Faulet69c581a2021-05-31 08:54:04 +020011093 free(hlua_flt_ops);
Christopher Fauletc86bb872021-08-13 08:33:57 +020011094 if (conf && conf->args) {
11095 for (pos = 0; conf->args[pos]; pos++)
11096 free(conf->args[pos]);
11097 free(conf->args);
11098 }
Christopher Faulet69c581a2021-05-31 08:54:04 +020011099 free(conf);
Christopher Fauletc86bb872021-08-13 08:33:57 +020011100 free((char *)fconf->id);
Christopher Faulet69c581a2021-05-31 08:54:04 +020011101 lua_settop(L, 0);
11102 return -1;
11103}
11104
Christopher Fauletc404f112020-02-26 15:03:09 +010011105__LJMP static int hlua_register_data_filter(lua_State *L)
11106{
11107 struct filter *filter;
11108 struct channel *chn;
11109
11110 MAY_LJMP(check_args(L, 2, "register_data_filter"));
11111 MAY_LJMP(luaL_checktype(L, 1, LUA_TTABLE));
11112 chn = MAY_LJMP(hlua_checkchannel(L, 2));
11113
11114 lua_getfield(L, 1, "__filter");
11115 MAY_LJMP(luaL_checktype(L, -1, LUA_TLIGHTUSERDATA));
11116 filter = lua_touserdata (L, -1);
11117 lua_pop(L, 1);
11118
11119 register_data_filter(chn_strm(chn), chn, filter);
11120 return 1;
11121}
11122
11123__LJMP static int hlua_unregister_data_filter(lua_State *L)
11124{
11125 struct filter *filter;
11126 struct channel *chn;
11127
11128 MAY_LJMP(check_args(L, 2, "unregister_data_filter"));
11129 MAY_LJMP(luaL_checktype(L, 1, LUA_TTABLE));
11130 chn = MAY_LJMP(hlua_checkchannel(L, 2));
11131
11132 lua_getfield(L, 1, "__filter");
11133 MAY_LJMP(luaL_checktype(L, -1, LUA_TLIGHTUSERDATA));
11134 filter = lua_touserdata (L, -1);
11135 lua_pop(L, 1);
11136
11137 unregister_data_filter(chn_strm(chn), chn, filter);
11138 return 1;
11139}
11140
Christopher Faulet69c581a2021-05-31 08:54:04 +020011141/* This function is an LUA binding used for registering a filter. It expects a
Ilya Shipitsinff0f2782021-08-22 22:18:07 +050011142 * filter name used in the haproxy configuration file and a LUA function to
Christopher Faulet69c581a2021-05-31 08:54:04 +020011143 * parse configuration arguments.
11144 */
11145__LJMP static int hlua_register_filter(lua_State *L)
11146{
11147 struct buffer *trash;
11148 struct flt_kw_list *fkl;
11149 struct flt_kw *fkw;
11150 const char *name;
11151 struct hlua_reg_filter *reg_flt= NULL;
11152 int flt_ref, fun_ref;
11153 int len;
11154
11155 MAY_LJMP(check_args(L, 3, "register_filter"));
11156
11157 /* First argument : filter name. */
11158 name = MAY_LJMP(luaL_checkstring(L, 1));
11159
11160 /* Second argument : The filter class */
11161 flt_ref = MAY_LJMP(hlua_checktable(L, 2));
11162
11163 /* Third argument : lua function. */
11164 fun_ref = MAY_LJMP(hlua_checkfunction(L, 3));
11165
11166 trash = get_trash_chunk();
11167 chunk_printf(trash, "lua.%s", name);
11168 fkw = flt_find_kw(trash->area);
11169 if (fkw != NULL) {
11170 reg_flt = fkw->private;
11171 if (reg_flt->flt_ref[hlua_state_id] != -1 || reg_flt->fun_ref[hlua_state_id] != -1) {
11172 ha_warning("Trying to register filter 'lua.%s' more than once. "
11173 "This will become a hard error in version 2.5.\n", name);
11174 }
11175 reg_flt->flt_ref[hlua_state_id] = flt_ref;
11176 reg_flt->fun_ref[hlua_state_id] = fun_ref;
11177 return 0;
11178 }
11179
11180 fkl = calloc(1, sizeof(*fkl) + sizeof(struct flt_kw) * 2);
11181 if (!fkl)
11182 goto alloc_error;
11183 fkl->scope = "HLUA";
11184
11185 reg_flt = new_hlua_reg_filter(name);
11186 if (!reg_flt)
11187 goto alloc_error;
11188
11189 reg_flt->flt_ref[hlua_state_id] = flt_ref;
11190 reg_flt->fun_ref[hlua_state_id] = fun_ref;
11191
11192 /* The filter keyword */
11193 len = strlen("lua.") + strlen(name) + 1;
11194 fkl->kw[0].kw = calloc(1, len);
11195 if (!fkl->kw[0].kw)
11196 goto alloc_error;
11197
11198 snprintf((char *)fkl->kw[0].kw, len, "lua.%s", name);
11199
11200 fkl->kw[0].parse = hlua_filter_parse_fct;
11201 fkl->kw[0].private = reg_flt;
11202 memset(&fkl->kw[1], 0, sizeof(*fkl->kw));
11203
11204 /* Register this new filter */
11205 flt_register_keywords(fkl);
11206
11207 return 0;
11208
11209 alloc_error:
11210 release_hlua_reg_filter(reg_flt);
11211 ha_free(&fkl);
11212 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
11213 return 0; /* Never reached */
11214}
11215
Thierry FOURNIERbd413492015-03-03 16:52:26 +010011216static int hlua_read_timeout(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011217 const struct proxy *defpx, const char *file, int line,
Thierry FOURNIERbd413492015-03-03 16:52:26 +010011218 char **err, unsigned int *timeout)
11219{
11220 const char *error;
11221
11222 error = parse_time_err(args[1], timeout, TIME_UNIT_MS);
Willy Tarreau9faebe32019-06-07 19:00:37 +020011223 if (error == PARSE_TIME_OVER) {
11224 memprintf(err, "timer overflow in argument <%s> to <%s> (maximum value is 2147483647 ms or ~24.8 days)",
11225 args[1], args[0]);
11226 return -1;
11227 }
11228 else if (error == PARSE_TIME_UNDER) {
11229 memprintf(err, "timer underflow in argument <%s> to <%s> (minimum non-null value is 1 ms)",
11230 args[1], args[0]);
11231 return -1;
11232 }
11233 else if (error) {
Thierry FOURNIERbd413492015-03-03 16:52:26 +010011234 memprintf(err, "%s: invalid timeout", args[0]);
11235 return -1;
11236 }
11237 return 0;
11238}
11239
11240static int hlua_session_timeout(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011241 const struct proxy *defpx, const char *file, int line,
Thierry FOURNIERbd413492015-03-03 16:52:26 +010011242 char **err)
11243{
11244 return hlua_read_timeout(args, section_type, curpx, defpx,
11245 file, line, err, &hlua_timeout_session);
11246}
11247
11248static int hlua_task_timeout(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011249 const struct proxy *defpx, const char *file, int line,
Thierry FOURNIERbd413492015-03-03 16:52:26 +010011250 char **err)
11251{
11252 return hlua_read_timeout(args, section_type, curpx, defpx,
11253 file, line, err, &hlua_timeout_task);
11254}
11255
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020011256static int hlua_applet_timeout(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011257 const struct proxy *defpx, const char *file, int line,
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020011258 char **err)
11259{
11260 return hlua_read_timeout(args, section_type, curpx, defpx,
11261 file, line, err, &hlua_timeout_applet);
11262}
11263
Thierry FOURNIERee9f8022015-03-03 17:37:37 +010011264static int hlua_forced_yield(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011265 const struct proxy *defpx, const char *file, int line,
Thierry FOURNIERee9f8022015-03-03 17:37:37 +010011266 char **err)
11267{
11268 char *error;
11269
11270 hlua_nb_instruction = strtoll(args[1], &error, 10);
11271 if (*error != '\0') {
11272 memprintf(err, "%s: invalid number", args[0]);
11273 return -1;
11274 }
11275 return 0;
11276}
11277
Willy Tarreau32f61e22015-03-18 17:54:59 +010011278static int hlua_parse_maxmem(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011279 const struct proxy *defpx, const char *file, int line,
Willy Tarreau32f61e22015-03-18 17:54:59 +010011280 char **err)
11281{
11282 char *error;
11283
11284 if (*(args[1]) == 0) {
Thierry Fournier70e38e92022-09-19 09:01:53 +020011285 memprintf(err, "'%s' expects an integer argument (Lua memory size in MB).", args[0]);
Willy Tarreau32f61e22015-03-18 17:54:59 +010011286 return -1;
11287 }
11288 hlua_global_allocator.limit = strtoll(args[1], &error, 10) * 1024L * 1024L;
11289 if (*error != '\0') {
11290 memprintf(err, "%s: invalid number %s (error at '%c')", args[0], args[1], *error);
11291 return -1;
11292 }
11293 return 0;
11294}
11295
11296
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011297/* This function is called by the main configuration key "lua-load". It loads and
11298 * execute an lua file during the parsing of the HAProxy configuration file. It is
11299 * the main lua entry point.
11300 *
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -080011301 * This function runs with the HAProxy keywords API. It returns -1 if an error
11302 * occurs, otherwise it returns 0.
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011303 *
11304 * In some error case, LUA set an error message in top of the stack. This function
11305 * returns this error message in the HAProxy logs and pop it from the stack.
Thierry FOURNIERbabae282015-09-17 11:36:37 +020011306 *
11307 * This function can fail with an abort() due to an Lua critical error.
11308 * We are in the configuration parsing process of HAProxy, this abort() is
11309 * tolerated.
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011310 */
Thierry Fournierae6b5682022-09-19 09:04:16 +020011311static int hlua_load_state(char **args, lua_State *L, char **err)
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011312{
11313 int error;
Thierry Fournierae6b5682022-09-19 09:04:16 +020011314 int nargs;
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011315
11316 /* Just load and compile the file. */
Thierry Fournierae6b5682022-09-19 09:04:16 +020011317 error = luaL_loadfile(L, args[0]);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011318 if (error) {
Thierry Fournierae6b5682022-09-19 09:04:16 +020011319 memprintf(err, "error in Lua file '%s': %s", args[0], lua_tostring(L, -1));
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011320 lua_pop(L, 1);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011321 return -1;
11322 }
Thierry Fournierae6b5682022-09-19 09:04:16 +020011323
11324 /* Push args in the Lua stack, except the first one which is the filename */
11325 for (nargs = 1; *(args[nargs]) != 0; nargs++) {
Aurelien DARRAGON4d7aefe2022-09-23 10:22:14 +020011326 /* Check stack size. */
11327 if (!lua_checkstack(L, 1)) {
11328 memprintf(err, "Lua runtime error while loading arguments: stack is full.");
11329 return -1;
11330 }
Thierry Fournierae6b5682022-09-19 09:04:16 +020011331 lua_pushstring(L, args[nargs]);
11332 }
11333 nargs--;
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011334
11335 /* If no syntax error where detected, execute the code. */
Thierry Fournierae6b5682022-09-19 09:04:16 +020011336 error = lua_pcall(L, nargs, LUA_MULTRET, 0);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011337 switch (error) {
11338 case LUA_OK:
11339 break;
11340 case LUA_ERRRUN:
Thierry Fournier70e38e92022-09-19 09:01:53 +020011341 memprintf(err, "Lua runtime error: %s", lua_tostring(L, -1));
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011342 lua_pop(L, 1);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011343 return -1;
11344 case LUA_ERRMEM:
Thierry Fournier70e38e92022-09-19 09:01:53 +020011345 memprintf(err, "Lua out of memory error");
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011346 return -1;
11347 case LUA_ERRERR:
Thierry Fournier70e38e92022-09-19 09:01:53 +020011348 memprintf(err, "Lua message handler error: %s", lua_tostring(L, -1));
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011349 lua_pop(L, 1);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011350 return -1;
Christopher Faulet08ed98f2020-07-28 10:33:25 +020011351#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM <= 503
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011352 case LUA_ERRGCMM:
Thierry Fournier70e38e92022-09-19 09:01:53 +020011353 memprintf(err, "Lua garbage collector error: %s", lua_tostring(L, -1));
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011354 lua_pop(L, 1);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011355 return -1;
Christopher Faulet08ed98f2020-07-28 10:33:25 +020011356#endif
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011357 default:
Thierry Fournier70e38e92022-09-19 09:01:53 +020011358 memprintf(err, "Lua unknown error: %s", lua_tostring(L, -1));
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011359 lua_pop(L, 1);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011360 return -1;
11361 }
11362
11363 return 0;
11364}
11365
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011366static int hlua_load(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011367 const struct proxy *defpx, const char *file, int line,
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011368 char **err)
11369{
11370 if (*(args[1]) == 0) {
Thierry Fournier70e38e92022-09-19 09:01:53 +020011371 memprintf(err, "'%s' expects a file name as parameter.", args[0]);
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011372 return -1;
11373 }
11374
Thierry Fournier59f11be2020-11-29 00:37:41 +010011375 /* loading for global state */
Thierry Fournierc7492592020-11-28 23:57:24 +010011376 hlua_state_id = 0;
Willy Tarreau43ab05b2021-09-28 09:43:11 +020011377 ha_set_thread(NULL);
Thierry Fournierae6b5682022-09-19 09:04:16 +020011378 return hlua_load_state(&args[1], hlua_states[0], err);
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011379}
11380
Thierry Fournier59f11be2020-11-29 00:37:41 +010011381static int hlua_load_per_thread(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011382 const struct proxy *defpx, const char *file, int line,
Thierry Fournier59f11be2020-11-29 00:37:41 +010011383 char **err)
11384{
11385 int len;
Thierry Fournierae6b5682022-09-19 09:04:16 +020011386 int i;
Thierry Fournier59f11be2020-11-29 00:37:41 +010011387
11388 if (*(args[1]) == 0) {
Thierry Fournier70e38e92022-09-19 09:01:53 +020011389 memprintf(err, "'%s' expects a file as parameter.", args[0]);
Thierry Fournier59f11be2020-11-29 00:37:41 +010011390 return -1;
11391 }
11392
11393 if (per_thread_load == NULL) {
11394 /* allocate the first entry large enough to store the final NULL */
11395 per_thread_load = calloc(1, sizeof(*per_thread_load));
11396 if (per_thread_load == NULL) {
11397 memprintf(err, "out of memory error");
11398 return -1;
11399 }
11400 }
11401
11402 /* count used entries */
11403 for (len = 0; per_thread_load[len] != NULL; len++)
11404 ;
11405
11406 per_thread_load = realloc(per_thread_load, (len + 2) * sizeof(*per_thread_load));
11407 if (per_thread_load == NULL) {
11408 memprintf(err, "out of memory error");
11409 return -1;
11410 }
Thierry Fournier59f11be2020-11-29 00:37:41 +010011411 per_thread_load[len + 1] = NULL;
11412
Thierry Fournierae6b5682022-09-19 09:04:16 +020011413 /* count args excepting the first, allocate array and copy args */
11414 for (i = 0; *(args[i + 1]) != 0; i++);
Aurelien DARRAGONb12d1692022-09-23 08:48:34 +020011415 per_thread_load[len] = calloc(i + 1, sizeof(*per_thread_load[len]));
Thierry Fournier59f11be2020-11-29 00:37:41 +010011416 if (per_thread_load[len] == NULL) {
11417 memprintf(err, "out of memory error");
11418 return -1;
11419 }
Thierry Fournierae6b5682022-09-19 09:04:16 +020011420 for (i = 1; *(args[i]) != 0; i++) {
11421 per_thread_load[len][i - 1] = strdup(args[i]);
11422 if (per_thread_load[len][i - 1] == NULL) {
11423 memprintf(err, "out of memory error");
11424 return -1;
11425 }
11426 }
11427 per_thread_load[len][i - 1] = strdup("");
11428 if (per_thread_load[len][i - 1] == NULL) {
11429 memprintf(err, "out of memory error");
11430 return -1;
11431 }
Thierry Fournier59f11be2020-11-29 00:37:41 +010011432
11433 /* loading for thread 1 only */
11434 hlua_state_id = 1;
Willy Tarreau43ab05b2021-09-28 09:43:11 +020011435 ha_set_thread(NULL);
Thierry Fournierae6b5682022-09-19 09:04:16 +020011436 return hlua_load_state(per_thread_load[len], hlua_states[1], err);
Thierry Fournier59f11be2020-11-29 00:37:41 +010011437}
11438
Tim Duesterhusc9fc9f22020-01-12 13:55:39 +010011439/* Prepend the given <path> followed by a semicolon to the `package.<type>` variable
11440 * in the given <ctx>.
11441 */
Thierry Fournier3fb9e512020-11-28 10:13:12 +010011442static int hlua_prepend_path(lua_State *L, char *type, char *path)
Tim Duesterhusc9fc9f22020-01-12 13:55:39 +010011443{
Thierry Fournier3fb9e512020-11-28 10:13:12 +010011444 lua_getglobal(L, "package"); /* push package variable */
11445 lua_pushstring(L, path); /* push given path */
11446 lua_pushstring(L, ";"); /* push semicolon */
11447 lua_getfield(L, -3, type); /* push old path */
11448 lua_concat(L, 3); /* concatenate to new path */
11449 lua_setfield(L, -2, type); /* store new path */
11450 lua_pop(L, 1); /* pop package variable */
Tim Duesterhusc9fc9f22020-01-12 13:55:39 +010011451
11452 return 0;
11453}
11454
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010011455static int hlua_config_prepend_path(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011456 const struct proxy *defpx, const char *file, int line,
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010011457 char **err)
11458{
11459 char *path;
11460 char *type = "path";
Tim Duesterhus621e74a2021-01-03 20:04:36 +010011461 struct prepend_path *p = NULL;
Bertrand Jacquin7fbc7702021-11-24 21:16:06 +000011462 size_t i;
Thierry Fournier59f11be2020-11-29 00:37:41 +010011463
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010011464 if (too_many_args(2, args, err, NULL)) {
Tim Duesterhus621e74a2021-01-03 20:04:36 +010011465 goto err;
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010011466 }
11467
11468 if (!(*args[1])) {
11469 memprintf(err, "'%s' expects to receive a <path> as argument", args[0]);
Tim Duesterhus621e74a2021-01-03 20:04:36 +010011470 goto err;
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010011471 }
11472 path = args[1];
11473
11474 if (*args[2]) {
11475 if (strcmp(args[2], "path") != 0 && strcmp(args[2], "cpath") != 0) {
11476 memprintf(err, "'%s' expects <type> to either be 'path' or 'cpath'", args[0]);
Tim Duesterhus621e74a2021-01-03 20:04:36 +010011477 goto err;
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010011478 }
11479 type = args[2];
11480 }
11481
Thierry Fournier59f11be2020-11-29 00:37:41 +010011482 p = calloc(1, sizeof(*p));
11483 if (p == NULL) {
Tim Duesterhusf89d43a2021-01-03 20:04:37 +010011484 memprintf(err, "memory allocation failed");
Tim Duesterhus621e74a2021-01-03 20:04:36 +010011485 goto err;
Thierry Fournier59f11be2020-11-29 00:37:41 +010011486 }
11487 p->path = strdup(path);
11488 if (p->path == NULL) {
Tim Duesterhusf89d43a2021-01-03 20:04:37 +010011489 memprintf(err, "memory allocation failed");
Tim Duesterhus621e74a2021-01-03 20:04:36 +010011490 goto err2;
Thierry Fournier59f11be2020-11-29 00:37:41 +010011491 }
11492 p->type = strdup(type);
11493 if (p->type == NULL) {
Tim Duesterhusf89d43a2021-01-03 20:04:37 +010011494 memprintf(err, "memory allocation failed");
Tim Duesterhus621e74a2021-01-03 20:04:36 +010011495 goto err2;
Thierry Fournier59f11be2020-11-29 00:37:41 +010011496 }
Willy Tarreau2b718102021-04-21 07:32:39 +020011497 LIST_APPEND(&prepend_path_list, &p->l);
Thierry Fournier59f11be2020-11-29 00:37:41 +010011498
Tim Duesterhus9e5e5862021-10-11 18:51:08 +020011499 /* Handle the global state and the per-thread state for the first
11500 * thread. The remaining threads will be initialized based on
11501 * prepend_path_list.
11502 */
Bertrand Jacquin7fbc7702021-11-24 21:16:06 +000011503 for (i = 0; i < 2; i++) {
Tim Duesterhus9e5e5862021-10-11 18:51:08 +020011504 lua_State *L = hlua_states[i];
11505 const char *error;
11506
11507 if (setjmp(safe_ljmp_env) != 0) {
11508 lua_atpanic(L, hlua_panic_safe);
11509 if (lua_type(L, -1) == LUA_TSTRING)
11510 error = lua_tostring(L, -1);
11511 else
11512 error = "critical error";
11513 fprintf(stderr, "lua-prepend-path: %s.\n", error);
11514 exit(1);
11515 } else {
11516 lua_atpanic(L, hlua_panic_ljmp);
11517 }
11518
11519 hlua_prepend_path(L, type, path);
11520
11521 lua_atpanic(L, hlua_panic_safe);
11522 }
11523
Thierry Fournier59f11be2020-11-29 00:37:41 +010011524 return 0;
Tim Duesterhus621e74a2021-01-03 20:04:36 +010011525
11526err2:
11527 free(p->type);
11528 free(p->path);
11529err:
11530 free(p);
11531 return -1;
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010011532}
11533
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011534/* configuration keywords declaration */
11535static struct cfg_kw_list cfg_kws = {{ },{
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010011536 { CFG_GLOBAL, "lua-prepend-path", hlua_config_prepend_path },
Thierry FOURNIERbd413492015-03-03 16:52:26 +010011537 { CFG_GLOBAL, "lua-load", hlua_load },
Thierry Fournier59f11be2020-11-29 00:37:41 +010011538 { CFG_GLOBAL, "lua-load-per-thread", hlua_load_per_thread },
Thierry FOURNIERbd413492015-03-03 16:52:26 +010011539 { CFG_GLOBAL, "tune.lua.session-timeout", hlua_session_timeout },
11540 { CFG_GLOBAL, "tune.lua.task-timeout", hlua_task_timeout },
Thierry FOURNIER56da1012015-10-01 08:42:31 +020011541 { CFG_GLOBAL, "tune.lua.service-timeout", hlua_applet_timeout },
Thierry FOURNIERee9f8022015-03-03 17:37:37 +010011542 { CFG_GLOBAL, "tune.lua.forced-yield", hlua_forced_yield },
Willy Tarreau32f61e22015-03-18 17:54:59 +010011543 { CFG_GLOBAL, "tune.lua.maxmem", hlua_parse_maxmem },
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011544 { 0, NULL, NULL },
11545}};
11546
Willy Tarreau0108d902018-11-25 19:14:37 +010011547INITCALL1(STG_REGISTER, cfg_register_keywords, &cfg_kws);
11548
William Lallemand52139182022-03-30 15:05:42 +020011549#ifdef USE_OPENSSL
Christopher Fauletafd8f102018-11-08 11:34:21 +010011550
William Lallemand30fcca12022-03-30 12:03:12 +020011551/*
11552 * This function replace a ckch_store by another one, and rebuild the ckch_inst and all its dependencies.
11553 * It does the sam as "cli_io_handler_commit_cert" but for lua, the major
11554 * difference is that the yield in lua and for the CLI is not handled the same
11555 * way.
11556 */
11557__LJMP static int hlua_ckch_commit_yield(lua_State *L, int status, lua_KContext ctx)
11558{
11559 struct ckch_inst **lua_ckchi = lua_touserdata(L, -1);
11560 struct ckch_store **lua_ckchs = lua_touserdata(L, -2);
11561 struct ckch_inst *ckchi = *lua_ckchi;
11562 struct ckch_store *old_ckchs = lua_ckchs[0];
11563 struct ckch_store *new_ckchs = lua_ckchs[1];
11564 struct hlua *hlua;
11565 char *err = NULL;
11566 int y = 1;
11567
11568 hlua = hlua_gethlua(L);
11569
11570 /* get the first ckchi to copy */
11571 if (ckchi == NULL)
11572 ckchi = LIST_ELEM(old_ckchs->ckch_inst.n, typeof(ckchi), by_ckchs);
11573
11574 /* walk through the old ckch_inst and creates new ckch_inst using the updated ckchs */
11575 list_for_each_entry_from(ckchi, &old_ckchs->ckch_inst, by_ckchs) {
11576 struct ckch_inst *new_inst;
11577
11578 /* it takes a lot of CPU to creates SSL_CTXs, so we yield every 10 CKCH instances */
11579 if (y % 10 == 0) {
11580
11581 *lua_ckchi = ckchi;
11582
11583 task_wakeup(hlua->task, TASK_WOKEN_MSG);
11584 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_ckch_commit_yield, TICK_ETERNITY, 0));
11585 }
11586
11587 if (ckch_inst_rebuild(new_ckchs, ckchi, &new_inst, &err))
11588 goto error;
11589
11590 /* link the new ckch_inst to the duplicate */
11591 LIST_APPEND(&new_ckchs->ckch_inst, &new_inst->by_ckchs);
11592 y++;
11593 }
11594
11595 /* The generation is finished, we can insert everything */
11596 ckch_store_replace(old_ckchs, new_ckchs);
11597
11598 lua_pop(L, 2); /* pop the lua_ckchs and ckchi */
11599
11600 HA_SPIN_UNLOCK(CKCH_LOCK, &ckch_lock);
11601
11602 return 0;
11603
11604error:
11605 ckch_store_free(new_ckchs);
11606 HA_SPIN_UNLOCK(CKCH_LOCK, &ckch_lock);
11607 WILL_LJMP(luaL_error(L, "%s", err));
11608 free(err);
11609
11610 return 0;
11611}
11612
11613/*
11614 * Replace a ckch_store <filename> in the ckchs_tree with a ckch_store created
11615 * from the table in parameter.
11616 *
11617 * This is equivalent to "set ssl cert" + "commit ssl cert" over the CLI, which
11618 * means it does not need to have a transaction since everything is done in the
11619 * same function.
11620 *
11621 * CertCache.set{filename="", crt="", key="", sctl="", ocsp="", issuer=""}
11622 *
11623 */
11624__LJMP static int hlua_ckch_set(lua_State *L)
11625{
11626 struct hlua *hlua;
11627 struct ckch_inst **lua_ckchi;
11628 struct ckch_store **lua_ckchs;
11629 struct ckch_store *old_ckchs = NULL;
11630 struct ckch_store *new_ckchs = NULL;
11631 int errcode = 0;
11632 char *err = NULL;
11633 struct cert_exts *cert_ext = NULL;
11634 char *filename;
William Lallemand52ddd992022-11-22 11:51:53 +010011635 struct ckch_data *data;
William Lallemand30fcca12022-03-30 12:03:12 +020011636 int ret;
11637
11638 if (lua_type(L, -1) != LUA_TTABLE)
11639 WILL_LJMP(luaL_error(L, "'CertCache.set' needs a table as argument"));
11640
11641 hlua = hlua_gethlua(L);
11642
11643 /* FIXME: this should not return an error but should come back later */
11644 if (HA_SPIN_TRYLOCK(CKCH_LOCK, &ckch_lock))
11645 WILL_LJMP(luaL_error(L, "CertCache already under lock"));
11646
11647 ret = lua_getfield(L, -1, "filename");
11648 if (ret != LUA_TSTRING) {
Thierry Fournier70e38e92022-09-19 09:01:53 +020011649 memprintf(&err, "%sNo filename specified!", err ? err : "");
William Lallemand30fcca12022-03-30 12:03:12 +020011650 errcode |= ERR_ALERT | ERR_FATAL;
11651 goto end;
11652 }
11653 filename = (char *)lua_tostring(L, -1);
11654
11655
11656 /* look for the filename in the tree */
11657 old_ckchs = ckchs_lookup(filename);
11658 if (!old_ckchs) {
Thierry Fournier70e38e92022-09-19 09:01:53 +020011659 memprintf(&err, "%sCan't replace a certificate which is not referenced by the configuration!", err ? err : "");
William Lallemand30fcca12022-03-30 12:03:12 +020011660 errcode |= ERR_ALERT | ERR_FATAL;
11661 goto end;
11662 }
11663 /* TODO: handle extra_files_noext */
11664
11665 new_ckchs = ckchs_dup(old_ckchs);
11666 if (!new_ckchs) {
Thierry Fournier70e38e92022-09-19 09:01:53 +020011667 memprintf(&err, "%sCannot allocate memory!", err ? err : "");
William Lallemand30fcca12022-03-30 12:03:12 +020011668 errcode |= ERR_ALERT | ERR_FATAL;
11669 goto end;
11670 }
11671
William Lallemand52ddd992022-11-22 11:51:53 +010011672 data = new_ckchs->data;
William Lallemand30fcca12022-03-30 12:03:12 +020011673
11674 /* loop on the field in the table, which have the same name as the
11675 * possible extensions of files */
11676 lua_pushnil(L);
11677 while (lua_next(L, 1)) {
11678 int i;
11679 const char *field = lua_tostring(L, -2);
11680 char *payload = (char *)lua_tostring(L, -1);
11681
11682 if (!field || strcmp(field, "filename") == 0) {
11683 lua_pop(L, 1);
11684 continue;
11685 }
11686
11687 for (i = 0; field && cert_exts[i].ext != NULL; i++) {
11688 if (strcmp(field, cert_exts[i].ext) == 0) {
11689 cert_ext = &cert_exts[i];
11690 break;
11691 }
11692 }
11693
11694 /* this is the default type, the field is not supported */
11695 if (cert_ext == NULL) {
Thierry Fournier70e38e92022-09-19 09:01:53 +020011696 memprintf(&err, "%sUnsupported field '%s'", err ? err : "", field);
William Lallemand30fcca12022-03-30 12:03:12 +020011697 errcode |= ERR_ALERT | ERR_FATAL;
11698 goto end;
11699 }
11700
11701 /* appply the change on the duplicate */
William Lallemand52ddd992022-11-22 11:51:53 +010011702 if (cert_ext->load(filename, payload, data, &err) != 0) {
Thierry Fournier70e38e92022-09-19 09:01:53 +020011703 memprintf(&err, "%sCan't load the payload for '%s'", err ? err : "", cert_ext->ext);
William Lallemand30fcca12022-03-30 12:03:12 +020011704 errcode |= ERR_ALERT | ERR_FATAL;
11705 goto end;
11706 }
11707 lua_pop(L, 1);
11708 }
11709
11710 /* store the pointers on the lua stack */
11711 lua_ckchs = lua_newuserdata(L, sizeof(struct ckch_store *) * 2);
11712 lua_ckchs[0] = old_ckchs;
11713 lua_ckchs[1] = new_ckchs;
11714 lua_ckchi = lua_newuserdata(L, sizeof(struct ckch_inst *));
11715 *lua_ckchi = NULL;
11716
11717 task_wakeup(hlua->task, TASK_WOKEN_MSG);
11718 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_ckch_commit_yield, TICK_ETERNITY, 0));
11719
11720end:
11721 HA_SPIN_UNLOCK(CKCH_LOCK, &ckch_lock);
11722
11723 if (errcode & ERR_CODE) {
11724 ckch_store_free(new_ckchs);
11725 WILL_LJMP(luaL_error(L, "%s", err));
11726 }
11727 free(err);
11728
11729 return 0;
11730}
11731
William Lallemand52139182022-03-30 15:05:42 +020011732#else
11733
11734__LJMP static int hlua_ckch_set(lua_State *L)
11735{
11736 WILL_LJMP(luaL_error(L, "'CertCache.set' needs an HAProxy built with OpenSSL"));
11737
11738 return 0;
11739}
11740#endif /* ! USE_OPENSSL */
11741
11742
11743
Thierry FOURNIERbabae282015-09-17 11:36:37 +020011744/* This function can fail with an abort() due to an Lua critical error.
11745 * We are in the initialisation process of HAProxy, this abort() is
11746 * tolerated.
11747 */
Thierry Fournierb8cef172020-11-28 15:37:17 +010011748int hlua_post_init_state(lua_State *L)
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010011749{
11750 struct hlua_init_function *init;
11751 const char *msg;
11752 enum hlua_exec ret;
Thierry Fournierfd107a22016-02-19 19:57:23 +010011753 const char *error;
Thierry Fournier670db242020-11-28 10:49:59 +010011754 const char *kind;
11755 const char *trace;
11756 int return_status = 1;
11757#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM >= 504
11758 int nres;
11759#endif
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010011760
Willy Tarreaucdb53462020-12-02 12:12:00 +010011761 /* disable memory limit checks if limit is not set */
11762 if (!hlua_global_allocator.limit)
11763 hlua_global_allocator.limit = ~hlua_global_allocator.limit;
11764
Ilya Shipitsin856aabc2020-04-16 23:51:34 +050011765 /* Call post initialisation function in safe environment. */
Thierry Fournier3c539322020-11-28 16:05:05 +010011766 if (setjmp(safe_ljmp_env) != 0) {
11767 lua_atpanic(L, hlua_panic_safe);
Thierry Fournierb8cef172020-11-28 15:37:17 +010011768 if (lua_type(L, -1) == LUA_TSTRING)
11769 error = lua_tostring(L, -1);
Thierry Fournier3d4a6752016-02-19 20:53:30 +010011770 else
11771 error = "critical error";
11772 fprintf(stderr, "Lua post-init: %s.\n", error);
11773 exit(1);
Thierry Fournier3c539322020-11-28 16:05:05 +010011774 } else {
11775 lua_atpanic(L, hlua_panic_ljmp);
Thierry Fournier3d4a6752016-02-19 20:53:30 +010011776 }
Frédéric Lécaille54f2bcf2018-08-29 13:46:24 +020011777
Thierry Fournierb8cef172020-11-28 15:37:17 +010011778 hlua_fcn_post_init(L);
Thierry Fournier3d4a6752016-02-19 20:53:30 +010011779
Thierry Fournierc7492592020-11-28 23:57:24 +010011780 list_for_each_entry(init, &hlua_init_functions[hlua_state_id], l) {
Thierry Fournierb8cef172020-11-28 15:37:17 +010011781 lua_rawgeti(L, LUA_REGISTRYINDEX, init->function_ref);
Thierry Fournier670db242020-11-28 10:49:59 +010011782
11783#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM >= 504
Thierry Fournierb8cef172020-11-28 15:37:17 +010011784 ret = lua_resume(L, L, 0, &nres);
Thierry Fournier670db242020-11-28 10:49:59 +010011785#else
Thierry Fournierb8cef172020-11-28 15:37:17 +010011786 ret = lua_resume(L, L, 0);
Thierry Fournier670db242020-11-28 10:49:59 +010011787#endif
11788 kind = NULL;
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010011789 switch (ret) {
Thierry Fournier670db242020-11-28 10:49:59 +010011790
11791 case LUA_OK:
Thierry Fournierb8cef172020-11-28 15:37:17 +010011792 lua_pop(L, -1);
Thierry Fournier13d08b72020-11-28 11:02:58 +010011793 break;
Thierry Fournier670db242020-11-28 10:49:59 +010011794
11795 case LUA_ERRERR:
11796 kind = "message handler error";
Willy Tarreau14de3952022-11-14 07:08:28 +010011797 __fallthrough;
Thierry Fournier670db242020-11-28 10:49:59 +010011798 case LUA_ERRRUN:
11799 if (!kind)
11800 kind = "runtime error";
Thierry Fournierb8cef172020-11-28 15:37:17 +010011801 msg = lua_tostring(L, -1);
11802 lua_settop(L, 0); /* Empty the stack. */
11803 lua_pop(L, 1);
Christopher Fauletd09cc512021-03-24 14:48:45 +010011804 trace = hlua_traceback(L, ", ");
Thierry Fournier670db242020-11-28 10:49:59 +010011805 if (msg)
11806 ha_alert("Lua init: %s: '%s' from %s\n", kind, msg, trace);
11807 else
11808 ha_alert("Lua init: unknown %s from %s\n", kind, trace);
11809 return_status = 0;
11810 break;
11811
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010011812 default:
Thierry Fournier670db242020-11-28 10:49:59 +010011813 /* Unknown error */
11814 kind = "Unknown error";
Willy Tarreau14de3952022-11-14 07:08:28 +010011815 __fallthrough;
Thierry Fournier670db242020-11-28 10:49:59 +010011816 case LUA_YIELD:
11817 /* yield is not configured at this step, this state doesn't happen */
11818 if (!kind)
11819 kind = "yield not allowed";
Willy Tarreau14de3952022-11-14 07:08:28 +010011820 __fallthrough;
Thierry Fournier670db242020-11-28 10:49:59 +010011821 case LUA_ERRMEM:
11822 if (!kind)
11823 kind = "out of memory error";
Thierry Fournierb8cef172020-11-28 15:37:17 +010011824 lua_settop(L, 0);
11825 lua_pop(L, 1);
Christopher Fauletd09cc512021-03-24 14:48:45 +010011826 trace = hlua_traceback(L, ", ");
Thierry Fournier670db242020-11-28 10:49:59 +010011827 ha_alert("Lua init: %s: %s\n", kind, trace);
11828 return_status = 0;
11829 break;
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010011830 }
Thierry Fournier670db242020-11-28 10:49:59 +010011831 if (!return_status)
11832 break;
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010011833 }
Thierry Fournier3c539322020-11-28 16:05:05 +010011834
11835 lua_atpanic(L, hlua_panic_safe);
Thierry Fournier670db242020-11-28 10:49:59 +010011836 return return_status;
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010011837}
11838
Thierry Fournierb8cef172020-11-28 15:37:17 +010011839int hlua_post_init()
11840{
Thierry Fournier59f11be2020-11-29 00:37:41 +010011841 int ret;
11842 int i;
11843 int errors;
11844 char *err = NULL;
11845 struct hlua_function *fcn;
Christopher Faulet69c581a2021-05-31 08:54:04 +020011846 struct hlua_reg_filter *reg_flt;
Thierry Fournier59f11be2020-11-29 00:37:41 +010011847
Willy Tarreaub1310492021-08-30 09:35:18 +020011848#if defined(USE_OPENSSL)
Thierry Fournierb8cef172020-11-28 15:37:17 +010011849 /* Initialize SSL server. */
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010011850 if (socket_ssl->xprt->prepare_srv) {
Thierry Fournierb8cef172020-11-28 15:37:17 +010011851 int saved_used_backed = global.ssl_used_backend;
11852 // don't affect maxconn automatic computation
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010011853 socket_ssl->xprt->prepare_srv(socket_ssl);
Thierry Fournierb8cef172020-11-28 15:37:17 +010011854 global.ssl_used_backend = saved_used_backed;
11855 }
11856#endif
11857
Thierry Fournierc7492592020-11-28 23:57:24 +010011858 /* Perform post init of common thread */
11859 hlua_state_id = 0;
Willy Tarreau43ab05b2021-09-28 09:43:11 +020011860 ha_set_thread(&ha_thread_info[0]);
Thierry Fournier59f11be2020-11-29 00:37:41 +010011861 ret = hlua_post_init_state(hlua_states[hlua_state_id]);
11862 if (ret == 0)
11863 return 0;
11864
11865 /* init remaining lua states and load files */
11866 for (hlua_state_id = 2; hlua_state_id < global.nbthread + 1; hlua_state_id++) {
11867
11868 /* set thread context */
Willy Tarreau43ab05b2021-09-28 09:43:11 +020011869 ha_set_thread(&ha_thread_info[hlua_state_id - 1]);
Thierry Fournier59f11be2020-11-29 00:37:41 +010011870
11871 /* Init lua state */
11872 hlua_states[hlua_state_id] = hlua_init_state(hlua_state_id);
11873
11874 /* Load lua files */
11875 for (i = 0; per_thread_load && per_thread_load[i]; i++) {
11876 ret = hlua_load_state(per_thread_load[i], hlua_states[hlua_state_id], &err);
11877 if (ret != 0) {
11878 ha_alert("Lua init: %s\n", err);
11879 return 0;
11880 }
11881 }
11882 }
11883
11884 /* Reset thread context */
Willy Tarreau43ab05b2021-09-28 09:43:11 +020011885 ha_set_thread(NULL);
Thierry Fournier59f11be2020-11-29 00:37:41 +010011886
11887 /* Execute post init for all states */
11888 for (hlua_state_id = 1; hlua_state_id < global.nbthread + 1; hlua_state_id++) {
11889
11890 /* set thread context */
Willy Tarreau43ab05b2021-09-28 09:43:11 +020011891 ha_set_thread(&ha_thread_info[hlua_state_id - 1]);
Thierry Fournier59f11be2020-11-29 00:37:41 +010011892
11893 /* run post init */
11894 ret = hlua_post_init_state(hlua_states[hlua_state_id]);
11895 if (ret == 0)
11896 return 0;
11897 }
11898
11899 /* Reset thread context */
Willy Tarreau43ab05b2021-09-28 09:43:11 +020011900 ha_set_thread(NULL);
Thierry Fournier59f11be2020-11-29 00:37:41 +010011901
11902 /* control functions registering. Each function must have:
11903 * - only the function_ref[0] set positive and all other to -1
11904 * - only the function_ref[0] set to -1 and all other positive
11905 * This ensure a same reference is not used both in shared
11906 * lua state and thread dedicated lua state. Note: is the case
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +050011907 * reach, the shared state is priority, but the bug will be
Thierry Fournier59f11be2020-11-29 00:37:41 +010011908 * complicated to found for the end user.
11909 */
11910 errors = 0;
11911 list_for_each_entry(fcn, &referenced_functions, l) {
11912 ret = 0;
11913 for (i = 1; i < global.nbthread + 1; i++) {
11914 if (fcn->function_ref[i] == -1)
11915 ret--;
11916 else
11917 ret++;
11918 }
11919 if (abs(ret) != global.nbthread) {
11920 ha_alert("Lua function '%s' is not referenced in all thread. "
11921 "Expect function in all thread or in none thread.\n", fcn->name);
11922 errors++;
11923 continue;
11924 }
11925
11926 if ((fcn->function_ref[0] == -1) == (ret < 0)) {
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +050011927 ha_alert("Lua function '%s' is referenced both ins shared Lua context (through lua-load) "
11928 "and per-thread Lua context (through lua-load-per-thread). these two context "
Thierry Fournier59f11be2020-11-29 00:37:41 +010011929 "exclusive.\n", fcn->name);
11930 errors++;
11931 }
11932 }
11933
Christopher Faulet69c581a2021-05-31 08:54:04 +020011934 /* Do the same with registered filters */
11935 list_for_each_entry(reg_flt, &referenced_filters, l) {
11936 ret = 0;
11937 for (i = 1; i < global.nbthread + 1; i++) {
11938 if (reg_flt->flt_ref[i] == -1)
11939 ret--;
11940 else
11941 ret++;
11942 }
11943 if (abs(ret) != global.nbthread) {
11944 ha_alert("Lua filter '%s' is not referenced in all thread. "
11945 "Expect function in all thread or in none thread.\n", reg_flt->name);
11946 errors++;
11947 continue;
11948 }
11949
11950 if ((reg_flt->flt_ref[0] == -1) == (ret < 0)) {
11951 ha_alert("Lua filter '%s' is referenced both ins shared Lua context (through lua-load) "
11952 "and per-thread Lua context (through lua-load-per-thread). these two context "
11953 "exclusive.\n", fcn->name);
11954 errors++;
11955 }
11956 }
11957
11958
Thierry Fournier59f11be2020-11-29 00:37:41 +010011959 if (errors > 0)
11960 return 0;
11961
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +050011962 /* after this point, this global will no longer be used, so set to
Thierry Fournier59f11be2020-11-29 00:37:41 +010011963 * -1 in order to have probably a segfault if someone use it
11964 */
11965 hlua_state_id = -1;
11966
11967 return 1;
Thierry Fournierb8cef172020-11-28 15:37:17 +010011968}
11969
Willy Tarreau32f61e22015-03-18 17:54:59 +010011970/* The memory allocator used by the Lua stack. <ud> is a pointer to the
11971 * allocator's context. <ptr> is the pointer to alloc/free/realloc. <osize>
11972 * is the previously allocated size or the kind of object in case of a new
Willy Tarreaud36c7fa2020-12-02 12:26:29 +010011973 * allocation. <nsize> is the requested new size. A new allocation is
11974 * indicated by <ptr> being NULL. A free is indicated by <nsize> being
Willy Tarreaucdb53462020-12-02 12:12:00 +010011975 * zero. This one verifies that the limits are respected but is optimized
11976 * for the fast case where limits are not used, hence stats are not updated.
Willy Tarreaua5efdff2021-10-22 16:00:02 +020011977 *
11978 * Warning: while this API ressembles glibc's realloc() a lot, glibc surpasses
11979 * POSIX by making realloc(ptr,0) an effective free(), but others do not do
11980 * that and will simply allocate zero as if it were the result of malloc(0),
11981 * so mapping this onto realloc() will lead to memory leaks on non-glibc
11982 * systems.
Willy Tarreau32f61e22015-03-18 17:54:59 +010011983 */
11984static void *hlua_alloc(void *ud, void *ptr, size_t osize, size_t nsize)
11985{
11986 struct hlua_mem_allocator *zone = ud;
Willy Tarreaucdb53462020-12-02 12:12:00 +010011987 size_t limit, old, new;
11988
11989 /* a limit of ~0 means unlimited and boot complete, so there's no need
11990 * for accounting anymore.
11991 */
Willy Tarreaua5efdff2021-10-22 16:00:02 +020011992 if (likely(~zone->limit == 0)) {
11993 if (!nsize)
11994 ha_free(&ptr);
11995 else
11996 ptr = realloc(ptr, nsize);
11997 return ptr;
11998 }
Willy Tarreau32f61e22015-03-18 17:54:59 +010011999
Willy Tarreaud36c7fa2020-12-02 12:26:29 +010012000 if (!ptr)
12001 osize = 0;
Willy Tarreau32f61e22015-03-18 17:54:59 +010012002
Willy Tarreaucdb53462020-12-02 12:12:00 +010012003 /* enforce strict limits across all threads */
12004 limit = zone->limit;
12005 old = _HA_ATOMIC_LOAD(&zone->allocated);
12006 do {
12007 new = old + nsize - osize;
12008 if (unlikely(nsize && limit && new > limit))
12009 return NULL;
12010 } while (!_HA_ATOMIC_CAS(&zone->allocated, &old, new));
Willy Tarreau32f61e22015-03-18 17:54:59 +010012011
Willy Tarreaua5efdff2021-10-22 16:00:02 +020012012 if (!nsize)
12013 ha_free(&ptr);
12014 else
12015 ptr = realloc(ptr, nsize);
Willy Tarreaucdb53462020-12-02 12:12:00 +010012016
12017 if (unlikely(!ptr && nsize)) // failed
12018 _HA_ATOMIC_SUB(&zone->allocated, nsize - osize);
12019
12020 __ha_barrier_atomic_store();
Willy Tarreau32f61e22015-03-18 17:54:59 +010012021 return ptr;
12022}
12023
Thierry Fournierecb83c22020-11-28 15:49:44 +010012024/* This function can fail with an abort() due to a Lua critical error.
Thierry FOURNIERbabae282015-09-17 11:36:37 +020012025 * We are in the initialisation process of HAProxy, this abort() is
12026 * tolerated.
12027 */
Thierry Fournierecb83c22020-11-28 15:49:44 +010012028lua_State *hlua_init_state(int thread_num)
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +010012029{
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010012030 int i;
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010012031 int idx;
12032 struct sample_fetch *sf;
Thierry FOURNIER594afe72015-03-10 23:58:30 +010012033 struct sample_conv *sc;
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010012034 char *p;
Thierry Fournierfd107a22016-02-19 19:57:23 +010012035 const char *error_msg;
Thierry Fournier4234dbd2020-11-28 13:18:23 +010012036 void **context;
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012037 lua_State *L;
Thierry Fournier59f11be2020-11-29 00:37:41 +010012038 struct prepend_path *pp;
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010012039
Thierry FOURNIER380d0932015-01-23 14:27:52 +010012040 /* Init main lua stack. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012041 L = lua_newstate(hlua_alloc, &hlua_global_allocator);
Thierry FOURNIER380d0932015-01-23 14:27:52 +010012042
Thierry Fournier4234dbd2020-11-28 13:18:23 +010012043 /* Initialise Lua context to NULL */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012044 context = lua_getextraspace(L);
Thierry Fournier4234dbd2020-11-28 13:18:23 +010012045 *context = NULL;
12046
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -080012047 /* From this point, until the end of the initialisation function,
Thierry FOURNIERbabae282015-09-17 11:36:37 +020012048 * the Lua function can fail with an abort. We are in the initialisation
12049 * process of HAProxy, this abort() is tolerated.
12050 */
12051
Thierry Fournier3c539322020-11-28 16:05:05 +010012052 /* Call post initialisation function in safe environment. */
12053 if (setjmp(safe_ljmp_env) != 0) {
12054 lua_atpanic(L, hlua_panic_safe);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012055 if (lua_type(L, -1) == LUA_TSTRING)
12056 error_msg = lua_tostring(L, -1);
Thierry Fournier2f05cc62020-11-28 16:08:02 +010012057 else
12058 error_msg = "critical error";
12059 fprintf(stderr, "Lua init: %s.\n", error_msg);
12060 exit(1);
Thierry Fournier3c539322020-11-28 16:05:05 +010012061 } else {
12062 lua_atpanic(L, hlua_panic_ljmp);
Thierry Fournier2f05cc62020-11-28 16:08:02 +010012063 }
12064
Thierry FOURNIER380d0932015-01-23 14:27:52 +010012065 /* Initialise lua. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012066 luaL_openlibs(L);
Tim Duesterhus541fe1e2020-01-12 13:55:41 +010012067#define HLUA_PREPEND_PATH_TOSTRING1(x) #x
12068#define HLUA_PREPEND_PATH_TOSTRING(x) HLUA_PREPEND_PATH_TOSTRING1(x)
12069#ifdef HLUA_PREPEND_PATH
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012070 hlua_prepend_path(L, "path", HLUA_PREPEND_PATH_TOSTRING(HLUA_PREPEND_PATH));
Tim Duesterhus541fe1e2020-01-12 13:55:41 +010012071#endif
12072#ifdef HLUA_PREPEND_CPATH
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012073 hlua_prepend_path(L, "cpath", HLUA_PREPEND_PATH_TOSTRING(HLUA_PREPEND_CPATH));
Tim Duesterhus541fe1e2020-01-12 13:55:41 +010012074#endif
12075#undef HLUA_PREPEND_PATH_TOSTRING
12076#undef HLUA_PREPEND_PATH_TOSTRING1
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010012077
Thierry Fournier59f11be2020-11-29 00:37:41 +010012078 /* Apply configured prepend path */
12079 list_for_each_entry(pp, &prepend_path_list, l)
12080 hlua_prepend_path(L, pp->type, pp->path);
12081
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010012082 /*
12083 *
12084 * Create "core" object.
12085 *
12086 */
12087
Thierry FOURNIERa2d8c652015-03-11 17:29:39 +010012088 /* This table entry is the object "core" base. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012089 lua_newtable(L);
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010012090
Thierry Fournierecb83c22020-11-28 15:49:44 +010012091 /* set the thread id */
12092 hlua_class_const_int(L, "thread", thread_num);
12093
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010012094 /* Push the loglevel constants. */
Willy Tarreau80f5fae2015-02-27 16:38:20 +010012095 for (i = 0; i < NB_LOG_LEVELS; i++)
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012096 hlua_class_const_int(L, log_levels[i], i);
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010012097
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010012098 /* Register special functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012099 hlua_class_function(L, "register_init", hlua_register_init);
12100 hlua_class_function(L, "register_task", hlua_register_task);
12101 hlua_class_function(L, "register_fetches", hlua_register_fetches);
12102 hlua_class_function(L, "register_converters", hlua_register_converters);
12103 hlua_class_function(L, "register_action", hlua_register_action);
12104 hlua_class_function(L, "register_service", hlua_register_service);
12105 hlua_class_function(L, "register_cli", hlua_register_cli);
Christopher Faulet69c581a2021-05-31 08:54:04 +020012106 hlua_class_function(L, "register_filter", hlua_register_filter);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012107 hlua_class_function(L, "yield", hlua_yield);
12108 hlua_class_function(L, "set_nice", hlua_set_nice);
12109 hlua_class_function(L, "sleep", hlua_sleep);
12110 hlua_class_function(L, "msleep", hlua_msleep);
12111 hlua_class_function(L, "add_acl", hlua_add_acl);
12112 hlua_class_function(L, "del_acl", hlua_del_acl);
12113 hlua_class_function(L, "set_map", hlua_set_map);
12114 hlua_class_function(L, "del_map", hlua_del_map);
12115 hlua_class_function(L, "tcp", hlua_socket_new);
William Lallemand3956c4e2021-09-21 16:25:15 +020012116 hlua_class_function(L, "httpclient", hlua_httpclient_new);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012117 hlua_class_function(L, "log", hlua_log);
12118 hlua_class_function(L, "Debug", hlua_log_debug);
12119 hlua_class_function(L, "Info", hlua_log_info);
12120 hlua_class_function(L, "Warning", hlua_log_warning);
12121 hlua_class_function(L, "Alert", hlua_log_alert);
12122 hlua_class_function(L, "done", hlua_done);
12123 hlua_fcn_reg_core_fcn(L);
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010012124
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012125 lua_setglobal(L, "core");
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010012126
12127 /*
12128 *
Christopher Faulet0f3c8902020-01-31 18:57:12 +010012129 * Create "act" object.
12130 *
12131 */
12132
12133 /* This table entry is the object "act" base. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012134 lua_newtable(L);
Christopher Faulet0f3c8902020-01-31 18:57:12 +010012135
12136 /* push action return constants */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012137 hlua_class_const_int(L, "CONTINUE", ACT_RET_CONT);
12138 hlua_class_const_int(L, "STOP", ACT_RET_STOP);
12139 hlua_class_const_int(L, "YIELD", ACT_RET_YIELD);
12140 hlua_class_const_int(L, "ERROR", ACT_RET_ERR);
12141 hlua_class_const_int(L, "DONE", ACT_RET_DONE);
12142 hlua_class_const_int(L, "DENY", ACT_RET_DENY);
12143 hlua_class_const_int(L, "ABORT", ACT_RET_ABRT);
12144 hlua_class_const_int(L, "INVALID", ACT_RET_INV);
Christopher Faulet0f3c8902020-01-31 18:57:12 +010012145
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012146 hlua_class_function(L, "wake_time", hlua_set_wake_time);
Christopher Faulet2c2c2e32020-01-31 19:07:52 +010012147
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012148 lua_setglobal(L, "act");
Christopher Faulet0f3c8902020-01-31 18:57:12 +010012149
12150 /*
12151 *
Christopher Faulet69c581a2021-05-31 08:54:04 +020012152 * Create "Filter" object.
12153 *
12154 */
12155
12156 /* This table entry is the object "filter" base. */
12157 lua_newtable(L);
12158
12159 /* push flags and constants */
12160 hlua_class_const_int(L, "CONTINUE", 1);
12161 hlua_class_const_int(L, "WAIT", 0);
12162 hlua_class_const_int(L, "ERROR", -1);
12163
12164 hlua_class_const_int(L, "FLT_CFG_FL_HTX", FLT_CFG_FL_HTX);
12165
Christopher Fauletc404f112020-02-26 15:03:09 +010012166 hlua_class_function(L, "wake_time", hlua_set_wake_time);
12167 hlua_class_function(L, "register_data_filter", hlua_register_data_filter);
12168 hlua_class_function(L, "unregister_data_filter", hlua_unregister_data_filter);
12169
Christopher Faulet69c581a2021-05-31 08:54:04 +020012170 lua_setglobal(L, "filter");
12171
12172 /*
12173 *
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012174 * Register class Map
12175 *
12176 */
12177
12178 /* This table entry is the object "Map" base. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012179 lua_newtable(L);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012180
12181 /* register pattern types. */
12182 for (i=0; i<PAT_MATCH_NUM; i++)
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012183 hlua_class_const_int(L, pat_match_names[i], i);
Thierry FOURNIER4dc71972017-01-28 08:33:08 +010012184 for (i=0; i<PAT_MATCH_NUM; i++) {
Willy Tarreau843b7cb2018-07-13 10:54:26 +020012185 snprintf(trash.area, trash.size, "_%s", pat_match_names[i]);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012186 hlua_class_const_int(L, trash.area, i);
Thierry FOURNIER4dc71972017-01-28 08:33:08 +010012187 }
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012188
12189 /* register constructor. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012190 hlua_class_function(L, "new", hlua_map_new);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012191
12192 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012193 lua_newtable(L);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012194
Ilya Shipitsind4259502020-04-08 01:07:56 +050012195 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012196 lua_pushstring(L, "__index");
12197 lua_newtable(L);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012198
12199 /* Register . */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012200 hlua_class_function(L, "lookup", hlua_map_lookup);
12201 hlua_class_function(L, "slookup", hlua_map_slookup);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012202
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012203 lua_rawset(L, -3);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012204
Thierry Fournier45e78d72016-02-19 18:34:46 +010012205 /* Register previous table in the registry with reference and named entry.
12206 * The function hlua_register_metatable() pops the stack, so we
12207 * previously create a copy of the table.
12208 */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012209 lua_pushvalue(L, -1); /* Copy the -1 entry and push it on the stack. */
12210 class_map_ref = hlua_register_metatable(L, CLASS_MAP);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012211
12212 /* Assign the metatable to the mai Map object. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012213 lua_setmetatable(L, -2);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012214
12215 /* Set a name to the table. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012216 lua_setglobal(L, "Map");
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012217
12218 /*
12219 *
William Lallemand30fcca12022-03-30 12:03:12 +020012220 * Register "CertCache" class
12221 *
12222 */
12223
12224 /* Create and fill the metatable. */
12225 lua_newtable(L);
12226 /* Register */
12227 hlua_class_function(L, "set", hlua_ckch_set);
12228 lua_setglobal(L, CLASS_CERTCACHE); /* Create global object called Regex */
12229
12230 /*
12231 *
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010012232 * Register class Channel
12233 *
12234 */
12235
12236 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012237 lua_newtable(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010012238
Ilya Shipitsind4259502020-04-08 01:07:56 +050012239 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012240 lua_pushstring(L, "__index");
12241 lua_newtable(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010012242
12243 /* Register . */
Christopher Faulet6a79fc12021-08-06 16:02:36 +020012244 hlua_class_function(L, "data", hlua_channel_get_data);
12245 hlua_class_function(L, "line", hlua_channel_get_line);
12246 hlua_class_function(L, "set", hlua_channel_set_data);
12247 hlua_class_function(L, "remove", hlua_channel_del_data);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012248 hlua_class_function(L, "append", hlua_channel_append);
Christopher Faulet6a79fc12021-08-06 16:02:36 +020012249 hlua_class_function(L, "prepend", hlua_channel_prepend);
12250 hlua_class_function(L, "insert", hlua_channel_insert_data);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012251 hlua_class_function(L, "send", hlua_channel_send);
12252 hlua_class_function(L, "forward", hlua_channel_forward);
Christopher Faulet6a79fc12021-08-06 16:02:36 +020012253 hlua_class_function(L, "input", hlua_channel_get_in_len);
12254 hlua_class_function(L, "output", hlua_channel_get_out_len);
12255 hlua_class_function(L, "may_recv", hlua_channel_may_recv);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012256 hlua_class_function(L, "is_full", hlua_channel_is_full);
12257 hlua_class_function(L, "is_resp", hlua_channel_is_resp);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010012258
Christopher Faulet6a79fc12021-08-06 16:02:36 +020012259 /* Deprecated API */
12260 hlua_class_function(L, "get", hlua_channel_get);
12261 hlua_class_function(L, "dup", hlua_channel_dup);
12262 hlua_class_function(L, "getline", hlua_channel_getline);
12263 hlua_class_function(L, "get_in_len", hlua_channel_get_in_len);
12264 hlua_class_function(L, "get_out_len", hlua_channel_get_out_len);
12265
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012266 lua_rawset(L, -3);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010012267
12268 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012269 class_channel_ref = hlua_register_metatable(L, CLASS_CHANNEL);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010012270
12271 /*
12272 *
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010012273 * Register class Fetches
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010012274 *
12275 */
12276
12277 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012278 lua_newtable(L);
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010012279
Ilya Shipitsind4259502020-04-08 01:07:56 +050012280 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012281 lua_pushstring(L, "__index");
12282 lua_newtable(L);
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010012283
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010012284 /* Browse existing fetches and create the associated
12285 * object method.
12286 */
12287 sf = NULL;
12288 while ((sf = sample_fetch_getnext(sf, &idx)) != NULL) {
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010012289 /* gL.Tua doesn't support '.' and '-' in the function names, replace it
12290 * by an underscore.
12291 */
Willy Tarreau5ef96562021-08-26 16:48:53 +020012292 strlcpy2(trash.area, sf->kw, trash.size);
Willy Tarreau843b7cb2018-07-13 10:54:26 +020012293 for (p = trash.area; *p; p++)
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010012294 if (*p == '.' || *p == '-' || *p == '+')
12295 *p = '_';
12296
12297 /* Register the function. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012298 lua_pushstring(L, trash.area);
12299 lua_pushlightuserdata(L, sf);
12300 lua_pushcclosure(L, hlua_run_sample_fetch, 1);
12301 lua_rawset(L, -3);
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010012302 }
12303
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012304 lua_rawset(L, -3);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010012305
12306 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012307 class_fetches_ref = hlua_register_metatable(L, CLASS_FETCHES);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010012308
12309 /*
12310 *
Thierry FOURNIER594afe72015-03-10 23:58:30 +010012311 * Register class Converters
12312 *
12313 */
12314
12315 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012316 lua_newtable(L);
Thierry FOURNIER594afe72015-03-10 23:58:30 +010012317
12318 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012319 lua_pushstring(L, "__index");
12320 lua_newtable(L);
Thierry FOURNIER594afe72015-03-10 23:58:30 +010012321
12322 /* Browse existing converters and create the associated
12323 * object method.
12324 */
12325 sc = NULL;
12326 while ((sc = sample_conv_getnext(sc, &idx)) != NULL) {
Thierry FOURNIER594afe72015-03-10 23:58:30 +010012327 /* gL.Tua doesn't support '.' and '-' in the function names, replace it
12328 * by an underscore.
12329 */
Willy Tarreau5ef96562021-08-26 16:48:53 +020012330 strlcpy2(trash.area, sc->kw, trash.size);
Willy Tarreau843b7cb2018-07-13 10:54:26 +020012331 for (p = trash.area; *p; p++)
Thierry FOURNIER594afe72015-03-10 23:58:30 +010012332 if (*p == '.' || *p == '-' || *p == '+')
12333 *p = '_';
12334
12335 /* Register the function. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012336 lua_pushstring(L, trash.area);
12337 lua_pushlightuserdata(L, sc);
12338 lua_pushcclosure(L, hlua_run_sample_conv, 1);
12339 lua_rawset(L, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +010012340 }
12341
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012342 lua_rawset(L, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +010012343
12344 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012345 class_converters_ref = hlua_register_metatable(L, CLASS_CONVERTERS);
Thierry FOURNIER594afe72015-03-10 23:58:30 +010012346
12347 /*
12348 *
Thierry FOURNIER08504f42015-03-16 14:17:08 +010012349 * Register class HTTP
12350 *
12351 */
12352
12353 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012354 lua_newtable(L);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010012355
Ilya Shipitsind4259502020-04-08 01:07:56 +050012356 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012357 lua_pushstring(L, "__index");
12358 lua_newtable(L);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010012359
12360 /* Register Lua functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012361 hlua_class_function(L, "req_get_headers",hlua_http_req_get_headers);
12362 hlua_class_function(L, "req_del_header", hlua_http_req_del_hdr);
12363 hlua_class_function(L, "req_rep_header", hlua_http_req_rep_hdr);
12364 hlua_class_function(L, "req_rep_value", hlua_http_req_rep_val);
12365 hlua_class_function(L, "req_add_header", hlua_http_req_add_hdr);
12366 hlua_class_function(L, "req_set_header", hlua_http_req_set_hdr);
12367 hlua_class_function(L, "req_set_method", hlua_http_req_set_meth);
12368 hlua_class_function(L, "req_set_path", hlua_http_req_set_path);
12369 hlua_class_function(L, "req_set_query", hlua_http_req_set_query);
12370 hlua_class_function(L, "req_set_uri", hlua_http_req_set_uri);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010012371
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012372 hlua_class_function(L, "res_get_headers",hlua_http_res_get_headers);
12373 hlua_class_function(L, "res_del_header", hlua_http_res_del_hdr);
12374 hlua_class_function(L, "res_rep_header", hlua_http_res_rep_hdr);
12375 hlua_class_function(L, "res_rep_value", hlua_http_res_rep_val);
12376 hlua_class_function(L, "res_add_header", hlua_http_res_add_hdr);
12377 hlua_class_function(L, "res_set_header", hlua_http_res_set_hdr);
12378 hlua_class_function(L, "res_set_status", hlua_http_res_set_status);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010012379
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012380 lua_rawset(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010012381
12382 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012383 class_http_ref = hlua_register_metatable(L, CLASS_HTTP);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010012384
Christopher Fauletdf97ac42020-02-26 16:57:19 +010012385 /*
12386 *
12387 * Register class HTTPMessage
12388 *
12389 */
12390
12391 /* Create and fill the metatable. */
12392 lua_newtable(L);
12393
Ilya Shipitsinff0f2782021-08-22 22:18:07 +050012394 /* Create and fill the __index entry. */
Christopher Fauletdf97ac42020-02-26 16:57:19 +010012395 lua_pushstring(L, "__index");
12396 lua_newtable(L);
12397
12398 /* Register Lua functions. */
12399 hlua_class_function(L, "is_resp", hlua_http_msg_is_resp);
12400 hlua_class_function(L, "get_stline", hlua_http_msg_get_stline);
12401 hlua_class_function(L, "get_headers", hlua_http_msg_get_headers);
12402 hlua_class_function(L, "del_header", hlua_http_msg_del_hdr);
12403 hlua_class_function(L, "rep_header", hlua_http_msg_rep_hdr);
12404 hlua_class_function(L, "rep_value", hlua_http_msg_rep_val);
12405 hlua_class_function(L, "add_header", hlua_http_msg_add_hdr);
12406 hlua_class_function(L, "set_header", hlua_http_msg_set_hdr);
12407 hlua_class_function(L, "set_method", hlua_http_msg_set_meth);
12408 hlua_class_function(L, "set_path", hlua_http_msg_set_path);
12409 hlua_class_function(L, "set_query", hlua_http_msg_set_query);
12410 hlua_class_function(L, "set_uri", hlua_http_msg_set_uri);
12411 hlua_class_function(L, "set_status", hlua_http_msg_set_status);
12412 hlua_class_function(L, "is_full", hlua_http_msg_is_full);
12413 hlua_class_function(L, "may_recv", hlua_http_msg_may_recv);
12414 hlua_class_function(L, "eom", hlua_http_msg_is_eom);
12415 hlua_class_function(L, "input", hlua_http_msg_get_in_len);
12416 hlua_class_function(L, "output", hlua_http_msg_get_out_len);
12417
12418 hlua_class_function(L, "body", hlua_http_msg_get_body);
12419 hlua_class_function(L, "set", hlua_http_msg_set_data);
12420 hlua_class_function(L, "remove", hlua_http_msg_del_data);
12421 hlua_class_function(L, "append", hlua_http_msg_append);
12422 hlua_class_function(L, "prepend", hlua_http_msg_prepend);
12423 hlua_class_function(L, "insert", hlua_http_msg_insert_data);
12424 hlua_class_function(L, "set_eom", hlua_http_msg_set_eom);
12425 hlua_class_function(L, "unset_eom", hlua_http_msg_unset_eom);
12426
12427 hlua_class_function(L, "send", hlua_http_msg_send);
12428 hlua_class_function(L, "forward", hlua_http_msg_forward);
12429
12430 lua_rawset(L, -3);
12431
12432 /* Register previous table in the registry with reference and named entry. */
12433 class_http_msg_ref = hlua_register_metatable(L, CLASS_HTTP_MSG);
William Lallemand3956c4e2021-09-21 16:25:15 +020012434
12435 /*
12436 *
12437 * Register class HTTPClient
12438 *
12439 */
12440
12441 /* Create and fill the metatable. */
12442 lua_newtable(L);
12443 lua_pushstring(L, "__index");
12444 lua_newtable(L);
12445 hlua_class_function(L, "get", hlua_httpclient_get);
William Lallemanddc2cc902021-10-26 11:43:26 +020012446 hlua_class_function(L, "head", hlua_httpclient_head);
12447 hlua_class_function(L, "put", hlua_httpclient_put);
12448 hlua_class_function(L, "post", hlua_httpclient_post);
12449 hlua_class_function(L, "delete", hlua_httpclient_delete);
William Lallemand3956c4e2021-09-21 16:25:15 +020012450 lua_settable(L, -3); /* Sets the __index entry. */
William Lallemandf77f1de2021-09-28 19:10:38 +020012451 /* Register the garbage collector entry. */
12452 lua_pushstring(L, "__gc");
12453 lua_pushcclosure(L, hlua_httpclient_gc, 0);
12454 lua_settable(L, -3); /* Push the last 2 entries in the table at index -3 */
12455
William Lallemand3956c4e2021-09-21 16:25:15 +020012456
12457
12458 class_httpclient_ref = hlua_register_metatable(L, CLASS_HTTPCLIENT);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010012459 /*
12460 *
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020012461 * Register class AppletTCP
12462 *
12463 */
12464
12465 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012466 lua_newtable(L);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020012467
Ilya Shipitsind4259502020-04-08 01:07:56 +050012468 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012469 lua_pushstring(L, "__index");
12470 lua_newtable(L);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020012471
12472 /* Register Lua functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012473 hlua_class_function(L, "getline", hlua_applet_tcp_getline);
12474 hlua_class_function(L, "receive", hlua_applet_tcp_recv);
12475 hlua_class_function(L, "send", hlua_applet_tcp_send);
12476 hlua_class_function(L, "set_priv", hlua_applet_tcp_set_priv);
12477 hlua_class_function(L, "get_priv", hlua_applet_tcp_get_priv);
12478 hlua_class_function(L, "set_var", hlua_applet_tcp_set_var);
12479 hlua_class_function(L, "unset_var", hlua_applet_tcp_unset_var);
12480 hlua_class_function(L, "get_var", hlua_applet_tcp_get_var);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020012481
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012482 lua_settable(L, -3);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020012483
12484 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012485 class_applet_tcp_ref = hlua_register_metatable(L, CLASS_APPLET_TCP);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020012486
12487 /*
12488 *
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020012489 * Register class AppletHTTP
12490 *
12491 */
12492
12493 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012494 lua_newtable(L);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020012495
Ilya Shipitsind4259502020-04-08 01:07:56 +050012496 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012497 lua_pushstring(L, "__index");
12498 lua_newtable(L);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020012499
12500 /* Register Lua functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012501 hlua_class_function(L, "set_priv", hlua_applet_http_set_priv);
12502 hlua_class_function(L, "get_priv", hlua_applet_http_get_priv);
12503 hlua_class_function(L, "set_var", hlua_applet_http_set_var);
12504 hlua_class_function(L, "unset_var", hlua_applet_http_unset_var);
12505 hlua_class_function(L, "get_var", hlua_applet_http_get_var);
12506 hlua_class_function(L, "getline", hlua_applet_http_getline);
12507 hlua_class_function(L, "receive", hlua_applet_http_recv);
12508 hlua_class_function(L, "send", hlua_applet_http_send);
12509 hlua_class_function(L, "add_header", hlua_applet_http_addheader);
12510 hlua_class_function(L, "set_status", hlua_applet_http_status);
12511 hlua_class_function(L, "start_response", hlua_applet_http_start_response);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020012512
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012513 lua_settable(L, -3);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020012514
12515 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012516 class_applet_http_ref = hlua_register_metatable(L, CLASS_APPLET_HTTP);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020012517
12518 /*
12519 *
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010012520 * Register class TXN
12521 *
12522 */
12523
12524 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012525 lua_newtable(L);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010012526
Ilya Shipitsind4259502020-04-08 01:07:56 +050012527 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012528 lua_pushstring(L, "__index");
12529 lua_newtable(L);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010012530
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +010012531 /* Register Lua functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012532 hlua_class_function(L, "set_priv", hlua_set_priv);
12533 hlua_class_function(L, "get_priv", hlua_get_priv);
12534 hlua_class_function(L, "set_var", hlua_set_var);
12535 hlua_class_function(L, "unset_var", hlua_unset_var);
12536 hlua_class_function(L, "get_var", hlua_get_var);
12537 hlua_class_function(L, "done", hlua_txn_done);
12538 hlua_class_function(L, "reply", hlua_txn_reply_new);
12539 hlua_class_function(L, "set_loglevel", hlua_txn_set_loglevel);
12540 hlua_class_function(L, "set_tos", hlua_txn_set_tos);
12541 hlua_class_function(L, "set_mark", hlua_txn_set_mark);
12542 hlua_class_function(L, "set_priority_class", hlua_txn_set_priority_class);
12543 hlua_class_function(L, "set_priority_offset", hlua_txn_set_priority_offset);
12544 hlua_class_function(L, "deflog", hlua_txn_deflog);
12545 hlua_class_function(L, "log", hlua_txn_log);
12546 hlua_class_function(L, "Debug", hlua_txn_log_debug);
12547 hlua_class_function(L, "Info", hlua_txn_log_info);
12548 hlua_class_function(L, "Warning", hlua_txn_log_warning);
12549 hlua_class_function(L, "Alert", hlua_txn_log_alert);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +010012550
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012551 lua_rawset(L, -3);
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010012552
12553 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012554 class_txn_ref = hlua_register_metatable(L, CLASS_TXN);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012555
12556 /*
12557 *
Christopher Faulet700d9e82020-01-31 12:21:52 +010012558 * Register class reply
12559 *
12560 */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012561 lua_newtable(L);
12562 lua_pushstring(L, "__index");
12563 lua_newtable(L);
12564 hlua_class_function(L, "set_status", hlua_txn_reply_set_status);
12565 hlua_class_function(L, "add_header", hlua_txn_reply_add_header);
12566 hlua_class_function(L, "del_header", hlua_txn_reply_del_header);
12567 hlua_class_function(L, "set_body", hlua_txn_reply_set_body);
12568 lua_settable(L, -3); /* Sets the __index entry. */
12569 class_txn_reply_ref = luaL_ref(L, LUA_REGISTRYINDEX);
Christopher Faulet700d9e82020-01-31 12:21:52 +010012570
12571
12572 /*
12573 *
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012574 * Register class Socket
12575 *
12576 */
12577
12578 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012579 lua_newtable(L);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012580
Ilya Shipitsind4259502020-04-08 01:07:56 +050012581 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012582 lua_pushstring(L, "__index");
12583 lua_newtable(L);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012584
Baptiste Assmann84bb4932015-03-02 21:40:06 +010012585#ifdef USE_OPENSSL
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012586 hlua_class_function(L, "connect_ssl", hlua_socket_connect_ssl);
Baptiste Assmann84bb4932015-03-02 21:40:06 +010012587#endif
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012588 hlua_class_function(L, "connect", hlua_socket_connect);
12589 hlua_class_function(L, "send", hlua_socket_send);
12590 hlua_class_function(L, "receive", hlua_socket_receive);
12591 hlua_class_function(L, "close", hlua_socket_close);
12592 hlua_class_function(L, "getpeername", hlua_socket_getpeername);
12593 hlua_class_function(L, "getsockname", hlua_socket_getsockname);
12594 hlua_class_function(L, "setoption", hlua_socket_setoption);
12595 hlua_class_function(L, "settimeout", hlua_socket_settimeout);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012596
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012597 lua_rawset(L, -3); /* Push the last 2 entries in the table at index -3 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012598
12599 /* Register the garbage collector entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012600 lua_pushstring(L, "__gc");
12601 lua_pushcclosure(L, hlua_socket_gc, 0);
12602 lua_rawset(L, -3); /* Push the last 2 entries in the table at index -3 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012603
12604 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012605 class_socket_ref = hlua_register_metatable(L, CLASS_SOCKET);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012606
Thierry Fournieraafc7772020-12-04 11:47:47 +010012607 lua_atpanic(L, hlua_panic_safe);
12608
12609 return L;
12610}
12611
12612void hlua_init(void) {
12613 int i;
Amaury Denoyelle239fdbf2021-03-24 10:22:03 +010012614 char *errmsg;
Thierry Fournieraafc7772020-12-04 11:47:47 +010012615#ifdef USE_OPENSSL
12616 struct srv_kw *kw;
12617 int tmp_error;
12618 char *error;
12619 char *args[] = { /* SSL client configuration. */
12620 "ssl",
12621 "verify",
12622 "none",
12623 NULL
12624 };
12625#endif
12626
12627 /* Init post init function list head */
12628 for (i = 0; i < MAX_THREADS + 1; i++)
12629 LIST_INIT(&hlua_init_functions[i]);
12630
12631 /* Init state for common/shared lua parts */
12632 hlua_state_id = 0;
Willy Tarreau43ab05b2021-09-28 09:43:11 +020012633 ha_set_thread(NULL);
Thierry Fournieraafc7772020-12-04 11:47:47 +010012634 hlua_states[0] = hlua_init_state(0);
12635
12636 /* Init state 1 for thread 0. We have at least one thread. */
12637 hlua_state_id = 1;
Willy Tarreau43ab05b2021-09-28 09:43:11 +020012638 ha_set_thread(NULL);
Thierry Fournieraafc7772020-12-04 11:47:47 +010012639 hlua_states[1] = hlua_init_state(1);
12640
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012641 /* Proxy and server configuration initialisation. */
William Lallemand6bb77b92021-07-28 15:48:16 +020012642 socket_proxy = alloc_new_proxy("LUA-SOCKET", PR_CAP_FE|PR_CAP_BE|PR_CAP_INT, &errmsg);
Amaury Denoyelle239fdbf2021-03-24 10:22:03 +010012643 if (!socket_proxy) {
12644 fprintf(stderr, "Lua init: %s\n", errmsg);
12645 exit(1);
12646 }
12647 proxy_preset_defaults(socket_proxy);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012648
12649 /* Init TCP server: unchanged parameters */
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010012650 socket_tcp = new_server(socket_proxy);
12651 if (!socket_tcp) {
12652 fprintf(stderr, "Lua init: failed to allocate tcp server socket\n");
12653 exit(1);
12654 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012655
12656#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012657 /* Init TCP server: unchanged parameters */
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010012658 socket_ssl = new_server(socket_proxy);
12659 if (!socket_ssl) {
12660 fprintf(stderr, "Lua init: failed to allocate ssl server socket\n");
12661 exit(1);
12662 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012663
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010012664 socket_ssl->use_ssl = 1;
12665 socket_ssl->xprt = xprt_get(XPRT_SSL);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012666
Bertrand Jacquin80839ff2021-01-21 19:14:46 +000012667 for (i = 0; args[i] != NULL; i++) {
12668 if ((kw = srv_find_kw(args[i])) != NULL) { /* Maybe it's registered server keyword */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012669 /*
12670 *
12671 * If the keyword is not known, we can search in the registered
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -080012672 * server keywords. This is useful to configure special SSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012673 * features like client certificates and ssl_verify.
12674 *
12675 */
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010012676 tmp_error = kw->parse(args, &i, socket_proxy, socket_ssl, &error);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012677 if (tmp_error != 0) {
12678 fprintf(stderr, "INTERNAL ERROR: %s\n", error);
12679 abort(); /* This must be never arrives because the command line
12680 not editable by the user. */
12681 }
Bertrand Jacquin80839ff2021-01-21 19:14:46 +000012682 i += kw->skip;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012683 }
12684 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012685#endif
Thierry Fournier75933d42016-01-21 09:30:18 +010012686
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +010012687}
Willy Tarreaubb57d942016-12-21 19:04:56 +010012688
Tim Duesterhusd0c0ca22020-07-04 11:53:26 +020012689static void hlua_deinit()
12690{
Willy Tarreau186f3762020-12-04 11:48:12 +010012691 int thr;
Christopher Faulet69c581a2021-05-31 08:54:04 +020012692 struct hlua_reg_filter *reg_flt, *reg_flt_bck;
12693
12694 list_for_each_entry_safe(reg_flt, reg_flt_bck, &referenced_filters, l)
12695 release_hlua_reg_filter(reg_flt);
Willy Tarreau186f3762020-12-04 11:48:12 +010012696
12697 for (thr = 0; thr < MAX_THREADS+1; thr++) {
12698 if (hlua_states[thr])
12699 lua_close(hlua_states[thr]);
12700 }
Willy Tarreau430bf4a2021-03-04 09:45:32 +010012701
Amaury Denoyellebc2ebfa2021-08-25 15:34:53 +020012702 srv_drop(socket_tcp);
Willy Tarreau430bf4a2021-03-04 09:45:32 +010012703
Willy Tarreau0f143af2021-03-05 10:41:48 +010012704#ifdef USE_OPENSSL
Amaury Denoyellebc2ebfa2021-08-25 15:34:53 +020012705 srv_drop(socket_ssl);
Willy Tarreau0f143af2021-03-05 10:41:48 +010012706#endif
Amaury Denoyelle239fdbf2021-03-24 10:22:03 +010012707
12708 free_proxy(socket_proxy);
Tim Duesterhusd0c0ca22020-07-04 11:53:26 +020012709}
12710
12711REGISTER_POST_DEINIT(hlua_deinit);
12712
Willy Tarreau80713382018-11-26 10:19:54 +010012713static void hlua_register_build_options(void)
12714{
Willy Tarreaubb57d942016-12-21 19:04:56 +010012715 char *ptr = NULL;
Willy Tarreau80713382018-11-26 10:19:54 +010012716
Willy Tarreaubb57d942016-12-21 19:04:56 +010012717 memprintf(&ptr, "Built with Lua version : %s", LUA_RELEASE);
12718 hap_register_build_opts(ptr, 1);
12719}
Willy Tarreau80713382018-11-26 10:19:54 +010012720
12721INITCALL0(STG_REGISTER, hlua_register_build_options);