blob: 29843f4e7f2f209cb7c390266a77618e33c7de86 [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 */
148static char **per_thread_load = NULL;
149
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:
863 argp[idx].data.prx = p;
864 argp[idx].type = ARGT_TAB;
865 argp[idx+1].type = ARGT_STOP;
866 break;
867
868 default:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200869 msg = "Mandatory argument expected";
870 goto error;
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100871 break;
872 }
873 }
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200874 break;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100875 }
876
Ilya Shipitsin856aabc2020-04-16 23:51:34 +0500877 /* Check for exceed the number of required argument. */
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100878 if ((mask & ARGT_MASK) == ARGT_STOP &&
879 argp[idx].type != ARGT_STOP) {
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200880 msg = "Last argument expected";
881 goto error;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100882 }
883
884 if ((mask & ARGT_MASK) == ARGT_STOP &&
885 argp[idx].type == ARGT_STOP) {
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200886 break;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100887 }
888
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200889 /* Convert some argument types. All string in argp[] are for not
890 * duplicated yet.
891 */
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100892 switch (mask & ARGT_MASK) {
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100893 case ARGT_SINT:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200894 if (argp[idx].type != ARGT_SINT) {
895 msg = "integer expected";
896 goto error;
897 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100898 argp[idx].type = ARGT_SINT;
899 break;
900
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100901 case ARGT_TIME:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200902 if (argp[idx].type != ARGT_SINT) {
903 msg = "integer expected";
904 goto error;
905 }
Thierry FOURNIER29176f32015-07-07 00:41:29 +0200906 argp[idx].type = ARGT_TIME;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100907 break;
908
909 case ARGT_SIZE:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200910 if (argp[idx].type != ARGT_SINT) {
911 msg = "integer expected";
912 goto error;
913 }
Thierry FOURNIER29176f32015-07-07 00:41:29 +0200914 argp[idx].type = ARGT_SIZE;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100915 break;
916
917 case ARGT_FE:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200918 if (argp[idx].type != ARGT_STR) {
919 msg = "string expected";
920 goto error;
921 }
Christopher Fauletfdea1b62020-08-06 08:29:18 +0200922 argp[idx].data.prx = proxy_fe_by_name(argp[idx].data.str.area);
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200923 if (!argp[idx].data.prx) {
924 msg = "frontend doesn't exist";
925 goto error;
926 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100927 argp[idx].type = ARGT_FE;
928 break;
929
930 case ARGT_BE:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200931 if (argp[idx].type != ARGT_STR) {
932 msg = "string expected";
933 goto error;
934 }
Christopher Fauletfdea1b62020-08-06 08:29:18 +0200935 argp[idx].data.prx = proxy_be_by_name(argp[idx].data.str.area);
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200936 if (!argp[idx].data.prx) {
937 msg = "backend doesn't exist";
938 goto error;
939 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100940 argp[idx].type = ARGT_BE;
941 break;
942
943 case ARGT_TAB:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200944 if (argp[idx].type != ARGT_STR) {
945 msg = "string expected";
946 goto error;
947 }
Christopher Fauletfdea1b62020-08-06 08:29:18 +0200948 argp[idx].data.t = stktable_find_by_name(argp[idx].data.str.area);
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200949 if (!argp[idx].data.t) {
950 msg = "table doesn't exist";
951 goto error;
952 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100953 argp[idx].type = ARGT_TAB;
954 break;
955
956 case ARGT_SRV:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200957 if (argp[idx].type != ARGT_STR) {
958 msg = "string expected";
959 goto error;
960 }
Christopher Fauletfdea1b62020-08-06 08:29:18 +0200961 sname = strrchr(argp[idx].data.str.area, '/');
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100962 if (sname) {
963 *sname++ = '\0';
Christopher Fauletfdea1b62020-08-06 08:29:18 +0200964 pname = argp[idx].data.str.area;
Willy Tarreau9e0bb102015-05-26 11:24:42 +0200965 px = proxy_be_by_name(pname);
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200966 if (!px) {
967 msg = "backend doesn't exist";
968 goto error;
969 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100970 }
971 else {
Christopher Fauletfdea1b62020-08-06 08:29:18 +0200972 sname = argp[idx].data.str.area;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100973 px = p;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100974 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100975 argp[idx].data.srv = findserver(px, sname);
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200976 if (!argp[idx].data.srv) {
977 msg = "server doesn't exist";
978 goto error;
979 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100980 argp[idx].type = ARGT_SRV;
981 break;
982
983 case ARGT_IPV4:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200984 if (argp[idx].type != ARGT_STR) {
985 msg = "string expected";
986 goto error;
987 }
988 if (inet_pton(AF_INET, argp[idx].data.str.area, &argp[idx].data.ipv4)) {
989 msg = "invalid IPv4 address";
990 goto error;
991 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100992 argp[idx].type = ARGT_IPV4;
993 break;
994
995 case ARGT_MSK4:
Christopher Faulete663a6e2020-08-07 09:11:22 +0200996 if (argp[idx].type == ARGT_SINT)
997 len2mask4(argp[idx].data.sint, &argp[idx].data.ipv4);
998 else if (argp[idx].type == ARGT_STR) {
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200999 if (!str2mask(argp[idx].data.str.area, &argp[idx].data.ipv4)) {
1000 msg = "invalid IPv4 mask";
1001 goto error;
1002 }
1003 }
1004 else {
1005 msg = "integer or string expected";
1006 goto error;
Christopher Faulete663a6e2020-08-07 09:11:22 +02001007 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001008 argp[idx].type = ARGT_MSK4;
1009 break;
1010
1011 case ARGT_IPV6:
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001012 if (argp[idx].type != ARGT_STR) {
1013 msg = "string expected";
1014 goto error;
1015 }
1016 if (inet_pton(AF_INET6, argp[idx].data.str.area, &argp[idx].data.ipv6)) {
1017 msg = "invalid IPv6 address";
1018 goto error;
1019 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001020 argp[idx].type = ARGT_IPV6;
1021 break;
1022
1023 case ARGT_MSK6:
Christopher Faulete663a6e2020-08-07 09:11:22 +02001024 if (argp[idx].type == ARGT_SINT)
1025 len2mask6(argp[idx].data.sint, &argp[idx].data.ipv6);
1026 else if (argp[idx].type == ARGT_STR) {
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001027 if (!str2mask6(argp[idx].data.str.area, &argp[idx].data.ipv6)) {
1028 msg = "invalid IPv6 mask";
1029 goto error;
1030 }
1031 }
1032 else {
1033 msg = "integer or string expected";
1034 goto error;
Christopher Faulete663a6e2020-08-07 09:11:22 +02001035 }
Tim Duesterhusb814da62018-01-25 16:24:50 +01001036 argp[idx].type = ARGT_MSK6;
1037 break;
1038
Christopher Fauletfd2e9062020-08-06 11:10:57 +02001039 case ARGT_REG:
1040 if (argp[idx].type != ARGT_STR) {
1041 msg = "string expected";
1042 goto error;
1043 }
1044 reg = regex_comp(argp[idx].data.str.area, !(argp[idx].type_flags & ARGF_REG_ICASE), 1, &err);
1045 if (!reg) {
1046 msg = lua_pushfstring(L, "error compiling regex '%s' : '%s'",
1047 argp[idx].data.str.area, err);
1048 free(err);
1049 goto error;
1050 }
1051 argp[idx].type = ARGT_REG;
1052 argp[idx].data.reg = reg;
1053 break;
1054
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001055 case ARGT_USR:
Christopher Fauletd25d9262020-08-06 11:04:46 +02001056 if (argp[idx].type != ARGT_STR) {
1057 msg = "string expected";
1058 goto error;
1059 }
1060 if (p->uri_auth && p->uri_auth->userlist &&
Tim Duesterhuse5ff1412021-01-02 22:31:53 +01001061 strcmp(p->uri_auth->userlist->name, argp[idx].data.str.area) == 0)
Christopher Fauletd25d9262020-08-06 11:04:46 +02001062 ul = p->uri_auth->userlist;
1063 else
1064 ul = auth_find_userlist(argp[idx].data.str.area);
1065
1066 if (!ul) {
1067 msg = lua_pushfstring(L, "unable to find userlist '%s'", argp[idx].data.str.area);
1068 goto error;
1069 }
1070 argp[idx].type = ARGT_USR;
1071 argp[idx].data.usr = ul;
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001072 break;
1073
1074 case ARGT_STR:
1075 if (!chunk_dup(&tmp, &argp[idx].data.str)) {
1076 msg = "unable to duplicate string arg";
1077 goto error;
1078 }
1079 argp[idx].data.str = tmp;
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001080 break;
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001081
Christopher Fauletd25d9262020-08-06 11:04:46 +02001082 case ARGT_MAP:
Christopher Fauletd25d9262020-08-06 11:04:46 +02001083 msg = "type not yet supported";
1084 goto error;
1085 break;
1086
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001087 }
1088
1089 /* Check for type of argument. */
1090 if ((mask & ARGT_MASK) != argp[idx].type) {
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001091 msg = lua_pushfstring(L, "'%s' expected, got '%s'",
1092 arg_type_names[(mask & ARGT_MASK)],
1093 arg_type_names[argp[idx].type & ARGT_MASK]);
1094 goto error;
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001095 }
1096
1097 /* Next argument. */
1098 mask >>= ARGT_BITS;
1099 idx++;
1100 }
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001101 return 0;
1102
1103 error:
Willy Tarreauee0d7272021-07-16 10:26:56 +02001104 free_args(argp);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001105 WILL_LJMP(luaL_argerror(L, first + idx, msg));
1106 return 0; /* Never reached */
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001107}
1108
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001109/*
Ilya Shipitsinc02a23f2020-05-06 00:53:22 +05001110 * The following functions are used to make correspondence between the the
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001111 * executed lua pointer and the "struct hlua *" that contain the context.
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001112 *
1113 * - hlua_gethlua : return the hlua context associated with an lua_State.
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001114 * - hlua_sethlua : create the association between hlua context and lua_state.
1115 */
1116static inline struct hlua *hlua_gethlua(lua_State *L)
1117{
Thierry FOURNIER38c5fd62015-03-10 02:40:29 +01001118 struct hlua **hlua = lua_getextraspace(L);
1119 return *hlua;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001120}
1121static inline void hlua_sethlua(struct hlua *hlua)
1122{
Thierry FOURNIER38c5fd62015-03-10 02:40:29 +01001123 struct hlua **hlua_store = lua_getextraspace(hlua->T);
1124 *hlua_store = hlua;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001125}
1126
Willy Tarreau0b7b6392022-06-19 17:39:33 +02001127/* Will return a non-NULL string indicating the Lua call trace if the caller
1128 * currently is executing from within a Lua function. One line per entry will
1129 * be emitted, and each extra line will be prefixed with <pfx>. If a current
1130 * Lua function is not detected, NULL is returned.
1131 */
1132const char *hlua_show_current_location(const char *pfx)
1133{
1134 lua_State *L;
1135 lua_Debug ar;
1136
1137 /* global or per-thread stack initializing ? */
1138 if (hlua_state_id != -1 && (L = hlua_states[hlua_state_id]) && lua_getstack(L, 0, &ar))
1139 return hlua_traceback(L, pfx);
1140
1141 /* per-thread stack running ? */
1142 if (hlua_states[tid + 1] && (L = hlua_states[tid + 1]) && lua_getstack(L, 0, &ar))
1143 return hlua_traceback(L, pfx);
1144
1145 /* global stack running ? */
1146 if (hlua_states[0] && (L = hlua_states[0]) && lua_getstack(L, 0, &ar))
1147 return hlua_traceback(L, pfx);
1148
1149 return NULL;
1150}
1151
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01001152/* This function is used to send logs. It try to send on screen (stderr)
1153 * and on the default syslog server.
1154 */
1155static inline void hlua_sendlog(struct proxy *px, int level, const char *msg)
1156{
1157 struct tm tm;
1158 char *p;
1159
1160 /* Cleanup the log message. */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001161 p = trash.area;
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01001162 for (; *msg != '\0'; msg++, p++) {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001163 if (p >= trash.area + trash.size - 1) {
Thierry FOURNIERccf00632015-09-16 12:47:03 +02001164 /* Break the message if exceed the buffer size. */
1165 *(p-4) = ' ';
1166 *(p-3) = '.';
1167 *(p-2) = '.';
1168 *(p-1) = '.';
1169 break;
1170 }
Willy Tarreau90807112020-02-25 08:16:33 +01001171 if (isprint((unsigned char)*msg))
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01001172 *p = *msg;
1173 else
1174 *p = '.';
1175 }
1176 *p = '\0';
1177
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001178 send_log(px, level, "%s\n", trash.area);
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01001179 if (!(global.mode & MODE_QUIET) || (global.mode & (MODE_VERBOSE | MODE_STARTING))) {
Christopher Fauletf98d8212020-10-02 18:13:52 +02001180 if (level == LOG_DEBUG && !(global.mode & MODE_DEBUG))
1181 return;
1182
Willy Tarreaua678b432015-08-28 10:14:59 +02001183 get_localtime(date.tv_sec, &tm);
1184 fprintf(stderr, "[%s] %03d/%02d%02d%02d (%d) : %s\n",
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01001185 log_levels[level], tm.tm_yday, tm.tm_hour, tm.tm_min, tm.tm_sec,
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001186 (int)getpid(), trash.area);
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01001187 fflush(stderr);
1188 }
1189}
1190
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001191/* This function just ensure that the yield will be always
1192 * returned with a timeout and permit to set some flags
1193 */
1194__LJMP void hlua_yieldk(lua_State *L, int nresults, int ctx,
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001195 lua_KFunction k, int timeout, unsigned int flags)
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001196{
Thierry Fournier4234dbd2020-11-28 13:18:23 +01001197 struct hlua *hlua;
1198
1199 /* Get hlua struct, or NULL if we execute from main lua state */
1200 hlua = hlua_gethlua(L);
1201 if (!hlua) {
1202 return;
1203 }
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001204
1205 /* Set the wake timeout. If timeout is required, we set
1206 * the expiration time.
1207 */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001208 hlua->wake_time = timeout;
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001209
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01001210 hlua->flags |= flags;
1211
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001212 /* Process the yield. */
Willy Tarreau9635e032018-10-16 17:52:55 +02001213 MAY_LJMP(lua_yieldk(L, nresults, ctx, k));
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001214}
1215
Willy Tarreau87b09662015-04-03 00:22:06 +02001216/* This function initialises the Lua environment stored in the stream.
1217 * It must be called at the start of the stream. This function creates
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001218 * an LUA coroutine. It can not be use to crete the main LUA context.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02001219 *
1220 * This function is particular. it initialises a new Lua thread. If the
1221 * initialisation fails (example: out of memory error), the lua function
1222 * throws an error (longjmp).
1223 *
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +01001224 * In some case (at least one), this function can be called from safe
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001225 * environment, so we must not initialise it. While the support of
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +01001226 * threads appear, the safe environment set a lock to ensure only one
1227 * Lua execution at a time. If we initialize safe environment in another
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001228 * safe environment, we have a dead lock.
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +01001229 *
1230 * set "already_safe" true if the context is initialized form safe
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001231 * Lua function.
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +01001232 *
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001233 * This function manipulates two Lua stacks: the main and the thread. Only
Thierry FOURNIERbabae282015-09-17 11:36:37 +02001234 * the main stack can fail. The thread is not manipulated. This function
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001235 * MUST NOT manipulate the created thread stack state, because it is not
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001236 * protected against errors thrown by the thread stack.
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001237 */
Thierry Fournier021d9862020-11-28 23:42:03 +01001238int hlua_ctx_init(struct hlua *lua, int state_id, struct task *task, int already_safe)
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001239{
1240 lua->Mref = LUA_REFNIL;
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001241 lua->flags = 0;
Willy Tarreauf31af932020-01-14 09:59:38 +01001242 lua->gc_count = 0;
Christopher Fauletbc275a92020-02-26 14:55:16 +01001243 lua->wake_time = TICK_ETERNITY;
Thierry Fournier021d9862020-11-28 23:42:03 +01001244 lua->state_id = state_id;
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01001245 LIST_INIT(&lua->com);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001246 if (!already_safe) {
1247 if (!SET_SAFE_LJMP_PARENT(lua)) {
1248 lua->Tref = LUA_REFNIL;
1249 return 0;
1250 }
1251 }
Thierry Fournier021d9862020-11-28 23:42:03 +01001252 lua->T = lua_newthread(hlua_states[state_id]);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001253 if (!lua->T) {
1254 lua->Tref = LUA_REFNIL;
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +01001255 if (!already_safe)
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001256 RESET_SAFE_LJMP_PARENT(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001257 return 0;
1258 }
1259 hlua_sethlua(lua);
Thierry Fournier021d9862020-11-28 23:42:03 +01001260 lua->Tref = luaL_ref(hlua_states[state_id], LUA_REGISTRYINDEX);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001261 lua->task = task;
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +01001262 if (!already_safe)
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001263 RESET_SAFE_LJMP_PARENT(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001264 return 1;
1265}
1266
Willy Tarreau87b09662015-04-03 00:22:06 +02001267/* Used to destroy the Lua coroutine when the attached stream or task
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001268 * is destroyed. The destroy also the memory context. The struct "lua"
1269 * is not freed.
1270 */
1271void hlua_ctx_destroy(struct hlua *lua)
1272{
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01001273 if (!lua)
Thierry FOURNIERa718b292015-03-04 16:48:34 +01001274 return;
1275
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01001276 if (!lua->T)
1277 goto end;
1278
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01001279 /* Purge all the pending signals. */
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001280 notification_purge(&lua->com);
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01001281
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001282 if (!SET_SAFE_LJMP(lua))
Thierry FOURNIER75d02082017-07-12 13:41:33 +02001283 return;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001284 luaL_unref(lua->T, LUA_REGISTRYINDEX, lua->Mref);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001285 RESET_SAFE_LJMP(lua);
Thierry FOURNIER5a50a852015-09-23 16:59:28 +02001286
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001287 if (!SET_SAFE_LJMP_PARENT(lua))
Thierry FOURNIER75d02082017-07-12 13:41:33 +02001288 return;
Thierry Fournier021d9862020-11-28 23:42:03 +01001289 luaL_unref(hlua_states[lua->state_id], LUA_REGISTRYINDEX, lua->Tref);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001290 RESET_SAFE_LJMP_PARENT(lua);
Thierry FOURNIER5a50a852015-09-23 16:59:28 +02001291 /* Forces a garbage collecting process. If the Lua program is finished
1292 * without error, we run the GC on the thread pointer. Its freed all
1293 * the unused memory.
1294 * If the thread is finnish with an error or is currently yielded,
1295 * it seems that the GC applied on the thread doesn't clean anything,
1296 * so e run the GC on the main thread.
1297 * NOTE: maybe this action locks all the Lua threads untiml the en of
1298 * the garbage collection.
1299 */
Willy Tarreauf31af932020-01-14 09:59:38 +01001300 if (lua->gc_count) {
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001301 if (!SET_SAFE_LJMP_PARENT(lua))
Thierry FOURNIER75d02082017-07-12 13:41:33 +02001302 return;
Thierry Fournier021d9862020-11-28 23:42:03 +01001303 lua_gc(hlua_states[lua->state_id], LUA_GCCOLLECT, 0);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001304 RESET_SAFE_LJMP_PARENT(lua);
Thierry FOURNIER7c39ab42015-09-27 22:53:33 +02001305 }
Thierry FOURNIER5a50a852015-09-23 16:59:28 +02001306
Thierry FOURNIERa7b536b2015-09-21 22:50:24 +02001307 lua->T = NULL;
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01001308
1309end:
Willy Tarreaubafbe012017-11-24 17:34:44 +01001310 pool_free(pool_head_hlua, lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001311}
1312
1313/* This function is used to restore the Lua context when a coroutine
1314 * fails. This function copy the common memory between old coroutine
1315 * and the new coroutine. The old coroutine is destroyed, and its
1316 * replaced by the new coroutine.
1317 * If the flag "keep_msg" is set, the last entry of the old is assumed
1318 * as string error message and it is copied in the new stack.
1319 */
1320static int hlua_ctx_renew(struct hlua *lua, int keep_msg)
1321{
1322 lua_State *T;
1323 int new_ref;
1324
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001325 /* New Lua coroutine. */
Thierry Fournier021d9862020-11-28 23:42:03 +01001326 T = lua_newthread(hlua_states[lua->state_id]);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001327 if (!T)
1328 return 0;
1329
1330 /* Copy last error message. */
1331 if (keep_msg)
1332 lua_xmove(lua->T, T, 1);
1333
1334 /* Copy data between the coroutines. */
1335 lua_rawgeti(lua->T, LUA_REGISTRYINDEX, lua->Mref);
1336 lua_xmove(lua->T, T, 1);
Ilya Shipitsin46a030c2020-07-05 16:36:08 +05001337 new_ref = luaL_ref(T, LUA_REGISTRYINDEX); /* Value popped. */
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001338
1339 /* Destroy old data. */
1340 luaL_unref(lua->T, LUA_REGISTRYINDEX, lua->Mref);
1341
1342 /* The thread is garbage collected by Lua. */
Thierry Fournier021d9862020-11-28 23:42:03 +01001343 luaL_unref(hlua_states[lua->state_id], LUA_REGISTRYINDEX, lua->Tref);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001344
1345 /* Fill the struct with the new coroutine values. */
1346 lua->Mref = new_ref;
1347 lua->T = T;
Thierry Fournier021d9862020-11-28 23:42:03 +01001348 lua->Tref = luaL_ref(hlua_states[lua->state_id], LUA_REGISTRYINDEX);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001349
1350 /* Set context. */
1351 hlua_sethlua(lua);
1352
1353 return 1;
1354}
1355
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001356void hlua_hook(lua_State *L, lua_Debug *ar)
1357{
Thierry Fournier4234dbd2020-11-28 13:18:23 +01001358 struct hlua *hlua;
1359
1360 /* Get hlua struct, or NULL if we execute from main lua state */
1361 hlua = hlua_gethlua(L);
1362 if (!hlua)
1363 return;
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001364
1365 /* Lua cannot yield when its returning from a function,
1366 * so, we can fix the interrupt hook to 1 instruction,
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001367 * expecting that the function is finished.
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001368 */
1369 if (lua_gethookmask(L) & LUA_MASKRET) {
1370 lua_sethook(hlua->T, hlua_hook, LUA_MASKCOUNT, 1);
1371 return;
1372 }
1373
1374 /* restore the interrupt condition. */
1375 lua_sethook(hlua->T, hlua_hook, LUA_MASKCOUNT, hlua_nb_instruction);
1376
1377 /* If we interrupt the Lua processing in yieldable state, we yield.
1378 * If the state is not yieldable, trying yield causes an error.
1379 */
1380 if (lua_isyieldable(L))
Willy Tarreau9635e032018-10-16 17:52:55 +02001381 MAY_LJMP(hlua_yieldk(L, 0, 0, NULL, TICK_ETERNITY, HLUA_CTRLYIELD));
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001382
Thierry FOURNIERa85cfb12015-03-13 14:50:06 +01001383 /* If we cannot yield, update the clock and check the timeout. */
Willy Tarreau55542642021-10-08 09:33:24 +02001384 clock_update_date(0, 1);
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001385 hlua->run_time += now_ms - hlua->start_time;
1386 if (hlua->max_time && hlua->run_time >= hlua->max_time) {
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001387 lua_pushfstring(L, "execution timeout");
1388 WILL_LJMP(lua_error(L));
1389 }
1390
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001391 /* Update the start time. */
1392 hlua->start_time = now_ms;
1393
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001394 /* Try to interrupt the process at the end of the current
1395 * unyieldable function.
1396 */
1397 lua_sethook(hlua->T, hlua_hook, LUA_MASKRET|LUA_MASKCOUNT, hlua_nb_instruction);
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001398}
1399
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001400/* This function start or resumes the Lua stack execution. If the flag
1401 * "yield_allowed" if no set and the LUA stack execution returns a yield
1402 * The function return an error.
1403 *
1404 * The function can returns 4 values:
1405 * - HLUA_E_OK : The execution is terminated without any errors.
1406 * - HLUA_E_AGAIN : The execution must continue at the next associated
1407 * task wakeup.
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001408 * - HLUA_E_ERRMSG : An error has occurred, an error message is set in
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001409 * the top of the stack.
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001410 * - HLUA_E_ERR : An error has occurred without error message.
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001411 *
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001412 * If an error occurred, the stack is renewed and it is ready to run new
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001413 * LUA code.
1414 */
1415static enum hlua_exec hlua_ctx_resume(struct hlua *lua, int yield_allowed)
1416{
Christopher Faulet08ed98f2020-07-28 10:33:25 +02001417#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM >= 504
1418 int nres;
1419#endif
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001420 int ret;
1421 const char *msg;
Thierry FOURNIERfc044c92018-06-07 14:40:48 +02001422 const char *trace;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001423
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001424 /* Initialise run time counter. */
1425 if (!HLUA_IS_RUNNING(lua))
1426 lua->run_time = 0;
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001427
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +02001428 /* Lock the whole Lua execution. This lock must be before the
1429 * label "resume_execution".
1430 */
Thierry Fournier021d9862020-11-28 23:42:03 +01001431 if (lua->state_id == 0)
Willy Tarreau1e7bef12021-08-20 15:47:25 +02001432 lua_take_global_lock();
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +02001433
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001434resume_execution:
1435
1436 /* This hook interrupts the Lua processing each 'hlua_nb_instruction'
1437 * instructions. it is used for preventing infinite loops.
1438 */
1439 lua_sethook(lua->T, hlua_hook, LUA_MASKCOUNT, hlua_nb_instruction);
1440
Thierry FOURNIER1bfc09b2015-03-05 17:10:14 +01001441 /* Remove all flags except the running flags. */
Thierry FOURNIER2f3867f2015-09-28 01:02:01 +02001442 HLUA_SET_RUN(lua);
1443 HLUA_CLR_CTRLYIELD(lua);
1444 HLUA_CLR_WAKERESWR(lua);
1445 HLUA_CLR_WAKEREQWR(lua);
Christopher Faulet1f43a342021-08-04 17:58:21 +02001446 HLUA_CLR_NOYIELD(lua);
1447 if (!yield_allowed)
1448 HLUA_SET_NOYIELD(lua);
Thierry FOURNIER1bfc09b2015-03-05 17:10:14 +01001449
Christopher Fauletbc275a92020-02-26 14:55:16 +01001450 /* Update the start time and reset wake_time. */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001451 lua->start_time = now_ms;
Christopher Fauletbc275a92020-02-26 14:55:16 +01001452 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001453
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001454 /* Call the function. */
Christopher Faulet08ed98f2020-07-28 10:33:25 +02001455#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM >= 504
Thierry Fournier021d9862020-11-28 23:42:03 +01001456 ret = lua_resume(lua->T, hlua_states[lua->state_id], lua->nargs, &nres);
Christopher Faulet08ed98f2020-07-28 10:33:25 +02001457#else
Thierry Fournier021d9862020-11-28 23:42:03 +01001458 ret = lua_resume(lua->T, hlua_states[lua->state_id], lua->nargs);
Christopher Faulet08ed98f2020-07-28 10:33:25 +02001459#endif
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001460 switch (ret) {
1461
1462 case LUA_OK:
1463 ret = HLUA_E_OK;
1464 break;
1465
1466 case LUA_YIELD:
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001467 /* Check if the execution timeout is expired. It it is the case, we
1468 * break the Lua execution.
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001469 */
Willy Tarreau55542642021-10-08 09:33:24 +02001470 clock_update_date(0, 1);
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001471 lua->run_time += now_ms - lua->start_time;
1472 if (lua->max_time && lua->run_time > lua->max_time) {
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001473 lua_settop(lua->T, 0); /* Empty the stack. */
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001474 ret = HLUA_E_ETMOUT;
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001475 break;
1476 }
1477 /* Process the forced yield. if the general yield is not allowed or
1478 * if no task were associated this the current Lua execution
1479 * coroutine, we resume the execution. Else we want to return in the
1480 * scheduler and we want to be waked up again, to continue the
1481 * current Lua execution. So we schedule our own task.
1482 */
1483 if (HLUA_IS_CTRLYIELDING(lua)) {
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001484 if (!yield_allowed || !lua->task)
1485 goto resume_execution;
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001486 task_wakeup(lua->task, TASK_WOKEN_MSG);
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001487 }
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001488 if (!yield_allowed) {
1489 lua_settop(lua->T, 0); /* Empty the stack. */
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001490 ret = HLUA_E_YIELD;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001491 break;
1492 }
1493 ret = HLUA_E_AGAIN;
1494 break;
1495
1496 case LUA_ERRRUN:
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001497
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001498 /* Special exit case. The traditional exit is returned as an error
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001499 * because the errors ares the only one mean to return immediately
1500 * from and lua execution.
1501 */
1502 if (lua->flags & HLUA_EXIT) {
1503 ret = HLUA_E_OK;
Christopher Faulet7716cdf2020-01-29 11:53:30 +01001504 hlua_ctx_renew(lua, 1);
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001505 break;
1506 }
1507
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001508 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001509 if (!lua_checkstack(lua->T, 1)) {
1510 ret = HLUA_E_ERR;
1511 break;
1512 }
1513 msg = lua_tostring(lua->T, -1);
1514 lua_settop(lua->T, 0); /* Empty the stack. */
1515 lua_pop(lua->T, 1);
Christopher Fauletd09cc512021-03-24 14:48:45 +01001516 trace = hlua_traceback(lua->T, ", ");
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001517 if (msg)
Thierry Fournier46278ff2020-11-29 11:48:12 +01001518 lua_pushfstring(lua->T, "[state-id %d] runtime error: %s from %s", lua->state_id, msg, trace);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001519 else
Thierry Fournier46278ff2020-11-29 11:48:12 +01001520 lua_pushfstring(lua->T, "[state-id %d] unknown runtime error from %s", lua->state_id, trace);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001521 ret = HLUA_E_ERRMSG;
1522 break;
1523
1524 case LUA_ERRMEM:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001525 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001526 lua_settop(lua->T, 0); /* Empty the stack. */
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001527 ret = HLUA_E_NOMEM;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001528 break;
1529
1530 case LUA_ERRERR:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001531 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001532 if (!lua_checkstack(lua->T, 1)) {
1533 ret = HLUA_E_ERR;
1534 break;
1535 }
1536 msg = lua_tostring(lua->T, -1);
1537 lua_settop(lua->T, 0); /* Empty the stack. */
1538 lua_pop(lua->T, 1);
1539 if (msg)
Thierry Fournier46278ff2020-11-29 11:48:12 +01001540 lua_pushfstring(lua->T, "[state-id %d] message handler error: %s", lua->state_id, msg);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001541 else
Thierry Fournier46278ff2020-11-29 11:48:12 +01001542 lua_pushfstring(lua->T, "[state-id %d] message handler error", lua->state_id);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001543 ret = HLUA_E_ERRMSG;
1544 break;
1545
1546 default:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001547 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001548 lua_settop(lua->T, 0); /* Empty the stack. */
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001549 ret = HLUA_E_ERR;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001550 break;
1551 }
1552
1553 switch (ret) {
1554 case HLUA_E_AGAIN:
1555 break;
1556
1557 case HLUA_E_ERRMSG:
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001558 notification_purge(&lua->com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001559 hlua_ctx_renew(lua, 1);
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001560 HLUA_CLR_RUN(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001561 break;
1562
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001563 case HLUA_E_ETMOUT:
1564 case HLUA_E_NOMEM:
1565 case HLUA_E_YIELD:
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001566 case HLUA_E_ERR:
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001567 HLUA_CLR_RUN(lua);
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001568 notification_purge(&lua->com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001569 hlua_ctx_renew(lua, 0);
1570 break;
1571
1572 case HLUA_E_OK:
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001573 HLUA_CLR_RUN(lua);
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001574 notification_purge(&lua->com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001575 break;
1576 }
1577
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +02001578 /* This is the main exit point, remove the Lua lock. */
Thierry Fournier021d9862020-11-28 23:42:03 +01001579 if (lua->state_id == 0)
Willy Tarreau1e7bef12021-08-20 15:47:25 +02001580 lua_drop_global_lock();
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +02001581
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001582 return ret;
1583}
1584
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001585/* This function exit the current code. */
1586__LJMP static int hlua_done(lua_State *L)
1587{
Thierry Fournier4234dbd2020-11-28 13:18:23 +01001588 struct hlua *hlua;
1589
1590 /* Get hlua struct, or NULL if we execute from main lua state */
1591 hlua = hlua_gethlua(L);
1592 if (!hlua)
1593 return 0;
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001594
1595 hlua->flags |= HLUA_EXIT;
1596 WILL_LJMP(lua_error(L));
1597
1598 return 0;
1599}
1600
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001601/* This function is an LUA binding. It provides a function
1602 * for deleting ACL from a referenced ACL file.
1603 */
1604__LJMP static int hlua_del_acl(lua_State *L)
1605{
1606 const char *name;
1607 const char *key;
1608 struct pat_ref *ref;
1609
1610 MAY_LJMP(check_args(L, 2, "del_acl"));
1611
1612 name = MAY_LJMP(luaL_checkstring(L, 1));
1613 key = MAY_LJMP(luaL_checkstring(L, 2));
1614
1615 ref = pat_ref_lookup(name);
1616 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001617 WILL_LJMP(luaL_error(L, "'del_acl': unknown acl file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001618
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001619 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001620 pat_ref_delete(ref, key);
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001621 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001622 return 0;
1623}
1624
1625/* This function is an LUA binding. It provides a function
1626 * for deleting map entry from a referenced map file.
1627 */
1628static int hlua_del_map(lua_State *L)
1629{
1630 const char *name;
1631 const char *key;
1632 struct pat_ref *ref;
1633
1634 MAY_LJMP(check_args(L, 2, "del_map"));
1635
1636 name = MAY_LJMP(luaL_checkstring(L, 1));
1637 key = MAY_LJMP(luaL_checkstring(L, 2));
1638
1639 ref = pat_ref_lookup(name);
1640 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001641 WILL_LJMP(luaL_error(L, "'del_map': unknown acl file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001642
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001643 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001644 pat_ref_delete(ref, key);
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001645 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001646 return 0;
1647}
1648
1649/* This function is an LUA binding. It provides a function
1650 * for adding ACL pattern from a referenced ACL file.
1651 */
1652static int hlua_add_acl(lua_State *L)
1653{
1654 const char *name;
1655 const char *key;
1656 struct pat_ref *ref;
1657
1658 MAY_LJMP(check_args(L, 2, "add_acl"));
1659
1660 name = MAY_LJMP(luaL_checkstring(L, 1));
1661 key = MAY_LJMP(luaL_checkstring(L, 2));
1662
1663 ref = pat_ref_lookup(name);
1664 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001665 WILL_LJMP(luaL_error(L, "'add_acl': unknown acl file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001666
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001667 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001668 if (pat_ref_find_elt(ref, key) == NULL)
1669 pat_ref_add(ref, key, NULL, NULL);
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001670 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001671 return 0;
1672}
1673
1674/* This function is an LUA binding. It provides a function
1675 * for setting map pattern and sample from a referenced map
1676 * file.
1677 */
1678static int hlua_set_map(lua_State *L)
1679{
1680 const char *name;
1681 const char *key;
1682 const char *value;
1683 struct pat_ref *ref;
1684
1685 MAY_LJMP(check_args(L, 3, "set_map"));
1686
1687 name = MAY_LJMP(luaL_checkstring(L, 1));
1688 key = MAY_LJMP(luaL_checkstring(L, 2));
1689 value = MAY_LJMP(luaL_checkstring(L, 3));
1690
1691 ref = pat_ref_lookup(name);
1692 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001693 WILL_LJMP(luaL_error(L, "'set_map': unknown map file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001694
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001695 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001696 if (pat_ref_find_elt(ref, key) != NULL)
1697 pat_ref_set(ref, key, value, NULL);
1698 else
1699 pat_ref_add(ref, key, value, NULL);
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001700 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001701 return 0;
1702}
1703
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01001704/* A class is a lot of memory that contain data. This data can be a table,
1705 * an integer or user data. This data is associated with a metatable. This
Ilya Shipitsinc02a23f2020-05-06 00:53:22 +05001706 * metatable have an original version registered in the global context with
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01001707 * the name of the object (_G[<name>] = <metable> ).
1708 *
1709 * A metable is a table that modify the standard behavior of a standard
1710 * access to the associated data. The entries of this new metatable are
1711 * defined as is:
1712 *
1713 * http://lua-users.org/wiki/MetatableEvents
1714 *
1715 * __index
1716 *
1717 * we access an absent field in a table, the result is nil. This is
1718 * true, but it is not the whole truth. Actually, such access triggers
1719 * the interpreter to look for an __index metamethod: If there is no
1720 * such method, as usually happens, then the access results in nil;
1721 * otherwise, the metamethod will provide the result.
1722 *
1723 * Control 'prototype' inheritance. When accessing "myTable[key]" and
1724 * the key does not appear in the table, but the metatable has an __index
1725 * property:
1726 *
1727 * - if the value is a function, the function is called, passing in the
1728 * table and the key; the return value of that function is returned as
1729 * the result.
1730 *
1731 * - if the value is another table, the value of the key in that table is
1732 * asked for and returned (and if it doesn't exist in that table, but that
1733 * table's metatable has an __index property, then it continues on up)
1734 *
1735 * - Use "rawget(myTable,key)" to skip this metamethod.
1736 *
1737 * http://www.lua.org/pil/13.4.1.html
1738 *
1739 * __newindex
1740 *
1741 * Like __index, but control property assignment.
1742 *
1743 * __mode - Control weak references. A string value with one or both
1744 * of the characters 'k' and 'v' which specifies that the the
1745 * keys and/or values in the table are weak references.
1746 *
1747 * __call - Treat a table like a function. When a table is followed by
1748 * parenthesis such as "myTable( 'foo' )" and the metatable has
1749 * a __call key pointing to a function, that function is invoked
1750 * (passing any specified arguments) and the return value is
1751 * returned.
1752 *
1753 * __metatable - Hide the metatable. When "getmetatable( myTable )" is
1754 * called, if the metatable for myTable has a __metatable
1755 * key, the value of that key is returned instead of the
1756 * actual metatable.
1757 *
1758 * __tostring - Control string representation. When the builtin
1759 * "tostring( myTable )" function is called, if the metatable
1760 * for myTable has a __tostring property set to a function,
1761 * that function is invoked (passing myTable to it) and the
1762 * return value is used as the string representation.
1763 *
1764 * __len - Control table length. When the table length is requested using
1765 * the length operator ( '#' ), if the metatable for myTable has
1766 * a __len key pointing to a function, that function is invoked
1767 * (passing myTable to it) and the return value used as the value
1768 * of "#myTable".
1769 *
1770 * __gc - Userdata finalizer code. When userdata is set to be garbage
1771 * collected, if the metatable has a __gc field pointing to a
1772 * function, that function is first invoked, passing the userdata
1773 * to it. The __gc metamethod is not called for tables.
1774 * (See http://lua-users.org/lists/lua-l/2006-11/msg00508.html)
1775 *
1776 * Special metamethods for redefining standard operators:
1777 * http://www.lua.org/pil/13.1.html
1778 *
1779 * __add "+"
1780 * __sub "-"
1781 * __mul "*"
1782 * __div "/"
1783 * __unm "!"
1784 * __pow "^"
1785 * __concat ".."
1786 *
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001787 * Special methods for redefining standard relations
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01001788 * http://www.lua.org/pil/13.2.html
1789 *
1790 * __eq "=="
1791 * __lt "<"
1792 * __le "<="
1793 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001794
1795/*
1796 *
1797 *
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001798 * Class Map
1799 *
1800 *
1801 */
1802
1803/* Returns a struct hlua_map if the stack entry "ud" is
1804 * a class session, otherwise it throws an error.
1805 */
1806__LJMP static struct map_descriptor *hlua_checkmap(lua_State *L, int ud)
1807{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02001808 return MAY_LJMP(hlua_checkudata(L, ud, class_map_ref));
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001809}
1810
1811/* This function is the map constructor. It don't need
1812 * the class Map object. It creates and return a new Map
1813 * object. It must be called only during "body" or "init"
1814 * context because it process some filesystem accesses.
1815 */
1816__LJMP static int hlua_map_new(struct lua_State *L)
1817{
1818 const char *fn;
1819 int match = PAT_MATCH_STR;
1820 struct sample_conv conv;
1821 const char *file = "";
1822 int line = 0;
1823 lua_Debug ar;
1824 char *err = NULL;
1825 struct arg args[2];
1826
1827 if (lua_gettop(L) < 1 || lua_gettop(L) > 2)
1828 WILL_LJMP(luaL_error(L, "'new' needs at least 1 argument."));
1829
1830 fn = MAY_LJMP(luaL_checkstring(L, 1));
1831
1832 if (lua_gettop(L) >= 2) {
1833 match = MAY_LJMP(luaL_checkinteger(L, 2));
1834 if (match < 0 || match >= PAT_MATCH_NUM)
1835 WILL_LJMP(luaL_error(L, "'new' needs a valid match method."));
1836 }
1837
1838 /* Get Lua filename and line number. */
1839 if (lua_getstack(L, 1, &ar)) { /* check function at level */
1840 lua_getinfo(L, "Sl", &ar); /* get info about it */
1841 if (ar.currentline > 0) { /* is there info? */
1842 file = ar.short_src;
1843 line = ar.currentline;
1844 }
1845 }
1846
1847 /* fill fake sample_conv struct. */
1848 conv.kw = ""; /* unused. */
1849 conv.process = NULL; /* unused. */
1850 conv.arg_mask = 0; /* unused. */
1851 conv.val_args = NULL; /* unused. */
1852 conv.out_type = SMP_T_STR;
1853 conv.private = (void *)(long)match;
1854 switch (match) {
1855 case PAT_MATCH_STR: conv.in_type = SMP_T_STR; break;
1856 case PAT_MATCH_BEG: conv.in_type = SMP_T_STR; break;
1857 case PAT_MATCH_SUB: conv.in_type = SMP_T_STR; break;
1858 case PAT_MATCH_DIR: conv.in_type = SMP_T_STR; break;
1859 case PAT_MATCH_DOM: conv.in_type = SMP_T_STR; break;
1860 case PAT_MATCH_END: conv.in_type = SMP_T_STR; break;
1861 case PAT_MATCH_REG: conv.in_type = SMP_T_STR; break;
Thierry FOURNIER07ee64e2015-07-06 23:43:03 +02001862 case PAT_MATCH_INT: conv.in_type = SMP_T_SINT; break;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001863 case PAT_MATCH_IP: conv.in_type = SMP_T_ADDR; break;
1864 default:
1865 WILL_LJMP(luaL_error(L, "'new' doesn't support this match mode."));
1866 }
1867
1868 /* fill fake args. */
1869 args[0].type = ARGT_STR;
Christopher Faulet73292e92020-08-06 08:40:09 +02001870 args[0].data.str.area = strdup(fn);
1871 args[0].data.str.data = strlen(fn);
1872 args[0].data.str.size = args[0].data.str.data+1;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001873 args[1].type = ARGT_STOP;
1874
1875 /* load the map. */
1876 if (!sample_load_map(args, &conv, file, line, &err)) {
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +05001877 /* error case: we can't use luaL_error because we must
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001878 * free the err variable.
1879 */
1880 luaL_where(L, 1);
1881 lua_pushfstring(L, "'new': %s.", err);
1882 lua_concat(L, 2);
1883 free(err);
Christopher Faulet6ad7df42020-08-07 11:45:18 +02001884 chunk_destroy(&args[0].data.str);
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001885 WILL_LJMP(lua_error(L));
1886 }
1887
1888 /* create the lua object. */
1889 lua_newtable(L);
1890 lua_pushlightuserdata(L, args[0].data.map);
1891 lua_rawseti(L, -2, 0);
1892
1893 /* Pop a class Map metatable and affect it to the userdata. */
1894 lua_rawgeti(L, LUA_REGISTRYINDEX, class_map_ref);
1895 lua_setmetatable(L, -2);
1896
1897
1898 return 1;
1899}
1900
1901__LJMP static inline int _hlua_map_lookup(struct lua_State *L, int str)
1902{
1903 struct map_descriptor *desc;
1904 struct pattern *pat;
1905 struct sample smp;
1906
1907 MAY_LJMP(check_args(L, 2, "lookup"));
1908 desc = MAY_LJMP(hlua_checkmap(L, 1));
Thierry FOURNIER07ee64e2015-07-06 23:43:03 +02001909 if (desc->pat.expect_type == SMP_T_SINT) {
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02001910 smp.data.type = SMP_T_SINT;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +02001911 smp.data.u.sint = MAY_LJMP(luaL_checkinteger(L, 2));
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001912 }
1913 else {
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02001914 smp.data.type = SMP_T_STR;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001915 smp.flags = SMP_F_CONST;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001916 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 +01001917 smp.data.u.str.size = smp.data.u.str.data + 1;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001918 }
1919
1920 pat = pattern_exec_match(&desc->pat, &smp, 1);
Thierry FOURNIER503bb092015-08-19 08:35:43 +02001921 if (!pat || !pat->data) {
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001922 if (str)
1923 lua_pushstring(L, "");
1924 else
1925 lua_pushnil(L);
1926 return 1;
1927 }
1928
1929 /* The Lua pattern must return a string, so we can't check the returned type */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001930 lua_pushlstring(L, pat->data->u.str.area, pat->data->u.str.data);
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001931 return 1;
1932}
1933
1934__LJMP static int hlua_map_lookup(struct lua_State *L)
1935{
1936 return _hlua_map_lookup(L, 0);
1937}
1938
1939__LJMP static int hlua_map_slookup(struct lua_State *L)
1940{
1941 return _hlua_map_lookup(L, 1);
1942}
1943
1944/*
1945 *
1946 *
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001947 * Class Socket
1948 *
1949 *
1950 */
1951
1952__LJMP static struct hlua_socket *hlua_checksocket(lua_State *L, int ud)
1953{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02001954 return MAY_LJMP(hlua_checkudata(L, ud, class_socket_ref));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001955}
1956
1957/* This function is the handler called for each I/O on the established
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001958 * connection. It is used for notify space available to send or data
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001959 * received.
1960 */
Willy Tarreau00a37f02015-04-13 12:05:19 +02001961static void hlua_socket_handler(struct appctx *appctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001962{
Willy Tarreau5321da92022-05-06 11:57:34 +02001963 struct hlua_csk_ctx *ctx = appctx->svcctx;
Willy Tarreauc12b3212022-05-27 11:08:15 +02001964 struct stconn *sc = appctx_sc(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001965
Willy Tarreau5321da92022-05-06 11:57:34 +02001966 if (ctx->die) {
Willy Tarreau3e7be362022-05-27 10:35:27 +02001967 sc_shutw(sc);
1968 sc_shutr(sc);
1969 sc_ic(sc)->flags |= CF_READ_NULL;
Willy Tarreau5321da92022-05-06 11:57:34 +02001970 notification_wake(&ctx->wake_on_read);
1971 notification_wake(&ctx->wake_on_write);
Willy Tarreau3e7be362022-05-27 10:35:27 +02001972 stream_shutdown(__sc_strm(sc), SF_ERR_KILLED);
Thierry FOURNIERb13b20a2017-07-16 20:48:54 +02001973 }
1974
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +05001975 /* If we can't write, wakeup the pending write signals. */
Willy Tarreau3e7be362022-05-27 10:35:27 +02001976 if (channel_output_closed(sc_ic(sc)))
Willy Tarreau5321da92022-05-06 11:57:34 +02001977 notification_wake(&ctx->wake_on_write);
Thierry FOURNIER6d695e62015-09-27 19:29:38 +02001978
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +05001979 /* If we can't read, wakeup the pending read signals. */
Willy Tarreau3e7be362022-05-27 10:35:27 +02001980 if (channel_input_closed(sc_oc(sc)))
Willy Tarreau5321da92022-05-06 11:57:34 +02001981 notification_wake(&ctx->wake_on_read);
Thierry FOURNIER6d695e62015-09-27 19:29:38 +02001982
Willy Tarreau5a0b25d2019-07-18 18:01:14 +02001983 /* if the connection is not established, inform the stream that we want
Thierry FOURNIER316e3192015-09-04 18:25:53 +02001984 * to be notified whenever the connection completes.
1985 */
Willy Tarreau3e7be362022-05-27 10:35:27 +02001986 if (sc_opposite(sc)->state < SC_ST_EST) {
Willy Tarreau90e8b452022-05-25 18:21:43 +02001987 applet_need_more_data(appctx);
Willy Tarreaub23edc82022-05-24 16:49:03 +02001988 se_need_remote_conn(appctx->sedesc);
Willy Tarreau4164eb92022-05-25 15:42:03 +02001989 applet_have_more_data(appctx);
Willy Tarreaud4da1962015-04-20 01:31:23 +02001990 return;
Thierry FOURNIER316e3192015-09-04 18:25:53 +02001991 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001992
1993 /* This function is called after the connect. */
Willy Tarreau5321da92022-05-06 11:57:34 +02001994 ctx->connected = 1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001995
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001996 /* Wake the tasks which wants to write if the buffer have available space. */
Willy Tarreau3e7be362022-05-27 10:35:27 +02001997 if (channel_may_recv(sc_ic(sc)))
Willy Tarreau5321da92022-05-06 11:57:34 +02001998 notification_wake(&ctx->wake_on_write);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001999
2000 /* Wake the tasks which wants to read if the buffer contains data. */
Willy Tarreau3e7be362022-05-27 10:35:27 +02002001 if (!channel_is_empty(sc_oc(sc)))
Willy Tarreau5321da92022-05-06 11:57:34 +02002002 notification_wake(&ctx->wake_on_read);
Thierry FOURNIER101b9762018-05-27 01:27:40 +02002003
2004 /* Some data were injected in the buffer, notify the stream
2005 * interface.
2006 */
Willy Tarreau3e7be362022-05-27 10:35:27 +02002007 if (!channel_is_empty(sc_ic(sc)))
2008 sc_update(sc);
Thierry FOURNIER101b9762018-05-27 01:27:40 +02002009
2010 /* If write notifications are registered, we considers we want
Willy Tarreau3367d412018-11-15 10:57:41 +01002011 * to write, so we clear the blocking flag.
Thierry FOURNIER101b9762018-05-27 01:27:40 +02002012 */
Willy Tarreau5321da92022-05-06 11:57:34 +02002013 if (notification_registered(&ctx->wake_on_write))
Willy Tarreau4164eb92022-05-25 15:42:03 +02002014 applet_have_more_data(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002015}
2016
Christopher Faulet5f35a3e2022-05-12 15:31:05 +02002017static int hlua_socket_init(struct appctx *appctx)
2018{
2019 struct hlua_csk_ctx *ctx = appctx->svcctx;
2020 struct stream *s;
2021
2022 if (appctx_finalize_startup(appctx, socket_proxy, &BUF_NULL) == -1)
2023 goto error;
2024
2025 s = appctx_strm(appctx);
2026
Willy Tarreau4596fe22022-05-17 19:07:51 +02002027 /* Configure "right" stream connector. This stconn is used to connect
Christopher Faulet5f35a3e2022-05-12 15:31:05 +02002028 * and retrieve data from the server. The connection is initialized
2029 * with the "struct server".
2030 */
Willy Tarreau74568cf2022-05-27 09:03:30 +02002031 sc_set_state(s->scb, SC_ST_ASS);
Christopher Faulet5f35a3e2022-05-12 15:31:05 +02002032
2033 /* Force destination server. */
2034 s->flags |= SF_DIRECT | SF_ASSIGNED | SF_BE_ASSIGNED;
2035 s->target = &socket_tcp->obj_type;
2036
2037 ctx->appctx = appctx;
2038 return 0;
2039
2040 error:
2041 return -1;
2042}
2043
Willy Tarreau87b09662015-04-03 00:22:06 +02002044/* This function is called when the "struct stream" is destroyed.
2045 * Remove the link from the object to this stream.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002046 * Wake all the pending signals.
2047 */
Willy Tarreau00a37f02015-04-13 12:05:19 +02002048static void hlua_socket_release(struct appctx *appctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002049{
Willy Tarreau5321da92022-05-06 11:57:34 +02002050 struct hlua_csk_ctx *ctx = appctx->svcctx;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002051 struct xref *peer;
2052
Christopher Faulet5f35a3e2022-05-12 15:31:05 +02002053 /* Remove my link in the original objects. */
Willy Tarreau5321da92022-05-06 11:57:34 +02002054 peer = xref_get_peer_and_lock(&ctx->xref);
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002055 if (peer)
Willy Tarreau5321da92022-05-06 11:57:34 +02002056 xref_disconnect(&ctx->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002057
2058 /* Wake all the task waiting for me. */
Willy Tarreau5321da92022-05-06 11:57:34 +02002059 notification_wake(&ctx->wake_on_read);
2060 notification_wake(&ctx->wake_on_write);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002061}
2062
2063/* If the garbage collectio of the object is launch, nobody
Willy Tarreau87b09662015-04-03 00:22:06 +02002064 * uses this object. If the stream does not exists, just quit.
2065 * Send the shutdown signal to the stream. In some cases,
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002066 * pending signal can rest in the read and write lists. destroy
2067 * it.
2068 */
2069__LJMP static int hlua_socket_gc(lua_State *L)
2070{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002071 struct hlua_socket *socket;
Willy Tarreau5321da92022-05-06 11:57:34 +02002072 struct hlua_csk_ctx *ctx;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002073 struct xref *peer;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002074
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002075 MAY_LJMP(check_args(L, 1, "__gc"));
2076
2077 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002078 peer = xref_get_peer_and_lock(&socket->xref);
2079 if (!peer)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002080 return 0;
Willy Tarreau5321da92022-05-06 11:57:34 +02002081
2082 ctx = container_of(peer, struct hlua_csk_ctx, xref);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002083
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002084 /* Set the flag which destroy the session. */
Willy Tarreau5321da92022-05-06 11:57:34 +02002085 ctx->die = 1;
2086 appctx_wakeup(ctx->appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002087
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002088 /* Remove all reference between the Lua stack and the coroutine stream. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002089 xref_disconnect(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002090 return 0;
2091}
2092
2093/* The close function send shutdown signal and break the
Willy Tarreau87b09662015-04-03 00:22:06 +02002094 * links between the stream and the object.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002095 */
sada05ed3302018-05-11 11:48:18 -07002096__LJMP static int hlua_socket_close_helper(lua_State *L)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002097{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002098 struct hlua_socket *socket;
Willy Tarreau5321da92022-05-06 11:57:34 +02002099 struct hlua_csk_ctx *ctx;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002100 struct xref *peer;
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002101 struct hlua *hlua;
2102
2103 /* Get hlua struct, or NULL if we execute from main lua state */
2104 hlua = hlua_gethlua(L);
2105 if (!hlua)
2106 return 0;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002107
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002108 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002109
2110 /* Check if we run on the same thread than the xreator thread.
2111 * We cannot access to the socket if the thread is different.
2112 */
2113 if (socket->tid != tid)
2114 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2115
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002116 peer = xref_get_peer_and_lock(&socket->xref);
2117 if (!peer)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002118 return 0;
Willy Tarreauf31af932020-01-14 09:59:38 +01002119
2120 hlua->gc_count--;
Willy Tarreau5321da92022-05-06 11:57:34 +02002121 ctx = container_of(peer, struct hlua_csk_ctx, xref);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002122
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002123 /* Set the flag which destroy the session. */
Willy Tarreau5321da92022-05-06 11:57:34 +02002124 ctx->die = 1;
2125 appctx_wakeup(ctx->appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002126
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002127 /* Remove all reference between the Lua stack and the coroutine stream. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002128 xref_disconnect(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002129 return 0;
2130}
2131
sada05ed3302018-05-11 11:48:18 -07002132/* The close function calls close_helper.
2133 */
2134__LJMP static int hlua_socket_close(lua_State *L)
2135{
2136 MAY_LJMP(check_args(L, 1, "close"));
2137 return hlua_socket_close_helper(L);
2138}
2139
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002140/* This Lua function assumes that the stack contain three parameters.
2141 * 1 - USERDATA containing a struct socket
2142 * 2 - INTEGER with values of the macro defined below
2143 * If the integer is -1, we must read at most one line.
2144 * If the integer is -2, we ust read all the data until the
2145 * end of the stream.
2146 * If the integer is positive value, we must read a number of
2147 * bytes corresponding to this value.
2148 */
2149#define HLSR_READ_LINE (-1)
2150#define HLSR_READ_ALL (-2)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002151__LJMP static int hlua_socket_receive_yield(struct lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002152{
2153 struct hlua_socket *socket = MAY_LJMP(hlua_checksocket(L, 1));
2154 int wanted = lua_tointeger(L, 2);
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002155 struct hlua *hlua;
Willy Tarreau5321da92022-05-06 11:57:34 +02002156 struct hlua_csk_ctx *csk_ctx;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002157 struct appctx *appctx;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02002158 size_t len;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002159 int nblk;
Willy Tarreau206ba832018-06-14 15:27:31 +02002160 const char *blk1;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02002161 size_t len1;
Willy Tarreau206ba832018-06-14 15:27:31 +02002162 const char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02002163 size_t len2;
Thierry FOURNIER00543922015-03-09 18:35:06 +01002164 int skip_at_end = 0;
Willy Tarreau81389672015-03-10 12:03:52 +01002165 struct channel *oc;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002166 struct stream *s;
2167 struct xref *peer;
Thierry FOURNIER8c126c72018-05-25 16:27:44 +02002168 int missing_bytes;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002169
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002170 /* Get hlua struct, or NULL if we execute from main lua state */
2171 hlua = hlua_gethlua(L);
2172
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002173 /* Check if this lua stack is schedulable. */
2174 if (!hlua || !hlua->task)
2175 WILL_LJMP(luaL_error(L, "The 'receive' function is only allowed in "
2176 "'frontend', 'backend' or 'task'"));
2177
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002178 /* Check if we run on the same thread than the xreator thread.
2179 * We cannot access to the socket if the thread is different.
2180 */
2181 if (socket->tid != tid)
2182 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2183
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002184 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002185 peer = xref_get_peer_and_lock(&socket->xref);
2186 if (!peer)
2187 goto no_peer;
Willy Tarreau5321da92022-05-06 11:57:34 +02002188
2189 csk_ctx = container_of(peer, struct hlua_csk_ctx, xref);
2190 appctx = csk_ctx->appctx;
Willy Tarreau0698c802022-05-11 14:09:57 +02002191 s = appctx_strm(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002192
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002193 oc = &s->res;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002194 if (wanted == HLSR_READ_LINE) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002195 /* Read line. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02002196 nblk = co_getline_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002197 if (nblk < 0) /* Connection close. */
2198 goto connection_closed;
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002199 if (nblk == 0) /* No data available. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002200 goto connection_empty;
Thierry FOURNIER00543922015-03-09 18:35:06 +01002201
2202 /* remove final \r\n. */
2203 if (nblk == 1) {
2204 if (blk1[len1-1] == '\n') {
2205 len1--;
2206 skip_at_end++;
2207 if (blk1[len1-1] == '\r') {
2208 len1--;
2209 skip_at_end++;
2210 }
2211 }
2212 }
2213 else {
2214 if (blk2[len2-1] == '\n') {
2215 len2--;
2216 skip_at_end++;
2217 if (blk2[len2-1] == '\r') {
2218 len2--;
2219 skip_at_end++;
2220 }
2221 }
2222 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002223 }
2224
2225 else if (wanted == HLSR_READ_ALL) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002226 /* Read all the available data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02002227 nblk = co_getblk_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002228 if (nblk < 0) /* Connection close. */
2229 goto connection_closed;
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002230 if (nblk == 0) /* No data available. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002231 goto connection_empty;
2232 }
2233
2234 else {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002235 /* Read a block of data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02002236 nblk = co_getblk_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002237 if (nblk < 0) /* Connection close. */
2238 goto connection_closed;
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002239 if (nblk == 0) /* No data available. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002240 goto connection_empty;
2241
Thierry FOURNIER8c126c72018-05-25 16:27:44 +02002242 missing_bytes = wanted - socket->b.n;
2243 if (len1 > missing_bytes) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002244 nblk = 1;
Thierry FOURNIER8c126c72018-05-25 16:27:44 +02002245 len1 = missing_bytes;
2246 } if (nblk == 2 && len1 + len2 > missing_bytes)
2247 len2 = missing_bytes - len1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002248 }
2249
2250 len = len1;
2251
2252 luaL_addlstring(&socket->b, blk1, len1);
2253 if (nblk == 2) {
2254 len += len2;
2255 luaL_addlstring(&socket->b, blk2, len2);
2256 }
2257
2258 /* Consume data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02002259 co_skip(oc, len + skip_at_end);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002260
2261 /* Don't wait anything. */
Thierry FOURNIER7e4ee472018-05-25 15:03:50 +02002262 appctx_wakeup(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002263
2264 /* If the pattern reclaim to read all the data
2265 * in the connection, got out.
2266 */
2267 if (wanted == HLSR_READ_ALL)
2268 goto connection_empty;
Thierry FOURNIER8c126c72018-05-25 16:27:44 +02002269 else if (wanted >= 0 && socket->b.n < wanted)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002270 goto connection_empty;
2271
2272 /* Return result. */
2273 luaL_pushresult(&socket->b);
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002274 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002275 return 1;
2276
2277connection_closed:
2278
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002279 xref_unlock(&socket->xref, peer);
2280
2281no_peer:
2282
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002283 /* If the buffer containds data. */
2284 if (socket->b.n > 0) {
2285 luaL_pushresult(&socket->b);
2286 return 1;
2287 }
2288 lua_pushnil(L);
2289 lua_pushstring(L, "connection closed.");
2290 return 2;
2291
2292connection_empty:
2293
Willy Tarreau5321da92022-05-06 11:57:34 +02002294 if (!notification_new(&hlua->com, &csk_ctx->wake_on_read, hlua->task)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002295 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002296 WILL_LJMP(luaL_error(L, "out of memory"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002297 }
2298 xref_unlock(&socket->xref, peer);
Willy Tarreau9635e032018-10-16 17:52:55 +02002299 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_receive_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002300 return 0;
2301}
2302
Tim Duesterhusb33754c2018-01-04 19:32:14 +01002303/* This Lua function gets two parameters. The first one can be string
2304 * or a number. If the string is "*l", the user requires one line. If
2305 * the string is "*a", the user requires all the contents of the stream.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002306 * If the value is a number, the user require a number of bytes equal
2307 * to the value. The default value is "*l" (a line).
2308 *
Tim Duesterhusb33754c2018-01-04 19:32:14 +01002309 * This parameter with a variable type is converted in integer. This
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002310 * integer takes this values:
2311 * -1 : read a line
2312 * -2 : read all the stream
Tim Duesterhusb33754c2018-01-04 19:32:14 +01002313 * >0 : amount of bytes.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002314 *
Tim Duesterhusb33754c2018-01-04 19:32:14 +01002315 * The second parameter is optional. It contains a string that must be
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002316 * concatenated with the read data.
2317 */
2318__LJMP static int hlua_socket_receive(struct lua_State *L)
2319{
2320 int wanted = HLSR_READ_LINE;
2321 const char *pattern;
Christopher Fauletc31b2002021-05-03 10:11:13 +02002322 int lastarg, type;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002323 char *error;
2324 size_t len;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002325 struct hlua_socket *socket;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002326
2327 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
2328 WILL_LJMP(luaL_error(L, "The 'receive' function requires between 1 and 3 arguments."));
2329
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002330 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002331
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002332 /* Check if we run on the same thread than the xreator thread.
2333 * We cannot access to the socket if the thread is different.
2334 */
2335 if (socket->tid != tid)
2336 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2337
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002338 /* check for pattern. */
2339 if (lua_gettop(L) >= 2) {
2340 type = lua_type(L, 2);
2341 if (type == LUA_TSTRING) {
2342 pattern = lua_tostring(L, 2);
2343 if (strcmp(pattern, "*a") == 0)
2344 wanted = HLSR_READ_ALL;
2345 else if (strcmp(pattern, "*l") == 0)
2346 wanted = HLSR_READ_LINE;
2347 else {
2348 wanted = strtoll(pattern, &error, 10);
2349 if (*error != '\0')
2350 WILL_LJMP(luaL_error(L, "Unsupported pattern."));
2351 }
2352 }
2353 else if (type == LUA_TNUMBER) {
2354 wanted = lua_tointeger(L, 2);
2355 if (wanted < 0)
2356 WILL_LJMP(luaL_error(L, "Unsupported size."));
2357 }
2358 }
2359
2360 /* Set pattern. */
2361 lua_pushinteger(L, wanted);
Tim Duesterhusc6e377e2018-01-04 19:32:13 +01002362
2363 /* Check if we would replace the top by itself. */
2364 if (lua_gettop(L) != 2)
2365 lua_replace(L, 2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002366
Christopher Fauletc31b2002021-05-03 10:11:13 +02002367 /* Save index of the top of the stack because since buffers are used, it
2368 * may change
2369 */
2370 lastarg = lua_gettop(L);
2371
Tim Duesterhusb33754c2018-01-04 19:32:14 +01002372 /* init buffer, and fill it with prefix. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002373 luaL_buffinit(L, &socket->b);
2374
2375 /* Check prefix. */
Christopher Fauletc31b2002021-05-03 10:11:13 +02002376 if (lastarg >= 3) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002377 if (lua_type(L, 3) != LUA_TSTRING)
2378 WILL_LJMP(luaL_error(L, "Expect a 'string' for the prefix"));
2379 pattern = lua_tolstring(L, 3, &len);
2380 luaL_addlstring(&socket->b, pattern, len);
2381 }
2382
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002383 return __LJMP(hlua_socket_receive_yield(L, 0, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002384}
2385
2386/* Write the Lua input string in the output buffer.
Mark Lakes22154b42018-01-29 14:38:40 -08002387 * This function returns a yield if no space is available.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002388 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002389static int hlua_socket_write_yield(struct lua_State *L,int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002390{
2391 struct hlua_socket *socket;
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002392 struct hlua *hlua;
Willy Tarreau5321da92022-05-06 11:57:34 +02002393 struct hlua_csk_ctx *csk_ctx;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002394 struct appctx *appctx;
2395 size_t buf_len;
2396 const char *buf;
2397 int len;
2398 int send_len;
2399 int sent;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002400 struct xref *peer;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002401 struct stream *s;
Willy Tarreau3e7be362022-05-27 10:35:27 +02002402 struct stconn *sc;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002403
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002404 /* Get hlua struct, or NULL if we execute from main lua state */
2405 hlua = hlua_gethlua(L);
2406
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002407 /* Check if this lua stack is schedulable. */
2408 if (!hlua || !hlua->task)
2409 WILL_LJMP(luaL_error(L, "The 'write' function is only allowed in "
2410 "'frontend', 'backend' or 'task'"));
2411
2412 /* Get object */
2413 socket = MAY_LJMP(hlua_checksocket(L, 1));
2414 buf = MAY_LJMP(luaL_checklstring(L, 2, &buf_len));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002415 sent = MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002416
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002417 /* Check if we run on the same thread than the xreator thread.
2418 * We cannot access to the socket if the thread is different.
2419 */
2420 if (socket->tid != tid)
2421 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2422
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002423 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002424 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002425 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002426 lua_pushinteger(L, -1);
2427 return 1;
2428 }
Willy Tarreau5321da92022-05-06 11:57:34 +02002429
2430 csk_ctx = container_of(peer, struct hlua_csk_ctx, xref);
2431 appctx = csk_ctx->appctx;
Willy Tarreauc12b3212022-05-27 11:08:15 +02002432 sc = appctx_sc(appctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02002433 s = __sc_strm(sc);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002434
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002435 /* Check for connection close. */
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002436 if (channel_output_closed(&s->req)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002437 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002438 lua_pushinteger(L, -1);
2439 return 1;
2440 }
2441
2442 /* Update the input buffer data. */
2443 buf += sent;
2444 send_len = buf_len - sent;
2445
2446 /* All the data are sent. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002447 if (sent >= buf_len) {
2448 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002449 return 1; /* Implicitly return the length sent. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002450 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002451
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002452 /* Check if the buffer is available because HAProxy doesn't allocate
Thierry FOURNIER486d52a2015-03-09 17:51:43 +01002453 * the request buffer if its not required.
2454 */
Willy Tarreauc9fa0482018-07-10 17:43:27 +02002455 if (s->req.buf.size == 0) {
Willy Tarreau3e7be362022-05-27 10:35:27 +02002456 if (!sc_alloc_ibuf(sc, &appctx->buffer_wait))
Christopher Faulet33834b12016-12-19 09:29:06 +01002457 goto hlua_socket_write_yield_return;
Thierry FOURNIER486d52a2015-03-09 17:51:43 +01002458 }
2459
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002460 /* Check for available space. */
Willy Tarreauc9fa0482018-07-10 17:43:27 +02002461 len = b_room(&s->req.buf);
Christopher Faulet33834b12016-12-19 09:29:06 +01002462 if (len <= 0) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002463 goto hlua_socket_write_yield_return;
Christopher Faulet33834b12016-12-19 09:29:06 +01002464 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002465
2466 /* send data */
2467 if (len < send_len)
2468 send_len = len;
Thierry FOURNIER66b89192018-05-27 01:14:47 +02002469 len = ci_putblk(&s->req, buf, send_len);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002470
2471 /* "Not enough space" (-1), "Buffer too little to contain
2472 * the data" (-2) are not expected because the available length
2473 * is tested.
2474 * Other unknown error are also not expected.
2475 */
2476 if (len <= 0) {
Willy Tarreaubc18da12015-03-13 14:00:47 +01002477 if (len == -1)
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002478 s->req.flags |= CF_WAKE_WRITE;
Willy Tarreaubc18da12015-03-13 14:00:47 +01002479
sada05ed3302018-05-11 11:48:18 -07002480 MAY_LJMP(hlua_socket_close_helper(L));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002481 lua_pop(L, 1);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002482 lua_pushinteger(L, -1);
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002483 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002484 return 1;
2485 }
2486
2487 /* update buffers. */
Thierry FOURNIER101b9762018-05-27 01:27:40 +02002488 appctx_wakeup(appctx);
Willy Tarreaude70fa12015-09-26 11:25:05 +02002489
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002490 s->req.rex = TICK_ETERNITY;
2491 s->res.wex = TICK_ETERNITY;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002492
2493 /* Update length sent. */
2494 lua_pop(L, 1);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002495 lua_pushinteger(L, sent + len);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002496
2497 /* All the data buffer is sent ? */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002498 if (sent + len >= buf_len) {
2499 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002500 return 1;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002501 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002502
2503hlua_socket_write_yield_return:
Willy Tarreau5321da92022-05-06 11:57:34 +02002504 if (!notification_new(&hlua->com, &csk_ctx->wake_on_write, hlua->task)) {
Thierry FOURNIERba42fcd2018-05-27 00:59:48 +02002505 xref_unlock(&socket->xref, peer);
2506 WILL_LJMP(luaL_error(L, "out of memory"));
2507 }
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002508 xref_unlock(&socket->xref, peer);
Willy Tarreau9635e032018-10-16 17:52:55 +02002509 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_write_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002510 return 0;
2511}
2512
2513/* This function initiate the send of data. It just check the input
2514 * parameters and push an integer in the Lua stack that contain the
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002515 * amount of data written to the buffer. This is used by the function
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002516 * "hlua_socket_write_yield" that can yield.
2517 *
2518 * The Lua function gets between 3 and 4 parameters. The first one is
2519 * the associated object. The second is a string buffer. The third is
2520 * a facultative integer that represents where is the buffer position
2521 * of the start of the data that can send. The first byte is the
2522 * position "1". The default value is "1". The fourth argument is a
2523 * facultative integer that represents where is the buffer position
2524 * of the end of the data that can send. The default is the last byte.
2525 */
2526static int hlua_socket_send(struct lua_State *L)
2527{
2528 int i;
2529 int j;
2530 const char *buf;
2531 size_t buf_len;
2532
2533 /* Check number of arguments. */
2534 if (lua_gettop(L) < 2 || lua_gettop(L) > 4)
2535 WILL_LJMP(luaL_error(L, "'send' needs between 2 and 4 arguments"));
2536
2537 /* Get the string. */
2538 buf = MAY_LJMP(luaL_checklstring(L, 2, &buf_len));
2539
2540 /* Get and check j. */
2541 if (lua_gettop(L) == 4) {
2542 j = MAY_LJMP(luaL_checkinteger(L, 4));
2543 if (j < 0)
2544 j = buf_len + j + 1;
2545 if (j > buf_len)
2546 j = buf_len + 1;
2547 lua_pop(L, 1);
2548 }
2549 else
2550 j = buf_len;
2551
2552 /* Get and check i. */
2553 if (lua_gettop(L) == 3) {
2554 i = MAY_LJMP(luaL_checkinteger(L, 3));
2555 if (i < 0)
2556 i = buf_len + i + 1;
2557 if (i > buf_len)
2558 i = buf_len + 1;
2559 lua_pop(L, 1);
2560 } else
2561 i = 1;
2562
2563 /* Check bth i and j. */
2564 if (i > j) {
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002565 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002566 return 1;
2567 }
2568 if (i == 0 && j == 0) {
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002569 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002570 return 1;
2571 }
2572 if (i == 0)
2573 i = 1;
2574 if (j == 0)
2575 j = 1;
2576
2577 /* Pop the string. */
2578 lua_pop(L, 1);
2579
2580 /* Update the buffer length. */
2581 buf += i - 1;
2582 buf_len = j - i + 1;
2583 lua_pushlstring(L, buf, buf_len);
2584
2585 /* This unsigned is used to remember the amount of sent data. */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002586 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002587
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002588 return MAY_LJMP(hlua_socket_write_yield(L, 0, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002589}
2590
Willy Tarreau22b0a682015-06-17 19:43:49 +02002591#define SOCKET_INFO_MAX_LEN sizeof("[0000:0000:0000:0000:0000:0000:0000:0000]:12345")
Christopher Faulete6465b32021-10-22 15:36:08 +02002592__LJMP static inline int hlua_socket_info(struct lua_State *L, const struct sockaddr_storage *addr)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002593{
2594 static char buffer[SOCKET_INFO_MAX_LEN];
2595 int ret;
2596 int len;
2597 char *p;
2598
2599 ret = addr_to_str(addr, buffer+1, SOCKET_INFO_MAX_LEN-1);
2600 if (ret <= 0) {
2601 lua_pushnil(L);
2602 return 1;
2603 }
2604
2605 if (ret == AF_UNIX) {
2606 lua_pushstring(L, buffer+1);
2607 return 1;
2608 }
2609 else if (ret == AF_INET6) {
2610 buffer[0] = '[';
2611 len = strlen(buffer);
2612 buffer[len] = ']';
2613 len++;
2614 buffer[len] = ':';
2615 len++;
2616 p = buffer;
2617 }
2618 else if (ret == AF_INET) {
2619 p = buffer + 1;
2620 len = strlen(p);
2621 p[len] = ':';
2622 len++;
2623 }
2624 else {
2625 lua_pushnil(L);
2626 return 1;
2627 }
2628
2629 if (port_to_str(addr, p + len, SOCKET_INFO_MAX_LEN-1 - len) <= 0) {
2630 lua_pushnil(L);
2631 return 1;
2632 }
2633
2634 lua_pushstring(L, p);
2635 return 1;
2636}
2637
2638/* Returns information about the peer of the connection. */
2639__LJMP static int hlua_socket_getpeername(struct lua_State *L)
2640{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002641 struct hlua_socket *socket;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002642 struct xref *peer;
2643 struct appctx *appctx;
Willy Tarreau3e7be362022-05-27 10:35:27 +02002644 struct stconn *sc;
Christopher Faulet16f16af2021-10-27 09:34:56 +02002645 const struct sockaddr_storage *dst;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002646 int ret;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002647
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002648 MAY_LJMP(check_args(L, 1, "getpeername"));
2649
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002650 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002651
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002652 /* Check if we run on the same thread than the xreator thread.
2653 * We cannot access to the socket if the thread is different.
2654 */
2655 if (socket->tid != tid)
2656 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2657
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002658 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002659 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002660 if (!peer) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002661 lua_pushnil(L);
2662 return 1;
2663 }
Willy Tarreau5321da92022-05-06 11:57:34 +02002664
2665 appctx = container_of(peer, struct hlua_csk_ctx, xref)->appctx;
Willy Tarreauc12b3212022-05-27 11:08:15 +02002666 sc = appctx_sc(appctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02002667 dst = sc_dst(sc_opposite(sc));
Christopher Faulet16f16af2021-10-27 09:34:56 +02002668 if (!dst) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002669 xref_unlock(&socket->xref, peer);
Willy Tarreaua71f6422016-11-16 17:00:14 +01002670 lua_pushnil(L);
2671 return 1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002672 }
2673
Christopher Faulet16f16af2021-10-27 09:34:56 +02002674 ret = MAY_LJMP(hlua_socket_info(L, dst));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002675 xref_unlock(&socket->xref, peer);
2676 return ret;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002677}
2678
2679/* Returns information about my connection side. */
2680static int hlua_socket_getsockname(struct lua_State *L)
2681{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002682 struct hlua_socket *socket;
2683 struct connection *conn;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002684 struct appctx *appctx;
2685 struct xref *peer;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002686 struct stream *s;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002687 int ret;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002688
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002689 MAY_LJMP(check_args(L, 1, "getsockname"));
2690
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002691 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002692
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002693 /* Check if we run on the same thread than the xreator thread.
2694 * We cannot access to the socket if the thread is different.
2695 */
2696 if (socket->tid != tid)
2697 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2698
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002699 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002700 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002701 if (!peer) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002702 lua_pushnil(L);
2703 return 1;
2704 }
Willy Tarreau5321da92022-05-06 11:57:34 +02002705
2706 appctx = container_of(peer, struct hlua_csk_ctx, xref)->appctx;
Willy Tarreau0698c802022-05-11 14:09:57 +02002707 s = appctx_strm(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002708
Willy Tarreaufd9417b2022-05-18 16:23:22 +02002709 conn = sc_conn(s->scb);
Willy Tarreau5a0b25d2019-07-18 18:01:14 +02002710 if (!conn || !conn_get_src(conn)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002711 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002712 lua_pushnil(L);
2713 return 1;
2714 }
2715
Willy Tarreau9da9a6f2019-07-17 14:49:44 +02002716 ret = hlua_socket_info(L, conn->src);
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002717 xref_unlock(&socket->xref, peer);
2718 return ret;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002719}
2720
2721/* This struct define the applet. */
Willy Tarreau30576452015-04-13 13:50:30 +02002722static struct applet update_applet = {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002723 .obj_type = OBJ_TYPE_APPLET,
2724 .name = "<LUA_TCP>",
2725 .fct = hlua_socket_handler,
Christopher Faulet5f35a3e2022-05-12 15:31:05 +02002726 .init = hlua_socket_init,
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002727 .release = hlua_socket_release,
2728};
2729
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002730__LJMP static int hlua_socket_connect_yield(struct lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002731{
2732 struct hlua_socket *socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002733 struct hlua *hlua;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002734 struct xref *peer;
Willy Tarreau5321da92022-05-06 11:57:34 +02002735 struct hlua_csk_ctx *csk_ctx;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002736 struct appctx *appctx;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002737 struct stream *s;
2738
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002739 /* Get hlua struct, or NULL if we execute from main lua state */
2740 hlua = hlua_gethlua(L);
2741 if (!hlua)
2742 return 0;
2743
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002744 /* Check if we run on the same thread than the xreator thread.
2745 * We cannot access to the socket if the thread is different.
2746 */
2747 if (socket->tid != tid)
2748 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2749
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002750 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002751 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002752 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002753 lua_pushnil(L);
2754 lua_pushstring(L, "Can't connect");
2755 return 2;
2756 }
Willy Tarreau5321da92022-05-06 11:57:34 +02002757
2758 csk_ctx = container_of(peer, struct hlua_csk_ctx, xref);
2759 appctx = csk_ctx->appctx;
Willy Tarreau0698c802022-05-11 14:09:57 +02002760 s = appctx_strm(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002761
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002762 /* Check if we run on the same thread than the xreator thread.
2763 * We cannot access to the socket if the thread is different.
2764 */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002765 if (socket->tid != tid) {
2766 xref_unlock(&socket->xref, peer);
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002767 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002768 }
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002769
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002770 /* Check for connection close. */
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002771 if (!hlua || channel_output_closed(&s->req)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002772 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002773 lua_pushnil(L);
2774 lua_pushstring(L, "Can't connect");
2775 return 2;
2776 }
2777
Willy Tarreau8e7c6e62022-05-18 17:58:02 +02002778 appctx = __sc_appctx(s->scf);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002779
2780 /* Check for connection established. */
Willy Tarreau5321da92022-05-06 11:57:34 +02002781 if (csk_ctx->connected) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002782 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002783 lua_pushinteger(L, 1);
2784 return 1;
2785 }
2786
Willy Tarreau5321da92022-05-06 11:57:34 +02002787 if (!notification_new(&hlua->com, &csk_ctx->wake_on_write, hlua->task)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002788 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002789 WILL_LJMP(luaL_error(L, "out of memory error"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002790 }
2791 xref_unlock(&socket->xref, peer);
Willy Tarreau9635e032018-10-16 17:52:55 +02002792 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_connect_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002793 return 0;
2794}
2795
2796/* This function fail or initite the connection. */
2797__LJMP static int hlua_socket_connect(struct lua_State *L)
2798{
2799 struct hlua_socket *socket;
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002800 int port = -1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002801 const char *ip;
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002802 struct hlua *hlua;
Willy Tarreau5321da92022-05-06 11:57:34 +02002803 struct hlua_csk_ctx *csk_ctx;
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002804 struct appctx *appctx;
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002805 int low, high;
2806 struct sockaddr_storage *addr;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002807 struct xref *peer;
Willy Tarreau3e7be362022-05-27 10:35:27 +02002808 struct stconn *sc;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002809 struct stream *s;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002810
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002811 if (lua_gettop(L) < 2)
2812 WILL_LJMP(luaL_error(L, "connect: need at least 2 arguments"));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002813
2814 /* Get args. */
2815 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002816
2817 /* Check if we run on the same thread than the xreator thread.
2818 * We cannot access to the socket if the thread is different.
2819 */
2820 if (socket->tid != tid)
2821 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2822
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002823 ip = MAY_LJMP(luaL_checkstring(L, 2));
Tim Duesterhus6edab862018-01-06 19:04:45 +01002824 if (lua_gettop(L) >= 3) {
2825 luaL_Buffer b;
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002826 port = MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002827
Tim Duesterhus6edab862018-01-06 19:04:45 +01002828 /* Force the ip to end with a colon, to support IPv6 addresses
2829 * that are not enclosed within square brackets.
2830 */
2831 if (port > 0) {
2832 luaL_buffinit(L, &b);
2833 luaL_addstring(&b, ip);
2834 luaL_addchar(&b, ':');
2835 luaL_pushresult(&b);
2836 ip = lua_tolstring(L, lua_gettop(L), NULL);
2837 }
2838 }
2839
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002840 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002841 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002842 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002843 lua_pushnil(L);
2844 return 1;
2845 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002846
2847 /* Parse ip address. */
Willy Tarreau5fc93282020-09-16 18:25:03 +02002848 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 +02002849 if (!addr) {
2850 xref_unlock(&socket->xref, peer);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002851 WILL_LJMP(luaL_error(L, "connect: cannot parse destination address '%s'", ip));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002852 }
Willy Tarreau9da9a6f2019-07-17 14:49:44 +02002853
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002854 /* Set port. */
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002855 if (low == 0) {
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02002856 if (addr->ss_family == AF_INET) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002857 if (port == -1) {
2858 xref_unlock(&socket->xref, peer);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002859 WILL_LJMP(luaL_error(L, "connect: port missing"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002860 }
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02002861 ((struct sockaddr_in *)addr)->sin_port = htons(port);
2862 } else if (addr->ss_family == AF_INET6) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002863 if (port == -1) {
2864 xref_unlock(&socket->xref, peer);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002865 WILL_LJMP(luaL_error(L, "connect: port missing"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002866 }
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02002867 ((struct sockaddr_in6 *)addr)->sin6_port = htons(port);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002868 }
2869 }
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02002870
Willy Tarreau5321da92022-05-06 11:57:34 +02002871 csk_ctx = container_of(peer, struct hlua_csk_ctx, xref);
2872 appctx = csk_ctx->appctx;
Willy Tarreauc12b3212022-05-27 11:08:15 +02002873 sc = appctx_sc(appctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02002874 s = __sc_strm(sc);
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02002875
Willy Tarreau3e7be362022-05-27 10:35:27 +02002876 if (!sockaddr_alloc(&sc_opposite(sc)->dst, addr, sizeof(*addr))) {
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02002877 xref_unlock(&socket->xref, peer);
2878 WILL_LJMP(luaL_error(L, "connect: internal error"));
2879 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002880
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002881 /* Get hlua struct, or NULL if we execute from main lua state */
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002882 hlua = hlua_gethlua(L);
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002883 if (!hlua)
2884 return 0;
Willy Tarreaubdc97a82015-08-24 15:42:28 +02002885
2886 /* inform the stream that we want to be notified whenever the
2887 * connection completes.
2888 */
Willy Tarreau90e8b452022-05-25 18:21:43 +02002889 applet_need_more_data(appctx);
Willy Tarreau4164eb92022-05-25 15:42:03 +02002890 applet_have_more_data(appctx);
Thierry FOURNIER8c8fbbe2015-09-26 17:02:35 +02002891 appctx_wakeup(appctx);
Willy Tarreaubdc97a82015-08-24 15:42:28 +02002892
Willy Tarreauf31af932020-01-14 09:59:38 +01002893 hlua->gc_count++;
Thierry FOURNIER7c39ab42015-09-27 22:53:33 +02002894
Willy Tarreau5321da92022-05-06 11:57:34 +02002895 if (!notification_new(&hlua->com, &csk_ctx->wake_on_write, hlua->task)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002896 xref_unlock(&socket->xref, peer);
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002897 WILL_LJMP(luaL_error(L, "out of memory"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002898 }
2899 xref_unlock(&socket->xref, peer);
PiBa-NL706d5ee2018-05-05 23:51:42 +02002900
2901 task_wakeup(s->task, TASK_WOKEN_INIT);
2902 /* Return yield waiting for connection. */
2903
Willy Tarreau9635e032018-10-16 17:52:55 +02002904 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_connect_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002905
2906 return 0;
2907}
2908
Baptiste Assmann84bb4932015-03-02 21:40:06 +01002909#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002910__LJMP static int hlua_socket_connect_ssl(struct lua_State *L)
2911{
2912 struct hlua_socket *socket;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002913 struct xref *peer;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002914 struct stream *s;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002915
2916 MAY_LJMP(check_args(L, 3, "connect_ssl"));
2917 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002918
2919 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002920 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002921 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002922 lua_pushnil(L);
2923 return 1;
2924 }
Willy Tarreau5321da92022-05-06 11:57:34 +02002925
Willy Tarreau0698c802022-05-11 14:09:57 +02002926 s = appctx_strm(container_of(peer, struct hlua_csk_ctx, xref)->appctx);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002927
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +01002928 s->target = &socket_ssl->obj_type;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002929 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002930 return MAY_LJMP(hlua_socket_connect(L));
2931}
Baptiste Assmann84bb4932015-03-02 21:40:06 +01002932#endif
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002933
2934__LJMP static int hlua_socket_setoption(struct lua_State *L)
2935{
2936 return 0;
2937}
2938
2939__LJMP static int hlua_socket_settimeout(struct lua_State *L)
2940{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002941 struct hlua_socket *socket;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002942 int tmout;
Mark Lakes56cc1252018-03-27 09:48:06 +02002943 double dtmout;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002944 struct xref *peer;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002945 struct stream *s;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002946
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002947 MAY_LJMP(check_args(L, 2, "settimeout"));
2948
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002949 socket = MAY_LJMP(hlua_checksocket(L, 1));
Mark Lakes56cc1252018-03-27 09:48:06 +02002950
Cyril Bonté7ee465f2018-08-19 22:08:50 +02002951 /* convert the timeout to millis */
2952 dtmout = MAY_LJMP(luaL_checknumber(L, 2)) * 1000;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002953
Thierry Fournier17a921b2018-03-08 09:59:02 +01002954 /* Check for negative values */
Mark Lakes56cc1252018-03-27 09:48:06 +02002955 if (dtmout < 0)
Thierry Fournier17a921b2018-03-08 09:59:02 +01002956 WILL_LJMP(luaL_error(L, "settimeout: cannot set negatives values"));
2957
Mark Lakes56cc1252018-03-27 09:48:06 +02002958 if (dtmout > INT_MAX) /* overflow check */
Cyril Bonté7ee465f2018-08-19 22:08:50 +02002959 WILL_LJMP(luaL_error(L, "settimeout: cannot set values larger than %d ms", INT_MAX));
Mark Lakes56cc1252018-03-27 09:48:06 +02002960
2961 tmout = MS_TO_TICKS((int)dtmout);
Cyril Bonté7ee465f2018-08-19 22:08:50 +02002962 if (tmout == 0)
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05002963 tmout++; /* very small timeouts are adjusted to a minimum of 1ms */
Mark Lakes56cc1252018-03-27 09:48:06 +02002964
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002965 /* Check if we run on the same thread than the xreator thread.
2966 * We cannot access to the socket if the thread is different.
2967 */
2968 if (socket->tid != tid)
2969 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2970
Mark Lakes56cc1252018-03-27 09:48:06 +02002971 /* check for connection break. If some data were read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002972 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002973 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002974 hlua_pusherror(L, "socket: not yet initialised, you can't set timeouts.");
2975 WILL_LJMP(lua_error(L));
2976 return 0;
2977 }
Willy Tarreau5321da92022-05-06 11:57:34 +02002978
Willy Tarreau0698c802022-05-11 14:09:57 +02002979 s = appctx_strm(container_of(peer, struct hlua_csk_ctx, xref)->appctx);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002980
Cyril Bonté7bb63452018-08-17 23:51:02 +02002981 s->sess->fe->timeout.connect = tmout;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002982 s->req.rto = tmout;
2983 s->req.wto = tmout;
2984 s->res.rto = tmout;
2985 s->res.wto = tmout;
Cyril Bonté7bb63452018-08-17 23:51:02 +02002986 s->req.rex = tick_add_ifset(now_ms, tmout);
2987 s->req.wex = tick_add_ifset(now_ms, tmout);
2988 s->res.rex = tick_add_ifset(now_ms, tmout);
2989 s->res.wex = tick_add_ifset(now_ms, tmout);
2990
2991 s->task->expire = tick_add_ifset(now_ms, tmout);
2992 task_queue(s->task);
2993
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002994 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002995
Thierry Fourniere9636f12018-03-08 09:54:32 +01002996 lua_pushinteger(L, 1);
Tim Duesterhus119a5f12018-01-06 19:16:25 +01002997 return 1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002998}
2999
3000__LJMP static int hlua_socket_new(lua_State *L)
3001{
3002 struct hlua_socket *socket;
Willy Tarreau5321da92022-05-06 11:57:34 +02003003 struct hlua_csk_ctx *ctx;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003004 struct appctx *appctx;
3005
3006 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003007 if (!lua_checkstack(L, 3)) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003008 hlua_pusherror(L, "socket: full stack");
3009 goto out_fail_conf;
3010 }
3011
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003012 /* Create the object: obj[0] = userdata. */
3013 lua_newtable(L);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003014 socket = MAY_LJMP(lua_newuserdata(L, sizeof(*socket)));
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003015 lua_rawseti(L, -2, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003016 memset(socket, 0, sizeof(*socket));
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02003017 socket->tid = tid;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003018
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05003019 /* Check if the various memory pools are initialized. */
Willy Tarreaubafbe012017-11-24 17:34:44 +01003020 if (!pool_head_stream || !pool_head_buffer) {
Thierry FOURNIER4a6170c2015-03-09 17:07:10 +01003021 hlua_pusherror(L, "socket: uninitialized pools.");
3022 goto out_fail_conf;
3023 }
3024
Willy Tarreau87b09662015-04-03 00:22:06 +02003025 /* Pop a class stream metatable and affect it to the userdata. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003026 lua_rawgeti(L, LUA_REGISTRYINDEX, class_socket_ref);
3027 lua_setmetatable(L, -2);
3028
Willy Tarreaud420a972015-04-06 00:39:18 +02003029 /* Create the applet context */
Christopher Faulet6095d572022-05-16 17:09:48 +02003030 appctx = appctx_new_here(&update_applet, NULL);
Willy Tarreau61cf7c82015-04-06 00:48:33 +02003031 if (!appctx) {
3032 hlua_pusherror(L, "socket: out of memory");
Christopher Fauleta9e8b392022-03-23 11:01:09 +01003033 goto out_fail_conf;
Willy Tarreau61cf7c82015-04-06 00:48:33 +02003034 }
Willy Tarreau5321da92022-05-06 11:57:34 +02003035 ctx = applet_reserve_svcctx(appctx, sizeof(*ctx));
3036 ctx->connected = 0;
Willy Tarreau5321da92022-05-06 11:57:34 +02003037 ctx->die = 0;
3038 LIST_INIT(&ctx->wake_on_write);
3039 LIST_INIT(&ctx->wake_on_read);
Willy Tarreaub2bf8332015-04-04 15:58:58 +02003040
Christopher Faulet5f35a3e2022-05-12 15:31:05 +02003041 if (appctx_init(appctx) == -1) {
3042 hlua_pusherror(L, "socket: fail to init applet.");
Christopher Faulet13a35e52021-12-20 15:34:16 +01003043 goto out_fail_appctx;
3044 }
3045
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003046 /* Initialise cross reference between stream and Lua socket object. */
Willy Tarreau5321da92022-05-06 11:57:34 +02003047 xref_create(&socket->xref, &ctx->xref);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003048 return 1;
3049
Christopher Faulet13a35e52021-12-20 15:34:16 +01003050 out_fail_appctx:
Christopher Faulet5f35a3e2022-05-12 15:31:05 +02003051 appctx_free_on_early_error(appctx);
Willy Tarreaud420a972015-04-06 00:39:18 +02003052 out_fail_conf:
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003053 WILL_LJMP(lua_error(L));
3054 return 0;
3055}
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01003056
3057/*
3058 *
3059 *
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003060 * Class Channel
3061 *
3062 *
3063 */
3064
3065/* Returns the struct hlua_channel join to the class channel in the
3066 * stack entry "ud" or throws an argument error.
3067 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01003068__LJMP static struct channel *hlua_checkchannel(lua_State *L, int ud)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003069{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003070 return MAY_LJMP(hlua_checkudata(L, ud, class_channel_ref));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003071}
3072
Willy Tarreau47860ed2015-03-10 14:07:50 +01003073/* Pushes the channel onto the top of the stack. If the stask does not have a
3074 * free slots, the function fails and returns 0;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003075 */
Willy Tarreau2a71af42015-03-10 13:51:50 +01003076static int hlua_channel_new(lua_State *L, struct channel *channel)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003077{
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003078 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003079 if (!lua_checkstack(L, 3))
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003080 return 0;
3081
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003082 lua_newtable(L);
Willy Tarreau47860ed2015-03-10 14:07:50 +01003083 lua_pushlightuserdata(L, channel);
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003084 lua_rawseti(L, -2, 0);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003085
3086 /* Pop a class sesison metatable and affect it to the userdata. */
3087 lua_rawgeti(L, LUA_REGISTRYINDEX, class_channel_ref);
3088 lua_setmetatable(L, -2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003089 return 1;
3090}
3091
Christopher Faulet9f55a502020-02-25 15:21:02 +01003092/* Helper function returning a filter attached to a channel at the position <ud>
3093 * in the stack, filling the current offset and length of the filter. If no
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05003094 * filter is attached, NULL is returned and <offset> and <len> are not
Christopher Faulet9f55a502020-02-25 15:21:02 +01003095 * initialized.
3096 */
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003097static 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 +01003098{
3099 struct filter *filter = NULL;
3100
3101 if (lua_getfield(L, ud, "__filter") == LUA_TLIGHTUSERDATA) {
3102 struct hlua_flt_ctx *flt_ctx;
3103
3104 filter = lua_touserdata (L, -1);
3105 flt_ctx = filter->ctx;
3106 if (hlua_filter_from_payload(filter)) {
3107 *offset = flt_ctx->cur_off[CHN_IDX(chn)];
3108 *len = flt_ctx->cur_len[CHN_IDX(chn)];
3109 }
3110 }
3111
3112 lua_pop(L, 1);
3113 return filter;
3114}
3115
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003116/* Copies <len> bytes of data present in the channel's buffer, starting at the
3117* offset <offset>, and put it in a LUA string variable. It is the caller
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003118* responsibility to ensure <len> and <offset> are valid. It always return the
3119* length of the built string. <len> may be 0, in this case, an empty string is
3120* created and 0 is returned.
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003121*/
3122static inline int _hlua_channel_dup(struct channel *chn, lua_State *L, size_t offset, size_t len)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003123{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003124 size_t block1, block2;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003125 luaL_Buffer b;
3126
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003127 block1 = len;
3128 if (block1 > b_contig_data(&chn->buf, b_peek_ofs(&chn->buf, offset)))
3129 block1 = b_contig_data(&chn->buf, b_peek_ofs(&chn->buf, offset));
3130 block2 = len - block1;
3131
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003132 luaL_buffinit(L, &b);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003133 luaL_addlstring(&b, b_peek(&chn->buf, offset), block1);
3134 if (block2)
3135 luaL_addlstring(&b, b_orig(&chn->buf), block2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003136 luaL_pushresult(&b);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003137 return len;
3138}
3139
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003140/* Inserts the string <str> to the channel's buffer at the offset <offset>. This
3141 * function returns -1 if data cannot be copied. Otherwise, it returns the
3142 * number of bytes copied.
3143 */
3144static int _hlua_channel_insert(struct channel *chn, lua_State *L, struct ist str, size_t offset)
3145{
3146 int ret = 0;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003147
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003148 /* Nothing to do, just return */
3149 if (unlikely(istlen(str) == 0))
3150 goto end;
3151
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003152 if (istlen(str) > c_room(chn)) {
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003153 ret = -1;
3154 goto end;
3155 }
3156 ret = b_insert_blk(&chn->buf, offset, istptr(str), istlen(str));
3157
3158 end:
3159 return ret;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003160}
3161
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003162/* Removes <len> bytes of data at the absolute position <offset>.
3163 */
3164static void _hlua_channel_delete(struct channel *chn, size_t offset, size_t len)
3165{
3166 size_t end = offset + len;
3167
3168 if (b_peek(&chn->buf, end) != b_tail(&chn->buf))
3169 b_move(&chn->buf, b_peek_ofs(&chn->buf, end),
3170 b_data(&chn->buf) - end, -len);
3171 b_sub(&chn->buf, len);
3172}
3173
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003174/* Copies input data in the channel's buffer. It is possible to set a specific
3175 * offset (0 by default) and a length (all remaining input data starting for the
3176 * offset by default). If there is not enough input data and more data can be
3177 * received, this function yields.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003178 *
3179 * From an action, All input data are considered. For a filter, the offset and
3180 * the length of input data to consider are retrieved from the filter context.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003181 */
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003182__LJMP static int hlua_channel_get_data_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003183{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003184 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003185 struct filter *filter;
3186 size_t input, output;
3187 int offset, len;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003188
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003189 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003190
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003191 output = co_data(chn);
3192 input = ci_data(chn);
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003193
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003194 filter = hlua_channel_filter(L, 1, chn, &output, &input);
3195 if (filter && !hlua_filter_from_payload(filter))
3196 WILL_LJMP(lua_error(L));
3197
3198 offset = output;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003199 if (lua_gettop(L) > 1) {
3200 offset = MAY_LJMP(luaL_checkinteger(L, 2));
3201 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02003202 offset = MAX(0, (int)input + offset);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003203 offset += output;
3204 if (offset < output || offset > input + output) {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003205 lua_pushfstring(L, "offset out of range.");
3206 WILL_LJMP(lua_error(L));
3207 }
3208 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003209 len = output + input - offset;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003210 if (lua_gettop(L) == 3) {
3211 len = MAY_LJMP(luaL_checkinteger(L, 3));
3212 if (!len)
3213 goto dup;
3214 if (len == -1)
3215 len = global.tune.bufsize;
3216 if (len < 0) {
3217 lua_pushfstring(L, "length out of range.");
3218 WILL_LJMP(lua_error(L));
3219 }
3220 }
3221
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003222 if (offset + len > output + input) {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003223 if (!HLUA_CANT_YIELD(hlua_gethlua(L)) && !channel_input_closed(chn) && channel_may_recv(chn)) {
3224 /* Yield waiting for more data, as requested */
3225 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_get_data_yield, TICK_ETERNITY, 0));
3226 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003227 len = output + input - offset;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003228 }
3229
3230 dup:
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003231 _hlua_channel_dup(chn, L, offset, len);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003232 return 1;
3233}
3234
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003235/* Copies the first line (including the trailing LF) of input data in the
3236 * channel's buffer. It is possible to set a specific offset (0 by default) and
3237 * a length (all remaining input data starting for the offset by default). If
3238 * there is not enough input data and more data can be received, the function
3239 * yields. If a length is explicitly specified, no more data are
3240 * copied. Otherwise, if no LF is found and more data can be received, this
3241 * function yields.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003242 *
3243 * From an action, All input data are considered. For a filter, the offset and
3244 * the length of input data to consider are retrieved from the filter context.
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003245 */
3246__LJMP static int hlua_channel_get_line_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003247{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003248 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003249 struct filter *filter;
3250 size_t l, input, output;
3251 int offset, len;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003252
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003253 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003254 output = co_data(chn);
3255 input = ci_data(chn);
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003256
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003257 filter = hlua_channel_filter(L, 1, chn, &output, &input);
3258 if (filter && !hlua_filter_from_payload(filter))
3259 WILL_LJMP(lua_error(L));
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003260
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003261 offset = output;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003262 if (lua_gettop(L) > 1) {
3263 offset = MAY_LJMP(luaL_checkinteger(L, 2));
3264 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02003265 offset = MAX(0, (int)input + offset);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003266 offset += output;
3267 if (offset < output || offset > input + output) {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003268 lua_pushfstring(L, "offset out of range.");
3269 WILL_LJMP(lua_error(L));
3270 }
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003271 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003272
3273 len = output + input - offset;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003274 if (lua_gettop(L) == 3) {
3275 len = MAY_LJMP(luaL_checkinteger(L, 3));
3276 if (!len)
3277 goto dup;
3278 if (len == -1)
3279 len = global.tune.bufsize;
3280 if (len < 0) {
3281 lua_pushfstring(L, "length out of range.");
3282 WILL_LJMP(lua_error(L));
3283 }
3284 }
3285
3286 for (l = 0; l < len; l++) {
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003287 if (l + offset >= output + input)
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003288 break;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003289 if (*(b_peek(&chn->buf, offset + l)) == '\n') {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003290 len = l+1;
3291 goto dup;
3292 }
3293 }
3294
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003295 if (offset + len > output + input) {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003296 if (!HLUA_CANT_YIELD(hlua_gethlua(L)) && !channel_input_closed(chn) && channel_may_recv(chn)) {
3297 /* Yield waiting for more data */
3298 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_get_line_yield, TICK_ETERNITY, 0));
3299 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003300 len = output + input - offset;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003301 }
3302
3303 dup:
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003304 _hlua_channel_dup(chn, L, offset, len);
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003305 return 1;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003306}
3307
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003308/* [ DEPRECATED ]
3309 *
3310 * Duplicate all input data foud in the channel's buffer. The data are not
3311 * removed from the buffer. This function relies on _hlua_channel_dup().
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003312 *
3313 * From an action, All input data are considered. For a filter, the offset and
3314 * the length of input data to consider are retrieved from the filter context.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003315 */
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003316__LJMP static int hlua_channel_dup(lua_State *L)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003317{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003318 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003319 struct filter *filter;
3320 size_t offset, len;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003321
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003322 MAY_LJMP(check_args(L, 1, "dup"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003323 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003324 if (IS_HTX_STRM(chn_strm(chn))) {
3325 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3326 WILL_LJMP(lua_error(L));
3327 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003328
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003329 offset = co_data(chn);
3330 len = ci_data(chn);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003331
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003332 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3333 if (filter && !hlua_filter_from_payload(filter))
3334 WILL_LJMP(lua_error(L));
3335
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003336 if (!ci_data(chn) && channel_input_closed(chn)) {
3337 lua_pushnil(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003338 return 1;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003339 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003340
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003341 _hlua_channel_dup(chn, L, offset, len);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003342 return 1;
3343}
3344
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003345/* [ DEPRECATED ]
3346 *
3347 * Get all input data foud in the channel's buffer. The data are removed from
3348 * the buffer after the copy. This function relies on _hlua_channel_dup() and
3349 * _hlua_channel_delete().
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003350 *
3351 * From an action, All input data are considered. For a filter, the offset and
3352 * the length of input data to consider are retrieved from the filter context.
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003353 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003354__LJMP static int hlua_channel_get(lua_State *L)
3355{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003356 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003357 struct filter *filter;
3358 size_t offset, len;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003359 int ret;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003360
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003361 MAY_LJMP(check_args(L, 1, "get"));
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003362 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3363 if (IS_HTX_STRM(chn_strm(chn))) {
3364 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3365 WILL_LJMP(lua_error(L));
3366 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003367
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003368 offset = co_data(chn);
3369 len = ci_data(chn);
3370
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003371 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3372 if (filter && !hlua_filter_from_payload(filter))
3373 WILL_LJMP(lua_error(L));
3374
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003375 if (!ci_data(chn) && channel_input_closed(chn)) {
3376 lua_pushnil(L);
3377 return 1;
3378 }
3379
3380 ret = _hlua_channel_dup(chn, L, offset, len);
3381 _hlua_channel_delete(chn, offset, ret);
3382 return 1;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003383}
3384
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003385/* This functions consumes and returns one line. If the channel is closed,
3386 * and the last data does not contains a final '\n', the data are returned
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003387 * without the final '\n'. When no more data are available, it returns nil
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003388 * value.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003389 *
3390 * From an action, All input data are considered. For a filter, the offset and
3391 * the length of input data to consider are retrieved from the filter context.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003392 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003393__LJMP static int hlua_channel_getline_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003394{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003395 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003396 struct filter *filter;
3397 size_t l, offset, len;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003398 int ret;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003399
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003400 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003401
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003402 offset = co_data(chn);
3403 len = ci_data(chn);
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003404
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003405 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3406 if (filter && !hlua_filter_from_payload(filter))
3407 WILL_LJMP(lua_error(L));
3408
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003409 if (!ci_data(chn) && channel_input_closed(chn)) {
3410 lua_pushnil(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003411 return 1;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003412 }
3413
3414 for (l = 0; l < len; l++) {
3415 if (*(b_peek(&chn->buf, offset+l)) == '\n') {
3416 len = l+1;
3417 goto dup;
3418 }
3419 }
3420
3421 if (!HLUA_CANT_YIELD(hlua_gethlua(L)) && !channel_input_closed(chn) && channel_may_recv(chn)) {
3422 /* Yield waiting for more data */
3423 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_getline_yield, TICK_ETERNITY, 0));
3424 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003425
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003426 dup:
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003427 ret = _hlua_channel_dup(chn, L, offset, len);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003428 _hlua_channel_delete(chn, offset, ret);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003429 return 1;
3430}
3431
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003432/* [ DEPRECATED ]
3433 *
3434 * Check arguments for the function "hlua_channel_getline_yield".
3435 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003436__LJMP static int hlua_channel_getline(lua_State *L)
3437{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003438 struct channel *chn;
3439
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003440 MAY_LJMP(check_args(L, 1, "getline"));
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003441 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3442 if (IS_HTX_STRM(chn_strm(chn))) {
3443 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3444 WILL_LJMP(lua_error(L));
3445 }
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003446 return MAY_LJMP(hlua_channel_getline_yield(L, 0, 0));
3447}
3448
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003449/* Retrieves a given amount of input data at the given offset. By default all
3450 * available input data are returned. The offset may be negactive to start from
3451 * the end of input data. The length may be -1 to set it to the maximum buffer
3452 * size.
3453 */
3454__LJMP static int hlua_channel_get_data(lua_State *L)
3455{
3456 struct channel *chn;
3457
3458 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
3459 WILL_LJMP(luaL_error(L, "'data' expects at most 2 arguments"));
3460 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3461 if (IS_HTX_STRM(chn_strm(chn))) {
3462 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3463 WILL_LJMP(lua_error(L));
3464 }
3465 return MAY_LJMP(hlua_channel_get_data_yield(L, 0, 0));
3466}
3467
3468/* Retrieves a given amount of input data at the given offset. By default all
3469 * available input data are returned. The offset may be negactive to start from
3470 * the end of input data. The length may be -1 to set it to the maximum buffer
3471 * size.
3472 */
3473__LJMP static int hlua_channel_get_line(lua_State *L)
3474{
3475 struct channel *chn;
3476
3477 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
3478 WILL_LJMP(luaL_error(L, "'line' expects at most 2 arguments"));
3479 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3480 if (IS_HTX_STRM(chn_strm(chn))) {
3481 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3482 WILL_LJMP(lua_error(L));
3483 }
3484 return MAY_LJMP(hlua_channel_get_line_yield(L, 0, 0));
3485}
3486
3487/* Appends a string into the input side of channel. It returns the length of the
3488 * written string, or -1 if the channel is closed or if the buffer size is too
3489 * little for the data. 0 may be returned if nothing is copied. This function
3490 * does not yield.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003491 *
3492 * For a filter, the context is updated on success.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003493 */
Christopher Faulet23976d92021-08-06 09:59:49 +02003494__LJMP static int hlua_channel_append(lua_State *L)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003495{
Christopher Faulet23976d92021-08-06 09:59:49 +02003496 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003497 struct filter *filter;
Christopher Faulet23976d92021-08-06 09:59:49 +02003498 const char *str;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003499 size_t sz, offset, len;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003500 int ret;
Christopher Faulet23976d92021-08-06 09:59:49 +02003501
3502 MAY_LJMP(check_args(L, 2, "append"));
3503 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003504 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
Christopher Faulet1bb6afa2021-03-08 17:57:53 +01003505 if (IS_HTX_STRM(chn_strm(chn))) {
Thierry Fournier77016da2020-08-15 14:35:51 +02003506 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
Christopher Faulet3f829a42018-12-13 21:56:45 +01003507 WILL_LJMP(lua_error(L));
Thierry Fournier77016da2020-08-15 14:35:51 +02003508 }
Christopher Faulet3f829a42018-12-13 21:56:45 +01003509
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003510 offset = co_data(chn);
3511 len = ci_data(chn);
3512
3513 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3514 if (filter && !hlua_filter_from_payload(filter))
3515 WILL_LJMP(lua_error(L));
3516
3517 ret = _hlua_channel_insert(chn, L, ist2(str, sz), offset);
3518 if (ret > 0 && filter) {
3519 struct hlua_flt_ctx *flt_ctx = filter->ctx;
3520
3521 flt_update_offsets(filter, chn, ret);
3522 flt_ctx->cur_len[CHN_IDX(chn)] += ret;
3523 }
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003524 lua_pushinteger(L, ret);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003525 return 1;
3526}
3527
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003528/* Prepends a string into the input side of channel. It returns the length of the
3529 * written string, or -1 if the channel is closed or if the buffer size is too
3530 * little for the data. 0 may be returned if nothing is copied. This function
3531 * does not yield.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003532 *
3533 * For a filter, the context is updated on success.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003534 */
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003535__LJMP static int hlua_channel_prepend(lua_State *L)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003536{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003537 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003538 struct filter *filter;
Christopher Faulet23976d92021-08-06 09:59:49 +02003539 const char *str;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003540 size_t sz, offset, len;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003541 int ret;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003542
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003543 MAY_LJMP(check_args(L, 2, "prepend"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003544 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003545 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
3546 if (IS_HTX_STRM(chn_strm(chn))) {
3547 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3548 WILL_LJMP(lua_error(L));
3549 }
3550
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003551 offset = co_data(chn);
3552 len = ci_data(chn);
3553
3554 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3555 if (filter && !hlua_filter_from_payload(filter))
3556 WILL_LJMP(lua_error(L));
3557
3558 ret = _hlua_channel_insert(chn, L, ist2(str, sz), offset);
3559 if (ret > 0 && filter) {
3560 struct hlua_flt_ctx *flt_ctx = filter->ctx;
3561
3562 flt_update_offsets(filter, chn, ret);
3563 flt_ctx->cur_len[CHN_IDX(chn)] += ret;
3564 }
3565
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003566 lua_pushinteger(L, ret);
3567 return 1;
3568}
3569
3570/* Inserts a given amount of input data at the given offset by a string
3571 * content. By default the string is appended at the end of input data. It
3572 * returns the length of the written string, or -1 if the channel is closed or
3573 * if the buffer size is too little for the data.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003574 *
3575 * For a filter, the context is updated on success.
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003576 */
3577__LJMP static int hlua_channel_insert_data(lua_State *L)
3578{
3579 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003580 struct filter *filter;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003581 const char *str;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003582 size_t sz, input, output;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003583 int ret, offset;
3584
3585 if (lua_gettop(L) < 2 || lua_gettop(L) > 3)
3586 WILL_LJMP(luaL_error(L, "'insert' expects at least 1 argument and at most 2 arguments"));
3587 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3588 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003589
3590 output = co_data(chn);
3591 input = ci_data(chn);
3592
3593 filter = hlua_channel_filter(L, 1, chn, &output, &input);
3594 if (filter && !hlua_filter_from_payload(filter))
3595 WILL_LJMP(lua_error(L));
3596
3597 offset = input + output;
3598 if (lua_gettop(L) > 2) {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003599 offset = MAY_LJMP(luaL_checkinteger(L, 3));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003600 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02003601 offset = MAX(0, (int)input + offset);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003602 offset += output;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003603 if (offset < output || offset > output + input) {
3604 lua_pushfstring(L, "offset out of range.");
3605 WILL_LJMP(lua_error(L));
3606 }
3607 }
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003608 if (IS_HTX_STRM(chn_strm(chn))) {
3609 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3610 WILL_LJMP(lua_error(L));
3611 }
3612
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003613 ret = _hlua_channel_insert(chn, L, ist2(str, sz), offset);
3614 if (ret > 0 && filter) {
3615 struct hlua_flt_ctx *flt_ctx = filter->ctx;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003616
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003617 flt_update_offsets(filter, chn, ret);
3618 flt_ctx->cur_len[CHN_IDX(chn)] += ret;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003619 }
3620
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003621 lua_pushinteger(L, ret);
3622 return 1;
3623}
3624/* Replaces a given amount of input data at the given offset by a string
3625 * content. By default all remaining data are removed (offset = 0 and len =
3626 * -1). It returns the length of the written string, or -1 if the channel is
3627 * closed or if the buffer size is too little for the data.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003628 *
3629 * For a filter, the context is updated on success.
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003630 */
3631__LJMP static int hlua_channel_set_data(lua_State *L)
3632{
3633 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003634 struct filter *filter;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003635 const char *str;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003636 size_t sz, input, output;
3637 int ret, offset, len;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003638
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003639 if (lua_gettop(L) < 2 || lua_gettop(L) > 4)
3640 WILL_LJMP(luaL_error(L, "'set' expects at least 1 argument and at most 3 arguments"));
3641 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3642 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003643
Christopher Faulet1bb6afa2021-03-08 17:57:53 +01003644 if (IS_HTX_STRM(chn_strm(chn))) {
Thierry Fournier77016da2020-08-15 14:35:51 +02003645 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
Christopher Faulet3f829a42018-12-13 21:56:45 +01003646 WILL_LJMP(lua_error(L));
Thierry Fournier77016da2020-08-15 14:35:51 +02003647 }
Christopher Faulet3f829a42018-12-13 21:56:45 +01003648
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003649 output = co_data(chn);
3650 input = ci_data(chn);
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003651
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003652 filter = hlua_channel_filter(L, 1, chn, &output, &input);
3653 if (filter && !hlua_filter_from_payload(filter))
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003654 WILL_LJMP(lua_error(L));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003655
3656 offset = output;
3657 if (lua_gettop(L) > 2) {
3658 offset = MAY_LJMP(luaL_checkinteger(L, 3));
3659 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02003660 offset = MAX(0, (int)input + offset);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003661 offset += output;
3662 if (offset < output || offset > input + output) {
3663 lua_pushfstring(L, "offset out of range.");
3664 WILL_LJMP(lua_error(L));
3665 }
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003666 }
3667
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003668 len = output + input - offset;
3669 if (lua_gettop(L) == 4) {
3670 len = MAY_LJMP(luaL_checkinteger(L, 4));
3671 if (!len)
3672 goto set;
3673 if (len == -1)
3674 len = output + input - offset;
3675 if (len < 0 || offset + len > output + input) {
3676 lua_pushfstring(L, "length out of range.");
3677 WILL_LJMP(lua_error(L));
3678 }
3679 }
3680
3681 set:
Christopher Faulet23976d92021-08-06 09:59:49 +02003682 /* Be sure we can copied the string once input data will be removed. */
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003683 if (sz > c_room(chn) + len)
Christopher Faulet23976d92021-08-06 09:59:49 +02003684 lua_pushinteger(L, -1);
3685 else {
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003686 _hlua_channel_delete(chn, offset, len);
3687 ret = _hlua_channel_insert(chn, L, ist2(str, sz), offset);
3688 if (filter) {
3689 struct hlua_flt_ctx *flt_ctx = filter->ctx;
3690
3691 len -= (ret > 0 ? ret : 0);
3692 flt_update_offsets(filter, chn, -len);
3693 flt_ctx->cur_len[CHN_IDX(chn)] -= len;
3694 }
3695
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003696 lua_pushinteger(L, ret);
Christopher Faulet23976d92021-08-06 09:59:49 +02003697 }
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003698 return 1;
3699}
3700
3701/* Removes a given amount of input data at the given offset. By default all
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003702 * input data are removed (offset = 0 and len = -1). It returns the amount of
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003703 * the removed data.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003704 *
3705 * For a filter, the context is updated on success.
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003706 */
3707__LJMP static int hlua_channel_del_data(lua_State *L)
3708{
3709 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003710 struct filter *filter;
3711 size_t input, output;
3712 int offset, len;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003713
3714 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
3715 WILL_LJMP(luaL_error(L, "'remove' expects at most 2 arguments"));
3716 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003717
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003718 if (IS_HTX_STRM(chn_strm(chn))) {
3719 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3720 WILL_LJMP(lua_error(L));
3721 }
3722
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003723 output = co_data(chn);
3724 input = ci_data(chn);
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003725
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003726 filter = hlua_channel_filter(L, 1, chn, &output, &input);
3727 if (filter && !hlua_filter_from_payload(filter))
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003728 WILL_LJMP(lua_error(L));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003729
3730 offset = output;
Boyang Lie0c54352022-05-10 17:47:23 +00003731 if (lua_gettop(L) > 1) {
3732 offset = MAY_LJMP(luaL_checkinteger(L, 2));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003733 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02003734 offset = MAX(0, (int)input + offset);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003735 offset += output;
3736 if (offset < output || offset > input + output) {
3737 lua_pushfstring(L, "offset out of range.");
3738 WILL_LJMP(lua_error(L));
3739 }
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003740 }
3741
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003742 len = output + input - offset;
Boyang Lie0c54352022-05-10 17:47:23 +00003743 if (lua_gettop(L) == 3) {
3744 len = MAY_LJMP(luaL_checkinteger(L, 3));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003745 if (!len)
3746 goto end;
3747 if (len == -1)
3748 len = output + input - offset;
3749 if (len < 0 || offset + len > output + input) {
3750 lua_pushfstring(L, "length out of range.");
3751 WILL_LJMP(lua_error(L));
3752 }
3753 }
3754
3755 _hlua_channel_delete(chn, offset, len);
3756 if (filter) {
3757 struct hlua_flt_ctx *flt_ctx = filter->ctx;
3758
3759 flt_update_offsets(filter, chn, -len);
3760 flt_ctx->cur_len[CHN_IDX(chn)] -= len;
3761 }
3762
3763 end:
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003764 lua_pushinteger(L, len);
Christopher Faulet23976d92021-08-06 09:59:49 +02003765 return 1;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003766}
3767
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003768/* Append data in the output side of the buffer. This data is immediately
3769 * sent. The function returns the amount of data written. If the buffer
3770 * cannot contain the data, the function yields. The function returns -1
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003771 * if the channel is closed.
3772 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003773__LJMP static int hlua_channel_send_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003774{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003775 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003776 struct filter *filter;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003777 const char *str;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003778 size_t offset, len, sz;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003779 int l, ret;
Thierry Fournier4234dbd2020-11-28 13:18:23 +01003780 struct hlua *hlua;
3781
3782 /* Get hlua struct, or NULL if we execute from main lua state */
3783 hlua = hlua_gethlua(L);
3784 if (!hlua) {
3785 lua_pushnil(L);
3786 return 1;
3787 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003788
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003789 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3790 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
3791 l = MAY_LJMP(luaL_checkinteger(L, 3));
Christopher Faulet3f829a42018-12-13 21:56:45 +01003792
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003793 offset = co_data(chn);
3794 len = ci_data(chn);
3795
3796 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3797 if (filter && !hlua_filter_from_payload(filter))
3798 WILL_LJMP(lua_error(L));
3799
3800
Willy Tarreau47860ed2015-03-10 14:07:50 +01003801 if (unlikely(channel_output_closed(chn))) {
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003802 lua_pushinteger(L, -1);
3803 return 1;
3804 }
3805
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003806 len = c_room(chn);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003807 if (len > sz -l) {
3808 if (filter) {
3809 lua_pushinteger(L, -1);
3810 return 1;
3811 }
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003812 len = sz - l;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003813 }
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01003814
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003815 ret = _hlua_channel_insert(chn, L, ist2(str, len), offset);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003816 if (ret == -1) {
3817 lua_pop(L, 1);
3818 lua_pushinteger(L, -1);
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01003819 return 1;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003820 }
3821 if (ret) {
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003822 if (filter) {
3823 struct hlua_flt_ctx *flt_ctx = filter->ctx;
3824
3825
3826 flt_update_offsets(filter, chn, ret);
3827 FLT_OFF(filter, chn) += ret;
3828 flt_ctx->cur_off[CHN_IDX(chn)] += ret;
3829 }
3830 else
3831 c_adv(chn, ret);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003832
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003833 l += ret;
3834 lua_pop(L, 1);
3835 lua_pushinteger(L, l);
3836 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003837
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003838 if (l < sz) {
3839 /* Yield only if the channel's output is not empty.
3840 * Otherwise it means we cannot add more data. */
3841 if (co_data(chn) == 0 || HLUA_CANT_YIELD(hlua_gethlua(L)))
Christopher Faulet2e60aa42021-08-05 11:58:37 +02003842 return 1;
3843
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003844 /* If we are waiting for space in the response buffer, we
3845 * must set the flag WAKERESWR. This flag required the task
3846 * wake up if any activity is detected on the response buffer.
3847 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01003848 if (chn->flags & CF_ISRESP)
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003849 HLUA_SET_WAKERESWR(hlua);
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01003850 else
3851 HLUA_SET_WAKEREQWR(hlua);
Willy Tarreau9635e032018-10-16 17:52:55 +02003852 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003853 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003854
3855 return 1;
3856}
3857
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05003858/* Just a wrapper of "_hlua_channel_send". This wrapper permits
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003859 * yield the LUA process, and resume it without checking the
3860 * input arguments.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003861 *
3862 * This function cannot be called from a filter.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003863 */
3864__LJMP static int hlua_channel_send(lua_State *L)
3865{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003866 struct channel *chn;
3867
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003868 MAY_LJMP(check_args(L, 2, "send"));
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003869 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3870 if (IS_HTX_STRM(chn_strm(chn))) {
3871 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3872 WILL_LJMP(lua_error(L));
3873 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003874 lua_pushinteger(L, 0);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003875 return MAY_LJMP(hlua_channel_send_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003876}
3877
3878/* This function forward and amount of butes. The data pass from
3879 * the input side of the buffer to the output side, and can be
3880 * forwarded. This function never fails.
3881 *
3882 * The Lua function takes an amount of bytes to be forwarded in
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05003883 * input. It returns the number of bytes forwarded.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003884 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003885__LJMP static int hlua_channel_forward_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003886{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003887 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003888 struct filter *filter;
3889 size_t offset, len, fwd;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003890 int l, max;
Thierry Fournier4234dbd2020-11-28 13:18:23 +01003891 struct hlua *hlua;
3892
3893 /* Get hlua struct, or NULL if we execute from main lua state */
3894 hlua = hlua_gethlua(L);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003895 if (!hlua) {
3896 lua_pushnil(L);
Thierry Fournier4234dbd2020-11-28 13:18:23 +01003897 return 1;
Thierry Fournier77016da2020-08-15 14:35:51 +02003898 }
Christopher Faulet3f829a42018-12-13 21:56:45 +01003899
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003900 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003901 fwd = MAY_LJMP(luaL_checkinteger(L, 2));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003902 l = MAY_LJMP(luaL_checkinteger(L, -1));
3903
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003904 offset = co_data(chn);
3905 len = ci_data(chn);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003906
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003907 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3908 if (filter && !hlua_filter_from_payload(filter))
3909 WILL_LJMP(lua_error(L));
3910
3911 max = fwd - l;
3912 if (max > len)
3913 max = len;
3914
3915 if (filter) {
3916 struct hlua_flt_ctx *flt_ctx = filter->ctx;
3917
3918 FLT_OFF(filter, chn) += max;
3919 flt_ctx->cur_off[CHN_IDX(chn)] += max;
3920 flt_ctx->cur_len[CHN_IDX(chn)] -= max;
3921 }
3922 else
3923 channel_forward(chn, max);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003924
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003925 l += max;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003926 lua_pop(L, 1);
3927 lua_pushinteger(L, l);
3928
3929 /* Check if it miss bytes to forward. */
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003930 if (l < fwd) {
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003931 /* The the input channel or the output channel are closed, we
3932 * must return the amount of data forwarded.
3933 */
Christopher Faulet2e60aa42021-08-05 11:58:37 +02003934 if (channel_input_closed(chn) || channel_output_closed(chn) || HLUA_CANT_YIELD(hlua_gethlua(L)))
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003935 return 1;
3936
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003937 /* If we are waiting for space data in the response buffer, we
3938 * must set the flag WAKERESWR. This flag required the task
3939 * wake up if any activity is detected on the response buffer.
3940 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01003941 if (chn->flags & CF_ISRESP)
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003942 HLUA_SET_WAKERESWR(hlua);
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01003943 else
3944 HLUA_SET_WAKEREQWR(hlua);
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003945
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003946 /* Otherwise, we can yield waiting for new data in the inpout side. */
Willy Tarreau9635e032018-10-16 17:52:55 +02003947 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_forward_yield, TICK_ETERNITY, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003948 }
3949
3950 return 1;
3951}
3952
3953/* Just check the input and prepare the stack for the previous
3954 * function "hlua_channel_forward_yield"
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003955 *
3956 * This function cannot be called from a filter.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003957 */
3958__LJMP static int hlua_channel_forward(lua_State *L)
3959{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003960 struct channel *chn;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003961
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003962 MAY_LJMP(check_args(L, 2, "forward"));
3963 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3964 if (IS_HTX_STRM(chn_strm(chn))) {
3965 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3966 WILL_LJMP(lua_error(L));
3967 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003968 lua_pushinteger(L, 0);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003969 return MAY_LJMP(hlua_channel_forward_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003970}
3971
3972/* Just returns the number of bytes available in the input
3973 * side of the buffer. This function never fails.
3974 */
3975__LJMP static int hlua_channel_get_in_len(lua_State *L)
3976{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003977 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003978 struct filter *filter;
3979 size_t output, input;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003980
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003981 MAY_LJMP(check_args(L, 1, "input"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003982 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003983
3984 output = co_data(chn);
3985 input = ci_data(chn);
3986 filter = hlua_channel_filter(L, 1, chn, &output, &input);
3987 if (filter || !IS_HTX_STRM(chn_strm(chn)))
3988 lua_pushinteger(L, input);
3989 else {
Christopher Fauleta3ceac12018-12-14 13:39:09 +01003990 struct htx *htx = htxbuf(&chn->buf);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003991
Christopher Fauleta3ceac12018-12-14 13:39:09 +01003992 lua_pushinteger(L, htx->data - co_data(chn));
3993 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003994 return 1;
3995}
3996
Thierry FOURNIER / OZON.IO65192f32016-11-07 15:28:40 +01003997/* Returns true if the channel is full. */
3998__LJMP static int hlua_channel_is_full(lua_State *L)
3999{
4000 struct channel *chn;
Thierry FOURNIER / OZON.IO65192f32016-11-07 15:28:40 +01004001
4002 MAY_LJMP(check_args(L, 1, "is_full"));
4003 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Faulet0ec740e2020-02-26 11:59:19 +01004004 /* ignore the reserve, we are not on a producer side (ie in an
4005 * applet).
4006 */
4007 lua_pushboolean(L, channel_full(chn, 0));
Thierry FOURNIER / OZON.IO65192f32016-11-07 15:28:40 +01004008 return 1;
4009}
4010
Christopher Faulet6a79fc12021-08-06 16:02:36 +02004011/* Returns true if the channel may still receive data. */
4012__LJMP static int hlua_channel_may_recv(lua_State *L)
4013{
4014 struct channel *chn;
4015
4016 MAY_LJMP(check_args(L, 1, "may_recv"));
4017 chn = MAY_LJMP(hlua_checkchannel(L, 1));
4018 lua_pushboolean(L, (!channel_input_closed(chn) && channel_may_recv(chn)));
4019 return 1;
4020}
4021
Christopher Faulet2ac9ba22020-02-25 10:15:50 +01004022/* Returns true if the channel is the response channel. */
4023__LJMP static int hlua_channel_is_resp(lua_State *L)
4024{
4025 struct channel *chn;
4026
4027 MAY_LJMP(check_args(L, 1, "is_resp"));
4028 chn = MAY_LJMP(hlua_checkchannel(L, 1));
4029
4030 lua_pushboolean(L, !!(chn->flags & CF_ISRESP));
4031 return 1;
4032}
4033
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004034/* Just returns the number of bytes available in the output
4035 * side of the buffer. This function never fails.
4036 */
4037__LJMP static int hlua_channel_get_out_len(lua_State *L)
4038{
Willy Tarreau47860ed2015-03-10 14:07:50 +01004039 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004040 size_t output, input;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004041
Christopher Faulet6a79fc12021-08-06 16:02:36 +02004042 MAY_LJMP(check_args(L, 1, "output"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004043 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004044
4045 output = co_data(chn);
4046 input = ci_data(chn);
4047 hlua_channel_filter(L, 1, chn, &output, &input);
4048
4049 lua_pushinteger(L, output);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004050 return 1;
4051}
4052
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004053/*
4054 *
4055 *
4056 * Class Fetches
4057 *
4058 *
4059 */
4060
4061/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02004062 * a class stream, otherwise it throws an error.
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004063 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004064__LJMP static struct hlua_smp *hlua_checkfetches(lua_State *L, int ud)
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004065{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004066 return MAY_LJMP(hlua_checkudata(L, ud, class_fetches_ref));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004067}
4068
4069/* This function creates and push in the stack a fetch object according
4070 * with a current TXN.
4071 */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004072static int hlua_fetches_new(lua_State *L, struct hlua_txn *txn, unsigned int flags)
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004073{
Willy Tarreau7073c472015-04-06 11:15:40 +02004074 struct hlua_smp *hsmp;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004075
4076 /* Check stack size. */
4077 if (!lua_checkstack(L, 3))
4078 return 0;
4079
4080 /* Create the object: obj[0] = userdata.
4081 * Note that the base of the Fetches object is the
4082 * transaction object.
4083 */
4084 lua_newtable(L);
Willy Tarreau7073c472015-04-06 11:15:40 +02004085 hsmp = lua_newuserdata(L, sizeof(*hsmp));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004086 lua_rawseti(L, -2, 0);
4087
Willy Tarreau7073c472015-04-06 11:15:40 +02004088 hsmp->s = txn->s;
4089 hsmp->p = txn->p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01004090 hsmp->dir = txn->dir;
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004091 hsmp->flags = flags;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004092
4093 /* Pop a class sesison metatable and affect it to the userdata. */
4094 lua_rawgeti(L, LUA_REGISTRYINDEX, class_fetches_ref);
4095 lua_setmetatable(L, -2);
4096
4097 return 1;
4098}
4099
4100/* This function is an LUA binding. It is called with each sample-fetch.
4101 * It uses closure argument to store the associated sample-fetch. It
4102 * returns only one argument or throws an error. An error is thrown
4103 * only if an error is encountered during the argument parsing. If
4104 * the "sample-fetch" function fails, nil is returned.
4105 */
4106__LJMP static int hlua_run_sample_fetch(lua_State *L)
4107{
Willy Tarreaub2ccb562015-04-06 11:11:15 +02004108 struct hlua_smp *hsmp;
Willy Tarreau2ec22742015-03-10 14:27:20 +01004109 struct sample_fetch *f;
Frédéric Lécaillef874a832018-06-15 13:56:04 +02004110 struct arg args[ARGM_NBARGS + 1] = {{0}};
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004111 int i;
4112 struct sample smp;
4113
4114 /* Get closure arguments. */
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004115 f = lua_touserdata(L, lua_upvalueindex(1));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004116
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004117 /* Get traditional arguments. */
Willy Tarreaub2ccb562015-04-06 11:11:15 +02004118 hsmp = MAY_LJMP(hlua_checkfetches(L, 1));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004119
Thierry FOURNIERca988662015-12-20 18:43:03 +01004120 /* Check execution authorization. */
4121 if (f->use & SMP_USE_HTTP_ANY &&
4122 !(hsmp->flags & HLUA_F_MAY_USE_HTTP)) {
4123 lua_pushfstring(L, "the sample-fetch '%s' needs an HTTP parser which "
4124 "is not available in Lua services", f->kw);
4125 WILL_LJMP(lua_error(L));
4126 }
4127
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004128 /* Get extra arguments. */
4129 for (i = 0; i < lua_gettop(L) - 1; i++) {
4130 if (i >= ARGM_NBARGS)
4131 break;
4132 hlua_lua2arg(L, i + 2, &args[i]);
4133 }
4134 args[i].type = ARGT_STOP;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004135 args[i].data.str.area = NULL;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004136
4137 /* Check arguments. */
Willy Tarreaub2ccb562015-04-06 11:11:15 +02004138 MAY_LJMP(hlua_lua2arg_check(L, 2, args, f->arg_mask, hsmp->p));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004139
4140 /* Run the special args checker. */
Willy Tarreau2ec22742015-03-10 14:27:20 +01004141 if (f->val_args && !f->val_args(args, NULL)) {
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004142 lua_pushfstring(L, "error in arguments");
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004143 goto error;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004144 }
4145
4146 /* Initialise the sample. */
4147 memset(&smp, 0, sizeof(smp));
4148
4149 /* Run the sample fetch process. */
Willy Tarreau1777ea62016-03-10 16:15:46 +01004150 smp_set_owner(&smp, hsmp->p, hsmp->s->sess, hsmp->s, hsmp->dir & SMP_OPT_DIR);
Thierry FOURNIER0786d052015-05-11 15:42:45 +02004151 if (!f->process(args, &smp, f->kw, f->private)) {
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004152 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004153 lua_pushstring(L, "");
4154 else
4155 lua_pushnil(L);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004156 goto end;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004157 }
4158
4159 /* Convert the returned sample in lua value. */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004160 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004161 hlua_smp2lua_str(L, &smp);
4162 else
4163 hlua_smp2lua(L, &smp);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004164
4165 end:
Willy Tarreauee0d7272021-07-16 10:26:56 +02004166 free_args(args);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004167 return 1;
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004168
4169 error:
Willy Tarreauee0d7272021-07-16 10:26:56 +02004170 free_args(args);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004171 WILL_LJMP(lua_error(L));
4172 return 0; /* Never reached */
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004173}
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004174
4175/*
4176 *
4177 *
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004178 * Class Converters
4179 *
4180 *
4181 */
4182
4183/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02004184 * a class stream, otherwise it throws an error.
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004185 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004186__LJMP static struct hlua_smp *hlua_checkconverters(lua_State *L, int ud)
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004187{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004188 return MAY_LJMP(hlua_checkudata(L, ud, class_converters_ref));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004189}
4190
4191/* This function creates and push in the stack a Converters object
4192 * according with a current TXN.
4193 */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004194static int hlua_converters_new(lua_State *L, struct hlua_txn *txn, unsigned int flags)
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004195{
Willy Tarreau7073c472015-04-06 11:15:40 +02004196 struct hlua_smp *hsmp;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004197
4198 /* Check stack size. */
4199 if (!lua_checkstack(L, 3))
4200 return 0;
4201
4202 /* Create the object: obj[0] = userdata.
4203 * Note that the base of the Converters object is the
4204 * same than the TXN object.
4205 */
4206 lua_newtable(L);
Willy Tarreau7073c472015-04-06 11:15:40 +02004207 hsmp = lua_newuserdata(L, sizeof(*hsmp));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004208 lua_rawseti(L, -2, 0);
4209
Willy Tarreau7073c472015-04-06 11:15:40 +02004210 hsmp->s = txn->s;
4211 hsmp->p = txn->p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01004212 hsmp->dir = txn->dir;
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004213 hsmp->flags = flags;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004214
Willy Tarreau87b09662015-04-03 00:22:06 +02004215 /* Pop a class stream metatable and affect it to the table. */
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004216 lua_rawgeti(L, LUA_REGISTRYINDEX, class_converters_ref);
4217 lua_setmetatable(L, -2);
4218
4219 return 1;
4220}
4221
4222/* This function is an LUA binding. It is called with each converter.
4223 * It uses closure argument to store the associated converter. It
4224 * returns only one argument or throws an error. An error is thrown
4225 * only if an error is encountered during the argument parsing. If
4226 * the converter function function fails, nil is returned.
4227 */
4228__LJMP static int hlua_run_sample_conv(lua_State *L)
4229{
Willy Tarreauda5f1082015-04-06 11:17:13 +02004230 struct hlua_smp *hsmp;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004231 struct sample_conv *conv;
Frédéric Lécaillef874a832018-06-15 13:56:04 +02004232 struct arg args[ARGM_NBARGS + 1] = {{0}};
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004233 int i;
4234 struct sample smp;
4235
4236 /* Get closure arguments. */
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004237 conv = lua_touserdata(L, lua_upvalueindex(1));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004238
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004239 /* Get traditional arguments. */
Willy Tarreauda5f1082015-04-06 11:17:13 +02004240 hsmp = MAY_LJMP(hlua_checkconverters(L, 1));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004241
4242 /* Get extra arguments. */
4243 for (i = 0; i < lua_gettop(L) - 2; i++) {
4244 if (i >= ARGM_NBARGS)
4245 break;
4246 hlua_lua2arg(L, i + 3, &args[i]);
4247 }
4248 args[i].type = ARGT_STOP;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004249 args[i].data.str.area = NULL;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004250
4251 /* Check arguments. */
Willy Tarreauda5f1082015-04-06 11:17:13 +02004252 MAY_LJMP(hlua_lua2arg_check(L, 3, args, conv->arg_mask, hsmp->p));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004253
4254 /* Run the special args checker. */
4255 if (conv->val_args && !conv->val_args(args, conv, "", 0, NULL)) {
4256 hlua_pusherror(L, "error in arguments");
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004257 goto error;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004258 }
4259
4260 /* Initialise the sample. */
Amaury Denoyellebc0af6a2020-10-29 17:21:20 +01004261 memset(&smp, 0, sizeof(smp));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004262 if (!hlua_lua2smp(L, 2, &smp)) {
4263 hlua_pusherror(L, "error in the input argument");
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004264 goto error;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004265 }
4266
Willy Tarreau1777ea62016-03-10 16:15:46 +01004267 smp_set_owner(&smp, hsmp->p, hsmp->s->sess, hsmp->s, hsmp->dir & SMP_OPT_DIR);
4268
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004269 /* Apply expected cast. */
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02004270 if (!sample_casts[smp.data.type][conv->in_type]) {
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004271 hlua_pusherror(L, "invalid input argument: cannot cast '%s' to '%s'",
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02004272 smp_to_type[smp.data.type], smp_to_type[conv->in_type]);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004273 goto error;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004274 }
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02004275 if (sample_casts[smp.data.type][conv->in_type] != c_none &&
4276 !sample_casts[smp.data.type][conv->in_type](&smp)) {
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004277 hlua_pusherror(L, "error during the input argument casting");
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004278 goto error;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004279 }
4280
4281 /* Run the sample conversion process. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02004282 if (!conv->process(args, &smp, conv->private)) {
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004283 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004284 lua_pushstring(L, "");
4285 else
Willy Tarreaua678b432015-08-28 10:14:59 +02004286 lua_pushnil(L);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004287 goto end;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004288 }
4289
4290 /* Convert the returned sample in lua value. */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004291 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004292 hlua_smp2lua_str(L, &smp);
4293 else
4294 hlua_smp2lua(L, &smp);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004295 end:
Willy Tarreauee0d7272021-07-16 10:26:56 +02004296 free_args(args);
Willy Tarreaua678b432015-08-28 10:14:59 +02004297 return 1;
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004298
4299 error:
Willy Tarreauee0d7272021-07-16 10:26:56 +02004300 free_args(args);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004301 WILL_LJMP(lua_error(L));
4302 return 0; /* Never reached */
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004303}
4304
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004305/*
4306 *
4307 *
4308 * Class AppletTCP
4309 *
4310 *
4311 */
4312
4313/* Returns a struct hlua_txn if the stack entry "ud" is
4314 * a class stream, otherwise it throws an error.
4315 */
4316__LJMP static struct hlua_appctx *hlua_checkapplet_tcp(lua_State *L, int ud)
4317{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004318 return MAY_LJMP(hlua_checkudata(L, ud, class_applet_tcp_ref));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004319}
4320
4321/* This function creates and push in the stack an Applet object
4322 * according with a current TXN.
4323 */
4324static int hlua_applet_tcp_new(lua_State *L, struct appctx *ctx)
4325{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004326 struct hlua_appctx *luactx;
Willy Tarreau0698c802022-05-11 14:09:57 +02004327 struct stream *s = appctx_strm(ctx);
Christopher Faulet2da02ae2022-02-24 13:45:27 +01004328 struct proxy *p;
4329
4330 ALREADY_CHECKED(s);
4331 p = s->be;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004332
4333 /* Check stack size. */
4334 if (!lua_checkstack(L, 3))
4335 return 0;
4336
4337 /* Create the object: obj[0] = userdata.
4338 * Note that the base of the Converters object is the
4339 * same than the TXN object.
4340 */
4341 lua_newtable(L);
Willy Tarreau7e702d12021-04-28 17:59:21 +02004342 luactx = lua_newuserdata(L, sizeof(*luactx));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004343 lua_rawseti(L, -2, 0);
Willy Tarreau7e702d12021-04-28 17:59:21 +02004344 luactx->appctx = ctx;
4345 luactx->htxn.s = s;
4346 luactx->htxn.p = p;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004347
4348 /* Create the "f" field that contains a list of fetches. */
4349 lua_pushstring(L, "f");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004350 if (!hlua_fetches_new(L, &luactx->htxn, 0))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004351 return 0;
4352 lua_settable(L, -3);
4353
4354 /* Create the "sf" field that contains a list of stringsafe fetches. */
4355 lua_pushstring(L, "sf");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004356 if (!hlua_fetches_new(L, &luactx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004357 return 0;
4358 lua_settable(L, -3);
4359
4360 /* Create the "c" field that contains a list of converters. */
4361 lua_pushstring(L, "c");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004362 if (!hlua_converters_new(L, &luactx->htxn, 0))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004363 return 0;
4364 lua_settable(L, -3);
4365
4366 /* Create the "sc" field that contains a list of stringsafe converters. */
4367 lua_pushstring(L, "sc");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004368 if (!hlua_converters_new(L, &luactx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004369 return 0;
4370 lua_settable(L, -3);
4371
4372 /* Pop a class stream metatable and affect it to the table. */
4373 lua_rawgeti(L, LUA_REGISTRYINDEX, class_applet_tcp_ref);
4374 lua_setmetatable(L, -2);
4375
4376 return 1;
4377}
4378
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004379__LJMP static int hlua_applet_tcp_set_var(lua_State *L)
4380{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004381 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004382 struct stream *s;
4383 const char *name;
4384 size_t len;
4385 struct sample smp;
4386
Tim Duesterhus4e172c92020-05-19 13:49:42 +02004387 if (lua_gettop(L) < 3 || lua_gettop(L) > 4)
4388 WILL_LJMP(luaL_error(L, "'set_var' needs between 3 and 4 arguments"));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004389
4390 /* It is useles to retrieve the stream, but this function
4391 * runs only in a stream context.
4392 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004393 luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004394 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02004395 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004396
4397 /* Converts the third argument in a sample. */
Amaury Denoyellebc0af6a2020-10-29 17:21:20 +01004398 memset(&smp, 0, sizeof(smp));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004399 hlua_lua2smp(L, 3, &smp);
4400
4401 /* Store the sample in a variable. */
4402 smp_set_owner(&smp, s->be, s->sess, s, 0);
Tim Duesterhus4e172c92020-05-19 13:49:42 +02004403
4404 if (lua_gettop(L) == 4 && lua_toboolean(L, 4))
4405 lua_pushboolean(L, vars_set_by_name_ifexist(name, len, &smp) != 0);
4406 else
4407 lua_pushboolean(L, vars_set_by_name(name, len, &smp) != 0);
4408
Tim Duesterhus84ebc132020-05-19 13:49:41 +02004409 return 1;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004410}
4411
4412__LJMP static int hlua_applet_tcp_unset_var(lua_State *L)
4413{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004414 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004415 struct stream *s;
4416 const char *name;
4417 size_t len;
4418 struct sample smp;
4419
4420 MAY_LJMP(check_args(L, 2, "unset_var"));
4421
4422 /* It is useles to retrieve the stream, but this function
4423 * runs only in a stream context.
4424 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004425 luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004426 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02004427 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004428
4429 /* Unset the variable. */
4430 smp_set_owner(&smp, s->be, s->sess, s, 0);
Tim Duesterhus84ebc132020-05-19 13:49:41 +02004431 lua_pushboolean(L, vars_unset_by_name_ifexist(name, len, &smp) != 0);
4432 return 1;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004433}
4434
4435__LJMP static int hlua_applet_tcp_get_var(lua_State *L)
4436{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004437 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004438 struct stream *s;
4439 const char *name;
4440 size_t len;
4441 struct sample smp;
4442
4443 MAY_LJMP(check_args(L, 2, "get_var"));
4444
4445 /* It is useles to retrieve the stream, but this function
4446 * runs only in a stream context.
4447 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004448 luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004449 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02004450 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004451
4452 smp_set_owner(&smp, s->be, s->sess, s, 0);
Willy Tarreaue352b9d2021-09-03 11:52:38 +02004453 if (!vars_get_by_name(name, len, &smp, NULL)) {
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004454 lua_pushnil(L);
4455 return 1;
4456 }
4457
4458 return hlua_smp2lua(L, &smp);
4459}
4460
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004461__LJMP static int hlua_applet_tcp_set_priv(lua_State *L)
4462{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004463 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
4464 struct stream *s = luactx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01004465 struct hlua *hlua;
4466
4467 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01004468 if (!s->hlua)
4469 return 0;
4470 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004471
4472 MAY_LJMP(check_args(L, 2, "set_priv"));
4473
4474 /* Remove previous value. */
Thierry FOURNIERe068b602017-04-26 13:27:05 +02004475 luaL_unref(L, LUA_REGISTRYINDEX, hlua->Mref);
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004476
4477 /* Get and store new value. */
4478 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
4479 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
4480
4481 return 0;
4482}
4483
4484__LJMP static int hlua_applet_tcp_get_priv(lua_State *L)
4485{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004486 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
4487 struct stream *s = luactx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01004488 struct hlua *hlua;
4489
4490 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01004491 if (!s->hlua) {
4492 lua_pushnil(L);
4493 return 1;
4494 }
4495 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004496
4497 /* Push configuration index in the stack. */
4498 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
4499
4500 return 1;
4501}
4502
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004503/* If expected data not yet available, it returns a yield. This function
4504 * consumes the data in the buffer. It returns a string containing the
4505 * data. This string can be empty.
4506 */
4507__LJMP static int hlua_applet_tcp_getline_yield(lua_State *L, int status, lua_KContext ctx)
4508{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004509 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Willy Tarreauc12b3212022-05-27 11:08:15 +02004510 struct stconn *sc = appctx_sc(luactx->appctx);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004511 int ret;
Willy Tarreau206ba832018-06-14 15:27:31 +02004512 const char *blk1;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004513 size_t len1;
Willy Tarreau206ba832018-06-14 15:27:31 +02004514 const char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004515 size_t len2;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004516
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004517 /* Read the maximum amount of data available. */
Willy Tarreau3e7be362022-05-27 10:35:27 +02004518 ret = co_getline_nc(sc_oc(sc), &blk1, &len1, &blk2, &len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004519
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004520 /* Data not yet available. return yield. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004521 if (ret == 0) {
Willy Tarreau90e8b452022-05-25 18:21:43 +02004522 applet_need_more_data(luactx->appctx);
Willy Tarreau9635e032018-10-16 17:52:55 +02004523 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_getline_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004524 }
4525
4526 /* End of data: commit the total strings and return. */
4527 if (ret < 0) {
Willy Tarreau7e702d12021-04-28 17:59:21 +02004528 luaL_pushresult(&luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004529 return 1;
4530 }
4531
4532 /* Ensure that the block 2 length is usable. */
4533 if (ret == 1)
4534 len2 = 0;
4535
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -07004536 /* don't check the max length read and don't check. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004537 luaL_addlstring(&luactx->b, blk1, len1);
4538 luaL_addlstring(&luactx->b, blk2, len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004539
4540 /* Consume input channel output buffer data. */
Willy Tarreau3e7be362022-05-27 10:35:27 +02004541 co_skip(sc_oc(sc), len1 + len2);
Willy Tarreau7e702d12021-04-28 17:59:21 +02004542 luaL_pushresult(&luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004543 return 1;
4544}
4545
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004546/* Check arguments for the function "hlua_channel_get_yield". */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004547__LJMP static int hlua_applet_tcp_getline(lua_State *L)
4548{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004549 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004550
4551 /* Initialise the string catenation. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004552 luaL_buffinit(L, &luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004553
4554 return MAY_LJMP(hlua_applet_tcp_getline_yield(L, 0, 0));
4555}
4556
4557/* If expected data not yet available, it returns a yield. This function
4558 * consumes the data in the buffer. It returns a string containing the
4559 * data. This string can be empty.
4560 */
4561__LJMP static int hlua_applet_tcp_recv_yield(lua_State *L, int status, lua_KContext ctx)
4562{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004563 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Willy Tarreauc12b3212022-05-27 11:08:15 +02004564 struct stconn *sc = appctx_sc(luactx->appctx);
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004565 size_t len = MAY_LJMP(luaL_checkinteger(L, 2));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004566 int ret;
Willy Tarreau206ba832018-06-14 15:27:31 +02004567 const char *blk1;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004568 size_t len1;
Willy Tarreau206ba832018-06-14 15:27:31 +02004569 const char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004570 size_t len2;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004571
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004572 /* Read the maximum amount of data available. */
Willy Tarreau3e7be362022-05-27 10:35:27 +02004573 ret = co_getblk_nc(sc_oc(sc), &blk1, &len1, &blk2, &len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004574
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004575 /* Data not yet available. return yield. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004576 if (ret == 0) {
Willy Tarreau90e8b452022-05-25 18:21:43 +02004577 applet_need_more_data(luactx->appctx);
Willy Tarreau9635e032018-10-16 17:52:55 +02004578 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004579 }
4580
4581 /* End of data: commit the total strings and return. */
4582 if (ret < 0) {
Willy Tarreau7e702d12021-04-28 17:59:21 +02004583 luaL_pushresult(&luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004584 return 1;
4585 }
4586
4587 /* Ensure that the block 2 length is usable. */
4588 if (ret == 1)
4589 len2 = 0;
4590
4591 if (len == -1) {
4592
4593 /* If len == -1, catenate all the data avalaile and
4594 * yield because we want to get all the data until
4595 * the end of data stream.
4596 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004597 luaL_addlstring(&luactx->b, blk1, len1);
4598 luaL_addlstring(&luactx->b, blk2, len2);
Willy Tarreau3e7be362022-05-27 10:35:27 +02004599 co_skip(sc_oc(sc), len1 + len2);
Willy Tarreau90e8b452022-05-25 18:21:43 +02004600 applet_need_more_data(luactx->appctx);
Willy Tarreau9635e032018-10-16 17:52:55 +02004601 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004602
4603 } else {
4604
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05004605 /* Copy the first block caping to the length required. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004606 if (len1 > len)
4607 len1 = len;
Willy Tarreau7e702d12021-04-28 17:59:21 +02004608 luaL_addlstring(&luactx->b, blk1, len1);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004609 len -= len1;
4610
4611 /* Copy the second block. */
4612 if (len2 > len)
4613 len2 = len;
Willy Tarreau7e702d12021-04-28 17:59:21 +02004614 luaL_addlstring(&luactx->b, blk2, len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004615 len -= len2;
4616
4617 /* Consume input channel output buffer data. */
Willy Tarreau3e7be362022-05-27 10:35:27 +02004618 co_skip(sc_oc(sc), len1 + len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004619
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004620 /* If there is no other data available, yield waiting for new data. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004621 if (len > 0) {
4622 lua_pushinteger(L, len);
4623 lua_replace(L, 2);
Willy Tarreau90e8b452022-05-25 18:21:43 +02004624 applet_need_more_data(luactx->appctx);
Willy Tarreau9635e032018-10-16 17:52:55 +02004625 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004626 }
4627
4628 /* return the result. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004629 luaL_pushresult(&luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004630 return 1;
4631 }
4632
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004633 /* we never execute this */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004634 hlua_pusherror(L, "Lua: internal error");
4635 WILL_LJMP(lua_error(L));
4636 return 0;
4637}
4638
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004639/* Check arguments for the function "hlua_channel_get_yield". */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004640__LJMP static int hlua_applet_tcp_recv(lua_State *L)
4641{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004642 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004643 int len = -1;
4644
4645 if (lua_gettop(L) > 2)
4646 WILL_LJMP(luaL_error(L, "The 'recv' function requires between 1 and 2 arguments."));
4647 if (lua_gettop(L) >= 2) {
4648 len = MAY_LJMP(luaL_checkinteger(L, 2));
4649 lua_pop(L, 1);
4650 }
4651
4652 /* Confirm or set the required length */
4653 lua_pushinteger(L, len);
4654
4655 /* Initialise the string catenation. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004656 luaL_buffinit(L, &luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004657
4658 return MAY_LJMP(hlua_applet_tcp_recv_yield(L, 0, 0));
4659}
4660
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004661/* Append data in the output side of the buffer. This data is immediately
4662 * sent. The function returns the amount of data written. If the buffer
4663 * cannot contain the data, the function yields. The function returns -1
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004664 * if the channel is closed.
4665 */
4666__LJMP static int hlua_applet_tcp_send_yield(lua_State *L, int status, lua_KContext ctx)
4667{
4668 size_t len;
Willy Tarreau7e702d12021-04-28 17:59:21 +02004669 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004670 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
4671 int l = MAY_LJMP(luaL_checkinteger(L, 3));
Willy Tarreauc12b3212022-05-27 11:08:15 +02004672 struct stconn *sc = appctx_sc(luactx->appctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02004673 struct channel *chn = sc_ic(sc);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004674 int max;
4675
4676 /* Get the max amount of data which can write as input in the channel. */
4677 max = channel_recv_max(chn);
4678 if (max > (len - l))
4679 max = len - l;
4680
4681 /* Copy data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02004682 ci_putblk(chn, str + l, max);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004683
4684 /* update counters. */
4685 l += max;
4686 lua_pop(L, 1);
4687 lua_pushinteger(L, l);
4688
4689 /* If some data is not send, declares the situation to the
4690 * applet, and returns a yield.
4691 */
4692 if (l < len) {
Willy Tarreau3e7be362022-05-27 10:35:27 +02004693 sc_need_room(sc);
Willy Tarreau9635e032018-10-16 17:52:55 +02004694 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004695 }
4696
4697 return 1;
4698}
4699
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05004700/* Just a wrapper of "hlua_applet_tcp_send_yield". This wrapper permits
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004701 * yield the LUA process, and resume it without checking the
4702 * input arguments.
4703 */
4704__LJMP static int hlua_applet_tcp_send(lua_State *L)
4705{
4706 MAY_LJMP(check_args(L, 2, "send"));
4707 lua_pushinteger(L, 0);
4708
4709 return MAY_LJMP(hlua_applet_tcp_send_yield(L, 0, 0));
4710}
4711
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004712/*
4713 *
4714 *
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004715 * Class AppletHTTP
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004716 *
4717 *
4718 */
4719
4720/* Returns a struct hlua_txn if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02004721 * a class stream, otherwise it throws an error.
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004722 */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004723__LJMP static struct hlua_appctx *hlua_checkapplet_http(lua_State *L, int ud)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004724{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004725 return MAY_LJMP(hlua_checkudata(L, ud, class_applet_http_ref));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004726}
4727
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004728/* This function creates and push in the stack an Applet object
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004729 * according with a current TXN.
Willy Tarreauaa229cc2022-05-06 14:26:10 +02004730 * It relies on the caller to have already reserved the room in ctx->svcctx
4731 * for the local storage of hlua_http_ctx.
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004732 */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004733static int hlua_applet_http_new(lua_State *L, struct appctx *ctx)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004734{
Willy Tarreauaa229cc2022-05-06 14:26:10 +02004735 struct hlua_http_ctx *http_ctx = ctx->svcctx;
Willy Tarreau7e702d12021-04-28 17:59:21 +02004736 struct hlua_appctx *luactx;
Thierry FOURNIER841475e2015-12-11 17:10:09 +01004737 struct hlua_txn htxn;
Willy Tarreau0698c802022-05-11 14:09:57 +02004738 struct stream *s = appctx_strm(ctx);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004739 struct proxy *px = s->be;
Christopher Fauleta2097962019-07-15 16:25:33 +02004740 struct htx *htx;
4741 struct htx_blk *blk;
4742 struct htx_sl *sl;
4743 struct ist path;
4744 unsigned long long len = 0;
4745 int32_t pos;
Amaury Denoyellec453f952021-07-06 11:40:12 +02004746 struct http_uri_parser parser;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004747
4748 /* Check stack size. */
4749 if (!lua_checkstack(L, 3))
4750 return 0;
4751
4752 /* Create the object: obj[0] = userdata.
4753 * Note that the base of the Converters object is the
4754 * same than the TXN object.
4755 */
4756 lua_newtable(L);
Willy Tarreau7e702d12021-04-28 17:59:21 +02004757 luactx = lua_newuserdata(L, sizeof(*luactx));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004758 lua_rawseti(L, -2, 0);
Willy Tarreau7e702d12021-04-28 17:59:21 +02004759 luactx->appctx = ctx;
Willy Tarreauaa229cc2022-05-06 14:26:10 +02004760 http_ctx->status = 200; /* Default status code returned. */
4761 http_ctx->reason = NULL; /* Use default reason based on status */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004762 luactx->htxn.s = s;
4763 luactx->htxn.p = px;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004764
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004765 /* Create the "f" field that contains a list of fetches. */
4766 lua_pushstring(L, "f");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004767 if (!hlua_fetches_new(L, &luactx->htxn, 0))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004768 return 0;
4769 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004770
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004771 /* Create the "sf" field that contains a list of stringsafe fetches. */
4772 lua_pushstring(L, "sf");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004773 if (!hlua_fetches_new(L, &luactx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004774 return 0;
4775 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004776
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004777 /* Create the "c" field that contains a list of converters. */
4778 lua_pushstring(L, "c");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004779 if (!hlua_converters_new(L, &luactx->htxn, 0))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004780 return 0;
4781 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004782
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004783 /* Create the "sc" field that contains a list of stringsafe converters. */
4784 lua_pushstring(L, "sc");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004785 if (!hlua_converters_new(L, &luactx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004786 return 0;
4787 lua_settable(L, -3);
Willy Tarreaueee5b512015-04-03 23:46:31 +02004788
Christopher Fauleta2097962019-07-15 16:25:33 +02004789 htx = htxbuf(&s->req.buf);
4790 blk = htx_get_first_blk(htx);
Christopher Fauletea009732019-11-18 15:50:25 +01004791 BUG_ON(!blk || htx_get_blk_type(blk) != HTX_BLK_REQ_SL);
Christopher Fauleta2097962019-07-15 16:25:33 +02004792 sl = htx_get_blk_ptr(htx, blk);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004793
Christopher Fauleta2097962019-07-15 16:25:33 +02004794 /* Stores the request method. */
4795 lua_pushstring(L, "method");
4796 lua_pushlstring(L, HTX_SL_REQ_MPTR(sl), HTX_SL_REQ_MLEN(sl));
4797 lua_settable(L, -3);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004798
Christopher Fauleta2097962019-07-15 16:25:33 +02004799 /* Stores the http version. */
4800 lua_pushstring(L, "version");
4801 lua_pushlstring(L, HTX_SL_REQ_VPTR(sl), HTX_SL_REQ_VLEN(sl));
4802 lua_settable(L, -3);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004803
Christopher Fauleta2097962019-07-15 16:25:33 +02004804 /* creates an array of headers. hlua_http_get_headers() crates and push
4805 * the array on the top of the stack.
4806 */
4807 lua_pushstring(L, "headers");
4808 htxn.s = s;
4809 htxn.p = px;
4810 htxn.dir = SMP_OPT_DIR_REQ;
Christopher Faulet9d1332b2020-02-24 16:46:16 +01004811 if (!hlua_http_get_headers(L, &htxn.s->txn->req))
Christopher Fauleta2097962019-07-15 16:25:33 +02004812 return 0;
4813 lua_settable(L, -3);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004814
Amaury Denoyellec453f952021-07-06 11:40:12 +02004815 parser = http_uri_parser_init(htx_sl_req_uri(sl));
4816 path = http_parse_path(&parser);
Tim Duesterhused526372020-03-05 17:56:33 +01004817 if (isttest(path)) {
Christopher Fauleta2097962019-07-15 16:25:33 +02004818 char *p, *q, *end;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004819
Christopher Fauleta2097962019-07-15 16:25:33 +02004820 p = path.ptr;
Tim Duesterhus4c8f75f2021-11-06 15:14:44 +01004821 end = istend(path);
Christopher Fauleta2097962019-07-15 16:25:33 +02004822 q = p;
4823 while (q < end && *q != '?')
4824 q++;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004825
Thierry FOURNIER7d388632017-02-22 02:06:16 +01004826 /* Stores the request path. */
Christopher Fauleta2097962019-07-15 16:25:33 +02004827 lua_pushstring(L, "path");
4828 lua_pushlstring(L, p, q - p);
Thierry FOURNIER7d388632017-02-22 02:06:16 +01004829 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01004830
Christopher Fauleta2097962019-07-15 16:25:33 +02004831 /* Stores the query string. */
4832 lua_pushstring(L, "qs");
4833 if (*q == '?')
4834 q++;
4835 lua_pushlstring(L, q, end - q);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004836 lua_settable(L, -3);
Christopher Fauleta2097962019-07-15 16:25:33 +02004837 }
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004838
Christopher Fauleta2097962019-07-15 16:25:33 +02004839 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
4840 struct htx_blk *blk = htx_get_blk(htx, pos);
4841 enum htx_blk_type type = htx_get_blk_type(blk);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004842
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01004843 if (type == HTX_BLK_TLR || type == HTX_BLK_EOT)
Christopher Fauleta2097962019-07-15 16:25:33 +02004844 break;
4845 if (type == HTX_BLK_DATA)
4846 len += htx_get_blksz(blk);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004847 }
Christopher Fauleta2097962019-07-15 16:25:33 +02004848 if (htx->extra != ULLONG_MAX)
4849 len += htx->extra;
4850
4851 /* Stores the request path. */
4852 lua_pushstring(L, "length");
4853 lua_pushinteger(L, len);
4854 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01004855
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004856 /* Create an empty array of HTTP request headers. */
4857 lua_pushstring(L, "response");
4858 lua_newtable(L);
4859 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01004860
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004861 /* Pop a class stream metatable and affect it to the table. */
4862 lua_rawgeti(L, LUA_REGISTRYINDEX, class_applet_http_ref);
4863 lua_setmetatable(L, -2);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004864
4865 return 1;
4866}
4867
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004868__LJMP static int hlua_applet_http_set_var(lua_State *L)
4869{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004870 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004871 struct stream *s;
4872 const char *name;
4873 size_t len;
4874 struct sample smp;
4875
Tim Duesterhus4e172c92020-05-19 13:49:42 +02004876 if (lua_gettop(L) < 3 || lua_gettop(L) > 4)
4877 WILL_LJMP(luaL_error(L, "'set_var' needs between 3 and 4 arguments"));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004878
4879 /* It is useles to retrieve the stream, but this function
4880 * runs only in a stream context.
4881 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004882 luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004883 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02004884 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004885
4886 /* Converts the third argument in a sample. */
Amaury Denoyellebc0af6a2020-10-29 17:21:20 +01004887 memset(&smp, 0, sizeof(smp));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004888 hlua_lua2smp(L, 3, &smp);
4889
4890 /* Store the sample in a variable. */
4891 smp_set_owner(&smp, s->be, s->sess, s, 0);
Tim Duesterhus4e172c92020-05-19 13:49:42 +02004892
4893 if (lua_gettop(L) == 4 && lua_toboolean(L, 4))
4894 lua_pushboolean(L, vars_set_by_name_ifexist(name, len, &smp) != 0);
4895 else
4896 lua_pushboolean(L, vars_set_by_name(name, len, &smp) != 0);
4897
Tim Duesterhus84ebc132020-05-19 13:49:41 +02004898 return 1;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004899}
4900
4901__LJMP static int hlua_applet_http_unset_var(lua_State *L)
4902{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004903 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004904 struct stream *s;
4905 const char *name;
4906 size_t len;
4907 struct sample smp;
4908
4909 MAY_LJMP(check_args(L, 2, "unset_var"));
4910
4911 /* It is useles to retrieve the stream, but this function
4912 * runs only in a stream context.
4913 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004914 luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004915 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02004916 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004917
4918 /* Unset the variable. */
4919 smp_set_owner(&smp, s->be, s->sess, s, 0);
Tim Duesterhus84ebc132020-05-19 13:49:41 +02004920 lua_pushboolean(L, vars_unset_by_name_ifexist(name, len, &smp) != 0);
4921 return 1;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004922}
4923
4924__LJMP static int hlua_applet_http_get_var(lua_State *L)
4925{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004926 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004927 struct stream *s;
4928 const char *name;
4929 size_t len;
4930 struct sample smp;
4931
4932 MAY_LJMP(check_args(L, 2, "get_var"));
4933
4934 /* It is useles to retrieve the stream, but this function
4935 * runs only in a stream context.
4936 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004937 luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004938 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02004939 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004940
4941 smp_set_owner(&smp, s->be, s->sess, s, 0);
Willy Tarreaue352b9d2021-09-03 11:52:38 +02004942 if (!vars_get_by_name(name, len, &smp, NULL)) {
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004943 lua_pushnil(L);
4944 return 1;
4945 }
4946
4947 return hlua_smp2lua(L, &smp);
4948}
4949
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004950__LJMP static int hlua_applet_http_set_priv(lua_State *L)
4951{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004952 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4953 struct stream *s = luactx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01004954 struct hlua *hlua;
4955
4956 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01004957 if (!s->hlua)
4958 return 0;
4959 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004960
4961 MAY_LJMP(check_args(L, 2, "set_priv"));
4962
4963 /* Remove previous value. */
Thierry FOURNIERe068b602017-04-26 13:27:05 +02004964 luaL_unref(L, LUA_REGISTRYINDEX, hlua->Mref);
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004965
4966 /* Get and store new value. */
4967 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
4968 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
4969
4970 return 0;
4971}
4972
4973__LJMP static int hlua_applet_http_get_priv(lua_State *L)
4974{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004975 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4976 struct stream *s = luactx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01004977 struct hlua *hlua;
4978
4979 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01004980 if (!s->hlua) {
4981 lua_pushnil(L);
4982 return 1;
4983 }
4984 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004985
4986 /* Push configuration index in the stack. */
4987 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
4988
4989 return 1;
4990}
4991
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004992/* If expected data not yet available, it returns a yield. This function
4993 * consumes the data in the buffer. It returns a string containing the
4994 * data. This string can be empty.
4995 */
Christopher Fauleta2097962019-07-15 16:25:33 +02004996__LJMP static int hlua_applet_http_getline_yield(lua_State *L, int status, lua_KContext ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004997{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004998 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Willy Tarreauc12b3212022-05-27 11:08:15 +02004999 struct stconn *sc = appctx_sc(luactx->appctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02005000 struct channel *req = sc_oc(sc);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005001 struct htx *htx;
5002 struct htx_blk *blk;
5003 size_t count;
5004 int stop = 0;
5005
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005006 htx = htx_from_buf(&req->buf);
5007 count = co_data(req);
Christopher Fauleta3f15502019-05-13 15:27:23 +02005008 blk = htx_get_first_blk(htx);
Christopher Fauletcc26b132018-12-18 21:20:57 +01005009
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005010 while (count && !stop && blk) {
5011 enum htx_blk_type type = htx_get_blk_type(blk);
5012 uint32_t sz = htx_get_blksz(blk);
5013 struct ist v;
5014 uint32_t vlen;
5015 char *nl;
5016
5017 vlen = sz;
5018 if (vlen > count) {
5019 if (type != HTX_BLK_DATA)
5020 break;
5021 vlen = count;
5022 }
5023
5024 switch (type) {
5025 case HTX_BLK_UNUSED:
5026 break;
5027
5028 case HTX_BLK_DATA:
5029 v = htx_get_blk_value(htx, blk);
5030 v.len = vlen;
5031 nl = istchr(v, '\n');
5032 if (nl != NULL) {
5033 stop = 1;
5034 vlen = nl - v.ptr + 1;
5035 }
Willy Tarreau7e702d12021-04-28 17:59:21 +02005036 luaL_addlstring(&luactx->b, v.ptr, vlen);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005037 break;
5038
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005039 case HTX_BLK_TLR:
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01005040 case HTX_BLK_EOT:
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005041 stop = 1;
5042 break;
5043
5044 default:
5045 break;
5046 }
5047
Willy Tarreau84240042022-02-28 16:51:23 +01005048 c_rew(req, vlen);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005049 count -= vlen;
5050 if (sz == vlen)
5051 blk = htx_remove_blk(htx, blk);
5052 else {
5053 htx_cut_data_blk(htx, blk, vlen);
5054 break;
5055 }
5056 }
5057
Christopher Fauleteccb31c2021-04-02 14:24:56 +02005058 /* The message was fully consumed and no more data are expected
5059 * (EOM flag set).
5060 */
5061 if (htx_is_empty(htx) && (htx->flags & HTX_FL_EOM))
5062 stop = 1;
5063
Christopher Faulet0ae79d02019-02-27 21:36:59 +01005064 htx_to_buf(htx, &req->buf);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005065 if (!stop) {
Willy Tarreau90e8b452022-05-25 18:21:43 +02005066 applet_need_more_data(luactx->appctx);
Christopher Fauleta2097962019-07-15 16:25:33 +02005067 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_getline_yield, TICK_ETERNITY, 0));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005068 }
5069
5070 /* return the result. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005071 luaL_pushresult(&luactx->b);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005072 return 1;
5073}
5074
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005075
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08005076/* Check arguments for the function "hlua_channel_get_yield". */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005077__LJMP static int hlua_applet_http_getline(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005078{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005079 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005080
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005081 /* Initialise the string catenation. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005082 luaL_buffinit(L, &luactx->b);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005083
Christopher Fauleta2097962019-07-15 16:25:33 +02005084 return MAY_LJMP(hlua_applet_http_getline_yield(L, 0, 0));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005085}
5086
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005087/* If expected data not yet available, it returns a yield. This function
5088 * consumes the data in the buffer. It returns a string containing the
5089 * data. This string can be empty.
5090 */
Christopher Fauleta2097962019-07-15 16:25:33 +02005091__LJMP static int hlua_applet_http_recv_yield(lua_State *L, int status, lua_KContext ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005092{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005093 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Willy Tarreauc12b3212022-05-27 11:08:15 +02005094 struct stconn *sc = appctx_sc(luactx->appctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02005095 struct channel *req = sc_oc(sc);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005096 struct htx *htx;
5097 struct htx_blk *blk;
5098 size_t count;
5099 int len;
5100
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005101 htx = htx_from_buf(&req->buf);
5102 len = MAY_LJMP(luaL_checkinteger(L, 2));
5103 count = co_data(req);
Christopher Faulet29f17582019-05-23 11:03:26 +02005104 blk = htx_get_head_blk(htx);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005105 while (count && len && blk) {
5106 enum htx_blk_type type = htx_get_blk_type(blk);
5107 uint32_t sz = htx_get_blksz(blk);
5108 struct ist v;
5109 uint32_t vlen;
5110
5111 vlen = sz;
5112 if (len > 0 && vlen > len)
5113 vlen = len;
5114 if (vlen > count) {
5115 if (type != HTX_BLK_DATA)
5116 break;
5117 vlen = count;
5118 }
5119
5120 switch (type) {
5121 case HTX_BLK_UNUSED:
5122 break;
5123
5124 case HTX_BLK_DATA:
5125 v = htx_get_blk_value(htx, blk);
Willy Tarreau7e702d12021-04-28 17:59:21 +02005126 luaL_addlstring(&luactx->b, v.ptr, vlen);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005127 break;
5128
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005129 case HTX_BLK_TLR:
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01005130 case HTX_BLK_EOT:
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005131 len = 0;
5132 break;
5133
5134 default:
5135 break;
5136 }
5137
Willy Tarreau84240042022-02-28 16:51:23 +01005138 c_rew(req, vlen);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005139 count -= vlen;
5140 if (len > 0)
5141 len -= vlen;
5142 if (sz == vlen)
5143 blk = htx_remove_blk(htx, blk);
5144 else {
5145 htx_cut_data_blk(htx, blk, vlen);
5146 break;
5147 }
5148 }
5149
Christopher Fauleteccb31c2021-04-02 14:24:56 +02005150 /* The message was fully consumed and no more data are expected
5151 * (EOM flag set).
5152 */
5153 if (htx_is_empty(htx) && (htx->flags & HTX_FL_EOM))
5154 len = 0;
5155
Christopher Faulet0ae79d02019-02-27 21:36:59 +01005156 htx_to_buf(htx, &req->buf);
5157
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005158 /* If we are no other data available, yield waiting for new data. */
5159 if (len) {
5160 if (len > 0) {
5161 lua_pushinteger(L, len);
5162 lua_replace(L, 2);
5163 }
Willy Tarreau90e8b452022-05-25 18:21:43 +02005164 applet_need_more_data(luactx->appctx);
Willy Tarreau9635e032018-10-16 17:52:55 +02005165 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005166 }
5167
5168 /* return the result. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005169 luaL_pushresult(&luactx->b);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005170 return 1;
5171}
5172
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08005173/* Check arguments for the function "hlua_channel_get_yield". */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005174__LJMP static int hlua_applet_http_recv(lua_State *L)
5175{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005176 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005177 int len = -1;
5178
5179 /* Check arguments. */
5180 if (lua_gettop(L) > 2)
5181 WILL_LJMP(luaL_error(L, "The 'recv' function requires between 1 and 2 arguments."));
5182 if (lua_gettop(L) >= 2) {
5183 len = MAY_LJMP(luaL_checkinteger(L, 2));
5184 lua_pop(L, 1);
5185 }
5186
Christopher Fauleta2097962019-07-15 16:25:33 +02005187 lua_pushinteger(L, len);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005188
Christopher Fauleta2097962019-07-15 16:25:33 +02005189 /* Initialise the string catenation. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005190 luaL_buffinit(L, &luactx->b);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005191
Christopher Fauleta2097962019-07-15 16:25:33 +02005192 return MAY_LJMP(hlua_applet_http_recv_yield(L, 0, 0));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005193}
5194
5195/* Append data in the output side of the buffer. This data is immediately
5196 * sent. The function returns the amount of data written. If the buffer
5197 * cannot contain the data, the function yields. The function returns -1
5198 * if the channel is closed.
5199 */
Christopher Fauleta2097962019-07-15 16:25:33 +02005200__LJMP static int hlua_applet_http_send_yield(lua_State *L, int status, lua_KContext ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005201{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005202 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Willy Tarreauc12b3212022-05-27 11:08:15 +02005203 struct stconn *sc = appctx_sc(luactx->appctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02005204 struct channel *res = sc_ic(sc);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005205 struct htx *htx = htx_from_buf(&res->buf);
5206 const char *data;
5207 size_t len;
5208 int l = MAY_LJMP(luaL_checkinteger(L, 3));
5209 int max;
5210
Christopher Faulet9060fc02019-07-03 11:39:30 +02005211 max = htx_get_max_blksz(htx, channel_htx_recv_max(res, htx));
Christopher Faulet4b0e9b22019-01-09 12:16:58 +01005212 if (!max)
5213 goto snd_yield;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005214
5215 data = MAY_LJMP(luaL_checklstring(L, 2, &len));
5216
5217 /* Get the max amount of data which can write as input in the channel. */
5218 if (max > (len - l))
5219 max = len - l;
5220
5221 /* Copy data. */
Willy Tarreau0a7ef022019-05-28 10:30:11 +02005222 max = htx_add_data(htx, ist2(data + l, max));
Christopher Fauletf6cce3f2019-02-27 21:20:09 +01005223 channel_add_input(res, max);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005224
5225 /* update counters. */
5226 l += max;
5227 lua_pop(L, 1);
5228 lua_pushinteger(L, l);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005229
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005230 /* If some data is not send, declares the situation to the
5231 * applet, and returns a yield.
5232 */
5233 if (l < len) {
Christopher Faulet4b0e9b22019-01-09 12:16:58 +01005234 snd_yield:
Christopher Faulet0ae79d02019-02-27 21:36:59 +01005235 htx_to_buf(htx, &res->buf);
Willy Tarreau3e7be362022-05-27 10:35:27 +02005236 sc_need_room(sc);
Willy Tarreau9635e032018-10-16 17:52:55 +02005237 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005238 }
5239
Christopher Fauleta2097962019-07-15 16:25:33 +02005240 htx_to_buf(htx, &res->buf);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005241 return 1;
5242}
5243
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05005244/* Just a wrapper of "hlua_applet_send_yield". This wrapper permits
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005245 * yield the LUA process, and resume it without checking the
5246 * input arguments.
5247 */
5248__LJMP static int hlua_applet_http_send(lua_State *L)
5249{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005250 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005251 struct hlua_http_ctx *http_ctx = luactx->appctx->svcctx;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005252
5253 /* We want to send some data. Headers must be sent. */
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005254 if (!(http_ctx->flags & APPLET_HDR_SENT)) {
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005255 hlua_pusherror(L, "Lua: 'send' you must call start_response() before sending data.");
5256 WILL_LJMP(lua_error(L));
5257 }
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005258
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05005259 /* This integer is used for followinf the amount of data sent. */
Christopher Fauleta2097962019-07-15 16:25:33 +02005260 lua_pushinteger(L, 0);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005261
Christopher Fauleta2097962019-07-15 16:25:33 +02005262 return MAY_LJMP(hlua_applet_http_send_yield(L, 0, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005263}
5264
5265__LJMP static int hlua_applet_http_addheader(lua_State *L)
5266{
5267 const char *name;
5268 int ret;
5269
5270 MAY_LJMP(hlua_checkapplet_http(L, 1));
5271 name = MAY_LJMP(luaL_checkstring(L, 2));
5272 MAY_LJMP(luaL_checkstring(L, 3));
5273
5274 /* Push in the stack the "response" entry. */
5275 ret = lua_getfield(L, 1, "response");
5276 if (ret != LUA_TTABLE) {
5277 hlua_pusherror(L, "Lua: 'add_header' internal error: AppletHTTP['response'] "
5278 "is expected as an array. %s found", lua_typename(L, ret));
5279 WILL_LJMP(lua_error(L));
5280 }
5281
5282 /* check if the header is already registered if it is not
5283 * the case, register it.
5284 */
5285 ret = lua_getfield(L, -1, name);
5286 if (ret == LUA_TNIL) {
5287
5288 /* Entry not found. */
5289 lua_pop(L, 1); /* remove the nil. The "response" table is the top of the stack. */
5290
5291 /* Insert the new header name in the array in the top of the stack.
5292 * It left the new array in the top of the stack.
5293 */
5294 lua_newtable(L);
5295 lua_pushvalue(L, 2);
5296 lua_pushvalue(L, -2);
5297 lua_settable(L, -4);
5298
5299 } else if (ret != LUA_TTABLE) {
5300
5301 /* corruption error. */
5302 hlua_pusherror(L, "Lua: 'add_header' internal error: AppletHTTP['response']['%s'] "
5303 "is expected as an array. %s found", name, lua_typename(L, ret));
5304 WILL_LJMP(lua_error(L));
5305 }
5306
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -07005307 /* Now the top of thestack is an array of values. We push
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005308 * the header value as new entry.
5309 */
5310 lua_pushvalue(L, 3);
5311 ret = lua_rawlen(L, -2);
5312 lua_rawseti(L, -2, ret + 1);
5313 lua_pushboolean(L, 1);
5314 return 1;
5315}
5316
5317__LJMP static int hlua_applet_http_status(lua_State *L)
5318{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005319 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005320 int status = MAY_LJMP(luaL_checkinteger(L, 2));
Robin H. Johnson52f5db22017-01-01 13:10:52 -08005321 const char *reason = MAY_LJMP(luaL_optlstring(L, 3, NULL, NULL));
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005322 struct hlua_http_ctx *http_ctx = luactx->appctx->svcctx;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005323
5324 if (status < 100 || status > 599) {
5325 lua_pushboolean(L, 0);
5326 return 1;
5327 }
5328
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005329 http_ctx->status = status;
5330 http_ctx->reason = reason;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005331 lua_pushboolean(L, 1);
5332 return 1;
5333}
5334
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005335
Christopher Fauleta2097962019-07-15 16:25:33 +02005336__LJMP static int hlua_applet_http_send_response(lua_State *L)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005337{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005338 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005339 struct hlua_http_ctx *http_ctx = luactx->appctx->svcctx;
Willy Tarreauc12b3212022-05-27 11:08:15 +02005340 struct stconn *sc = appctx_sc(luactx->appctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02005341 struct channel *res = sc_ic(sc);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005342 struct htx *htx;
5343 struct htx_sl *sl;
5344 struct h1m h1m;
5345 const char *status, *reason;
5346 const char *name, *value;
5347 size_t nlen, vlen;
5348 unsigned int flags;
5349
5350 /* Send the message at once. */
5351 htx = htx_from_buf(&res->buf);
5352 h1m_init_res(&h1m);
5353
5354 /* Use the same http version than the request. */
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005355 status = ultoa_r(http_ctx->status, trash.area, trash.size);
5356 reason = http_ctx->reason;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005357 if (reason == NULL)
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005358 reason = http_get_reason(http_ctx->status);
5359 if (http_ctx->flags & APPLET_HTTP11) {
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005360 flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11);
5361 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.1"), ist(status), ist(reason));
5362 }
5363 else {
5364 flags = HTX_SL_F_IS_RESP;
5365 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.0"), ist(status), ist(reason));
5366 }
5367 if (!sl) {
5368 hlua_pusherror(L, "Lua applet http '%s': Failed to create response.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005369 luactx->appctx->rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005370 WILL_LJMP(lua_error(L));
5371 }
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005372 sl->info.res.status = http_ctx->status;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005373
5374 /* Get the array associated to the field "response" in the object AppletHTTP. */
5375 lua_pushvalue(L, 0);
5376 if (lua_getfield(L, 1, "response") != LUA_TTABLE) {
5377 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response'] missing.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005378 luactx->appctx->rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005379 WILL_LJMP(lua_error(L));
5380 }
5381
5382 /* Browse the list of headers. */
5383 lua_pushnil(L);
5384 while(lua_next(L, -2) != 0) {
5385 /* We expect a string as -2. */
5386 if (lua_type(L, -2) != LUA_TSTRING) {
5387 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response'][] element must be a string. got %s.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005388 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005389 lua_typename(L, lua_type(L, -2)));
5390 WILL_LJMP(lua_error(L));
5391 }
5392 name = lua_tolstring(L, -2, &nlen);
5393
5394 /* We expect an array as -1. */
5395 if (lua_type(L, -1) != LUA_TTABLE) {
5396 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 +02005397 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005398 name,
5399 lua_typename(L, lua_type(L, -1)));
5400 WILL_LJMP(lua_error(L));
5401 }
5402
5403 /* Browse the table who is on the top of the stack. */
5404 lua_pushnil(L);
5405 while(lua_next(L, -2) != 0) {
5406 int id;
5407
5408 /* We expect a number as -2. */
5409 if (lua_type(L, -2) != LUA_TNUMBER) {
5410 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 +02005411 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005412 name,
5413 lua_typename(L, lua_type(L, -2)));
5414 WILL_LJMP(lua_error(L));
5415 }
5416 id = lua_tointeger(L, -2);
5417
5418 /* We expect a string as -2. */
5419 if (lua_type(L, -1) != LUA_TSTRING) {
5420 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 +02005421 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005422 name, id,
5423 lua_typename(L, lua_type(L, -1)));
5424 WILL_LJMP(lua_error(L));
5425 }
5426 value = lua_tolstring(L, -1, &vlen);
5427
5428 /* Simple Protocol checks. */
Christopher Faulet545fbba2021-09-28 09:36:25 +02005429 if (isteqi(ist2(name, nlen), ist("transfer-encoding"))) {
5430 int ret;
5431
5432 ret = h1_parse_xfer_enc_header(&h1m, ist2(value, vlen));
5433 if (ret < 0) {
5434 hlua_pusherror(L, "Lua applet http '%s': Invalid '%s' header.\n",
5435 luactx->appctx->rule->arg.hlua_rule->fcn->name,
5436 name);
5437 WILL_LJMP(lua_error(L));
5438 }
5439 else if (ret == 0)
5440 goto next; /* Skip it */
5441 }
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005442 else if (isteqi(ist2(name, nlen), ist("content-length"))) {
5443 struct ist v = ist2(value, vlen);
5444 int ret;
5445
5446 ret = h1_parse_cont_len_header(&h1m, &v);
5447 if (ret < 0) {
5448 hlua_pusherror(L, "Lua applet http '%s': Invalid '%s' header.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005449 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005450 name);
5451 WILL_LJMP(lua_error(L));
5452 }
5453 else if (ret == 0)
5454 goto next; /* Skip it */
5455 }
5456
5457 /* Add a new header */
5458 if (!htx_add_header(htx, ist2(name, nlen), ist2(value, vlen))) {
5459 hlua_pusherror(L, "Lua applet http '%s': Failed to add header '%s' in the response.\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 WILL_LJMP(lua_error(L));
5463 }
5464 next:
5465 /* Remove the array from the stack, and get next element with a remaining string. */
5466 lua_pop(L, 1);
5467 }
5468
5469 /* Remove the array from the stack, and get next element with a remaining string. */
5470 lua_pop(L, 1);
5471 }
5472
5473 if (h1m.flags & H1_MF_CHNK)
5474 h1m.flags &= ~H1_MF_CLEN;
5475 if (h1m.flags & (H1_MF_CLEN|H1_MF_CHNK))
5476 h1m.flags |= H1_MF_XFER_LEN;
5477
5478 /* Uset HTX start-line flags */
5479 if (h1m.flags & H1_MF_XFER_ENC)
5480 flags |= HTX_SL_F_XFER_ENC;
5481 if (h1m.flags & H1_MF_XFER_LEN) {
5482 flags |= HTX_SL_F_XFER_LEN;
5483 if (h1m.flags & H1_MF_CHNK)
5484 flags |= HTX_SL_F_CHNK;
5485 else if (h1m.flags & H1_MF_CLEN)
5486 flags |= HTX_SL_F_CLEN;
5487 if (h1m.body_len == 0)
5488 flags |= HTX_SL_F_BODYLESS;
5489 }
5490 sl->flags |= flags;
5491
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -07005492 /* If we don't have a content-length set, and the HTTP version is 1.1
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005493 * and the status code implies the presence of a message body, we must
5494 * announce a transfer encoding chunked. This is required by haproxy
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05005495 * for the keepalive compliance. If the applet announces a transfer-encoding
5496 * chunked itself, don't do anything.
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005497 */
5498 if ((flags & (HTX_SL_F_VER_11|HTX_SL_F_XFER_LEN)) == HTX_SL_F_VER_11 &&
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005499 http_ctx->status >= 200 && http_ctx->status != 204 && http_ctx->status != 304) {
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005500 /* Add a new header */
5501 sl->flags |= (HTX_SL_F_XFER_ENC|H1_MF_CHNK|H1_MF_XFER_LEN);
5502 if (!htx_add_header(htx, ist("transfer-encoding"), ist("chunked"))) {
5503 hlua_pusherror(L, "Lua applet http '%s': Failed to add header 'transfer-encoding' in the response.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005504 luactx->appctx->rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005505 WILL_LJMP(lua_error(L));
5506 }
5507 }
5508
5509 /* Finalize headers. */
5510 if (!htx_add_endof(htx, HTX_BLK_EOH)) {
5511 hlua_pusherror(L, "Lua applet http '%s': Failed create the response.\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 WILL_LJMP(lua_error(L));
5514 }
5515
5516 if (htx_used_space(htx) > b_size(&res->buf) - global.tune.maxrewrite) {
5517 b_reset(&res->buf);
5518 hlua_pusherror(L, "Lua: 'start_response': response header block too big");
5519 WILL_LJMP(lua_error(L));
5520 }
5521
5522 htx_to_buf(htx, &res->buf);
Christopher Fauletf6cce3f2019-02-27 21:20:09 +01005523 channel_add_input(res, htx->data);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005524
5525 /* Headers sent, set the flag. */
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005526 http_ctx->flags |= APPLET_HDR_SENT;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005527 return 0;
5528
5529}
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005530/* We will build the status line and the headers of the HTTP response.
5531 * We will try send at once if its not possible, we give back the hand
5532 * waiting for more room.
5533 */
Christopher Fauleta2097962019-07-15 16:25:33 +02005534__LJMP static int hlua_applet_http_start_response_yield(lua_State *L, int status, lua_KContext ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005535{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005536 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Willy Tarreauc12b3212022-05-27 11:08:15 +02005537 struct stconn *sc = appctx_sc(luactx->appctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02005538 struct channel *res = sc_ic(sc);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005539
5540 if (co_data(res)) {
Willy Tarreau3e7be362022-05-27 10:35:27 +02005541 sc_need_room(sc);
Christopher Fauleta2097962019-07-15 16:25:33 +02005542 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_start_response_yield, TICK_ETERNITY, 0));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005543 }
Christopher Fauleta2097962019-07-15 16:25:33 +02005544 return MAY_LJMP(hlua_applet_http_send_response(L));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005545}
5546
5547
Christopher Fauleta2097962019-07-15 16:25:33 +02005548__LJMP static int hlua_applet_http_start_response(lua_State *L)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005549{
Christopher Fauleta2097962019-07-15 16:25:33 +02005550 return MAY_LJMP(hlua_applet_http_start_response_yield(L, 0, 0));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005551}
5552
Christopher Fauleta2097962019-07-15 16:25:33 +02005553/*
5554 *
5555 *
5556 * Class HTTP
5557 *
5558 *
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005559 */
Christopher Fauleta2097962019-07-15 16:25:33 +02005560
5561/* Returns a struct hlua_txn if the stack entry "ud" is
5562 * a class stream, otherwise it throws an error.
5563 */
5564__LJMP static struct hlua_txn *hlua_checkhttp(lua_State *L, int ud)
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005565{
Christopher Fauleta2097962019-07-15 16:25:33 +02005566 return MAY_LJMP(hlua_checkudata(L, ud, class_http_ref));
5567}
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005568
Christopher Fauleta2097962019-07-15 16:25:33 +02005569/* This function creates and push in the stack a HTTP object
5570 * according with a current TXN.
5571 */
5572static int hlua_http_new(lua_State *L, struct hlua_txn *txn)
5573{
5574 struct hlua_txn *htxn;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005575
Christopher Fauleta2097962019-07-15 16:25:33 +02005576 /* Check stack size. */
5577 if (!lua_checkstack(L, 3))
5578 return 0;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005579
Christopher Fauleta2097962019-07-15 16:25:33 +02005580 /* Create the object: obj[0] = userdata.
5581 * Note that the base of the Converters object is the
5582 * same than the TXN object.
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005583 */
Christopher Fauleta2097962019-07-15 16:25:33 +02005584 lua_newtable(L);
5585 htxn = lua_newuserdata(L, sizeof(*htxn));
5586 lua_rawseti(L, -2, 0);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005587
5588 htxn->s = txn->s;
5589 htxn->p = txn->p;
Christopher Faulet256b69a2019-05-23 11:14:21 +02005590 htxn->dir = txn->dir;
5591 htxn->flags = txn->flags;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005592
5593 /* Pop a class stream metatable and affect it to the table. */
5594 lua_rawgeti(L, LUA_REGISTRYINDEX, class_http_ref);
5595 lua_setmetatable(L, -2);
5596
5597 return 1;
5598}
5599
Christopher Fauletdf97ac42020-02-26 16:57:19 +01005600/* This function creates and returns an array containing the status-line
5601 * elements. This function does not fails.
5602 */
5603__LJMP static int hlua_http_get_stline(lua_State *L, struct htx_sl *sl)
5604{
5605 /* Create the table. */
5606 lua_newtable(L);
5607
5608 if (sl->flags & HTX_SL_F_IS_RESP) {
5609 lua_pushstring(L, "version");
5610 lua_pushlstring(L, HTX_SL_RES_VPTR(sl), HTX_SL_RES_VLEN(sl));
5611 lua_settable(L, -3);
5612 lua_pushstring(L, "code");
5613 lua_pushlstring(L, HTX_SL_RES_CPTR(sl), HTX_SL_RES_CLEN(sl));
5614 lua_settable(L, -3);
5615 lua_pushstring(L, "reason");
5616 lua_pushlstring(L, HTX_SL_RES_RPTR(sl), HTX_SL_RES_RLEN(sl));
5617 lua_settable(L, -3);
5618 }
5619 else {
5620 lua_pushstring(L, "method");
5621 lua_pushlstring(L, HTX_SL_REQ_MPTR(sl), HTX_SL_REQ_MLEN(sl));
5622 lua_settable(L, -3);
5623 lua_pushstring(L, "uri");
5624 lua_pushlstring(L, HTX_SL_REQ_UPTR(sl), HTX_SL_REQ_ULEN(sl));
5625 lua_settable(L, -3);
5626 lua_pushstring(L, "version");
5627 lua_pushlstring(L, HTX_SL_REQ_VPTR(sl), HTX_SL_REQ_VLEN(sl));
5628 lua_settable(L, -3);
5629 }
5630 return 1;
5631}
5632
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005633/* This function creates ans returns an array of HTTP headers.
5634 * This function does not fails. It is used as wrapper with the
5635 * 2 following functions.
5636 */
Christopher Faulet9d1332b2020-02-24 16:46:16 +01005637__LJMP static int hlua_http_get_headers(lua_State *L, struct http_msg *msg)
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005638{
Christopher Fauleta2097962019-07-15 16:25:33 +02005639 struct htx *htx;
5640 int32_t pos;
5641
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005642 /* Create the table. */
5643 lua_newtable(L);
5644
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005645
Christopher Fauleta2097962019-07-15 16:25:33 +02005646 htx = htxbuf(&msg->chn->buf);
5647 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
5648 struct htx_blk *blk = htx_get_blk(htx, pos);
5649 enum htx_blk_type type = htx_get_blk_type(blk);
5650 struct ist n, v;
5651 int len;
Christopher Faulet724a12c2018-12-13 22:12:15 +01005652
Christopher Fauleta2097962019-07-15 16:25:33 +02005653 if (type == HTX_BLK_HDR) {
5654 n = htx_get_blk_name(htx,blk);
5655 v = htx_get_blk_value(htx, blk);
Christopher Faulet724a12c2018-12-13 22:12:15 +01005656 }
Christopher Fauleta2097962019-07-15 16:25:33 +02005657 else if (type == HTX_BLK_EOH)
5658 break;
5659 else
5660 continue;
Christopher Faulet724a12c2018-12-13 22:12:15 +01005661
Christopher Fauleta2097962019-07-15 16:25:33 +02005662 /* Check for existing entry:
5663 * assume that the table is on the top of the stack, and
5664 * push the key in the stack, the function lua_gettable()
5665 * perform the lookup.
5666 */
5667 lua_pushlstring(L, n.ptr, n.len);
5668 lua_gettable(L, -2);
Christopher Faulet724a12c2018-12-13 22:12:15 +01005669
Christopher Fauleta2097962019-07-15 16:25:33 +02005670 switch (lua_type(L, -1)) {
5671 case LUA_TNIL:
5672 /* Table not found, create it. */
5673 lua_pop(L, 1); /* remove the nil value. */
5674 lua_pushlstring(L, n.ptr, n.len); /* push the header name as key. */
5675 lua_newtable(L); /* create and push empty table. */
5676 lua_pushlstring(L, v.ptr, v.len); /* push header value. */
5677 lua_rawseti(L, -2, 0); /* index header value (pop it). */
5678 lua_rawset(L, -3); /* index new table with header name (pop the values). */
Christopher Faulet724a12c2018-12-13 22:12:15 +01005679 break;
Christopher Faulet724a12c2018-12-13 22:12:15 +01005680
Christopher Fauleta2097962019-07-15 16:25:33 +02005681 case LUA_TTABLE:
5682 /* Entry found: push the value in the table. */
5683 len = lua_rawlen(L, -1);
5684 lua_pushlstring(L, v.ptr, v.len); /* push header value. */
5685 lua_rawseti(L, -2, len+1); /* index header value (pop it). */
5686 lua_pop(L, 1); /* remove the table (it is stored in the main table). */
5687 break;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005688
Christopher Fauleta2097962019-07-15 16:25:33 +02005689 default:
5690 /* Other cases are errors. */
5691 hlua_pusherror(L, "internal error during the parsing of headers.");
5692 WILL_LJMP(lua_error(L));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005693 }
5694 }
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005695 return 1;
5696}
5697
5698__LJMP static int hlua_http_req_get_headers(lua_State *L)
5699{
5700 struct hlua_txn *htxn;
5701
5702 MAY_LJMP(check_args(L, 1, "req_get_headers"));
5703 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5704
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005705 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005706 WILL_LJMP(lua_error(L));
5707
Christopher Faulet9d1332b2020-02-24 16:46:16 +01005708 return hlua_http_get_headers(L, &htxn->s->txn->req);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005709}
5710
5711__LJMP static int hlua_http_res_get_headers(lua_State *L)
5712{
5713 struct hlua_txn *htxn;
5714
5715 MAY_LJMP(check_args(L, 1, "res_get_headers"));
5716 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5717
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005718 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005719 WILL_LJMP(lua_error(L));
5720
Christopher Faulet9d1332b2020-02-24 16:46:16 +01005721 return hlua_http_get_headers(L, &htxn->s->txn->rsp);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005722}
5723
5724/* This function replace full header, or just a value in
5725 * the request or in the response. It is a wrapper fir the
5726 * 4 following functions.
5727 */
Christopher Fauletd1914aa2020-02-24 16:52:46 +01005728__LJMP static inline int hlua_http_rep_hdr(lua_State *L, struct http_msg *msg, int full)
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005729{
5730 size_t name_len;
5731 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
5732 const char *reg = MAY_LJMP(luaL_checkstring(L, 3));
5733 const char *value = MAY_LJMP(luaL_checkstring(L, 4));
Christopher Fauleta2097962019-07-15 16:25:33 +02005734 struct htx *htx;
Dragan Dosen26743032019-04-30 15:54:36 +02005735 struct my_regex *re;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005736
Dragan Dosen26743032019-04-30 15:54:36 +02005737 if (!(re = regex_comp(reg, 1, 1, NULL)))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005738 WILL_LJMP(luaL_argerror(L, 3, "invalid regex"));
5739
Christopher Fauleta2097962019-07-15 16:25:33 +02005740 htx = htxbuf(&msg->chn->buf);
Christopher Fauletd1914aa2020-02-24 16:52:46 +01005741 http_replace_hdrs(chn_strm(msg->chn), htx, ist2(name, name_len), value, re, full);
Dragan Dosen26743032019-04-30 15:54:36 +02005742 regex_free(re);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005743 return 0;
5744}
5745
5746__LJMP static int hlua_http_req_rep_hdr(lua_State *L)
5747{
5748 struct hlua_txn *htxn;
5749
5750 MAY_LJMP(check_args(L, 4, "req_rep_hdr"));
5751 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5752
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005753 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005754 WILL_LJMP(lua_error(L));
5755
Christopher Fauletd1914aa2020-02-24 16:52:46 +01005756 return MAY_LJMP(hlua_http_rep_hdr(L, &htxn->s->txn->req, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005757}
5758
5759__LJMP static int hlua_http_res_rep_hdr(lua_State *L)
5760{
5761 struct hlua_txn *htxn;
5762
5763 MAY_LJMP(check_args(L, 4, "res_rep_hdr"));
5764 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5765
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005766 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005767 WILL_LJMP(lua_error(L));
5768
Christopher Fauletd1914aa2020-02-24 16:52:46 +01005769 return MAY_LJMP(hlua_http_rep_hdr(L, &htxn->s->txn->rsp, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005770}
5771
5772__LJMP static int hlua_http_req_rep_val(lua_State *L)
5773{
5774 struct hlua_txn *htxn;
5775
5776 MAY_LJMP(check_args(L, 4, "req_rep_hdr"));
5777 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5778
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005779 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005780 WILL_LJMP(lua_error(L));
5781
Christopher Fauletd1914aa2020-02-24 16:52:46 +01005782 return MAY_LJMP(hlua_http_rep_hdr(L, &htxn->s->txn->req, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005783}
5784
5785__LJMP static int hlua_http_res_rep_val(lua_State *L)
5786{
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005787 struct hlua_txn *htxn;
5788
5789 MAY_LJMP(check_args(L, 4, "res_rep_val"));
5790 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5791
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005792 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005793 WILL_LJMP(lua_error(L));
5794
Christopher Fauletd1914aa2020-02-24 16:52:46 +01005795 return MAY_LJMP(hlua_http_rep_hdr(L, &htxn->s->txn->rsp, 0));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005796}
5797
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08005798/* This function deletes all the occurrences of an header.
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005799 * It is a wrapper for the 2 following functions.
5800 */
Christopher Fauletd31c7b32020-02-25 09:37:57 +01005801__LJMP static inline int hlua_http_del_hdr(lua_State *L, struct http_msg *msg)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005802{
5803 size_t len;
5804 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Christopher Fauleta2097962019-07-15 16:25:33 +02005805 struct htx *htx = htxbuf(&msg->chn->buf);
5806 struct http_hdr_ctx ctx;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005807
Christopher Fauleta2097962019-07-15 16:25:33 +02005808 ctx.blk = NULL;
5809 while (http_find_header(htx, ist2(name, len), &ctx, 1))
5810 http_remove_header(htx, &ctx);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005811 return 0;
5812}
5813
5814__LJMP static int hlua_http_req_del_hdr(lua_State *L)
5815{
5816 struct hlua_txn *htxn;
5817
5818 MAY_LJMP(check_args(L, 2, "req_del_hdr"));
5819 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5820
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005821 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005822 WILL_LJMP(lua_error(L));
5823
Christopher Fauletd31c7b32020-02-25 09:37:57 +01005824 return hlua_http_del_hdr(L, &htxn->s->txn->req);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005825}
5826
5827__LJMP static int hlua_http_res_del_hdr(lua_State *L)
5828{
5829 struct hlua_txn *htxn;
5830
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005831 MAY_LJMP(check_args(L, 2, "res_del_hdr"));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005832 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5833
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005834 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005835 WILL_LJMP(lua_error(L));
5836
Christopher Fauletd31c7b32020-02-25 09:37:57 +01005837 return hlua_http_del_hdr(L, &htxn->s->txn->rsp);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005838}
5839
5840/* This function adds an header. It is a wrapper used by
5841 * the 2 following functions.
5842 */
Christopher Fauletd31c7b32020-02-25 09:37:57 +01005843__LJMP static inline int hlua_http_add_hdr(lua_State *L, struct http_msg *msg)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005844{
5845 size_t name_len;
5846 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
5847 size_t value_len;
5848 const char *value = MAY_LJMP(luaL_checklstring(L, 3, &value_len));
Christopher Fauleta2097962019-07-15 16:25:33 +02005849 struct htx *htx = htxbuf(&msg->chn->buf);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005850
Christopher Fauleta2097962019-07-15 16:25:33 +02005851 lua_pushboolean(L, http_add_header(htx, ist2(name, name_len),
5852 ist2(value, value_len)));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005853 return 0;
5854}
5855
Christopher Fauletdf97ac42020-02-26 16:57:19 +01005856__LJMP static int hlua_http_req_add_hdr(lua_State *L)
5857{
5858 struct hlua_txn *htxn;
5859
5860 MAY_LJMP(check_args(L, 3, "req_add_hdr"));
5861 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5862
5863 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
5864 WILL_LJMP(lua_error(L));
5865
5866 return hlua_http_add_hdr(L, &htxn->s->txn->req);
5867}
5868
5869__LJMP static int hlua_http_res_add_hdr(lua_State *L)
5870{
5871 struct hlua_txn *htxn;
5872
5873 MAY_LJMP(check_args(L, 3, "res_add_hdr"));
5874 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5875
5876 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
5877 WILL_LJMP(lua_error(L));
5878
5879 return hlua_http_add_hdr(L, &htxn->s->txn->rsp);
5880}
5881
5882static int hlua_http_req_set_hdr(lua_State *L)
5883{
5884 struct hlua_txn *htxn;
5885
5886 MAY_LJMP(check_args(L, 3, "req_set_hdr"));
5887 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5888
5889 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
5890 WILL_LJMP(lua_error(L));
5891
5892 hlua_http_del_hdr(L, &htxn->s->txn->req);
5893 return hlua_http_add_hdr(L, &htxn->s->txn->req);
5894}
5895
5896static int hlua_http_res_set_hdr(lua_State *L)
5897{
5898 struct hlua_txn *htxn;
5899
5900 MAY_LJMP(check_args(L, 3, "res_set_hdr"));
5901 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5902
5903 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
5904 WILL_LJMP(lua_error(L));
5905
5906 hlua_http_del_hdr(L, &htxn->s->txn->rsp);
5907 return hlua_http_add_hdr(L, &htxn->s->txn->rsp);
5908}
5909
5910/* This function set the method. */
5911static int hlua_http_req_set_meth(lua_State *L)
5912{
5913 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5914 size_t name_len;
5915 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
5916
5917 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
5918 WILL_LJMP(lua_error(L));
5919
5920 lua_pushboolean(L, http_req_replace_stline(0, name, name_len, htxn->p, htxn->s) != -1);
5921 return 1;
5922}
5923
5924/* This function set the method. */
5925static int hlua_http_req_set_path(lua_State *L)
5926{
5927 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5928 size_t name_len;
5929 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
5930
5931 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
5932 WILL_LJMP(lua_error(L));
5933
5934 lua_pushboolean(L, http_req_replace_stline(1, name, name_len, htxn->p, htxn->s) != -1);
5935 return 1;
5936}
5937
5938/* This function set the query-string. */
5939static int hlua_http_req_set_query(lua_State *L)
5940{
5941 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5942 size_t name_len;
5943 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
5944
5945 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
5946 WILL_LJMP(lua_error(L));
5947
5948 /* Check length. */
5949 if (name_len > trash.size - 1) {
5950 lua_pushboolean(L, 0);
5951 return 1;
5952 }
5953
5954 /* Add the mark question as prefix. */
5955 chunk_reset(&trash);
5956 trash.area[trash.data++] = '?';
5957 memcpy(trash.area + trash.data, name, name_len);
5958 trash.data += name_len;
5959
5960 lua_pushboolean(L,
5961 http_req_replace_stline(2, trash.area, trash.data, htxn->p, htxn->s) != -1);
5962 return 1;
5963}
5964
5965/* This function set the uri. */
5966static int hlua_http_req_set_uri(lua_State *L)
5967{
5968 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5969 size_t name_len;
5970 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
5971
5972 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
5973 WILL_LJMP(lua_error(L));
5974
5975 lua_pushboolean(L, http_req_replace_stline(3, name, name_len, htxn->p, htxn->s) != -1);
5976 return 1;
5977}
5978
5979/* This function set the response code & optionally reason. */
5980static int hlua_http_res_set_status(lua_State *L)
5981{
5982 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5983 unsigned int code = MAY_LJMP(luaL_checkinteger(L, 2));
5984 const char *str = MAY_LJMP(luaL_optlstring(L, 3, NULL, NULL));
5985 const struct ist reason = ist2(str, (str ? strlen(str) : 0));
5986
5987 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
5988 WILL_LJMP(lua_error(L));
5989
5990 http_res_set_status(code, reason, htxn->s);
5991 return 0;
5992}
5993
5994/*
5995 *
5996 *
5997 * Class HTTPMessage
5998 *
5999 *
6000 */
6001
6002/* Returns a struct http_msg if the stack entry "ud" is a class HTTPMessage,
6003 * otherwise it throws an error.
6004 */
6005__LJMP static struct http_msg *hlua_checkhttpmsg(lua_State *L, int ud)
6006{
6007 return MAY_LJMP(hlua_checkudata(L, ud, class_http_msg_ref));
6008}
6009
6010/* Creates and pushes on the stack a HTTP object according with a current TXN.
6011 */
Christopher Faulet78c35472020-02-26 17:14:08 +01006012static int hlua_http_msg_new(lua_State *L, struct http_msg *msg)
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006013{
6014 /* Check stack size. */
6015 if (!lua_checkstack(L, 3))
6016 return 0;
6017
6018 lua_newtable(L);
6019 lua_pushlightuserdata(L, msg);
6020 lua_rawseti(L, -2, 0);
6021
6022 /* Create the "channel" field that contains the request channel object. */
6023 lua_pushstring(L, "channel");
6024 if (!hlua_channel_new(L, msg->chn))
6025 return 0;
6026 lua_rawset(L, -3);
6027
6028 /* Pop a class stream metatable and affect it to the table. */
6029 lua_rawgeti(L, LUA_REGISTRYINDEX, class_http_msg_ref);
6030 lua_setmetatable(L, -2);
6031
6032 return 1;
6033}
6034
6035/* Helper function returning a filter attached to the HTTP message at the
6036 * position <ud> in the stack, filling the current offset and length of the
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006037 * filter. If no filter is attached, NULL is returned and <offset> and <len> are
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006038 * filled with output and input length respectively.
6039 */
6040static struct filter *hlua_http_msg_filter(lua_State *L, int ud, struct http_msg *msg, size_t *offset, size_t *len)
6041{
6042 struct channel *chn = msg->chn;
6043 struct htx *htx = htxbuf(&chn->buf);
6044 struct filter *filter = NULL;
6045
6046 *offset = co_data(msg->chn);
6047 *len = htx->data - co_data(msg->chn);
6048
6049 if (lua_getfield(L, ud, "__filter") == LUA_TLIGHTUSERDATA) {
6050 filter = lua_touserdata (L, -1);
6051 if (msg->msg_state >= HTTP_MSG_DATA) {
6052 struct hlua_flt_ctx *flt_ctx = filter->ctx;
6053
6054 *offset = flt_ctx->cur_off[CHN_IDX(chn)];
6055 *len = flt_ctx->cur_len[CHN_IDX(chn)];
6056 }
6057 }
6058
6059 lua_pop(L, 1);
6060 return filter;
6061}
6062
6063/* Returns true if the channel attached to the HTTP message is the response
6064 * channel.
6065 */
6066__LJMP static int hlua_http_msg_is_resp(lua_State *L)
6067{
6068 struct http_msg *msg;
6069
6070 MAY_LJMP(check_args(L, 1, "is_resp"));
6071 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6072
6073 lua_pushboolean(L, !!(msg->chn->flags & CF_ISRESP));
6074 return 1;
6075}
6076
6077/* Returns an array containing the elements status-line of the HTTP message. It relies
6078 * on hlua_http_get_stline().
6079 */
6080__LJMP static int hlua_http_msg_get_stline(lua_State *L)
6081{
6082 struct http_msg *msg;
6083 struct htx *htx;
6084 struct htx_sl *sl;
6085
6086 MAY_LJMP(check_args(L, 1, "get_stline"));
6087 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6088
6089 if (msg->msg_state > HTTP_MSG_BODY)
6090 WILL_LJMP(lua_error(L));
6091
6092 htx = htxbuf(&msg->chn->buf);
6093 sl = http_get_stline(htx);
6094 if (!sl)
6095 return 0;
6096 return hlua_http_get_stline(L, sl);
6097}
6098
6099/* Returns an array containing all headers of the HTTP message. it relies on
6100 * hlua_http_get_headers().
6101 */
6102__LJMP static int hlua_http_msg_get_headers(lua_State *L)
6103{
6104 struct http_msg *msg;
6105
6106 MAY_LJMP(check_args(L, 1, "get_headers"));
6107 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6108
6109 if (msg->msg_state > HTTP_MSG_BODY)
6110 WILL_LJMP(lua_error(L));
6111
6112 return hlua_http_get_headers(L, msg);
6113}
6114
6115/* Deletes all occurrences of an header in the HTTP message matching on its
6116 * name. It relies on hlua_http_del_hdr().
6117 */
6118__LJMP static int hlua_http_msg_del_hdr(lua_State *L)
6119{
6120 struct http_msg *msg;
6121
6122 MAY_LJMP(check_args(L, 2, "del_header"));
6123 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6124
6125 if (msg->msg_state > HTTP_MSG_BODY)
6126 WILL_LJMP(lua_error(L));
6127
6128 return hlua_http_del_hdr(L, msg);
6129}
6130
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006131/* Matches the full value line of all occurrences of an header in the HTTP
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006132 * message given its name against a regex and replaces it if it matches. It
6133 * relies on hlua_http_rep_hdr().
6134 */
6135__LJMP static int hlua_http_msg_rep_hdr(lua_State *L)
6136{
6137 struct http_msg *msg;
6138
6139 MAY_LJMP(check_args(L, 4, "rep_header"));
6140 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6141
6142 if (msg->msg_state > HTTP_MSG_BODY)
6143 WILL_LJMP(lua_error(L));
6144
6145 return hlua_http_rep_hdr(L, msg, 1);
6146}
6147
Ilya Shipitsinbd6b4be2021-10-15 16:18:21 +05006148/* Matches all comma-separated values of all occurrences of an header in the HTTP
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006149 * message given its name against a regex and replaces it if it matches. It
6150 * relies on hlua_http_rep_hdr().
6151 */
6152__LJMP static int hlua_http_msg_rep_val(lua_State *L)
6153{
6154 struct http_msg *msg;
6155
6156 MAY_LJMP(check_args(L, 4, "rep_value"));
6157 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6158
6159 if (msg->msg_state > HTTP_MSG_BODY)
6160 WILL_LJMP(lua_error(L));
6161
6162 return hlua_http_rep_hdr(L, msg, 0);
6163}
6164
6165/* Add an header in the HTTP message. It relies on hlua_http_add_hdr() */
6166__LJMP static int hlua_http_msg_add_hdr(lua_State *L)
6167{
6168 struct http_msg *msg;
6169
6170 MAY_LJMP(check_args(L, 3, "add_header"));
6171 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6172
6173 if (msg->msg_state > HTTP_MSG_BODY)
6174 WILL_LJMP(lua_error(L));
6175
6176 return hlua_http_add_hdr(L, msg);
6177}
6178
6179/* Add an header in the HTTP message removing existing headers with the same
6180 * name. It relies on hlua_http_del_hdr() and hlua_http_add_hdr().
6181 */
6182__LJMP static int hlua_http_msg_set_hdr(lua_State *L)
6183{
6184 struct http_msg *msg;
6185
6186 MAY_LJMP(check_args(L, 3, "set_header"));
6187 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6188
6189 if (msg->msg_state > HTTP_MSG_BODY)
6190 WILL_LJMP(lua_error(L));
6191
6192 hlua_http_del_hdr(L, msg);
6193 return hlua_http_add_hdr(L, msg);
6194}
6195
6196/* Rewrites the request method. It relies on http_req_replace_stline(). */
6197__LJMP static int hlua_http_msg_set_meth(lua_State *L)
6198{
6199 struct stream *s;
6200 struct http_msg *msg;
6201 const char *name;
6202 size_t name_len;
6203
6204 MAY_LJMP(check_args(L, 2, "set_method"));
6205 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6206 name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
6207
6208 if ((msg->chn->flags & CF_ISRESP) || msg->msg_state > HTTP_MSG_BODY)
6209 WILL_LJMP(lua_error(L));
6210
6211 s = chn_strm(msg->chn);
6212 lua_pushboolean(L, http_req_replace_stline(0, name, name_len, s->be, s) != -1);
6213 return 1;
6214}
6215
6216/* Rewrites the request path. It relies on http_req_replace_stline(). */
6217__LJMP static int hlua_http_msg_set_path(lua_State *L)
6218{
6219 struct stream *s;
6220 struct http_msg *msg;
6221 const char *name;
6222 size_t name_len;
6223
6224 MAY_LJMP(check_args(L, 2, "set_path"));
6225 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6226 name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
6227
6228 if ((msg->chn->flags & CF_ISRESP) || msg->msg_state > HTTP_MSG_BODY)
6229 WILL_LJMP(lua_error(L));
6230
6231 s = chn_strm(msg->chn);
6232 lua_pushboolean(L, http_req_replace_stline(1, name, name_len, s->be, s) != -1);
6233 return 1;
6234}
6235
6236/* Rewrites the request query-string. It relies on http_req_replace_stline(). */
6237__LJMP static int hlua_http_msg_set_query(lua_State *L)
6238{
6239 struct stream *s;
6240 struct http_msg *msg;
6241 const char *name;
6242 size_t name_len;
6243
6244 MAY_LJMP(check_args(L, 2, "set_query"));
6245 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6246 name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
6247
6248 if ((msg->chn->flags & CF_ISRESP) || msg->msg_state > HTTP_MSG_BODY)
6249 WILL_LJMP(lua_error(L));
6250
6251 /* Check length. */
6252 if (name_len > trash.size - 1) {
6253 lua_pushboolean(L, 0);
6254 return 1;
6255 }
6256
6257 /* Add the mark question as prefix. */
6258 chunk_reset(&trash);
6259 trash.area[trash.data++] = '?';
6260 memcpy(trash.area + trash.data, name, name_len);
6261 trash.data += name_len;
6262
6263 s = chn_strm(msg->chn);
6264 lua_pushboolean(L, http_req_replace_stline(2, trash.area, trash.data, s->be, s) != -1);
6265 return 1;
6266}
6267
6268/* Rewrites the request URI. It relies on http_req_replace_stline(). */
6269__LJMP static int hlua_http_msg_set_uri(lua_State *L)
6270{
6271 struct stream *s;
6272 struct http_msg *msg;
6273 const char *name;
6274 size_t name_len;
6275
6276 MAY_LJMP(check_args(L, 2, "set_uri"));
6277 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6278 name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
6279
6280 if ((msg->chn->flags & CF_ISRESP) || msg->msg_state > HTTP_MSG_BODY)
6281 WILL_LJMP(lua_error(L));
6282
6283 s = chn_strm(msg->chn);
6284 lua_pushboolean(L, http_req_replace_stline(3, name, name_len, s->be, s) != -1);
6285 return 1;
6286}
6287
6288/* Rewrites the response status code. It relies on http_res_set_status(). */
6289__LJMP static int hlua_http_msg_set_status(lua_State *L)
6290{
6291 struct http_msg *msg;
6292 unsigned int code;
6293 const char *reason;
6294 size_t reason_len;
6295
6296 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6297 code = MAY_LJMP(luaL_checkinteger(L, 2));
6298 reason = MAY_LJMP(luaL_optlstring(L, 3, NULL, &reason_len));
6299
6300 if (!(msg->chn->flags & CF_ISRESP) || msg->msg_state > HTTP_MSG_BODY)
6301 WILL_LJMP(lua_error(L));
6302
6303 lua_pushboolean(L, http_res_set_status(code, ist2(reason, reason_len), chn_strm(msg->chn)) != -1);
6304 return 1;
6305}
6306
6307/* Returns true if the HTTP message is full. */
6308__LJMP static int hlua_http_msg_is_full(lua_State *L)
6309{
6310 struct http_msg *msg;
6311
6312 MAY_LJMP(check_args(L, 1, "is_full"));
6313 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6314 lua_pushboolean(L, channel_full(msg->chn, 0));
6315 return 1;
6316}
6317
6318/* Returns true if the HTTP message may still receive data. */
6319__LJMP static int hlua_http_msg_may_recv(lua_State *L)
6320{
6321 struct http_msg *msg;
6322 struct htx *htx;
6323
6324 MAY_LJMP(check_args(L, 1, "may_recv"));
6325 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6326 htx = htxbuf(&msg->chn->buf);
6327 lua_pushboolean(L, (htx_expect_more(htx) && !channel_input_closed(msg->chn) && channel_may_recv(msg->chn)));
6328 return 1;
6329}
6330
6331/* Returns true if the HTTP message EOM was received */
6332__LJMP static int hlua_http_msg_is_eom(lua_State *L)
6333{
6334 struct http_msg *msg;
6335 struct htx *htx;
6336
6337 MAY_LJMP(check_args(L, 1, "may_recv"));
6338 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6339 htx = htxbuf(&msg->chn->buf);
6340 lua_pushboolean(L, !htx_expect_more(htx));
6341 return 1;
6342}
6343
6344/* Returns the number of bytes available in the input side of the HTTP
6345 * message. This function never fails.
6346 */
6347__LJMP static int hlua_http_msg_get_in_len(lua_State *L)
6348{
6349 struct http_msg *msg;
Christopher Fauleteae8afa2020-02-26 17:15:48 +01006350 size_t output, input;
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006351
6352 MAY_LJMP(check_args(L, 1, "input"));
6353 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
Christopher Fauleteae8afa2020-02-26 17:15:48 +01006354 hlua_http_msg_filter(L, 1, msg, &output, &input);
6355 lua_pushinteger(L, input);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006356 return 1;
6357}
6358
6359/* Returns the number of bytes available in the output side of the HTTP
6360 * message. This function never fails.
6361 */
6362__LJMP static int hlua_http_msg_get_out_len(lua_State *L)
6363{
6364 struct http_msg *msg;
Christopher Fauleteae8afa2020-02-26 17:15:48 +01006365 size_t output, input;
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006366
6367 MAY_LJMP(check_args(L, 1, "output"));
6368 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
Christopher Fauleteae8afa2020-02-26 17:15:48 +01006369 hlua_http_msg_filter(L, 1, msg, &output, &input);
6370 lua_pushinteger(L, output);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006371 return 1;
6372}
6373
6374/* Copies at most <len> bytes of DATA blocks from the HTTP message <msg>
6375 * starting at the offset <offset> and put it in a string LUA variables. It
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006376 * returns the built string length. It stops on the first non-DATA HTX
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006377 * block. This function is called during the payload filtering, so the headers
6378 * are already scheduled for output (from the filter point of view).
6379 */
6380static int _hlua_http_msg_dup(struct http_msg *msg, lua_State *L, size_t offset, size_t len)
6381{
6382 struct htx *htx = htxbuf(&msg->chn->buf);
6383 struct htx_blk *blk;
6384 struct htx_ret htxret;
6385 luaL_Buffer b;
6386 int ret = 0;
6387
6388 luaL_buffinit(L, &b);
6389 htxret = htx_find_offset(htx, offset);
6390 for (blk = htxret.blk, offset = htxret.ret; blk && len; blk = htx_get_next_blk(htx, blk)) {
6391 enum htx_blk_type type = htx_get_blk_type(blk);
6392 struct ist v;
6393
6394 switch (type) {
6395 case HTX_BLK_UNUSED:
6396 break;
6397
6398 case HTX_BLK_DATA:
6399 v = htx_get_blk_value(htx, blk);
Tim Duesterhusb113b5c2021-09-15 13:58:44 +02006400 v = istadv(v, offset);
Tim Duesterhus2471f5c2021-11-08 09:05:01 +01006401 v = isttrim(v, len);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006402
6403 luaL_addlstring(&b, v.ptr, v.len);
6404 ret += v.len;
6405 break;
6406
6407 default:
vishnu0af4bd72021-10-24 06:46:24 +05306408 if (!ret)
6409 goto no_data;
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006410 goto end;
6411 }
6412 offset = 0;
6413 }
6414
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006415end:
vishnu0af4bd72021-10-24 06:46:24 +05306416 if (!ret && (htx->flags & HTX_FL_EOM))
6417 goto no_data;
6418 luaL_pushresult(&b);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006419 return ret;
vishnu0af4bd72021-10-24 06:46:24 +05306420
6421 no_data:
6422 /* Remove the empty string and push nil on the stack */
6423 lua_pop(L, 1);
6424 lua_pushnil(L);
6425 return 0;
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006426}
6427
6428/* Copies the string <str> to the HTTP message <msg> at the offset
6429 * <offset>. This function returns -1 if data cannot be copied. Otherwise, it
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006430 * returns the amount of data written. This function is responsible to update
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006431 * the filter context.
6432 */
6433static int _hlua_http_msg_insert(struct http_msg *msg, struct filter *filter, struct ist str, size_t offset)
6434{
6435 struct htx *htx = htx_from_buf(&msg->chn->buf);
6436 struct htx_ret htxret;
6437 int /*max, */ret = 0;
6438
6439 /* Nothing to do, just return */
6440 if (unlikely(istlen(str) == 0))
6441 goto end;
6442
6443 if (istlen(str) > htx_free_data_space(htx)) {
6444 ret = -1;
6445 goto end;
6446 }
6447
6448 htxret = htx_find_offset(htx, offset);
6449 if (!htxret.blk || htx_get_blk_type(htxret.blk) != HTX_BLK_DATA) {
6450 if (!htx_add_last_data(htx, str))
6451 goto end;
6452 }
6453 else {
6454 struct ist v = htx_get_blk_value(htx, htxret.blk);
6455 v.ptr += htxret.ret;
6456 v.len = 0;
6457 if (!htx_replace_blk_value(htx, htxret.blk, v, str))
6458 goto end;
6459 }
6460 ret = str.len;
6461 if (ret) {
6462 struct hlua_flt_ctx *flt_ctx = filter->ctx;
6463 flt_update_offsets(filter, msg->chn, ret);
6464 flt_ctx->cur_len[CHN_IDX(msg->chn)] += ret;
6465 }
6466
6467 end:
6468 htx_to_buf(htx, &msg->chn->buf);
6469 return ret;
6470}
6471
6472/* Helper function removing at most <len> bytes of DATA blocks at the absolute
6473 * position <offset>. It stops on the first non-DATA HTX block. This function is
6474 * called during the payload filtering, so the headers are already scheduled for
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006475 * output (from the filter point of view). This function is responsible to
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006476 * update the filter context.
6477 */
6478static void _hlua_http_msg_delete(struct http_msg *msg, struct filter *filter, size_t offset, size_t len)
6479{
6480 struct hlua_flt_ctx *flt_ctx = filter->ctx;
6481 struct htx *htx = htx_from_buf(&msg->chn->buf);
6482 struct htx_blk *blk;
6483 struct htx_ret htxret;
6484 size_t ret = 0;
6485
6486 /* Be sure <len> is always the amount of DATA to remove */
6487 if (htx->data == offset+len && htx_get_tail_type(htx) == HTX_BLK_DATA) {
6488 htx_truncate(htx, offset);
6489 ret = len;
6490 goto end;
6491 }
6492
6493 htxret = htx_find_offset(htx, offset);
6494 blk = htxret.blk;
6495 if (htxret.ret) {
6496 struct ist v;
6497
6498 if (htx_get_blk_type(blk) != HTX_BLK_DATA)
6499 goto end;
6500 v = htx_get_blk_value(htx, blk);
6501 v.ptr += htxret.ret;
Tim Duesterhus2471f5c2021-11-08 09:05:01 +01006502 v = isttrim(v, len);
Tim Duesterhusb113b5c2021-09-15 13:58:44 +02006503 blk = htx_replace_blk_value(htx, blk, v, IST_NULL);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006504 len -= v.len;
6505 ret += v.len;
6506 }
6507
6508
6509 while (blk && len) {
6510 enum htx_blk_type type = htx_get_blk_type(blk);
6511 uint32_t sz = htx_get_blksz(blk);
6512
6513 switch (type) {
6514 case HTX_BLK_UNUSED:
6515 break;
6516
6517 case HTX_BLK_DATA:
6518 if (len < sz) {
6519 htx_cut_data_blk(htx, blk, len);
6520 ret += len;
6521 goto end;
6522 }
6523 break;
6524
6525 default:
6526 goto end;
6527 }
6528
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006529 /* Remove all the data block */
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006530 len -= sz;
6531 ret += sz;
6532 blk = htx_remove_blk(htx, blk);
6533 }
6534
6535end:
6536 flt_update_offsets(filter, msg->chn, -ret);
6537 flt_ctx->cur_len[CHN_IDX(msg->chn)] -= ret;
6538 /* WARNING: we don't call htx_to_buf() on purpose, because we don't want
6539 * to loose the EOM flag if the message is empty.
6540 */
6541}
6542
6543/* Copies input data found in an HTTP message. Unlike the channel function used
6544 * to duplicate raw data, this one can only be called inside a filter, from
6545 * http_payload callback. So it cannot yield. An exception is returned if it is
6546 * called from another callback. If nothing was copied, a nil value is pushed on
6547 * the stack.
6548 */
6549__LJMP static int hlua_http_msg_get_body(lua_State *L)
6550{
6551 struct http_msg *msg;
6552 struct filter *filter;
6553 size_t output, input;
6554 int offset, len;
6555
6556 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
6557 WILL_LJMP(luaL_error(L, "'data' expects at most 2 arguments"));
6558 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6559
6560 if (msg->msg_state < HTTP_MSG_DATA)
6561 WILL_LJMP(lua_error(L));
6562
6563 filter = hlua_http_msg_filter(L, 1, msg, &output, &input);
6564 if (!filter || !hlua_filter_from_payload(filter))
6565 WILL_LJMP(lua_error(L));
6566
6567 if (!ci_data(msg->chn) && channel_input_closed(msg->chn)) {
6568 lua_pushnil(L);
6569 return 1;
6570 }
6571
6572 offset = output;
6573 if (lua_gettop(L) > 1) {
6574 offset = MAY_LJMP(luaL_checkinteger(L, 2));
6575 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02006576 offset = MAX(0, (int)input + offset);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006577 offset += output;
6578 if (offset < output || offset > input + output) {
6579 lua_pushfstring(L, "offset out of range.");
6580 WILL_LJMP(lua_error(L));
6581 }
6582 }
6583 len = output + input - offset;
6584 if (lua_gettop(L) == 3) {
6585 len = MAY_LJMP(luaL_checkinteger(L, 3));
6586 if (!len)
6587 goto dup;
6588 if (len == -1)
6589 len = global.tune.bufsize;
6590 if (len < 0) {
6591 lua_pushfstring(L, "length out of range.");
6592 WILL_LJMP(lua_error(L));
6593 }
6594 }
6595
6596 dup:
6597 _hlua_http_msg_dup(msg, L, offset, len);
6598 return 1;
6599}
6600
6601/* Appends a string to the HTTP message, after all existing DATA blocks but
6602 * before the trailers, if any. It returns the amount of data written or -1 if
6603 * nothing was copied. Unlike the channel function used to append data, this one
6604 * can only be called inside a filter, from http_payload callback. So it cannot
6605 * yield. An exception is returned if it is called from another callback.
6606 */
6607__LJMP static int hlua_http_msg_append(lua_State *L)
6608{
6609 struct http_msg *msg;
6610 struct filter *filter;
6611 const char *str;
6612 size_t offset, len, sz;
6613 int ret;
6614
6615 MAY_LJMP(check_args(L, 2, "append"));
6616 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6617
6618 if (msg->msg_state < HTTP_MSG_DATA)
6619 WILL_LJMP(lua_error(L));
6620
6621 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
6622 filter = hlua_http_msg_filter(L, 1, msg, &offset, &len);
6623 if (!filter || !hlua_filter_from_payload(filter))
6624 WILL_LJMP(lua_error(L));
6625
6626 ret = _hlua_http_msg_insert(msg, filter, ist2(str, sz), offset+len);
6627 lua_pushinteger(L, ret);
6628 return 1;
6629}
6630
6631/* Prepends a string to the HTTP message, before all existing DATA blocks. It
6632 * returns the amount of data written or -1 if nothing was copied. Unlike the
6633 * channel function used to prepend data, this one can only be called inside a
6634 * filter, from http_payload callback. So it cannot yield. An exception is
6635 * returned if it is called from another callback.
6636 */
6637__LJMP static int hlua_http_msg_prepend(lua_State *L)
6638{
6639 struct http_msg *msg;
6640 struct filter *filter;
6641 const char *str;
6642 size_t offset, len, sz;
6643 int ret;
6644
6645 MAY_LJMP(check_args(L, 2, "prepend"));
6646 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006647
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006648 if (msg->msg_state < HTTP_MSG_DATA)
6649 WILL_LJMP(lua_error(L));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006650
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006651 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
6652 filter = hlua_http_msg_filter(L, 1, msg, &offset, &len);
6653 if (!filter || !hlua_filter_from_payload(filter))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006654 WILL_LJMP(lua_error(L));
6655
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006656 ret = _hlua_http_msg_insert(msg, filter, ist2(str, sz), offset);
6657 lua_pushinteger(L, ret);
6658 return 1;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006659}
6660
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006661/* Inserts a string to the HTTP message at a given offset. By default the string
6662 * is appended at the end of DATA blocks. It returns the amount of data written
6663 * or -1 if nothing was copied. Unlike the channel function used to insert data,
6664 * this one can only be called inside a filter, from http_payload callback. So
6665 * it cannot yield. An exception is returned if it is called from another
6666 * callback.
6667 */
6668__LJMP static int hlua_http_msg_insert_data(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006669{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006670 struct http_msg *msg;
6671 struct filter *filter;
6672 const char *str;
6673 size_t input, output, sz;
6674 int offset;
6675 int ret;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006676
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006677 if (lua_gettop(L) < 2 || lua_gettop(L) > 3)
6678 WILL_LJMP(luaL_error(L, "'insert' expects at least 1 argument and at most 2 arguments"));
6679 MAY_LJMP(check_args(L, 2, "insert"));
6680 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006681
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006682 if (msg->msg_state < HTTP_MSG_DATA)
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006683 WILL_LJMP(lua_error(L));
6684
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006685 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
6686 filter = hlua_http_msg_filter(L, 1, msg, &input, &output);
6687 if (!filter || !hlua_filter_from_payload(filter))
6688 WILL_LJMP(lua_error(L));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006689
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006690 offset = input + output;
6691 if (lua_gettop(L) > 2) {
6692 offset = MAY_LJMP(luaL_checkinteger(L, 3));
6693 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02006694 offset = MAX(0, (int)input + offset);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006695 offset += output;
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006696 if (offset < output || offset > output + input) {
6697 lua_pushfstring(L, "offset out of range.");
6698 WILL_LJMP(lua_error(L));
6699 }
6700 }
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006701
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006702 ret = _hlua_http_msg_insert(msg, filter, ist2(str, sz), offset);
6703 lua_pushinteger(L, ret);
6704 return 1;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006705}
6706
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006707/* Removes a given amount of data from the HTTP message at a given offset. By
6708 * default all DATA blocks are removed. It returns the amount of data
6709 * removed. Unlike the channel function used to remove data, this one can only
6710 * be called inside a filter, from http_payload callback. So it cannot yield. An
6711 * exception is returned if it is called from another callback.
6712 */
6713__LJMP static int hlua_http_msg_del_data(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006714{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006715 struct http_msg *msg;
6716 struct filter *filter;
6717 size_t input, output;
6718 int offset, len;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006719
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006720 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
Boyang Lie0c54352022-05-10 17:47:23 +00006721 WILL_LJMP(luaL_error(L, "'remove' expects at most 2 arguments"));
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006722 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006723
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006724 if (msg->msg_state < HTTP_MSG_DATA)
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006725 WILL_LJMP(lua_error(L));
6726
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006727 filter = hlua_http_msg_filter(L, 1, msg, &input, &output);
6728 if (!filter || !hlua_filter_from_payload(filter))
6729 WILL_LJMP(lua_error(L));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006730
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006731 offset = input + output;
Boyang Lie0c54352022-05-10 17:47:23 +00006732 if (lua_gettop(L) > 1) {
6733 offset = MAY_LJMP(luaL_checkinteger(L, 2));
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006734 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02006735 offset = MAX(0, (int)input + offset);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006736 offset += output;
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006737 if (offset < output || offset > output + input) {
6738 lua_pushfstring(L, "offset out of range.");
6739 WILL_LJMP(lua_error(L));
6740 }
6741 }
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006742
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006743 len = output + input - offset;
Boyang Lie0c54352022-05-10 17:47:23 +00006744 if (lua_gettop(L) == 3) {
6745 len = MAY_LJMP(luaL_checkinteger(L, 3));
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006746 if (!len)
6747 goto end;
6748 if (len == -1)
6749 len = output + input - offset;
6750 if (len < 0 || offset + len > output + input) {
6751 lua_pushfstring(L, "length out of range.");
6752 WILL_LJMP(lua_error(L));
6753 }
6754 }
6755
6756 _hlua_http_msg_delete(msg, filter, offset, len);
6757
6758 end:
6759 lua_pushinteger(L, len);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006760 return 1;
6761}
6762
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006763/* Replaces a given amount of data at the given offset by a string. By default,
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006764 * all remaining data are removed, accordingly to the filter context. It returns
6765 * the amount of data written or -1 if nothing was copied. Unlike the channel
6766 * function used to replace data, this one can only be called inside a filter,
6767 * from http_payload callback. So it cannot yield. An exception is returned if
6768 * it is called from another callback.
6769 */
6770__LJMP static int hlua_http_msg_set_data(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006771{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006772 struct http_msg *msg;
6773 struct filter *filter;
6774 struct htx *htx;
6775 const char *str;
6776 size_t input, output, sz;
6777 int offset, len;
6778 int ret;
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02006779
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006780 if (lua_gettop(L) < 2 || lua_gettop(L) > 4)
6781 WILL_LJMP(luaL_error(L, "'set' expects at least 1 argument and at most 3 arguments"));
6782 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6783
6784 if (msg->msg_state < HTTP_MSG_DATA)
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006785 WILL_LJMP(lua_error(L));
6786
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006787 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
6788 filter = hlua_http_msg_filter(L, 1, msg, &output, &input);
6789 if (!filter || !hlua_filter_from_payload(filter))
6790 WILL_LJMP(lua_error(L));
6791
6792 offset = output;
6793 if (lua_gettop(L) > 2) {
6794 offset = MAY_LJMP(luaL_checkinteger(L, 3));
6795 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02006796 offset = MAX(0, (int)input + offset);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006797 offset += output;
6798 if (offset < output || offset > input + output) {
6799 lua_pushfstring(L, "offset out of range.");
6800 WILL_LJMP(lua_error(L));
6801 }
6802 }
6803
6804 len = output + input - offset;
6805 if (lua_gettop(L) == 4) {
6806 len = MAY_LJMP(luaL_checkinteger(L, 4));
6807 if (!len)
6808 goto set;
6809 if (len == -1)
6810 len = output + input - offset;
6811 if (len < 0 || offset + len > output + input) {
6812 lua_pushfstring(L, "length out of range.");
6813 WILL_LJMP(lua_error(L));
6814 }
6815 }
6816
6817 set:
6818 /* Be sure we can copied the string once input data will be removed. */
6819 htx = htx_from_buf(&msg->chn->buf);
6820 if (sz > htx_free_data_space(htx) + len)
6821 lua_pushinteger(L, -1);
6822 else {
6823 _hlua_http_msg_delete(msg, filter, offset, len);
6824 ret = _hlua_http_msg_insert(msg, filter, ist2(str, sz), offset);
6825 lua_pushinteger(L, ret);
6826 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006827 return 1;
6828}
6829
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006830/* Prepends data into an HTTP message and forward it, from the filter point of
6831 * view. It returns the amount of data written or -1 if nothing was sent. Unlike
6832 * the channel function used to send data, this one can only be called inside a
6833 * filter, from http_payload callback. So it cannot yield. An exception is
6834 * returned if it is called from another callback.
6835 */
6836__LJMP static int hlua_http_msg_send(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006837{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006838 struct http_msg *msg;
6839 struct filter *filter;
6840 struct htx *htx;
6841 const char *str;
6842 size_t offset, len, sz;
6843 int ret;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006844
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006845 MAY_LJMP(check_args(L, 2, "send"));
6846 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6847
6848 if (msg->msg_state < HTTP_MSG_DATA)
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006849 WILL_LJMP(lua_error(L));
6850
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006851 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
6852 filter = hlua_http_msg_filter(L, 1, msg, &offset, &len);
6853 if (!filter || !hlua_filter_from_payload(filter))
6854 WILL_LJMP(lua_error(L));
6855
6856 /* Return an error if the channel's output is closed */
6857 if (unlikely(channel_output_closed(msg->chn))) {
6858 lua_pushinteger(L, -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006859 return 1;
6860 }
6861
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006862 htx = htx_from_buf(&msg->chn->buf);
6863 if (sz > htx_free_data_space(htx)) {
6864 lua_pushinteger(L, -1);
6865 return 1;
6866 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006867
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006868 ret = _hlua_http_msg_insert(msg, filter, ist2(str, sz), offset);
6869 if (ret > 0) {
6870 struct hlua_flt_ctx *flt_ctx = filter->ctx;
6871
6872 FLT_OFF(filter, msg->chn) += ret;
6873 flt_ctx->cur_len[CHN_IDX(msg->chn)] -= ret;
6874 flt_ctx->cur_off[CHN_IDX(msg->chn)] += ret;
6875 }
6876
6877 lua_pushinteger(L, ret);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006878 return 1;
6879}
6880
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006881/* Forwards a given amount of bytes. It return -1 if the channel's output is
6882 * closed. Otherwise, it returns the number of bytes forwarded. Unlike the
6883 * channel function used to forward data, this one can only be called inside a
6884 * filter, from http_payload callback. So it cannot yield. An exception is
6885 * returned if it is called from another callback. All other functions deal with
6886 * DATA block, this one not.
6887*/
6888__LJMP static int hlua_http_msg_forward(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006889{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006890 struct http_msg *msg;
6891 struct filter *filter;
6892 size_t offset, len;
6893 int fwd, ret = 0;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006894
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006895 MAY_LJMP(check_args(L, 2, "forward"));
6896 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6897
6898 if (msg->msg_state < HTTP_MSG_DATA)
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006899 WILL_LJMP(lua_error(L));
6900
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006901 fwd = MAY_LJMP(luaL_checkinteger(L, 2));
6902 filter = hlua_http_msg_filter(L, 1, msg, &offset, &len);
6903 if (!filter || !hlua_filter_from_payload(filter))
6904 WILL_LJMP(lua_error(L));
6905
6906 /* Nothing to do, just return */
6907 if (!fwd)
6908 goto end;
6909
6910 /* Return an error if the channel's output is closed */
6911 if (unlikely(channel_output_closed(msg->chn))) {
6912 ret = -1;
6913 goto end;
6914 }
6915
6916 ret = fwd;
6917 if (ret > len)
6918 ret = len;
6919
6920 if (ret) {
6921 struct hlua_flt_ctx *flt_ctx = filter->ctx;
6922
6923 FLT_OFF(filter, msg->chn) += ret;
6924 flt_ctx->cur_off[CHN_IDX(msg->chn)] += ret;
6925 flt_ctx->cur_len[CHN_IDX(msg->chn)] -= ret;
6926 }
6927
6928 end:
6929 lua_pushinteger(L, ret);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006930 return 1;
6931}
6932
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006933/* Set EOM flag on the HTX message.
6934 *
6935 * NOTE: Not sure it is a good idea to manipulate this flag but for now I don't
6936 * really know how to do without this feature.
6937 */
6938__LJMP static int hlua_http_msg_set_eom(lua_State *L)
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02006939{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006940 struct http_msg *msg;
6941 struct htx *htx;
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02006942
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006943 MAY_LJMP(check_args(L, 1, "set_eom"));
6944 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6945 htx = htxbuf(&msg->chn->buf);
6946 htx->flags |= HTX_FL_EOM;
6947 return 0;
6948}
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006949
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006950/* Unset EOM flag on the HTX message.
6951 *
6952 * NOTE: Not sure it is a good idea to manipulate this flag but for now I don't
6953 * really know how to do without this feature.
6954 */
6955__LJMP static int hlua_http_msg_unset_eom(lua_State *L)
6956{
6957 struct http_msg *msg;
6958 struct htx *htx;
6959
6960 MAY_LJMP(check_args(L, 1, "set_eom"));
6961 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6962 htx = htxbuf(&msg->chn->buf);
6963 htx->flags &= ~HTX_FL_EOM;
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02006964 return 0;
6965}
6966
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006967/*
6968 *
6969 *
William Lallemand3956c4e2021-09-21 16:25:15 +02006970 * Class HTTPClient
6971 *
6972 *
6973 */
6974__LJMP static struct hlua_httpclient *hlua_checkhttpclient(lua_State *L, int ud)
6975{
6976 return MAY_LJMP(hlua_checkudata(L, ud, class_httpclient_ref));
6977}
6978
William Lallemandf77f1de2021-09-28 19:10:38 +02006979
6980/* stops the httpclient and ask it to kill itself */
6981__LJMP static int hlua_httpclient_gc(lua_State *L)
6982{
6983 struct hlua_httpclient *hlua_hc;
6984
6985 MAY_LJMP(check_args(L, 1, "__gc"));
6986
6987 hlua_hc = MAY_LJMP(hlua_checkhttpclient(L, 1));
6988
6989 httpclient_stop_and_destroy(hlua_hc->hc);
6990
6991 hlua_hc->hc = NULL;
6992
6993
6994 return 0;
6995}
6996
6997
William Lallemand3956c4e2021-09-21 16:25:15 +02006998__LJMP static int hlua_httpclient_new(lua_State *L)
6999{
7000 struct hlua_httpclient *hlua_hc;
7001 struct hlua *hlua;
7002
7003 /* Get hlua struct, or NULL if we execute from main lua state */
7004 hlua = hlua_gethlua(L);
7005 if (!hlua)
7006 return 0;
7007
7008 /* Check stack size. */
7009 if (!lua_checkstack(L, 3)) {
7010 hlua_pusherror(L, "httpclient: full stack");
7011 goto err;
7012 }
7013 /* Create the object: obj[0] = userdata. */
7014 lua_newtable(L);
7015 hlua_hc = MAY_LJMP(lua_newuserdata(L, sizeof(*hlua_hc)));
7016 lua_rawseti(L, -2, 0);
7017 memset(hlua_hc, 0, sizeof(*hlua_hc));
7018
7019 hlua_hc->hc = httpclient_new(hlua, 0, IST_NULL);
7020 if (!hlua_hc->hc)
7021 goto err;
7022
7023 /* Pop a class stream metatable and affect it to the userdata. */
7024 lua_rawgeti(L, LUA_REGISTRYINDEX, class_httpclient_ref);
7025 lua_setmetatable(L, -2);
7026
7027 return 1;
7028
7029 err:
7030 WILL_LJMP(lua_error(L));
7031 return 0;
7032}
7033
7034
7035/*
7036 * Callback of the httpclient, this callback wakes the lua task up, once the
7037 * httpclient receives some data
7038 *
7039 */
7040
William Lallemandbd5739e2021-10-28 15:41:38 +02007041static void hlua_httpclient_cb(struct httpclient *hc)
William Lallemand3956c4e2021-09-21 16:25:15 +02007042{
7043 struct hlua *hlua = hc->caller;
7044
7045 if (!hlua || !hlua->task)
7046 return;
7047
7048 task_wakeup(hlua->task, TASK_WOKEN_MSG);
7049}
7050
7051/*
William Lallemandd7df73a2021-09-23 17:54:00 +02007052 * Fill the lua stack with headers from the httpclient response
7053 * This works the same way as the hlua_http_get_headers() function
7054 */
7055__LJMP static int hlua_httpclient_get_headers(lua_State *L, struct hlua_httpclient *hlua_hc)
7056{
7057 struct http_hdr *hdr;
7058
7059 lua_newtable(L);
7060
William Lallemandef574b22021-10-05 16:19:31 +02007061 for (hdr = hlua_hc->hc->res.hdrs; hdr && isttest(hdr->n); hdr++) {
William Lallemandd7df73a2021-09-23 17:54:00 +02007062 struct ist n, v;
7063 int len;
7064
7065 n = hdr->n;
7066 v = hdr->v;
7067
7068 /* Check for existing entry:
7069 * assume that the table is on the top of the stack, and
7070 * push the key in the stack, the function lua_gettable()
7071 * perform the lookup.
7072 */
7073
7074 lua_pushlstring(L, n.ptr, n.len);
7075 lua_gettable(L, -2);
7076
7077 switch (lua_type(L, -1)) {
7078 case LUA_TNIL:
7079 /* Table not found, create it. */
7080 lua_pop(L, 1); /* remove the nil value. */
7081 lua_pushlstring(L, n.ptr, n.len); /* push the header name as key. */
7082 lua_newtable(L); /* create and push empty table. */
7083 lua_pushlstring(L, v.ptr, v.len); /* push header value. */
7084 lua_rawseti(L, -2, 0); /* index header value (pop it). */
7085 lua_rawset(L, -3); /* index new table with header name (pop the values). */
7086 break;
7087
7088 case LUA_TTABLE:
7089 /* Entry found: push the value in the table. */
7090 len = lua_rawlen(L, -1);
7091 lua_pushlstring(L, v.ptr, v.len); /* push header value. */
7092 lua_rawseti(L, -2, len+1); /* index header value (pop it). */
7093 lua_pop(L, 1); /* remove the table (it is stored in the main table). */
7094 break;
7095
7096 default:
7097 /* Other cases are errors. */
7098 hlua_pusherror(L, "internal error during the parsing of headers.");
7099 WILL_LJMP(lua_error(L));
7100 }
7101 }
7102 return 1;
7103}
7104
7105/*
William Lallemand746e6f32021-10-06 10:57:44 +02007106 * Allocate and return an array of http_hdr ist extracted from the <headers> lua table
7107 *
7108 * Caller must free the result
7109 */
7110struct http_hdr *hlua_httpclient_table_to_hdrs(lua_State *L)
7111{
7112 struct http_hdr hdrs[global.tune.max_http_hdr];
7113 struct http_hdr *result = NULL;
7114 uint32_t hdr_num = 0;
7115
7116 lua_pushnil(L);
7117 while (lua_next(L, -2) != 0) {
7118 struct ist name, value;
7119 const char *n, *v;
7120 size_t nlen, vlen;
7121
7122 if (!lua_isstring(L, -2) || !lua_istable(L, -1)) {
7123 /* Skip element if the key is not a string or if the value is not a table */
7124 goto next_hdr;
7125 }
7126
7127 n = lua_tolstring(L, -2, &nlen);
7128 name = ist2(n, nlen);
7129
7130 /* Loop on header's values */
7131 lua_pushnil(L);
7132 while (lua_next(L, -2)) {
7133 if (!lua_isstring(L, -1)) {
7134 /* Skip the value if it is not a string */
7135 goto next_value;
7136 }
7137
7138 v = lua_tolstring(L, -1, &vlen);
7139 value = ist2(v, vlen);
7140 name = ist2(n, nlen);
7141
7142 hdrs[hdr_num].n = istdup(name);
7143 hdrs[hdr_num].v = istdup(value);
7144
7145 hdr_num++;
7146
7147 next_value:
7148 lua_pop(L, 1);
7149 }
7150
7151 next_hdr:
7152 lua_pop(L, 1);
7153
7154 }
7155
7156 if (hdr_num) {
7157 /* alloc and copy the headers in the httpclient struct */
Tim Duesterhus16cc16d2021-11-06 15:14:45 +01007158 result = calloc((hdr_num + 1), sizeof(*result));
William Lallemand746e6f32021-10-06 10:57:44 +02007159 if (!result)
7160 goto skip_headers;
7161 memcpy(result, hdrs, sizeof(struct http_hdr) * (hdr_num + 1));
7162
7163 result[hdr_num].n = IST_NULL;
7164 result[hdr_num].v = IST_NULL;
7165 }
7166
7167skip_headers:
William Lallemand746e6f32021-10-06 10:57:44 +02007168
7169 return result;
7170}
7171
7172
William Lallemandbd5739e2021-10-28 15:41:38 +02007173/*
7174 * For each yield, checks if there is some data in the httpclient and push them
7175 * in the lua buffer, once the httpclient finished its job, push the result on
7176 * the stack
7177 */
7178__LJMP static int hlua_httpclient_rcv_yield(lua_State *L, int status, lua_KContext ctx)
7179{
7180 struct buffer *tr;
7181 int res;
7182 struct hlua *hlua = hlua_gethlua(L);
7183 struct hlua_httpclient *hlua_hc = hlua_checkhttpclient(L, 1);
7184
7185
7186 tr = get_trash_chunk();
7187
7188 res = httpclient_res_xfer(hlua_hc->hc, tr);
7189 luaL_addlstring(&hlua_hc->b, b_orig(tr), res);
7190
7191 if (!httpclient_data(hlua_hc->hc) && httpclient_ended(hlua_hc->hc)) {
7192
7193 luaL_pushresult(&hlua_hc->b);
7194 lua_settable(L, -3);
7195
7196 lua_pushstring(L, "status");
7197 lua_pushinteger(L, hlua_hc->hc->res.status);
7198 lua_settable(L, -3);
7199
7200
7201 lua_pushstring(L, "reason");
7202 lua_pushlstring(L, hlua_hc->hc->res.reason.ptr, hlua_hc->hc->res.reason.len);
7203 lua_settable(L, -3);
7204
7205 lua_pushstring(L, "headers");
7206 hlua_httpclient_get_headers(L, hlua_hc);
7207 lua_settable(L, -3);
7208
7209 return 1;
7210 }
7211
7212 if (httpclient_data(hlua_hc->hc))
7213 task_wakeup(hlua->task, TASK_WOKEN_MSG);
7214
7215 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_httpclient_rcv_yield, TICK_ETERNITY, 0));
7216
7217 return 0;
7218}
7219
7220/*
7221 * Call this when trying to stream a body during a request
7222 */
7223__LJMP static int hlua_httpclient_snd_yield(lua_State *L, int status, lua_KContext ctx)
7224{
7225 struct hlua *hlua;
7226 struct hlua_httpclient *hlua_hc = hlua_checkhttpclient(L, 1);
7227 const char *body_str = NULL;
7228 int ret;
7229 int end = 0;
7230 size_t buf_len;
7231 size_t to_send = 0;
7232
7233 hlua = hlua_gethlua(L);
7234
7235 if (!hlua || !hlua->task)
7236 WILL_LJMP(luaL_error(L, "The 'get' function is only allowed in "
7237 "'frontend', 'backend' or 'task'"));
7238
7239 ret = lua_getfield(L, -1, "body");
7240 if (ret != LUA_TSTRING)
7241 goto rcv;
7242
7243 body_str = lua_tolstring(L, -1, &buf_len);
7244 lua_pop(L, 1);
7245
Christopher Fauletfc591292022-01-12 14:46:03 +01007246 to_send = buf_len - hlua_hc->sent;
William Lallemandbd5739e2021-10-28 15:41:38 +02007247
7248 if ((hlua_hc->sent + to_send) >= buf_len)
7249 end = 1;
7250
7251 /* the end flag is always set since we are using the whole remaining size */
7252 hlua_hc->sent += httpclient_req_xfer(hlua_hc->hc, ist2(body_str + hlua_hc->sent, to_send), end);
7253
7254 if (buf_len > hlua_hc->sent) {
7255 /* still need to process the buffer */
7256 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_httpclient_snd_yield, TICK_ETERNITY, 0));
7257 } else {
7258 goto rcv;
7259 /* we sent the whole request buffer we can recv */
7260 }
7261 return 0;
7262
7263rcv:
7264
7265 /* we return a "res" object */
7266 lua_newtable(L);
7267
William Lallemandbd5739e2021-10-28 15:41:38 +02007268 lua_pushstring(L, "body");
William Lallemandd1187eb2021-11-02 10:40:06 +01007269 luaL_buffinit(L, &hlua_hc->b);
William Lallemandbd5739e2021-10-28 15:41:38 +02007270
William Lallemand933fe392021-11-04 09:45:58 +01007271 task_wakeup(hlua->task, TASK_WOKEN_MSG);
William Lallemandbd5739e2021-10-28 15:41:38 +02007272 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_httpclient_rcv_yield, TICK_ETERNITY, 0));
7273
7274 return 1;
7275}
William Lallemand746e6f32021-10-06 10:57:44 +02007276
William Lallemand3956c4e2021-09-21 16:25:15 +02007277/*
William Lallemanddc2cc902021-10-26 11:43:26 +02007278 * Send an HTTP request and wait for a response
William Lallemand3956c4e2021-09-21 16:25:15 +02007279 */
7280
William Lallemanddc2cc902021-10-26 11:43:26 +02007281__LJMP static int hlua_httpclient_send(lua_State *L, enum http_meth_t meth)
William Lallemand3956c4e2021-09-21 16:25:15 +02007282{
7283 struct hlua_httpclient *hlua_hc;
William Lallemand746e6f32021-10-06 10:57:44 +02007284 struct http_hdr *hdrs = NULL;
7285 struct http_hdr *hdrs_i = NULL;
William Lallemand3956c4e2021-09-21 16:25:15 +02007286 struct hlua *hlua;
William Lallemand746e6f32021-10-06 10:57:44 +02007287 const char *url_str = NULL;
William Lallemanddec25c32021-10-25 19:48:37 +02007288 const char *body_str = NULL;
William Lallemandbd5739e2021-10-28 15:41:38 +02007289 size_t buf_len;
William Lallemand746e6f32021-10-06 10:57:44 +02007290 int ret;
William Lallemand3956c4e2021-09-21 16:25:15 +02007291
7292 hlua = hlua_gethlua(L);
7293
7294 if (!hlua || !hlua->task)
7295 WILL_LJMP(luaL_error(L, "The 'get' function is only allowed in "
7296 "'frontend', 'backend' or 'task'"));
7297
William Lallemand746e6f32021-10-06 10:57:44 +02007298 if (lua_gettop(L) != 2 || lua_type(L, -1) != LUA_TTABLE)
7299 WILL_LJMP(luaL_error(L, "'get' needs a table as argument"));
7300
William Lallemand4f4f2b72022-02-17 20:00:23 +01007301 hlua_hc = hlua_checkhttpclient(L, 1);
7302
William Lallemand7177a952022-03-03 15:33:12 +01007303 lua_pushnil(L); /* first key */
7304 while (lua_next(L, 2)) {
7305 if (strcmp(lua_tostring(L, -2), "dst") == 0) {
7306 if (httpclient_set_dst(hlua_hc->hc, lua_tostring(L, -1)) < 0)
7307 WILL_LJMP(luaL_error(L, "Can't use the 'dst' argument"));
William Lallemand4f4f2b72022-02-17 20:00:23 +01007308
William Lallemand7177a952022-03-03 15:33:12 +01007309 } else if (strcmp(lua_tostring(L, -2), "url") == 0) {
7310 if (lua_type(L, -1) != LUA_TSTRING)
7311 WILL_LJMP(luaL_error(L, "invalid parameter in 'url', must be a string"));
7312 url_str = lua_tostring(L, -1);
William Lallemand3956c4e2021-09-21 16:25:15 +02007313
William Lallemand7177a952022-03-03 15:33:12 +01007314 } else if (strcmp(lua_tostring(L, -2), "timeout") == 0) {
7315 if (lua_type(L, -1) != LUA_TNUMBER)
7316 WILL_LJMP(luaL_error(L, "invalid parameter in 'timeout', must be a number"));
7317 httpclient_set_timeout(hlua_hc->hc, lua_tointeger(L, -1));
William Lallemandb4a4ef62022-02-23 14:18:16 +01007318
William Lallemand7177a952022-03-03 15:33:12 +01007319 } else if (strcmp(lua_tostring(L, -2), "headers") == 0) {
7320 if (lua_type(L, -1) != LUA_TTABLE)
7321 WILL_LJMP(luaL_error(L, "invalid parameter in 'headers', must be a table"));
7322 hdrs = hlua_httpclient_table_to_hdrs(L);
William Lallemand79416cb2021-09-24 14:51:44 +02007323
William Lallemand7177a952022-03-03 15:33:12 +01007324 } else if (strcmp(lua_tostring(L, -2), "body") == 0) {
7325 if (lua_type(L, -1) != LUA_TSTRING)
7326 WILL_LJMP(luaL_error(L, "invalid parameter in 'body', must be a string"));
7327 body_str = lua_tolstring(L, -1, &buf_len);
William Lallemandbd5739e2021-10-28 15:41:38 +02007328
William Lallemand7177a952022-03-03 15:33:12 +01007329 } else {
7330 WILL_LJMP(luaL_error(L, "'%s' invalid parameter name", lua_tostring(L, -2)));
7331 }
7332 /* removes 'value'; keeps 'key' for next iteration */
7333 lua_pop(L, 1);
7334 }
William Lallemanddec25c32021-10-25 19:48:37 +02007335
William Lallemand746e6f32021-10-06 10:57:44 +02007336 if (!url_str) {
7337 WILL_LJMP(luaL_error(L, "'get' need a 'url' argument"));
7338 return 0;
7339 }
William Lallemand3956c4e2021-09-21 16:25:15 +02007340
William Lallemand10a37362022-03-02 16:18:26 +01007341 hlua_hc->sent = 0;
William Lallemand3956c4e2021-09-21 16:25:15 +02007342
7343 hlua_hc->hc->req.url = istdup(ist(url_str));
William Lallemanddc2cc902021-10-26 11:43:26 +02007344 hlua_hc->hc->req.meth = meth;
William Lallemand3956c4e2021-09-21 16:25:15 +02007345
7346 /* update the httpclient callbacks */
William Lallemandbd5739e2021-10-28 15:41:38 +02007347 hlua_hc->hc->ops.res_stline = hlua_httpclient_cb;
7348 hlua_hc->hc->ops.res_headers = hlua_httpclient_cb;
7349 hlua_hc->hc->ops.res_payload = hlua_httpclient_cb;
William Lallemand8f170c72022-03-15 10:52:07 +01007350 hlua_hc->hc->ops.res_end = hlua_httpclient_cb;
William Lallemand3956c4e2021-09-21 16:25:15 +02007351
William Lallemandbd5739e2021-10-28 15:41:38 +02007352 /* a body is available, it will use the request callback */
7353 if (body_str) {
7354 hlua_hc->hc->ops.req_payload = hlua_httpclient_cb;
7355 }
William Lallemand3956c4e2021-09-21 16:25:15 +02007356
William Lallemandbd5739e2021-10-28 15:41:38 +02007357 ret = httpclient_req_gen(hlua_hc->hc, hlua_hc->hc->req.url, meth, hdrs, IST_NULL);
William Lallemand3956c4e2021-09-21 16:25:15 +02007358
William Lallemand746e6f32021-10-06 10:57:44 +02007359 /* free the temporary headers array */
7360 hdrs_i = hdrs;
7361 while (hdrs_i && isttest(hdrs_i->n)) {
7362 istfree(&hdrs_i->n);
7363 istfree(&hdrs_i->v);
7364 hdrs_i++;
7365 }
7366 ha_free(&hdrs);
7367
7368
William Lallemand6137a9e2021-10-26 15:01:53 +02007369 if (ret != ERR_NONE) {
7370 WILL_LJMP(luaL_error(L, "Can't generate the HTTP request"));
7371 return 0;
7372 }
7373
William Lallemandc2d3db42022-04-26 11:46:13 +02007374 if (!httpclient_start(hlua_hc->hc))
7375 WILL_LJMP(luaL_error(L, "couldn't start the httpclient"));
William Lallemand6137a9e2021-10-26 15:01:53 +02007376
William Lallemandbd5739e2021-10-28 15:41:38 +02007377 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_httpclient_snd_yield, TICK_ETERNITY, 0));
William Lallemand3956c4e2021-09-21 16:25:15 +02007378
William Lallemand3956c4e2021-09-21 16:25:15 +02007379 return 0;
7380}
7381
7382/*
William Lallemanddc2cc902021-10-26 11:43:26 +02007383 * Sends an HTTP HEAD request and wait for a response
7384 *
7385 * httpclient:head(url, headers, payload)
7386 */
7387__LJMP static int hlua_httpclient_head(lua_State *L)
7388{
7389 return hlua_httpclient_send(L, HTTP_METH_HEAD);
7390}
7391
7392/*
7393 * Send an HTTP GET request and wait for a response
7394 *
7395 * httpclient:get(url, headers, payload)
7396 */
7397__LJMP static int hlua_httpclient_get(lua_State *L)
7398{
7399 return hlua_httpclient_send(L, HTTP_METH_GET);
7400
7401}
7402
7403/*
7404 * Sends an HTTP PUT request and wait for a response
7405 *
7406 * httpclient:put(url, headers, payload)
7407 */
7408__LJMP static int hlua_httpclient_put(lua_State *L)
7409{
7410 return hlua_httpclient_send(L, HTTP_METH_PUT);
7411}
7412
7413/*
7414 * Send an HTTP POST request and wait for a response
7415 *
7416 * httpclient:post(url, headers, payload)
7417 */
7418__LJMP static int hlua_httpclient_post(lua_State *L)
7419{
7420 return hlua_httpclient_send(L, HTTP_METH_POST);
7421}
7422
7423
7424/*
7425 * Sends an HTTP DELETE request and wait for a response
7426 *
7427 * httpclient:delete(url, headers, payload)
7428 */
7429__LJMP static int hlua_httpclient_delete(lua_State *L)
7430{
7431 return hlua_httpclient_send(L, HTTP_METH_DELETE);
7432}
7433
7434/*
William Lallemand3956c4e2021-09-21 16:25:15 +02007435 *
7436 *
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007437 * Class TXN
7438 *
7439 *
7440 */
7441
7442/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02007443 * a class stream, otherwise it throws an error.
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007444 */
7445__LJMP static struct hlua_txn *hlua_checktxn(lua_State *L, int ud)
7446{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02007447 return MAY_LJMP(hlua_checkudata(L, ud, class_txn_ref));
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007448}
7449
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007450__LJMP static int hlua_set_var(lua_State *L)
7451{
7452 struct hlua_txn *htxn;
7453 const char *name;
7454 size_t len;
7455 struct sample smp;
7456
Tim Duesterhus4e172c92020-05-19 13:49:42 +02007457 if (lua_gettop(L) < 3 || lua_gettop(L) > 4)
7458 WILL_LJMP(luaL_error(L, "'set_var' needs between 3 and 4 arguments"));
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007459
7460 /* It is useles to retrieve the stream, but this function
7461 * runs only in a stream context.
7462 */
7463 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7464 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
7465
7466 /* Converts the third argument in a sample. */
Amaury Denoyellebc0af6a2020-10-29 17:21:20 +01007467 memset(&smp, 0, sizeof(smp));
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007468 hlua_lua2smp(L, 3, &smp);
7469
7470 /* Store the sample in a variable. */
Willy Tarreau7560dd42016-03-10 16:28:58 +01007471 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
Tim Duesterhus4e172c92020-05-19 13:49:42 +02007472
7473 if (lua_gettop(L) == 4 && lua_toboolean(L, 4))
7474 lua_pushboolean(L, vars_set_by_name_ifexist(name, len, &smp) != 0);
7475 else
7476 lua_pushboolean(L, vars_set_by_name(name, len, &smp) != 0);
7477
Tim Duesterhus84ebc132020-05-19 13:49:41 +02007478 return 1;
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007479}
7480
Christopher Faulet85d79c92016-11-09 16:54:56 +01007481__LJMP static int hlua_unset_var(lua_State *L)
7482{
7483 struct hlua_txn *htxn;
7484 const char *name;
7485 size_t len;
7486 struct sample smp;
7487
7488 MAY_LJMP(check_args(L, 2, "unset_var"));
7489
7490 /* It is useles to retrieve the stream, but this function
7491 * runs only in a stream context.
7492 */
7493 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7494 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
7495
7496 /* Unset the variable. */
7497 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
Tim Duesterhus84ebc132020-05-19 13:49:41 +02007498 lua_pushboolean(L, vars_unset_by_name_ifexist(name, len, &smp) != 0);
7499 return 1;
Christopher Faulet85d79c92016-11-09 16:54:56 +01007500}
7501
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007502__LJMP static int hlua_get_var(lua_State *L)
7503{
7504 struct hlua_txn *htxn;
7505 const char *name;
7506 size_t len;
7507 struct sample smp;
7508
7509 MAY_LJMP(check_args(L, 2, "get_var"));
7510
7511 /* It is useles to retrieve the stream, but this function
7512 * runs only in a stream context.
7513 */
7514 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7515 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
7516
Willy Tarreau7560dd42016-03-10 16:28:58 +01007517 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
Willy Tarreaue352b9d2021-09-03 11:52:38 +02007518 if (!vars_get_by_name(name, len, &smp, NULL)) {
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007519 lua_pushnil(L);
7520 return 1;
7521 }
7522
7523 return hlua_smp2lua(L, &smp);
7524}
7525
Willy Tarreau59551662015-03-10 14:23:13 +01007526__LJMP static int hlua_set_priv(lua_State *L)
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007527{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007528 struct hlua *hlua;
7529
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007530 MAY_LJMP(check_args(L, 2, "set_priv"));
7531
Willy Tarreau87b09662015-04-03 00:22:06 +02007532 /* It is useles to retrieve the stream, but this function
7533 * runs only in a stream context.
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007534 */
7535 MAY_LJMP(hlua_checktxn(L, 1));
Thierry Fournier4234dbd2020-11-28 13:18:23 +01007536
7537 /* Get hlua struct, or NULL if we execute from main lua state */
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007538 hlua = hlua_gethlua(L);
Thierry Fournier4234dbd2020-11-28 13:18:23 +01007539 if (!hlua)
7540 return 0;
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007541
7542 /* Remove previous value. */
Thierry FOURNIERe068b602017-04-26 13:27:05 +02007543 luaL_unref(L, LUA_REGISTRYINDEX, hlua->Mref);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007544
7545 /* Get and store new value. */
7546 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
7547 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
7548
7549 return 0;
7550}
7551
Willy Tarreau59551662015-03-10 14:23:13 +01007552__LJMP static int hlua_get_priv(lua_State *L)
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007553{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007554 struct hlua *hlua;
7555
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007556 MAY_LJMP(check_args(L, 1, "get_priv"));
7557
Willy Tarreau87b09662015-04-03 00:22:06 +02007558 /* It is useles to retrieve the stream, but this function
7559 * runs only in a stream context.
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007560 */
7561 MAY_LJMP(hlua_checktxn(L, 1));
Thierry Fournier4234dbd2020-11-28 13:18:23 +01007562
7563 /* Get hlua struct, or NULL if we execute from main lua state */
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007564 hlua = hlua_gethlua(L);
Thierry Fournier4234dbd2020-11-28 13:18:23 +01007565 if (!hlua) {
7566 lua_pushnil(L);
7567 return 1;
7568 }
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007569
7570 /* Push configuration index in the stack. */
7571 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
7572
7573 return 1;
7574}
7575
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007576/* Create stack entry containing a class TXN. This function
7577 * return 0 if the stack does not contains free slots,
7578 * otherwise it returns 1.
7579 */
Thierry FOURNIERab00df62016-07-14 11:42:37 +02007580static int hlua_txn_new(lua_State *L, struct stream *s, struct proxy *p, int dir, int flags)
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007581{
Willy Tarreaude491382015-04-06 11:04:28 +02007582 struct hlua_txn *htxn;
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007583
7584 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01007585 if (!lua_checkstack(L, 3))
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007586 return 0;
7587
7588 /* NOTE: The allocation never fails. The failure
7589 * throw an error, and the function never returns.
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08007590 * if the throw is not available, the process is aborted.
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007591 */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01007592 /* Create the object: obj[0] = userdata. */
7593 lua_newtable(L);
Willy Tarreaude491382015-04-06 11:04:28 +02007594 htxn = lua_newuserdata(L, sizeof(*htxn));
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01007595 lua_rawseti(L, -2, 0);
7596
Willy Tarreaude491382015-04-06 11:04:28 +02007597 htxn->s = s;
7598 htxn->p = p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01007599 htxn->dir = dir;
Thierry FOURNIERab00df62016-07-14 11:42:37 +02007600 htxn->flags = flags;
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007601
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01007602 /* Create the "f" field that contains a list of fetches. */
7603 lua_pushstring(L, "f");
Thierry FOURNIERca988662015-12-20 18:43:03 +01007604 if (!hlua_fetches_new(L, htxn, HLUA_F_MAY_USE_HTTP))
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01007605 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007606 lua_rawset(L, -3);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01007607
7608 /* Create the "sf" field that contains a list of stringsafe fetches. */
7609 lua_pushstring(L, "sf");
Thierry FOURNIERca988662015-12-20 18:43:03 +01007610 if (!hlua_fetches_new(L, htxn, HLUA_F_MAY_USE_HTTP | HLUA_F_AS_STRING))
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01007611 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007612 lua_rawset(L, -3);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01007613
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007614 /* Create the "c" field that contains a list of converters. */
7615 lua_pushstring(L, "c");
Willy Tarreaude491382015-04-06 11:04:28 +02007616 if (!hlua_converters_new(L, htxn, 0))
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01007617 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007618 lua_rawset(L, -3);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01007619
7620 /* Create the "sc" field that contains a list of stringsafe converters. */
7621 lua_pushstring(L, "sc");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01007622 if (!hlua_converters_new(L, htxn, HLUA_F_AS_STRING))
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007623 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007624 lua_rawset(L, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007625
Thierry FOURNIER397826a2015-03-11 19:39:09 +01007626 /* Create the "req" field that contains the request channel object. */
7627 lua_pushstring(L, "req");
Willy Tarreau2a71af42015-03-10 13:51:50 +01007628 if (!hlua_channel_new(L, &s->req))
Thierry FOURNIER397826a2015-03-11 19:39:09 +01007629 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007630 lua_rawset(L, -3);
Thierry FOURNIER397826a2015-03-11 19:39:09 +01007631
7632 /* Create the "res" field that contains the response channel object. */
7633 lua_pushstring(L, "res");
Willy Tarreau2a71af42015-03-10 13:51:50 +01007634 if (!hlua_channel_new(L, &s->res))
Thierry FOURNIER397826a2015-03-11 19:39:09 +01007635 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007636 lua_rawset(L, -3);
Thierry FOURNIER397826a2015-03-11 19:39:09 +01007637
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007638 /* Creates the HTTP object is the current proxy allows http. */
7639 lua_pushstring(L, "http");
Christopher Faulet1bb6afa2021-03-08 17:57:53 +01007640 if (IS_HTX_STRM(s)) {
Willy Tarreaude491382015-04-06 11:04:28 +02007641 if (!hlua_http_new(L, htxn))
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007642 return 0;
7643 }
7644 else
7645 lua_pushnil(L);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007646 lua_rawset(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007647
Christopher Faulet78c35472020-02-26 17:14:08 +01007648 if ((htxn->flags & HLUA_TXN_CTX_MASK) == HLUA_TXN_FLT_CTX) {
7649 /* HTTPMessage object are created when a lua TXN is created from
7650 * a filter context only
7651 */
7652
7653 /* Creates the HTTP-Request object is the current proxy allows http. */
7654 lua_pushstring(L, "http_req");
7655 if (p->mode == PR_MODE_HTTP) {
7656 if (!hlua_http_msg_new(L, &s->txn->req))
7657 return 0;
7658 }
7659 else
7660 lua_pushnil(L);
7661 lua_rawset(L, -3);
7662
7663 /* Creates the HTTP-Response object is the current proxy allows http. */
7664 lua_pushstring(L, "http_res");
7665 if (p->mode == PR_MODE_HTTP) {
7666 if (!hlua_http_msg_new(L, &s->txn->rsp))
7667 return 0;
7668 }
7669 else
7670 lua_pushnil(L);
7671 lua_rawset(L, -3);
7672 }
7673
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007674 /* Pop a class sesison metatable and affect it to the userdata. */
7675 lua_rawgeti(L, LUA_REGISTRYINDEX, class_txn_ref);
7676 lua_setmetatable(L, -2);
7677
7678 return 1;
7679}
7680
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01007681__LJMP static int hlua_txn_deflog(lua_State *L)
7682{
7683 const char *msg;
7684 struct hlua_txn *htxn;
7685
7686 MAY_LJMP(check_args(L, 2, "deflog"));
7687 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7688 msg = MAY_LJMP(luaL_checkstring(L, 2));
7689
7690 hlua_sendlog(htxn->s->be, htxn->s->logs.level, msg);
7691 return 0;
7692}
7693
7694__LJMP static int hlua_txn_log(lua_State *L)
7695{
7696 int level;
7697 const char *msg;
7698 struct hlua_txn *htxn;
7699
7700 MAY_LJMP(check_args(L, 3, "log"));
7701 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7702 level = MAY_LJMP(luaL_checkinteger(L, 2));
7703 msg = MAY_LJMP(luaL_checkstring(L, 3));
7704
7705 if (level < 0 || level >= NB_LOG_LEVELS)
7706 WILL_LJMP(luaL_argerror(L, 1, "Invalid loglevel."));
7707
7708 hlua_sendlog(htxn->s->be, level, msg);
7709 return 0;
7710}
7711
7712__LJMP static int hlua_txn_log_debug(lua_State *L)
7713{
7714 const char *msg;
7715 struct hlua_txn *htxn;
7716
7717 MAY_LJMP(check_args(L, 2, "Debug"));
7718 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7719 msg = MAY_LJMP(luaL_checkstring(L, 2));
7720 hlua_sendlog(htxn->s->be, LOG_DEBUG, msg);
7721 return 0;
7722}
7723
7724__LJMP static int hlua_txn_log_info(lua_State *L)
7725{
7726 const char *msg;
7727 struct hlua_txn *htxn;
7728
7729 MAY_LJMP(check_args(L, 2, "Info"));
7730 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7731 msg = MAY_LJMP(luaL_checkstring(L, 2));
7732 hlua_sendlog(htxn->s->be, LOG_INFO, msg);
7733 return 0;
7734}
7735
7736__LJMP static int hlua_txn_log_warning(lua_State *L)
7737{
7738 const char *msg;
7739 struct hlua_txn *htxn;
7740
7741 MAY_LJMP(check_args(L, 2, "Warning"));
7742 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7743 msg = MAY_LJMP(luaL_checkstring(L, 2));
7744 hlua_sendlog(htxn->s->be, LOG_WARNING, msg);
7745 return 0;
7746}
7747
7748__LJMP static int hlua_txn_log_alert(lua_State *L)
7749{
7750 const char *msg;
7751 struct hlua_txn *htxn;
7752
7753 MAY_LJMP(check_args(L, 2, "Alert"));
7754 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7755 msg = MAY_LJMP(luaL_checkstring(L, 2));
7756 hlua_sendlog(htxn->s->be, LOG_ALERT, msg);
7757 return 0;
7758}
7759
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01007760__LJMP static int hlua_txn_set_loglevel(lua_State *L)
7761{
7762 struct hlua_txn *htxn;
7763 int ll;
7764
7765 MAY_LJMP(check_args(L, 2, "set_loglevel"));
7766 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7767 ll = MAY_LJMP(luaL_checkinteger(L, 2));
7768
7769 if (ll < 0 || ll > 7)
7770 WILL_LJMP(luaL_argerror(L, 2, "Bad log level. It must be between 0 and 7"));
7771
7772 htxn->s->logs.level = ll;
7773 return 0;
7774}
7775
7776__LJMP static int hlua_txn_set_tos(lua_State *L)
7777{
7778 struct hlua_txn *htxn;
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01007779 int tos;
7780
7781 MAY_LJMP(check_args(L, 2, "set_tos"));
7782 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7783 tos = MAY_LJMP(luaL_checkinteger(L, 2));
7784
Willy Tarreau1a18b542018-12-11 16:37:42 +01007785 conn_set_tos(objt_conn(htxn->s->sess->origin), tos);
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01007786 return 0;
7787}
7788
7789__LJMP static int hlua_txn_set_mark(lua_State *L)
7790{
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01007791 struct hlua_txn *htxn;
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01007792 int mark;
7793
7794 MAY_LJMP(check_args(L, 2, "set_mark"));
7795 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7796 mark = MAY_LJMP(luaL_checkinteger(L, 2));
7797
Lukas Tribus579e3e32019-08-11 18:03:45 +02007798 conn_set_mark(objt_conn(htxn->s->sess->origin), mark);
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01007799 return 0;
7800}
7801
Patrick Hemmer268a7072018-05-11 12:52:31 -04007802__LJMP static int hlua_txn_set_priority_class(lua_State *L)
7803{
7804 struct hlua_txn *htxn;
7805
7806 MAY_LJMP(check_args(L, 2, "set_priority_class"));
7807 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7808 htxn->s->priority_class = queue_limit_class(MAY_LJMP(luaL_checkinteger(L, 2)));
7809 return 0;
7810}
7811
7812__LJMP static int hlua_txn_set_priority_offset(lua_State *L)
7813{
7814 struct hlua_txn *htxn;
7815
7816 MAY_LJMP(check_args(L, 2, "set_priority_offset"));
7817 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7818 htxn->s->priority_offset = queue_limit_offset(MAY_LJMP(luaL_checkinteger(L, 2)));
7819 return 0;
7820}
7821
Christopher Faulet700d9e82020-01-31 12:21:52 +01007822/* Forward the Reply object to the client. This function converts the reply in
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05007823 * HTX an push it to into the response channel. It is response to forward the
Christopher Faulet700d9e82020-01-31 12:21:52 +01007824 * message and terminate the transaction. It returns 1 on success and 0 on
7825 * error. The Reply must be on top of the stack.
7826 */
7827__LJMP static int hlua_txn_forward_reply(lua_State *L, struct stream *s)
7828{
7829 struct htx *htx;
7830 struct htx_sl *sl;
7831 struct h1m h1m;
7832 const char *status, *reason, *body;
7833 size_t status_len, reason_len, body_len;
7834 int ret, code, flags;
7835
7836 code = 200;
7837 status = "200";
7838 status_len = 3;
7839 ret = lua_getfield(L, -1, "status");
7840 if (ret == LUA_TNUMBER) {
7841 code = lua_tointeger(L, -1);
7842 status = lua_tolstring(L, -1, &status_len);
7843 }
7844 lua_pop(L, 1);
7845
7846 reason = http_get_reason(code);
7847 reason_len = strlen(reason);
7848 ret = lua_getfield(L, -1, "reason");
7849 if (ret == LUA_TSTRING)
7850 reason = lua_tolstring(L, -1, &reason_len);
7851 lua_pop(L, 1);
7852
7853 body = NULL;
7854 body_len = 0;
7855 ret = lua_getfield(L, -1, "body");
7856 if (ret == LUA_TSTRING)
7857 body = lua_tolstring(L, -1, &body_len);
7858 lua_pop(L, 1);
7859
7860 /* Prepare the response before inserting the headers */
7861 h1m_init_res(&h1m);
7862 htx = htx_from_buf(&s->res.buf);
7863 channel_htx_truncate(&s->res, htx);
7864 if (s->txn->req.flags & HTTP_MSGF_VER_11) {
7865 flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11);
7866 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.1"),
7867 ist2(status, status_len), ist2(reason, reason_len));
7868 }
7869 else {
7870 flags = HTX_SL_F_IS_RESP;
7871 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.0"),
7872 ist2(status, status_len), ist2(reason, reason_len));
7873 }
7874 if (!sl)
7875 goto fail;
7876 sl->info.res.status = code;
7877
7878 /* Push in the stack the "headers" entry. */
7879 ret = lua_getfield(L, -1, "headers");
7880 if (ret != LUA_TTABLE)
7881 goto skip_headers;
7882
7883 lua_pushnil(L);
7884 while (lua_next(L, -2) != 0) {
7885 struct ist name, value;
7886 const char *n, *v;
7887 size_t nlen, vlen;
7888
7889 if (!lua_isstring(L, -2) || !lua_istable(L, -1)) {
7890 /* Skip element if the key is not a string or if the value is not a table */
7891 goto next_hdr;
7892 }
7893
7894 n = lua_tolstring(L, -2, &nlen);
7895 name = ist2(n, nlen);
7896 if (isteqi(name, ist("content-length"))) {
7897 /* Always skip content-length header. It will be added
7898 * later with the correct len
7899 */
7900 goto next_hdr;
7901 }
7902
7903 /* Loop on header's values */
7904 lua_pushnil(L);
7905 while (lua_next(L, -2)) {
7906 if (!lua_isstring(L, -1)) {
7907 /* Skip the value if it is not a string */
7908 goto next_value;
7909 }
7910
7911 v = lua_tolstring(L, -1, &vlen);
7912 value = ist2(v, vlen);
7913
7914 if (isteqi(name, ist("transfer-encoding")))
7915 h1_parse_xfer_enc_header(&h1m, value);
7916 if (!htx_add_header(htx, ist2(n, nlen), ist2(v, vlen)))
7917 goto fail;
7918
7919 next_value:
7920 lua_pop(L, 1);
7921 }
7922
7923 next_hdr:
7924 lua_pop(L, 1);
7925 }
7926 skip_headers:
7927 lua_pop(L, 1);
7928
7929 /* Update h1m flags: CLEN is set if CHNK is not present */
7930 if (!(h1m.flags & H1_MF_CHNK)) {
7931 const char *clen = ultoa(body_len);
7932
7933 h1m.flags |= H1_MF_CLEN;
7934 if (!htx_add_header(htx, ist("content-length"), ist(clen)))
7935 goto fail;
7936 }
7937 if (h1m.flags & (H1_MF_CLEN|H1_MF_CHNK))
7938 h1m.flags |= H1_MF_XFER_LEN;
7939
7940 /* Update HTX start-line flags */
7941 if (h1m.flags & H1_MF_XFER_ENC)
7942 flags |= HTX_SL_F_XFER_ENC;
7943 if (h1m.flags & H1_MF_XFER_LEN) {
7944 flags |= HTX_SL_F_XFER_LEN;
7945 if (h1m.flags & H1_MF_CHNK)
7946 flags |= HTX_SL_F_CHNK;
7947 else if (h1m.flags & H1_MF_CLEN)
7948 flags |= HTX_SL_F_CLEN;
7949 if (h1m.body_len == 0)
7950 flags |= HTX_SL_F_BODYLESS;
7951 }
7952 sl->flags |= flags;
7953
7954
7955 if (!htx_add_endof(htx, HTX_BLK_EOH) ||
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01007956 (body_len && !htx_add_data_atonce(htx, ist2(body, body_len))))
Christopher Faulet700d9e82020-01-31 12:21:52 +01007957 goto fail;
7958
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01007959 htx->flags |= HTX_FL_EOM;
7960
Christopher Faulet700d9e82020-01-31 12:21:52 +01007961 /* Now, forward the response and terminate the transaction */
7962 s->txn->status = code;
7963 htx_to_buf(htx, &s->res.buf);
7964 if (!http_forward_proxy_resp(s, 1))
7965 goto fail;
7966
7967 return 1;
7968
7969 fail:
7970 channel_htx_truncate(&s->res, htx);
7971 return 0;
7972}
7973
7974/* Terminate a transaction if called from a lua action. For TCP streams,
7975 * processing is just aborted. Nothing is returned to the client and all
7976 * arguments are ignored. For HTTP streams, if a reply is passed as argument, it
7977 * is forwarded to the client before terminating the transaction. On success,
7978 * the function exits with ACT_RET_DONE code. If an error occurred, it exits
7979 * with ACT_RET_ERR code. If this function is not called from a lua action, it
7980 * just exits without any processing.
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01007981 */
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02007982__LJMP static int hlua_txn_done(lua_State *L)
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01007983{
Willy Tarreaub2ccb562015-04-06 11:11:15 +02007984 struct hlua_txn *htxn;
Christopher Faulet700d9e82020-01-31 12:21:52 +01007985 struct stream *s;
7986 int finst;
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01007987
Willy Tarreaub2ccb562015-04-06 11:11:15 +02007988 htxn = MAY_LJMP(hlua_checktxn(L, 1));
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01007989
Christopher Faulet700d9e82020-01-31 12:21:52 +01007990 /* If the flags NOTERM is set, we cannot terminate the session, so we
7991 * just end the execution of the current lua code. */
7992 if (htxn->flags & HLUA_TXN_NOTERM)
Thierry FOURNIERab00df62016-07-14 11:42:37 +02007993 WILL_LJMP(hlua_done(L));
Thierry FOURNIERab00df62016-07-14 11:42:37 +02007994
Christopher Faulet700d9e82020-01-31 12:21:52 +01007995 s = htxn->s;
Christopher Fauletd8f0e072020-02-25 09:45:51 +01007996 if (!IS_HTX_STRM(htxn->s)) {
Christopher Faulet700d9e82020-01-31 12:21:52 +01007997 struct channel *req = &s->req;
7998 struct channel *res = &s->res;
Willy Tarreau81389672015-03-10 12:03:52 +01007999
Christopher Faulet700d9e82020-01-31 12:21:52 +01008000 channel_auto_read(req);
8001 channel_abort(req);
8002 channel_auto_close(req);
8003 channel_erase(req);
8004
8005 res->wex = tick_add_ifset(now_ms, res->wto);
8006 channel_auto_read(res);
8007 channel_auto_close(res);
8008 channel_shutr_now(res);
8009
8010 finst = ((htxn->dir == SMP_OPT_DIR_REQ) ? SF_FINST_R : SF_FINST_D);
8011 goto done;
Christopher Fauletfe6a71b2019-07-26 16:40:24 +02008012 }
Thierry FOURNIER10ec2142015-08-24 17:23:45 +02008013
Christopher Faulet700d9e82020-01-31 12:21:52 +01008014 if (lua_gettop(L) == 1 || !lua_istable(L, 2)) {
8015 /* No reply or invalid reply */
8016 s->txn->status = 0;
8017 http_reply_and_close(s, 0, NULL);
8018 }
8019 else {
8020 /* Remove extra args to have the reply on top of the stack */
8021 if (lua_gettop(L) > 2)
8022 lua_pop(L, lua_gettop(L) - 2);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01008023
Christopher Faulet700d9e82020-01-31 12:21:52 +01008024 if (!hlua_txn_forward_reply(L, s)) {
8025 if (!(s->flags & SF_ERR_MASK))
8026 s->flags |= SF_ERR_PRXCOND;
8027 lua_pushinteger(L, ACT_RET_ERR);
8028 WILL_LJMP(hlua_done(L));
8029 return 0; /* Never reached */
8030 }
Christopher Faulet4d0e2632019-07-16 10:52:40 +02008031 }
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02008032
Christopher Faulet700d9e82020-01-31 12:21:52 +01008033 finst = ((htxn->dir == SMP_OPT_DIR_REQ) ? SF_FINST_R : SF_FINST_H);
8034 if (htxn->dir == SMP_OPT_DIR_REQ) {
8035 /* let's log the request time */
8036 s->logs.tv_request = now;
8037 if (s->sess->fe == s->be) /* report it if the request was intercepted by the frontend */
Willy Tarreau4781b152021-04-06 13:53:36 +02008038 _HA_ATOMIC_INC(&s->sess->fe->fe_counters.intercepted_req);
Christopher Faulet700d9e82020-01-31 12:21:52 +01008039 }
Christopher Fauletfe6a71b2019-07-26 16:40:24 +02008040
Christopher Faulet700d9e82020-01-31 12:21:52 +01008041 done:
8042 if (!(s->flags & SF_ERR_MASK))
8043 s->flags |= SF_ERR_LOCAL;
8044 if (!(s->flags & SF_FINST_MASK))
8045 s->flags |= finst;
Christopher Fauletfe6a71b2019-07-26 16:40:24 +02008046
Christopher Faulete48d1dc2021-08-13 14:11:17 +02008047 if ((htxn->flags & HLUA_TXN_CTX_MASK) == HLUA_TXN_FLT_CTX)
8048 lua_pushinteger(L, -1);
8049 else
8050 lua_pushinteger(L, ACT_RET_ABRT);
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02008051 WILL_LJMP(hlua_done(L));
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01008052 return 0;
8053}
8054
Christopher Faulet700d9e82020-01-31 12:21:52 +01008055/*
8056 *
8057 *
8058 * Class REPLY
8059 *
8060 *
8061 */
8062
8063/* Pushes the TXN reply onto the top of the stack. If the stask does not have a
8064 * free slots, the function fails and returns 0;
8065 */
8066static int hlua_txn_reply_new(lua_State *L)
8067{
8068 struct hlua_txn *htxn;
8069 const char *reason, *body = NULL;
8070 int ret, status;
8071
8072 htxn = MAY_LJMP(hlua_checktxn(L, 1));
Christopher Fauletd8f0e072020-02-25 09:45:51 +01008073 if (!IS_HTX_STRM(htxn->s)) {
Christopher Faulet700d9e82020-01-31 12:21:52 +01008074 hlua_pusherror(L, "txn object is not an HTTP transaction.");
8075 WILL_LJMP(lua_error(L));
8076 }
8077
8078 /* Default value */
8079 status = 200;
8080 reason = http_get_reason(status);
8081
8082 if (lua_istable(L, 2)) {
8083 /* load status and reason from the table argument at index 2 */
8084 ret = lua_getfield(L, 2, "status");
8085 if (ret == LUA_TNIL)
8086 goto reason;
8087 else if (ret != LUA_TNUMBER) {
8088 /* invalid status: ignore the reason */
8089 goto body;
8090 }
8091 status = lua_tointeger(L, -1);
8092
8093 reason:
8094 lua_pop(L, 1); /* restore the stack: remove status */
8095 ret = lua_getfield(L, 2, "reason");
8096 if (ret == LUA_TSTRING)
8097 reason = lua_tostring(L, -1);
8098
8099 body:
8100 lua_pop(L, 1); /* restore the stack: remove invalid status or reason */
8101 ret = lua_getfield(L, 2, "body");
8102 if (ret == LUA_TSTRING)
8103 body = lua_tostring(L, -1);
8104 lua_pop(L, 1); /* restore the stack: remove body */
8105 }
8106
8107 /* Create the Reply table */
8108 lua_newtable(L);
8109
8110 /* Add status element */
8111 lua_pushstring(L, "status");
8112 lua_pushinteger(L, status);
8113 lua_settable(L, -3);
8114
8115 /* Add reason element */
8116 reason = http_get_reason(status);
8117 lua_pushstring(L, "reason");
8118 lua_pushstring(L, reason);
8119 lua_settable(L, -3);
8120
8121 /* Add body element, nil if undefined */
8122 lua_pushstring(L, "body");
8123 if (body)
8124 lua_pushstring(L, body);
8125 else
8126 lua_pushnil(L);
8127 lua_settable(L, -3);
8128
8129 /* Add headers element */
8130 lua_pushstring(L, "headers");
8131 lua_newtable(L);
8132
8133 /* stack: [ txn, <Arg:table>, <Reply:table>, "headers", <headers:table> ] */
8134 if (lua_istable(L, 2)) {
8135 /* load headers from the table argument at index 2. If it is a table, copy it. */
8136 ret = lua_getfield(L, 2, "headers");
8137 if (ret == LUA_TTABLE) {
8138 /* stack: [ ... <headers:table>, <table> ] */
8139 lua_pushnil(L);
8140 while (lua_next(L, -2) != 0) {
8141 /* stack: [ ... <headers:table>, <table>, k, v] */
8142 if (!lua_isstring(L, -1) && !lua_istable(L, -1)) {
8143 /* invalid value type, skip it */
8144 lua_pop(L, 1);
8145 continue;
8146 }
8147
8148
8149 /* Duplicate the key and swap it with the value. */
8150 lua_pushvalue(L, -2);
8151 lua_insert(L, -2);
8152 /* stack: [ ... <headers:table>, <table>, k, k, v ] */
8153
8154 lua_newtable(L);
8155 lua_insert(L, -2);
8156 /* stack: [ ... <headers:table>, <table>, k, k, <inner:table>, v ] */
8157
8158 if (lua_isstring(L, -1)) {
8159 /* push the value in the inner table */
8160 lua_rawseti(L, -2, 1);
8161 }
8162 else { /* table */
8163 lua_pushnil(L);
8164 while (lua_next(L, -2) != 0) {
8165 /* stack: [ ... <headers:table>, <table>, k, k, <inner:table>, <v:table>, k2, v2 ] */
8166 if (!lua_isstring(L, -1)) {
8167 /* invalid value type, skip it*/
8168 lua_pop(L, 1);
8169 continue;
8170 }
8171 /* push the value in the inner table */
8172 lua_rawseti(L, -4, lua_rawlen(L, -4) + 1);
8173 /* stack: [ ... <headers:table>, <table>, k, k, <inner:table>, <v:table>, k2 ] */
8174 }
8175 lua_pop(L, 1);
8176 /* stack: [ ... <headers:table>, <table>, k, k, <inner:table> ] */
8177 }
8178
8179 /* push (k,v) on the stack in the headers table:
8180 * stack: [ ... <headers:table>, <table>, k, k, v ]
8181 */
8182 lua_settable(L, -5);
8183 /* stack: [ ... <headers:table>, <table>, k ] */
8184 }
8185 }
8186 lua_pop(L, 1);
8187 }
8188 /* stack: [ txn, <Arg:table>, <Reply:table>, "headers", <headers:table> ] */
8189 lua_settable(L, -3);
8190 /* stack: [ txn, <Arg:table>, <Reply:table> ] */
8191
8192 /* Pop a class sesison metatable and affect it to the userdata. */
8193 lua_rawgeti(L, LUA_REGISTRYINDEX, class_txn_reply_ref);
8194 lua_setmetatable(L, -2);
8195 return 1;
8196}
8197
8198/* Set the reply status code, and optionally the reason. If no reason is
8199 * provided, the default one corresponding to the status code is used.
8200 */
8201__LJMP static int hlua_txn_reply_set_status(lua_State *L)
8202{
8203 int status = MAY_LJMP(luaL_checkinteger(L, 2));
8204 const char *reason = MAY_LJMP(luaL_optlstring(L, 3, NULL, NULL));
8205
8206 /* First argument (self) must be a table */
8207 luaL_checktype(L, 1, LUA_TTABLE);
8208
8209 if (status < 100 || status > 599) {
8210 lua_pushboolean(L, 0);
8211 return 1;
8212 }
8213 if (!reason)
8214 reason = http_get_reason(status);
8215
8216 lua_pushinteger(L, status);
8217 lua_setfield(L, 1, "status");
8218
8219 lua_pushstring(L, reason);
8220 lua_setfield(L, 1, "reason");
8221
8222 lua_pushboolean(L, 1);
8223 return 1;
8224}
8225
8226/* Add a header into the reply object. Each header name is associated to an
8227 * array of values in the "headers" table. If the header name is not found, a
8228 * new entry is created.
8229 */
8230__LJMP static int hlua_txn_reply_add_header(lua_State *L)
8231{
8232 const char *name = MAY_LJMP(luaL_checkstring(L, 2));
8233 const char *value = MAY_LJMP(luaL_checkstring(L, 3));
8234 int ret;
8235
8236 /* First argument (self) must be a table */
8237 luaL_checktype(L, 1, LUA_TTABLE);
8238
8239 /* Push in the stack the "headers" entry. */
8240 ret = lua_getfield(L, 1, "headers");
8241 if (ret != LUA_TTABLE) {
8242 hlua_pusherror(L, "Reply['headers'] is expected to a an array. %s found", lua_typename(L, ret));
8243 WILL_LJMP(lua_error(L));
8244 }
8245
8246 /* check if the header is already registered. If not, register it. */
8247 ret = lua_getfield(L, -1, name);
8248 if (ret == LUA_TNIL) {
8249 /* Entry not found. */
8250 lua_pop(L, 1); /* remove the nil. The "headers" table is the top of the stack. */
8251
8252 /* Insert the new header name in the array in the top of the stack.
8253 * It left the new array in the top of the stack.
8254 */
8255 lua_newtable(L);
8256 lua_pushstring(L, name);
8257 lua_pushvalue(L, -2);
8258 lua_settable(L, -4);
8259 }
8260 else if (ret != LUA_TTABLE) {
8261 hlua_pusherror(L, "Reply['headers']['%s'] is expected to be an array. %s found", name, lua_typename(L, ret));
8262 WILL_LJMP(lua_error(L));
8263 }
8264
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -07008265 /* Now the top of thestack is an array of values. We push
Christopher Faulet700d9e82020-01-31 12:21:52 +01008266 * the header value as new entry.
8267 */
8268 lua_pushstring(L, value);
8269 ret = lua_rawlen(L, -2);
8270 lua_rawseti(L, -2, ret + 1);
8271
8272 lua_pushboolean(L, 1);
8273 return 1;
8274}
8275
8276/* Remove all occurrences of a given header name. */
8277__LJMP static int hlua_txn_reply_del_header(lua_State *L)
8278{
8279 const char *name = MAY_LJMP(luaL_checkstring(L, 2));
8280 int ret;
8281
8282 /* First argument (self) must be a table */
8283 luaL_checktype(L, 1, LUA_TTABLE);
8284
8285 /* Push in the stack the "headers" entry. */
8286 ret = lua_getfield(L, 1, "headers");
8287 if (ret != LUA_TTABLE) {
8288 hlua_pusherror(L, "Reply['headers'] is expected to be an array. %s found", lua_typename(L, ret));
8289 WILL_LJMP(lua_error(L));
8290 }
8291
8292 lua_pushstring(L, name);
8293 lua_pushnil(L);
8294 lua_settable(L, -3);
8295
8296 lua_pushboolean(L, 1);
8297 return 1;
8298}
8299
8300/* Set the reply's body. Overwrite any existing entry. */
8301__LJMP static int hlua_txn_reply_set_body(lua_State *L)
8302{
8303 const char *payload = MAY_LJMP(luaL_checkstring(L, 2));
8304
8305 /* First argument (self) must be a table */
8306 luaL_checktype(L, 1, LUA_TTABLE);
8307
8308 lua_pushstring(L, payload);
8309 lua_setfield(L, 1, "body");
8310
8311 lua_pushboolean(L, 1);
8312 return 1;
8313}
8314
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01008315__LJMP static int hlua_log(lua_State *L)
8316{
8317 int level;
8318 const char *msg;
8319
8320 MAY_LJMP(check_args(L, 2, "log"));
8321 level = MAY_LJMP(luaL_checkinteger(L, 1));
8322 msg = MAY_LJMP(luaL_checkstring(L, 2));
8323
8324 if (level < 0 || level >= NB_LOG_LEVELS)
8325 WILL_LJMP(luaL_argerror(L, 1, "Invalid loglevel."));
8326
8327 hlua_sendlog(NULL, level, msg);
8328 return 0;
8329}
8330
8331__LJMP static int hlua_log_debug(lua_State *L)
8332{
8333 const char *msg;
8334
8335 MAY_LJMP(check_args(L, 1, "debug"));
8336 msg = MAY_LJMP(luaL_checkstring(L, 1));
8337 hlua_sendlog(NULL, LOG_DEBUG, msg);
8338 return 0;
8339}
8340
8341__LJMP static int hlua_log_info(lua_State *L)
8342{
8343 const char *msg;
8344
8345 MAY_LJMP(check_args(L, 1, "info"));
8346 msg = MAY_LJMP(luaL_checkstring(L, 1));
8347 hlua_sendlog(NULL, LOG_INFO, msg);
8348 return 0;
8349}
8350
8351__LJMP static int hlua_log_warning(lua_State *L)
8352{
8353 const char *msg;
8354
8355 MAY_LJMP(check_args(L, 1, "warning"));
8356 msg = MAY_LJMP(luaL_checkstring(L, 1));
8357 hlua_sendlog(NULL, LOG_WARNING, msg);
8358 return 0;
8359}
8360
8361__LJMP static int hlua_log_alert(lua_State *L)
8362{
8363 const char *msg;
8364
8365 MAY_LJMP(check_args(L, 1, "alert"));
8366 msg = MAY_LJMP(luaL_checkstring(L, 1));
8367 hlua_sendlog(NULL, LOG_ALERT, msg);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01008368 return 0;
8369}
8370
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01008371__LJMP static int hlua_sleep_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008372{
8373 int wakeup_ms = lua_tointeger(L, -1);
Willy Tarreau12c02702021-09-30 16:12:31 +02008374 if (!tick_is_expired(wakeup_ms, now_ms))
Willy Tarreau9635e032018-10-16 17:52:55 +02008375 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008376 return 0;
8377}
8378
8379__LJMP static int hlua_sleep(lua_State *L)
8380{
8381 unsigned int delay;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008382 unsigned int wakeup_ms;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008383
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008384 MAY_LJMP(check_args(L, 1, "sleep"));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008385
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01008386 delay = MAY_LJMP(luaL_checkinteger(L, 1)) * 1000;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008387 wakeup_ms = tick_add(now_ms, delay);
8388 lua_pushinteger(L, wakeup_ms);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008389
Willy Tarreau9635e032018-10-16 17:52:55 +02008390 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008391 return 0;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008392}
8393
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008394__LJMP static int hlua_msleep(lua_State *L)
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008395{
8396 unsigned int delay;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008397 unsigned int wakeup_ms;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008398
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008399 MAY_LJMP(check_args(L, 1, "msleep"));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008400
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01008401 delay = MAY_LJMP(luaL_checkinteger(L, 1));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008402 wakeup_ms = tick_add(now_ms, delay);
8403 lua_pushinteger(L, wakeup_ms);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008404
Willy Tarreau9635e032018-10-16 17:52:55 +02008405 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008406 return 0;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008407}
8408
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01008409/* This functionis an LUA binding. it permits to give back
8410 * the hand at the HAProxy scheduler. It is used when the
8411 * LUA processing consumes a lot of time.
8412 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01008413__LJMP static int hlua_yield_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008414{
8415 return 0;
8416}
8417
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01008418__LJMP static int hlua_yield(lua_State *L)
8419{
Willy Tarreau9635e032018-10-16 17:52:55 +02008420 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_yield_yield, TICK_ETERNITY, HLUA_CTRLYIELD));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008421 return 0;
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01008422}
8423
Thierry FOURNIER37196f42015-02-16 19:34:56 +01008424/* This function change the nice of the currently executed
8425 * task. It is used set low or high priority at the current
8426 * task.
8427 */
Willy Tarreau59551662015-03-10 14:23:13 +01008428__LJMP static int hlua_set_nice(lua_State *L)
Thierry FOURNIER37196f42015-02-16 19:34:56 +01008429{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01008430 struct hlua *hlua;
8431 int nice;
Thierry FOURNIER37196f42015-02-16 19:34:56 +01008432
Willy Tarreau80f5fae2015-02-27 16:38:20 +01008433 MAY_LJMP(check_args(L, 1, "set_nice"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01008434 nice = MAY_LJMP(luaL_checkinteger(L, 1));
Thierry FOURNIER37196f42015-02-16 19:34:56 +01008435
Thierry Fournier4234dbd2020-11-28 13:18:23 +01008436 /* Get hlua struct, or NULL if we execute from main lua state */
8437 hlua = hlua_gethlua(L);
8438
8439 /* If the task is not set, I'm in a start mode. */
Thierry FOURNIER37196f42015-02-16 19:34:56 +01008440 if (!hlua || !hlua->task)
8441 return 0;
8442
8443 if (nice < -1024)
8444 nice = -1024;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01008445 else if (nice > 1024)
Thierry FOURNIER37196f42015-02-16 19:34:56 +01008446 nice = 1024;
8447
8448 hlua->task->nice = nice;
8449 return 0;
8450}
8451
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08008452/* This function is used as a callback of a task. It is called by the
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008453 * HAProxy task subsystem when the task is awaked. The LUA runtime can
8454 * return an E_AGAIN signal, the emmiter of this signal must set a
8455 * signal to wake the task.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008456 *
8457 * Task wrapper are longjmp safe because the only one Lua code
8458 * executed is the safe hlua_ctx_resume();
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008459 */
Willy Tarreau144f84a2021-03-02 16:09:26 +01008460struct task *hlua_process_task(struct task *task, void *context, unsigned int state)
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008461{
Olivier Houchard9f6af332018-05-25 14:04:04 +02008462 struct hlua *hlua = context;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008463 enum hlua_exec status;
8464
Willy Tarreaue35f0322022-06-14 11:00:46 +02008465 if (atleast2(task->thread_mask))
Christopher Faulet5bc99722018-04-25 10:34:45 +02008466 task_set_affinity(task, tid_bit);
8467
Willy Tarreau6ef52f42022-06-15 14:19:48 +02008468 if (task->tid < 0)
8469 task->tid = tid;
8470
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008471 /* If it is the first call to the task, we must initialize the
8472 * execution timeouts.
8473 */
8474 if (!HLUA_IS_RUNNING(hlua))
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02008475 hlua->max_time = hlua_timeout_task;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008476
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008477 /* Execute the Lua code. */
8478 status = hlua_ctx_resume(hlua, 1);
8479
8480 switch (status) {
8481 /* finished or yield */
8482 case HLUA_E_OK:
8483 hlua_ctx_destroy(hlua);
Olivier Houchard3f795f72019-04-17 22:51:06 +02008484 task_destroy(task);
Tim Duesterhuscd235c62018-04-24 13:56:01 +02008485 task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008486 break;
8487
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01008488 case HLUA_E_AGAIN: /* co process or timeout wake me later. */
Thierry FOURNIERcb146882017-12-10 17:10:57 +01008489 notification_gc(&hlua->com);
PiBa-NLfe971b32018-05-02 22:27:14 +02008490 task->expire = hlua->wake_time;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008491 break;
8492
8493 /* finished with error. */
8494 case HLUA_E_ERRMSG:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008495 SEND_ERR(NULL, "Lua task: %s.\n", lua_tostring(hlua->T, -1));
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008496 hlua_ctx_destroy(hlua);
Olivier Houchard3f795f72019-04-17 22:51:06 +02008497 task_destroy(task);
Emeric Brun253e53e2017-10-17 18:58:40 +02008498 task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008499 break;
8500
8501 case HLUA_E_ERR:
8502 default:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008503 SEND_ERR(NULL, "Lua task: unknown error.\n");
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008504 hlua_ctx_destroy(hlua);
Olivier Houchard3f795f72019-04-17 22:51:06 +02008505 task_destroy(task);
Emeric Brun253e53e2017-10-17 18:58:40 +02008506 task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008507 break;
8508 }
Emeric Brun253e53e2017-10-17 18:58:40 +02008509 return task;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008510}
8511
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008512/* This function is an LUA binding that register LUA function to be
8513 * executed after the HAProxy configuration parsing and before the
8514 * HAProxy scheduler starts. This function expect only one LUA
8515 * argument that is a function. This function returns nothing, but
8516 * throws if an error is encountered.
8517 */
8518__LJMP static int hlua_register_init(lua_State *L)
8519{
8520 struct hlua_init_function *init;
8521 int ref;
8522
8523 MAY_LJMP(check_args(L, 1, "register_init"));
8524
8525 ref = MAY_LJMP(hlua_checkfunction(L, 1));
8526
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02008527 init = calloc(1, sizeof(*init));
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008528 if (!init)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01008529 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008530
8531 init->function_ref = ref;
Willy Tarreau2b718102021-04-21 07:32:39 +02008532 LIST_APPEND(&hlua_init_functions[hlua_state_id], &init->l);
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008533 return 0;
8534}
8535
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008536/* This functio is an LUA binding. It permits to register a task
8537 * executed in parallel of the main HAroxy activity. The task is
8538 * created and it is set in the HAProxy scheduler. It can be called
8539 * from the "init" section, "post init" or during the runtime.
8540 *
8541 * Lua prototype:
8542 *
8543 * <none> core.register_task(<function>)
8544 */
8545static int hlua_register_task(lua_State *L)
8546{
Christopher Faulet5294ec02021-04-12 12:24:47 +02008547 struct hlua *hlua = NULL;
8548 struct task *task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008549 int ref;
Thierry Fournier021d9862020-11-28 23:42:03 +01008550 int state_id;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008551
8552 MAY_LJMP(check_args(L, 1, "register_task"));
8553
8554 ref = MAY_LJMP(hlua_checkfunction(L, 1));
8555
Thierry Fournier75fc0292020-11-28 13:18:56 +01008556 /* Get the reference state. If the reference is NULL, L is the master
8557 * state, otherwise hlua->T is.
8558 */
8559 hlua = hlua_gethlua(L);
8560 if (hlua)
Thierry Fournier021d9862020-11-28 23:42:03 +01008561 /* we are in runtime processing */
8562 state_id = hlua->state_id;
Thierry Fournier75fc0292020-11-28 13:18:56 +01008563 else
Thierry Fournier021d9862020-11-28 23:42:03 +01008564 /* we are in initialization mode */
Thierry Fournierc7492592020-11-28 23:57:24 +01008565 state_id = hlua_state_id;
Thierry Fournier75fc0292020-11-28 13:18:56 +01008566
Willy Tarreaubafbe012017-11-24 17:34:44 +01008567 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008568 if (!hlua)
Christopher Faulet5294ec02021-04-12 12:24:47 +02008569 goto alloc_error;
Christopher Faulet1e8433f2021-03-24 15:03:01 +01008570 HLUA_INIT(hlua);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008571
Thierry Fournier59f11be2020-11-29 00:37:41 +01008572 /* We are in the common lua state, execute the task anywhere,
8573 * otherwise, inherit the current thread identifier
8574 */
8575 if (state_id == 0)
Willy Tarreaubeeabf52021-10-01 18:23:30 +02008576 task = task_new_anywhere();
Thierry Fournier59f11be2020-11-29 00:37:41 +01008577 else
Willy Tarreaubeeabf52021-10-01 18:23:30 +02008578 task = task_new_here();
Willy Tarreaue09101e2018-10-16 17:37:12 +02008579 if (!task)
Christopher Faulet5294ec02021-04-12 12:24:47 +02008580 goto alloc_error;
Willy Tarreaue09101e2018-10-16 17:37:12 +02008581
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008582 task->context = hlua;
8583 task->process = hlua_process_task;
8584
Thierry Fournier021d9862020-11-28 23:42:03 +01008585 if (!hlua_ctx_init(hlua, state_id, task, 1))
Christopher Faulet5294ec02021-04-12 12:24:47 +02008586 goto alloc_error;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008587
8588 /* Restore the function in the stack. */
8589 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ref);
8590 hlua->nargs = 0;
8591
8592 /* Schedule task. */
Willy Tarreaue3957f82021-09-30 16:17:37 +02008593 task_wakeup(task, TASK_WOKEN_INIT);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008594
8595 return 0;
Christopher Faulet5294ec02021-04-12 12:24:47 +02008596
8597 alloc_error:
8598 task_destroy(task);
8599 hlua_ctx_destroy(hlua);
8600 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
8601 return 0; /* Never reached */
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008602}
8603
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008604/* Wrapper called by HAProxy to execute an LUA converter. This wrapper
8605 * doesn't allow "yield" functions because the HAProxy engine cannot
8606 * resume converters.
8607 */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02008608static int hlua_sample_conv_wrapper(const struct arg *arg_p, struct sample *smp, void *private)
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008609{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02008610 struct hlua_function *fcn = private;
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02008611 struct stream *stream = smp->strm;
Thierry Fournierfd107a22016-02-19 19:57:23 +01008612 const char *error;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008613
Willy Tarreaube508f12016-03-10 11:47:01 +01008614 if (!stream)
8615 return 0;
8616
Willy Tarreau87b09662015-04-03 00:22:06 +02008617 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01008618 * Lua context can be not initialized. This behavior
8619 * permits to save performances because a systematic
8620 * Lua initialization cause 5% performances loss.
8621 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008622 if (!stream->hlua) {
Christopher Faulet1e8433f2021-03-24 15:03:01 +01008623 struct hlua *hlua;
8624
8625 hlua = pool_alloc(pool_head_hlua);
8626 if (!hlua) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008627 SEND_ERR(stream->be, "Lua converter '%s': can't initialize Lua context.\n", fcn->name);
8628 return 0;
8629 }
Christopher Faulet1e8433f2021-03-24 15:03:01 +01008630 HLUA_INIT(hlua);
8631 stream->hlua = hlua;
Thierry Fournierc7492592020-11-28 23:57:24 +01008632 if (!hlua_ctx_init(stream->hlua, fcn_ref_to_stack_id(fcn), stream->task, 0)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008633 SEND_ERR(stream->be, "Lua converter '%s': can't initialize Lua context.\n", fcn->name);
8634 return 0;
8635 }
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01008636 }
8637
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008638 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008639 if (!HLUA_IS_RUNNING(stream->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008640
8641 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008642 if (!SET_SAFE_LJMP(stream->hlua)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008643 if (lua_type(stream->hlua->T, -1) == LUA_TSTRING)
8644 error = lua_tostring(stream->hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +01008645 else
8646 error = "critical error";
8647 SEND_ERR(stream->be, "Lua converter '%s': %s.\n", fcn->name, error);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008648 return 0;
8649 }
8650
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008651 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008652 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008653 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008654 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008655 return 0;
8656 }
8657
8658 /* Restore the function in the stack. */
Thierry Fournierc7492592020-11-28 23:57:24 +01008659 lua_rawgeti(stream->hlua->T, LUA_REGISTRYINDEX, fcn->function_ref[stream->hlua->state_id]);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008660
8661 /* convert input sample and pust-it in the stack. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008662 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008663 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008664 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008665 return 0;
8666 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008667 hlua_smp2lua(stream->hlua->T, smp);
8668 stream->hlua->nargs = 1;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008669
8670 /* push keywords in the stack. */
8671 if (arg_p) {
8672 for (; arg_p->type != ARGT_STOP; arg_p++) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008673 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008674 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008675 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008676 return 0;
8677 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008678 hlua_arg2lua(stream->hlua->T, arg_p);
8679 stream->hlua->nargs++;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008680 }
8681 }
8682
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008683 /* We must initialize the execution timeouts. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008684 stream->hlua->max_time = hlua_timeout_session;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008685
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008686 /* At this point the execution is safe. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008687 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008688 }
8689
8690 /* Execute the function. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008691 switch (hlua_ctx_resume(stream->hlua, 0)) {
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008692 /* finished. */
8693 case HLUA_E_OK:
Thierry FOURNIERfd80df12017-05-12 16:32:20 +02008694 /* If the stack is empty, the function fails. */
8695 if (lua_gettop(stream->hlua->T) <= 0)
8696 return 0;
8697
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008698 /* Convert the returned value in sample. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008699 hlua_lua2smp(stream->hlua->T, -1, smp);
8700 lua_pop(stream->hlua->T, 1);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008701 return 1;
8702
8703 /* yield. */
8704 case HLUA_E_AGAIN:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008705 SEND_ERR(stream->be, "Lua converter '%s': cannot use yielded functions.\n", fcn->name);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008706 return 0;
8707
8708 /* finished with error. */
8709 case HLUA_E_ERRMSG:
8710 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008711 SEND_ERR(stream->be, "Lua converter '%s': %s.\n",
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008712 fcn->name, lua_tostring(stream->hlua->T, -1));
8713 lua_pop(stream->hlua->T, 1);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008714 return 0;
8715
Thierry Fournierd5b073c2018-05-21 19:42:47 +02008716 case HLUA_E_ETMOUT:
8717 SEND_ERR(stream->be, "Lua converter '%s': execution timeout.\n", fcn->name);
8718 return 0;
8719
8720 case HLUA_E_NOMEM:
8721 SEND_ERR(stream->be, "Lua converter '%s': out of memory error.\n", fcn->name);
8722 return 0;
8723
8724 case HLUA_E_YIELD:
8725 SEND_ERR(stream->be, "Lua converter '%s': yield functions like core.tcp() or core.sleep() are not allowed.\n", fcn->name);
8726 return 0;
8727
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008728 case HLUA_E_ERR:
8729 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008730 SEND_ERR(stream->be, "Lua converter '%s' returns an unknown error.\n", fcn->name);
Tim Duesterhus588b3142020-05-29 14:35:51 +02008731 /* fall through */
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008732
8733 default:
8734 return 0;
8735 }
8736}
8737
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008738/* Wrapper called by HAProxy to execute a sample-fetch. this wrapper
8739 * doesn't allow "yield" functions because the HAProxy engine cannot
Willy Tarreaube508f12016-03-10 11:47:01 +01008740 * resume sample-fetches. This function will be called by the sample
8741 * fetch engine to call lua-based fetch operations.
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008742 */
Thierry FOURNIER0786d052015-05-11 15:42:45 +02008743static int hlua_sample_fetch_wrapper(const struct arg *arg_p, struct sample *smp,
8744 const char *kw, void *private)
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008745{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02008746 struct hlua_function *fcn = private;
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02008747 struct stream *stream = smp->strm;
Thierry Fournierfd107a22016-02-19 19:57:23 +01008748 const char *error;
Christopher Faulet8c9e6bb2021-08-06 16:29:41 +02008749 unsigned int hflags = HLUA_TXN_NOTERM | HLUA_TXN_SMP_CTX;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008750
Willy Tarreaube508f12016-03-10 11:47:01 +01008751 if (!stream)
8752 return 0;
Christopher Fauletafd8f102018-11-08 11:34:21 +01008753
Willy Tarreau87b09662015-04-03 00:22:06 +02008754 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01008755 * Lua context can be not initialized. This behavior
8756 * permits to save performances because a systematic
8757 * Lua initialization cause 5% performances loss.
8758 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008759 if (!stream->hlua) {
Christopher Faulet1e8433f2021-03-24 15:03:01 +01008760 struct hlua *hlua;
8761
8762 hlua = pool_alloc(pool_head_hlua);
8763 if (!hlua) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008764 SEND_ERR(stream->be, "Lua sample-fetch '%s': can't initialize Lua context.\n", fcn->name);
8765 return 0;
8766 }
Christopher Faulet1e8433f2021-03-24 15:03:01 +01008767 hlua->T = NULL;
8768 stream->hlua = hlua;
Thierry Fournierc7492592020-11-28 23:57:24 +01008769 if (!hlua_ctx_init(stream->hlua, fcn_ref_to_stack_id(fcn), stream->task, 0)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008770 SEND_ERR(stream->be, "Lua sample-fetch '%s': can't initialize Lua context.\n", fcn->name);
8771 return 0;
8772 }
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01008773 }
8774
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008775 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008776 if (!HLUA_IS_RUNNING(stream->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008777
8778 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008779 if (!SET_SAFE_LJMP(stream->hlua)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008780 if (lua_type(stream->hlua->T, -1) == LUA_TSTRING)
8781 error = lua_tostring(stream->hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +01008782 else
8783 error = "critical error";
8784 SEND_ERR(smp->px, "Lua sample-fetch '%s': %s.\n", fcn->name, error);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008785 return 0;
8786 }
8787
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008788 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008789 if (!lua_checkstack(stream->hlua->T, 2)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008790 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008791 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008792 return 0;
8793 }
8794
8795 /* Restore the function in the stack. */
Thierry Fournierc7492592020-11-28 23:57:24 +01008796 lua_rawgeti(stream->hlua->T, LUA_REGISTRYINDEX, fcn->function_ref[stream->hlua->state_id]);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008797
8798 /* push arguments in the stack. */
Christopher Fauletbfab2dd2019-07-26 15:09:53 +02008799 if (!hlua_txn_new(stream->hlua->T, stream, smp->px, smp->opt & SMP_OPT_DIR, hflags)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008800 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008801 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008802 return 0;
8803 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008804 stream->hlua->nargs = 1;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008805
8806 /* push keywords in the stack. */
8807 for (; arg_p && arg_p->type != ARGT_STOP; arg_p++) {
8808 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008809 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008810 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008811 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008812 return 0;
8813 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008814 hlua_arg2lua(stream->hlua->T, arg_p);
8815 stream->hlua->nargs++;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008816 }
8817
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008818 /* We must initialize the execution timeouts. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008819 stream->hlua->max_time = hlua_timeout_session;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008820
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008821 /* At this point the execution is safe. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008822 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008823 }
8824
8825 /* Execute the function. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008826 switch (hlua_ctx_resume(stream->hlua, 0)) {
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008827 /* finished. */
8828 case HLUA_E_OK:
Thierry FOURNIERfd80df12017-05-12 16:32:20 +02008829 /* If the stack is empty, the function fails. */
8830 if (lua_gettop(stream->hlua->T) <= 0)
8831 return 0;
8832
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008833 /* Convert the returned value in sample. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008834 hlua_lua2smp(stream->hlua->T, -1, smp);
8835 lua_pop(stream->hlua->T, 1);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008836
8837 /* Set the end of execution flag. */
8838 smp->flags &= ~SMP_F_MAY_CHANGE;
8839 return 1;
8840
8841 /* yield. */
8842 case HLUA_E_AGAIN:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008843 SEND_ERR(smp->px, "Lua sample-fetch '%s': cannot use yielded functions.\n", fcn->name);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008844 return 0;
8845
8846 /* finished with error. */
8847 case HLUA_E_ERRMSG:
8848 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008849 SEND_ERR(smp->px, "Lua sample-fetch '%s': %s.\n",
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008850 fcn->name, lua_tostring(stream->hlua->T, -1));
8851 lua_pop(stream->hlua->T, 1);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008852 return 0;
8853
Thierry Fournierd5b073c2018-05-21 19:42:47 +02008854 case HLUA_E_ETMOUT:
Thierry Fournierd5b073c2018-05-21 19:42:47 +02008855 SEND_ERR(smp->px, "Lua sample-fetch '%s': execution timeout.\n", fcn->name);
8856 return 0;
8857
8858 case HLUA_E_NOMEM:
Thierry Fournierd5b073c2018-05-21 19:42:47 +02008859 SEND_ERR(smp->px, "Lua sample-fetch '%s': out of memory error.\n", fcn->name);
8860 return 0;
8861
8862 case HLUA_E_YIELD:
Thierry Fournierd5b073c2018-05-21 19:42:47 +02008863 SEND_ERR(smp->px, "Lua sample-fetch '%s': yield not allowed.\n", fcn->name);
8864 return 0;
8865
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008866 case HLUA_E_ERR:
8867 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008868 SEND_ERR(smp->px, "Lua sample-fetch '%s' returns an unknown error.\n", fcn->name);
Tim Duesterhus588b3142020-05-29 14:35:51 +02008869 /* fall through */
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008870
8871 default:
8872 return 0;
8873 }
8874}
8875
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008876/* This function is an LUA binding used for registering
8877 * "sample-conv" functions. It expects a converter name used
8878 * in the haproxy configuration file, and an LUA function.
8879 */
8880__LJMP static int hlua_register_converters(lua_State *L)
8881{
8882 struct sample_conv_kw_list *sck;
8883 const char *name;
8884 int ref;
8885 int len;
Christopher Fauletaa224302021-04-12 14:08:21 +02008886 struct hlua_function *fcn = NULL;
Thierry Fournierf67442e2020-11-28 20:41:07 +01008887 struct sample_conv *sc;
8888 struct buffer *trash;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008889
8890 MAY_LJMP(check_args(L, 2, "register_converters"));
8891
8892 /* First argument : converter name. */
8893 name = MAY_LJMP(luaL_checkstring(L, 1));
8894
8895 /* Second argument : lua function. */
8896 ref = MAY_LJMP(hlua_checkfunction(L, 2));
8897
Thierry Fournierf67442e2020-11-28 20:41:07 +01008898 /* Check if the converter is already registered */
8899 trash = get_trash_chunk();
8900 chunk_printf(trash, "lua.%s", name);
8901 sc = find_sample_conv(trash->area, trash->data);
8902 if (sc != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +01008903 fcn = sc->private;
8904 if (fcn->function_ref[hlua_state_id] != -1) {
8905 ha_warning("Trying to register converter 'lua.%s' more than once. "
8906 "This will become a hard error in version 2.5.\n", name);
8907 }
8908 fcn->function_ref[hlua_state_id] = ref;
8909 return 0;
Thierry Fournierf67442e2020-11-28 20:41:07 +01008910 }
8911
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008912 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02008913 sck = calloc(1, sizeof(*sck) + sizeof(struct sample_conv) * 2);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008914 if (!sck)
Christopher Fauletaa224302021-04-12 14:08:21 +02008915 goto alloc_error;
Thierry Fournier62a22aa2020-11-28 21:06:35 +01008916 fcn = new_hlua_function();
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008917 if (!fcn)
Christopher Fauletaa224302021-04-12 14:08:21 +02008918 goto alloc_error;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008919
8920 /* Fill fcn. */
8921 fcn->name = strdup(name);
8922 if (!fcn->name)
Christopher Fauletaa224302021-04-12 14:08:21 +02008923 goto alloc_error;
Thierry Fournierc7492592020-11-28 23:57:24 +01008924 fcn->function_ref[hlua_state_id] = ref;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008925
8926 /* List head */
8927 sck->list.n = sck->list.p = NULL;
8928
8929 /* converter keyword. */
8930 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02008931 sck->kw[0].kw = calloc(1, len);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008932 if (!sck->kw[0].kw)
Christopher Fauletaa224302021-04-12 14:08:21 +02008933 goto alloc_error;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008934
8935 snprintf((char *)sck->kw[0].kw, len, "lua.%s", name);
8936 sck->kw[0].process = hlua_sample_conv_wrapper;
David Carlier0c437f42016-04-27 16:21:56 +01008937 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 +01008938 sck->kw[0].val_args = NULL;
8939 sck->kw[0].in_type = SMP_T_STR;
8940 sck->kw[0].out_type = SMP_T_STR;
8941 sck->kw[0].private = fcn;
8942
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008943 /* Register this new converter */
8944 sample_register_convs(sck);
8945
8946 return 0;
Christopher Fauletaa224302021-04-12 14:08:21 +02008947
8948 alloc_error:
8949 release_hlua_function(fcn);
8950 ha_free(&sck);
8951 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
8952 return 0; /* Never reached */
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008953}
8954
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08008955/* This function is an LUA binding used for registering
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008956 * "sample-fetch" functions. It expects a converter name used
8957 * in the haproxy configuration file, and an LUA function.
8958 */
8959__LJMP static int hlua_register_fetches(lua_State *L)
8960{
8961 const char *name;
8962 int ref;
8963 int len;
8964 struct sample_fetch_kw_list *sfk;
Christopher Faulet2567f182021-04-12 14:11:50 +02008965 struct hlua_function *fcn = NULL;
Thierry Fournierf67442e2020-11-28 20:41:07 +01008966 struct sample_fetch *sf;
8967 struct buffer *trash;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008968
8969 MAY_LJMP(check_args(L, 2, "register_fetches"));
8970
8971 /* First argument : sample-fetch name. */
8972 name = MAY_LJMP(luaL_checkstring(L, 1));
8973
8974 /* Second argument : lua function. */
8975 ref = MAY_LJMP(hlua_checkfunction(L, 2));
8976
Thierry Fournierf67442e2020-11-28 20:41:07 +01008977 /* Check if the sample-fetch is already registered */
8978 trash = get_trash_chunk();
8979 chunk_printf(trash, "lua.%s", name);
8980 sf = find_sample_fetch(trash->area, trash->data);
8981 if (sf != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +01008982 fcn = sf->private;
8983 if (fcn->function_ref[hlua_state_id] != -1) {
8984 ha_warning("Trying to register sample-fetch 'lua.%s' more than once. "
8985 "This will become a hard error in version 2.5.\n", name);
8986 }
8987 fcn->function_ref[hlua_state_id] = ref;
8988 return 0;
Thierry Fournierf67442e2020-11-28 20:41:07 +01008989 }
8990
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008991 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02008992 sfk = calloc(1, sizeof(*sfk) + sizeof(struct sample_fetch) * 2);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008993 if (!sfk)
Christopher Faulet2567f182021-04-12 14:11:50 +02008994 goto alloc_error;
Thierry Fournier62a22aa2020-11-28 21:06:35 +01008995 fcn = new_hlua_function();
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008996 if (!fcn)
Christopher Faulet2567f182021-04-12 14:11:50 +02008997 goto alloc_error;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008998
8999 /* Fill fcn. */
9000 fcn->name = strdup(name);
9001 if (!fcn->name)
Christopher Faulet2567f182021-04-12 14:11:50 +02009002 goto alloc_error;
Thierry Fournierc7492592020-11-28 23:57:24 +01009003 fcn->function_ref[hlua_state_id] = ref;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009004
9005 /* List head */
9006 sfk->list.n = sfk->list.p = NULL;
9007
9008 /* sample-fetch keyword. */
9009 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02009010 sfk->kw[0].kw = calloc(1, len);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009011 if (!sfk->kw[0].kw)
Christopher Faulet2567f182021-04-12 14:11:50 +02009012 goto alloc_error;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009013
9014 snprintf((char *)sfk->kw[0].kw, len, "lua.%s", name);
9015 sfk->kw[0].process = hlua_sample_fetch_wrapper;
David Carlier0c437f42016-04-27 16:21:56 +01009016 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 +01009017 sfk->kw[0].val_args = NULL;
9018 sfk->kw[0].out_type = SMP_T_STR;
9019 sfk->kw[0].use = SMP_USE_HTTP_ANY;
9020 sfk->kw[0].val = 0;
9021 sfk->kw[0].private = fcn;
9022
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009023 /* Register this new fetch. */
9024 sample_register_fetches(sfk);
9025
9026 return 0;
Christopher Faulet2567f182021-04-12 14:11:50 +02009027
9028 alloc_error:
9029 release_hlua_function(fcn);
9030 ha_free(&sfk);
9031 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
9032 return 0; /* Never reached */
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009033}
9034
Christopher Faulet501465d2020-02-26 14:54:16 +01009035/* This function is a lua binding to set the wake_time.
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01009036 */
Christopher Faulet501465d2020-02-26 14:54:16 +01009037__LJMP static int hlua_set_wake_time(lua_State *L)
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01009038{
Thierry Fournier4234dbd2020-11-28 13:18:23 +01009039 struct hlua *hlua;
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01009040 unsigned int delay;
9041 unsigned int wakeup_ms;
9042
Thierry Fournier4234dbd2020-11-28 13:18:23 +01009043 /* Get hlua struct, or NULL if we execute from main lua state */
9044 hlua = hlua_gethlua(L);
9045 if (!hlua) {
9046 return 0;
9047 }
9048
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01009049 MAY_LJMP(check_args(L, 1, "wake_time"));
9050
9051 delay = MAY_LJMP(luaL_checkinteger(L, 1));
9052 wakeup_ms = tick_add(now_ms, delay);
9053 hlua->wake_time = wakeup_ms;
9054 return 0;
9055}
9056
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009057/* This function is a wrapper to execute each LUA function declared as an action
9058 * wrapper during the initialisation period. This function may return any
9059 * ACT_RET_* value. On error ACT_RET_CONT is returned and the action is
9060 * ignored. If the lua action yields, ACT_RET_YIELD is returned. On success, the
9061 * return value is the first element on the stack.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009062 */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009063static enum act_return hlua_action(struct act_rule *rule, struct proxy *px,
Willy Tarreau658b85b2015-09-27 10:00:49 +02009064 struct session *sess, struct stream *s, int flags)
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009065{
9066 char **arg;
Christopher Faulet8c9e6bb2021-08-06 16:29:41 +02009067 unsigned int hflags = HLUA_TXN_ACT_CTX;
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009068 int dir, act_ret = ACT_RET_CONT;
Thierry Fournierfd107a22016-02-19 19:57:23 +01009069 const char *error;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009070
9071 switch (rule->from) {
Christopher Fauletd8f0e072020-02-25 09:45:51 +01009072 case ACT_F_TCP_REQ_CNT: dir = SMP_OPT_DIR_REQ; break;
9073 case ACT_F_TCP_RES_CNT: dir = SMP_OPT_DIR_RES; break;
9074 case ACT_F_HTTP_REQ: dir = SMP_OPT_DIR_REQ; break;
9075 case ACT_F_HTTP_RES: dir = SMP_OPT_DIR_RES; break;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009076 default:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009077 SEND_ERR(px, "Lua: internal error while execute action.\n");
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009078 goto end;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009079 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009080
Willy Tarreau87b09662015-04-03 00:22:06 +02009081 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01009082 * Lua context can be not initialized. This behavior
9083 * permits to save performances because a systematic
9084 * Lua initialization cause 5% performances loss.
9085 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009086 if (!s->hlua) {
Christopher Faulet1e8433f2021-03-24 15:03:01 +01009087 struct hlua *hlua;
9088
9089 hlua = pool_alloc(pool_head_hlua);
9090 if (!hlua) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009091 SEND_ERR(px, "Lua action '%s': can't initialize Lua context.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009092 rule->arg.hlua_rule->fcn->name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009093 goto end;
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009094 }
Christopher Faulet1e8433f2021-03-24 15:03:01 +01009095 HLUA_INIT(hlua);
9096 s->hlua = hlua;
Thierry Fournierc7492592020-11-28 23:57:24 +01009097 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 +01009098 SEND_ERR(px, "Lua action '%s': can't initialize Lua context.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009099 rule->arg.hlua_rule->fcn->name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009100 goto end;
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009101 }
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01009102 }
9103
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009104 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009105 if (!HLUA_IS_RUNNING(s->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02009106
9107 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009108 if (!SET_SAFE_LJMP(s->hlua)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009109 if (lua_type(s->hlua->T, -1) == LUA_TSTRING)
9110 error = lua_tostring(s->hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +01009111 else
9112 error = "critical error";
9113 SEND_ERR(px, "Lua function '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009114 rule->arg.hlua_rule->fcn->name, error);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009115 goto end;
Thierry FOURNIERbabae282015-09-17 11:36:37 +02009116 }
9117
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009118 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009119 if (!lua_checkstack(s->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009120 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009121 rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009122 RESET_SAFE_LJMP(s->hlua);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009123 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009124 }
9125
9126 /* Restore the function in the stack. */
Thierry Fournierc7492592020-11-28 23:57:24 +01009127 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 +01009128
Willy Tarreau87b09662015-04-03 00:22:06 +02009129 /* Create and and push object stream in the stack. */
Christopher Fauletbfab2dd2019-07-26 15:09:53 +02009130 if (!hlua_txn_new(s->hlua->T, s, px, dir, hflags)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009131 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009132 rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009133 RESET_SAFE_LJMP(s->hlua);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009134 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009135 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009136 s->hlua->nargs = 1;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009137
9138 /* push keywords in the stack. */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009139 for (arg = rule->arg.hlua_rule->args; arg && *arg; arg++) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009140 if (!lua_checkstack(s->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009141 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009142 rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009143 RESET_SAFE_LJMP(s->hlua);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009144 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009145 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009146 lua_pushstring(s->hlua->T, *arg);
9147 s->hlua->nargs++;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009148 }
9149
Thierry FOURNIERbabae282015-09-17 11:36:37 +02009150 /* Now the execution is safe. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009151 RESET_SAFE_LJMP(s->hlua);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02009152
Thierry FOURNIERbd413492015-03-03 16:52:26 +01009153 /* We must initialize the execution timeouts. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009154 s->hlua->max_time = hlua_timeout_session;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009155 }
9156
9157 /* Execute the function. */
Christopher Faulet105ba6c2019-12-18 14:41:51 +01009158 switch (hlua_ctx_resume(s->hlua, !(flags & ACT_OPT_FINAL))) {
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009159 /* finished. */
9160 case HLUA_E_OK:
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009161 /* Catch the return value */
9162 if (lua_gettop(s->hlua->T) > 0)
9163 act_ret = lua_tointeger(s->hlua->T, -1);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009164
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01009165 /* Set timeout in the required channel. */
Christopher Faulet498c4832020-07-28 11:59:58 +02009166 if (act_ret == ACT_RET_YIELD) {
9167 if (flags & ACT_OPT_FINAL)
9168 goto err_yield;
9169
Christopher Faulet8f587ea2020-07-28 12:01:55 +02009170 if (dir == SMP_OPT_DIR_REQ)
9171 s->req.analyse_exp = tick_first((tick_is_expired(s->req.analyse_exp, now_ms) ? 0 : s->req.analyse_exp),
9172 s->hlua->wake_time);
9173 else
9174 s->res.analyse_exp = tick_first((tick_is_expired(s->res.analyse_exp, now_ms) ? 0 : s->res.analyse_exp),
9175 s->hlua->wake_time);
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01009176 }
9177 goto end;
9178
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009179 /* yield. */
9180 case HLUA_E_AGAIN:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01009181 /* Set timeout in the required channel. */
Christopher Faulet8f587ea2020-07-28 12:01:55 +02009182 if (dir == SMP_OPT_DIR_REQ)
9183 s->req.analyse_exp = tick_first((tick_is_expired(s->req.analyse_exp, now_ms) ? 0 : s->req.analyse_exp),
9184 s->hlua->wake_time);
9185 else
9186 s->res.analyse_exp = tick_first((tick_is_expired(s->res.analyse_exp, now_ms) ? 0 : s->res.analyse_exp),
9187 s->hlua->wake_time);
9188
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009189 /* Some actions can be wake up when a "write" event
9190 * is detected on a response channel. This is useful
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08009191 * only for actions targeted on the requests.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009192 */
Christopher Faulet51fa3582019-07-26 14:54:52 +02009193 if (HLUA_IS_WAKERESWR(s->hlua))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01009194 s->res.flags |= CF_WAKE_WRITE;
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009195 if (HLUA_IS_WAKEREQWR(s->hlua))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01009196 s->req.flags |= CF_WAKE_WRITE;
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009197 act_ret = ACT_RET_YIELD;
9198 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009199
9200 /* finished with error. */
9201 case HLUA_E_ERRMSG:
9202 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009203 SEND_ERR(px, "Lua function '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009204 rule->arg.hlua_rule->fcn->name, lua_tostring(s->hlua->T, -1));
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009205 lua_pop(s->hlua->T, 1);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009206 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009207
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009208 case HLUA_E_ETMOUT:
Thierry Fournierad5345f2020-11-29 02:05:57 +01009209 SEND_ERR(px, "Lua function '%s': execution timeout.\n", rule->arg.hlua_rule->fcn->name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009210 goto end;
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009211
9212 case HLUA_E_NOMEM:
Thierry Fournierad5345f2020-11-29 02:05:57 +01009213 SEND_ERR(px, "Lua function '%s': out of memory error.\n", rule->arg.hlua_rule->fcn->name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009214 goto end;
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009215
9216 case HLUA_E_YIELD:
Christopher Faulet498c4832020-07-28 11:59:58 +02009217 err_yield:
9218 act_ret = ACT_RET_CONT;
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009219 SEND_ERR(px, "Lua function '%s': aborting Lua processing on expired timeout.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009220 rule->arg.hlua_rule->fcn->name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009221 goto end;
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009222
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009223 case HLUA_E_ERR:
9224 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009225 SEND_ERR(px, "Lua function '%s' return an unknown error.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009226 rule->arg.hlua_rule->fcn->name);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009227
9228 default:
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009229 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009230 }
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009231
9232 end:
Christopher Faulet2361fd92020-07-30 10:40:58 +02009233 if (act_ret != ACT_RET_YIELD && s->hlua)
Christopher Faulet8f587ea2020-07-28 12:01:55 +02009234 s->hlua->wake_time = TICK_ETERNITY;
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009235 return act_ret;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009236}
9237
Willy Tarreau144f84a2021-03-02 16:09:26 +01009238struct task *hlua_applet_wakeup(struct task *t, void *context, unsigned int state)
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009239{
Olivier Houchard9f6af332018-05-25 14:04:04 +02009240 struct appctx *ctx = context;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009241
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009242 appctx_wakeup(ctx);
Willy Tarreaud9587412017-08-23 16:07:33 +02009243 t->expire = TICK_ETERNITY;
Willy Tarreaud1aa41f2017-07-21 16:41:56 +02009244 return t;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009245}
9246
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009247static int hlua_applet_tcp_init(struct appctx *ctx)
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009248{
Willy Tarreaue23f33b2022-05-06 14:07:13 +02009249 struct hlua_tcp_ctx *tcp_ctx = applet_reserve_svcctx(ctx, sizeof(*tcp_ctx));
Willy Tarreauc12b3212022-05-27 11:08:15 +02009250 struct stconn *sc = appctx_sc(ctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02009251 struct stream *strm = __sc_strm(sc);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009252 struct hlua *hlua;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009253 struct task *task;
9254 char **arg;
Thierry Fournierfd107a22016-02-19 19:57:23 +01009255 const char *error;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009256
Willy Tarreaubafbe012017-11-24 17:34:44 +01009257 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009258 if (!hlua) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009259 SEND_ERR(strm->be, "Lua applet tcp '%s': out of memory.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009260 ctx->rule->arg.hlua_rule->fcn->name);
Christopher Fauletc9929382022-05-12 11:52:27 +02009261 return -1;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009262 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009263 HLUA_INIT(hlua);
Willy Tarreaue23f33b2022-05-06 14:07:13 +02009264 tcp_ctx->hlua = hlua;
9265 tcp_ctx->flags = 0;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009266
9267 /* Create task used by signal to wakeup applets. */
Willy Tarreaubeeabf52021-10-01 18:23:30 +02009268 task = task_new_here();
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009269 if (!task) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009270 SEND_ERR(strm->be, "Lua applet tcp '%s': out of memory.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009271 ctx->rule->arg.hlua_rule->fcn->name);
Christopher Fauletc9929382022-05-12 11:52:27 +02009272 return -1;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009273 }
9274 task->nice = 0;
9275 task->context = ctx;
9276 task->process = hlua_applet_wakeup;
Willy Tarreaue23f33b2022-05-06 14:07:13 +02009277 tcp_ctx->task = task;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009278
9279 /* In the execution wrappers linked with a stream, the
9280 * Lua context can be not initialized. This behavior
9281 * permits to save performances because a systematic
9282 * Lua initialization cause 5% performances loss.
9283 */
Thierry Fournierc7492592020-11-28 23:57:24 +01009284 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 +01009285 SEND_ERR(strm->be, "Lua applet tcp '%s': can't initialize Lua context.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009286 ctx->rule->arg.hlua_rule->fcn->name);
Christopher Fauletc9929382022-05-12 11:52:27 +02009287 return -1;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009288 }
9289
9290 /* Set timeout according with the applet configuration. */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02009291 hlua->max_time = ctx->applet->timeout;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009292
9293 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009294 if (!SET_SAFE_LJMP(hlua)) {
Thierry Fournierfd107a22016-02-19 19:57:23 +01009295 if (lua_type(hlua->T, -1) == LUA_TSTRING)
9296 error = lua_tostring(hlua->T, -1);
9297 else
9298 error = "critical error";
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009299 SEND_ERR(strm->be, "Lua applet tcp '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009300 ctx->rule->arg.hlua_rule->fcn->name, error);
Christopher Fauletc9929382022-05-12 11:52:27 +02009301 return -1;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009302 }
9303
9304 /* Check stack available size. */
9305 if (!lua_checkstack(hlua->T, 1)) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009306 SEND_ERR(strm->be, "Lua applet tcp '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009307 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009308 RESET_SAFE_LJMP(hlua);
Christopher Fauletc9929382022-05-12 11:52:27 +02009309 return -1;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009310 }
9311
9312 /* Restore the function in the stack. */
Thierry Fournierc7492592020-11-28 23:57:24 +01009313 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ctx->rule->arg.hlua_rule->fcn->function_ref[hlua->state_id]);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009314
9315 /* Create and and push object stream in the stack. */
9316 if (!hlua_applet_tcp_new(hlua->T, ctx)) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009317 SEND_ERR(strm->be, "Lua applet tcp '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009318 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009319 RESET_SAFE_LJMP(hlua);
Christopher Fauletc9929382022-05-12 11:52:27 +02009320 return -1;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009321 }
9322 hlua->nargs = 1;
9323
9324 /* push keywords in the stack. */
9325 for (arg = ctx->rule->arg.hlua_rule->args; arg && *arg; arg++) {
9326 if (!lua_checkstack(hlua->T, 1)) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009327 SEND_ERR(strm->be, "Lua applet tcp '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009328 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009329 RESET_SAFE_LJMP(hlua);
Christopher Fauletc9929382022-05-12 11:52:27 +02009330 return -1;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009331 }
9332 lua_pushstring(hlua->T, *arg);
9333 hlua->nargs++;
9334 }
9335
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009336 RESET_SAFE_LJMP(hlua);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009337
9338 /* Wakeup the applet ASAP. */
Willy Tarreau90e8b452022-05-25 18:21:43 +02009339 applet_need_more_data(ctx);
Willy Tarreau4164eb92022-05-25 15:42:03 +02009340 applet_have_more_data(ctx);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009341
Christopher Fauletc9929382022-05-12 11:52:27 +02009342 return 0;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009343}
9344
Willy Tarreau60409db2019-08-21 14:14:50 +02009345void hlua_applet_tcp_fct(struct appctx *ctx)
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009346{
Willy Tarreaue23f33b2022-05-06 14:07:13 +02009347 struct hlua_tcp_ctx *tcp_ctx = ctx->svcctx;
Willy Tarreauc12b3212022-05-27 11:08:15 +02009348 struct stconn *sc = appctx_sc(ctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02009349 struct stream *strm = __sc_strm(sc);
9350 struct channel *res = sc_ic(sc);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009351 struct act_rule *rule = ctx->rule;
9352 struct proxy *px = strm->be;
Willy Tarreaue23f33b2022-05-06 14:07:13 +02009353 struct hlua *hlua = tcp_ctx->hlua;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009354
9355 /* The applet execution is already done. */
Willy Tarreaue23f33b2022-05-06 14:07:13 +02009356 if (tcp_ctx->flags & APPLET_DONE) {
Olivier Houchard594c8c52018-08-28 14:41:31 +02009357 /* eat the whole request */
Willy Tarreau3e7be362022-05-27 10:35:27 +02009358 co_skip(sc_oc(sc), co_data(sc_oc(sc)));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009359 return;
Olivier Houchard594c8c52018-08-28 14:41:31 +02009360 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009361
9362 /* If the stream is disconnect or closed, ldo nothing. */
Willy Tarreau3e7be362022-05-27 10:35:27 +02009363 if (unlikely(sc->state == SC_ST_DIS || sc->state == SC_ST_CLO))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009364 return;
9365
9366 /* Execute the function. */
9367 switch (hlua_ctx_resume(hlua, 1)) {
9368 /* finished. */
9369 case HLUA_E_OK:
Willy Tarreaue23f33b2022-05-06 14:07:13 +02009370 tcp_ctx->flags |= APPLET_DONE;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009371
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009372 /* eat the whole request */
Willy Tarreau3e7be362022-05-27 10:35:27 +02009373 co_skip(sc_oc(sc), co_data(sc_oc(sc)));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009374 res->flags |= CF_READ_NULL;
Willy Tarreau3e7be362022-05-27 10:35:27 +02009375 sc_shutr(sc);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009376 return;
9377
9378 /* yield. */
9379 case HLUA_E_AGAIN:
Thierry Fournier0164f202016-02-20 17:47:43 +01009380 if (hlua->wake_time != TICK_ETERNITY)
Willy Tarreaue23f33b2022-05-06 14:07:13 +02009381 task_schedule(tcp_ctx->task, hlua->wake_time);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009382 return;
9383
9384 /* finished with error. */
9385 case HLUA_E_ERRMSG:
9386 /* Display log. */
9387 SEND_ERR(px, "Lua applet tcp '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009388 rule->arg.hlua_rule->fcn->name, lua_tostring(hlua->T, -1));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009389 lua_pop(hlua->T, 1);
9390 goto error;
9391
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009392 case HLUA_E_ETMOUT:
9393 SEND_ERR(px, "Lua applet tcp '%s': execution timeout.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009394 rule->arg.hlua_rule->fcn->name);
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009395 goto error;
9396
9397 case HLUA_E_NOMEM:
9398 SEND_ERR(px, "Lua applet tcp '%s': out of memory error.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009399 rule->arg.hlua_rule->fcn->name);
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009400 goto error;
9401
9402 case HLUA_E_YIELD: /* unexpected */
9403 SEND_ERR(px, "Lua applet tcp '%s': yield not allowed.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009404 rule->arg.hlua_rule->fcn->name);
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009405 goto error;
9406
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009407 case HLUA_E_ERR:
9408 /* Display log. */
9409 SEND_ERR(px, "Lua applet tcp '%s' return an unknown error.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009410 rule->arg.hlua_rule->fcn->name);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009411 goto error;
9412
9413 default:
9414 goto error;
9415 }
9416
9417error:
9418
9419 /* For all other cases, just close the stream. */
Willy Tarreau3e7be362022-05-27 10:35:27 +02009420 sc_shutw(sc);
9421 sc_shutr(sc);
Willy Tarreaue23f33b2022-05-06 14:07:13 +02009422 tcp_ctx->flags |= APPLET_DONE;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009423}
9424
9425static void hlua_applet_tcp_release(struct appctx *ctx)
9426{
Willy Tarreaue23f33b2022-05-06 14:07:13 +02009427 struct hlua_tcp_ctx *tcp_ctx = ctx->svcctx;
9428
9429 task_destroy(tcp_ctx->task);
9430 tcp_ctx->task = NULL;
9431 hlua_ctx_destroy(tcp_ctx->hlua);
9432 tcp_ctx->hlua = NULL;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009433}
9434
Christopher Fauletc9929382022-05-12 11:52:27 +02009435/* The function returns 0 if the initialisation is complete or -1 if
9436 * an errors occurs. It also reserves the appctx for an hlua_http_ctx.
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009437 */
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009438static int hlua_applet_http_init(struct appctx *ctx)
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009439{
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009440 struct hlua_http_ctx *http_ctx = applet_reserve_svcctx(ctx, sizeof(*http_ctx));
Willy Tarreauc12b3212022-05-27 11:08:15 +02009441 struct stconn *sc = appctx_sc(ctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02009442 struct stream *strm = __sc_strm(sc);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009443 struct http_txn *txn;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009444 struct hlua *hlua;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009445 char **arg;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009446 struct task *task;
Thierry Fournierfd107a22016-02-19 19:57:23 +01009447 const char *error;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009448
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009449 txn = strm->txn;
Willy Tarreaubafbe012017-11-24 17:34:44 +01009450 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009451 if (!hlua) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009452 SEND_ERR(strm->be, "Lua applet http '%s': out of memory.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009453 ctx->rule->arg.hlua_rule->fcn->name);
Christopher Fauletc9929382022-05-12 11:52:27 +02009454 return -1;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009455 }
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009456 HLUA_INIT(hlua);
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009457 http_ctx->hlua = hlua;
9458 http_ctx->left_bytes = -1;
9459 http_ctx->flags = 0;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009460
Thierry FOURNIERd93ea2b2015-12-20 19:14:52 +01009461 if (txn->req.flags & HTTP_MSGF_VER_11)
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009462 http_ctx->flags |= APPLET_HTTP11;
Thierry FOURNIERd93ea2b2015-12-20 19:14:52 +01009463
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009464 /* Create task used by signal to wakeup applets. */
Willy Tarreaubeeabf52021-10-01 18:23:30 +02009465 task = task_new_here();
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009466 if (!task) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009467 SEND_ERR(strm->be, "Lua applet http '%s': out of memory.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009468 ctx->rule->arg.hlua_rule->fcn->name);
Christopher Fauletc9929382022-05-12 11:52:27 +02009469 return -1;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009470 }
9471 task->nice = 0;
9472 task->context = ctx;
9473 task->process = hlua_applet_wakeup;
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009474 http_ctx->task = task;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009475
9476 /* In the execution wrappers linked with a stream, the
9477 * Lua context can be not initialized. This behavior
9478 * permits to save performances because a systematic
9479 * Lua initialization cause 5% performances loss.
9480 */
Thierry Fournierc7492592020-11-28 23:57:24 +01009481 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 +01009482 SEND_ERR(strm->be, "Lua applet http '%s': can't initialize Lua context.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009483 ctx->rule->arg.hlua_rule->fcn->name);
Christopher Fauletc9929382022-05-12 11:52:27 +02009484 return -1;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009485 }
9486
9487 /* Set timeout according with the applet configuration. */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02009488 hlua->max_time = ctx->applet->timeout;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009489
9490 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009491 if (!SET_SAFE_LJMP(hlua)) {
Thierry Fournierfd107a22016-02-19 19:57:23 +01009492 if (lua_type(hlua->T, -1) == LUA_TSTRING)
9493 error = lua_tostring(hlua->T, -1);
9494 else
9495 error = "critical error";
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009496 SEND_ERR(strm->be, "Lua applet http '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009497 ctx->rule->arg.hlua_rule->fcn->name, error);
Christopher Fauletc9929382022-05-12 11:52:27 +02009498 return -1;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009499 }
9500
9501 /* Check stack available size. */
9502 if (!lua_checkstack(hlua->T, 1)) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009503 SEND_ERR(strm->be, "Lua applet http '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009504 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009505 RESET_SAFE_LJMP(hlua);
Christopher Fauletc9929382022-05-12 11:52:27 +02009506 return -1;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009507 }
9508
9509 /* Restore the function in the stack. */
Thierry Fournierc7492592020-11-28 23:57:24 +01009510 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ctx->rule->arg.hlua_rule->fcn->function_ref[hlua->state_id]);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009511
9512 /* Create and and push object stream in the stack. */
9513 if (!hlua_applet_http_new(hlua->T, ctx)) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009514 SEND_ERR(strm->be, "Lua applet http '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009515 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009516 RESET_SAFE_LJMP(hlua);
Christopher Fauletc9929382022-05-12 11:52:27 +02009517 return -1;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009518 }
9519 hlua->nargs = 1;
9520
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009521 /* push keywords in the stack. */
9522 for (arg = ctx->rule->arg.hlua_rule->args; arg && *arg; arg++) {
9523 if (!lua_checkstack(hlua->T, 1)) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009524 SEND_ERR(strm->be, "Lua applet http '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009525 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009526 RESET_SAFE_LJMP(hlua);
Christopher Fauletc9929382022-05-12 11:52:27 +02009527 return -1;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009528 }
9529 lua_pushstring(hlua->T, *arg);
9530 hlua->nargs++;
9531 }
9532
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009533 RESET_SAFE_LJMP(hlua);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009534
9535 /* Wakeup the applet when data is ready for read. */
Willy Tarreau90e8b452022-05-25 18:21:43 +02009536 applet_need_more_data(ctx);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009537
Christopher Fauletc9929382022-05-12 11:52:27 +02009538 return 0;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009539}
9540
Willy Tarreau60409db2019-08-21 14:14:50 +02009541void hlua_applet_http_fct(struct appctx *ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009542{
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009543 struct hlua_http_ctx *http_ctx = ctx->svcctx;
Willy Tarreauc12b3212022-05-27 11:08:15 +02009544 struct stconn *sc = appctx_sc(ctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02009545 struct stream *strm = __sc_strm(sc);
9546 struct channel *req = sc_oc(sc);
9547 struct channel *res = sc_ic(sc);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009548 struct act_rule *rule = ctx->rule;
9549 struct proxy *px = strm->be;
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009550 struct hlua *hlua = http_ctx->hlua;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009551 struct htx *req_htx, *res_htx;
9552
9553 res_htx = htx_from_buf(&res->buf);
9554
9555 /* If the stream is disconnect or closed, ldo nothing. */
Willy Tarreau3e7be362022-05-27 10:35:27 +02009556 if (unlikely(sc->state == SC_ST_DIS || sc->state == SC_ST_CLO))
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009557 goto out;
9558
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05009559 /* Check if the input buffer is available. */
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009560 if (!b_size(&res->buf)) {
Willy Tarreau3e7be362022-05-27 10:35:27 +02009561 sc_need_room(sc);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009562 goto out;
9563 }
9564 /* check that the output is not closed */
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01009565 if (res->flags & (CF_SHUTW|CF_SHUTW_NOW|CF_SHUTR))
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009566 http_ctx->flags |= APPLET_DONE;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009567
9568 /* Set the currently running flag. */
9569 if (!HLUA_IS_RUNNING(hlua) &&
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009570 !(http_ctx->flags & APPLET_DONE)) {
Christopher Fauletbd878d22021-04-28 10:50:21 +02009571 if (!co_data(req)) {
Willy Tarreau90e8b452022-05-25 18:21:43 +02009572 applet_need_more_data(ctx);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009573 goto out;
9574 }
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009575 }
9576
9577 /* Executes The applet if it is not done. */
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009578 if (!(http_ctx->flags & APPLET_DONE)) {
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009579
9580 /* Execute the function. */
9581 switch (hlua_ctx_resume(hlua, 1)) {
9582 /* finished. */
9583 case HLUA_E_OK:
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009584 http_ctx->flags |= APPLET_DONE;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009585 break;
9586
9587 /* yield. */
9588 case HLUA_E_AGAIN:
9589 if (hlua->wake_time != TICK_ETERNITY)
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009590 task_schedule(http_ctx->task, hlua->wake_time);
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01009591 goto out;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009592
9593 /* finished with error. */
9594 case HLUA_E_ERRMSG:
9595 /* Display log. */
9596 SEND_ERR(px, "Lua applet http '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009597 rule->arg.hlua_rule->fcn->name, lua_tostring(hlua->T, -1));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009598 lua_pop(hlua->T, 1);
9599 goto error;
9600
9601 case HLUA_E_ETMOUT:
9602 SEND_ERR(px, "Lua applet http '%s': execution timeout.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009603 rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009604 goto error;
9605
9606 case HLUA_E_NOMEM:
9607 SEND_ERR(px, "Lua applet http '%s': out of memory error.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009608 rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009609 goto error;
9610
9611 case HLUA_E_YIELD: /* unexpected */
9612 SEND_ERR(px, "Lua applet http '%s': yield not allowed.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009613 rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009614 goto error;
9615
9616 case HLUA_E_ERR:
9617 /* Display log. */
9618 SEND_ERR(px, "Lua applet http '%s' return an unknown error.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009619 rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009620 goto error;
9621
9622 default:
9623 goto error;
9624 }
9625 }
9626
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009627 if (http_ctx->flags & APPLET_DONE) {
9628 if (http_ctx->flags & APPLET_RSP_SENT)
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01009629 goto done;
9630
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009631 if (!(http_ctx->flags & APPLET_HDR_SENT))
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009632 goto error;
9633
Christopher Fauletf89af9c2022-04-07 10:07:18 +02009634 /* no more data are expected. If the response buffer is empty
9635 * for a chunked message, be sure to add something (EOT block in
9636 * this case) to have something to send. It is important to be
9637 * sure the EOM flags will be handled by the endpoint.
9638 */
9639 if (htx_is_empty(res_htx) && (strm->txn->rsp.flags & (HTTP_MSGF_XFER_LEN|HTTP_MSGF_CNT_LEN)) == HTTP_MSGF_XFER_LEN) {
9640 if (!htx_add_endof(res_htx, HTX_BLK_EOT)) {
Willy Tarreau3e7be362022-05-27 10:35:27 +02009641 sc_need_room(sc);
Christopher Fauletf89af9c2022-04-07 10:07:18 +02009642 goto out;
9643 }
9644 channel_add_input(res, 1);
9645 }
9646
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01009647 res_htx->flags |= HTX_FL_EOM;
Christopher Fauletd8d27082022-03-07 15:50:54 +01009648 res->flags |= CF_EOI;
Willy Tarreaud869e132022-05-17 18:05:31 +02009649 se_fl_set(ctx->sedesc, SE_FL_EOI);
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009650 strm->txn->status = http_ctx->status;
9651 http_ctx->flags |= APPLET_RSP_SENT;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009652 }
9653
9654 done:
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009655 if (http_ctx->flags & APPLET_DONE) {
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01009656 if (!(res->flags & CF_SHUTR)) {
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009657 res->flags |= CF_READ_NULL;
Willy Tarreau3e7be362022-05-27 10:35:27 +02009658 sc_shutr(sc);
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01009659 }
9660
9661 /* eat the whole request */
9662 if (co_data(req)) {
9663 req_htx = htx_from_buf(&req->buf);
9664 co_htx_skip(req, req_htx, co_data(req));
9665 htx_to_buf(req_htx, &req->buf);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009666 }
9667 }
9668
9669 out:
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009670 htx_to_buf(res_htx, &res->buf);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009671 return;
9672
9673 error:
9674
9675 /* If we are in HTTP mode, and we are not send any
9676 * data, return a 500 server error in best effort:
9677 * if there is no room available in the buffer,
9678 * just close the connection.
9679 */
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009680 if (!(http_ctx->flags & APPLET_HDR_SENT)) {
Christopher Fauletf7346382019-07-17 22:02:08 +02009681 struct buffer *err = &http_err_chunks[HTTP_ERR_500];
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009682
9683 channel_erase(res);
9684 res->buf.data = b_data(err);
9685 memcpy(res->buf.area, b_head(err), b_data(err));
9686 res_htx = htx_from_buf(&res->buf);
Christopher Fauletf6cce3f2019-02-27 21:20:09 +01009687 channel_add_input(res, res_htx->data);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009688 }
9689 if (!(strm->flags & SF_ERR_MASK))
9690 strm->flags |= SF_ERR_RESOURCE;
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009691 http_ctx->flags |= APPLET_DONE;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009692 goto done;
9693}
9694
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009695static void hlua_applet_http_release(struct appctx *ctx)
9696{
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009697 struct hlua_http_ctx *http_ctx = ctx->svcctx;
9698
9699 task_destroy(http_ctx->task);
9700 http_ctx->task = NULL;
9701 hlua_ctx_destroy(http_ctx->hlua);
9702 http_ctx->hlua = NULL;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009703}
9704
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009705/* global {tcp|http}-request parser. Return ACT_RET_PRS_OK in
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05009706 * success case, else return ACT_RET_PRS_ERR.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02009707 *
9708 * This function can fail with an abort() due to an Lua critical error.
9709 * We are in the configuration parsing process of HAProxy, this abort() is
9710 * tolerated.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009711 */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009712static enum act_parse_ret action_register_lua(const char **args, int *cur_arg, struct proxy *px,
9713 struct act_rule *rule, char **err)
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009714{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02009715 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009716 int i;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009717
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009718 /* Memory for the rule. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02009719 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009720 if (!rule->arg.hlua_rule) {
9721 memprintf(err, "out of memory error");
Christopher Faulet528526f2021-04-12 14:37:32 +02009722 goto error;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009723 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009724
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009725 /* Memory for arguments. */
Tim Duesterhuse52b6e52020-09-12 20:26:43 +02009726 rule->arg.hlua_rule->args = calloc(fcn->nargs + 1,
9727 sizeof(*rule->arg.hlua_rule->args));
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009728 if (!rule->arg.hlua_rule->args) {
9729 memprintf(err, "out of memory error");
Christopher Faulet528526f2021-04-12 14:37:32 +02009730 goto error;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009731 }
9732
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009733 /* Reference the Lua function and store the reference. */
Thierry Fournierad5345f2020-11-29 02:05:57 +01009734 rule->arg.hlua_rule->fcn = fcn;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009735
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009736 /* Expect some arguments */
9737 for (i = 0; i < fcn->nargs; i++) {
Thierry FOURNIER1725c2e2019-01-06 19:38:49 +01009738 if (*args[*cur_arg] == '\0') {
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009739 memprintf(err, "expect %d arguments", fcn->nargs);
Christopher Faulet528526f2021-04-12 14:37:32 +02009740 goto error;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009741 }
Thierry FOURNIER1725c2e2019-01-06 19:38:49 +01009742 rule->arg.hlua_rule->args[i] = strdup(args[*cur_arg]);
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009743 if (!rule->arg.hlua_rule->args[i]) {
9744 memprintf(err, "out of memory error");
Christopher Faulet528526f2021-04-12 14:37:32 +02009745 goto error;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009746 }
9747 (*cur_arg)++;
9748 }
9749 rule->arg.hlua_rule->args[i] = NULL;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009750
Thierry FOURNIER42148732015-09-02 17:17:33 +02009751 rule->action = ACT_CUSTOM;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009752 rule->action_ptr = hlua_action;
Thierry FOURNIERafa80492015-08-19 09:04:15 +02009753 return ACT_RET_PRS_OK;
Christopher Faulet528526f2021-04-12 14:37:32 +02009754
9755 error:
9756 if (rule->arg.hlua_rule) {
9757 if (rule->arg.hlua_rule->args) {
9758 for (i = 0; i < fcn->nargs; i++)
9759 ha_free(&rule->arg.hlua_rule->args[i]);
9760 ha_free(&rule->arg.hlua_rule->args);
9761 }
9762 ha_free(&rule->arg.hlua_rule);
9763 }
9764 return ACT_RET_PRS_ERR;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009765}
9766
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009767static enum act_parse_ret action_register_service_http(const char **args, int *cur_arg, struct proxy *px,
9768 struct act_rule *rule, char **err)
9769{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02009770 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009771
Thierry FOURNIER718e2a72015-12-20 20:13:14 +01009772 /* HTTP applets are forbidden in tcp-request rules.
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05009773 * HTTP applet request requires everything initialized by
Thierry FOURNIER718e2a72015-12-20 20:13:14 +01009774 * "http_process_request" (analyzer flag AN_REQ_HTTP_INNER).
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05009775 * The applet will be immediately initialized, but its before
Thierry FOURNIER718e2a72015-12-20 20:13:14 +01009776 * the call of this analyzer.
9777 */
9778 if (rule->from != ACT_F_HTTP_REQ) {
9779 memprintf(err, "HTTP applets are forbidden from 'tcp-request' rulesets");
9780 return ACT_RET_PRS_ERR;
9781 }
9782
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009783 /* Memory for the rule. */
9784 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
9785 if (!rule->arg.hlua_rule) {
9786 memprintf(err, "out of memory error");
9787 return ACT_RET_PRS_ERR;
9788 }
9789
9790 /* Reference the Lua function and store the reference. */
Thierry Fournierad5345f2020-11-29 02:05:57 +01009791 rule->arg.hlua_rule->fcn = fcn;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009792
9793 /* TODO: later accept arguments. */
9794 rule->arg.hlua_rule->args = NULL;
9795
9796 /* Add applet pointer in the rule. */
9797 rule->applet.obj_type = OBJ_TYPE_APPLET;
9798 rule->applet.name = fcn->name;
9799 rule->applet.init = hlua_applet_http_init;
9800 rule->applet.fct = hlua_applet_http_fct;
9801 rule->applet.release = hlua_applet_http_release;
9802 rule->applet.timeout = hlua_timeout_applet;
9803
9804 return ACT_RET_PRS_OK;
9805}
9806
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009807/* This function is an LUA binding used for registering
9808 * "sample-conv" functions. It expects a converter name used
9809 * in the haproxy configuration file, and an LUA function.
9810 */
9811__LJMP static int hlua_register_action(lua_State *L)
9812{
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009813 struct action_kw_list *akl = NULL;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009814 const char *name;
9815 int ref;
9816 int len;
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009817 struct hlua_function *fcn = NULL;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009818 int nargs;
Thierry Fournierf67442e2020-11-28 20:41:07 +01009819 struct buffer *trash;
9820 struct action_kw *akw;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009821
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009822 /* Initialise the number of expected arguments at 0. */
9823 nargs = 0;
9824
9825 if (lua_gettop(L) < 3 || lua_gettop(L) > 4)
9826 WILL_LJMP(luaL_error(L, "'register_action' needs between 3 and 4 arguments"));
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009827
9828 /* First argument : converter name. */
9829 name = MAY_LJMP(luaL_checkstring(L, 1));
9830
9831 /* Second argument : environment. */
9832 if (lua_type(L, 2) != LUA_TTABLE)
9833 WILL_LJMP(luaL_error(L, "register_action: second argument must be a table of strings"));
9834
9835 /* Third argument : lua function. */
9836 ref = MAY_LJMP(hlua_checkfunction(L, 3));
9837
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08009838 /* Fourth argument : number of mandatory arguments expected on the configuration line. */
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009839 if (lua_gettop(L) >= 4)
9840 nargs = MAY_LJMP(luaL_checkinteger(L, 4));
9841
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08009842 /* browse the second argument as an array. */
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009843 lua_pushnil(L);
9844 while (lua_next(L, 2) != 0) {
9845 if (lua_type(L, -1) != LUA_TSTRING)
9846 WILL_LJMP(luaL_error(L, "register_action: second argument must be a table of strings"));
9847
Thierry Fournierf67442e2020-11-28 20:41:07 +01009848 /* Check if action exists */
9849 trash = get_trash_chunk();
9850 chunk_printf(trash, "lua.%s", name);
9851 if (strcmp(lua_tostring(L, -1), "tcp-req") == 0) {
9852 akw = tcp_req_cont_action(trash->area);
9853 } else if (strcmp(lua_tostring(L, -1), "tcp-res") == 0) {
9854 akw = tcp_res_cont_action(trash->area);
9855 } else if (strcmp(lua_tostring(L, -1), "http-req") == 0) {
9856 akw = action_http_req_custom(trash->area);
9857 } else if (strcmp(lua_tostring(L, -1), "http-res") == 0) {
9858 akw = action_http_res_custom(trash->area);
9859 } else {
9860 akw = NULL;
9861 }
9862 if (akw != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +01009863 fcn = akw->private;
9864 if (fcn->function_ref[hlua_state_id] != -1) {
9865 ha_warning("Trying to register action 'lua.%s' more than once. "
9866 "This will become a hard error in version 2.5.\n", name);
9867 }
9868 fcn->function_ref[hlua_state_id] = ref;
9869
9870 /* pop the environment string. */
9871 lua_pop(L, 1);
9872 continue;
Thierry Fournierf67442e2020-11-28 20:41:07 +01009873 }
9874
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009875 /* Check required environment. Only accepted "http" or "tcp". */
9876 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02009877 akl = calloc(1, sizeof(*akl) + sizeof(struct action_kw) * 2);
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009878 if (!akl)
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009879 goto alloc_error;;
Thierry Fournier62a22aa2020-11-28 21:06:35 +01009880 fcn = new_hlua_function();
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009881 if (!fcn)
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009882 goto alloc_error;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009883
9884 /* Fill fcn. */
9885 fcn->name = strdup(name);
9886 if (!fcn->name)
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009887 goto alloc_error;
Thierry Fournierc7492592020-11-28 23:57:24 +01009888 fcn->function_ref[hlua_state_id] = ref;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009889
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -07009890 /* Set the expected number of arguments. */
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009891 fcn->nargs = nargs;
9892
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009893 /* List head */
9894 akl->list.n = akl->list.p = NULL;
9895
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009896 /* action keyword. */
9897 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02009898 akl->kw[0].kw = calloc(1, len);
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009899 if (!akl->kw[0].kw)
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009900 goto alloc_error;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009901
9902 snprintf((char *)akl->kw[0].kw, len, "lua.%s", name);
9903
Amaury Denoyellee4a617c2021-05-06 15:33:09 +02009904 akl->kw[0].flags = 0;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009905 akl->kw[0].private = fcn;
9906 akl->kw[0].parse = action_register_lua;
9907
9908 /* select the action registering point. */
9909 if (strcmp(lua_tostring(L, -1), "tcp-req") == 0)
9910 tcp_req_cont_keywords_register(akl);
9911 else if (strcmp(lua_tostring(L, -1), "tcp-res") == 0)
9912 tcp_res_cont_keywords_register(akl);
9913 else if (strcmp(lua_tostring(L, -1), "http-req") == 0)
9914 http_req_keywords_register(akl);
9915 else if (strcmp(lua_tostring(L, -1), "http-res") == 0)
9916 http_res_keywords_register(akl);
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009917 else {
9918 release_hlua_function(fcn);
9919 if (akl)
9920 ha_free((char **)&(akl->kw[0].kw));
9921 ha_free(&akl);
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01009922 WILL_LJMP(luaL_error(L, "Lua action environment '%s' is unknown. "
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009923 "'tcp-req', 'tcp-res', 'http-req' or 'http-res' "
9924 "are expected.", lua_tostring(L, -1)));
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009925 }
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009926
9927 /* pop the environment string. */
9928 lua_pop(L, 1);
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009929
9930 /* reset for next loop */
9931 akl = NULL;
9932 fcn = NULL;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009933 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009934 return ACT_RET_PRS_OK;
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009935
9936 alloc_error:
9937 release_hlua_function(fcn);
9938 ha_free(&akl);
9939 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
9940 return 0; /* Never reached */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009941}
9942
9943static enum act_parse_ret action_register_service_tcp(const char **args, int *cur_arg, struct proxy *px,
9944 struct act_rule *rule, char **err)
9945{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02009946 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009947
Christopher Faulet280f85b2019-07-15 15:02:04 +02009948 if (px->mode == PR_MODE_HTTP) {
9949 memprintf(err, "Lua TCP services cannot be used on HTTP proxies");
Christopher Fauletafd8f102018-11-08 11:34:21 +01009950 return ACT_RET_PRS_ERR;
9951 }
9952
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009953 /* Memory for the rule. */
9954 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
9955 if (!rule->arg.hlua_rule) {
9956 memprintf(err, "out of memory error");
9957 return ACT_RET_PRS_ERR;
9958 }
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009959
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009960 /* Reference the Lua function and store the reference. */
Thierry Fournierad5345f2020-11-29 02:05:57 +01009961 rule->arg.hlua_rule->fcn = fcn;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009962
9963 /* TODO: later accept arguments. */
9964 rule->arg.hlua_rule->args = NULL;
9965
9966 /* Add applet pointer in the rule. */
9967 rule->applet.obj_type = OBJ_TYPE_APPLET;
9968 rule->applet.name = fcn->name;
9969 rule->applet.init = hlua_applet_tcp_init;
9970 rule->applet.fct = hlua_applet_tcp_fct;
9971 rule->applet.release = hlua_applet_tcp_release;
9972 rule->applet.timeout = hlua_timeout_applet;
9973
9974 return 0;
9975}
9976
9977/* This function is an LUA binding used for registering
9978 * "sample-conv" functions. It expects a converter name used
9979 * in the haproxy configuration file, and an LUA function.
9980 */
9981__LJMP static int hlua_register_service(lua_State *L)
9982{
9983 struct action_kw_list *akl;
9984 const char *name;
9985 const char *env;
9986 int ref;
9987 int len;
Christopher Faulet5c028d72021-04-12 15:11:44 +02009988 struct hlua_function *fcn = NULL;
Thierry Fournierf67442e2020-11-28 20:41:07 +01009989 struct buffer *trash;
9990 struct action_kw *akw;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009991
9992 MAY_LJMP(check_args(L, 3, "register_service"));
9993
9994 /* First argument : converter name. */
9995 name = MAY_LJMP(luaL_checkstring(L, 1));
9996
9997 /* Second argument : environment. */
9998 env = MAY_LJMP(luaL_checkstring(L, 2));
9999
10000 /* Third argument : lua function. */
10001 ref = MAY_LJMP(hlua_checkfunction(L, 3));
10002
Thierry Fournierf67442e2020-11-28 20:41:07 +010010003 /* Check for service already registered */
10004 trash = get_trash_chunk();
10005 chunk_printf(trash, "lua.%s", name);
10006 akw = service_find(trash->area);
10007 if (akw != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +010010008 fcn = akw->private;
10009 if (fcn->function_ref[hlua_state_id] != -1) {
10010 ha_warning("Trying to register service 'lua.%s' more than once. "
10011 "This will become a hard error in version 2.5.\n", name);
10012 }
10013 fcn->function_ref[hlua_state_id] = ref;
10014 return 0;
Thierry Fournierf67442e2020-11-28 20:41:07 +010010015 }
10016
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010017 /* Allocate and fill the sample fetch keyword struct. */
10018 akl = calloc(1, sizeof(*akl) + sizeof(struct action_kw) * 2);
10019 if (!akl)
Christopher Faulet5c028d72021-04-12 15:11:44 +020010020 goto alloc_error;
Thierry Fournier62a22aa2020-11-28 21:06:35 +010010021 fcn = new_hlua_function();
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010022 if (!fcn)
Christopher Faulet5c028d72021-04-12 15:11:44 +020010023 goto alloc_error;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010024
10025 /* Fill fcn. */
10026 len = strlen("<lua.>") + strlen(name) + 1;
10027 fcn->name = calloc(1, len);
10028 if (!fcn->name)
Christopher Faulet5c028d72021-04-12 15:11:44 +020010029 goto alloc_error;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010030 snprintf((char *)fcn->name, len, "<lua.%s>", name);
Thierry Fournierc7492592020-11-28 23:57:24 +010010031 fcn->function_ref[hlua_state_id] = ref;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010032
10033 /* List head */
10034 akl->list.n = akl->list.p = NULL;
10035
10036 /* converter keyword. */
10037 len = strlen("lua.") + strlen(name) + 1;
10038 akl->kw[0].kw = calloc(1, len);
10039 if (!akl->kw[0].kw)
Christopher Faulet5c028d72021-04-12 15:11:44 +020010040 goto alloc_error;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010041
10042 snprintf((char *)akl->kw[0].kw, len, "lua.%s", name);
10043
Thierry FOURNIER / OZON.IO02564fd2016-11-12 11:07:05 +010010044 /* Check required environment. Only accepted "http" or "tcp". */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010045 if (strcmp(env, "tcp") == 0)
10046 akl->kw[0].parse = action_register_service_tcp;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010047 else if (strcmp(env, "http") == 0)
10048 akl->kw[0].parse = action_register_service_http;
Christopher Faulet5c028d72021-04-12 15:11:44 +020010049 else {
10050 release_hlua_function(fcn);
10051 if (akl)
10052 ha_free((char **)&(akl->kw[0].kw));
10053 ha_free(&akl);
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +010010054 WILL_LJMP(luaL_error(L, "Lua service environment '%s' is unknown. "
Eric Salamafe7456f2017-12-21 14:30:07 +010010055 "'tcp' or 'http' are expected.", env));
Christopher Faulet5c028d72021-04-12 15:11:44 +020010056 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010057
Amaury Denoyellee4a617c2021-05-06 15:33:09 +020010058 akl->kw[0].flags = 0;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010059 akl->kw[0].private = fcn;
10060
10061 /* End of array. */
10062 memset(&akl->kw[1], 0, sizeof(*akl->kw));
10063
10064 /* Register this new converter */
10065 service_keywords_register(akl);
10066
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010067 return 0;
Christopher Faulet5c028d72021-04-12 15:11:44 +020010068
10069 alloc_error:
10070 release_hlua_function(fcn);
10071 ha_free(&akl);
10072 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
10073 return 0; /* Never reached */
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010074}
10075
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010076/* This function initialises Lua cli handler. It copies the
10077 * arguments in the Lua stack and create channel IO objects.
10078 */
Aurélien Nephtaliabbf6072018-04-18 13:26:46 +020010079static int hlua_cli_parse_fct(char **args, char *payload, struct appctx *appctx, void *private)
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010080{
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010081 struct hlua_cli_ctx *ctx = applet_reserve_svcctx(appctx, sizeof(*ctx));
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010082 struct hlua *hlua;
10083 struct hlua_function *fcn;
10084 int i;
10085 const char *error;
10086
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010087 fcn = private;
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010088 ctx->fcn = private;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +010010089
Willy Tarreaubafbe012017-11-24 17:34:44 +010010090 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +010010091 if (!hlua) {
10092 SEND_ERR(NULL, "Lua cli '%s': out of memory.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +010010093 return 1;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +010010094 }
10095 HLUA_INIT(hlua);
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010096 ctx->hlua = hlua;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010097
10098 /* Create task used by signal to wakeup applets.
Ilya Shipitsind4259502020-04-08 01:07:56 +050010099 * We use the same wakeup function than the Lua applet_tcp and
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010100 * applet_http. It is absolutely compatible.
10101 */
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010102 ctx->task = task_new_here();
10103 if (!ctx->task) {
Thierry FOURNIERffbf5692016-12-16 11:14:06 +010010104 SEND_ERR(NULL, "Lua cli '%s': out of memory.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +010010105 goto error;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010106 }
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010107 ctx->task->nice = 0;
10108 ctx->task->context = appctx;
10109 ctx->task->process = hlua_applet_wakeup;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010110
10111 /* Initialises the Lua context */
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010112 if (!hlua_ctx_init(hlua, fcn_ref_to_stack_id(fcn), ctx->task, 0)) {
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010113 SEND_ERR(NULL, "Lua cli '%s': can't initialize Lua context.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +010010114 goto error;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010115 }
10116
10117 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010118 if (!SET_SAFE_LJMP(hlua)) {
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010119 if (lua_type(hlua->T, -1) == LUA_TSTRING)
10120 error = lua_tostring(hlua->T, -1);
10121 else
10122 error = "critical error";
10123 SEND_ERR(NULL, "Lua cli '%s': %s.\n", fcn->name, error);
10124 goto error;
10125 }
10126
10127 /* Check stack available size. */
10128 if (!lua_checkstack(hlua->T, 2)) {
10129 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
10130 goto error;
10131 }
10132
10133 /* Restore the function in the stack. */
Thierry Fournierc7492592020-11-28 23:57:24 +010010134 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, fcn->function_ref[hlua->state_id]);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010135
10136 /* Once the arguments parsed, the CLI is like an AppletTCP,
10137 * so push AppletTCP in the stack.
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010138 */
10139 if (!hlua_applet_tcp_new(hlua->T, appctx)) {
10140 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
10141 goto error;
10142 }
10143 hlua->nargs = 1;
10144
10145 /* push keywords in the stack. */
10146 for (i = 0; *args[i]; i++) {
10147 /* Check stack available size. */
10148 if (!lua_checkstack(hlua->T, 1)) {
10149 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
10150 goto error;
10151 }
10152 lua_pushstring(hlua->T, args[i]);
10153 hlua->nargs++;
10154 }
10155
10156 /* We must initialize the execution timeouts. */
10157 hlua->max_time = hlua_timeout_session;
10158
10159 /* At this point the execution is safe. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010160 RESET_SAFE_LJMP(hlua);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010161
10162 /* It's ok */
10163 return 0;
10164
10165 /* It's not ok. */
10166error:
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010167 RESET_SAFE_LJMP(hlua);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010168 hlua_ctx_destroy(hlua);
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010169 ctx->hlua = NULL;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010170 return 1;
10171}
10172
10173static int hlua_cli_io_handler_fct(struct appctx *appctx)
10174{
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010175 struct hlua_cli_ctx *ctx = appctx->svcctx;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010176 struct hlua *hlua;
Willy Tarreau475e4632022-05-27 10:26:46 +020010177 struct stconn *sc;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010178 struct hlua_function *fcn;
10179
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010180 hlua = ctx->hlua;
Willy Tarreauc12b3212022-05-27 11:08:15 +020010181 sc = appctx_sc(appctx);
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010182 fcn = ctx->fcn;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010183
10184 /* If the stream is disconnect or closed, ldo nothing. */
Willy Tarreau475e4632022-05-27 10:26:46 +020010185 if (unlikely(sc->state == SC_ST_DIS || sc->state == SC_ST_CLO))
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010186 return 1;
10187
10188 /* Execute the function. */
10189 switch (hlua_ctx_resume(hlua, 1)) {
10190
10191 /* finished. */
10192 case HLUA_E_OK:
10193 return 1;
10194
10195 /* yield. */
10196 case HLUA_E_AGAIN:
10197 /* We want write. */
10198 if (HLUA_IS_WAKERESWR(hlua))
Willy Tarreau475e4632022-05-27 10:26:46 +020010199 sc_need_room(sc);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010200 /* Set the timeout. */
10201 if (hlua->wake_time != TICK_ETERNITY)
10202 task_schedule(hlua->task, hlua->wake_time);
10203 return 0;
10204
10205 /* finished with error. */
10206 case HLUA_E_ERRMSG:
10207 /* Display log. */
10208 SEND_ERR(NULL, "Lua cli '%s': %s.\n",
10209 fcn->name, lua_tostring(hlua->T, -1));
10210 lua_pop(hlua->T, 1);
10211 return 1;
10212
Thierry Fournierd5b073c2018-05-21 19:42:47 +020010213 case HLUA_E_ETMOUT:
10214 SEND_ERR(NULL, "Lua converter '%s': execution timeout.\n",
10215 fcn->name);
10216 return 1;
10217
10218 case HLUA_E_NOMEM:
10219 SEND_ERR(NULL, "Lua converter '%s': out of memory error.\n",
10220 fcn->name);
10221 return 1;
10222
10223 case HLUA_E_YIELD: /* unexpected */
10224 SEND_ERR(NULL, "Lua converter '%s': yield not allowed.\n",
10225 fcn->name);
10226 return 1;
10227
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010228 case HLUA_E_ERR:
10229 /* Display log. */
10230 SEND_ERR(NULL, "Lua cli '%s' return an unknown error.\n",
10231 fcn->name);
10232 return 1;
10233
10234 default:
10235 return 1;
10236 }
10237
10238 return 1;
10239}
10240
10241static void hlua_cli_io_release_fct(struct appctx *appctx)
10242{
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010243 struct hlua_cli_ctx *ctx = appctx->svcctx;
10244
10245 hlua_ctx_destroy(ctx->hlua);
10246 ctx->hlua = NULL;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010247}
10248
10249/* This function is an LUA binding used for registering
10250 * new keywords in the cli. It expects a list of keywords
10251 * which are the "path". It is limited to 5 keywords. A
10252 * description of the command, a function to be executed
10253 * for the parsing and a function for io handlers.
10254 */
10255__LJMP static int hlua_register_cli(lua_State *L)
10256{
10257 struct cli_kw_list *cli_kws;
10258 const char *message;
10259 int ref_io;
10260 int len;
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010261 struct hlua_function *fcn = NULL;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010262 int index;
10263 int i;
Thierry Fournierf67442e2020-11-28 20:41:07 +010010264 struct buffer *trash;
10265 const char *kw[5];
10266 struct cli_kw *cli_kw;
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010267 const char *errmsg;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010268
10269 MAY_LJMP(check_args(L, 3, "register_cli"));
10270
10271 /* First argument : an array of maximum 5 keywords. */
10272 if (!lua_istable(L, 1))
10273 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table"));
10274
10275 /* Second argument : string with contextual message. */
10276 message = MAY_LJMP(luaL_checkstring(L, 2));
10277
10278 /* Third and fourth argument : lua function. */
10279 ref_io = MAY_LJMP(hlua_checkfunction(L, 3));
10280
Thierry Fournierf67442e2020-11-28 20:41:07 +010010281 /* Check for CLI service already registered */
10282 trash = get_trash_chunk();
10283 index = 0;
10284 lua_pushnil(L);
10285 memset(kw, 0, sizeof(kw));
10286 while (lua_next(L, 1) != 0) {
10287 if (index >= CLI_PREFIX_KW_NB)
10288 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table with a maximum of 5 entries"));
10289 if (lua_type(L, -1) != LUA_TSTRING)
10290 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table filled with strings"));
10291 kw[index] = lua_tostring(L, -1);
10292 if (index == 0)
10293 chunk_printf(trash, "%s", kw[index]);
10294 else
10295 chunk_appendf(trash, " %s", kw[index]);
10296 index++;
10297 lua_pop(L, 1);
10298 }
10299 cli_kw = cli_find_kw_exact((char **)kw);
10300 if (cli_kw != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +010010301 fcn = cli_kw->private;
10302 if (fcn->function_ref[hlua_state_id] != -1) {
10303 ha_warning("Trying to register CLI keyword 'lua.%s' more than once. "
10304 "This will become a hard error in version 2.5.\n", trash->area);
10305 }
10306 fcn->function_ref[hlua_state_id] = ref_io;
10307 return 0;
Thierry Fournierf67442e2020-11-28 20:41:07 +010010308 }
10309
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010310 /* Allocate and fill the sample fetch keyword struct. */
10311 cli_kws = calloc(1, sizeof(*cli_kws) + sizeof(struct cli_kw) * 2);
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010312 if (!cli_kws) {
10313 errmsg = "Lua out of memory error.";
10314 goto error;
10315 }
Thierry Fournier62a22aa2020-11-28 21:06:35 +010010316 fcn = new_hlua_function();
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010317 if (!fcn) {
10318 errmsg = "Lua out of memory error.";
10319 goto error;
10320 }
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010321
10322 /* Fill path. */
10323 index = 0;
10324 lua_pushnil(L);
10325 while(lua_next(L, 1) != 0) {
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010326 if (index >= 5) {
10327 errmsg = "1st argument must be a table with a maximum of 5 entries";
10328 goto error;
10329 }
10330 if (lua_type(L, -1) != LUA_TSTRING) {
10331 errmsg = "1st argument must be a table filled with strings";
10332 goto error;
10333 }
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010334 cli_kws->kw[0].str_kw[index] = strdup(lua_tostring(L, -1));
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010335 if (!cli_kws->kw[0].str_kw[index]) {
10336 errmsg = "Lua out of memory error.";
10337 goto error;
10338 }
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010339 index++;
10340 lua_pop(L, 1);
10341 }
10342
10343 /* Copy help message. */
10344 cli_kws->kw[0].usage = strdup(message);
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010345 if (!cli_kws->kw[0].usage) {
10346 errmsg = "Lua out of memory error.";
10347 goto error;
10348 }
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010349
10350 /* Fill fcn io handler. */
10351 len = strlen("<lua.cli>") + 1;
10352 for (i = 0; i < index; i++)
10353 len += strlen(cli_kws->kw[0].str_kw[i]) + 1;
10354 fcn->name = calloc(1, len);
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010355 if (!fcn->name) {
10356 errmsg = "Lua out of memory error.";
10357 goto error;
10358 }
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010359 strncat((char *)fcn->name, "<lua.cli", len);
10360 for (i = 0; i < index; i++) {
10361 strncat((char *)fcn->name, ".", len);
10362 strncat((char *)fcn->name, cli_kws->kw[0].str_kw[i], len);
10363 }
10364 strncat((char *)fcn->name, ">", len);
Thierry Fournierc7492592020-11-28 23:57:24 +010010365 fcn->function_ref[hlua_state_id] = ref_io;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010366
10367 /* Fill last entries. */
10368 cli_kws->kw[0].private = fcn;
10369 cli_kws->kw[0].parse = hlua_cli_parse_fct;
10370 cli_kws->kw[0].io_handler = hlua_cli_io_handler_fct;
10371 cli_kws->kw[0].io_release = hlua_cli_io_release_fct;
10372
10373 /* Register this new converter */
10374 cli_register_kw(cli_kws);
10375
10376 return 0;
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010377
10378 error:
10379 release_hlua_function(fcn);
10380 if (cli_kws) {
10381 for (i = 0; i < index; i++)
10382 ha_free((char **)&(cli_kws->kw[0].str_kw[i]));
10383 ha_free((char **)&(cli_kws->kw[0].usage));
10384 }
10385 ha_free(&cli_kws);
10386 WILL_LJMP(luaL_error(L, errmsg));
10387 return 0; /* Never reached */
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010388}
10389
Christopher Faulet69c581a2021-05-31 08:54:04 +020010390static int hlua_filter_init_per_thread(struct proxy *px, struct flt_conf *fconf)
10391{
10392 struct hlua_flt_config *conf = fconf->conf;
10393 lua_State *L;
10394 int error, pos, state_id, flt_ref;
10395
10396 state_id = reg_flt_to_stack_id(conf->reg);
10397 L = hlua_states[state_id];
10398 pos = lua_gettop(L);
10399
10400 /* The filter parsing function */
10401 lua_rawgeti(L, LUA_REGISTRYINDEX, conf->reg->fun_ref[state_id]);
10402
10403 /* Push the filter class on the stack and resolve all callbacks */
10404 lua_rawgeti(L, LUA_REGISTRYINDEX, conf->reg->flt_ref[state_id]);
10405
10406 /* Duplicate the filter class so each filter will have its own copy */
10407 lua_newtable(L);
10408 lua_pushnil(L);
10409
10410 while (lua_next(L, pos+2)) {
10411 lua_pushvalue(L, -2);
10412 lua_insert(L, -2);
10413 lua_settable(L, -4);
10414 }
10415 flt_ref = luaL_ref(L, LUA_REGISTRYINDEX);
10416
10417 /* Remove the original lua filter class from the stack */
10418 lua_pop(L, 1);
10419
10420 /* Push the copy on the stack */
10421 lua_rawgeti(L, LUA_REGISTRYINDEX, flt_ref);
10422
10423 /* extra args are pushed in a table */
10424 lua_newtable(L);
10425 for (pos = 0; conf->args[pos]; pos++) {
10426 /* Check stack available size. */
10427 if (!lua_checkstack(L, 1)) {
10428 ha_alert("Lua filter '%s' : Lua error : full stack.", conf->reg->name);
10429 goto error;
10430 }
10431 lua_pushstring(L, conf->args[pos]);
10432 lua_rawseti(L, -2, lua_rawlen(L, -2) + 1);
10433 }
10434
10435 error = lua_pcall(L, 2, LUA_MULTRET, 0);
10436 switch (error) {
10437 case LUA_OK:
10438 /* replace the filter ref */
10439 conf->ref[state_id] = flt_ref;
10440 break;
10441 case LUA_ERRRUN:
10442 ha_alert("Lua filter '%s' : runtime error : %s", conf->reg->name, lua_tostring(L, -1));
10443 goto error;
10444 case LUA_ERRMEM:
10445 ha_alert("Lua filter '%s' : out of memory error", conf->reg->name);
10446 goto error;
10447 case LUA_ERRERR:
10448 ha_alert("Lua filter '%s' : message handler error : %s", conf->reg->name, lua_tostring(L, -1));
10449 goto error;
10450#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM <= 503
10451 case LUA_ERRGCMM:
10452 ha_alert("Lua filter '%s' : garbage collector error : %s", conf->reg->name, lua_tostring(L, -1));
10453 goto error;
10454#endif
10455 default:
Ilya Shipitsinff0f2782021-08-22 22:18:07 +050010456 ha_alert("Lua filter '%s' : unknown error : %s", conf->reg->name, lua_tostring(L, -1));
Christopher Faulet69c581a2021-05-31 08:54:04 +020010457 goto error;
10458 }
10459
10460 lua_settop(L, 0);
10461 return 0;
10462
10463 error:
10464 lua_settop(L, 0);
10465 return -1;
10466}
10467
10468static void hlua_filter_deinit_per_thread(struct proxy *px, struct flt_conf *fconf)
10469{
10470 struct hlua_flt_config *conf = fconf->conf;
10471 lua_State *L;
10472 int state_id;
10473
10474 if (!conf)
10475 return;
10476
10477 state_id = reg_flt_to_stack_id(conf->reg);
10478 L = hlua_states[state_id];
10479 luaL_unref(L, LUA_REGISTRYINDEX, conf->ref[state_id]);
10480}
10481
10482static int hlua_filter_init(struct proxy *px, struct flt_conf *fconf)
10483{
10484 struct hlua_flt_config *conf = fconf->conf;
10485 int state_id = reg_flt_to_stack_id(conf->reg);
10486
10487 /* Rely on per-thread init for global scripts */
10488 if (!state_id)
10489 return hlua_filter_init_per_thread(px, fconf);
10490 return 0;
10491}
10492
10493static void hlua_filter_deinit(struct proxy *px, struct flt_conf *fconf)
10494{
10495
10496 if (fconf->conf) {
10497 struct hlua_flt_config *conf = fconf->conf;
10498 int state_id = reg_flt_to_stack_id(conf->reg);
10499 int pos;
10500
10501 /* Rely on per-thread deinit for global scripts */
10502 if (!state_id)
10503 hlua_filter_deinit_per_thread(px, fconf);
10504
10505 for (pos = 0; conf->args[pos]; pos++)
10506 free(conf->args[pos]);
10507 free(conf->args);
10508 }
10509 ha_free(&fconf->conf);
10510 ha_free((char **)&fconf->id);
10511 ha_free(&fconf->ops);
10512}
10513
10514static int hlua_filter_new(struct stream *s, struct filter *filter)
10515{
10516 struct hlua_flt_config *conf = FLT_CONF(filter);
10517 struct hlua_flt_ctx *flt_ctx = NULL;
10518 int ret = 1;
10519
10520 /* In the execution wrappers linked with a stream, the
10521 * Lua context can be not initialized. This behavior
10522 * permits to save performances because a systematic
10523 * Lua initialization cause 5% performances loss.
10524 */
10525 if (!s->hlua) {
10526 struct hlua *hlua;
10527
10528 hlua = pool_alloc(pool_head_hlua);
10529 if (!hlua) {
10530 SEND_ERR(s->be, "Lua filter '%s': can't initialize Lua context.\n",
10531 conf->reg->name);
10532 ret = 0;
10533 goto end;
10534 }
10535 HLUA_INIT(hlua);
10536 s->hlua = hlua;
10537 if (!hlua_ctx_init(s->hlua, reg_flt_to_stack_id(conf->reg), s->task, 0)) {
10538 SEND_ERR(s->be, "Lua filter '%s': can't initialize Lua context.\n",
10539 conf->reg->name);
10540 ret = 0;
10541 goto end;
10542 }
10543 }
10544
10545 flt_ctx = pool_zalloc(pool_head_hlua_flt_ctx);
10546 if (!flt_ctx) {
10547 SEND_ERR(s->be, "Lua filter '%s': can't initialize filter Lua context.\n",
10548 conf->reg->name);
10549 ret = 0;
10550 goto end;
10551 }
10552 flt_ctx->hlua[0] = pool_alloc(pool_head_hlua);
10553 flt_ctx->hlua[1] = pool_alloc(pool_head_hlua);
10554 if (!flt_ctx->hlua[0] || !flt_ctx->hlua[1]) {
10555 SEND_ERR(s->be, "Lua filter '%s': can't initialize filter Lua context.\n",
10556 conf->reg->name);
10557 ret = 0;
10558 goto end;
10559 }
10560 HLUA_INIT(flt_ctx->hlua[0]);
10561 HLUA_INIT(flt_ctx->hlua[1]);
10562 if (!hlua_ctx_init(flt_ctx->hlua[0], reg_flt_to_stack_id(conf->reg), s->task, 0) ||
10563 !hlua_ctx_init(flt_ctx->hlua[1], reg_flt_to_stack_id(conf->reg), s->task, 0)) {
10564 SEND_ERR(s->be, "Lua filter '%s': can't initialize filter Lua context.\n",
10565 conf->reg->name);
10566 ret = 0;
10567 goto end;
10568 }
10569
10570 if (!HLUA_IS_RUNNING(s->hlua)) {
10571 /* The following Lua calls can fail. */
10572 if (!SET_SAFE_LJMP(s->hlua)) {
10573 const char *error;
10574
10575 if (lua_type(s->hlua->T, -1) == LUA_TSTRING)
10576 error = lua_tostring(s->hlua->T, -1);
10577 else
10578 error = "critical error";
10579 SEND_ERR(s->be, "Lua filter '%s': %s.\n", conf->reg->name, error);
10580 ret = 0;
10581 goto end;
10582 }
10583
10584 /* Check stack size. */
10585 if (!lua_checkstack(s->hlua->T, 1)) {
10586 SEND_ERR(s->be, "Lua filter '%s': full stack.\n", conf->reg->name);
Tim Duesterhus22817382021-09-11 23:17:25 +020010587 RESET_SAFE_LJMP(s->hlua);
Christopher Faulet69c581a2021-05-31 08:54:04 +020010588 ret = 0;
10589 goto end;
10590 }
10591
10592 lua_rawgeti(s->hlua->T, LUA_REGISTRYINDEX, conf->ref[s->hlua->state_id]);
10593 if (lua_getfield(s->hlua->T, -1, "new") != LUA_TFUNCTION) {
10594 SEND_ERR(s->be, "Lua filter '%s': 'new' field is not a function.\n",
10595 conf->reg->name);
10596 RESET_SAFE_LJMP(s->hlua);
10597 ret = 0;
10598 goto end;
10599 }
10600 lua_insert(s->hlua->T, -2);
10601
10602 /* Push the copy on the stack */
10603 s->hlua->nargs = 1;
10604
10605 /* We must initialize the execution timeouts. */
10606 s->hlua->max_time = hlua_timeout_session;
10607
10608 /* At this point the execution is safe. */
10609 RESET_SAFE_LJMP(s->hlua);
10610 }
10611
10612 switch (hlua_ctx_resume(s->hlua, 0)) {
10613 case HLUA_E_OK:
10614 /* Nothing returned or not a table, ignore the filter for current stream */
10615 if (!lua_gettop(s->hlua->T) || !lua_istable(s->hlua->T, 1)) {
10616 ret = 0;
10617 goto end;
10618 }
10619
10620 /* Attached the filter pointer to the ctx */
10621 lua_pushstring(s->hlua->T, "__filter");
10622 lua_pushlightuserdata(s->hlua->T, filter);
10623 lua_settable(s->hlua->T, -3);
10624
10625 /* Save a ref on the filter ctx */
10626 lua_pushvalue(s->hlua->T, 1);
10627 flt_ctx->ref = luaL_ref(s->hlua->T, LUA_REGISTRYINDEX);
10628 filter->ctx = flt_ctx;
10629 break;
10630 case HLUA_E_ERRMSG:
10631 SEND_ERR(s->be, "Lua filter '%s' : %s.\n", conf->reg->name, lua_tostring(s->hlua->T, -1));
10632 ret = -1;
10633 goto end;
10634 case HLUA_E_ETMOUT:
10635 SEND_ERR(s->be, "Lua filter '%s' : 'new' execution timeout.\n", conf->reg->name);
10636 ret = 0;
10637 goto end;
10638 case HLUA_E_NOMEM:
10639 SEND_ERR(s->be, "Lua filter '%s' : out of memory error.\n", conf->reg->name);
10640 ret = 0;
10641 goto end;
10642 case HLUA_E_AGAIN:
10643 case HLUA_E_YIELD:
10644 SEND_ERR(s->be, "Lua filter '%s': yield functions like core.tcp() or core.sleep()"
10645 " are not allowed from 'new' function.\n", conf->reg->name);
10646 ret = 0;
10647 goto end;
10648 case HLUA_E_ERR:
10649 SEND_ERR(s->be, "Lua filter '%s': 'new' returns an unknown error.\n", conf->reg->name);
10650 ret = 0;
10651 goto end;
10652 default:
10653 ret = 0;
10654 goto end;
10655 }
10656
10657 end:
10658 if (s->hlua)
10659 lua_settop(s->hlua->T, 0);
10660 if (ret <= 0) {
10661 if (flt_ctx) {
10662 hlua_ctx_destroy(flt_ctx->hlua[0]);
10663 hlua_ctx_destroy(flt_ctx->hlua[1]);
10664 pool_free(pool_head_hlua_flt_ctx, flt_ctx);
10665 }
10666 }
10667 return ret;
10668}
10669
10670static void hlua_filter_delete(struct stream *s, struct filter *filter)
10671{
10672 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10673
10674 luaL_unref(s->hlua->T, LUA_REGISTRYINDEX, flt_ctx->ref);
10675 hlua_ctx_destroy(flt_ctx->hlua[0]);
10676 hlua_ctx_destroy(flt_ctx->hlua[1]);
10677 pool_free(pool_head_hlua_flt_ctx, flt_ctx);
10678 filter->ctx = NULL;
10679}
10680
Christopher Faulet9f55a502020-02-25 15:21:02 +010010681static int hlua_filter_from_payload(struct filter *filter)
10682{
10683 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10684
10685 return (flt_ctx && !!(flt_ctx->flags & HLUA_FLT_CTX_FL_PAYLOAD));
10686}
10687
Christopher Fauletc404f112020-02-26 15:03:09 +010010688static int hlua_filter_callback(struct stream *s, struct filter *filter, const char *fun,
10689 int dir, unsigned int flags)
10690{
10691 struct hlua *flt_hlua;
10692 struct hlua_flt_config *conf = FLT_CONF(filter);
10693 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10694 unsigned int hflags = HLUA_TXN_FLT_CTX;
10695 int ret = 1;
10696
10697 flt_hlua = flt_ctx->hlua[(dir == SMP_OPT_DIR_REQ ? 0 : 1)];
10698 if (!flt_hlua)
10699 goto end;
10700
10701 if (!HLUA_IS_RUNNING(flt_hlua)) {
10702 int extra_idx = lua_gettop(flt_hlua->T);
10703
10704 /* The following Lua calls can fail. */
10705 if (!SET_SAFE_LJMP(flt_hlua)) {
10706 const char *error;
10707
10708 if (lua_type(flt_hlua->T, -1) == LUA_TSTRING)
10709 error = lua_tostring(flt_hlua->T, -1);
10710 else
10711 error = "critical error";
10712 SEND_ERR(s->be, "Lua filter '%s': %s.\n", conf->reg->name, error);
10713 goto end;
10714 }
10715
10716 /* Check stack size. */
10717 if (!lua_checkstack(flt_hlua->T, 3)) {
10718 SEND_ERR(s->be, "Lua filter '%s': full stack.\n", conf->reg->name);
10719 RESET_SAFE_LJMP(flt_hlua);
10720 goto end;
10721 }
10722
10723 lua_rawgeti(flt_hlua->T, LUA_REGISTRYINDEX, flt_ctx->ref);
10724 if (lua_getfield(flt_hlua->T, -1, fun) != LUA_TFUNCTION) {
10725 RESET_SAFE_LJMP(flt_hlua);
10726 goto end;
10727 }
10728 lua_insert(flt_hlua->T, -2);
10729
10730 if (!hlua_txn_new(flt_hlua->T, s, s->be, dir, hflags)) {
10731 SEND_ERR(s->be, "Lua filter '%s': full stack.\n", conf->reg->name);
10732 RESET_SAFE_LJMP(flt_hlua);
10733 goto end;
10734 }
10735 flt_hlua->nargs = 2;
10736
10737 if (flags & HLUA_FLT_CB_ARG_CHN) {
10738 if (dir == SMP_OPT_DIR_REQ)
10739 lua_getfield(flt_hlua->T, -1, "req");
10740 else
10741 lua_getfield(flt_hlua->T, -1, "res");
10742 if (lua_type(flt_hlua->T, -1) == LUA_TTABLE) {
10743 lua_pushstring(flt_hlua->T, "__filter");
10744 lua_pushlightuserdata(flt_hlua->T, filter);
10745 lua_settable(flt_hlua->T, -3);
10746 }
10747 flt_hlua->nargs++;
10748 }
10749 else if (flags & HLUA_FLT_CB_ARG_HTTP_MSG) {
Christopher Fauleteae8afa2020-02-26 17:15:48 +010010750 if (dir == SMP_OPT_DIR_REQ)
10751 lua_getfield(flt_hlua->T, -1, "http_req");
10752 else
10753 lua_getfield(flt_hlua->T, -1, "http_res");
10754 if (lua_type(flt_hlua->T, -1) == LUA_TTABLE) {
10755 lua_pushstring(flt_hlua->T, "__filter");
10756 lua_pushlightuserdata(flt_hlua->T, filter);
10757 lua_settable(flt_hlua->T, -3);
10758 }
10759 flt_hlua->nargs++;
Christopher Fauletc404f112020-02-26 15:03:09 +010010760 }
10761
10762 /* Check stack size. */
10763 if (!lua_checkstack(flt_hlua->T, 1)) {
10764 SEND_ERR(s->be, "Lua filter '%s': full stack.\n", conf->reg->name);
10765 RESET_SAFE_LJMP(flt_hlua);
10766 goto end;
10767 }
10768
10769 while (extra_idx--) {
10770 lua_pushvalue(flt_hlua->T, 1);
10771 lua_remove(flt_hlua->T, 1);
10772 flt_hlua->nargs++;
10773 }
10774
10775 /* We must initialize the execution timeouts. */
10776 flt_hlua->max_time = hlua_timeout_session;
10777
10778 /* At this point the execution is safe. */
10779 RESET_SAFE_LJMP(flt_hlua);
10780 }
10781
10782 switch (hlua_ctx_resume(flt_hlua, !(flags & HLUA_FLT_CB_FINAL))) {
10783 case HLUA_E_OK:
10784 /* Catch the return value if it required */
10785 if ((flags & HLUA_FLT_CB_RETVAL) && lua_gettop(flt_hlua->T) > 0) {
10786 ret = lua_tointeger(flt_hlua->T, -1);
10787 lua_settop(flt_hlua->T, 0); /* Empty the stack. */
10788 }
10789
10790 /* Set timeout in the required channel. */
10791 if (flt_hlua->wake_time != TICK_ETERNITY) {
10792 if (dir == SMP_OPT_DIR_REQ)
10793 s->req.analyse_exp = flt_hlua->wake_time;
10794 else
10795 s->res.analyse_exp = flt_hlua->wake_time;
10796 }
10797 break;
10798 case HLUA_E_AGAIN:
10799 /* Set timeout in the required channel. */
10800 if (flt_hlua->wake_time != TICK_ETERNITY) {
10801 if (dir == SMP_OPT_DIR_REQ)
10802 s->req.analyse_exp = flt_hlua->wake_time;
10803 else
10804 s->res.analyse_exp = flt_hlua->wake_time;
10805 }
10806 /* Some actions can be wake up when a "write" event
10807 * is detected on a response channel. This is useful
10808 * only for actions targeted on the requests.
10809 */
10810 if (HLUA_IS_WAKERESWR(flt_hlua))
10811 s->res.flags |= CF_WAKE_WRITE;
10812 if (HLUA_IS_WAKEREQWR(flt_hlua))
10813 s->req.flags |= CF_WAKE_WRITE;
10814 ret = 0;
10815 goto end;
10816 case HLUA_E_ERRMSG:
10817 SEND_ERR(s->be, "Lua filter '%s' : %s.\n", conf->reg->name, lua_tostring(flt_hlua->T, -1));
10818 ret = -1;
10819 goto end;
10820 case HLUA_E_ETMOUT:
10821 SEND_ERR(s->be, "Lua filter '%s' : '%s' callback execution timeout.\n", conf->reg->name, fun);
10822 goto end;
10823 case HLUA_E_NOMEM:
10824 SEND_ERR(s->be, "Lua filter '%s' : out of memory error.\n", conf->reg->name);
10825 goto end;
10826 case HLUA_E_YIELD:
10827 SEND_ERR(s->be, "Lua filter '%s': yield functions like core.tcp() or core.sleep()"
10828 " are not allowed from '%s' callback.\n", conf->reg->name, fun);
10829 goto end;
10830 case HLUA_E_ERR:
10831 SEND_ERR(s->be, "Lua filter '%s': '%s' returns an unknown error.\n", conf->reg->name, fun);
10832 goto end;
10833 default:
10834 goto end;
10835 }
10836
10837
10838 end:
10839 return ret;
10840}
10841
10842static int hlua_filter_start_analyze(struct stream *s, struct filter *filter, struct channel *chn)
10843{
10844 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10845
10846 flt_ctx->flags = 0;
10847 return hlua_filter_callback(s, filter, "start_analyze",
10848 (!(chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES),
10849 (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_RETVAL | HLUA_FLT_CB_ARG_CHN));
10850}
10851
10852static int hlua_filter_end_analyze(struct stream *s, struct filter *filter, struct channel *chn)
10853{
10854 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10855
10856 flt_ctx->flags &= ~HLUA_FLT_CTX_FL_PAYLOAD;
10857 return hlua_filter_callback(s, filter, "end_analyze",
10858 (!(chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES),
10859 (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_RETVAL | HLUA_FLT_CB_ARG_CHN));
10860}
10861
Christopher Fauleteae8afa2020-02-26 17:15:48 +010010862static int hlua_filter_http_headers(struct stream *s, struct filter *filter, struct http_msg *msg)
10863{
10864 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10865
10866 flt_ctx->flags &= ~HLUA_FLT_CTX_FL_PAYLOAD;
10867 return hlua_filter_callback(s, filter, "http_headers",
10868 (!(msg->chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES),
10869 (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_RETVAL | HLUA_FLT_CB_ARG_HTTP_MSG));
10870}
10871
10872static int hlua_filter_http_payload(struct stream *s, struct filter *filter, struct http_msg *msg,
10873 unsigned int offset, unsigned int len)
10874{
10875 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10876 struct hlua *flt_hlua;
10877 int dir = (!(msg->chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES);
10878 int idx = (dir == SMP_OPT_DIR_REQ ? 0 : 1);
10879 int ret;
10880
10881 flt_hlua = flt_ctx->hlua[idx];
10882 flt_ctx->cur_off[idx] = offset;
10883 flt_ctx->cur_len[idx] = len;
10884 flt_ctx->flags |= HLUA_FLT_CTX_FL_PAYLOAD;
10885 ret = hlua_filter_callback(s, filter, "http_payload", dir, (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_ARG_HTTP_MSG));
10886 if (ret != -1) {
10887 ret = flt_ctx->cur_len[idx];
10888 if (lua_gettop(flt_hlua->T) > 0) {
10889 ret = lua_tointeger(flt_hlua->T, -1);
10890 if (ret > flt_ctx->cur_len[idx])
10891 ret = flt_ctx->cur_len[idx];
10892 lua_settop(flt_hlua->T, 0); /* Empty the stack. */
10893 }
10894 }
10895 return ret;
10896}
10897
10898static int hlua_filter_http_end(struct stream *s, struct filter *filter, struct http_msg *msg)
10899{
10900 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10901
10902 flt_ctx->flags &= ~HLUA_FLT_CTX_FL_PAYLOAD;
10903 return hlua_filter_callback(s, filter, "http_end",
10904 (!(msg->chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES),
10905 (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_RETVAL | HLUA_FLT_CB_ARG_HTTP_MSG));
10906}
10907
Christopher Fauletc404f112020-02-26 15:03:09 +010010908static int hlua_filter_tcp_payload(struct stream *s, struct filter *filter, struct channel *chn,
10909 unsigned int offset, unsigned int len)
10910{
10911 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10912 struct hlua *flt_hlua;
10913 int dir = (!(chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES);
10914 int idx = (dir == SMP_OPT_DIR_REQ ? 0 : 1);
10915 int ret;
10916
10917 flt_hlua = flt_ctx->hlua[idx];
10918 flt_ctx->cur_off[idx] = offset;
10919 flt_ctx->cur_len[idx] = len;
10920 flt_ctx->flags |= HLUA_FLT_CTX_FL_PAYLOAD;
10921 ret = hlua_filter_callback(s, filter, "tcp_payload", dir, (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_ARG_CHN));
10922 if (ret != -1) {
10923 ret = flt_ctx->cur_len[idx];
10924 if (lua_gettop(flt_hlua->T) > 0) {
10925 ret = lua_tointeger(flt_hlua->T, -1);
10926 if (ret > flt_ctx->cur_len[idx])
10927 ret = flt_ctx->cur_len[idx];
10928 lua_settop(flt_hlua->T, 0); /* Empty the stack. */
10929 }
10930 }
10931 return ret;
10932}
10933
Christopher Faulet69c581a2021-05-31 08:54:04 +020010934static int hlua_filter_parse_fct(char **args, int *cur_arg, struct proxy *px,
10935 struct flt_conf *fconf, char **err, void *private)
10936{
10937 struct hlua_reg_filter *reg_flt = private;
10938 lua_State *L;
10939 struct hlua_flt_config *conf = NULL;
10940 const char *flt_id = NULL;
10941 int state_id, pos, flt_flags = 0;
10942 struct flt_ops *hlua_flt_ops = NULL;
10943
10944 state_id = reg_flt_to_stack_id(reg_flt);
10945 L = hlua_states[state_id];
10946
10947 /* Initialize the filter ops with default callbacks */
10948 hlua_flt_ops = calloc(1, sizeof(*hlua_flt_ops));
Christopher Fauletc86bb872021-08-13 08:33:57 +020010949 if (!hlua_flt_ops)
10950 goto error;
Christopher Faulet69c581a2021-05-31 08:54:04 +020010951 hlua_flt_ops->init = hlua_filter_init;
10952 hlua_flt_ops->deinit = hlua_filter_deinit;
10953 if (state_id) {
10954 /* Set per-thread callback if script is loaded per-thread */
10955 hlua_flt_ops->init_per_thread = hlua_filter_init_per_thread;
10956 hlua_flt_ops->deinit_per_thread = hlua_filter_deinit_per_thread;
10957 }
10958 hlua_flt_ops->attach = hlua_filter_new;
10959 hlua_flt_ops->detach = hlua_filter_delete;
10960
10961 /* Push the filter class on the stack and resolve all callbacks */
10962 lua_rawgeti(L, LUA_REGISTRYINDEX, reg_flt->flt_ref[state_id]);
10963
Christopher Fauletc404f112020-02-26 15:03:09 +010010964 if (lua_getfield(L, -1, "start_analyze") == LUA_TFUNCTION)
10965 hlua_flt_ops->channel_start_analyze = hlua_filter_start_analyze;
10966 lua_pop(L, 1);
10967 if (lua_getfield(L, -1, "end_analyze") == LUA_TFUNCTION)
10968 hlua_flt_ops->channel_end_analyze = hlua_filter_end_analyze;
10969 lua_pop(L, 1);
Christopher Fauleteae8afa2020-02-26 17:15:48 +010010970 if (lua_getfield(L, -1, "http_headers") == LUA_TFUNCTION)
10971 hlua_flt_ops->http_headers = hlua_filter_http_headers;
10972 lua_pop(L, 1);
10973 if (lua_getfield(L, -1, "http_payload") == LUA_TFUNCTION)
10974 hlua_flt_ops->http_payload = hlua_filter_http_payload;
10975 lua_pop(L, 1);
10976 if (lua_getfield(L, -1, "http_end") == LUA_TFUNCTION)
10977 hlua_flt_ops->http_end = hlua_filter_http_end;
10978 lua_pop(L, 1);
Christopher Fauletc404f112020-02-26 15:03:09 +010010979 if (lua_getfield(L, -1, "tcp_payload") == LUA_TFUNCTION)
10980 hlua_flt_ops->tcp_payload = hlua_filter_tcp_payload;
10981 lua_pop(L, 1);
Christopher Faulet69c581a2021-05-31 08:54:04 +020010982
10983 /* Get id and flags of the filter class */
10984 if (lua_getfield(L, -1, "id") == LUA_TSTRING)
10985 flt_id = lua_tostring(L, -1);
10986 lua_pop(L, 1);
10987 if (lua_getfield(L, -1, "flags") == LUA_TNUMBER)
10988 flt_flags = lua_tointeger(L, -1);
10989 lua_pop(L, 1);
10990
10991 /* Create the filter config */
10992 conf = calloc(1, sizeof(*conf));
Christopher Fauletc86bb872021-08-13 08:33:57 +020010993 if (!conf)
Christopher Faulet69c581a2021-05-31 08:54:04 +020010994 goto error;
Christopher Faulet69c581a2021-05-31 08:54:04 +020010995 conf->reg = reg_flt;
10996
10997 /* duplicate args */
10998 for (pos = 0; *args[*cur_arg + 1 + pos]; pos++);
10999 conf->args = calloc(pos + 1, sizeof(*conf->args));
Christopher Fauletc86bb872021-08-13 08:33:57 +020011000 if (!conf->args)
11001 goto error;
11002 for (pos = 0; *args[*cur_arg + 1 + pos]; pos++) {
Christopher Faulet69c581a2021-05-31 08:54:04 +020011003 conf->args[pos] = strdup(args[*cur_arg + 1 + pos]);
Christopher Fauletc86bb872021-08-13 08:33:57 +020011004 if (!conf->args[pos])
11005 goto error;
11006 }
Christopher Faulet69c581a2021-05-31 08:54:04 +020011007 conf->args[pos] = NULL;
11008 *cur_arg += pos + 1;
11009
Christopher Fauletc86bb872021-08-13 08:33:57 +020011010 if (flt_id) {
11011 fconf->id = strdup(flt_id);
11012 if (!fconf->id)
11013 goto error;
11014 }
Christopher Faulet69c581a2021-05-31 08:54:04 +020011015 fconf->flags = flt_flags;
11016 fconf->conf = conf;
11017 fconf->ops = hlua_flt_ops;
11018
11019 lua_settop(L, 0);
11020 return 0;
11021
11022 error:
Christopher Fauletc86bb872021-08-13 08:33:57 +020011023 memprintf(err, "Lua filter '%s' : Lua out of memory error", reg_flt->name);
Christopher Faulet69c581a2021-05-31 08:54:04 +020011024 free(hlua_flt_ops);
Christopher Fauletc86bb872021-08-13 08:33:57 +020011025 if (conf && conf->args) {
11026 for (pos = 0; conf->args[pos]; pos++)
11027 free(conf->args[pos]);
11028 free(conf->args);
11029 }
Christopher Faulet69c581a2021-05-31 08:54:04 +020011030 free(conf);
Christopher Fauletc86bb872021-08-13 08:33:57 +020011031 free((char *)fconf->id);
Christopher Faulet69c581a2021-05-31 08:54:04 +020011032 lua_settop(L, 0);
11033 return -1;
11034}
11035
Christopher Fauletc404f112020-02-26 15:03:09 +010011036__LJMP static int hlua_register_data_filter(lua_State *L)
11037{
11038 struct filter *filter;
11039 struct channel *chn;
11040
11041 MAY_LJMP(check_args(L, 2, "register_data_filter"));
11042 MAY_LJMP(luaL_checktype(L, 1, LUA_TTABLE));
11043 chn = MAY_LJMP(hlua_checkchannel(L, 2));
11044
11045 lua_getfield(L, 1, "__filter");
11046 MAY_LJMP(luaL_checktype(L, -1, LUA_TLIGHTUSERDATA));
11047 filter = lua_touserdata (L, -1);
11048 lua_pop(L, 1);
11049
11050 register_data_filter(chn_strm(chn), chn, filter);
11051 return 1;
11052}
11053
11054__LJMP static int hlua_unregister_data_filter(lua_State *L)
11055{
11056 struct filter *filter;
11057 struct channel *chn;
11058
11059 MAY_LJMP(check_args(L, 2, "unregister_data_filter"));
11060 MAY_LJMP(luaL_checktype(L, 1, LUA_TTABLE));
11061 chn = MAY_LJMP(hlua_checkchannel(L, 2));
11062
11063 lua_getfield(L, 1, "__filter");
11064 MAY_LJMP(luaL_checktype(L, -1, LUA_TLIGHTUSERDATA));
11065 filter = lua_touserdata (L, -1);
11066 lua_pop(L, 1);
11067
11068 unregister_data_filter(chn_strm(chn), chn, filter);
11069 return 1;
11070}
11071
Christopher Faulet69c581a2021-05-31 08:54:04 +020011072/* This function is an LUA binding used for registering a filter. It expects a
Ilya Shipitsinff0f2782021-08-22 22:18:07 +050011073 * filter name used in the haproxy configuration file and a LUA function to
Christopher Faulet69c581a2021-05-31 08:54:04 +020011074 * parse configuration arguments.
11075 */
11076__LJMP static int hlua_register_filter(lua_State *L)
11077{
11078 struct buffer *trash;
11079 struct flt_kw_list *fkl;
11080 struct flt_kw *fkw;
11081 const char *name;
11082 struct hlua_reg_filter *reg_flt= NULL;
11083 int flt_ref, fun_ref;
11084 int len;
11085
11086 MAY_LJMP(check_args(L, 3, "register_filter"));
11087
11088 /* First argument : filter name. */
11089 name = MAY_LJMP(luaL_checkstring(L, 1));
11090
11091 /* Second argument : The filter class */
11092 flt_ref = MAY_LJMP(hlua_checktable(L, 2));
11093
11094 /* Third argument : lua function. */
11095 fun_ref = MAY_LJMP(hlua_checkfunction(L, 3));
11096
11097 trash = get_trash_chunk();
11098 chunk_printf(trash, "lua.%s", name);
11099 fkw = flt_find_kw(trash->area);
11100 if (fkw != NULL) {
11101 reg_flt = fkw->private;
11102 if (reg_flt->flt_ref[hlua_state_id] != -1 || reg_flt->fun_ref[hlua_state_id] != -1) {
11103 ha_warning("Trying to register filter 'lua.%s' more than once. "
11104 "This will become a hard error in version 2.5.\n", name);
11105 }
11106 reg_flt->flt_ref[hlua_state_id] = flt_ref;
11107 reg_flt->fun_ref[hlua_state_id] = fun_ref;
11108 return 0;
11109 }
11110
11111 fkl = calloc(1, sizeof(*fkl) + sizeof(struct flt_kw) * 2);
11112 if (!fkl)
11113 goto alloc_error;
11114 fkl->scope = "HLUA";
11115
11116 reg_flt = new_hlua_reg_filter(name);
11117 if (!reg_flt)
11118 goto alloc_error;
11119
11120 reg_flt->flt_ref[hlua_state_id] = flt_ref;
11121 reg_flt->fun_ref[hlua_state_id] = fun_ref;
11122
11123 /* The filter keyword */
11124 len = strlen("lua.") + strlen(name) + 1;
11125 fkl->kw[0].kw = calloc(1, len);
11126 if (!fkl->kw[0].kw)
11127 goto alloc_error;
11128
11129 snprintf((char *)fkl->kw[0].kw, len, "lua.%s", name);
11130
11131 fkl->kw[0].parse = hlua_filter_parse_fct;
11132 fkl->kw[0].private = reg_flt;
11133 memset(&fkl->kw[1], 0, sizeof(*fkl->kw));
11134
11135 /* Register this new filter */
11136 flt_register_keywords(fkl);
11137
11138 return 0;
11139
11140 alloc_error:
11141 release_hlua_reg_filter(reg_flt);
11142 ha_free(&fkl);
11143 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
11144 return 0; /* Never reached */
11145}
11146
Thierry FOURNIERbd413492015-03-03 16:52:26 +010011147static int hlua_read_timeout(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011148 const struct proxy *defpx, const char *file, int line,
Thierry FOURNIERbd413492015-03-03 16:52:26 +010011149 char **err, unsigned int *timeout)
11150{
11151 const char *error;
11152
11153 error = parse_time_err(args[1], timeout, TIME_UNIT_MS);
Willy Tarreau9faebe32019-06-07 19:00:37 +020011154 if (error == PARSE_TIME_OVER) {
11155 memprintf(err, "timer overflow in argument <%s> to <%s> (maximum value is 2147483647 ms or ~24.8 days)",
11156 args[1], args[0]);
11157 return -1;
11158 }
11159 else if (error == PARSE_TIME_UNDER) {
11160 memprintf(err, "timer underflow in argument <%s> to <%s> (minimum non-null value is 1 ms)",
11161 args[1], args[0]);
11162 return -1;
11163 }
11164 else if (error) {
Thierry FOURNIERbd413492015-03-03 16:52:26 +010011165 memprintf(err, "%s: invalid timeout", args[0]);
11166 return -1;
11167 }
11168 return 0;
11169}
11170
11171static int hlua_session_timeout(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011172 const struct proxy *defpx, const char *file, int line,
Thierry FOURNIERbd413492015-03-03 16:52:26 +010011173 char **err)
11174{
11175 return hlua_read_timeout(args, section_type, curpx, defpx,
11176 file, line, err, &hlua_timeout_session);
11177}
11178
11179static int hlua_task_timeout(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011180 const struct proxy *defpx, const char *file, int line,
Thierry FOURNIERbd413492015-03-03 16:52:26 +010011181 char **err)
11182{
11183 return hlua_read_timeout(args, section_type, curpx, defpx,
11184 file, line, err, &hlua_timeout_task);
11185}
11186
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020011187static int hlua_applet_timeout(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011188 const struct proxy *defpx, const char *file, int line,
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020011189 char **err)
11190{
11191 return hlua_read_timeout(args, section_type, curpx, defpx,
11192 file, line, err, &hlua_timeout_applet);
11193}
11194
Thierry FOURNIERee9f8022015-03-03 17:37:37 +010011195static int hlua_forced_yield(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011196 const struct proxy *defpx, const char *file, int line,
Thierry FOURNIERee9f8022015-03-03 17:37:37 +010011197 char **err)
11198{
11199 char *error;
11200
11201 hlua_nb_instruction = strtoll(args[1], &error, 10);
11202 if (*error != '\0') {
11203 memprintf(err, "%s: invalid number", args[0]);
11204 return -1;
11205 }
11206 return 0;
11207}
11208
Willy Tarreau32f61e22015-03-18 17:54:59 +010011209static int hlua_parse_maxmem(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011210 const struct proxy *defpx, const char *file, int line,
Willy Tarreau32f61e22015-03-18 17:54:59 +010011211 char **err)
11212{
11213 char *error;
11214
11215 if (*(args[1]) == 0) {
11216 memprintf(err, "'%s' expects an integer argument (Lua memory size in MB).\n", args[0]);
11217 return -1;
11218 }
11219 hlua_global_allocator.limit = strtoll(args[1], &error, 10) * 1024L * 1024L;
11220 if (*error != '\0') {
11221 memprintf(err, "%s: invalid number %s (error at '%c')", args[0], args[1], *error);
11222 return -1;
11223 }
11224 return 0;
11225}
11226
11227
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011228/* This function is called by the main configuration key "lua-load". It loads and
11229 * execute an lua file during the parsing of the HAProxy configuration file. It is
11230 * the main lua entry point.
11231 *
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -080011232 * This function runs with the HAProxy keywords API. It returns -1 if an error
11233 * occurs, otherwise it returns 0.
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011234 *
11235 * In some error case, LUA set an error message in top of the stack. This function
11236 * returns this error message in the HAProxy logs and pop it from the stack.
Thierry FOURNIERbabae282015-09-17 11:36:37 +020011237 *
11238 * This function can fail with an abort() due to an Lua critical error.
11239 * We are in the configuration parsing process of HAProxy, this abort() is
11240 * tolerated.
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011241 */
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011242static int hlua_load_state(char *filename, lua_State *L, char **err)
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011243{
11244 int error;
11245
11246 /* Just load and compile the file. */
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011247 error = luaL_loadfile(L, filename);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011248 if (error) {
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011249 memprintf(err, "error in Lua file '%s': %s", filename, lua_tostring(L, -1));
11250 lua_pop(L, 1);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011251 return -1;
11252 }
11253
11254 /* If no syntax error where detected, execute the code. */
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011255 error = lua_pcall(L, 0, LUA_MULTRET, 0);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011256 switch (error) {
11257 case LUA_OK:
11258 break;
11259 case LUA_ERRRUN:
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011260 memprintf(err, "Lua runtime error: %s\n", lua_tostring(L, -1));
11261 lua_pop(L, 1);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011262 return -1;
11263 case LUA_ERRMEM:
Thierry Fournierde6145f2020-11-29 00:55:53 +010011264 memprintf(err, "Lua out of memory error\n");
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011265 return -1;
11266 case LUA_ERRERR:
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011267 memprintf(err, "Lua message handler error: %s\n", lua_tostring(L, -1));
11268 lua_pop(L, 1);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011269 return -1;
Christopher Faulet08ed98f2020-07-28 10:33:25 +020011270#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM <= 503
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011271 case LUA_ERRGCMM:
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011272 memprintf(err, "Lua garbage collector error: %s\n", lua_tostring(L, -1));
11273 lua_pop(L, 1);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011274 return -1;
Christopher Faulet08ed98f2020-07-28 10:33:25 +020011275#endif
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011276 default:
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011277 memprintf(err, "Lua unknown error: %s\n", lua_tostring(L, -1));
11278 lua_pop(L, 1);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011279 return -1;
11280 }
11281
11282 return 0;
11283}
11284
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011285static int hlua_load(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011286 const struct proxy *defpx, const char *file, int line,
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011287 char **err)
11288{
11289 if (*(args[1]) == 0) {
11290 memprintf(err, "'%s' expects a file name as parameter.\n", args[0]);
11291 return -1;
11292 }
11293
Thierry Fournier59f11be2020-11-29 00:37:41 +010011294 /* loading for global state */
Thierry Fournierc7492592020-11-28 23:57:24 +010011295 hlua_state_id = 0;
Willy Tarreau43ab05b2021-09-28 09:43:11 +020011296 ha_set_thread(NULL);
Thierry Fournierafc63e22020-11-28 17:06:51 +010011297 return hlua_load_state(args[1], hlua_states[0], err);
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011298}
11299
Thierry Fournier59f11be2020-11-29 00:37:41 +010011300static int hlua_load_per_thread(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011301 const struct proxy *defpx, const char *file, int line,
Thierry Fournier59f11be2020-11-29 00:37:41 +010011302 char **err)
11303{
11304 int len;
11305
11306 if (*(args[1]) == 0) {
11307 memprintf(err, "'%s' expects a file as parameter.\n", args[0]);
11308 return -1;
11309 }
11310
11311 if (per_thread_load == NULL) {
11312 /* allocate the first entry large enough to store the final NULL */
11313 per_thread_load = calloc(1, sizeof(*per_thread_load));
11314 if (per_thread_load == NULL) {
11315 memprintf(err, "out of memory error");
11316 return -1;
11317 }
11318 }
11319
11320 /* count used entries */
11321 for (len = 0; per_thread_load[len] != NULL; len++)
11322 ;
11323
11324 per_thread_load = realloc(per_thread_load, (len + 2) * sizeof(*per_thread_load));
11325 if (per_thread_load == NULL) {
11326 memprintf(err, "out of memory error");
11327 return -1;
11328 }
11329
11330 per_thread_load[len] = strdup(args[1]);
11331 per_thread_load[len + 1] = NULL;
11332
11333 if (per_thread_load[len] == NULL) {
11334 memprintf(err, "out of memory error");
11335 return -1;
11336 }
11337
11338 /* loading for thread 1 only */
11339 hlua_state_id = 1;
Willy Tarreau43ab05b2021-09-28 09:43:11 +020011340 ha_set_thread(NULL);
Thierry Fournier59f11be2020-11-29 00:37:41 +010011341 return hlua_load_state(args[1], hlua_states[1], err);
11342}
11343
Tim Duesterhusc9fc9f22020-01-12 13:55:39 +010011344/* Prepend the given <path> followed by a semicolon to the `package.<type>` variable
11345 * in the given <ctx>.
11346 */
Thierry Fournier3fb9e512020-11-28 10:13:12 +010011347static int hlua_prepend_path(lua_State *L, char *type, char *path)
Tim Duesterhusc9fc9f22020-01-12 13:55:39 +010011348{
Thierry Fournier3fb9e512020-11-28 10:13:12 +010011349 lua_getglobal(L, "package"); /* push package variable */
11350 lua_pushstring(L, path); /* push given path */
11351 lua_pushstring(L, ";"); /* push semicolon */
11352 lua_getfield(L, -3, type); /* push old path */
11353 lua_concat(L, 3); /* concatenate to new path */
11354 lua_setfield(L, -2, type); /* store new path */
11355 lua_pop(L, 1); /* pop package variable */
Tim Duesterhusc9fc9f22020-01-12 13:55:39 +010011356
11357 return 0;
11358}
11359
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010011360static int hlua_config_prepend_path(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011361 const struct proxy *defpx, const char *file, int line,
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010011362 char **err)
11363{
11364 char *path;
11365 char *type = "path";
Tim Duesterhus621e74a2021-01-03 20:04:36 +010011366 struct prepend_path *p = NULL;
Bertrand Jacquin7fbc7702021-11-24 21:16:06 +000011367 size_t i;
Thierry Fournier59f11be2020-11-29 00:37:41 +010011368
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010011369 if (too_many_args(2, args, err, NULL)) {
Tim Duesterhus621e74a2021-01-03 20:04:36 +010011370 goto err;
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010011371 }
11372
11373 if (!(*args[1])) {
11374 memprintf(err, "'%s' expects to receive a <path> as argument", args[0]);
Tim Duesterhus621e74a2021-01-03 20:04:36 +010011375 goto err;
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010011376 }
11377 path = args[1];
11378
11379 if (*args[2]) {
11380 if (strcmp(args[2], "path") != 0 && strcmp(args[2], "cpath") != 0) {
11381 memprintf(err, "'%s' expects <type> to either be 'path' or 'cpath'", args[0]);
Tim Duesterhus621e74a2021-01-03 20:04:36 +010011382 goto err;
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010011383 }
11384 type = args[2];
11385 }
11386
Thierry Fournier59f11be2020-11-29 00:37:41 +010011387 p = calloc(1, sizeof(*p));
11388 if (p == NULL) {
Tim Duesterhusf89d43a2021-01-03 20:04:37 +010011389 memprintf(err, "memory allocation failed");
Tim Duesterhus621e74a2021-01-03 20:04:36 +010011390 goto err;
Thierry Fournier59f11be2020-11-29 00:37:41 +010011391 }
11392 p->path = strdup(path);
11393 if (p->path == NULL) {
Tim Duesterhusf89d43a2021-01-03 20:04:37 +010011394 memprintf(err, "memory allocation failed");
Tim Duesterhus621e74a2021-01-03 20:04:36 +010011395 goto err2;
Thierry Fournier59f11be2020-11-29 00:37:41 +010011396 }
11397 p->type = strdup(type);
11398 if (p->type == NULL) {
Tim Duesterhusf89d43a2021-01-03 20:04:37 +010011399 memprintf(err, "memory allocation failed");
Tim Duesterhus621e74a2021-01-03 20:04:36 +010011400 goto err2;
Thierry Fournier59f11be2020-11-29 00:37:41 +010011401 }
Willy Tarreau2b718102021-04-21 07:32:39 +020011402 LIST_APPEND(&prepend_path_list, &p->l);
Thierry Fournier59f11be2020-11-29 00:37:41 +010011403
Tim Duesterhus9e5e5862021-10-11 18:51:08 +020011404 /* Handle the global state and the per-thread state for the first
11405 * thread. The remaining threads will be initialized based on
11406 * prepend_path_list.
11407 */
Bertrand Jacquin7fbc7702021-11-24 21:16:06 +000011408 for (i = 0; i < 2; i++) {
Tim Duesterhus9e5e5862021-10-11 18:51:08 +020011409 lua_State *L = hlua_states[i];
11410 const char *error;
11411
11412 if (setjmp(safe_ljmp_env) != 0) {
11413 lua_atpanic(L, hlua_panic_safe);
11414 if (lua_type(L, -1) == LUA_TSTRING)
11415 error = lua_tostring(L, -1);
11416 else
11417 error = "critical error";
11418 fprintf(stderr, "lua-prepend-path: %s.\n", error);
11419 exit(1);
11420 } else {
11421 lua_atpanic(L, hlua_panic_ljmp);
11422 }
11423
11424 hlua_prepend_path(L, type, path);
11425
11426 lua_atpanic(L, hlua_panic_safe);
11427 }
11428
Thierry Fournier59f11be2020-11-29 00:37:41 +010011429 return 0;
Tim Duesterhus621e74a2021-01-03 20:04:36 +010011430
11431err2:
11432 free(p->type);
11433 free(p->path);
11434err:
11435 free(p);
11436 return -1;
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010011437}
11438
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011439/* configuration keywords declaration */
11440static struct cfg_kw_list cfg_kws = {{ },{
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010011441 { CFG_GLOBAL, "lua-prepend-path", hlua_config_prepend_path },
Thierry FOURNIERbd413492015-03-03 16:52:26 +010011442 { CFG_GLOBAL, "lua-load", hlua_load },
Thierry Fournier59f11be2020-11-29 00:37:41 +010011443 { CFG_GLOBAL, "lua-load-per-thread", hlua_load_per_thread },
Thierry FOURNIERbd413492015-03-03 16:52:26 +010011444 { CFG_GLOBAL, "tune.lua.session-timeout", hlua_session_timeout },
11445 { CFG_GLOBAL, "tune.lua.task-timeout", hlua_task_timeout },
Thierry FOURNIER56da1012015-10-01 08:42:31 +020011446 { CFG_GLOBAL, "tune.lua.service-timeout", hlua_applet_timeout },
Thierry FOURNIERee9f8022015-03-03 17:37:37 +010011447 { CFG_GLOBAL, "tune.lua.forced-yield", hlua_forced_yield },
Willy Tarreau32f61e22015-03-18 17:54:59 +010011448 { CFG_GLOBAL, "tune.lua.maxmem", hlua_parse_maxmem },
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011449 { 0, NULL, NULL },
11450}};
11451
Willy Tarreau0108d902018-11-25 19:14:37 +010011452INITCALL1(STG_REGISTER, cfg_register_keywords, &cfg_kws);
11453
William Lallemand52139182022-03-30 15:05:42 +020011454#ifdef USE_OPENSSL
Christopher Fauletafd8f102018-11-08 11:34:21 +010011455
William Lallemand30fcca12022-03-30 12:03:12 +020011456/*
11457 * This function replace a ckch_store by another one, and rebuild the ckch_inst and all its dependencies.
11458 * It does the sam as "cli_io_handler_commit_cert" but for lua, the major
11459 * difference is that the yield in lua and for the CLI is not handled the same
11460 * way.
11461 */
11462__LJMP static int hlua_ckch_commit_yield(lua_State *L, int status, lua_KContext ctx)
11463{
11464 struct ckch_inst **lua_ckchi = lua_touserdata(L, -1);
11465 struct ckch_store **lua_ckchs = lua_touserdata(L, -2);
11466 struct ckch_inst *ckchi = *lua_ckchi;
11467 struct ckch_store *old_ckchs = lua_ckchs[0];
11468 struct ckch_store *new_ckchs = lua_ckchs[1];
11469 struct hlua *hlua;
11470 char *err = NULL;
11471 int y = 1;
11472
11473 hlua = hlua_gethlua(L);
11474
11475 /* get the first ckchi to copy */
11476 if (ckchi == NULL)
11477 ckchi = LIST_ELEM(old_ckchs->ckch_inst.n, typeof(ckchi), by_ckchs);
11478
11479 /* walk through the old ckch_inst and creates new ckch_inst using the updated ckchs */
11480 list_for_each_entry_from(ckchi, &old_ckchs->ckch_inst, by_ckchs) {
11481 struct ckch_inst *new_inst;
11482
11483 /* it takes a lot of CPU to creates SSL_CTXs, so we yield every 10 CKCH instances */
11484 if (y % 10 == 0) {
11485
11486 *lua_ckchi = ckchi;
11487
11488 task_wakeup(hlua->task, TASK_WOKEN_MSG);
11489 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_ckch_commit_yield, TICK_ETERNITY, 0));
11490 }
11491
11492 if (ckch_inst_rebuild(new_ckchs, ckchi, &new_inst, &err))
11493 goto error;
11494
11495 /* link the new ckch_inst to the duplicate */
11496 LIST_APPEND(&new_ckchs->ckch_inst, &new_inst->by_ckchs);
11497 y++;
11498 }
11499
11500 /* The generation is finished, we can insert everything */
11501 ckch_store_replace(old_ckchs, new_ckchs);
11502
11503 lua_pop(L, 2); /* pop the lua_ckchs and ckchi */
11504
11505 HA_SPIN_UNLOCK(CKCH_LOCK, &ckch_lock);
11506
11507 return 0;
11508
11509error:
11510 ckch_store_free(new_ckchs);
11511 HA_SPIN_UNLOCK(CKCH_LOCK, &ckch_lock);
11512 WILL_LJMP(luaL_error(L, "%s", err));
11513 free(err);
11514
11515 return 0;
11516}
11517
11518/*
11519 * Replace a ckch_store <filename> in the ckchs_tree with a ckch_store created
11520 * from the table in parameter.
11521 *
11522 * This is equivalent to "set ssl cert" + "commit ssl cert" over the CLI, which
11523 * means it does not need to have a transaction since everything is done in the
11524 * same function.
11525 *
11526 * CertCache.set{filename="", crt="", key="", sctl="", ocsp="", issuer=""}
11527 *
11528 */
11529__LJMP static int hlua_ckch_set(lua_State *L)
11530{
11531 struct hlua *hlua;
11532 struct ckch_inst **lua_ckchi;
11533 struct ckch_store **lua_ckchs;
11534 struct ckch_store *old_ckchs = NULL;
11535 struct ckch_store *new_ckchs = NULL;
11536 int errcode = 0;
11537 char *err = NULL;
11538 struct cert_exts *cert_ext = NULL;
11539 char *filename;
11540 struct cert_key_and_chain *ckch;
11541 int ret;
11542
11543 if (lua_type(L, -1) != LUA_TTABLE)
11544 WILL_LJMP(luaL_error(L, "'CertCache.set' needs a table as argument"));
11545
11546 hlua = hlua_gethlua(L);
11547
11548 /* FIXME: this should not return an error but should come back later */
11549 if (HA_SPIN_TRYLOCK(CKCH_LOCK, &ckch_lock))
11550 WILL_LJMP(luaL_error(L, "CertCache already under lock"));
11551
11552 ret = lua_getfield(L, -1, "filename");
11553 if (ret != LUA_TSTRING) {
11554 memprintf(&err, "%sNo filename specified!\n", err ? err : "");
11555 errcode |= ERR_ALERT | ERR_FATAL;
11556 goto end;
11557 }
11558 filename = (char *)lua_tostring(L, -1);
11559
11560
11561 /* look for the filename in the tree */
11562 old_ckchs = ckchs_lookup(filename);
11563 if (!old_ckchs) {
11564 memprintf(&err, "%sCan't replace a certificate which is not referenced by the configuration!\n", err ? err : "");
11565 errcode |= ERR_ALERT | ERR_FATAL;
11566 goto end;
11567 }
11568 /* TODO: handle extra_files_noext */
11569
11570 new_ckchs = ckchs_dup(old_ckchs);
11571 if (!new_ckchs) {
11572 memprintf(&err, "%sCannot allocate memory!\n", err ? err : "");
11573 errcode |= ERR_ALERT | ERR_FATAL;
11574 goto end;
11575 }
11576
11577 ckch = new_ckchs->ckch;
11578
11579 /* loop on the field in the table, which have the same name as the
11580 * possible extensions of files */
11581 lua_pushnil(L);
11582 while (lua_next(L, 1)) {
11583 int i;
11584 const char *field = lua_tostring(L, -2);
11585 char *payload = (char *)lua_tostring(L, -1);
11586
11587 if (!field || strcmp(field, "filename") == 0) {
11588 lua_pop(L, 1);
11589 continue;
11590 }
11591
11592 for (i = 0; field && cert_exts[i].ext != NULL; i++) {
11593 if (strcmp(field, cert_exts[i].ext) == 0) {
11594 cert_ext = &cert_exts[i];
11595 break;
11596 }
11597 }
11598
11599 /* this is the default type, the field is not supported */
11600 if (cert_ext == NULL) {
11601 memprintf(&err, "%sUnsupported field '%s'\n", err ? err : "", field);
11602 errcode |= ERR_ALERT | ERR_FATAL;
11603 goto end;
11604 }
11605
11606 /* appply the change on the duplicate */
William Lallemandd8c195a2022-05-26 11:20:13 +020011607 if (cert_ext->load(filename, payload, ckch, &err) != 0) {
11608 memprintf(&err, "%sCan't load the payload for '%s'\n", err ? err : "", cert_ext->ext);
William Lallemand30fcca12022-03-30 12:03:12 +020011609 errcode |= ERR_ALERT | ERR_FATAL;
11610 goto end;
11611 }
11612 lua_pop(L, 1);
11613 }
11614
11615 /* store the pointers on the lua stack */
11616 lua_ckchs = lua_newuserdata(L, sizeof(struct ckch_store *) * 2);
11617 lua_ckchs[0] = old_ckchs;
11618 lua_ckchs[1] = new_ckchs;
11619 lua_ckchi = lua_newuserdata(L, sizeof(struct ckch_inst *));
11620 *lua_ckchi = NULL;
11621
11622 task_wakeup(hlua->task, TASK_WOKEN_MSG);
11623 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_ckch_commit_yield, TICK_ETERNITY, 0));
11624
11625end:
11626 HA_SPIN_UNLOCK(CKCH_LOCK, &ckch_lock);
11627
11628 if (errcode & ERR_CODE) {
11629 ckch_store_free(new_ckchs);
11630 WILL_LJMP(luaL_error(L, "%s", err));
11631 }
11632 free(err);
11633
11634 return 0;
11635}
11636
William Lallemand52139182022-03-30 15:05:42 +020011637#else
11638
11639__LJMP static int hlua_ckch_set(lua_State *L)
11640{
11641 WILL_LJMP(luaL_error(L, "'CertCache.set' needs an HAProxy built with OpenSSL"));
11642
11643 return 0;
11644}
11645#endif /* ! USE_OPENSSL */
11646
11647
11648
Thierry FOURNIERbabae282015-09-17 11:36:37 +020011649/* This function can fail with an abort() due to an Lua critical error.
11650 * We are in the initialisation process of HAProxy, this abort() is
11651 * tolerated.
11652 */
Thierry Fournierb8cef172020-11-28 15:37:17 +010011653int hlua_post_init_state(lua_State *L)
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010011654{
11655 struct hlua_init_function *init;
11656 const char *msg;
11657 enum hlua_exec ret;
Thierry Fournierfd107a22016-02-19 19:57:23 +010011658 const char *error;
Thierry Fournier670db242020-11-28 10:49:59 +010011659 const char *kind;
11660 const char *trace;
11661 int return_status = 1;
11662#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM >= 504
11663 int nres;
11664#endif
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010011665
Willy Tarreaucdb53462020-12-02 12:12:00 +010011666 /* disable memory limit checks if limit is not set */
11667 if (!hlua_global_allocator.limit)
11668 hlua_global_allocator.limit = ~hlua_global_allocator.limit;
11669
Ilya Shipitsin856aabc2020-04-16 23:51:34 +050011670 /* Call post initialisation function in safe environment. */
Thierry Fournier3c539322020-11-28 16:05:05 +010011671 if (setjmp(safe_ljmp_env) != 0) {
11672 lua_atpanic(L, hlua_panic_safe);
Thierry Fournierb8cef172020-11-28 15:37:17 +010011673 if (lua_type(L, -1) == LUA_TSTRING)
11674 error = lua_tostring(L, -1);
Thierry Fournier3d4a6752016-02-19 20:53:30 +010011675 else
11676 error = "critical error";
11677 fprintf(stderr, "Lua post-init: %s.\n", error);
11678 exit(1);
Thierry Fournier3c539322020-11-28 16:05:05 +010011679 } else {
11680 lua_atpanic(L, hlua_panic_ljmp);
Thierry Fournier3d4a6752016-02-19 20:53:30 +010011681 }
Frédéric Lécaille54f2bcf2018-08-29 13:46:24 +020011682
Thierry Fournierb8cef172020-11-28 15:37:17 +010011683 hlua_fcn_post_init(L);
Thierry Fournier3d4a6752016-02-19 20:53:30 +010011684
Thierry Fournierc7492592020-11-28 23:57:24 +010011685 list_for_each_entry(init, &hlua_init_functions[hlua_state_id], l) {
Thierry Fournierb8cef172020-11-28 15:37:17 +010011686 lua_rawgeti(L, LUA_REGISTRYINDEX, init->function_ref);
Thierry Fournier670db242020-11-28 10:49:59 +010011687
11688#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM >= 504
Thierry Fournierb8cef172020-11-28 15:37:17 +010011689 ret = lua_resume(L, L, 0, &nres);
Thierry Fournier670db242020-11-28 10:49:59 +010011690#else
Thierry Fournierb8cef172020-11-28 15:37:17 +010011691 ret = lua_resume(L, L, 0);
Thierry Fournier670db242020-11-28 10:49:59 +010011692#endif
11693 kind = NULL;
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010011694 switch (ret) {
Thierry Fournier670db242020-11-28 10:49:59 +010011695
11696 case LUA_OK:
Thierry Fournierb8cef172020-11-28 15:37:17 +010011697 lua_pop(L, -1);
Thierry Fournier13d08b72020-11-28 11:02:58 +010011698 break;
Thierry Fournier670db242020-11-28 10:49:59 +010011699
11700 case LUA_ERRERR:
11701 kind = "message handler error";
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -070011702 /* Fall through */
Thierry Fournier670db242020-11-28 10:49:59 +010011703 case LUA_ERRRUN:
11704 if (!kind)
11705 kind = "runtime error";
Thierry Fournierb8cef172020-11-28 15:37:17 +010011706 msg = lua_tostring(L, -1);
11707 lua_settop(L, 0); /* Empty the stack. */
11708 lua_pop(L, 1);
Christopher Fauletd09cc512021-03-24 14:48:45 +010011709 trace = hlua_traceback(L, ", ");
Thierry Fournier670db242020-11-28 10:49:59 +010011710 if (msg)
11711 ha_alert("Lua init: %s: '%s' from %s\n", kind, msg, trace);
11712 else
11713 ha_alert("Lua init: unknown %s from %s\n", kind, trace);
11714 return_status = 0;
11715 break;
11716
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010011717 default:
Thierry Fournier670db242020-11-28 10:49:59 +010011718 /* Unknown error */
11719 kind = "Unknown error";
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -070011720 /* Fall through */
Thierry Fournier670db242020-11-28 10:49:59 +010011721 case LUA_YIELD:
11722 /* yield is not configured at this step, this state doesn't happen */
11723 if (!kind)
11724 kind = "yield not allowed";
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -070011725 /* Fall through */
Thierry Fournier670db242020-11-28 10:49:59 +010011726 case LUA_ERRMEM:
11727 if (!kind)
11728 kind = "out of memory error";
Thierry Fournierb8cef172020-11-28 15:37:17 +010011729 lua_settop(L, 0);
11730 lua_pop(L, 1);
Christopher Fauletd09cc512021-03-24 14:48:45 +010011731 trace = hlua_traceback(L, ", ");
Thierry Fournier670db242020-11-28 10:49:59 +010011732 ha_alert("Lua init: %s: %s\n", kind, trace);
11733 return_status = 0;
11734 break;
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010011735 }
Thierry Fournier670db242020-11-28 10:49:59 +010011736 if (!return_status)
11737 break;
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010011738 }
Thierry Fournier3c539322020-11-28 16:05:05 +010011739
11740 lua_atpanic(L, hlua_panic_safe);
Thierry Fournier670db242020-11-28 10:49:59 +010011741 return return_status;
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010011742}
11743
Thierry Fournierb8cef172020-11-28 15:37:17 +010011744int hlua_post_init()
11745{
Thierry Fournier59f11be2020-11-29 00:37:41 +010011746 int ret;
11747 int i;
11748 int errors;
11749 char *err = NULL;
11750 struct hlua_function *fcn;
Christopher Faulet69c581a2021-05-31 08:54:04 +020011751 struct hlua_reg_filter *reg_flt;
Thierry Fournier59f11be2020-11-29 00:37:41 +010011752
Willy Tarreaub1310492021-08-30 09:35:18 +020011753#if defined(USE_OPENSSL)
Thierry Fournierb8cef172020-11-28 15:37:17 +010011754 /* Initialize SSL server. */
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010011755 if (socket_ssl->xprt->prepare_srv) {
Thierry Fournierb8cef172020-11-28 15:37:17 +010011756 int saved_used_backed = global.ssl_used_backend;
11757 // don't affect maxconn automatic computation
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010011758 socket_ssl->xprt->prepare_srv(socket_ssl);
Thierry Fournierb8cef172020-11-28 15:37:17 +010011759 global.ssl_used_backend = saved_used_backed;
11760 }
11761#endif
11762
Thierry Fournierc7492592020-11-28 23:57:24 +010011763 /* Perform post init of common thread */
11764 hlua_state_id = 0;
Willy Tarreau43ab05b2021-09-28 09:43:11 +020011765 ha_set_thread(&ha_thread_info[0]);
Thierry Fournier59f11be2020-11-29 00:37:41 +010011766 ret = hlua_post_init_state(hlua_states[hlua_state_id]);
11767 if (ret == 0)
11768 return 0;
11769
11770 /* init remaining lua states and load files */
11771 for (hlua_state_id = 2; hlua_state_id < global.nbthread + 1; hlua_state_id++) {
11772
11773 /* set thread context */
Willy Tarreau43ab05b2021-09-28 09:43:11 +020011774 ha_set_thread(&ha_thread_info[hlua_state_id - 1]);
Thierry Fournier59f11be2020-11-29 00:37:41 +010011775
11776 /* Init lua state */
11777 hlua_states[hlua_state_id] = hlua_init_state(hlua_state_id);
11778
11779 /* Load lua files */
11780 for (i = 0; per_thread_load && per_thread_load[i]; i++) {
11781 ret = hlua_load_state(per_thread_load[i], hlua_states[hlua_state_id], &err);
11782 if (ret != 0) {
11783 ha_alert("Lua init: %s\n", err);
11784 return 0;
11785 }
11786 }
11787 }
11788
11789 /* Reset thread context */
Willy Tarreau43ab05b2021-09-28 09:43:11 +020011790 ha_set_thread(NULL);
Thierry Fournier59f11be2020-11-29 00:37:41 +010011791
11792 /* Execute post init for all states */
11793 for (hlua_state_id = 1; hlua_state_id < global.nbthread + 1; hlua_state_id++) {
11794
11795 /* set thread context */
Willy Tarreau43ab05b2021-09-28 09:43:11 +020011796 ha_set_thread(&ha_thread_info[hlua_state_id - 1]);
Thierry Fournier59f11be2020-11-29 00:37:41 +010011797
11798 /* run post init */
11799 ret = hlua_post_init_state(hlua_states[hlua_state_id]);
11800 if (ret == 0)
11801 return 0;
11802 }
11803
11804 /* Reset thread context */
Willy Tarreau43ab05b2021-09-28 09:43:11 +020011805 ha_set_thread(NULL);
Thierry Fournier59f11be2020-11-29 00:37:41 +010011806
11807 /* control functions registering. Each function must have:
11808 * - only the function_ref[0] set positive and all other to -1
11809 * - only the function_ref[0] set to -1 and all other positive
11810 * This ensure a same reference is not used both in shared
11811 * lua state and thread dedicated lua state. Note: is the case
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +050011812 * reach, the shared state is priority, but the bug will be
Thierry Fournier59f11be2020-11-29 00:37:41 +010011813 * complicated to found for the end user.
11814 */
11815 errors = 0;
11816 list_for_each_entry(fcn, &referenced_functions, l) {
11817 ret = 0;
11818 for (i = 1; i < global.nbthread + 1; i++) {
11819 if (fcn->function_ref[i] == -1)
11820 ret--;
11821 else
11822 ret++;
11823 }
11824 if (abs(ret) != global.nbthread) {
11825 ha_alert("Lua function '%s' is not referenced in all thread. "
11826 "Expect function in all thread or in none thread.\n", fcn->name);
11827 errors++;
11828 continue;
11829 }
11830
11831 if ((fcn->function_ref[0] == -1) == (ret < 0)) {
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +050011832 ha_alert("Lua function '%s' is referenced both ins shared Lua context (through lua-load) "
11833 "and per-thread Lua context (through lua-load-per-thread). these two context "
Thierry Fournier59f11be2020-11-29 00:37:41 +010011834 "exclusive.\n", fcn->name);
11835 errors++;
11836 }
11837 }
11838
Christopher Faulet69c581a2021-05-31 08:54:04 +020011839 /* Do the same with registered filters */
11840 list_for_each_entry(reg_flt, &referenced_filters, l) {
11841 ret = 0;
11842 for (i = 1; i < global.nbthread + 1; i++) {
11843 if (reg_flt->flt_ref[i] == -1)
11844 ret--;
11845 else
11846 ret++;
11847 }
11848 if (abs(ret) != global.nbthread) {
11849 ha_alert("Lua filter '%s' is not referenced in all thread. "
11850 "Expect function in all thread or in none thread.\n", reg_flt->name);
11851 errors++;
11852 continue;
11853 }
11854
11855 if ((reg_flt->flt_ref[0] == -1) == (ret < 0)) {
11856 ha_alert("Lua filter '%s' is referenced both ins shared Lua context (through lua-load) "
11857 "and per-thread Lua context (through lua-load-per-thread). these two context "
11858 "exclusive.\n", fcn->name);
11859 errors++;
11860 }
11861 }
11862
11863
Thierry Fournier59f11be2020-11-29 00:37:41 +010011864 if (errors > 0)
11865 return 0;
11866
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +050011867 /* after this point, this global will no longer be used, so set to
Thierry Fournier59f11be2020-11-29 00:37:41 +010011868 * -1 in order to have probably a segfault if someone use it
11869 */
11870 hlua_state_id = -1;
11871
11872 return 1;
Thierry Fournierb8cef172020-11-28 15:37:17 +010011873}
11874
Willy Tarreau32f61e22015-03-18 17:54:59 +010011875/* The memory allocator used by the Lua stack. <ud> is a pointer to the
11876 * allocator's context. <ptr> is the pointer to alloc/free/realloc. <osize>
11877 * is the previously allocated size or the kind of object in case of a new
Willy Tarreaud36c7fa2020-12-02 12:26:29 +010011878 * allocation. <nsize> is the requested new size. A new allocation is
11879 * indicated by <ptr> being NULL. A free is indicated by <nsize> being
Willy Tarreaucdb53462020-12-02 12:12:00 +010011880 * zero. This one verifies that the limits are respected but is optimized
11881 * for the fast case where limits are not used, hence stats are not updated.
Willy Tarreaua5efdff2021-10-22 16:00:02 +020011882 *
11883 * Warning: while this API ressembles glibc's realloc() a lot, glibc surpasses
11884 * POSIX by making realloc(ptr,0) an effective free(), but others do not do
11885 * that and will simply allocate zero as if it were the result of malloc(0),
11886 * so mapping this onto realloc() will lead to memory leaks on non-glibc
11887 * systems.
Willy Tarreau32f61e22015-03-18 17:54:59 +010011888 */
11889static void *hlua_alloc(void *ud, void *ptr, size_t osize, size_t nsize)
11890{
11891 struct hlua_mem_allocator *zone = ud;
Willy Tarreaucdb53462020-12-02 12:12:00 +010011892 size_t limit, old, new;
11893
11894 /* a limit of ~0 means unlimited and boot complete, so there's no need
11895 * for accounting anymore.
11896 */
Willy Tarreaua5efdff2021-10-22 16:00:02 +020011897 if (likely(~zone->limit == 0)) {
11898 if (!nsize)
11899 ha_free(&ptr);
11900 else
11901 ptr = realloc(ptr, nsize);
11902 return ptr;
11903 }
Willy Tarreau32f61e22015-03-18 17:54:59 +010011904
Willy Tarreaud36c7fa2020-12-02 12:26:29 +010011905 if (!ptr)
11906 osize = 0;
Willy Tarreau32f61e22015-03-18 17:54:59 +010011907
Willy Tarreaucdb53462020-12-02 12:12:00 +010011908 /* enforce strict limits across all threads */
11909 limit = zone->limit;
11910 old = _HA_ATOMIC_LOAD(&zone->allocated);
11911 do {
11912 new = old + nsize - osize;
11913 if (unlikely(nsize && limit && new > limit))
11914 return NULL;
11915 } while (!_HA_ATOMIC_CAS(&zone->allocated, &old, new));
Willy Tarreau32f61e22015-03-18 17:54:59 +010011916
Willy Tarreaua5efdff2021-10-22 16:00:02 +020011917 if (!nsize)
11918 ha_free(&ptr);
11919 else
11920 ptr = realloc(ptr, nsize);
Willy Tarreaucdb53462020-12-02 12:12:00 +010011921
11922 if (unlikely(!ptr && nsize)) // failed
11923 _HA_ATOMIC_SUB(&zone->allocated, nsize - osize);
11924
11925 __ha_barrier_atomic_store();
Willy Tarreau32f61e22015-03-18 17:54:59 +010011926 return ptr;
11927}
11928
Thierry Fournierecb83c22020-11-28 15:49:44 +010011929/* This function can fail with an abort() due to a Lua critical error.
Thierry FOURNIERbabae282015-09-17 11:36:37 +020011930 * We are in the initialisation process of HAProxy, this abort() is
11931 * tolerated.
11932 */
Thierry Fournierecb83c22020-11-28 15:49:44 +010011933lua_State *hlua_init_state(int thread_num)
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +010011934{
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010011935 int i;
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010011936 int idx;
11937 struct sample_fetch *sf;
Thierry FOURNIER594afe72015-03-10 23:58:30 +010011938 struct sample_conv *sc;
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010011939 char *p;
Thierry Fournierfd107a22016-02-19 19:57:23 +010011940 const char *error_msg;
Thierry Fournier4234dbd2020-11-28 13:18:23 +010011941 void **context;
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011942 lua_State *L;
Thierry Fournier59f11be2020-11-29 00:37:41 +010011943 struct prepend_path *pp;
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010011944
Thierry FOURNIER380d0932015-01-23 14:27:52 +010011945 /* Init main lua stack. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011946 L = lua_newstate(hlua_alloc, &hlua_global_allocator);
Thierry FOURNIER380d0932015-01-23 14:27:52 +010011947
Thierry Fournier4234dbd2020-11-28 13:18:23 +010011948 /* Initialise Lua context to NULL */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011949 context = lua_getextraspace(L);
Thierry Fournier4234dbd2020-11-28 13:18:23 +010011950 *context = NULL;
11951
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -080011952 /* From this point, until the end of the initialisation function,
Thierry FOURNIERbabae282015-09-17 11:36:37 +020011953 * the Lua function can fail with an abort. We are in the initialisation
11954 * process of HAProxy, this abort() is tolerated.
11955 */
11956
Thierry Fournier3c539322020-11-28 16:05:05 +010011957 /* Call post initialisation function in safe environment. */
11958 if (setjmp(safe_ljmp_env) != 0) {
11959 lua_atpanic(L, hlua_panic_safe);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011960 if (lua_type(L, -1) == LUA_TSTRING)
11961 error_msg = lua_tostring(L, -1);
Thierry Fournier2f05cc62020-11-28 16:08:02 +010011962 else
11963 error_msg = "critical error";
11964 fprintf(stderr, "Lua init: %s.\n", error_msg);
11965 exit(1);
Thierry Fournier3c539322020-11-28 16:05:05 +010011966 } else {
11967 lua_atpanic(L, hlua_panic_ljmp);
Thierry Fournier2f05cc62020-11-28 16:08:02 +010011968 }
11969
Thierry FOURNIER380d0932015-01-23 14:27:52 +010011970 /* Initialise lua. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011971 luaL_openlibs(L);
Tim Duesterhus541fe1e2020-01-12 13:55:41 +010011972#define HLUA_PREPEND_PATH_TOSTRING1(x) #x
11973#define HLUA_PREPEND_PATH_TOSTRING(x) HLUA_PREPEND_PATH_TOSTRING1(x)
11974#ifdef HLUA_PREPEND_PATH
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011975 hlua_prepend_path(L, "path", HLUA_PREPEND_PATH_TOSTRING(HLUA_PREPEND_PATH));
Tim Duesterhus541fe1e2020-01-12 13:55:41 +010011976#endif
11977#ifdef HLUA_PREPEND_CPATH
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011978 hlua_prepend_path(L, "cpath", HLUA_PREPEND_PATH_TOSTRING(HLUA_PREPEND_CPATH));
Tim Duesterhus541fe1e2020-01-12 13:55:41 +010011979#endif
11980#undef HLUA_PREPEND_PATH_TOSTRING
11981#undef HLUA_PREPEND_PATH_TOSTRING1
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010011982
Thierry Fournier59f11be2020-11-29 00:37:41 +010011983 /* Apply configured prepend path */
11984 list_for_each_entry(pp, &prepend_path_list, l)
11985 hlua_prepend_path(L, pp->type, pp->path);
11986
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010011987 /*
11988 *
11989 * Create "core" object.
11990 *
11991 */
11992
Thierry FOURNIERa2d8c652015-03-11 17:29:39 +010011993 /* This table entry is the object "core" base. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011994 lua_newtable(L);
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010011995
Thierry Fournierecb83c22020-11-28 15:49:44 +010011996 /* set the thread id */
11997 hlua_class_const_int(L, "thread", thread_num);
11998
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010011999 /* Push the loglevel constants. */
Willy Tarreau80f5fae2015-02-27 16:38:20 +010012000 for (i = 0; i < NB_LOG_LEVELS; i++)
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012001 hlua_class_const_int(L, log_levels[i], i);
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010012002
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010012003 /* Register special functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012004 hlua_class_function(L, "register_init", hlua_register_init);
12005 hlua_class_function(L, "register_task", hlua_register_task);
12006 hlua_class_function(L, "register_fetches", hlua_register_fetches);
12007 hlua_class_function(L, "register_converters", hlua_register_converters);
12008 hlua_class_function(L, "register_action", hlua_register_action);
12009 hlua_class_function(L, "register_service", hlua_register_service);
12010 hlua_class_function(L, "register_cli", hlua_register_cli);
Christopher Faulet69c581a2021-05-31 08:54:04 +020012011 hlua_class_function(L, "register_filter", hlua_register_filter);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012012 hlua_class_function(L, "yield", hlua_yield);
12013 hlua_class_function(L, "set_nice", hlua_set_nice);
12014 hlua_class_function(L, "sleep", hlua_sleep);
12015 hlua_class_function(L, "msleep", hlua_msleep);
12016 hlua_class_function(L, "add_acl", hlua_add_acl);
12017 hlua_class_function(L, "del_acl", hlua_del_acl);
12018 hlua_class_function(L, "set_map", hlua_set_map);
12019 hlua_class_function(L, "del_map", hlua_del_map);
12020 hlua_class_function(L, "tcp", hlua_socket_new);
William Lallemand3956c4e2021-09-21 16:25:15 +020012021 hlua_class_function(L, "httpclient", hlua_httpclient_new);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012022 hlua_class_function(L, "log", hlua_log);
12023 hlua_class_function(L, "Debug", hlua_log_debug);
12024 hlua_class_function(L, "Info", hlua_log_info);
12025 hlua_class_function(L, "Warning", hlua_log_warning);
12026 hlua_class_function(L, "Alert", hlua_log_alert);
12027 hlua_class_function(L, "done", hlua_done);
12028 hlua_fcn_reg_core_fcn(L);
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010012029
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012030 lua_setglobal(L, "core");
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010012031
12032 /*
12033 *
Christopher Faulet0f3c8902020-01-31 18:57:12 +010012034 * Create "act" object.
12035 *
12036 */
12037
12038 /* This table entry is the object "act" base. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012039 lua_newtable(L);
Christopher Faulet0f3c8902020-01-31 18:57:12 +010012040
12041 /* push action return constants */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012042 hlua_class_const_int(L, "CONTINUE", ACT_RET_CONT);
12043 hlua_class_const_int(L, "STOP", ACT_RET_STOP);
12044 hlua_class_const_int(L, "YIELD", ACT_RET_YIELD);
12045 hlua_class_const_int(L, "ERROR", ACT_RET_ERR);
12046 hlua_class_const_int(L, "DONE", ACT_RET_DONE);
12047 hlua_class_const_int(L, "DENY", ACT_RET_DENY);
12048 hlua_class_const_int(L, "ABORT", ACT_RET_ABRT);
12049 hlua_class_const_int(L, "INVALID", ACT_RET_INV);
Christopher Faulet0f3c8902020-01-31 18:57:12 +010012050
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012051 hlua_class_function(L, "wake_time", hlua_set_wake_time);
Christopher Faulet2c2c2e32020-01-31 19:07:52 +010012052
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012053 lua_setglobal(L, "act");
Christopher Faulet0f3c8902020-01-31 18:57:12 +010012054
12055 /*
12056 *
Christopher Faulet69c581a2021-05-31 08:54:04 +020012057 * Create "Filter" object.
12058 *
12059 */
12060
12061 /* This table entry is the object "filter" base. */
12062 lua_newtable(L);
12063
12064 /* push flags and constants */
12065 hlua_class_const_int(L, "CONTINUE", 1);
12066 hlua_class_const_int(L, "WAIT", 0);
12067 hlua_class_const_int(L, "ERROR", -1);
12068
12069 hlua_class_const_int(L, "FLT_CFG_FL_HTX", FLT_CFG_FL_HTX);
12070
Christopher Fauletc404f112020-02-26 15:03:09 +010012071 hlua_class_function(L, "wake_time", hlua_set_wake_time);
12072 hlua_class_function(L, "register_data_filter", hlua_register_data_filter);
12073 hlua_class_function(L, "unregister_data_filter", hlua_unregister_data_filter);
12074
Christopher Faulet69c581a2021-05-31 08:54:04 +020012075 lua_setglobal(L, "filter");
12076
12077 /*
12078 *
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012079 * Register class Map
12080 *
12081 */
12082
12083 /* This table entry is the object "Map" base. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012084 lua_newtable(L);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012085
12086 /* register pattern types. */
12087 for (i=0; i<PAT_MATCH_NUM; i++)
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012088 hlua_class_const_int(L, pat_match_names[i], i);
Thierry FOURNIER4dc71972017-01-28 08:33:08 +010012089 for (i=0; i<PAT_MATCH_NUM; i++) {
Willy Tarreau843b7cb2018-07-13 10:54:26 +020012090 snprintf(trash.area, trash.size, "_%s", pat_match_names[i]);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012091 hlua_class_const_int(L, trash.area, i);
Thierry FOURNIER4dc71972017-01-28 08:33:08 +010012092 }
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012093
12094 /* register constructor. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012095 hlua_class_function(L, "new", hlua_map_new);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012096
12097 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012098 lua_newtable(L);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012099
Ilya Shipitsind4259502020-04-08 01:07:56 +050012100 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012101 lua_pushstring(L, "__index");
12102 lua_newtable(L);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012103
12104 /* Register . */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012105 hlua_class_function(L, "lookup", hlua_map_lookup);
12106 hlua_class_function(L, "slookup", hlua_map_slookup);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012107
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012108 lua_rawset(L, -3);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012109
Thierry Fournier45e78d72016-02-19 18:34:46 +010012110 /* Register previous table in the registry with reference and named entry.
12111 * The function hlua_register_metatable() pops the stack, so we
12112 * previously create a copy of the table.
12113 */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012114 lua_pushvalue(L, -1); /* Copy the -1 entry and push it on the stack. */
12115 class_map_ref = hlua_register_metatable(L, CLASS_MAP);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012116
12117 /* Assign the metatable to the mai Map object. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012118 lua_setmetatable(L, -2);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012119
12120 /* Set a name to the table. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012121 lua_setglobal(L, "Map");
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012122
12123 /*
12124 *
William Lallemand30fcca12022-03-30 12:03:12 +020012125 * Register "CertCache" class
12126 *
12127 */
12128
12129 /* Create and fill the metatable. */
12130 lua_newtable(L);
12131 /* Register */
12132 hlua_class_function(L, "set", hlua_ckch_set);
12133 lua_setglobal(L, CLASS_CERTCACHE); /* Create global object called Regex */
12134
12135 /*
12136 *
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010012137 * Register class Channel
12138 *
12139 */
12140
12141 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012142 lua_newtable(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010012143
Ilya Shipitsind4259502020-04-08 01:07:56 +050012144 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012145 lua_pushstring(L, "__index");
12146 lua_newtable(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010012147
12148 /* Register . */
Christopher Faulet6a79fc12021-08-06 16:02:36 +020012149 hlua_class_function(L, "data", hlua_channel_get_data);
12150 hlua_class_function(L, "line", hlua_channel_get_line);
12151 hlua_class_function(L, "set", hlua_channel_set_data);
12152 hlua_class_function(L, "remove", hlua_channel_del_data);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012153 hlua_class_function(L, "append", hlua_channel_append);
Christopher Faulet6a79fc12021-08-06 16:02:36 +020012154 hlua_class_function(L, "prepend", hlua_channel_prepend);
12155 hlua_class_function(L, "insert", hlua_channel_insert_data);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012156 hlua_class_function(L, "send", hlua_channel_send);
12157 hlua_class_function(L, "forward", hlua_channel_forward);
Christopher Faulet6a79fc12021-08-06 16:02:36 +020012158 hlua_class_function(L, "input", hlua_channel_get_in_len);
12159 hlua_class_function(L, "output", hlua_channel_get_out_len);
12160 hlua_class_function(L, "may_recv", hlua_channel_may_recv);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012161 hlua_class_function(L, "is_full", hlua_channel_is_full);
12162 hlua_class_function(L, "is_resp", hlua_channel_is_resp);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010012163
Christopher Faulet6a79fc12021-08-06 16:02:36 +020012164 /* Deprecated API */
12165 hlua_class_function(L, "get", hlua_channel_get);
12166 hlua_class_function(L, "dup", hlua_channel_dup);
12167 hlua_class_function(L, "getline", hlua_channel_getline);
12168 hlua_class_function(L, "get_in_len", hlua_channel_get_in_len);
12169 hlua_class_function(L, "get_out_len", hlua_channel_get_out_len);
12170
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012171 lua_rawset(L, -3);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010012172
12173 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012174 class_channel_ref = hlua_register_metatable(L, CLASS_CHANNEL);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010012175
12176 /*
12177 *
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010012178 * Register class Fetches
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010012179 *
12180 */
12181
12182 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012183 lua_newtable(L);
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010012184
Ilya Shipitsind4259502020-04-08 01:07:56 +050012185 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012186 lua_pushstring(L, "__index");
12187 lua_newtable(L);
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010012188
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010012189 /* Browse existing fetches and create the associated
12190 * object method.
12191 */
12192 sf = NULL;
12193 while ((sf = sample_fetch_getnext(sf, &idx)) != NULL) {
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010012194 /* gL.Tua doesn't support '.' and '-' in the function names, replace it
12195 * by an underscore.
12196 */
Willy Tarreau5ef96562021-08-26 16:48:53 +020012197 strlcpy2(trash.area, sf->kw, trash.size);
Willy Tarreau843b7cb2018-07-13 10:54:26 +020012198 for (p = trash.area; *p; p++)
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010012199 if (*p == '.' || *p == '-' || *p == '+')
12200 *p = '_';
12201
12202 /* Register the function. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012203 lua_pushstring(L, trash.area);
12204 lua_pushlightuserdata(L, sf);
12205 lua_pushcclosure(L, hlua_run_sample_fetch, 1);
12206 lua_rawset(L, -3);
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010012207 }
12208
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012209 lua_rawset(L, -3);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010012210
12211 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012212 class_fetches_ref = hlua_register_metatable(L, CLASS_FETCHES);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010012213
12214 /*
12215 *
Thierry FOURNIER594afe72015-03-10 23:58:30 +010012216 * Register class Converters
12217 *
12218 */
12219
12220 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012221 lua_newtable(L);
Thierry FOURNIER594afe72015-03-10 23:58:30 +010012222
12223 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012224 lua_pushstring(L, "__index");
12225 lua_newtable(L);
Thierry FOURNIER594afe72015-03-10 23:58:30 +010012226
12227 /* Browse existing converters and create the associated
12228 * object method.
12229 */
12230 sc = NULL;
12231 while ((sc = sample_conv_getnext(sc, &idx)) != NULL) {
Thierry FOURNIER594afe72015-03-10 23:58:30 +010012232 /* gL.Tua doesn't support '.' and '-' in the function names, replace it
12233 * by an underscore.
12234 */
Willy Tarreau5ef96562021-08-26 16:48:53 +020012235 strlcpy2(trash.area, sc->kw, trash.size);
Willy Tarreau843b7cb2018-07-13 10:54:26 +020012236 for (p = trash.area; *p; p++)
Thierry FOURNIER594afe72015-03-10 23:58:30 +010012237 if (*p == '.' || *p == '-' || *p == '+')
12238 *p = '_';
12239
12240 /* Register the function. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012241 lua_pushstring(L, trash.area);
12242 lua_pushlightuserdata(L, sc);
12243 lua_pushcclosure(L, hlua_run_sample_conv, 1);
12244 lua_rawset(L, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +010012245 }
12246
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012247 lua_rawset(L, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +010012248
12249 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012250 class_converters_ref = hlua_register_metatable(L, CLASS_CONVERTERS);
Thierry FOURNIER594afe72015-03-10 23:58:30 +010012251
12252 /*
12253 *
Thierry FOURNIER08504f42015-03-16 14:17:08 +010012254 * Register class HTTP
12255 *
12256 */
12257
12258 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012259 lua_newtable(L);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010012260
Ilya Shipitsind4259502020-04-08 01:07:56 +050012261 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012262 lua_pushstring(L, "__index");
12263 lua_newtable(L);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010012264
12265 /* Register Lua functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012266 hlua_class_function(L, "req_get_headers",hlua_http_req_get_headers);
12267 hlua_class_function(L, "req_del_header", hlua_http_req_del_hdr);
12268 hlua_class_function(L, "req_rep_header", hlua_http_req_rep_hdr);
12269 hlua_class_function(L, "req_rep_value", hlua_http_req_rep_val);
12270 hlua_class_function(L, "req_add_header", hlua_http_req_add_hdr);
12271 hlua_class_function(L, "req_set_header", hlua_http_req_set_hdr);
12272 hlua_class_function(L, "req_set_method", hlua_http_req_set_meth);
12273 hlua_class_function(L, "req_set_path", hlua_http_req_set_path);
12274 hlua_class_function(L, "req_set_query", hlua_http_req_set_query);
12275 hlua_class_function(L, "req_set_uri", hlua_http_req_set_uri);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010012276
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012277 hlua_class_function(L, "res_get_headers",hlua_http_res_get_headers);
12278 hlua_class_function(L, "res_del_header", hlua_http_res_del_hdr);
12279 hlua_class_function(L, "res_rep_header", hlua_http_res_rep_hdr);
12280 hlua_class_function(L, "res_rep_value", hlua_http_res_rep_val);
12281 hlua_class_function(L, "res_add_header", hlua_http_res_add_hdr);
12282 hlua_class_function(L, "res_set_header", hlua_http_res_set_hdr);
12283 hlua_class_function(L, "res_set_status", hlua_http_res_set_status);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010012284
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012285 lua_rawset(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010012286
12287 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012288 class_http_ref = hlua_register_metatable(L, CLASS_HTTP);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010012289
Christopher Fauletdf97ac42020-02-26 16:57:19 +010012290 /*
12291 *
12292 * Register class HTTPMessage
12293 *
12294 */
12295
12296 /* Create and fill the metatable. */
12297 lua_newtable(L);
12298
Ilya Shipitsinff0f2782021-08-22 22:18:07 +050012299 /* Create and fill the __index entry. */
Christopher Fauletdf97ac42020-02-26 16:57:19 +010012300 lua_pushstring(L, "__index");
12301 lua_newtable(L);
12302
12303 /* Register Lua functions. */
12304 hlua_class_function(L, "is_resp", hlua_http_msg_is_resp);
12305 hlua_class_function(L, "get_stline", hlua_http_msg_get_stline);
12306 hlua_class_function(L, "get_headers", hlua_http_msg_get_headers);
12307 hlua_class_function(L, "del_header", hlua_http_msg_del_hdr);
12308 hlua_class_function(L, "rep_header", hlua_http_msg_rep_hdr);
12309 hlua_class_function(L, "rep_value", hlua_http_msg_rep_val);
12310 hlua_class_function(L, "add_header", hlua_http_msg_add_hdr);
12311 hlua_class_function(L, "set_header", hlua_http_msg_set_hdr);
12312 hlua_class_function(L, "set_method", hlua_http_msg_set_meth);
12313 hlua_class_function(L, "set_path", hlua_http_msg_set_path);
12314 hlua_class_function(L, "set_query", hlua_http_msg_set_query);
12315 hlua_class_function(L, "set_uri", hlua_http_msg_set_uri);
12316 hlua_class_function(L, "set_status", hlua_http_msg_set_status);
12317 hlua_class_function(L, "is_full", hlua_http_msg_is_full);
12318 hlua_class_function(L, "may_recv", hlua_http_msg_may_recv);
12319 hlua_class_function(L, "eom", hlua_http_msg_is_eom);
12320 hlua_class_function(L, "input", hlua_http_msg_get_in_len);
12321 hlua_class_function(L, "output", hlua_http_msg_get_out_len);
12322
12323 hlua_class_function(L, "body", hlua_http_msg_get_body);
12324 hlua_class_function(L, "set", hlua_http_msg_set_data);
12325 hlua_class_function(L, "remove", hlua_http_msg_del_data);
12326 hlua_class_function(L, "append", hlua_http_msg_append);
12327 hlua_class_function(L, "prepend", hlua_http_msg_prepend);
12328 hlua_class_function(L, "insert", hlua_http_msg_insert_data);
12329 hlua_class_function(L, "set_eom", hlua_http_msg_set_eom);
12330 hlua_class_function(L, "unset_eom", hlua_http_msg_unset_eom);
12331
12332 hlua_class_function(L, "send", hlua_http_msg_send);
12333 hlua_class_function(L, "forward", hlua_http_msg_forward);
12334
12335 lua_rawset(L, -3);
12336
12337 /* Register previous table in the registry with reference and named entry. */
12338 class_http_msg_ref = hlua_register_metatable(L, CLASS_HTTP_MSG);
William Lallemand3956c4e2021-09-21 16:25:15 +020012339
12340 /*
12341 *
12342 * Register class HTTPClient
12343 *
12344 */
12345
12346 /* Create and fill the metatable. */
12347 lua_newtable(L);
12348 lua_pushstring(L, "__index");
12349 lua_newtable(L);
12350 hlua_class_function(L, "get", hlua_httpclient_get);
William Lallemanddc2cc902021-10-26 11:43:26 +020012351 hlua_class_function(L, "head", hlua_httpclient_head);
12352 hlua_class_function(L, "put", hlua_httpclient_put);
12353 hlua_class_function(L, "post", hlua_httpclient_post);
12354 hlua_class_function(L, "delete", hlua_httpclient_delete);
William Lallemand3956c4e2021-09-21 16:25:15 +020012355 lua_settable(L, -3); /* Sets the __index entry. */
William Lallemandf77f1de2021-09-28 19:10:38 +020012356 /* Register the garbage collector entry. */
12357 lua_pushstring(L, "__gc");
12358 lua_pushcclosure(L, hlua_httpclient_gc, 0);
12359 lua_settable(L, -3); /* Push the last 2 entries in the table at index -3 */
12360
William Lallemand3956c4e2021-09-21 16:25:15 +020012361
12362
12363 class_httpclient_ref = hlua_register_metatable(L, CLASS_HTTPCLIENT);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010012364 /*
12365 *
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020012366 * Register class AppletTCP
12367 *
12368 */
12369
12370 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012371 lua_newtable(L);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020012372
Ilya Shipitsind4259502020-04-08 01:07:56 +050012373 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012374 lua_pushstring(L, "__index");
12375 lua_newtable(L);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020012376
12377 /* Register Lua functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012378 hlua_class_function(L, "getline", hlua_applet_tcp_getline);
12379 hlua_class_function(L, "receive", hlua_applet_tcp_recv);
12380 hlua_class_function(L, "send", hlua_applet_tcp_send);
12381 hlua_class_function(L, "set_priv", hlua_applet_tcp_set_priv);
12382 hlua_class_function(L, "get_priv", hlua_applet_tcp_get_priv);
12383 hlua_class_function(L, "set_var", hlua_applet_tcp_set_var);
12384 hlua_class_function(L, "unset_var", hlua_applet_tcp_unset_var);
12385 hlua_class_function(L, "get_var", hlua_applet_tcp_get_var);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020012386
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012387 lua_settable(L, -3);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020012388
12389 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012390 class_applet_tcp_ref = hlua_register_metatable(L, CLASS_APPLET_TCP);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020012391
12392 /*
12393 *
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020012394 * Register class AppletHTTP
12395 *
12396 */
12397
12398 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012399 lua_newtable(L);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020012400
Ilya Shipitsind4259502020-04-08 01:07:56 +050012401 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012402 lua_pushstring(L, "__index");
12403 lua_newtable(L);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020012404
12405 /* Register Lua functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012406 hlua_class_function(L, "set_priv", hlua_applet_http_set_priv);
12407 hlua_class_function(L, "get_priv", hlua_applet_http_get_priv);
12408 hlua_class_function(L, "set_var", hlua_applet_http_set_var);
12409 hlua_class_function(L, "unset_var", hlua_applet_http_unset_var);
12410 hlua_class_function(L, "get_var", hlua_applet_http_get_var);
12411 hlua_class_function(L, "getline", hlua_applet_http_getline);
12412 hlua_class_function(L, "receive", hlua_applet_http_recv);
12413 hlua_class_function(L, "send", hlua_applet_http_send);
12414 hlua_class_function(L, "add_header", hlua_applet_http_addheader);
12415 hlua_class_function(L, "set_status", hlua_applet_http_status);
12416 hlua_class_function(L, "start_response", hlua_applet_http_start_response);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020012417
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012418 lua_settable(L, -3);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020012419
12420 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012421 class_applet_http_ref = hlua_register_metatable(L, CLASS_APPLET_HTTP);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020012422
12423 /*
12424 *
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010012425 * Register class TXN
12426 *
12427 */
12428
12429 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012430 lua_newtable(L);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010012431
Ilya Shipitsind4259502020-04-08 01:07:56 +050012432 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012433 lua_pushstring(L, "__index");
12434 lua_newtable(L);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010012435
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +010012436 /* Register Lua functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012437 hlua_class_function(L, "set_priv", hlua_set_priv);
12438 hlua_class_function(L, "get_priv", hlua_get_priv);
12439 hlua_class_function(L, "set_var", hlua_set_var);
12440 hlua_class_function(L, "unset_var", hlua_unset_var);
12441 hlua_class_function(L, "get_var", hlua_get_var);
12442 hlua_class_function(L, "done", hlua_txn_done);
12443 hlua_class_function(L, "reply", hlua_txn_reply_new);
12444 hlua_class_function(L, "set_loglevel", hlua_txn_set_loglevel);
12445 hlua_class_function(L, "set_tos", hlua_txn_set_tos);
12446 hlua_class_function(L, "set_mark", hlua_txn_set_mark);
12447 hlua_class_function(L, "set_priority_class", hlua_txn_set_priority_class);
12448 hlua_class_function(L, "set_priority_offset", hlua_txn_set_priority_offset);
12449 hlua_class_function(L, "deflog", hlua_txn_deflog);
12450 hlua_class_function(L, "log", hlua_txn_log);
12451 hlua_class_function(L, "Debug", hlua_txn_log_debug);
12452 hlua_class_function(L, "Info", hlua_txn_log_info);
12453 hlua_class_function(L, "Warning", hlua_txn_log_warning);
12454 hlua_class_function(L, "Alert", hlua_txn_log_alert);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +010012455
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012456 lua_rawset(L, -3);
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010012457
12458 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012459 class_txn_ref = hlua_register_metatable(L, CLASS_TXN);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012460
12461 /*
12462 *
Christopher Faulet700d9e82020-01-31 12:21:52 +010012463 * Register class reply
12464 *
12465 */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012466 lua_newtable(L);
12467 lua_pushstring(L, "__index");
12468 lua_newtable(L);
12469 hlua_class_function(L, "set_status", hlua_txn_reply_set_status);
12470 hlua_class_function(L, "add_header", hlua_txn_reply_add_header);
12471 hlua_class_function(L, "del_header", hlua_txn_reply_del_header);
12472 hlua_class_function(L, "set_body", hlua_txn_reply_set_body);
12473 lua_settable(L, -3); /* Sets the __index entry. */
12474 class_txn_reply_ref = luaL_ref(L, LUA_REGISTRYINDEX);
Christopher Faulet700d9e82020-01-31 12:21:52 +010012475
12476
12477 /*
12478 *
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012479 * Register class Socket
12480 *
12481 */
12482
12483 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012484 lua_newtable(L);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012485
Ilya Shipitsind4259502020-04-08 01:07:56 +050012486 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012487 lua_pushstring(L, "__index");
12488 lua_newtable(L);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012489
Baptiste Assmann84bb4932015-03-02 21:40:06 +010012490#ifdef USE_OPENSSL
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012491 hlua_class_function(L, "connect_ssl", hlua_socket_connect_ssl);
Baptiste Assmann84bb4932015-03-02 21:40:06 +010012492#endif
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012493 hlua_class_function(L, "connect", hlua_socket_connect);
12494 hlua_class_function(L, "send", hlua_socket_send);
12495 hlua_class_function(L, "receive", hlua_socket_receive);
12496 hlua_class_function(L, "close", hlua_socket_close);
12497 hlua_class_function(L, "getpeername", hlua_socket_getpeername);
12498 hlua_class_function(L, "getsockname", hlua_socket_getsockname);
12499 hlua_class_function(L, "setoption", hlua_socket_setoption);
12500 hlua_class_function(L, "settimeout", hlua_socket_settimeout);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012501
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012502 lua_rawset(L, -3); /* Push the last 2 entries in the table at index -3 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012503
12504 /* Register the garbage collector entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012505 lua_pushstring(L, "__gc");
12506 lua_pushcclosure(L, hlua_socket_gc, 0);
12507 lua_rawset(L, -3); /* Push the last 2 entries in the table at index -3 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012508
12509 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012510 class_socket_ref = hlua_register_metatable(L, CLASS_SOCKET);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012511
Thierry Fournieraafc7772020-12-04 11:47:47 +010012512 lua_atpanic(L, hlua_panic_safe);
12513
12514 return L;
12515}
12516
12517void hlua_init(void) {
12518 int i;
Amaury Denoyelle239fdbf2021-03-24 10:22:03 +010012519 char *errmsg;
Thierry Fournieraafc7772020-12-04 11:47:47 +010012520#ifdef USE_OPENSSL
12521 struct srv_kw *kw;
12522 int tmp_error;
12523 char *error;
12524 char *args[] = { /* SSL client configuration. */
12525 "ssl",
12526 "verify",
12527 "none",
12528 NULL
12529 };
12530#endif
12531
12532 /* Init post init function list head */
12533 for (i = 0; i < MAX_THREADS + 1; i++)
12534 LIST_INIT(&hlua_init_functions[i]);
12535
12536 /* Init state for common/shared lua parts */
12537 hlua_state_id = 0;
Willy Tarreau43ab05b2021-09-28 09:43:11 +020012538 ha_set_thread(NULL);
Thierry Fournieraafc7772020-12-04 11:47:47 +010012539 hlua_states[0] = hlua_init_state(0);
12540
12541 /* Init state 1 for thread 0. We have at least one thread. */
12542 hlua_state_id = 1;
Willy Tarreau43ab05b2021-09-28 09:43:11 +020012543 ha_set_thread(NULL);
Thierry Fournieraafc7772020-12-04 11:47:47 +010012544 hlua_states[1] = hlua_init_state(1);
12545
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012546 /* Proxy and server configuration initialisation. */
William Lallemand6bb77b92021-07-28 15:48:16 +020012547 socket_proxy = alloc_new_proxy("LUA-SOCKET", PR_CAP_FE|PR_CAP_BE|PR_CAP_INT, &errmsg);
Amaury Denoyelle239fdbf2021-03-24 10:22:03 +010012548 if (!socket_proxy) {
12549 fprintf(stderr, "Lua init: %s\n", errmsg);
12550 exit(1);
12551 }
12552 proxy_preset_defaults(socket_proxy);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012553
12554 /* Init TCP server: unchanged parameters */
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010012555 socket_tcp = new_server(socket_proxy);
12556 if (!socket_tcp) {
12557 fprintf(stderr, "Lua init: failed to allocate tcp server socket\n");
12558 exit(1);
12559 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012560
12561#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012562 /* Init TCP server: unchanged parameters */
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010012563 socket_ssl = new_server(socket_proxy);
12564 if (!socket_ssl) {
12565 fprintf(stderr, "Lua init: failed to allocate ssl server socket\n");
12566 exit(1);
12567 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012568
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010012569 socket_ssl->use_ssl = 1;
12570 socket_ssl->xprt = xprt_get(XPRT_SSL);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012571
Bertrand Jacquin80839ff2021-01-21 19:14:46 +000012572 for (i = 0; args[i] != NULL; i++) {
12573 if ((kw = srv_find_kw(args[i])) != NULL) { /* Maybe it's registered server keyword */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012574 /*
12575 *
12576 * If the keyword is not known, we can search in the registered
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -080012577 * server keywords. This is useful to configure special SSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012578 * features like client certificates and ssl_verify.
12579 *
12580 */
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010012581 tmp_error = kw->parse(args, &i, socket_proxy, socket_ssl, &error);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012582 if (tmp_error != 0) {
12583 fprintf(stderr, "INTERNAL ERROR: %s\n", error);
12584 abort(); /* This must be never arrives because the command line
12585 not editable by the user. */
12586 }
Bertrand Jacquin80839ff2021-01-21 19:14:46 +000012587 i += kw->skip;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012588 }
12589 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012590#endif
Thierry Fournier75933d42016-01-21 09:30:18 +010012591
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +010012592}
Willy Tarreaubb57d942016-12-21 19:04:56 +010012593
Tim Duesterhusd0c0ca22020-07-04 11:53:26 +020012594static void hlua_deinit()
12595{
Willy Tarreau186f3762020-12-04 11:48:12 +010012596 int thr;
Christopher Faulet69c581a2021-05-31 08:54:04 +020012597 struct hlua_reg_filter *reg_flt, *reg_flt_bck;
12598
12599 list_for_each_entry_safe(reg_flt, reg_flt_bck, &referenced_filters, l)
12600 release_hlua_reg_filter(reg_flt);
Willy Tarreau186f3762020-12-04 11:48:12 +010012601
12602 for (thr = 0; thr < MAX_THREADS+1; thr++) {
12603 if (hlua_states[thr])
12604 lua_close(hlua_states[thr]);
12605 }
Willy Tarreau430bf4a2021-03-04 09:45:32 +010012606
Amaury Denoyellebc2ebfa2021-08-25 15:34:53 +020012607 srv_drop(socket_tcp);
Willy Tarreau430bf4a2021-03-04 09:45:32 +010012608
Willy Tarreau0f143af2021-03-05 10:41:48 +010012609#ifdef USE_OPENSSL
Amaury Denoyellebc2ebfa2021-08-25 15:34:53 +020012610 srv_drop(socket_ssl);
Willy Tarreau0f143af2021-03-05 10:41:48 +010012611#endif
Amaury Denoyelle239fdbf2021-03-24 10:22:03 +010012612
12613 free_proxy(socket_proxy);
Tim Duesterhusd0c0ca22020-07-04 11:53:26 +020012614}
12615
12616REGISTER_POST_DEINIT(hlua_deinit);
12617
Willy Tarreau80713382018-11-26 10:19:54 +010012618static void hlua_register_build_options(void)
12619{
Willy Tarreaubb57d942016-12-21 19:04:56 +010012620 char *ptr = NULL;
Willy Tarreau80713382018-11-26 10:19:54 +010012621
Willy Tarreaubb57d942016-12-21 19:04:56 +010012622 memprintf(&ptr, "Built with Lua version : %s", LUA_RELEASE);
12623 hap_register_build_opts(ptr, 1);
12624}
Willy Tarreau80713382018-11-26 10:19:54 +010012625
12626INITCALL0(STG_REGISTER, hlua_register_build_options);