blob: e323b9afa251715469cdfc3f822c89c3e705a0c6 [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 Faulet908628c2022-03-25 16:43:49 +010037#include <haproxy/conn_stream.h>
38#include <haproxy/cs_utils.h>
Christopher Faulet69c581a2021-05-31 08:54:04 +020039#include <haproxy/filters.h>
Willy Tarreau5413a872020-06-02 19:33:08 +020040#include <haproxy/h1.h>
Willy Tarreau86416052020-06-04 09:20:54 +020041#include <haproxy/hlua.h>
Willy Tarreau8c794002020-06-04 10:05:25 +020042#include <haproxy/hlua_fcn.h>
Willy Tarreauc2b1ff02020-06-04 21:21:03 +020043#include <haproxy/http_ana.h>
William Lallemand3956c4e2021-09-21 16:25:15 +020044#include <haproxy/http_client.h>
Willy Tarreau126ba3a2020-06-04 18:26:43 +020045#include <haproxy/http_fetch.h>
Willy Tarreaub2551052020-06-09 09:07:15 +020046#include <haproxy/http_htx.h>
Willy Tarreauc761f842020-06-04 11:40:28 +020047#include <haproxy/http_rules.h>
Willy Tarreau36979d92020-06-05 17:27:29 +020048#include <haproxy/log.h>
Willy Tarreau2cd58092020-06-04 15:10:43 +020049#include <haproxy/map.h>
Willy Tarreau8efbdfb2020-06-04 11:29:21 +020050#include <haproxy/obj_type.h>
Willy Tarreau225a90a2020-06-04 15:06:28 +020051#include <haproxy/pattern.h>
Willy Tarreau469509b2020-06-04 15:13:30 +020052#include <haproxy/payload.h>
Willy Tarreau3d6ee402021-05-08 20:28:07 +020053#include <haproxy/proxy.h>
Willy Tarreaub2551052020-06-09 09:07:15 +020054#include <haproxy/regex.h>
Willy Tarreaue6ce10b2020-06-04 15:33:47 +020055#include <haproxy/sample.h>
Willy Tarreau198e92a2021-03-05 10:23:32 +010056#include <haproxy/server.h>
Willy Tarreau48d25b32020-06-04 18:58:52 +020057#include <haproxy/session.h>
William Lallemand30fcca12022-03-30 12:03:12 +020058#include <haproxy/ssl_ckch.h>
59#include <haproxy/ssl_sock.h>
Willy Tarreau2eec9b52020-06-04 19:58:55 +020060#include <haproxy/stats-t.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)) {
508
509 /* Add separator */
Christopher Fauletd09cc512021-03-24 14:48:45 +0100510 if (b_data(msg))
511 chunk_appendf(msg, "%s", sep);
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200512
513 /* Fill fields:
514 * 'S': fills in the fields source, short_src, linedefined, lastlinedefined, and what;
515 * 'l': fills in the field currentline;
516 * 'n': fills in the field name and namewhat;
517 * 't': fills in the field istailcall;
518 */
519 lua_getinfo(L, "Slnt", &ar);
520
521 /* Append code localisation */
522 if (ar.currentline > 0)
Christopher Fauletd09cc512021-03-24 14:48:45 +0100523 chunk_appendf(msg, "%s:%d: ", ar.short_src, ar.currentline);
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200524 else
Christopher Fauletd09cc512021-03-24 14:48:45 +0100525 chunk_appendf(msg, "%s: ", ar.short_src);
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200526
527 /*
528 * Get function name
529 *
530 * if namewhat is no empty, name is defined.
531 * what contains "Lua" for Lua function, "C" for C function,
532 * or "main" for main code.
533 */
534 if (*ar.namewhat != '\0' && ar.name != NULL) /* is there a name from code? */
Christopher Fauletd09cc512021-03-24 14:48:45 +0100535 chunk_appendf(msg, "in %s '%s'", ar.namewhat, ar.name); /* use it */
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200536
537 else if (*ar.what == 'm') /* "main", the code is not executed in a function */
Christopher Fauletd09cc512021-03-24 14:48:45 +0100538 chunk_appendf(msg, "in main chunk");
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200539
540 else if (*ar.what != 'C') /* for Lua functions, use <file:line> */
Christopher Fauletd09cc512021-03-24 14:48:45 +0100541 chunk_appendf(msg, "in function line %d", ar.linedefined);
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200542
543 else /* nothing left... */
544 chunk_appendf(msg, "?");
545
546
547 /* Display tailed call */
548 if (ar.istailcall)
549 chunk_appendf(msg, " ...");
550 }
551
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200552 return msg->area;
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200553}
554
555
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100556/* This function check the number of arguments available in the
557 * stack. If the number of arguments available is not the same
Ilya Shipitsinc02a23f2020-05-06 00:53:22 +0500558 * then <nb> an error is thrown.
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100559 */
560__LJMP static inline void check_args(lua_State *L, int nb, char *fcn)
561{
562 if (lua_gettop(L) == nb)
563 return;
564 WILL_LJMP(luaL_error(L, "'%s' needs %d arguments", fcn, nb));
565}
566
Mark Lakes22154b42018-01-29 14:38:40 -0800567/* This function pushes an error string prefixed by the file name
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100568 * and the line number where the error is encountered.
569 */
570static int hlua_pusherror(lua_State *L, const char *fmt, ...)
571{
572 va_list argp;
573 va_start(argp, fmt);
574 luaL_where(L, 1);
575 lua_pushvfstring(L, fmt, argp);
576 va_end(argp);
577 lua_concat(L, 2);
578 return 1;
579}
580
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100581/* This functions is used with sample fetch and converters. It
582 * converts the HAProxy configuration argument in a lua stack
583 * values.
584 *
585 * It takes an array of "arg", and each entry of the array is
586 * converted and pushed in the LUA stack.
587 */
588static int hlua_arg2lua(lua_State *L, const struct arg *arg)
589{
590 switch (arg->type) {
591 case ARGT_SINT:
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100592 case ARGT_TIME:
593 case ARGT_SIZE:
Thierry FOURNIERf90838b2015-03-06 13:48:32 +0100594 lua_pushinteger(L, arg->data.sint);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100595 break;
596
597 case ARGT_STR:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200598 lua_pushlstring(L, arg->data.str.area, arg->data.str.data);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100599 break;
600
601 case ARGT_IPV4:
602 case ARGT_IPV6:
603 case ARGT_MSK4:
604 case ARGT_MSK6:
605 case ARGT_FE:
606 case ARGT_BE:
607 case ARGT_TAB:
608 case ARGT_SRV:
609 case ARGT_USR:
610 case ARGT_MAP:
611 default:
612 lua_pushnil(L);
613 break;
614 }
615 return 1;
616}
617
Ilya Shipitsinc02a23f2020-05-06 00:53:22 +0500618/* This function take one entry in an LUA stack at the index "ud",
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100619 * and try to convert it in an HAProxy argument entry. This is useful
Ilya Shipitsind4259502020-04-08 01:07:56 +0500620 * with sample fetch wrappers. The input arguments are given to the
621 * lua wrapper and converted as arg list by the function.
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100622 */
623static int hlua_lua2arg(lua_State *L, int ud, struct arg *arg)
624{
625 switch (lua_type(L, ud)) {
626
627 case LUA_TNUMBER:
628 case LUA_TBOOLEAN:
629 arg->type = ARGT_SINT;
630 arg->data.sint = lua_tointeger(L, ud);
631 break;
632
633 case LUA_TSTRING:
634 arg->type = ARGT_STR;
Tim Duesterhus2e89dec2019-09-29 23:03:08 +0200635 arg->data.str.area = (char *)lua_tolstring(L, ud, &arg->data.str.data);
Tim Duesterhus29d2e8a2019-09-29 23:03:07 +0200636 /* We don't know the actual size of the underlying allocation, so be conservative. */
Christopher Fauletfdea1b62020-08-06 08:29:18 +0200637 arg->data.str.size = arg->data.str.data+1; /* count the terminating null byte */
Tim Duesterhus29d2e8a2019-09-29 23:03:07 +0200638 arg->data.str.head = 0;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100639 break;
640
641 case LUA_TUSERDATA:
642 case LUA_TNIL:
643 case LUA_TTABLE:
644 case LUA_TFUNCTION:
645 case LUA_TTHREAD:
646 case LUA_TLIGHTUSERDATA:
647 arg->type = ARGT_SINT;
Thierry FOURNIERbf65cd42015-07-20 17:45:02 +0200648 arg->data.sint = 0;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100649 break;
650 }
651 return 1;
652}
653
654/* the following functions are used to convert a struct sample
655 * in Lua type. This useful to convert the return of the
Ilya Shipitsind4259502020-04-08 01:07:56 +0500656 * fetches or converters.
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100657 */
Willy Tarreau5eadada2015-03-10 17:28:54 +0100658static int hlua_smp2lua(lua_State *L, struct sample *smp)
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100659{
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200660 switch (smp->data.type) {
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100661 case SMP_T_SINT:
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100662 case SMP_T_BOOL:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200663 lua_pushinteger(L, smp->data.u.sint);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100664 break;
665
666 case SMP_T_BIN:
667 case SMP_T_STR:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200668 lua_pushlstring(L, smp->data.u.str.area, smp->data.u.str.data);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100669 break;
670
671 case SMP_T_METH:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200672 switch (smp->data.u.meth.meth) {
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100673 case HTTP_METH_OPTIONS: lua_pushstring(L, "OPTIONS"); break;
674 case HTTP_METH_GET: lua_pushstring(L, "GET"); break;
675 case HTTP_METH_HEAD: lua_pushstring(L, "HEAD"); break;
676 case HTTP_METH_POST: lua_pushstring(L, "POST"); break;
677 case HTTP_METH_PUT: lua_pushstring(L, "PUT"); break;
678 case HTTP_METH_DELETE: lua_pushstring(L, "DELETE"); break;
679 case HTTP_METH_TRACE: lua_pushstring(L, "TRACE"); break;
680 case HTTP_METH_CONNECT: lua_pushstring(L, "CONNECT"); break;
681 case HTTP_METH_OTHER:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200682 lua_pushlstring(L, smp->data.u.meth.str.area, smp->data.u.meth.str.data);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100683 break;
684 default:
685 lua_pushnil(L);
686 break;
687 }
688 break;
689
690 case SMP_T_IPV4:
691 case SMP_T_IPV6:
692 case SMP_T_ADDR: /* This type is never used to qualify a sample. */
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200693 if (sample_casts[smp->data.type][SMP_T_STR] &&
694 sample_casts[smp->data.type][SMP_T_STR](smp))
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200695 lua_pushlstring(L, smp->data.u.str.area, smp->data.u.str.data);
Willy Tarreau5eadada2015-03-10 17:28:54 +0100696 else
697 lua_pushnil(L);
698 break;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100699 default:
700 lua_pushnil(L);
701 break;
702 }
703 return 1;
704}
705
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100706/* the following functions are used to convert a struct sample
707 * in Lua strings. This is useful to convert the return of the
Ilya Shipitsind4259502020-04-08 01:07:56 +0500708 * fetches or converters.
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100709 */
710static int hlua_smp2lua_str(lua_State *L, struct sample *smp)
711{
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200712 switch (smp->data.type) {
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100713
714 case SMP_T_BIN:
715 case SMP_T_STR:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200716 lua_pushlstring(L, smp->data.u.str.area, smp->data.u.str.data);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100717 break;
718
719 case SMP_T_METH:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200720 switch (smp->data.u.meth.meth) {
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100721 case HTTP_METH_OPTIONS: lua_pushstring(L, "OPTIONS"); break;
722 case HTTP_METH_GET: lua_pushstring(L, "GET"); break;
723 case HTTP_METH_HEAD: lua_pushstring(L, "HEAD"); break;
724 case HTTP_METH_POST: lua_pushstring(L, "POST"); break;
725 case HTTP_METH_PUT: lua_pushstring(L, "PUT"); break;
726 case HTTP_METH_DELETE: lua_pushstring(L, "DELETE"); break;
727 case HTTP_METH_TRACE: lua_pushstring(L, "TRACE"); break;
728 case HTTP_METH_CONNECT: lua_pushstring(L, "CONNECT"); break;
729 case HTTP_METH_OTHER:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200730 lua_pushlstring(L, smp->data.u.meth.str.area, smp->data.u.meth.str.data);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100731 break;
732 default:
733 lua_pushstring(L, "");
734 break;
735 }
736 break;
737
738 case SMP_T_SINT:
739 case SMP_T_BOOL:
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100740 case SMP_T_IPV4:
741 case SMP_T_IPV6:
742 case SMP_T_ADDR: /* This type is never used to qualify a sample. */
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200743 if (sample_casts[smp->data.type][SMP_T_STR] &&
744 sample_casts[smp->data.type][SMP_T_STR](smp))
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200745 lua_pushlstring(L, smp->data.u.str.area, smp->data.u.str.data);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100746 else
747 lua_pushstring(L, "");
748 break;
749 default:
750 lua_pushstring(L, "");
751 break;
752 }
753 return 1;
754}
755
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100756/* the following functions are used to convert an Lua type in a
757 * struct sample. This is useful to provide data from a converter
758 * to the LUA code.
759 */
760static int hlua_lua2smp(lua_State *L, int ud, struct sample *smp)
761{
762 switch (lua_type(L, ud)) {
763
764 case LUA_TNUMBER:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200765 smp->data.type = SMP_T_SINT;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200766 smp->data.u.sint = lua_tointeger(L, ud);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100767 break;
768
769
770 case LUA_TBOOLEAN:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200771 smp->data.type = SMP_T_BOOL;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200772 smp->data.u.sint = lua_toboolean(L, ud);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100773 break;
774
775 case LUA_TSTRING:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200776 smp->data.type = SMP_T_STR;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100777 smp->flags |= SMP_F_CONST;
Tim Duesterhus2e89dec2019-09-29 23:03:08 +0200778 smp->data.u.str.area = (char *)lua_tolstring(L, ud, &smp->data.u.str.data);
Tim Duesterhus29d2e8a2019-09-29 23:03:07 +0200779 /* We don't know the actual size of the underlying allocation, so be conservative. */
Christopher Fauletfdea1b62020-08-06 08:29:18 +0200780 smp->data.u.str.size = smp->data.u.str.data+1; /* count the terminating null byte */
Tim Duesterhus29d2e8a2019-09-29 23:03:07 +0200781 smp->data.u.str.head = 0;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100782 break;
783
784 case LUA_TUSERDATA:
785 case LUA_TNIL:
786 case LUA_TTABLE:
787 case LUA_TFUNCTION:
788 case LUA_TTHREAD:
789 case LUA_TLIGHTUSERDATA:
Thierry FOURNIER93405e12015-08-26 14:19:03 +0200790 case LUA_TNONE:
791 default:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200792 smp->data.type = SMP_T_BOOL;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200793 smp->data.u.sint = 0;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100794 break;
795 }
796 return 1;
797}
798
Ilya Shipitsind4259502020-04-08 01:07:56 +0500799/* This function check the "argp" built by another conversion function
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -0800800 * is in accord with the expected argp defined by the "mask". The function
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100801 * returns true or false. It can be adjust the types if there compatibles.
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100802 *
Ilya Shipitsinc02a23f2020-05-06 00:53:22 +0500803 * This function assumes that the argp argument contains ARGM_NBARGS + 1
Willy Tarreauee0d7272021-07-16 10:26:56 +0200804 * entries and that there is at least one stop at the last position.
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100805 */
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100806__LJMP int hlua_lua2arg_check(lua_State *L, int first, struct arg *argp,
David Carlier0c437f42016-04-27 16:21:56 +0100807 uint64_t mask, struct proxy *p)
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100808{
809 int min_arg;
Willy Tarreauee0d7272021-07-16 10:26:56 +0200810 int idx;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100811 struct proxy *px;
Christopher Fauletd25d9262020-08-06 11:04:46 +0200812 struct userlist *ul;
Christopher Fauletfd2e9062020-08-06 11:10:57 +0200813 struct my_regex *reg;
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200814 const char *msg = NULL;
Christopher Fauletfd2e9062020-08-06 11:10:57 +0200815 char *sname, *pname, *err = NULL;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100816
817 idx = 0;
818 min_arg = ARGM(mask);
819 mask >>= ARGM_BITS;
820
821 while (1) {
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200822 struct buffer tmp = BUF_NULL;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100823
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100824 /* Check for mandatory arguments. */
825 if (argp[idx].type == ARGT_STOP) {
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100826 if (idx < min_arg) {
827
828 /* If miss other argument than the first one, we return an error. */
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200829 if (idx > 0) {
830 msg = "Mandatory argument expected";
831 goto error;
832 }
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100833
834 /* If first argument have a certain type, some default values
835 * may be used. See the function smp_resolve_args().
836 */
837 switch (mask & ARGT_MASK) {
838
839 case ARGT_FE:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200840 if (!(p->cap & PR_CAP_FE)) {
841 msg = "Mandatory argument expected";
842 goto error;
843 }
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100844 argp[idx].data.prx = p;
845 argp[idx].type = ARGT_FE;
846 argp[idx+1].type = ARGT_STOP;
847 break;
848
849 case ARGT_BE:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200850 if (!(p->cap & PR_CAP_BE)) {
851 msg = "Mandatory argument expected";
852 goto error;
853 }
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100854 argp[idx].data.prx = p;
855 argp[idx].type = ARGT_BE;
856 argp[idx+1].type = ARGT_STOP;
857 break;
858
859 case ARGT_TAB:
860 argp[idx].data.prx = p;
861 argp[idx].type = ARGT_TAB;
862 argp[idx+1].type = ARGT_STOP;
863 break;
864
865 default:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200866 msg = "Mandatory argument expected";
867 goto error;
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100868 break;
869 }
870 }
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200871 break;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100872 }
873
Ilya Shipitsin856aabc2020-04-16 23:51:34 +0500874 /* Check for exceed the number of required argument. */
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100875 if ((mask & ARGT_MASK) == ARGT_STOP &&
876 argp[idx].type != ARGT_STOP) {
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200877 msg = "Last argument expected";
878 goto error;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100879 }
880
881 if ((mask & ARGT_MASK) == ARGT_STOP &&
882 argp[idx].type == ARGT_STOP) {
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200883 break;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100884 }
885
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200886 /* Convert some argument types. All string in argp[] are for not
887 * duplicated yet.
888 */
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100889 switch (mask & ARGT_MASK) {
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100890 case ARGT_SINT:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200891 if (argp[idx].type != ARGT_SINT) {
892 msg = "integer expected";
893 goto error;
894 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100895 argp[idx].type = ARGT_SINT;
896 break;
897
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100898 case ARGT_TIME:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200899 if (argp[idx].type != ARGT_SINT) {
900 msg = "integer expected";
901 goto error;
902 }
Thierry FOURNIER29176f32015-07-07 00:41:29 +0200903 argp[idx].type = ARGT_TIME;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100904 break;
905
906 case ARGT_SIZE:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200907 if (argp[idx].type != ARGT_SINT) {
908 msg = "integer expected";
909 goto error;
910 }
Thierry FOURNIER29176f32015-07-07 00:41:29 +0200911 argp[idx].type = ARGT_SIZE;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100912 break;
913
914 case ARGT_FE:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200915 if (argp[idx].type != ARGT_STR) {
916 msg = "string expected";
917 goto error;
918 }
Christopher Fauletfdea1b62020-08-06 08:29:18 +0200919 argp[idx].data.prx = proxy_fe_by_name(argp[idx].data.str.area);
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200920 if (!argp[idx].data.prx) {
921 msg = "frontend doesn't exist";
922 goto error;
923 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100924 argp[idx].type = ARGT_FE;
925 break;
926
927 case ARGT_BE:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200928 if (argp[idx].type != ARGT_STR) {
929 msg = "string expected";
930 goto error;
931 }
Christopher Fauletfdea1b62020-08-06 08:29:18 +0200932 argp[idx].data.prx = proxy_be_by_name(argp[idx].data.str.area);
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200933 if (!argp[idx].data.prx) {
934 msg = "backend doesn't exist";
935 goto error;
936 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100937 argp[idx].type = ARGT_BE;
938 break;
939
940 case ARGT_TAB:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200941 if (argp[idx].type != ARGT_STR) {
942 msg = "string expected";
943 goto error;
944 }
Christopher Fauletfdea1b62020-08-06 08:29:18 +0200945 argp[idx].data.t = stktable_find_by_name(argp[idx].data.str.area);
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200946 if (!argp[idx].data.t) {
947 msg = "table doesn't exist";
948 goto error;
949 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100950 argp[idx].type = ARGT_TAB;
951 break;
952
953 case ARGT_SRV:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200954 if (argp[idx].type != ARGT_STR) {
955 msg = "string expected";
956 goto error;
957 }
Christopher Fauletfdea1b62020-08-06 08:29:18 +0200958 sname = strrchr(argp[idx].data.str.area, '/');
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100959 if (sname) {
960 *sname++ = '\0';
Christopher Fauletfdea1b62020-08-06 08:29:18 +0200961 pname = argp[idx].data.str.area;
Willy Tarreau9e0bb102015-05-26 11:24:42 +0200962 px = proxy_be_by_name(pname);
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200963 if (!px) {
964 msg = "backend doesn't exist";
965 goto error;
966 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100967 }
968 else {
Christopher Fauletfdea1b62020-08-06 08:29:18 +0200969 sname = argp[idx].data.str.area;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100970 px = p;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100971 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100972 argp[idx].data.srv = findserver(px, sname);
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200973 if (!argp[idx].data.srv) {
974 msg = "server doesn't exist";
975 goto error;
976 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100977 argp[idx].type = ARGT_SRV;
978 break;
979
980 case ARGT_IPV4:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200981 if (argp[idx].type != ARGT_STR) {
982 msg = "string expected";
983 goto error;
984 }
985 if (inet_pton(AF_INET, argp[idx].data.str.area, &argp[idx].data.ipv4)) {
986 msg = "invalid IPv4 address";
987 goto error;
988 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100989 argp[idx].type = ARGT_IPV4;
990 break;
991
992 case ARGT_MSK4:
Christopher Faulete663a6e2020-08-07 09:11:22 +0200993 if (argp[idx].type == ARGT_SINT)
994 len2mask4(argp[idx].data.sint, &argp[idx].data.ipv4);
995 else if (argp[idx].type == ARGT_STR) {
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200996 if (!str2mask(argp[idx].data.str.area, &argp[idx].data.ipv4)) {
997 msg = "invalid IPv4 mask";
998 goto error;
999 }
1000 }
1001 else {
1002 msg = "integer or string expected";
1003 goto error;
Christopher Faulete663a6e2020-08-07 09:11:22 +02001004 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001005 argp[idx].type = ARGT_MSK4;
1006 break;
1007
1008 case ARGT_IPV6:
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001009 if (argp[idx].type != ARGT_STR) {
1010 msg = "string expected";
1011 goto error;
1012 }
1013 if (inet_pton(AF_INET6, argp[idx].data.str.area, &argp[idx].data.ipv6)) {
1014 msg = "invalid IPv6 address";
1015 goto error;
1016 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001017 argp[idx].type = ARGT_IPV6;
1018 break;
1019
1020 case ARGT_MSK6:
Christopher Faulete663a6e2020-08-07 09:11:22 +02001021 if (argp[idx].type == ARGT_SINT)
1022 len2mask6(argp[idx].data.sint, &argp[idx].data.ipv6);
1023 else if (argp[idx].type == ARGT_STR) {
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001024 if (!str2mask6(argp[idx].data.str.area, &argp[idx].data.ipv6)) {
1025 msg = "invalid IPv6 mask";
1026 goto error;
1027 }
1028 }
1029 else {
1030 msg = "integer or string expected";
1031 goto error;
Christopher Faulete663a6e2020-08-07 09:11:22 +02001032 }
Tim Duesterhusb814da62018-01-25 16:24:50 +01001033 argp[idx].type = ARGT_MSK6;
1034 break;
1035
Christopher Fauletfd2e9062020-08-06 11:10:57 +02001036 case ARGT_REG:
1037 if (argp[idx].type != ARGT_STR) {
1038 msg = "string expected";
1039 goto error;
1040 }
1041 reg = regex_comp(argp[idx].data.str.area, !(argp[idx].type_flags & ARGF_REG_ICASE), 1, &err);
1042 if (!reg) {
1043 msg = lua_pushfstring(L, "error compiling regex '%s' : '%s'",
1044 argp[idx].data.str.area, err);
1045 free(err);
1046 goto error;
1047 }
1048 argp[idx].type = ARGT_REG;
1049 argp[idx].data.reg = reg;
1050 break;
1051
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001052 case ARGT_USR:
Christopher Fauletd25d9262020-08-06 11:04:46 +02001053 if (argp[idx].type != ARGT_STR) {
1054 msg = "string expected";
1055 goto error;
1056 }
1057 if (p->uri_auth && p->uri_auth->userlist &&
Tim Duesterhuse5ff1412021-01-02 22:31:53 +01001058 strcmp(p->uri_auth->userlist->name, argp[idx].data.str.area) == 0)
Christopher Fauletd25d9262020-08-06 11:04:46 +02001059 ul = p->uri_auth->userlist;
1060 else
1061 ul = auth_find_userlist(argp[idx].data.str.area);
1062
1063 if (!ul) {
1064 msg = lua_pushfstring(L, "unable to find userlist '%s'", argp[idx].data.str.area);
1065 goto error;
1066 }
1067 argp[idx].type = ARGT_USR;
1068 argp[idx].data.usr = ul;
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001069 break;
1070
1071 case ARGT_STR:
1072 if (!chunk_dup(&tmp, &argp[idx].data.str)) {
1073 msg = "unable to duplicate string arg";
1074 goto error;
1075 }
1076 argp[idx].data.str = tmp;
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001077 break;
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001078
Christopher Fauletd25d9262020-08-06 11:04:46 +02001079 case ARGT_MAP:
Christopher Fauletd25d9262020-08-06 11:04:46 +02001080 msg = "type not yet supported";
1081 goto error;
1082 break;
1083
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001084 }
1085
1086 /* Check for type of argument. */
1087 if ((mask & ARGT_MASK) != argp[idx].type) {
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001088 msg = lua_pushfstring(L, "'%s' expected, got '%s'",
1089 arg_type_names[(mask & ARGT_MASK)],
1090 arg_type_names[argp[idx].type & ARGT_MASK]);
1091 goto error;
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001092 }
1093
1094 /* Next argument. */
1095 mask >>= ARGT_BITS;
1096 idx++;
1097 }
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001098 return 0;
1099
1100 error:
Willy Tarreauee0d7272021-07-16 10:26:56 +02001101 free_args(argp);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001102 WILL_LJMP(luaL_argerror(L, first + idx, msg));
1103 return 0; /* Never reached */
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001104}
1105
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001106/*
Ilya Shipitsinc02a23f2020-05-06 00:53:22 +05001107 * The following functions are used to make correspondence between the the
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001108 * executed lua pointer and the "struct hlua *" that contain the context.
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001109 *
1110 * - hlua_gethlua : return the hlua context associated with an lua_State.
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001111 * - hlua_sethlua : create the association between hlua context and lua_state.
1112 */
1113static inline struct hlua *hlua_gethlua(lua_State *L)
1114{
Thierry FOURNIER38c5fd62015-03-10 02:40:29 +01001115 struct hlua **hlua = lua_getextraspace(L);
1116 return *hlua;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001117}
1118static inline void hlua_sethlua(struct hlua *hlua)
1119{
Thierry FOURNIER38c5fd62015-03-10 02:40:29 +01001120 struct hlua **hlua_store = lua_getextraspace(hlua->T);
1121 *hlua_store = hlua;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001122}
1123
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01001124/* This function is used to send logs. It try to send on screen (stderr)
1125 * and on the default syslog server.
1126 */
1127static inline void hlua_sendlog(struct proxy *px, int level, const char *msg)
1128{
1129 struct tm tm;
1130 char *p;
1131
1132 /* Cleanup the log message. */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001133 p = trash.area;
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01001134 for (; *msg != '\0'; msg++, p++) {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001135 if (p >= trash.area + trash.size - 1) {
Thierry FOURNIERccf00632015-09-16 12:47:03 +02001136 /* Break the message if exceed the buffer size. */
1137 *(p-4) = ' ';
1138 *(p-3) = '.';
1139 *(p-2) = '.';
1140 *(p-1) = '.';
1141 break;
1142 }
Willy Tarreau90807112020-02-25 08:16:33 +01001143 if (isprint((unsigned char)*msg))
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01001144 *p = *msg;
1145 else
1146 *p = '.';
1147 }
1148 *p = '\0';
1149
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001150 send_log(px, level, "%s\n", trash.area);
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01001151 if (!(global.mode & MODE_QUIET) || (global.mode & (MODE_VERBOSE | MODE_STARTING))) {
Christopher Fauletf98d8212020-10-02 18:13:52 +02001152 if (level == LOG_DEBUG && !(global.mode & MODE_DEBUG))
1153 return;
1154
Willy Tarreaua678b432015-08-28 10:14:59 +02001155 get_localtime(date.tv_sec, &tm);
1156 fprintf(stderr, "[%s] %03d/%02d%02d%02d (%d) : %s\n",
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01001157 log_levels[level], tm.tm_yday, tm.tm_hour, tm.tm_min, tm.tm_sec,
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001158 (int)getpid(), trash.area);
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01001159 fflush(stderr);
1160 }
1161}
1162
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001163/* This function just ensure that the yield will be always
1164 * returned with a timeout and permit to set some flags
1165 */
1166__LJMP void hlua_yieldk(lua_State *L, int nresults, int ctx,
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001167 lua_KFunction k, int timeout, unsigned int flags)
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001168{
Thierry Fournier4234dbd2020-11-28 13:18:23 +01001169 struct hlua *hlua;
1170
1171 /* Get hlua struct, or NULL if we execute from main lua state */
1172 hlua = hlua_gethlua(L);
1173 if (!hlua) {
1174 return;
1175 }
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001176
1177 /* Set the wake timeout. If timeout is required, we set
1178 * the expiration time.
1179 */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001180 hlua->wake_time = timeout;
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001181
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01001182 hlua->flags |= flags;
1183
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001184 /* Process the yield. */
Willy Tarreau9635e032018-10-16 17:52:55 +02001185 MAY_LJMP(lua_yieldk(L, nresults, ctx, k));
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001186}
1187
Willy Tarreau87b09662015-04-03 00:22:06 +02001188/* This function initialises the Lua environment stored in the stream.
1189 * It must be called at the start of the stream. This function creates
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001190 * an LUA coroutine. It can not be use to crete the main LUA context.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02001191 *
1192 * This function is particular. it initialises a new Lua thread. If the
1193 * initialisation fails (example: out of memory error), the lua function
1194 * throws an error (longjmp).
1195 *
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +01001196 * In some case (at least one), this function can be called from safe
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001197 * environment, so we must not initialise it. While the support of
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +01001198 * threads appear, the safe environment set a lock to ensure only one
1199 * Lua execution at a time. If we initialize safe environment in another
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001200 * safe environment, we have a dead lock.
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +01001201 *
1202 * set "already_safe" true if the context is initialized form safe
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001203 * Lua function.
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +01001204 *
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001205 * This function manipulates two Lua stacks: the main and the thread. Only
Thierry FOURNIERbabae282015-09-17 11:36:37 +02001206 * the main stack can fail. The thread is not manipulated. This function
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001207 * MUST NOT manipulate the created thread stack state, because it is not
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001208 * protected against errors thrown by the thread stack.
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001209 */
Thierry Fournier021d9862020-11-28 23:42:03 +01001210int hlua_ctx_init(struct hlua *lua, int state_id, struct task *task, int already_safe)
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001211{
1212 lua->Mref = LUA_REFNIL;
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001213 lua->flags = 0;
Willy Tarreauf31af932020-01-14 09:59:38 +01001214 lua->gc_count = 0;
Christopher Fauletbc275a92020-02-26 14:55:16 +01001215 lua->wake_time = TICK_ETERNITY;
Thierry Fournier021d9862020-11-28 23:42:03 +01001216 lua->state_id = state_id;
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01001217 LIST_INIT(&lua->com);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001218 if (!already_safe) {
1219 if (!SET_SAFE_LJMP_PARENT(lua)) {
1220 lua->Tref = LUA_REFNIL;
1221 return 0;
1222 }
1223 }
Thierry Fournier021d9862020-11-28 23:42:03 +01001224 lua->T = lua_newthread(hlua_states[state_id]);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001225 if (!lua->T) {
1226 lua->Tref = LUA_REFNIL;
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +01001227 if (!already_safe)
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001228 RESET_SAFE_LJMP_PARENT(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001229 return 0;
1230 }
1231 hlua_sethlua(lua);
Thierry Fournier021d9862020-11-28 23:42:03 +01001232 lua->Tref = luaL_ref(hlua_states[state_id], LUA_REGISTRYINDEX);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001233 lua->task = task;
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +01001234 if (!already_safe)
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001235 RESET_SAFE_LJMP_PARENT(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001236 return 1;
1237}
1238
Willy Tarreau87b09662015-04-03 00:22:06 +02001239/* Used to destroy the Lua coroutine when the attached stream or task
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001240 * is destroyed. The destroy also the memory context. The struct "lua"
1241 * is not freed.
1242 */
1243void hlua_ctx_destroy(struct hlua *lua)
1244{
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01001245 if (!lua)
Thierry FOURNIERa718b292015-03-04 16:48:34 +01001246 return;
1247
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01001248 if (!lua->T)
1249 goto end;
1250
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01001251 /* Purge all the pending signals. */
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001252 notification_purge(&lua->com);
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01001253
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001254 if (!SET_SAFE_LJMP(lua))
Thierry FOURNIER75d02082017-07-12 13:41:33 +02001255 return;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001256 luaL_unref(lua->T, LUA_REGISTRYINDEX, lua->Mref);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001257 RESET_SAFE_LJMP(lua);
Thierry FOURNIER5a50a852015-09-23 16:59:28 +02001258
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001259 if (!SET_SAFE_LJMP_PARENT(lua))
Thierry FOURNIER75d02082017-07-12 13:41:33 +02001260 return;
Thierry Fournier021d9862020-11-28 23:42:03 +01001261 luaL_unref(hlua_states[lua->state_id], LUA_REGISTRYINDEX, lua->Tref);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001262 RESET_SAFE_LJMP_PARENT(lua);
Thierry FOURNIER5a50a852015-09-23 16:59:28 +02001263 /* Forces a garbage collecting process. If the Lua program is finished
1264 * without error, we run the GC on the thread pointer. Its freed all
1265 * the unused memory.
1266 * If the thread is finnish with an error or is currently yielded,
1267 * it seems that the GC applied on the thread doesn't clean anything,
1268 * so e run the GC on the main thread.
1269 * NOTE: maybe this action locks all the Lua threads untiml the en of
1270 * the garbage collection.
1271 */
Willy Tarreauf31af932020-01-14 09:59:38 +01001272 if (lua->gc_count) {
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001273 if (!SET_SAFE_LJMP_PARENT(lua))
Thierry FOURNIER75d02082017-07-12 13:41:33 +02001274 return;
Thierry Fournier021d9862020-11-28 23:42:03 +01001275 lua_gc(hlua_states[lua->state_id], LUA_GCCOLLECT, 0);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001276 RESET_SAFE_LJMP_PARENT(lua);
Thierry FOURNIER7c39ab42015-09-27 22:53:33 +02001277 }
Thierry FOURNIER5a50a852015-09-23 16:59:28 +02001278
Thierry FOURNIERa7b536b2015-09-21 22:50:24 +02001279 lua->T = NULL;
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01001280
1281end:
Willy Tarreaubafbe012017-11-24 17:34:44 +01001282 pool_free(pool_head_hlua, lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001283}
1284
1285/* This function is used to restore the Lua context when a coroutine
1286 * fails. This function copy the common memory between old coroutine
1287 * and the new coroutine. The old coroutine is destroyed, and its
1288 * replaced by the new coroutine.
1289 * If the flag "keep_msg" is set, the last entry of the old is assumed
1290 * as string error message and it is copied in the new stack.
1291 */
1292static int hlua_ctx_renew(struct hlua *lua, int keep_msg)
1293{
1294 lua_State *T;
1295 int new_ref;
1296
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001297 /* New Lua coroutine. */
Thierry Fournier021d9862020-11-28 23:42:03 +01001298 T = lua_newthread(hlua_states[lua->state_id]);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001299 if (!T)
1300 return 0;
1301
1302 /* Copy last error message. */
1303 if (keep_msg)
1304 lua_xmove(lua->T, T, 1);
1305
1306 /* Copy data between the coroutines. */
1307 lua_rawgeti(lua->T, LUA_REGISTRYINDEX, lua->Mref);
1308 lua_xmove(lua->T, T, 1);
Ilya Shipitsin46a030c2020-07-05 16:36:08 +05001309 new_ref = luaL_ref(T, LUA_REGISTRYINDEX); /* Value popped. */
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001310
1311 /* Destroy old data. */
1312 luaL_unref(lua->T, LUA_REGISTRYINDEX, lua->Mref);
1313
1314 /* The thread is garbage collected by Lua. */
Thierry Fournier021d9862020-11-28 23:42:03 +01001315 luaL_unref(hlua_states[lua->state_id], LUA_REGISTRYINDEX, lua->Tref);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001316
1317 /* Fill the struct with the new coroutine values. */
1318 lua->Mref = new_ref;
1319 lua->T = T;
Thierry Fournier021d9862020-11-28 23:42:03 +01001320 lua->Tref = luaL_ref(hlua_states[lua->state_id], LUA_REGISTRYINDEX);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001321
1322 /* Set context. */
1323 hlua_sethlua(lua);
1324
1325 return 1;
1326}
1327
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001328void hlua_hook(lua_State *L, lua_Debug *ar)
1329{
Thierry Fournier4234dbd2020-11-28 13:18:23 +01001330 struct hlua *hlua;
1331
1332 /* Get hlua struct, or NULL if we execute from main lua state */
1333 hlua = hlua_gethlua(L);
1334 if (!hlua)
1335 return;
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001336
1337 /* Lua cannot yield when its returning from a function,
1338 * so, we can fix the interrupt hook to 1 instruction,
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001339 * expecting that the function is finished.
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001340 */
1341 if (lua_gethookmask(L) & LUA_MASKRET) {
1342 lua_sethook(hlua->T, hlua_hook, LUA_MASKCOUNT, 1);
1343 return;
1344 }
1345
1346 /* restore the interrupt condition. */
1347 lua_sethook(hlua->T, hlua_hook, LUA_MASKCOUNT, hlua_nb_instruction);
1348
1349 /* If we interrupt the Lua processing in yieldable state, we yield.
1350 * If the state is not yieldable, trying yield causes an error.
1351 */
1352 if (lua_isyieldable(L))
Willy Tarreau9635e032018-10-16 17:52:55 +02001353 MAY_LJMP(hlua_yieldk(L, 0, 0, NULL, TICK_ETERNITY, HLUA_CTRLYIELD));
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001354
Thierry FOURNIERa85cfb12015-03-13 14:50:06 +01001355 /* If we cannot yield, update the clock and check the timeout. */
Willy Tarreau55542642021-10-08 09:33:24 +02001356 clock_update_date(0, 1);
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001357 hlua->run_time += now_ms - hlua->start_time;
1358 if (hlua->max_time && hlua->run_time >= hlua->max_time) {
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001359 lua_pushfstring(L, "execution timeout");
1360 WILL_LJMP(lua_error(L));
1361 }
1362
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001363 /* Update the start time. */
1364 hlua->start_time = now_ms;
1365
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001366 /* Try to interrupt the process at the end of the current
1367 * unyieldable function.
1368 */
1369 lua_sethook(hlua->T, hlua_hook, LUA_MASKRET|LUA_MASKCOUNT, hlua_nb_instruction);
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001370}
1371
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001372/* This function start or resumes the Lua stack execution. If the flag
1373 * "yield_allowed" if no set and the LUA stack execution returns a yield
1374 * The function return an error.
1375 *
1376 * The function can returns 4 values:
1377 * - HLUA_E_OK : The execution is terminated without any errors.
1378 * - HLUA_E_AGAIN : The execution must continue at the next associated
1379 * task wakeup.
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001380 * - HLUA_E_ERRMSG : An error has occurred, an error message is set in
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001381 * the top of the stack.
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001382 * - HLUA_E_ERR : An error has occurred without error message.
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001383 *
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001384 * If an error occurred, the stack is renewed and it is ready to run new
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001385 * LUA code.
1386 */
1387static enum hlua_exec hlua_ctx_resume(struct hlua *lua, int yield_allowed)
1388{
Christopher Faulet08ed98f2020-07-28 10:33:25 +02001389#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM >= 504
1390 int nres;
1391#endif
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001392 int ret;
1393 const char *msg;
Thierry FOURNIERfc044c92018-06-07 14:40:48 +02001394 const char *trace;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001395
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001396 /* Initialise run time counter. */
1397 if (!HLUA_IS_RUNNING(lua))
1398 lua->run_time = 0;
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001399
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +02001400 /* Lock the whole Lua execution. This lock must be before the
1401 * label "resume_execution".
1402 */
Thierry Fournier021d9862020-11-28 23:42:03 +01001403 if (lua->state_id == 0)
Willy Tarreau1e7bef12021-08-20 15:47:25 +02001404 lua_take_global_lock();
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +02001405
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001406resume_execution:
1407
1408 /* This hook interrupts the Lua processing each 'hlua_nb_instruction'
1409 * instructions. it is used for preventing infinite loops.
1410 */
1411 lua_sethook(lua->T, hlua_hook, LUA_MASKCOUNT, hlua_nb_instruction);
1412
Thierry FOURNIER1bfc09b2015-03-05 17:10:14 +01001413 /* Remove all flags except the running flags. */
Thierry FOURNIER2f3867f2015-09-28 01:02:01 +02001414 HLUA_SET_RUN(lua);
1415 HLUA_CLR_CTRLYIELD(lua);
1416 HLUA_CLR_WAKERESWR(lua);
1417 HLUA_CLR_WAKEREQWR(lua);
Christopher Faulet1f43a342021-08-04 17:58:21 +02001418 HLUA_CLR_NOYIELD(lua);
1419 if (!yield_allowed)
1420 HLUA_SET_NOYIELD(lua);
Thierry FOURNIER1bfc09b2015-03-05 17:10:14 +01001421
Christopher Fauletbc275a92020-02-26 14:55:16 +01001422 /* Update the start time and reset wake_time. */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001423 lua->start_time = now_ms;
Christopher Fauletbc275a92020-02-26 14:55:16 +01001424 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001425
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001426 /* Call the function. */
Christopher Faulet08ed98f2020-07-28 10:33:25 +02001427#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM >= 504
Thierry Fournier021d9862020-11-28 23:42:03 +01001428 ret = lua_resume(lua->T, hlua_states[lua->state_id], lua->nargs, &nres);
Christopher Faulet08ed98f2020-07-28 10:33:25 +02001429#else
Thierry Fournier021d9862020-11-28 23:42:03 +01001430 ret = lua_resume(lua->T, hlua_states[lua->state_id], lua->nargs);
Christopher Faulet08ed98f2020-07-28 10:33:25 +02001431#endif
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001432 switch (ret) {
1433
1434 case LUA_OK:
1435 ret = HLUA_E_OK;
1436 break;
1437
1438 case LUA_YIELD:
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001439 /* Check if the execution timeout is expired. It it is the case, we
1440 * break the Lua execution.
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001441 */
Willy Tarreau55542642021-10-08 09:33:24 +02001442 clock_update_date(0, 1);
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001443 lua->run_time += now_ms - lua->start_time;
1444 if (lua->max_time && lua->run_time > lua->max_time) {
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001445 lua_settop(lua->T, 0); /* Empty the stack. */
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001446 ret = HLUA_E_ETMOUT;
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001447 break;
1448 }
1449 /* Process the forced yield. if the general yield is not allowed or
1450 * if no task were associated this the current Lua execution
1451 * coroutine, we resume the execution. Else we want to return in the
1452 * scheduler and we want to be waked up again, to continue the
1453 * current Lua execution. So we schedule our own task.
1454 */
1455 if (HLUA_IS_CTRLYIELDING(lua)) {
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001456 if (!yield_allowed || !lua->task)
1457 goto resume_execution;
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001458 task_wakeup(lua->task, TASK_WOKEN_MSG);
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001459 }
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001460 if (!yield_allowed) {
1461 lua_settop(lua->T, 0); /* Empty the stack. */
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001462 ret = HLUA_E_YIELD;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001463 break;
1464 }
1465 ret = HLUA_E_AGAIN;
1466 break;
1467
1468 case LUA_ERRRUN:
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001469
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001470 /* Special exit case. The traditional exit is returned as an error
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001471 * because the errors ares the only one mean to return immediately
1472 * from and lua execution.
1473 */
1474 if (lua->flags & HLUA_EXIT) {
1475 ret = HLUA_E_OK;
Christopher Faulet7716cdf2020-01-29 11:53:30 +01001476 hlua_ctx_renew(lua, 1);
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001477 break;
1478 }
1479
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001480 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001481 if (!lua_checkstack(lua->T, 1)) {
1482 ret = HLUA_E_ERR;
1483 break;
1484 }
1485 msg = lua_tostring(lua->T, -1);
1486 lua_settop(lua->T, 0); /* Empty the stack. */
1487 lua_pop(lua->T, 1);
Christopher Fauletd09cc512021-03-24 14:48:45 +01001488 trace = hlua_traceback(lua->T, ", ");
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001489 if (msg)
Thierry Fournier46278ff2020-11-29 11:48:12 +01001490 lua_pushfstring(lua->T, "[state-id %d] runtime error: %s from %s", lua->state_id, msg, trace);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001491 else
Thierry Fournier46278ff2020-11-29 11:48:12 +01001492 lua_pushfstring(lua->T, "[state-id %d] unknown runtime error from %s", lua->state_id, trace);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001493 ret = HLUA_E_ERRMSG;
1494 break;
1495
1496 case LUA_ERRMEM:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001497 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001498 lua_settop(lua->T, 0); /* Empty the stack. */
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001499 ret = HLUA_E_NOMEM;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001500 break;
1501
1502 case LUA_ERRERR:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001503 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001504 if (!lua_checkstack(lua->T, 1)) {
1505 ret = HLUA_E_ERR;
1506 break;
1507 }
1508 msg = lua_tostring(lua->T, -1);
1509 lua_settop(lua->T, 0); /* Empty the stack. */
1510 lua_pop(lua->T, 1);
1511 if (msg)
Thierry Fournier46278ff2020-11-29 11:48:12 +01001512 lua_pushfstring(lua->T, "[state-id %d] message handler error: %s", lua->state_id, msg);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001513 else
Thierry Fournier46278ff2020-11-29 11:48:12 +01001514 lua_pushfstring(lua->T, "[state-id %d] message handler error", lua->state_id);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001515 ret = HLUA_E_ERRMSG;
1516 break;
1517
1518 default:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001519 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001520 lua_settop(lua->T, 0); /* Empty the stack. */
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001521 ret = HLUA_E_ERR;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001522 break;
1523 }
1524
1525 switch (ret) {
1526 case HLUA_E_AGAIN:
1527 break;
1528
1529 case HLUA_E_ERRMSG:
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001530 notification_purge(&lua->com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001531 hlua_ctx_renew(lua, 1);
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001532 HLUA_CLR_RUN(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001533 break;
1534
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001535 case HLUA_E_ETMOUT:
1536 case HLUA_E_NOMEM:
1537 case HLUA_E_YIELD:
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001538 case HLUA_E_ERR:
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001539 HLUA_CLR_RUN(lua);
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001540 notification_purge(&lua->com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001541 hlua_ctx_renew(lua, 0);
1542 break;
1543
1544 case HLUA_E_OK:
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001545 HLUA_CLR_RUN(lua);
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001546 notification_purge(&lua->com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001547 break;
1548 }
1549
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +02001550 /* This is the main exit point, remove the Lua lock. */
Thierry Fournier021d9862020-11-28 23:42:03 +01001551 if (lua->state_id == 0)
Willy Tarreau1e7bef12021-08-20 15:47:25 +02001552 lua_drop_global_lock();
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +02001553
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001554 return ret;
1555}
1556
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001557/* This function exit the current code. */
1558__LJMP static int hlua_done(lua_State *L)
1559{
Thierry Fournier4234dbd2020-11-28 13:18:23 +01001560 struct hlua *hlua;
1561
1562 /* Get hlua struct, or NULL if we execute from main lua state */
1563 hlua = hlua_gethlua(L);
1564 if (!hlua)
1565 return 0;
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001566
1567 hlua->flags |= HLUA_EXIT;
1568 WILL_LJMP(lua_error(L));
1569
1570 return 0;
1571}
1572
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001573/* This function is an LUA binding. It provides a function
1574 * for deleting ACL from a referenced ACL file.
1575 */
1576__LJMP static int hlua_del_acl(lua_State *L)
1577{
1578 const char *name;
1579 const char *key;
1580 struct pat_ref *ref;
1581
1582 MAY_LJMP(check_args(L, 2, "del_acl"));
1583
1584 name = MAY_LJMP(luaL_checkstring(L, 1));
1585 key = MAY_LJMP(luaL_checkstring(L, 2));
1586
1587 ref = pat_ref_lookup(name);
1588 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001589 WILL_LJMP(luaL_error(L, "'del_acl': unknown acl file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001590
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001591 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001592 pat_ref_delete(ref, key);
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001593 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001594 return 0;
1595}
1596
1597/* This function is an LUA binding. It provides a function
1598 * for deleting map entry from a referenced map file.
1599 */
1600static int hlua_del_map(lua_State *L)
1601{
1602 const char *name;
1603 const char *key;
1604 struct pat_ref *ref;
1605
1606 MAY_LJMP(check_args(L, 2, "del_map"));
1607
1608 name = MAY_LJMP(luaL_checkstring(L, 1));
1609 key = MAY_LJMP(luaL_checkstring(L, 2));
1610
1611 ref = pat_ref_lookup(name);
1612 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001613 WILL_LJMP(luaL_error(L, "'del_map': unknown acl file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001614
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001615 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001616 pat_ref_delete(ref, key);
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001617 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001618 return 0;
1619}
1620
1621/* This function is an LUA binding. It provides a function
1622 * for adding ACL pattern from a referenced ACL file.
1623 */
1624static int hlua_add_acl(lua_State *L)
1625{
1626 const char *name;
1627 const char *key;
1628 struct pat_ref *ref;
1629
1630 MAY_LJMP(check_args(L, 2, "add_acl"));
1631
1632 name = MAY_LJMP(luaL_checkstring(L, 1));
1633 key = MAY_LJMP(luaL_checkstring(L, 2));
1634
1635 ref = pat_ref_lookup(name);
1636 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001637 WILL_LJMP(luaL_error(L, "'add_acl': unknown acl file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001638
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001639 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001640 if (pat_ref_find_elt(ref, key) == NULL)
1641 pat_ref_add(ref, key, NULL, NULL);
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001642 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001643 return 0;
1644}
1645
1646/* This function is an LUA binding. It provides a function
1647 * for setting map pattern and sample from a referenced map
1648 * file.
1649 */
1650static int hlua_set_map(lua_State *L)
1651{
1652 const char *name;
1653 const char *key;
1654 const char *value;
1655 struct pat_ref *ref;
1656
1657 MAY_LJMP(check_args(L, 3, "set_map"));
1658
1659 name = MAY_LJMP(luaL_checkstring(L, 1));
1660 key = MAY_LJMP(luaL_checkstring(L, 2));
1661 value = MAY_LJMP(luaL_checkstring(L, 3));
1662
1663 ref = pat_ref_lookup(name);
1664 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001665 WILL_LJMP(luaL_error(L, "'set_map': unknown map 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_set(ref, key, value, NULL);
1670 else
1671 pat_ref_add(ref, key, value, NULL);
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001672 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001673 return 0;
1674}
1675
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01001676/* A class is a lot of memory that contain data. This data can be a table,
1677 * an integer or user data. This data is associated with a metatable. This
Ilya Shipitsinc02a23f2020-05-06 00:53:22 +05001678 * metatable have an original version registered in the global context with
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01001679 * the name of the object (_G[<name>] = <metable> ).
1680 *
1681 * A metable is a table that modify the standard behavior of a standard
1682 * access to the associated data. The entries of this new metatable are
1683 * defined as is:
1684 *
1685 * http://lua-users.org/wiki/MetatableEvents
1686 *
1687 * __index
1688 *
1689 * we access an absent field in a table, the result is nil. This is
1690 * true, but it is not the whole truth. Actually, such access triggers
1691 * the interpreter to look for an __index metamethod: If there is no
1692 * such method, as usually happens, then the access results in nil;
1693 * otherwise, the metamethod will provide the result.
1694 *
1695 * Control 'prototype' inheritance. When accessing "myTable[key]" and
1696 * the key does not appear in the table, but the metatable has an __index
1697 * property:
1698 *
1699 * - if the value is a function, the function is called, passing in the
1700 * table and the key; the return value of that function is returned as
1701 * the result.
1702 *
1703 * - if the value is another table, the value of the key in that table is
1704 * asked for and returned (and if it doesn't exist in that table, but that
1705 * table's metatable has an __index property, then it continues on up)
1706 *
1707 * - Use "rawget(myTable,key)" to skip this metamethod.
1708 *
1709 * http://www.lua.org/pil/13.4.1.html
1710 *
1711 * __newindex
1712 *
1713 * Like __index, but control property assignment.
1714 *
1715 * __mode - Control weak references. A string value with one or both
1716 * of the characters 'k' and 'v' which specifies that the the
1717 * keys and/or values in the table are weak references.
1718 *
1719 * __call - Treat a table like a function. When a table is followed by
1720 * parenthesis such as "myTable( 'foo' )" and the metatable has
1721 * a __call key pointing to a function, that function is invoked
1722 * (passing any specified arguments) and the return value is
1723 * returned.
1724 *
1725 * __metatable - Hide the metatable. When "getmetatable( myTable )" is
1726 * called, if the metatable for myTable has a __metatable
1727 * key, the value of that key is returned instead of the
1728 * actual metatable.
1729 *
1730 * __tostring - Control string representation. When the builtin
1731 * "tostring( myTable )" function is called, if the metatable
1732 * for myTable has a __tostring property set to a function,
1733 * that function is invoked (passing myTable to it) and the
1734 * return value is used as the string representation.
1735 *
1736 * __len - Control table length. When the table length is requested using
1737 * the length operator ( '#' ), if the metatable for myTable has
1738 * a __len key pointing to a function, that function is invoked
1739 * (passing myTable to it) and the return value used as the value
1740 * of "#myTable".
1741 *
1742 * __gc - Userdata finalizer code. When userdata is set to be garbage
1743 * collected, if the metatable has a __gc field pointing to a
1744 * function, that function is first invoked, passing the userdata
1745 * to it. The __gc metamethod is not called for tables.
1746 * (See http://lua-users.org/lists/lua-l/2006-11/msg00508.html)
1747 *
1748 * Special metamethods for redefining standard operators:
1749 * http://www.lua.org/pil/13.1.html
1750 *
1751 * __add "+"
1752 * __sub "-"
1753 * __mul "*"
1754 * __div "/"
1755 * __unm "!"
1756 * __pow "^"
1757 * __concat ".."
1758 *
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001759 * Special methods for redefining standard relations
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01001760 * http://www.lua.org/pil/13.2.html
1761 *
1762 * __eq "=="
1763 * __lt "<"
1764 * __le "<="
1765 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001766
1767/*
1768 *
1769 *
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001770 * Class Map
1771 *
1772 *
1773 */
1774
1775/* Returns a struct hlua_map if the stack entry "ud" is
1776 * a class session, otherwise it throws an error.
1777 */
1778__LJMP static struct map_descriptor *hlua_checkmap(lua_State *L, int ud)
1779{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02001780 return MAY_LJMP(hlua_checkudata(L, ud, class_map_ref));
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001781}
1782
1783/* This function is the map constructor. It don't need
1784 * the class Map object. It creates and return a new Map
1785 * object. It must be called only during "body" or "init"
1786 * context because it process some filesystem accesses.
1787 */
1788__LJMP static int hlua_map_new(struct lua_State *L)
1789{
1790 const char *fn;
1791 int match = PAT_MATCH_STR;
1792 struct sample_conv conv;
1793 const char *file = "";
1794 int line = 0;
1795 lua_Debug ar;
1796 char *err = NULL;
1797 struct arg args[2];
1798
1799 if (lua_gettop(L) < 1 || lua_gettop(L) > 2)
1800 WILL_LJMP(luaL_error(L, "'new' needs at least 1 argument."));
1801
1802 fn = MAY_LJMP(luaL_checkstring(L, 1));
1803
1804 if (lua_gettop(L) >= 2) {
1805 match = MAY_LJMP(luaL_checkinteger(L, 2));
1806 if (match < 0 || match >= PAT_MATCH_NUM)
1807 WILL_LJMP(luaL_error(L, "'new' needs a valid match method."));
1808 }
1809
1810 /* Get Lua filename and line number. */
1811 if (lua_getstack(L, 1, &ar)) { /* check function at level */
1812 lua_getinfo(L, "Sl", &ar); /* get info about it */
1813 if (ar.currentline > 0) { /* is there info? */
1814 file = ar.short_src;
1815 line = ar.currentline;
1816 }
1817 }
1818
1819 /* fill fake sample_conv struct. */
1820 conv.kw = ""; /* unused. */
1821 conv.process = NULL; /* unused. */
1822 conv.arg_mask = 0; /* unused. */
1823 conv.val_args = NULL; /* unused. */
1824 conv.out_type = SMP_T_STR;
1825 conv.private = (void *)(long)match;
1826 switch (match) {
1827 case PAT_MATCH_STR: conv.in_type = SMP_T_STR; break;
1828 case PAT_MATCH_BEG: conv.in_type = SMP_T_STR; break;
1829 case PAT_MATCH_SUB: conv.in_type = SMP_T_STR; break;
1830 case PAT_MATCH_DIR: conv.in_type = SMP_T_STR; break;
1831 case PAT_MATCH_DOM: conv.in_type = SMP_T_STR; break;
1832 case PAT_MATCH_END: conv.in_type = SMP_T_STR; break;
1833 case PAT_MATCH_REG: conv.in_type = SMP_T_STR; break;
Thierry FOURNIER07ee64e2015-07-06 23:43:03 +02001834 case PAT_MATCH_INT: conv.in_type = SMP_T_SINT; break;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001835 case PAT_MATCH_IP: conv.in_type = SMP_T_ADDR; break;
1836 default:
1837 WILL_LJMP(luaL_error(L, "'new' doesn't support this match mode."));
1838 }
1839
1840 /* fill fake args. */
1841 args[0].type = ARGT_STR;
Christopher Faulet73292e92020-08-06 08:40:09 +02001842 args[0].data.str.area = strdup(fn);
1843 args[0].data.str.data = strlen(fn);
1844 args[0].data.str.size = args[0].data.str.data+1;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001845 args[1].type = ARGT_STOP;
1846
1847 /* load the map. */
1848 if (!sample_load_map(args, &conv, file, line, &err)) {
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +05001849 /* error case: we can't use luaL_error because we must
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001850 * free the err variable.
1851 */
1852 luaL_where(L, 1);
1853 lua_pushfstring(L, "'new': %s.", err);
1854 lua_concat(L, 2);
1855 free(err);
Christopher Faulet6ad7df42020-08-07 11:45:18 +02001856 chunk_destroy(&args[0].data.str);
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001857 WILL_LJMP(lua_error(L));
1858 }
1859
1860 /* create the lua object. */
1861 lua_newtable(L);
1862 lua_pushlightuserdata(L, args[0].data.map);
1863 lua_rawseti(L, -2, 0);
1864
1865 /* Pop a class Map metatable and affect it to the userdata. */
1866 lua_rawgeti(L, LUA_REGISTRYINDEX, class_map_ref);
1867 lua_setmetatable(L, -2);
1868
1869
1870 return 1;
1871}
1872
1873__LJMP static inline int _hlua_map_lookup(struct lua_State *L, int str)
1874{
1875 struct map_descriptor *desc;
1876 struct pattern *pat;
1877 struct sample smp;
1878
1879 MAY_LJMP(check_args(L, 2, "lookup"));
1880 desc = MAY_LJMP(hlua_checkmap(L, 1));
Thierry FOURNIER07ee64e2015-07-06 23:43:03 +02001881 if (desc->pat.expect_type == SMP_T_SINT) {
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02001882 smp.data.type = SMP_T_SINT;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +02001883 smp.data.u.sint = MAY_LJMP(luaL_checkinteger(L, 2));
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001884 }
1885 else {
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02001886 smp.data.type = SMP_T_STR;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001887 smp.flags = SMP_F_CONST;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001888 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 +01001889 smp.data.u.str.size = smp.data.u.str.data + 1;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001890 }
1891
1892 pat = pattern_exec_match(&desc->pat, &smp, 1);
Thierry FOURNIER503bb092015-08-19 08:35:43 +02001893 if (!pat || !pat->data) {
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001894 if (str)
1895 lua_pushstring(L, "");
1896 else
1897 lua_pushnil(L);
1898 return 1;
1899 }
1900
1901 /* The Lua pattern must return a string, so we can't check the returned type */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001902 lua_pushlstring(L, pat->data->u.str.area, pat->data->u.str.data);
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001903 return 1;
1904}
1905
1906__LJMP static int hlua_map_lookup(struct lua_State *L)
1907{
1908 return _hlua_map_lookup(L, 0);
1909}
1910
1911__LJMP static int hlua_map_slookup(struct lua_State *L)
1912{
1913 return _hlua_map_lookup(L, 1);
1914}
1915
1916/*
1917 *
1918 *
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001919 * Class Socket
1920 *
1921 *
1922 */
1923
1924__LJMP static struct hlua_socket *hlua_checksocket(lua_State *L, int ud)
1925{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02001926 return MAY_LJMP(hlua_checkudata(L, ud, class_socket_ref));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001927}
1928
1929/* This function is the handler called for each I/O on the established
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001930 * connection. It is used for notify space available to send or data
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001931 * received.
1932 */
Willy Tarreau00a37f02015-04-13 12:05:19 +02001933static void hlua_socket_handler(struct appctx *appctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001934{
Willy Tarreau5321da92022-05-06 11:57:34 +02001935 struct hlua_csk_ctx *ctx = appctx->svcctx;
Willy Tarreau0698c802022-05-11 14:09:57 +02001936 struct conn_stream *cs = appctx_cs(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001937
Willy Tarreau5321da92022-05-06 11:57:34 +02001938 if (ctx->die) {
Christopher Fauletda098e62022-03-31 17:44:45 +02001939 cs_shutw(cs);
1940 cs_shutr(cs);
Christopher Faulet908628c2022-03-25 16:43:49 +01001941 cs_ic(cs)->flags |= CF_READ_NULL;
Willy Tarreau5321da92022-05-06 11:57:34 +02001942 notification_wake(&ctx->wake_on_read);
1943 notification_wake(&ctx->wake_on_write);
Christopher Faulet908628c2022-03-25 16:43:49 +01001944 stream_shutdown(__cs_strm(cs), SF_ERR_KILLED);
Thierry FOURNIERb13b20a2017-07-16 20:48:54 +02001945 }
1946
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +05001947 /* If we can't write, wakeup the pending write signals. */
Christopher Faulet908628c2022-03-25 16:43:49 +01001948 if (channel_output_closed(cs_ic(cs)))
Willy Tarreau5321da92022-05-06 11:57:34 +02001949 notification_wake(&ctx->wake_on_write);
Thierry FOURNIER6d695e62015-09-27 19:29:38 +02001950
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +05001951 /* If we can't read, wakeup the pending read signals. */
Christopher Faulet908628c2022-03-25 16:43:49 +01001952 if (channel_input_closed(cs_oc(cs)))
Willy Tarreau5321da92022-05-06 11:57:34 +02001953 notification_wake(&ctx->wake_on_read);
Thierry FOURNIER6d695e62015-09-27 19:29:38 +02001954
Willy Tarreau5a0b25d2019-07-18 18:01:14 +02001955 /* if the connection is not established, inform the stream that we want
Thierry FOURNIER316e3192015-09-04 18:25:53 +02001956 * to be notified whenever the connection completes.
1957 */
Christopher Faulet62e75742022-03-31 09:16:34 +02001958 if (cs_opposite(cs)->state < CS_ST_EST) {
Christopher Fauleta0bdec32022-04-04 07:51:21 +02001959 cs_cant_get(cs);
1960 cs_rx_conn_blk(cs);
1961 cs_rx_endp_more(cs);
Willy Tarreaud4da1962015-04-20 01:31:23 +02001962 return;
Thierry FOURNIER316e3192015-09-04 18:25:53 +02001963 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001964
1965 /* This function is called after the connect. */
Willy Tarreau5321da92022-05-06 11:57:34 +02001966 ctx->connected = 1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001967
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001968 /* Wake the tasks which wants to write if the buffer have available space. */
Christopher Faulet908628c2022-03-25 16:43:49 +01001969 if (channel_may_recv(cs_ic(cs)))
Willy Tarreau5321da92022-05-06 11:57:34 +02001970 notification_wake(&ctx->wake_on_write);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001971
1972 /* Wake the tasks which wants to read if the buffer contains data. */
Christopher Faulet908628c2022-03-25 16:43:49 +01001973 if (!channel_is_empty(cs_oc(cs)))
Willy Tarreau5321da92022-05-06 11:57:34 +02001974 notification_wake(&ctx->wake_on_read);
Thierry FOURNIER101b9762018-05-27 01:27:40 +02001975
1976 /* Some data were injected in the buffer, notify the stream
1977 * interface.
1978 */
Christopher Faulet908628c2022-03-25 16:43:49 +01001979 if (!channel_is_empty(cs_ic(cs)))
Christopher Faulet13045f02022-04-01 14:23:38 +02001980 cs_update(cs);
Thierry FOURNIER101b9762018-05-27 01:27:40 +02001981
1982 /* If write notifications are registered, we considers we want
Willy Tarreau3367d412018-11-15 10:57:41 +01001983 * to write, so we clear the blocking flag.
Thierry FOURNIER101b9762018-05-27 01:27:40 +02001984 */
Willy Tarreau5321da92022-05-06 11:57:34 +02001985 if (notification_registered(&ctx->wake_on_write))
Christopher Fauleta0bdec32022-04-04 07:51:21 +02001986 cs_rx_endp_more(cs);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001987}
1988
Willy Tarreau87b09662015-04-03 00:22:06 +02001989/* This function is called when the "struct stream" is destroyed.
1990 * Remove the link from the object to this stream.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001991 * Wake all the pending signals.
1992 */
Willy Tarreau00a37f02015-04-13 12:05:19 +02001993static void hlua_socket_release(struct appctx *appctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001994{
Willy Tarreau5321da92022-05-06 11:57:34 +02001995 struct hlua_csk_ctx *ctx = appctx->svcctx;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001996 struct xref *peer;
1997
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001998 /* Remove my link in the original object. */
Willy Tarreau5321da92022-05-06 11:57:34 +02001999 peer = xref_get_peer_and_lock(&ctx->xref);
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002000 if (peer)
Willy Tarreau5321da92022-05-06 11:57:34 +02002001 xref_disconnect(&ctx->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002002
2003 /* Wake all the task waiting for me. */
Willy Tarreau5321da92022-05-06 11:57:34 +02002004 notification_wake(&ctx->wake_on_read);
2005 notification_wake(&ctx->wake_on_write);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002006}
2007
2008/* If the garbage collectio of the object is launch, nobody
Willy Tarreau87b09662015-04-03 00:22:06 +02002009 * uses this object. If the stream does not exists, just quit.
2010 * Send the shutdown signal to the stream. In some cases,
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002011 * pending signal can rest in the read and write lists. destroy
2012 * it.
2013 */
2014__LJMP static int hlua_socket_gc(lua_State *L)
2015{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002016 struct hlua_socket *socket;
Willy Tarreau5321da92022-05-06 11:57:34 +02002017 struct hlua_csk_ctx *ctx;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002018 struct xref *peer;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002019
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002020 MAY_LJMP(check_args(L, 1, "__gc"));
2021
2022 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002023 peer = xref_get_peer_and_lock(&socket->xref);
2024 if (!peer)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002025 return 0;
Willy Tarreau5321da92022-05-06 11:57:34 +02002026
2027 ctx = container_of(peer, struct hlua_csk_ctx, xref);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002028
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002029 /* Set the flag which destroy the session. */
Willy Tarreau5321da92022-05-06 11:57:34 +02002030 ctx->die = 1;
2031 appctx_wakeup(ctx->appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002032
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002033 /* Remove all reference between the Lua stack and the coroutine stream. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002034 xref_disconnect(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002035 return 0;
2036}
2037
2038/* The close function send shutdown signal and break the
Willy Tarreau87b09662015-04-03 00:22:06 +02002039 * links between the stream and the object.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002040 */
sada05ed3302018-05-11 11:48:18 -07002041__LJMP static int hlua_socket_close_helper(lua_State *L)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002042{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002043 struct hlua_socket *socket;
Willy Tarreau5321da92022-05-06 11:57:34 +02002044 struct hlua_csk_ctx *ctx;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002045 struct xref *peer;
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002046 struct hlua *hlua;
2047
2048 /* Get hlua struct, or NULL if we execute from main lua state */
2049 hlua = hlua_gethlua(L);
2050 if (!hlua)
2051 return 0;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002052
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002053 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002054
2055 /* Check if we run on the same thread than the xreator thread.
2056 * We cannot access to the socket if the thread is different.
2057 */
2058 if (socket->tid != tid)
2059 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2060
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002061 peer = xref_get_peer_and_lock(&socket->xref);
2062 if (!peer)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002063 return 0;
Willy Tarreauf31af932020-01-14 09:59:38 +01002064
2065 hlua->gc_count--;
Willy Tarreau5321da92022-05-06 11:57:34 +02002066 ctx = container_of(peer, struct hlua_csk_ctx, xref);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002067
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002068 /* Set the flag which destroy the session. */
Willy Tarreau5321da92022-05-06 11:57:34 +02002069 ctx->die = 1;
2070 appctx_wakeup(ctx->appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002071
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002072 /* Remove all reference between the Lua stack and the coroutine stream. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002073 xref_disconnect(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002074 return 0;
2075}
2076
sada05ed3302018-05-11 11:48:18 -07002077/* The close function calls close_helper.
2078 */
2079__LJMP static int hlua_socket_close(lua_State *L)
2080{
2081 MAY_LJMP(check_args(L, 1, "close"));
2082 return hlua_socket_close_helper(L);
2083}
2084
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002085/* This Lua function assumes that the stack contain three parameters.
2086 * 1 - USERDATA containing a struct socket
2087 * 2 - INTEGER with values of the macro defined below
2088 * If the integer is -1, we must read at most one line.
2089 * If the integer is -2, we ust read all the data until the
2090 * end of the stream.
2091 * If the integer is positive value, we must read a number of
2092 * bytes corresponding to this value.
2093 */
2094#define HLSR_READ_LINE (-1)
2095#define HLSR_READ_ALL (-2)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002096__LJMP static int hlua_socket_receive_yield(struct lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002097{
2098 struct hlua_socket *socket = MAY_LJMP(hlua_checksocket(L, 1));
2099 int wanted = lua_tointeger(L, 2);
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002100 struct hlua *hlua;
Willy Tarreau5321da92022-05-06 11:57:34 +02002101 struct hlua_csk_ctx *csk_ctx;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002102 struct appctx *appctx;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02002103 size_t len;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002104 int nblk;
Willy Tarreau206ba832018-06-14 15:27:31 +02002105 const char *blk1;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02002106 size_t len1;
Willy Tarreau206ba832018-06-14 15:27:31 +02002107 const char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02002108 size_t len2;
Thierry FOURNIER00543922015-03-09 18:35:06 +01002109 int skip_at_end = 0;
Willy Tarreau81389672015-03-10 12:03:52 +01002110 struct channel *oc;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002111 struct stream *s;
2112 struct xref *peer;
Thierry FOURNIER8c126c72018-05-25 16:27:44 +02002113 int missing_bytes;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002114
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002115 /* Get hlua struct, or NULL if we execute from main lua state */
2116 hlua = hlua_gethlua(L);
2117
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002118 /* Check if this lua stack is schedulable. */
2119 if (!hlua || !hlua->task)
2120 WILL_LJMP(luaL_error(L, "The 'receive' function is only allowed in "
2121 "'frontend', 'backend' or 'task'"));
2122
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002123 /* Check if we run on the same thread than the xreator thread.
2124 * We cannot access to the socket if the thread is different.
2125 */
2126 if (socket->tid != tid)
2127 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2128
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002129 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002130 peer = xref_get_peer_and_lock(&socket->xref);
2131 if (!peer)
2132 goto no_peer;
Willy Tarreau5321da92022-05-06 11:57:34 +02002133
2134 csk_ctx = container_of(peer, struct hlua_csk_ctx, xref);
2135 appctx = csk_ctx->appctx;
Willy Tarreau0698c802022-05-11 14:09:57 +02002136 s = appctx_strm(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002137
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002138 oc = &s->res;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002139 if (wanted == HLSR_READ_LINE) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002140 /* Read line. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02002141 nblk = co_getline_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002142 if (nblk < 0) /* Connection close. */
2143 goto connection_closed;
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002144 if (nblk == 0) /* No data available. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002145 goto connection_empty;
Thierry FOURNIER00543922015-03-09 18:35:06 +01002146
2147 /* remove final \r\n. */
2148 if (nblk == 1) {
2149 if (blk1[len1-1] == '\n') {
2150 len1--;
2151 skip_at_end++;
2152 if (blk1[len1-1] == '\r') {
2153 len1--;
2154 skip_at_end++;
2155 }
2156 }
2157 }
2158 else {
2159 if (blk2[len2-1] == '\n') {
2160 len2--;
2161 skip_at_end++;
2162 if (blk2[len2-1] == '\r') {
2163 len2--;
2164 skip_at_end++;
2165 }
2166 }
2167 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002168 }
2169
2170 else if (wanted == HLSR_READ_ALL) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002171 /* Read all the available data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02002172 nblk = co_getblk_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002173 if (nblk < 0) /* Connection close. */
2174 goto connection_closed;
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002175 if (nblk == 0) /* No data available. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002176 goto connection_empty;
2177 }
2178
2179 else {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002180 /* Read a block of data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02002181 nblk = co_getblk_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002182 if (nblk < 0) /* Connection close. */
2183 goto connection_closed;
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002184 if (nblk == 0) /* No data available. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002185 goto connection_empty;
2186
Thierry FOURNIER8c126c72018-05-25 16:27:44 +02002187 missing_bytes = wanted - socket->b.n;
2188 if (len1 > missing_bytes) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002189 nblk = 1;
Thierry FOURNIER8c126c72018-05-25 16:27:44 +02002190 len1 = missing_bytes;
2191 } if (nblk == 2 && len1 + len2 > missing_bytes)
2192 len2 = missing_bytes - len1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002193 }
2194
2195 len = len1;
2196
2197 luaL_addlstring(&socket->b, blk1, len1);
2198 if (nblk == 2) {
2199 len += len2;
2200 luaL_addlstring(&socket->b, blk2, len2);
2201 }
2202
2203 /* Consume data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02002204 co_skip(oc, len + skip_at_end);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002205
2206 /* Don't wait anything. */
Thierry FOURNIER7e4ee472018-05-25 15:03:50 +02002207 appctx_wakeup(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002208
2209 /* If the pattern reclaim to read all the data
2210 * in the connection, got out.
2211 */
2212 if (wanted == HLSR_READ_ALL)
2213 goto connection_empty;
Thierry FOURNIER8c126c72018-05-25 16:27:44 +02002214 else if (wanted >= 0 && socket->b.n < wanted)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002215 goto connection_empty;
2216
2217 /* Return result. */
2218 luaL_pushresult(&socket->b);
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002219 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002220 return 1;
2221
2222connection_closed:
2223
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002224 xref_unlock(&socket->xref, peer);
2225
2226no_peer:
2227
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002228 /* If the buffer containds data. */
2229 if (socket->b.n > 0) {
2230 luaL_pushresult(&socket->b);
2231 return 1;
2232 }
2233 lua_pushnil(L);
2234 lua_pushstring(L, "connection closed.");
2235 return 2;
2236
2237connection_empty:
2238
Willy Tarreau5321da92022-05-06 11:57:34 +02002239 if (!notification_new(&hlua->com, &csk_ctx->wake_on_read, hlua->task)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002240 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002241 WILL_LJMP(luaL_error(L, "out of memory"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002242 }
2243 xref_unlock(&socket->xref, peer);
Willy Tarreau9635e032018-10-16 17:52:55 +02002244 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_receive_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002245 return 0;
2246}
2247
Tim Duesterhusb33754c2018-01-04 19:32:14 +01002248/* This Lua function gets two parameters. The first one can be string
2249 * or a number. If the string is "*l", the user requires one line. If
2250 * the string is "*a", the user requires all the contents of the stream.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002251 * If the value is a number, the user require a number of bytes equal
2252 * to the value. The default value is "*l" (a line).
2253 *
Tim Duesterhusb33754c2018-01-04 19:32:14 +01002254 * This parameter with a variable type is converted in integer. This
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002255 * integer takes this values:
2256 * -1 : read a line
2257 * -2 : read all the stream
Tim Duesterhusb33754c2018-01-04 19:32:14 +01002258 * >0 : amount of bytes.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002259 *
Tim Duesterhusb33754c2018-01-04 19:32:14 +01002260 * The second parameter is optional. It contains a string that must be
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002261 * concatenated with the read data.
2262 */
2263__LJMP static int hlua_socket_receive(struct lua_State *L)
2264{
2265 int wanted = HLSR_READ_LINE;
2266 const char *pattern;
Christopher Fauletc31b2002021-05-03 10:11:13 +02002267 int lastarg, type;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002268 char *error;
2269 size_t len;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002270 struct hlua_socket *socket;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002271
2272 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
2273 WILL_LJMP(luaL_error(L, "The 'receive' function requires between 1 and 3 arguments."));
2274
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002275 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002276
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002277 /* Check if we run on the same thread than the xreator thread.
2278 * We cannot access to the socket if the thread is different.
2279 */
2280 if (socket->tid != tid)
2281 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2282
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002283 /* check for pattern. */
2284 if (lua_gettop(L) >= 2) {
2285 type = lua_type(L, 2);
2286 if (type == LUA_TSTRING) {
2287 pattern = lua_tostring(L, 2);
2288 if (strcmp(pattern, "*a") == 0)
2289 wanted = HLSR_READ_ALL;
2290 else if (strcmp(pattern, "*l") == 0)
2291 wanted = HLSR_READ_LINE;
2292 else {
2293 wanted = strtoll(pattern, &error, 10);
2294 if (*error != '\0')
2295 WILL_LJMP(luaL_error(L, "Unsupported pattern."));
2296 }
2297 }
2298 else if (type == LUA_TNUMBER) {
2299 wanted = lua_tointeger(L, 2);
2300 if (wanted < 0)
2301 WILL_LJMP(luaL_error(L, "Unsupported size."));
2302 }
2303 }
2304
2305 /* Set pattern. */
2306 lua_pushinteger(L, wanted);
Tim Duesterhusc6e377e2018-01-04 19:32:13 +01002307
2308 /* Check if we would replace the top by itself. */
2309 if (lua_gettop(L) != 2)
2310 lua_replace(L, 2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002311
Christopher Fauletc31b2002021-05-03 10:11:13 +02002312 /* Save index of the top of the stack because since buffers are used, it
2313 * may change
2314 */
2315 lastarg = lua_gettop(L);
2316
Tim Duesterhusb33754c2018-01-04 19:32:14 +01002317 /* init buffer, and fill it with prefix. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002318 luaL_buffinit(L, &socket->b);
2319
2320 /* Check prefix. */
Christopher Fauletc31b2002021-05-03 10:11:13 +02002321 if (lastarg >= 3) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002322 if (lua_type(L, 3) != LUA_TSTRING)
2323 WILL_LJMP(luaL_error(L, "Expect a 'string' for the prefix"));
2324 pattern = lua_tolstring(L, 3, &len);
2325 luaL_addlstring(&socket->b, pattern, len);
2326 }
2327
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002328 return __LJMP(hlua_socket_receive_yield(L, 0, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002329}
2330
2331/* Write the Lua input string in the output buffer.
Mark Lakes22154b42018-01-29 14:38:40 -08002332 * This function returns a yield if no space is available.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002333 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002334static int hlua_socket_write_yield(struct lua_State *L,int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002335{
2336 struct hlua_socket *socket;
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002337 struct hlua *hlua;
Willy Tarreau5321da92022-05-06 11:57:34 +02002338 struct hlua_csk_ctx *csk_ctx;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002339 struct appctx *appctx;
2340 size_t buf_len;
2341 const char *buf;
2342 int len;
2343 int send_len;
2344 int sent;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002345 struct xref *peer;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002346 struct stream *s;
Christopher Faulet908628c2022-03-25 16:43:49 +01002347 struct conn_stream *cs;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002348
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002349 /* Get hlua struct, or NULL if we execute from main lua state */
2350 hlua = hlua_gethlua(L);
2351
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002352 /* Check if this lua stack is schedulable. */
2353 if (!hlua || !hlua->task)
2354 WILL_LJMP(luaL_error(L, "The 'write' function is only allowed in "
2355 "'frontend', 'backend' or 'task'"));
2356
2357 /* Get object */
2358 socket = MAY_LJMP(hlua_checksocket(L, 1));
2359 buf = MAY_LJMP(luaL_checklstring(L, 2, &buf_len));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002360 sent = MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002361
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002362 /* Check if we run on the same thread than the xreator thread.
2363 * We cannot access to the socket if the thread is different.
2364 */
2365 if (socket->tid != tid)
2366 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2367
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002368 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002369 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002370 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002371 lua_pushinteger(L, -1);
2372 return 1;
2373 }
Willy Tarreau5321da92022-05-06 11:57:34 +02002374
2375 csk_ctx = container_of(peer, struct hlua_csk_ctx, xref);
2376 appctx = csk_ctx->appctx;
Willy Tarreau0698c802022-05-11 14:09:57 +02002377 cs = appctx_cs(appctx);
Christopher Faulet908628c2022-03-25 16:43:49 +01002378 s = __cs_strm(cs);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002379
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002380 /* Check for connection close. */
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002381 if (channel_output_closed(&s->req)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002382 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002383 lua_pushinteger(L, -1);
2384 return 1;
2385 }
2386
2387 /* Update the input buffer data. */
2388 buf += sent;
2389 send_len = buf_len - sent;
2390
2391 /* All the data are sent. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002392 if (sent >= buf_len) {
2393 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002394 return 1; /* Implicitly return the length sent. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002395 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002396
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002397 /* Check if the buffer is available because HAProxy doesn't allocate
Thierry FOURNIER486d52a2015-03-09 17:51:43 +01002398 * the request buffer if its not required.
2399 */
Willy Tarreauc9fa0482018-07-10 17:43:27 +02002400 if (s->req.buf.size == 0) {
Christopher Faulet8f45eec2022-04-01 17:19:36 +02002401 if (!cs_alloc_ibuf(cs, &appctx->buffer_wait))
Christopher Faulet33834b12016-12-19 09:29:06 +01002402 goto hlua_socket_write_yield_return;
Thierry FOURNIER486d52a2015-03-09 17:51:43 +01002403 }
2404
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002405 /* Check for available space. */
Willy Tarreauc9fa0482018-07-10 17:43:27 +02002406 len = b_room(&s->req.buf);
Christopher Faulet33834b12016-12-19 09:29:06 +01002407 if (len <= 0) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002408 goto hlua_socket_write_yield_return;
Christopher Faulet33834b12016-12-19 09:29:06 +01002409 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002410
2411 /* send data */
2412 if (len < send_len)
2413 send_len = len;
Thierry FOURNIER66b89192018-05-27 01:14:47 +02002414 len = ci_putblk(&s->req, buf, send_len);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002415
2416 /* "Not enough space" (-1), "Buffer too little to contain
2417 * the data" (-2) are not expected because the available length
2418 * is tested.
2419 * Other unknown error are also not expected.
2420 */
2421 if (len <= 0) {
Willy Tarreaubc18da12015-03-13 14:00:47 +01002422 if (len == -1)
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002423 s->req.flags |= CF_WAKE_WRITE;
Willy Tarreaubc18da12015-03-13 14:00:47 +01002424
sada05ed3302018-05-11 11:48:18 -07002425 MAY_LJMP(hlua_socket_close_helper(L));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002426 lua_pop(L, 1);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002427 lua_pushinteger(L, -1);
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002428 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002429 return 1;
2430 }
2431
2432 /* update buffers. */
Thierry FOURNIER101b9762018-05-27 01:27:40 +02002433 appctx_wakeup(appctx);
Willy Tarreaude70fa12015-09-26 11:25:05 +02002434
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002435 s->req.rex = TICK_ETERNITY;
2436 s->res.wex = TICK_ETERNITY;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002437
2438 /* Update length sent. */
2439 lua_pop(L, 1);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002440 lua_pushinteger(L, sent + len);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002441
2442 /* All the data buffer is sent ? */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002443 if (sent + len >= buf_len) {
2444 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002445 return 1;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002446 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002447
2448hlua_socket_write_yield_return:
Willy Tarreau5321da92022-05-06 11:57:34 +02002449 if (!notification_new(&hlua->com, &csk_ctx->wake_on_write, hlua->task)) {
Thierry FOURNIERba42fcd2018-05-27 00:59:48 +02002450 xref_unlock(&socket->xref, peer);
2451 WILL_LJMP(luaL_error(L, "out of memory"));
2452 }
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002453 xref_unlock(&socket->xref, peer);
Willy Tarreau9635e032018-10-16 17:52:55 +02002454 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_write_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002455 return 0;
2456}
2457
2458/* This function initiate the send of data. It just check the input
2459 * parameters and push an integer in the Lua stack that contain the
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002460 * amount of data written to the buffer. This is used by the function
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002461 * "hlua_socket_write_yield" that can yield.
2462 *
2463 * The Lua function gets between 3 and 4 parameters. The first one is
2464 * the associated object. The second is a string buffer. The third is
2465 * a facultative integer that represents where is the buffer position
2466 * of the start of the data that can send. The first byte is the
2467 * position "1". The default value is "1". The fourth argument is a
2468 * facultative integer that represents where is the buffer position
2469 * of the end of the data that can send. The default is the last byte.
2470 */
2471static int hlua_socket_send(struct lua_State *L)
2472{
2473 int i;
2474 int j;
2475 const char *buf;
2476 size_t buf_len;
2477
2478 /* Check number of arguments. */
2479 if (lua_gettop(L) < 2 || lua_gettop(L) > 4)
2480 WILL_LJMP(luaL_error(L, "'send' needs between 2 and 4 arguments"));
2481
2482 /* Get the string. */
2483 buf = MAY_LJMP(luaL_checklstring(L, 2, &buf_len));
2484
2485 /* Get and check j. */
2486 if (lua_gettop(L) == 4) {
2487 j = MAY_LJMP(luaL_checkinteger(L, 4));
2488 if (j < 0)
2489 j = buf_len + j + 1;
2490 if (j > buf_len)
2491 j = buf_len + 1;
2492 lua_pop(L, 1);
2493 }
2494 else
2495 j = buf_len;
2496
2497 /* Get and check i. */
2498 if (lua_gettop(L) == 3) {
2499 i = MAY_LJMP(luaL_checkinteger(L, 3));
2500 if (i < 0)
2501 i = buf_len + i + 1;
2502 if (i > buf_len)
2503 i = buf_len + 1;
2504 lua_pop(L, 1);
2505 } else
2506 i = 1;
2507
2508 /* Check bth i and j. */
2509 if (i > j) {
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002510 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002511 return 1;
2512 }
2513 if (i == 0 && j == 0) {
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002514 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002515 return 1;
2516 }
2517 if (i == 0)
2518 i = 1;
2519 if (j == 0)
2520 j = 1;
2521
2522 /* Pop the string. */
2523 lua_pop(L, 1);
2524
2525 /* Update the buffer length. */
2526 buf += i - 1;
2527 buf_len = j - i + 1;
2528 lua_pushlstring(L, buf, buf_len);
2529
2530 /* This unsigned is used to remember the amount of sent data. */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002531 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002532
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002533 return MAY_LJMP(hlua_socket_write_yield(L, 0, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002534}
2535
Willy Tarreau22b0a682015-06-17 19:43:49 +02002536#define SOCKET_INFO_MAX_LEN sizeof("[0000:0000:0000:0000:0000:0000:0000:0000]:12345")
Christopher Faulete6465b32021-10-22 15:36:08 +02002537__LJMP static inline int hlua_socket_info(struct lua_State *L, const struct sockaddr_storage *addr)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002538{
2539 static char buffer[SOCKET_INFO_MAX_LEN];
2540 int ret;
2541 int len;
2542 char *p;
2543
2544 ret = addr_to_str(addr, buffer+1, SOCKET_INFO_MAX_LEN-1);
2545 if (ret <= 0) {
2546 lua_pushnil(L);
2547 return 1;
2548 }
2549
2550 if (ret == AF_UNIX) {
2551 lua_pushstring(L, buffer+1);
2552 return 1;
2553 }
2554 else if (ret == AF_INET6) {
2555 buffer[0] = '[';
2556 len = strlen(buffer);
2557 buffer[len] = ']';
2558 len++;
2559 buffer[len] = ':';
2560 len++;
2561 p = buffer;
2562 }
2563 else if (ret == AF_INET) {
2564 p = buffer + 1;
2565 len = strlen(p);
2566 p[len] = ':';
2567 len++;
2568 }
2569 else {
2570 lua_pushnil(L);
2571 return 1;
2572 }
2573
2574 if (port_to_str(addr, p + len, SOCKET_INFO_MAX_LEN-1 - len) <= 0) {
2575 lua_pushnil(L);
2576 return 1;
2577 }
2578
2579 lua_pushstring(L, p);
2580 return 1;
2581}
2582
2583/* Returns information about the peer of the connection. */
2584__LJMP static int hlua_socket_getpeername(struct lua_State *L)
2585{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002586 struct hlua_socket *socket;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002587 struct xref *peer;
2588 struct appctx *appctx;
Christopher Faulet908628c2022-03-25 16:43:49 +01002589 struct conn_stream *cs;
Christopher Faulet16f16af2021-10-27 09:34:56 +02002590 const struct sockaddr_storage *dst;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002591 int ret;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002592
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002593 MAY_LJMP(check_args(L, 1, "getpeername"));
2594
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002595 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002596
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002597 /* Check if we run on the same thread than the xreator thread.
2598 * We cannot access to the socket if the thread is different.
2599 */
2600 if (socket->tid != tid)
2601 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2602
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002603 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002604 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002605 if (!peer) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002606 lua_pushnil(L);
2607 return 1;
2608 }
Willy Tarreau5321da92022-05-06 11:57:34 +02002609
2610 appctx = container_of(peer, struct hlua_csk_ctx, xref)->appctx;
Willy Tarreau0698c802022-05-11 14:09:57 +02002611 cs = appctx_cs(appctx);
Christopher Faulet8da67aa2022-03-29 17:53:09 +02002612 dst = cs_dst(cs_opposite(cs));
Christopher Faulet16f16af2021-10-27 09:34:56 +02002613 if (!dst) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002614 xref_unlock(&socket->xref, peer);
Willy Tarreaua71f6422016-11-16 17:00:14 +01002615 lua_pushnil(L);
2616 return 1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002617 }
2618
Christopher Faulet16f16af2021-10-27 09:34:56 +02002619 ret = MAY_LJMP(hlua_socket_info(L, dst));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002620 xref_unlock(&socket->xref, peer);
2621 return ret;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002622}
2623
2624/* Returns information about my connection side. */
2625static int hlua_socket_getsockname(struct lua_State *L)
2626{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002627 struct hlua_socket *socket;
2628 struct connection *conn;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002629 struct appctx *appctx;
2630 struct xref *peer;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002631 struct stream *s;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002632 int ret;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002633
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002634 MAY_LJMP(check_args(L, 1, "getsockname"));
2635
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002636 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002637
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002638 /* Check if we run on the same thread than the xreator thread.
2639 * We cannot access to the socket if the thread is different.
2640 */
2641 if (socket->tid != tid)
2642 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2643
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002644 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002645 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002646 if (!peer) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002647 lua_pushnil(L);
2648 return 1;
2649 }
Willy Tarreau5321da92022-05-06 11:57:34 +02002650
2651 appctx = container_of(peer, struct hlua_csk_ctx, xref)->appctx;
Willy Tarreau0698c802022-05-11 14:09:57 +02002652 s = appctx_strm(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002653
Christopher Faulet95a61e82021-12-22 14:22:03 +01002654 conn = cs_conn(s->csb);
Willy Tarreau5a0b25d2019-07-18 18:01:14 +02002655 if (!conn || !conn_get_src(conn)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002656 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002657 lua_pushnil(L);
2658 return 1;
2659 }
2660
Willy Tarreau9da9a6f2019-07-17 14:49:44 +02002661 ret = hlua_socket_info(L, conn->src);
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002662 xref_unlock(&socket->xref, peer);
2663 return ret;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002664}
2665
2666/* This struct define the applet. */
Willy Tarreau30576452015-04-13 13:50:30 +02002667static struct applet update_applet = {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002668 .obj_type = OBJ_TYPE_APPLET,
2669 .name = "<LUA_TCP>",
2670 .fct = hlua_socket_handler,
2671 .release = hlua_socket_release,
2672};
2673
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002674__LJMP static int hlua_socket_connect_yield(struct lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002675{
2676 struct hlua_socket *socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002677 struct hlua *hlua;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002678 struct xref *peer;
Willy Tarreau5321da92022-05-06 11:57:34 +02002679 struct hlua_csk_ctx *csk_ctx;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002680 struct appctx *appctx;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002681 struct stream *s;
2682
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002683 /* Get hlua struct, or NULL if we execute from main lua state */
2684 hlua = hlua_gethlua(L);
2685 if (!hlua)
2686 return 0;
2687
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002688 /* Check if we run on the same thread than the xreator thread.
2689 * We cannot access to the socket if the thread is different.
2690 */
2691 if (socket->tid != tid)
2692 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2693
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002694 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002695 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002696 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002697 lua_pushnil(L);
2698 lua_pushstring(L, "Can't connect");
2699 return 2;
2700 }
Willy Tarreau5321da92022-05-06 11:57:34 +02002701
2702 csk_ctx = container_of(peer, struct hlua_csk_ctx, xref);
2703 appctx = csk_ctx->appctx;
Willy Tarreau0698c802022-05-11 14:09:57 +02002704 s = appctx_strm(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002705
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002706 /* Check if we run on the same thread than the xreator thread.
2707 * We cannot access to the socket if the thread is different.
2708 */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002709 if (socket->tid != tid) {
2710 xref_unlock(&socket->xref, peer);
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002711 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002712 }
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002713
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002714 /* Check for connection close. */
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002715 if (!hlua || channel_output_closed(&s->req)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002716 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002717 lua_pushnil(L);
2718 lua_pushstring(L, "Can't connect");
2719 return 2;
2720 }
2721
Christopher Faulet693b23b2022-02-28 09:09:05 +01002722 appctx = __cs_appctx(s->csf);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002723
2724 /* Check for connection established. */
Willy Tarreau5321da92022-05-06 11:57:34 +02002725 if (csk_ctx->connected) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002726 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002727 lua_pushinteger(L, 1);
2728 return 1;
2729 }
2730
Willy Tarreau5321da92022-05-06 11:57:34 +02002731 if (!notification_new(&hlua->com, &csk_ctx->wake_on_write, hlua->task)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002732 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002733 WILL_LJMP(luaL_error(L, "out of memory error"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002734 }
2735 xref_unlock(&socket->xref, peer);
Willy Tarreau9635e032018-10-16 17:52:55 +02002736 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_connect_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002737 return 0;
2738}
2739
2740/* This function fail or initite the connection. */
2741__LJMP static int hlua_socket_connect(struct lua_State *L)
2742{
2743 struct hlua_socket *socket;
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002744 int port = -1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002745 const char *ip;
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002746 struct hlua *hlua;
Willy Tarreau5321da92022-05-06 11:57:34 +02002747 struct hlua_csk_ctx *csk_ctx;
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002748 struct appctx *appctx;
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002749 int low, high;
2750 struct sockaddr_storage *addr;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002751 struct xref *peer;
Christopher Faulet908628c2022-03-25 16:43:49 +01002752 struct conn_stream *cs;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002753 struct stream *s;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002754
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002755 if (lua_gettop(L) < 2)
2756 WILL_LJMP(luaL_error(L, "connect: need at least 2 arguments"));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002757
2758 /* Get args. */
2759 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002760
2761 /* Check if we run on the same thread than the xreator thread.
2762 * We cannot access to the socket if the thread is different.
2763 */
2764 if (socket->tid != tid)
2765 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2766
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002767 ip = MAY_LJMP(luaL_checkstring(L, 2));
Tim Duesterhus6edab862018-01-06 19:04:45 +01002768 if (lua_gettop(L) >= 3) {
2769 luaL_Buffer b;
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002770 port = MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002771
Tim Duesterhus6edab862018-01-06 19:04:45 +01002772 /* Force the ip to end with a colon, to support IPv6 addresses
2773 * that are not enclosed within square brackets.
2774 */
2775 if (port > 0) {
2776 luaL_buffinit(L, &b);
2777 luaL_addstring(&b, ip);
2778 luaL_addchar(&b, ':');
2779 luaL_pushresult(&b);
2780 ip = lua_tolstring(L, lua_gettop(L), NULL);
2781 }
2782 }
2783
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002784 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002785 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002786 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002787 lua_pushnil(L);
2788 return 1;
2789 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002790
2791 /* Parse ip address. */
Willy Tarreau5fc93282020-09-16 18:25:03 +02002792 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 +02002793 if (!addr) {
2794 xref_unlock(&socket->xref, peer);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002795 WILL_LJMP(luaL_error(L, "connect: cannot parse destination address '%s'", ip));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002796 }
Willy Tarreau9da9a6f2019-07-17 14:49:44 +02002797
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002798 /* Set port. */
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002799 if (low == 0) {
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02002800 if (addr->ss_family == AF_INET) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002801 if (port == -1) {
2802 xref_unlock(&socket->xref, peer);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002803 WILL_LJMP(luaL_error(L, "connect: port missing"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002804 }
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02002805 ((struct sockaddr_in *)addr)->sin_port = htons(port);
2806 } else if (addr->ss_family == AF_INET6) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002807 if (port == -1) {
2808 xref_unlock(&socket->xref, peer);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002809 WILL_LJMP(luaL_error(L, "connect: port missing"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002810 }
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02002811 ((struct sockaddr_in6 *)addr)->sin6_port = htons(port);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002812 }
2813 }
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02002814
Willy Tarreau5321da92022-05-06 11:57:34 +02002815 csk_ctx = container_of(peer, struct hlua_csk_ctx, xref);
2816 appctx = csk_ctx->appctx;
Willy Tarreau0698c802022-05-11 14:09:57 +02002817 cs = appctx_cs(appctx);
Christopher Faulet908628c2022-03-25 16:43:49 +01002818 s = __cs_strm(cs);
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02002819
Christopher Faulet8da67aa2022-03-29 17:53:09 +02002820 if (!sockaddr_alloc(&cs_opposite(cs)->dst, addr, sizeof(*addr))) {
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02002821 xref_unlock(&socket->xref, peer);
2822 WILL_LJMP(luaL_error(L, "connect: internal error"));
2823 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002824
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002825 /* Get hlua struct, or NULL if we execute from main lua state */
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002826 hlua = hlua_gethlua(L);
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002827 if (!hlua)
2828 return 0;
Willy Tarreaubdc97a82015-08-24 15:42:28 +02002829
2830 /* inform the stream that we want to be notified whenever the
2831 * connection completes.
2832 */
Christopher Fauleta0bdec32022-04-04 07:51:21 +02002833 cs_cant_get(s->csf);
2834 cs_rx_endp_more(s->csf);
Thierry FOURNIER8c8fbbe2015-09-26 17:02:35 +02002835 appctx_wakeup(appctx);
Willy Tarreaubdc97a82015-08-24 15:42:28 +02002836
Willy Tarreauf31af932020-01-14 09:59:38 +01002837 hlua->gc_count++;
Thierry FOURNIER7c39ab42015-09-27 22:53:33 +02002838
Willy Tarreau5321da92022-05-06 11:57:34 +02002839 if (!notification_new(&hlua->com, &csk_ctx->wake_on_write, hlua->task)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002840 xref_unlock(&socket->xref, peer);
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002841 WILL_LJMP(luaL_error(L, "out of memory"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002842 }
2843 xref_unlock(&socket->xref, peer);
PiBa-NL706d5ee2018-05-05 23:51:42 +02002844
2845 task_wakeup(s->task, TASK_WOKEN_INIT);
2846 /* Return yield waiting for connection. */
2847
Willy Tarreau9635e032018-10-16 17:52:55 +02002848 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_connect_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002849
2850 return 0;
2851}
2852
Baptiste Assmann84bb4932015-03-02 21:40:06 +01002853#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002854__LJMP static int hlua_socket_connect_ssl(struct lua_State *L)
2855{
2856 struct hlua_socket *socket;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002857 struct xref *peer;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002858 struct stream *s;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002859
2860 MAY_LJMP(check_args(L, 3, "connect_ssl"));
2861 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002862
2863 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002864 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002865 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002866 lua_pushnil(L);
2867 return 1;
2868 }
Willy Tarreau5321da92022-05-06 11:57:34 +02002869
Willy Tarreau0698c802022-05-11 14:09:57 +02002870 s = appctx_strm(container_of(peer, struct hlua_csk_ctx, xref)->appctx);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002871
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +01002872 s->target = &socket_ssl->obj_type;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002873 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002874 return MAY_LJMP(hlua_socket_connect(L));
2875}
Baptiste Assmann84bb4932015-03-02 21:40:06 +01002876#endif
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002877
2878__LJMP static int hlua_socket_setoption(struct lua_State *L)
2879{
2880 return 0;
2881}
2882
2883__LJMP static int hlua_socket_settimeout(struct lua_State *L)
2884{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002885 struct hlua_socket *socket;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002886 int tmout;
Mark Lakes56cc1252018-03-27 09:48:06 +02002887 double dtmout;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002888 struct xref *peer;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002889 struct stream *s;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002890
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002891 MAY_LJMP(check_args(L, 2, "settimeout"));
2892
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002893 socket = MAY_LJMP(hlua_checksocket(L, 1));
Mark Lakes56cc1252018-03-27 09:48:06 +02002894
Cyril Bonté7ee465f2018-08-19 22:08:50 +02002895 /* convert the timeout to millis */
2896 dtmout = MAY_LJMP(luaL_checknumber(L, 2)) * 1000;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002897
Thierry Fournier17a921b2018-03-08 09:59:02 +01002898 /* Check for negative values */
Mark Lakes56cc1252018-03-27 09:48:06 +02002899 if (dtmout < 0)
Thierry Fournier17a921b2018-03-08 09:59:02 +01002900 WILL_LJMP(luaL_error(L, "settimeout: cannot set negatives values"));
2901
Mark Lakes56cc1252018-03-27 09:48:06 +02002902 if (dtmout > INT_MAX) /* overflow check */
Cyril Bonté7ee465f2018-08-19 22:08:50 +02002903 WILL_LJMP(luaL_error(L, "settimeout: cannot set values larger than %d ms", INT_MAX));
Mark Lakes56cc1252018-03-27 09:48:06 +02002904
2905 tmout = MS_TO_TICKS((int)dtmout);
Cyril Bonté7ee465f2018-08-19 22:08:50 +02002906 if (tmout == 0)
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05002907 tmout++; /* very small timeouts are adjusted to a minimum of 1ms */
Mark Lakes56cc1252018-03-27 09:48:06 +02002908
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002909 /* Check if we run on the same thread than the xreator thread.
2910 * We cannot access to the socket if the thread is different.
2911 */
2912 if (socket->tid != tid)
2913 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2914
Mark Lakes56cc1252018-03-27 09:48:06 +02002915 /* check for connection break. If some data were read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002916 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002917 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002918 hlua_pusherror(L, "socket: not yet initialised, you can't set timeouts.");
2919 WILL_LJMP(lua_error(L));
2920 return 0;
2921 }
Willy Tarreau5321da92022-05-06 11:57:34 +02002922
Willy Tarreau0698c802022-05-11 14:09:57 +02002923 s = appctx_strm(container_of(peer, struct hlua_csk_ctx, xref)->appctx);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002924
Cyril Bonté7bb63452018-08-17 23:51:02 +02002925 s->sess->fe->timeout.connect = tmout;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002926 s->req.rto = tmout;
2927 s->req.wto = tmout;
2928 s->res.rto = tmout;
2929 s->res.wto = tmout;
Cyril Bonté7bb63452018-08-17 23:51:02 +02002930 s->req.rex = tick_add_ifset(now_ms, tmout);
2931 s->req.wex = tick_add_ifset(now_ms, tmout);
2932 s->res.rex = tick_add_ifset(now_ms, tmout);
2933 s->res.wex = tick_add_ifset(now_ms, tmout);
2934
2935 s->task->expire = tick_add_ifset(now_ms, tmout);
2936 task_queue(s->task);
2937
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002938 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002939
Thierry Fourniere9636f12018-03-08 09:54:32 +01002940 lua_pushinteger(L, 1);
Tim Duesterhus119a5f12018-01-06 19:16:25 +01002941 return 1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002942}
2943
2944__LJMP static int hlua_socket_new(lua_State *L)
2945{
2946 struct hlua_socket *socket;
Willy Tarreau5321da92022-05-06 11:57:34 +02002947 struct hlua_csk_ctx *ctx;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002948 struct appctx *appctx;
Willy Tarreau15b5e142015-04-04 14:38:25 +02002949 struct session *sess;
Christopher Faulet13a35e52021-12-20 15:34:16 +01002950 struct conn_stream *cs;
Christopher Fauleta9e8b392022-03-23 11:01:09 +01002951 struct stream *s;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002952
2953 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002954 if (!lua_checkstack(L, 3)) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002955 hlua_pusherror(L, "socket: full stack");
2956 goto out_fail_conf;
2957 }
2958
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002959 /* Create the object: obj[0] = userdata. */
2960 lua_newtable(L);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002961 socket = MAY_LJMP(lua_newuserdata(L, sizeof(*socket)));
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002962 lua_rawseti(L, -2, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002963 memset(socket, 0, sizeof(*socket));
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002964 socket->tid = tid;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002965
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05002966 /* Check if the various memory pools are initialized. */
Willy Tarreaubafbe012017-11-24 17:34:44 +01002967 if (!pool_head_stream || !pool_head_buffer) {
Thierry FOURNIER4a6170c2015-03-09 17:07:10 +01002968 hlua_pusherror(L, "socket: uninitialized pools.");
2969 goto out_fail_conf;
2970 }
2971
Willy Tarreau87b09662015-04-03 00:22:06 +02002972 /* Pop a class stream metatable and affect it to the userdata. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002973 lua_rawgeti(L, LUA_REGISTRYINDEX, class_socket_ref);
2974 lua_setmetatable(L, -2);
2975
Willy Tarreaud420a972015-04-06 00:39:18 +02002976 /* Create the applet context */
Christopher Faulet9ec2f4d2022-03-23 15:15:29 +01002977 appctx = appctx_new(&update_applet, NULL);
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002978 if (!appctx) {
2979 hlua_pusherror(L, "socket: out of memory");
Christopher Fauleta9e8b392022-03-23 11:01:09 +01002980 goto out_fail_conf;
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002981 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002982
Willy Tarreau5321da92022-05-06 11:57:34 +02002983 ctx = applet_reserve_svcctx(appctx, sizeof(*ctx));
2984 ctx->connected = 0;
2985 ctx->appctx = appctx;
2986 ctx->die = 0;
2987 LIST_INIT(&ctx->wake_on_write);
2988 LIST_INIT(&ctx->wake_on_read);
Willy Tarreaub2bf8332015-04-04 15:58:58 +02002989
Willy Tarreaud420a972015-04-06 00:39:18 +02002990 /* Now create a session, task and stream for this applet */
Amaury Denoyelle239fdbf2021-03-24 10:22:03 +01002991 sess = session_new(socket_proxy, NULL, &appctx->obj_type);
Willy Tarreaud420a972015-04-06 00:39:18 +02002992 if (!sess) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002993 hlua_pusherror(L, "socket: out of memory");
Christopher Faulet13a35e52021-12-20 15:34:16 +01002994 goto out_fail_appctx;
2995 }
2996
Christopher Faulet92202da2022-05-11 12:22:10 +02002997 appctx->sess = sess;
Willy Tarreau6796a062022-05-11 16:11:24 +02002998 cs = cs_new_from_endp(appctx->endp, sess, &BUF_NULL);
Christopher Fauleta9e8b392022-03-23 11:01:09 +01002999 if (!cs) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003000 hlua_pusherror(L, "socket: out of memory");
Christopher Faulet92202da2022-05-11 12:22:10 +02003001 goto out_fail_appctx;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003002 }
3003
Christopher Fauleta9e8b392022-03-23 11:01:09 +01003004 s = DISGUISE(cs_strm(cs));
Christopher Faulet2479e5f2022-01-19 14:50:11 +01003005
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003006 /* Initialise cross reference between stream and Lua socket object. */
Willy Tarreau5321da92022-05-06 11:57:34 +02003007 xref_create(&socket->xref, &ctx->xref);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003008
Christopher Faulet6b0a0fb2022-04-04 11:29:28 +02003009 /* Configure "right" conn-stream. this "si" is used to connect
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003010 * and retrieve data from the server. The connection is initialized
3011 * with the "struct server".
3012 */
Christopher Faulet62e75742022-03-31 09:16:34 +02003013 cs_set_state(s->csb, CS_ST_ASS);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003014
3015 /* Force destination server. */
Christopher Fauleta9e8b392022-03-23 11:01:09 +01003016 s->flags |= SF_DIRECT | SF_ASSIGNED | SF_BE_ASSIGNED;
3017 s->target = &socket_tcp->obj_type;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003018
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003019 return 1;
3020
Christopher Faulet13a35e52021-12-20 15:34:16 +01003021 out_fail_appctx:
Willy Tarreaud420a972015-04-06 00:39:18 +02003022 appctx_free(appctx);
3023 out_fail_conf:
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003024 WILL_LJMP(lua_error(L));
3025 return 0;
3026}
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01003027
3028/*
3029 *
3030 *
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003031 * Class Channel
3032 *
3033 *
3034 */
3035
3036/* Returns the struct hlua_channel join to the class channel in the
3037 * stack entry "ud" or throws an argument error.
3038 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01003039__LJMP static struct channel *hlua_checkchannel(lua_State *L, int ud)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003040{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003041 return MAY_LJMP(hlua_checkudata(L, ud, class_channel_ref));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003042}
3043
Willy Tarreau47860ed2015-03-10 14:07:50 +01003044/* Pushes the channel onto the top of the stack. If the stask does not have a
3045 * free slots, the function fails and returns 0;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003046 */
Willy Tarreau2a71af42015-03-10 13:51:50 +01003047static int hlua_channel_new(lua_State *L, struct channel *channel)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003048{
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003049 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003050 if (!lua_checkstack(L, 3))
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003051 return 0;
3052
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003053 lua_newtable(L);
Willy Tarreau47860ed2015-03-10 14:07:50 +01003054 lua_pushlightuserdata(L, channel);
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003055 lua_rawseti(L, -2, 0);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003056
3057 /* Pop a class sesison metatable and affect it to the userdata. */
3058 lua_rawgeti(L, LUA_REGISTRYINDEX, class_channel_ref);
3059 lua_setmetatable(L, -2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003060 return 1;
3061}
3062
Christopher Faulet9f55a502020-02-25 15:21:02 +01003063/* Helper function returning a filter attached to a channel at the position <ud>
3064 * in the stack, filling the current offset and length of the filter. If no
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05003065 * filter is attached, NULL is returned and <offset> and <len> are not
Christopher Faulet9f55a502020-02-25 15:21:02 +01003066 * initialized.
3067 */
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003068static 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 +01003069{
3070 struct filter *filter = NULL;
3071
3072 if (lua_getfield(L, ud, "__filter") == LUA_TLIGHTUSERDATA) {
3073 struct hlua_flt_ctx *flt_ctx;
3074
3075 filter = lua_touserdata (L, -1);
3076 flt_ctx = filter->ctx;
3077 if (hlua_filter_from_payload(filter)) {
3078 *offset = flt_ctx->cur_off[CHN_IDX(chn)];
3079 *len = flt_ctx->cur_len[CHN_IDX(chn)];
3080 }
3081 }
3082
3083 lua_pop(L, 1);
3084 return filter;
3085}
3086
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003087/* Copies <len> bytes of data present in the channel's buffer, starting at the
3088* offset <offset>, and put it in a LUA string variable. It is the caller
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003089* responsibility to ensure <len> and <offset> are valid. It always return the
3090* length of the built string. <len> may be 0, in this case, an empty string is
3091* created and 0 is returned.
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003092*/
3093static inline int _hlua_channel_dup(struct channel *chn, lua_State *L, size_t offset, size_t len)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003094{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003095 size_t block1, block2;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003096 luaL_Buffer b;
3097
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003098 block1 = len;
3099 if (block1 > b_contig_data(&chn->buf, b_peek_ofs(&chn->buf, offset)))
3100 block1 = b_contig_data(&chn->buf, b_peek_ofs(&chn->buf, offset));
3101 block2 = len - block1;
3102
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003103 luaL_buffinit(L, &b);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003104 luaL_addlstring(&b, b_peek(&chn->buf, offset), block1);
3105 if (block2)
3106 luaL_addlstring(&b, b_orig(&chn->buf), block2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003107 luaL_pushresult(&b);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003108 return len;
3109}
3110
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003111/* Inserts the string <str> to the channel's buffer at the offset <offset>. This
3112 * function returns -1 if data cannot be copied. Otherwise, it returns the
3113 * number of bytes copied.
3114 */
3115static int _hlua_channel_insert(struct channel *chn, lua_State *L, struct ist str, size_t offset)
3116{
3117 int ret = 0;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003118
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003119 /* Nothing to do, just return */
3120 if (unlikely(istlen(str) == 0))
3121 goto end;
3122
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003123 if (istlen(str) > c_room(chn)) {
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003124 ret = -1;
3125 goto end;
3126 }
3127 ret = b_insert_blk(&chn->buf, offset, istptr(str), istlen(str));
3128
3129 end:
3130 return ret;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003131}
3132
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003133/* Removes <len> bytes of data at the absolute position <offset>.
3134 */
3135static void _hlua_channel_delete(struct channel *chn, size_t offset, size_t len)
3136{
3137 size_t end = offset + len;
3138
3139 if (b_peek(&chn->buf, end) != b_tail(&chn->buf))
3140 b_move(&chn->buf, b_peek_ofs(&chn->buf, end),
3141 b_data(&chn->buf) - end, -len);
3142 b_sub(&chn->buf, len);
3143}
3144
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003145/* Copies input data in the channel's buffer. It is possible to set a specific
3146 * offset (0 by default) and a length (all remaining input data starting for the
3147 * offset by default). If there is not enough input data and more data can be
3148 * received, this function yields.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003149 *
3150 * From an action, All input data are considered. For a filter, the offset and
3151 * the length of input data to consider are retrieved from the filter context.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003152 */
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003153__LJMP static int hlua_channel_get_data_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003154{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003155 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003156 struct filter *filter;
3157 size_t input, output;
3158 int offset, len;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003159
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003160 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003161
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003162 output = co_data(chn);
3163 input = ci_data(chn);
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003164
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003165 filter = hlua_channel_filter(L, 1, chn, &output, &input);
3166 if (filter && !hlua_filter_from_payload(filter))
3167 WILL_LJMP(lua_error(L));
3168
3169 offset = output;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003170 if (lua_gettop(L) > 1) {
3171 offset = MAY_LJMP(luaL_checkinteger(L, 2));
3172 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02003173 offset = MAX(0, (int)input + offset);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003174 offset += output;
3175 if (offset < output || offset > input + output) {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003176 lua_pushfstring(L, "offset out of range.");
3177 WILL_LJMP(lua_error(L));
3178 }
3179 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003180 len = output + input - offset;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003181 if (lua_gettop(L) == 3) {
3182 len = MAY_LJMP(luaL_checkinteger(L, 3));
3183 if (!len)
3184 goto dup;
3185 if (len == -1)
3186 len = global.tune.bufsize;
3187 if (len < 0) {
3188 lua_pushfstring(L, "length out of range.");
3189 WILL_LJMP(lua_error(L));
3190 }
3191 }
3192
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003193 if (offset + len > output + input) {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003194 if (!HLUA_CANT_YIELD(hlua_gethlua(L)) && !channel_input_closed(chn) && channel_may_recv(chn)) {
3195 /* Yield waiting for more data, as requested */
3196 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_get_data_yield, TICK_ETERNITY, 0));
3197 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003198 len = output + input - offset;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003199 }
3200
3201 dup:
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003202 _hlua_channel_dup(chn, L, offset, len);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003203 return 1;
3204}
3205
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003206/* Copies the first line (including the trailing LF) of input data in the
3207 * channel's buffer. It is possible to set a specific offset (0 by default) and
3208 * a length (all remaining input data starting for the offset by default). If
3209 * there is not enough input data and more data can be received, the function
3210 * yields. If a length is explicitly specified, no more data are
3211 * copied. Otherwise, if no LF is found and more data can be received, this
3212 * function yields.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003213 *
3214 * From an action, All input data are considered. For a filter, the offset and
3215 * the length of input data to consider are retrieved from the filter context.
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003216 */
3217__LJMP static int hlua_channel_get_line_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003218{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003219 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003220 struct filter *filter;
3221 size_t l, input, output;
3222 int offset, len;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003223
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003224 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003225 output = co_data(chn);
3226 input = ci_data(chn);
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003227
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003228 filter = hlua_channel_filter(L, 1, chn, &output, &input);
3229 if (filter && !hlua_filter_from_payload(filter))
3230 WILL_LJMP(lua_error(L));
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003231
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003232 offset = output;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003233 if (lua_gettop(L) > 1) {
3234 offset = MAY_LJMP(luaL_checkinteger(L, 2));
3235 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02003236 offset = MAX(0, (int)input + offset);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003237 offset += output;
3238 if (offset < output || offset > input + output) {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003239 lua_pushfstring(L, "offset out of range.");
3240 WILL_LJMP(lua_error(L));
3241 }
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003242 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003243
3244 len = output + input - offset;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003245 if (lua_gettop(L) == 3) {
3246 len = MAY_LJMP(luaL_checkinteger(L, 3));
3247 if (!len)
3248 goto dup;
3249 if (len == -1)
3250 len = global.tune.bufsize;
3251 if (len < 0) {
3252 lua_pushfstring(L, "length out of range.");
3253 WILL_LJMP(lua_error(L));
3254 }
3255 }
3256
3257 for (l = 0; l < len; l++) {
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003258 if (l + offset >= output + input)
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003259 break;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003260 if (*(b_peek(&chn->buf, offset + l)) == '\n') {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003261 len = l+1;
3262 goto dup;
3263 }
3264 }
3265
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003266 if (offset + len > output + input) {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003267 if (!HLUA_CANT_YIELD(hlua_gethlua(L)) && !channel_input_closed(chn) && channel_may_recv(chn)) {
3268 /* Yield waiting for more data */
3269 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_get_line_yield, TICK_ETERNITY, 0));
3270 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003271 len = output + input - offset;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003272 }
3273
3274 dup:
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003275 _hlua_channel_dup(chn, L, offset, len);
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003276 return 1;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003277}
3278
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003279/* [ DEPRECATED ]
3280 *
3281 * Duplicate all input data foud in the channel's buffer. The data are not
3282 * removed from the buffer. This function relies on _hlua_channel_dup().
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003283 *
3284 * From an action, All input data are considered. For a filter, the offset and
3285 * the length of input data to consider are retrieved from the filter context.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003286 */
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003287__LJMP static int hlua_channel_dup(lua_State *L)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003288{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003289 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003290 struct filter *filter;
3291 size_t offset, len;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003292
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003293 MAY_LJMP(check_args(L, 1, "dup"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003294 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003295 if (IS_HTX_STRM(chn_strm(chn))) {
3296 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3297 WILL_LJMP(lua_error(L));
3298 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003299
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003300 offset = co_data(chn);
3301 len = ci_data(chn);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003302
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003303 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3304 if (filter && !hlua_filter_from_payload(filter))
3305 WILL_LJMP(lua_error(L));
3306
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003307 if (!ci_data(chn) && channel_input_closed(chn)) {
3308 lua_pushnil(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003309 return 1;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003310 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003311
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003312 _hlua_channel_dup(chn, L, offset, len);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003313 return 1;
3314}
3315
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003316/* [ DEPRECATED ]
3317 *
3318 * Get all input data foud in the channel's buffer. The data are removed from
3319 * the buffer after the copy. This function relies on _hlua_channel_dup() and
3320 * _hlua_channel_delete().
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003321 *
3322 * From an action, All input data are considered. For a filter, the offset and
3323 * the length of input data to consider are retrieved from the filter context.
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003324 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003325__LJMP static int hlua_channel_get(lua_State *L)
3326{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003327 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003328 struct filter *filter;
3329 size_t offset, len;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003330 int ret;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003331
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003332 MAY_LJMP(check_args(L, 1, "get"));
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003333 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3334 if (IS_HTX_STRM(chn_strm(chn))) {
3335 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3336 WILL_LJMP(lua_error(L));
3337 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003338
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003339 offset = co_data(chn);
3340 len = ci_data(chn);
3341
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003342 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3343 if (filter && !hlua_filter_from_payload(filter))
3344 WILL_LJMP(lua_error(L));
3345
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003346 if (!ci_data(chn) && channel_input_closed(chn)) {
3347 lua_pushnil(L);
3348 return 1;
3349 }
3350
3351 ret = _hlua_channel_dup(chn, L, offset, len);
3352 _hlua_channel_delete(chn, offset, ret);
3353 return 1;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003354}
3355
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003356/* This functions consumes and returns one line. If the channel is closed,
3357 * and the last data does not contains a final '\n', the data are returned
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003358 * without the final '\n'. When no more data are available, it returns nil
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003359 * value.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003360 *
3361 * From an action, All input data are considered. For a filter, the offset and
3362 * the length of input data to consider are retrieved from the filter context.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003363 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003364__LJMP static int hlua_channel_getline_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003365{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003366 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003367 struct filter *filter;
3368 size_t l, offset, len;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003369 int ret;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003370
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003371 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003372
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003373 offset = co_data(chn);
3374 len = ci_data(chn);
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003375
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003376 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3377 if (filter && !hlua_filter_from_payload(filter))
3378 WILL_LJMP(lua_error(L));
3379
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003380 if (!ci_data(chn) && channel_input_closed(chn)) {
3381 lua_pushnil(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003382 return 1;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003383 }
3384
3385 for (l = 0; l < len; l++) {
3386 if (*(b_peek(&chn->buf, offset+l)) == '\n') {
3387 len = l+1;
3388 goto dup;
3389 }
3390 }
3391
3392 if (!HLUA_CANT_YIELD(hlua_gethlua(L)) && !channel_input_closed(chn) && channel_may_recv(chn)) {
3393 /* Yield waiting for more data */
3394 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_getline_yield, TICK_ETERNITY, 0));
3395 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003396
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003397 dup:
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003398 ret = _hlua_channel_dup(chn, L, offset, len);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003399 _hlua_channel_delete(chn, offset, ret);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003400 return 1;
3401}
3402
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003403/* [ DEPRECATED ]
3404 *
3405 * Check arguments for the function "hlua_channel_getline_yield".
3406 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003407__LJMP static int hlua_channel_getline(lua_State *L)
3408{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003409 struct channel *chn;
3410
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003411 MAY_LJMP(check_args(L, 1, "getline"));
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003412 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3413 if (IS_HTX_STRM(chn_strm(chn))) {
3414 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3415 WILL_LJMP(lua_error(L));
3416 }
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003417 return MAY_LJMP(hlua_channel_getline_yield(L, 0, 0));
3418}
3419
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003420/* Retrieves a given amount of input data at the given offset. By default all
3421 * available input data are returned. The offset may be negactive to start from
3422 * the end of input data. The length may be -1 to set it to the maximum buffer
3423 * size.
3424 */
3425__LJMP static int hlua_channel_get_data(lua_State *L)
3426{
3427 struct channel *chn;
3428
3429 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
3430 WILL_LJMP(luaL_error(L, "'data' expects at most 2 arguments"));
3431 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3432 if (IS_HTX_STRM(chn_strm(chn))) {
3433 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3434 WILL_LJMP(lua_error(L));
3435 }
3436 return MAY_LJMP(hlua_channel_get_data_yield(L, 0, 0));
3437}
3438
3439/* Retrieves a given amount of input data at the given offset. By default all
3440 * available input data are returned. The offset may be negactive to start from
3441 * the end of input data. The length may be -1 to set it to the maximum buffer
3442 * size.
3443 */
3444__LJMP static int hlua_channel_get_line(lua_State *L)
3445{
3446 struct channel *chn;
3447
3448 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
3449 WILL_LJMP(luaL_error(L, "'line' expects at most 2 arguments"));
3450 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3451 if (IS_HTX_STRM(chn_strm(chn))) {
3452 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3453 WILL_LJMP(lua_error(L));
3454 }
3455 return MAY_LJMP(hlua_channel_get_line_yield(L, 0, 0));
3456}
3457
3458/* Appends a string into the input side of channel. It returns the length of the
3459 * written string, or -1 if the channel is closed or if the buffer size is too
3460 * little for the data. 0 may be returned if nothing is copied. This function
3461 * does not yield.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003462 *
3463 * For a filter, the context is updated on success.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003464 */
Christopher Faulet23976d92021-08-06 09:59:49 +02003465__LJMP static int hlua_channel_append(lua_State *L)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003466{
Christopher Faulet23976d92021-08-06 09:59:49 +02003467 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003468 struct filter *filter;
Christopher Faulet23976d92021-08-06 09:59:49 +02003469 const char *str;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003470 size_t sz, offset, len;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003471 int ret;
Christopher Faulet23976d92021-08-06 09:59:49 +02003472
3473 MAY_LJMP(check_args(L, 2, "append"));
3474 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003475 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
Christopher Faulet1bb6afa2021-03-08 17:57:53 +01003476 if (IS_HTX_STRM(chn_strm(chn))) {
Thierry Fournier77016da2020-08-15 14:35:51 +02003477 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
Christopher Faulet3f829a42018-12-13 21:56:45 +01003478 WILL_LJMP(lua_error(L));
Thierry Fournier77016da2020-08-15 14:35:51 +02003479 }
Christopher Faulet3f829a42018-12-13 21:56:45 +01003480
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003481 offset = co_data(chn);
3482 len = ci_data(chn);
3483
3484 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3485 if (filter && !hlua_filter_from_payload(filter))
3486 WILL_LJMP(lua_error(L));
3487
3488 ret = _hlua_channel_insert(chn, L, ist2(str, sz), offset);
3489 if (ret > 0 && filter) {
3490 struct hlua_flt_ctx *flt_ctx = filter->ctx;
3491
3492 flt_update_offsets(filter, chn, ret);
3493 flt_ctx->cur_len[CHN_IDX(chn)] += ret;
3494 }
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003495 lua_pushinteger(L, ret);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003496 return 1;
3497}
3498
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003499/* Prepends a string into the input side of channel. It returns the length of the
3500 * written string, or -1 if the channel is closed or if the buffer size is too
3501 * little for the data. 0 may be returned if nothing is copied. This function
3502 * does not yield.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003503 *
3504 * For a filter, the context is updated on success.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003505 */
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003506__LJMP static int hlua_channel_prepend(lua_State *L)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003507{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003508 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003509 struct filter *filter;
Christopher Faulet23976d92021-08-06 09:59:49 +02003510 const char *str;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003511 size_t sz, offset, len;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003512 int ret;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003513
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003514 MAY_LJMP(check_args(L, 2, "prepend"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003515 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003516 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
3517 if (IS_HTX_STRM(chn_strm(chn))) {
3518 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3519 WILL_LJMP(lua_error(L));
3520 }
3521
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003522 offset = co_data(chn);
3523 len = ci_data(chn);
3524
3525 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3526 if (filter && !hlua_filter_from_payload(filter))
3527 WILL_LJMP(lua_error(L));
3528
3529 ret = _hlua_channel_insert(chn, L, ist2(str, sz), offset);
3530 if (ret > 0 && filter) {
3531 struct hlua_flt_ctx *flt_ctx = filter->ctx;
3532
3533 flt_update_offsets(filter, chn, ret);
3534 flt_ctx->cur_len[CHN_IDX(chn)] += ret;
3535 }
3536
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003537 lua_pushinteger(L, ret);
3538 return 1;
3539}
3540
3541/* Inserts a given amount of input data at the given offset by a string
3542 * content. By default the string is appended at the end of input data. It
3543 * returns the length of the written string, or -1 if the channel is closed or
3544 * if the buffer size is too little for the data.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003545 *
3546 * For a filter, the context is updated on success.
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003547 */
3548__LJMP static int hlua_channel_insert_data(lua_State *L)
3549{
3550 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003551 struct filter *filter;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003552 const char *str;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003553 size_t sz, input, output;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003554 int ret, offset;
3555
3556 if (lua_gettop(L) < 2 || lua_gettop(L) > 3)
3557 WILL_LJMP(luaL_error(L, "'insert' expects at least 1 argument and at most 2 arguments"));
3558 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3559 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003560
3561 output = co_data(chn);
3562 input = ci_data(chn);
3563
3564 filter = hlua_channel_filter(L, 1, chn, &output, &input);
3565 if (filter && !hlua_filter_from_payload(filter))
3566 WILL_LJMP(lua_error(L));
3567
3568 offset = input + output;
3569 if (lua_gettop(L) > 2) {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003570 offset = MAY_LJMP(luaL_checkinteger(L, 3));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003571 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02003572 offset = MAX(0, (int)input + offset);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003573 offset += output;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003574 if (offset < output || offset > output + input) {
3575 lua_pushfstring(L, "offset out of range.");
3576 WILL_LJMP(lua_error(L));
3577 }
3578 }
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003579 if (IS_HTX_STRM(chn_strm(chn))) {
3580 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3581 WILL_LJMP(lua_error(L));
3582 }
3583
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003584 ret = _hlua_channel_insert(chn, L, ist2(str, sz), offset);
3585 if (ret > 0 && filter) {
3586 struct hlua_flt_ctx *flt_ctx = filter->ctx;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003587
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003588 flt_update_offsets(filter, chn, ret);
3589 flt_ctx->cur_len[CHN_IDX(chn)] += ret;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003590 }
3591
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003592 lua_pushinteger(L, ret);
3593 return 1;
3594}
3595/* Replaces a given amount of input data at the given offset by a string
3596 * content. By default all remaining data are removed (offset = 0 and len =
3597 * -1). It returns the length of the written string, or -1 if the channel is
3598 * closed or if the buffer size is too little for the data.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003599 *
3600 * For a filter, the context is updated on success.
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003601 */
3602__LJMP static int hlua_channel_set_data(lua_State *L)
3603{
3604 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003605 struct filter *filter;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003606 const char *str;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003607 size_t sz, input, output;
3608 int ret, offset, len;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003609
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003610 if (lua_gettop(L) < 2 || lua_gettop(L) > 4)
3611 WILL_LJMP(luaL_error(L, "'set' expects at least 1 argument and at most 3 arguments"));
3612 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3613 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003614
Christopher Faulet1bb6afa2021-03-08 17:57:53 +01003615 if (IS_HTX_STRM(chn_strm(chn))) {
Thierry Fournier77016da2020-08-15 14:35:51 +02003616 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
Christopher Faulet3f829a42018-12-13 21:56:45 +01003617 WILL_LJMP(lua_error(L));
Thierry Fournier77016da2020-08-15 14:35:51 +02003618 }
Christopher Faulet3f829a42018-12-13 21:56:45 +01003619
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003620 output = co_data(chn);
3621 input = ci_data(chn);
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003622
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003623 filter = hlua_channel_filter(L, 1, chn, &output, &input);
3624 if (filter && !hlua_filter_from_payload(filter))
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003625 WILL_LJMP(lua_error(L));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003626
3627 offset = output;
3628 if (lua_gettop(L) > 2) {
3629 offset = MAY_LJMP(luaL_checkinteger(L, 3));
3630 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02003631 offset = MAX(0, (int)input + offset);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003632 offset += output;
3633 if (offset < output || offset > input + output) {
3634 lua_pushfstring(L, "offset out of range.");
3635 WILL_LJMP(lua_error(L));
3636 }
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003637 }
3638
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003639 len = output + input - offset;
3640 if (lua_gettop(L) == 4) {
3641 len = MAY_LJMP(luaL_checkinteger(L, 4));
3642 if (!len)
3643 goto set;
3644 if (len == -1)
3645 len = output + input - offset;
3646 if (len < 0 || offset + len > output + input) {
3647 lua_pushfstring(L, "length out of range.");
3648 WILL_LJMP(lua_error(L));
3649 }
3650 }
3651
3652 set:
Christopher Faulet23976d92021-08-06 09:59:49 +02003653 /* Be sure we can copied the string once input data will be removed. */
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003654 if (sz > c_room(chn) + len)
Christopher Faulet23976d92021-08-06 09:59:49 +02003655 lua_pushinteger(L, -1);
3656 else {
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003657 _hlua_channel_delete(chn, offset, len);
3658 ret = _hlua_channel_insert(chn, L, ist2(str, sz), offset);
3659 if (filter) {
3660 struct hlua_flt_ctx *flt_ctx = filter->ctx;
3661
3662 len -= (ret > 0 ? ret : 0);
3663 flt_update_offsets(filter, chn, -len);
3664 flt_ctx->cur_len[CHN_IDX(chn)] -= len;
3665 }
3666
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003667 lua_pushinteger(L, ret);
Christopher Faulet23976d92021-08-06 09:59:49 +02003668 }
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003669 return 1;
3670}
3671
3672/* Removes a given amount of input data at the given offset. By default all
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003673 * input data are removed (offset = 0 and len = -1). It returns the amount of
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003674 * the removed data.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003675 *
3676 * For a filter, the context is updated on success.
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003677 */
3678__LJMP static int hlua_channel_del_data(lua_State *L)
3679{
3680 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003681 struct filter *filter;
3682 size_t input, output;
3683 int offset, len;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003684
3685 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
3686 WILL_LJMP(luaL_error(L, "'remove' expects at most 2 arguments"));
3687 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003688
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003689 if (IS_HTX_STRM(chn_strm(chn))) {
3690 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3691 WILL_LJMP(lua_error(L));
3692 }
3693
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003694 output = co_data(chn);
3695 input = ci_data(chn);
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003696
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003697 filter = hlua_channel_filter(L, 1, chn, &output, &input);
3698 if (filter && !hlua_filter_from_payload(filter))
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003699 WILL_LJMP(lua_error(L));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003700
3701 offset = output;
Boyang Lie0c54352022-05-10 17:47:23 +00003702 if (lua_gettop(L) > 1) {
3703 offset = MAY_LJMP(luaL_checkinteger(L, 2));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003704 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02003705 offset = MAX(0, (int)input + offset);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003706 offset += output;
3707 if (offset < output || offset > input + output) {
3708 lua_pushfstring(L, "offset out of range.");
3709 WILL_LJMP(lua_error(L));
3710 }
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003711 }
3712
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003713 len = output + input - offset;
Boyang Lie0c54352022-05-10 17:47:23 +00003714 if (lua_gettop(L) == 3) {
3715 len = MAY_LJMP(luaL_checkinteger(L, 3));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003716 if (!len)
3717 goto end;
3718 if (len == -1)
3719 len = output + input - offset;
3720 if (len < 0 || offset + len > output + input) {
3721 lua_pushfstring(L, "length out of range.");
3722 WILL_LJMP(lua_error(L));
3723 }
3724 }
3725
3726 _hlua_channel_delete(chn, offset, len);
3727 if (filter) {
3728 struct hlua_flt_ctx *flt_ctx = filter->ctx;
3729
3730 flt_update_offsets(filter, chn, -len);
3731 flt_ctx->cur_len[CHN_IDX(chn)] -= len;
3732 }
3733
3734 end:
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003735 lua_pushinteger(L, len);
Christopher Faulet23976d92021-08-06 09:59:49 +02003736 return 1;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003737}
3738
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003739/* Append data in the output side of the buffer. This data is immediately
3740 * sent. The function returns the amount of data written. If the buffer
3741 * cannot contain the data, the function yields. The function returns -1
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003742 * if the channel is closed.
3743 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003744__LJMP static int hlua_channel_send_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003745{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003746 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003747 struct filter *filter;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003748 const char *str;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003749 size_t offset, len, sz;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003750 int l, ret;
Thierry Fournier4234dbd2020-11-28 13:18:23 +01003751 struct hlua *hlua;
3752
3753 /* Get hlua struct, or NULL if we execute from main lua state */
3754 hlua = hlua_gethlua(L);
3755 if (!hlua) {
3756 lua_pushnil(L);
3757 return 1;
3758 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003759
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003760 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3761 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
3762 l = MAY_LJMP(luaL_checkinteger(L, 3));
Christopher Faulet3f829a42018-12-13 21:56:45 +01003763
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003764 offset = co_data(chn);
3765 len = ci_data(chn);
3766
3767 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3768 if (filter && !hlua_filter_from_payload(filter))
3769 WILL_LJMP(lua_error(L));
3770
3771
Willy Tarreau47860ed2015-03-10 14:07:50 +01003772 if (unlikely(channel_output_closed(chn))) {
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003773 lua_pushinteger(L, -1);
3774 return 1;
3775 }
3776
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003777 len = c_room(chn);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003778 if (len > sz -l) {
3779 if (filter) {
3780 lua_pushinteger(L, -1);
3781 return 1;
3782 }
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003783 len = sz - l;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003784 }
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01003785
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003786 ret = _hlua_channel_insert(chn, L, ist2(str, len), offset);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003787 if (ret == -1) {
3788 lua_pop(L, 1);
3789 lua_pushinteger(L, -1);
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01003790 return 1;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003791 }
3792 if (ret) {
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003793 if (filter) {
3794 struct hlua_flt_ctx *flt_ctx = filter->ctx;
3795
3796
3797 flt_update_offsets(filter, chn, ret);
3798 FLT_OFF(filter, chn) += ret;
3799 flt_ctx->cur_off[CHN_IDX(chn)] += ret;
3800 }
3801 else
3802 c_adv(chn, ret);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003803
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003804 l += ret;
3805 lua_pop(L, 1);
3806 lua_pushinteger(L, l);
3807 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003808
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003809 if (l < sz) {
3810 /* Yield only if the channel's output is not empty.
3811 * Otherwise it means we cannot add more data. */
3812 if (co_data(chn) == 0 || HLUA_CANT_YIELD(hlua_gethlua(L)))
Christopher Faulet2e60aa42021-08-05 11:58:37 +02003813 return 1;
3814
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003815 /* If we are waiting for space in the response buffer, we
3816 * must set the flag WAKERESWR. This flag required the task
3817 * wake up if any activity is detected on the response buffer.
3818 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01003819 if (chn->flags & CF_ISRESP)
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003820 HLUA_SET_WAKERESWR(hlua);
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01003821 else
3822 HLUA_SET_WAKEREQWR(hlua);
Willy Tarreau9635e032018-10-16 17:52:55 +02003823 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003824 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003825
3826 return 1;
3827}
3828
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05003829/* Just a wrapper of "_hlua_channel_send". This wrapper permits
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003830 * yield the LUA process, and resume it without checking the
3831 * input arguments.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003832 *
3833 * This function cannot be called from a filter.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003834 */
3835__LJMP static int hlua_channel_send(lua_State *L)
3836{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003837 struct channel *chn;
3838
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003839 MAY_LJMP(check_args(L, 2, "send"));
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003840 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3841 if (IS_HTX_STRM(chn_strm(chn))) {
3842 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3843 WILL_LJMP(lua_error(L));
3844 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003845 lua_pushinteger(L, 0);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003846 return MAY_LJMP(hlua_channel_send_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003847}
3848
3849/* This function forward and amount of butes. The data pass from
3850 * the input side of the buffer to the output side, and can be
3851 * forwarded. This function never fails.
3852 *
3853 * The Lua function takes an amount of bytes to be forwarded in
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05003854 * input. It returns the number of bytes forwarded.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003855 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003856__LJMP static int hlua_channel_forward_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003857{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003858 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003859 struct filter *filter;
3860 size_t offset, len, fwd;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003861 int l, max;
Thierry Fournier4234dbd2020-11-28 13:18:23 +01003862 struct hlua *hlua;
3863
3864 /* Get hlua struct, or NULL if we execute from main lua state */
3865 hlua = hlua_gethlua(L);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003866 if (!hlua) {
3867 lua_pushnil(L);
Thierry Fournier4234dbd2020-11-28 13:18:23 +01003868 return 1;
Thierry Fournier77016da2020-08-15 14:35:51 +02003869 }
Christopher Faulet3f829a42018-12-13 21:56:45 +01003870
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003871 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003872 fwd = MAY_LJMP(luaL_checkinteger(L, 2));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003873 l = MAY_LJMP(luaL_checkinteger(L, -1));
3874
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003875 offset = co_data(chn);
3876 len = ci_data(chn);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003877
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003878 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3879 if (filter && !hlua_filter_from_payload(filter))
3880 WILL_LJMP(lua_error(L));
3881
3882 max = fwd - l;
3883 if (max > len)
3884 max = len;
3885
3886 if (filter) {
3887 struct hlua_flt_ctx *flt_ctx = filter->ctx;
3888
3889 FLT_OFF(filter, chn) += max;
3890 flt_ctx->cur_off[CHN_IDX(chn)] += max;
3891 flt_ctx->cur_len[CHN_IDX(chn)] -= max;
3892 }
3893 else
3894 channel_forward(chn, max);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003895
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003896 l += max;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003897 lua_pop(L, 1);
3898 lua_pushinteger(L, l);
3899
3900 /* Check if it miss bytes to forward. */
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003901 if (l < fwd) {
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003902 /* The the input channel or the output channel are closed, we
3903 * must return the amount of data forwarded.
3904 */
Christopher Faulet2e60aa42021-08-05 11:58:37 +02003905 if (channel_input_closed(chn) || channel_output_closed(chn) || HLUA_CANT_YIELD(hlua_gethlua(L)))
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003906 return 1;
3907
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003908 /* If we are waiting for space data in the response buffer, we
3909 * must set the flag WAKERESWR. This flag required the task
3910 * wake up if any activity is detected on the response buffer.
3911 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01003912 if (chn->flags & CF_ISRESP)
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003913 HLUA_SET_WAKERESWR(hlua);
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01003914 else
3915 HLUA_SET_WAKEREQWR(hlua);
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003916
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003917 /* Otherwise, we can yield waiting for new data in the inpout side. */
Willy Tarreau9635e032018-10-16 17:52:55 +02003918 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_forward_yield, TICK_ETERNITY, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003919 }
3920
3921 return 1;
3922}
3923
3924/* Just check the input and prepare the stack for the previous
3925 * function "hlua_channel_forward_yield"
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003926 *
3927 * This function cannot be called from a filter.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003928 */
3929__LJMP static int hlua_channel_forward(lua_State *L)
3930{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003931 struct channel *chn;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003932
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003933 MAY_LJMP(check_args(L, 2, "forward"));
3934 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3935 if (IS_HTX_STRM(chn_strm(chn))) {
3936 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3937 WILL_LJMP(lua_error(L));
3938 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003939 lua_pushinteger(L, 0);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003940 return MAY_LJMP(hlua_channel_forward_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003941}
3942
3943/* Just returns the number of bytes available in the input
3944 * side of the buffer. This function never fails.
3945 */
3946__LJMP static int hlua_channel_get_in_len(lua_State *L)
3947{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003948 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003949 struct filter *filter;
3950 size_t output, input;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003951
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003952 MAY_LJMP(check_args(L, 1, "input"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003953 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003954
3955 output = co_data(chn);
3956 input = ci_data(chn);
3957 filter = hlua_channel_filter(L, 1, chn, &output, &input);
3958 if (filter || !IS_HTX_STRM(chn_strm(chn)))
3959 lua_pushinteger(L, input);
3960 else {
Christopher Fauleta3ceac12018-12-14 13:39:09 +01003961 struct htx *htx = htxbuf(&chn->buf);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003962
Christopher Fauleta3ceac12018-12-14 13:39:09 +01003963 lua_pushinteger(L, htx->data - co_data(chn));
3964 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003965 return 1;
3966}
3967
Thierry FOURNIER / OZON.IO65192f32016-11-07 15:28:40 +01003968/* Returns true if the channel is full. */
3969__LJMP static int hlua_channel_is_full(lua_State *L)
3970{
3971 struct channel *chn;
Thierry FOURNIER / OZON.IO65192f32016-11-07 15:28:40 +01003972
3973 MAY_LJMP(check_args(L, 1, "is_full"));
3974 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Faulet0ec740e2020-02-26 11:59:19 +01003975 /* ignore the reserve, we are not on a producer side (ie in an
3976 * applet).
3977 */
3978 lua_pushboolean(L, channel_full(chn, 0));
Thierry FOURNIER / OZON.IO65192f32016-11-07 15:28:40 +01003979 return 1;
3980}
3981
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003982/* Returns true if the channel may still receive data. */
3983__LJMP static int hlua_channel_may_recv(lua_State *L)
3984{
3985 struct channel *chn;
3986
3987 MAY_LJMP(check_args(L, 1, "may_recv"));
3988 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3989 lua_pushboolean(L, (!channel_input_closed(chn) && channel_may_recv(chn)));
3990 return 1;
3991}
3992
Christopher Faulet2ac9ba22020-02-25 10:15:50 +01003993/* Returns true if the channel is the response channel. */
3994__LJMP static int hlua_channel_is_resp(lua_State *L)
3995{
3996 struct channel *chn;
3997
3998 MAY_LJMP(check_args(L, 1, "is_resp"));
3999 chn = MAY_LJMP(hlua_checkchannel(L, 1));
4000
4001 lua_pushboolean(L, !!(chn->flags & CF_ISRESP));
4002 return 1;
4003}
4004
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004005/* Just returns the number of bytes available in the output
4006 * side of the buffer. This function never fails.
4007 */
4008__LJMP static int hlua_channel_get_out_len(lua_State *L)
4009{
Willy Tarreau47860ed2015-03-10 14:07:50 +01004010 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004011 size_t output, input;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004012
Christopher Faulet6a79fc12021-08-06 16:02:36 +02004013 MAY_LJMP(check_args(L, 1, "output"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004014 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004015
4016 output = co_data(chn);
4017 input = ci_data(chn);
4018 hlua_channel_filter(L, 1, chn, &output, &input);
4019
4020 lua_pushinteger(L, output);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004021 return 1;
4022}
4023
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004024/*
4025 *
4026 *
4027 * Class Fetches
4028 *
4029 *
4030 */
4031
4032/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02004033 * a class stream, otherwise it throws an error.
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004034 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004035__LJMP static struct hlua_smp *hlua_checkfetches(lua_State *L, int ud)
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004036{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004037 return MAY_LJMP(hlua_checkudata(L, ud, class_fetches_ref));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004038}
4039
4040/* This function creates and push in the stack a fetch object according
4041 * with a current TXN.
4042 */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004043static int hlua_fetches_new(lua_State *L, struct hlua_txn *txn, unsigned int flags)
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004044{
Willy Tarreau7073c472015-04-06 11:15:40 +02004045 struct hlua_smp *hsmp;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004046
4047 /* Check stack size. */
4048 if (!lua_checkstack(L, 3))
4049 return 0;
4050
4051 /* Create the object: obj[0] = userdata.
4052 * Note that the base of the Fetches object is the
4053 * transaction object.
4054 */
4055 lua_newtable(L);
Willy Tarreau7073c472015-04-06 11:15:40 +02004056 hsmp = lua_newuserdata(L, sizeof(*hsmp));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004057 lua_rawseti(L, -2, 0);
4058
Willy Tarreau7073c472015-04-06 11:15:40 +02004059 hsmp->s = txn->s;
4060 hsmp->p = txn->p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01004061 hsmp->dir = txn->dir;
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004062 hsmp->flags = flags;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004063
4064 /* Pop a class sesison metatable and affect it to the userdata. */
4065 lua_rawgeti(L, LUA_REGISTRYINDEX, class_fetches_ref);
4066 lua_setmetatable(L, -2);
4067
4068 return 1;
4069}
4070
4071/* This function is an LUA binding. It is called with each sample-fetch.
4072 * It uses closure argument to store the associated sample-fetch. It
4073 * returns only one argument or throws an error. An error is thrown
4074 * only if an error is encountered during the argument parsing. If
4075 * the "sample-fetch" function fails, nil is returned.
4076 */
4077__LJMP static int hlua_run_sample_fetch(lua_State *L)
4078{
Willy Tarreaub2ccb562015-04-06 11:11:15 +02004079 struct hlua_smp *hsmp;
Willy Tarreau2ec22742015-03-10 14:27:20 +01004080 struct sample_fetch *f;
Frédéric Lécaillef874a832018-06-15 13:56:04 +02004081 struct arg args[ARGM_NBARGS + 1] = {{0}};
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004082 int i;
4083 struct sample smp;
4084
4085 /* Get closure arguments. */
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004086 f = lua_touserdata(L, lua_upvalueindex(1));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004087
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004088 /* Get traditional arguments. */
Willy Tarreaub2ccb562015-04-06 11:11:15 +02004089 hsmp = MAY_LJMP(hlua_checkfetches(L, 1));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004090
Thierry FOURNIERca988662015-12-20 18:43:03 +01004091 /* Check execution authorization. */
4092 if (f->use & SMP_USE_HTTP_ANY &&
4093 !(hsmp->flags & HLUA_F_MAY_USE_HTTP)) {
4094 lua_pushfstring(L, "the sample-fetch '%s' needs an HTTP parser which "
4095 "is not available in Lua services", f->kw);
4096 WILL_LJMP(lua_error(L));
4097 }
4098
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004099 /* Get extra arguments. */
4100 for (i = 0; i < lua_gettop(L) - 1; i++) {
4101 if (i >= ARGM_NBARGS)
4102 break;
4103 hlua_lua2arg(L, i + 2, &args[i]);
4104 }
4105 args[i].type = ARGT_STOP;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004106 args[i].data.str.area = NULL;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004107
4108 /* Check arguments. */
Willy Tarreaub2ccb562015-04-06 11:11:15 +02004109 MAY_LJMP(hlua_lua2arg_check(L, 2, args, f->arg_mask, hsmp->p));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004110
4111 /* Run the special args checker. */
Willy Tarreau2ec22742015-03-10 14:27:20 +01004112 if (f->val_args && !f->val_args(args, NULL)) {
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004113 lua_pushfstring(L, "error in arguments");
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004114 goto error;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004115 }
4116
4117 /* Initialise the sample. */
4118 memset(&smp, 0, sizeof(smp));
4119
4120 /* Run the sample fetch process. */
Willy Tarreau1777ea62016-03-10 16:15:46 +01004121 smp_set_owner(&smp, hsmp->p, hsmp->s->sess, hsmp->s, hsmp->dir & SMP_OPT_DIR);
Thierry FOURNIER0786d052015-05-11 15:42:45 +02004122 if (!f->process(args, &smp, f->kw, f->private)) {
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004123 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004124 lua_pushstring(L, "");
4125 else
4126 lua_pushnil(L);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004127 goto end;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004128 }
4129
4130 /* Convert the returned sample in lua value. */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004131 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004132 hlua_smp2lua_str(L, &smp);
4133 else
4134 hlua_smp2lua(L, &smp);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004135
4136 end:
Willy Tarreauee0d7272021-07-16 10:26:56 +02004137 free_args(args);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004138 return 1;
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004139
4140 error:
Willy Tarreauee0d7272021-07-16 10:26:56 +02004141 free_args(args);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004142 WILL_LJMP(lua_error(L));
4143 return 0; /* Never reached */
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004144}
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004145
4146/*
4147 *
4148 *
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004149 * Class Converters
4150 *
4151 *
4152 */
4153
4154/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02004155 * a class stream, otherwise it throws an error.
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004156 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004157__LJMP static struct hlua_smp *hlua_checkconverters(lua_State *L, int ud)
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004158{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004159 return MAY_LJMP(hlua_checkudata(L, ud, class_converters_ref));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004160}
4161
4162/* This function creates and push in the stack a Converters object
4163 * according with a current TXN.
4164 */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004165static int hlua_converters_new(lua_State *L, struct hlua_txn *txn, unsigned int flags)
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004166{
Willy Tarreau7073c472015-04-06 11:15:40 +02004167 struct hlua_smp *hsmp;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004168
4169 /* Check stack size. */
4170 if (!lua_checkstack(L, 3))
4171 return 0;
4172
4173 /* Create the object: obj[0] = userdata.
4174 * Note that the base of the Converters object is the
4175 * same than the TXN object.
4176 */
4177 lua_newtable(L);
Willy Tarreau7073c472015-04-06 11:15:40 +02004178 hsmp = lua_newuserdata(L, sizeof(*hsmp));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004179 lua_rawseti(L, -2, 0);
4180
Willy Tarreau7073c472015-04-06 11:15:40 +02004181 hsmp->s = txn->s;
4182 hsmp->p = txn->p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01004183 hsmp->dir = txn->dir;
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004184 hsmp->flags = flags;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004185
Willy Tarreau87b09662015-04-03 00:22:06 +02004186 /* Pop a class stream metatable and affect it to the table. */
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004187 lua_rawgeti(L, LUA_REGISTRYINDEX, class_converters_ref);
4188 lua_setmetatable(L, -2);
4189
4190 return 1;
4191}
4192
4193/* This function is an LUA binding. It is called with each converter.
4194 * It uses closure argument to store the associated converter. It
4195 * returns only one argument or throws an error. An error is thrown
4196 * only if an error is encountered during the argument parsing. If
4197 * the converter function function fails, nil is returned.
4198 */
4199__LJMP static int hlua_run_sample_conv(lua_State *L)
4200{
Willy Tarreauda5f1082015-04-06 11:17:13 +02004201 struct hlua_smp *hsmp;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004202 struct sample_conv *conv;
Frédéric Lécaillef874a832018-06-15 13:56:04 +02004203 struct arg args[ARGM_NBARGS + 1] = {{0}};
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004204 int i;
4205 struct sample smp;
4206
4207 /* Get closure arguments. */
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004208 conv = lua_touserdata(L, lua_upvalueindex(1));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004209
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004210 /* Get traditional arguments. */
Willy Tarreauda5f1082015-04-06 11:17:13 +02004211 hsmp = MAY_LJMP(hlua_checkconverters(L, 1));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004212
4213 /* Get extra arguments. */
4214 for (i = 0; i < lua_gettop(L) - 2; i++) {
4215 if (i >= ARGM_NBARGS)
4216 break;
4217 hlua_lua2arg(L, i + 3, &args[i]);
4218 }
4219 args[i].type = ARGT_STOP;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004220 args[i].data.str.area = NULL;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004221
4222 /* Check arguments. */
Willy Tarreauda5f1082015-04-06 11:17:13 +02004223 MAY_LJMP(hlua_lua2arg_check(L, 3, args, conv->arg_mask, hsmp->p));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004224
4225 /* Run the special args checker. */
4226 if (conv->val_args && !conv->val_args(args, conv, "", 0, NULL)) {
4227 hlua_pusherror(L, "error in arguments");
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004228 goto error;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004229 }
4230
4231 /* Initialise the sample. */
Amaury Denoyellebc0af6a2020-10-29 17:21:20 +01004232 memset(&smp, 0, sizeof(smp));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004233 if (!hlua_lua2smp(L, 2, &smp)) {
4234 hlua_pusherror(L, "error in the input argument");
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004235 goto error;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004236 }
4237
Willy Tarreau1777ea62016-03-10 16:15:46 +01004238 smp_set_owner(&smp, hsmp->p, hsmp->s->sess, hsmp->s, hsmp->dir & SMP_OPT_DIR);
4239
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004240 /* Apply expected cast. */
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02004241 if (!sample_casts[smp.data.type][conv->in_type]) {
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004242 hlua_pusherror(L, "invalid input argument: cannot cast '%s' to '%s'",
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02004243 smp_to_type[smp.data.type], smp_to_type[conv->in_type]);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004244 goto error;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004245 }
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02004246 if (sample_casts[smp.data.type][conv->in_type] != c_none &&
4247 !sample_casts[smp.data.type][conv->in_type](&smp)) {
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004248 hlua_pusherror(L, "error during the input argument casting");
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004249 goto error;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004250 }
4251
4252 /* Run the sample conversion process. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02004253 if (!conv->process(args, &smp, conv->private)) {
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004254 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004255 lua_pushstring(L, "");
4256 else
Willy Tarreaua678b432015-08-28 10:14:59 +02004257 lua_pushnil(L);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004258 goto end;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004259 }
4260
4261 /* Convert the returned sample in lua value. */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004262 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004263 hlua_smp2lua_str(L, &smp);
4264 else
4265 hlua_smp2lua(L, &smp);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004266 end:
Willy Tarreauee0d7272021-07-16 10:26:56 +02004267 free_args(args);
Willy Tarreaua678b432015-08-28 10:14:59 +02004268 return 1;
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004269
4270 error:
Willy Tarreauee0d7272021-07-16 10:26:56 +02004271 free_args(args);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004272 WILL_LJMP(lua_error(L));
4273 return 0; /* Never reached */
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004274}
4275
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004276/*
4277 *
4278 *
4279 * Class AppletTCP
4280 *
4281 *
4282 */
4283
4284/* Returns a struct hlua_txn if the stack entry "ud" is
4285 * a class stream, otherwise it throws an error.
4286 */
4287__LJMP static struct hlua_appctx *hlua_checkapplet_tcp(lua_State *L, int ud)
4288{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004289 return MAY_LJMP(hlua_checkudata(L, ud, class_applet_tcp_ref));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004290}
4291
4292/* This function creates and push in the stack an Applet object
4293 * according with a current TXN.
4294 */
4295static int hlua_applet_tcp_new(lua_State *L, struct appctx *ctx)
4296{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004297 struct hlua_appctx *luactx;
Willy Tarreau0698c802022-05-11 14:09:57 +02004298 struct stream *s = appctx_strm(ctx);
Christopher Faulet2da02ae2022-02-24 13:45:27 +01004299 struct proxy *p;
4300
4301 ALREADY_CHECKED(s);
4302 p = s->be;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004303
4304 /* Check stack size. */
4305 if (!lua_checkstack(L, 3))
4306 return 0;
4307
4308 /* Create the object: obj[0] = userdata.
4309 * Note that the base of the Converters object is the
4310 * same than the TXN object.
4311 */
4312 lua_newtable(L);
Willy Tarreau7e702d12021-04-28 17:59:21 +02004313 luactx = lua_newuserdata(L, sizeof(*luactx));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004314 lua_rawseti(L, -2, 0);
Willy Tarreau7e702d12021-04-28 17:59:21 +02004315 luactx->appctx = ctx;
4316 luactx->htxn.s = s;
4317 luactx->htxn.p = p;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004318
4319 /* Create the "f" field that contains a list of fetches. */
4320 lua_pushstring(L, "f");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004321 if (!hlua_fetches_new(L, &luactx->htxn, 0))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004322 return 0;
4323 lua_settable(L, -3);
4324
4325 /* Create the "sf" field that contains a list of stringsafe fetches. */
4326 lua_pushstring(L, "sf");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004327 if (!hlua_fetches_new(L, &luactx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004328 return 0;
4329 lua_settable(L, -3);
4330
4331 /* Create the "c" field that contains a list of converters. */
4332 lua_pushstring(L, "c");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004333 if (!hlua_converters_new(L, &luactx->htxn, 0))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004334 return 0;
4335 lua_settable(L, -3);
4336
4337 /* Create the "sc" field that contains a list of stringsafe converters. */
4338 lua_pushstring(L, "sc");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004339 if (!hlua_converters_new(L, &luactx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004340 return 0;
4341 lua_settable(L, -3);
4342
4343 /* Pop a class stream metatable and affect it to the table. */
4344 lua_rawgeti(L, LUA_REGISTRYINDEX, class_applet_tcp_ref);
4345 lua_setmetatable(L, -2);
4346
4347 return 1;
4348}
4349
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004350__LJMP static int hlua_applet_tcp_set_var(lua_State *L)
4351{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004352 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004353 struct stream *s;
4354 const char *name;
4355 size_t len;
4356 struct sample smp;
4357
Tim Duesterhus4e172c92020-05-19 13:49:42 +02004358 if (lua_gettop(L) < 3 || lua_gettop(L) > 4)
4359 WILL_LJMP(luaL_error(L, "'set_var' needs between 3 and 4 arguments"));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004360
4361 /* It is useles to retrieve the stream, but this function
4362 * runs only in a stream context.
4363 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004364 luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004365 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02004366 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004367
4368 /* Converts the third argument in a sample. */
Amaury Denoyellebc0af6a2020-10-29 17:21:20 +01004369 memset(&smp, 0, sizeof(smp));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004370 hlua_lua2smp(L, 3, &smp);
4371
4372 /* Store the sample in a variable. */
4373 smp_set_owner(&smp, s->be, s->sess, s, 0);
Tim Duesterhus4e172c92020-05-19 13:49:42 +02004374
4375 if (lua_gettop(L) == 4 && lua_toboolean(L, 4))
4376 lua_pushboolean(L, vars_set_by_name_ifexist(name, len, &smp) != 0);
4377 else
4378 lua_pushboolean(L, vars_set_by_name(name, len, &smp) != 0);
4379
Tim Duesterhus84ebc132020-05-19 13:49:41 +02004380 return 1;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004381}
4382
4383__LJMP static int hlua_applet_tcp_unset_var(lua_State *L)
4384{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004385 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004386 struct stream *s;
4387 const char *name;
4388 size_t len;
4389 struct sample smp;
4390
4391 MAY_LJMP(check_args(L, 2, "unset_var"));
4392
4393 /* It is useles to retrieve the stream, but this function
4394 * runs only in a stream context.
4395 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004396 luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004397 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02004398 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004399
4400 /* Unset the variable. */
4401 smp_set_owner(&smp, s->be, s->sess, s, 0);
Tim Duesterhus84ebc132020-05-19 13:49:41 +02004402 lua_pushboolean(L, vars_unset_by_name_ifexist(name, len, &smp) != 0);
4403 return 1;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004404}
4405
4406__LJMP static int hlua_applet_tcp_get_var(lua_State *L)
4407{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004408 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004409 struct stream *s;
4410 const char *name;
4411 size_t len;
4412 struct sample smp;
4413
4414 MAY_LJMP(check_args(L, 2, "get_var"));
4415
4416 /* It is useles to retrieve the stream, but this function
4417 * runs only in a stream context.
4418 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004419 luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004420 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02004421 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004422
4423 smp_set_owner(&smp, s->be, s->sess, s, 0);
Willy Tarreaue352b9d2021-09-03 11:52:38 +02004424 if (!vars_get_by_name(name, len, &smp, NULL)) {
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004425 lua_pushnil(L);
4426 return 1;
4427 }
4428
4429 return hlua_smp2lua(L, &smp);
4430}
4431
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004432__LJMP static int hlua_applet_tcp_set_priv(lua_State *L)
4433{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004434 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
4435 struct stream *s = luactx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01004436 struct hlua *hlua;
4437
4438 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01004439 if (!s->hlua)
4440 return 0;
4441 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004442
4443 MAY_LJMP(check_args(L, 2, "set_priv"));
4444
4445 /* Remove previous value. */
Thierry FOURNIERe068b602017-04-26 13:27:05 +02004446 luaL_unref(L, LUA_REGISTRYINDEX, hlua->Mref);
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004447
4448 /* Get and store new value. */
4449 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
4450 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
4451
4452 return 0;
4453}
4454
4455__LJMP static int hlua_applet_tcp_get_priv(lua_State *L)
4456{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004457 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
4458 struct stream *s = luactx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01004459 struct hlua *hlua;
4460
4461 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01004462 if (!s->hlua) {
4463 lua_pushnil(L);
4464 return 1;
4465 }
4466 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004467
4468 /* Push configuration index in the stack. */
4469 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
4470
4471 return 1;
4472}
4473
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004474/* If expected data not yet available, it returns a yield. This function
4475 * consumes the data in the buffer. It returns a string containing the
4476 * data. This string can be empty.
4477 */
4478__LJMP static int hlua_applet_tcp_getline_yield(lua_State *L, int status, lua_KContext ctx)
4479{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004480 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Willy Tarreau0698c802022-05-11 14:09:57 +02004481 struct conn_stream *cs = appctx_cs(luactx->appctx);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004482 int ret;
Willy Tarreau206ba832018-06-14 15:27:31 +02004483 const char *blk1;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004484 size_t len1;
Willy Tarreau206ba832018-06-14 15:27:31 +02004485 const char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004486 size_t len2;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004487
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004488 /* Read the maximum amount of data available. */
Christopher Faulet908628c2022-03-25 16:43:49 +01004489 ret = co_getline_nc(cs_oc(cs), &blk1, &len1, &blk2, &len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004490
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004491 /* Data not yet available. return yield. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004492 if (ret == 0) {
Christopher Fauleta0bdec32022-04-04 07:51:21 +02004493 cs_cant_get(cs);
Willy Tarreau9635e032018-10-16 17:52:55 +02004494 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_getline_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004495 }
4496
4497 /* End of data: commit the total strings and return. */
4498 if (ret < 0) {
Willy Tarreau7e702d12021-04-28 17:59:21 +02004499 luaL_pushresult(&luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004500 return 1;
4501 }
4502
4503 /* Ensure that the block 2 length is usable. */
4504 if (ret == 1)
4505 len2 = 0;
4506
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -07004507 /* don't check the max length read and don't check. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004508 luaL_addlstring(&luactx->b, blk1, len1);
4509 luaL_addlstring(&luactx->b, blk2, len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004510
4511 /* Consume input channel output buffer data. */
Christopher Faulet908628c2022-03-25 16:43:49 +01004512 co_skip(cs_oc(cs), len1 + len2);
Willy Tarreau7e702d12021-04-28 17:59:21 +02004513 luaL_pushresult(&luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004514 return 1;
4515}
4516
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004517/* Check arguments for the function "hlua_channel_get_yield". */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004518__LJMP static int hlua_applet_tcp_getline(lua_State *L)
4519{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004520 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004521
4522 /* Initialise the string catenation. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004523 luaL_buffinit(L, &luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004524
4525 return MAY_LJMP(hlua_applet_tcp_getline_yield(L, 0, 0));
4526}
4527
4528/* If expected data not yet available, it returns a yield. This function
4529 * consumes the data in the buffer. It returns a string containing the
4530 * data. This string can be empty.
4531 */
4532__LJMP static int hlua_applet_tcp_recv_yield(lua_State *L, int status, lua_KContext ctx)
4533{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004534 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Willy Tarreau0698c802022-05-11 14:09:57 +02004535 struct conn_stream *cs = appctx_cs(luactx->appctx);
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004536 size_t len = MAY_LJMP(luaL_checkinteger(L, 2));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004537 int ret;
Willy Tarreau206ba832018-06-14 15:27:31 +02004538 const char *blk1;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004539 size_t len1;
Willy Tarreau206ba832018-06-14 15:27:31 +02004540 const char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004541 size_t len2;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004542
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004543 /* Read the maximum amount of data available. */
Christopher Faulet908628c2022-03-25 16:43:49 +01004544 ret = co_getblk_nc(cs_oc(cs), &blk1, &len1, &blk2, &len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004545
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004546 /* Data not yet available. return yield. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004547 if (ret == 0) {
Christopher Fauleta0bdec32022-04-04 07:51:21 +02004548 cs_cant_get(cs);
Willy Tarreau9635e032018-10-16 17:52:55 +02004549 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004550 }
4551
4552 /* End of data: commit the total strings and return. */
4553 if (ret < 0) {
Willy Tarreau7e702d12021-04-28 17:59:21 +02004554 luaL_pushresult(&luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004555 return 1;
4556 }
4557
4558 /* Ensure that the block 2 length is usable. */
4559 if (ret == 1)
4560 len2 = 0;
4561
4562 if (len == -1) {
4563
4564 /* If len == -1, catenate all the data avalaile and
4565 * yield because we want to get all the data until
4566 * the end of data stream.
4567 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004568 luaL_addlstring(&luactx->b, blk1, len1);
4569 luaL_addlstring(&luactx->b, blk2, len2);
Christopher Faulet908628c2022-03-25 16:43:49 +01004570 co_skip(cs_oc(cs), len1 + len2);
Christopher Fauleta0bdec32022-04-04 07:51:21 +02004571 cs_cant_get(cs);
Willy Tarreau9635e032018-10-16 17:52:55 +02004572 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004573
4574 } else {
4575
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05004576 /* Copy the first block caping to the length required. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004577 if (len1 > len)
4578 len1 = len;
Willy Tarreau7e702d12021-04-28 17:59:21 +02004579 luaL_addlstring(&luactx->b, blk1, len1);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004580 len -= len1;
4581
4582 /* Copy the second block. */
4583 if (len2 > len)
4584 len2 = len;
Willy Tarreau7e702d12021-04-28 17:59:21 +02004585 luaL_addlstring(&luactx->b, blk2, len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004586 len -= len2;
4587
4588 /* Consume input channel output buffer data. */
Christopher Faulet908628c2022-03-25 16:43:49 +01004589 co_skip(cs_oc(cs), len1 + len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004590
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004591 /* If there is no other data available, yield waiting for new data. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004592 if (len > 0) {
4593 lua_pushinteger(L, len);
4594 lua_replace(L, 2);
Christopher Fauleta0bdec32022-04-04 07:51:21 +02004595 cs_cant_get(cs);
Willy Tarreau9635e032018-10-16 17:52:55 +02004596 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004597 }
4598
4599 /* return the result. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004600 luaL_pushresult(&luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004601 return 1;
4602 }
4603
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004604 /* we never execute this */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004605 hlua_pusherror(L, "Lua: internal error");
4606 WILL_LJMP(lua_error(L));
4607 return 0;
4608}
4609
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004610/* Check arguments for the function "hlua_channel_get_yield". */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004611__LJMP static int hlua_applet_tcp_recv(lua_State *L)
4612{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004613 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004614 int len = -1;
4615
4616 if (lua_gettop(L) > 2)
4617 WILL_LJMP(luaL_error(L, "The 'recv' function requires between 1 and 2 arguments."));
4618 if (lua_gettop(L) >= 2) {
4619 len = MAY_LJMP(luaL_checkinteger(L, 2));
4620 lua_pop(L, 1);
4621 }
4622
4623 /* Confirm or set the required length */
4624 lua_pushinteger(L, len);
4625
4626 /* Initialise the string catenation. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004627 luaL_buffinit(L, &luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004628
4629 return MAY_LJMP(hlua_applet_tcp_recv_yield(L, 0, 0));
4630}
4631
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004632/* Append data in the output side of the buffer. This data is immediately
4633 * sent. The function returns the amount of data written. If the buffer
4634 * cannot contain the data, the function yields. The function returns -1
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004635 * if the channel is closed.
4636 */
4637__LJMP static int hlua_applet_tcp_send_yield(lua_State *L, int status, lua_KContext ctx)
4638{
4639 size_t len;
Willy Tarreau7e702d12021-04-28 17:59:21 +02004640 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004641 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
4642 int l = MAY_LJMP(luaL_checkinteger(L, 3));
Willy Tarreau0698c802022-05-11 14:09:57 +02004643 struct conn_stream *cs = appctx_cs(luactx->appctx);
Christopher Faulet908628c2022-03-25 16:43:49 +01004644 struct channel *chn = cs_ic(cs);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004645 int max;
4646
4647 /* Get the max amount of data which can write as input in the channel. */
4648 max = channel_recv_max(chn);
4649 if (max > (len - l))
4650 max = len - l;
4651
4652 /* Copy data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02004653 ci_putblk(chn, str + l, max);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004654
4655 /* update counters. */
4656 l += max;
4657 lua_pop(L, 1);
4658 lua_pushinteger(L, l);
4659
4660 /* If some data is not send, declares the situation to the
4661 * applet, and returns a yield.
4662 */
4663 if (l < len) {
Christopher Fauleta0bdec32022-04-04 07:51:21 +02004664 cs_rx_room_blk(cs);
Willy Tarreau9635e032018-10-16 17:52:55 +02004665 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004666 }
4667
4668 return 1;
4669}
4670
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05004671/* Just a wrapper of "hlua_applet_tcp_send_yield". This wrapper permits
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004672 * yield the LUA process, and resume it without checking the
4673 * input arguments.
4674 */
4675__LJMP static int hlua_applet_tcp_send(lua_State *L)
4676{
4677 MAY_LJMP(check_args(L, 2, "send"));
4678 lua_pushinteger(L, 0);
4679
4680 return MAY_LJMP(hlua_applet_tcp_send_yield(L, 0, 0));
4681}
4682
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004683/*
4684 *
4685 *
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004686 * Class AppletHTTP
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004687 *
4688 *
4689 */
4690
4691/* Returns a struct hlua_txn if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02004692 * a class stream, otherwise it throws an error.
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004693 */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004694__LJMP static struct hlua_appctx *hlua_checkapplet_http(lua_State *L, int ud)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004695{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004696 return MAY_LJMP(hlua_checkudata(L, ud, class_applet_http_ref));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004697}
4698
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004699/* This function creates and push in the stack an Applet object
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004700 * according with a current TXN.
Willy Tarreauaa229cc2022-05-06 14:26:10 +02004701 * It relies on the caller to have already reserved the room in ctx->svcctx
4702 * for the local storage of hlua_http_ctx.
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004703 */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004704static int hlua_applet_http_new(lua_State *L, struct appctx *ctx)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004705{
Willy Tarreauaa229cc2022-05-06 14:26:10 +02004706 struct hlua_http_ctx *http_ctx = ctx->svcctx;
Willy Tarreau7e702d12021-04-28 17:59:21 +02004707 struct hlua_appctx *luactx;
Thierry FOURNIER841475e2015-12-11 17:10:09 +01004708 struct hlua_txn htxn;
Willy Tarreau0698c802022-05-11 14:09:57 +02004709 struct stream *s = appctx_strm(ctx);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004710 struct proxy *px = s->be;
Christopher Fauleta2097962019-07-15 16:25:33 +02004711 struct htx *htx;
4712 struct htx_blk *blk;
4713 struct htx_sl *sl;
4714 struct ist path;
4715 unsigned long long len = 0;
4716 int32_t pos;
Amaury Denoyellec453f952021-07-06 11:40:12 +02004717 struct http_uri_parser parser;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004718
4719 /* Check stack size. */
4720 if (!lua_checkstack(L, 3))
4721 return 0;
4722
4723 /* Create the object: obj[0] = userdata.
4724 * Note that the base of the Converters object is the
4725 * same than the TXN object.
4726 */
4727 lua_newtable(L);
Willy Tarreau7e702d12021-04-28 17:59:21 +02004728 luactx = lua_newuserdata(L, sizeof(*luactx));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004729 lua_rawseti(L, -2, 0);
Willy Tarreau7e702d12021-04-28 17:59:21 +02004730 luactx->appctx = ctx;
Willy Tarreauaa229cc2022-05-06 14:26:10 +02004731 http_ctx->status = 200; /* Default status code returned. */
4732 http_ctx->reason = NULL; /* Use default reason based on status */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004733 luactx->htxn.s = s;
4734 luactx->htxn.p = px;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004735
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004736 /* Create the "f" field that contains a list of fetches. */
4737 lua_pushstring(L, "f");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004738 if (!hlua_fetches_new(L, &luactx->htxn, 0))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004739 return 0;
4740 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004741
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004742 /* Create the "sf" field that contains a list of stringsafe fetches. */
4743 lua_pushstring(L, "sf");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004744 if (!hlua_fetches_new(L, &luactx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004745 return 0;
4746 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004747
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004748 /* Create the "c" field that contains a list of converters. */
4749 lua_pushstring(L, "c");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004750 if (!hlua_converters_new(L, &luactx->htxn, 0))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004751 return 0;
4752 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004753
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004754 /* Create the "sc" field that contains a list of stringsafe converters. */
4755 lua_pushstring(L, "sc");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004756 if (!hlua_converters_new(L, &luactx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004757 return 0;
4758 lua_settable(L, -3);
Willy Tarreaueee5b512015-04-03 23:46:31 +02004759
Christopher Fauleta2097962019-07-15 16:25:33 +02004760 htx = htxbuf(&s->req.buf);
4761 blk = htx_get_first_blk(htx);
Christopher Fauletea009732019-11-18 15:50:25 +01004762 BUG_ON(!blk || htx_get_blk_type(blk) != HTX_BLK_REQ_SL);
Christopher Fauleta2097962019-07-15 16:25:33 +02004763 sl = htx_get_blk_ptr(htx, blk);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004764
Christopher Fauleta2097962019-07-15 16:25:33 +02004765 /* Stores the request method. */
4766 lua_pushstring(L, "method");
4767 lua_pushlstring(L, HTX_SL_REQ_MPTR(sl), HTX_SL_REQ_MLEN(sl));
4768 lua_settable(L, -3);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004769
Christopher Fauleta2097962019-07-15 16:25:33 +02004770 /* Stores the http version. */
4771 lua_pushstring(L, "version");
4772 lua_pushlstring(L, HTX_SL_REQ_VPTR(sl), HTX_SL_REQ_VLEN(sl));
4773 lua_settable(L, -3);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004774
Christopher Fauleta2097962019-07-15 16:25:33 +02004775 /* creates an array of headers. hlua_http_get_headers() crates and push
4776 * the array on the top of the stack.
4777 */
4778 lua_pushstring(L, "headers");
4779 htxn.s = s;
4780 htxn.p = px;
4781 htxn.dir = SMP_OPT_DIR_REQ;
Christopher Faulet9d1332b2020-02-24 16:46:16 +01004782 if (!hlua_http_get_headers(L, &htxn.s->txn->req))
Christopher Fauleta2097962019-07-15 16:25:33 +02004783 return 0;
4784 lua_settable(L, -3);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004785
Amaury Denoyellec453f952021-07-06 11:40:12 +02004786 parser = http_uri_parser_init(htx_sl_req_uri(sl));
4787 path = http_parse_path(&parser);
Tim Duesterhused526372020-03-05 17:56:33 +01004788 if (isttest(path)) {
Christopher Fauleta2097962019-07-15 16:25:33 +02004789 char *p, *q, *end;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004790
Christopher Fauleta2097962019-07-15 16:25:33 +02004791 p = path.ptr;
Tim Duesterhus4c8f75f2021-11-06 15:14:44 +01004792 end = istend(path);
Christopher Fauleta2097962019-07-15 16:25:33 +02004793 q = p;
4794 while (q < end && *q != '?')
4795 q++;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004796
Thierry FOURNIER7d388632017-02-22 02:06:16 +01004797 /* Stores the request path. */
Christopher Fauleta2097962019-07-15 16:25:33 +02004798 lua_pushstring(L, "path");
4799 lua_pushlstring(L, p, q - p);
Thierry FOURNIER7d388632017-02-22 02:06:16 +01004800 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01004801
Christopher Fauleta2097962019-07-15 16:25:33 +02004802 /* Stores the query string. */
4803 lua_pushstring(L, "qs");
4804 if (*q == '?')
4805 q++;
4806 lua_pushlstring(L, q, end - q);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004807 lua_settable(L, -3);
Christopher Fauleta2097962019-07-15 16:25:33 +02004808 }
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004809
Christopher Fauleta2097962019-07-15 16:25:33 +02004810 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
4811 struct htx_blk *blk = htx_get_blk(htx, pos);
4812 enum htx_blk_type type = htx_get_blk_type(blk);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004813
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01004814 if (type == HTX_BLK_TLR || type == HTX_BLK_EOT)
Christopher Fauleta2097962019-07-15 16:25:33 +02004815 break;
4816 if (type == HTX_BLK_DATA)
4817 len += htx_get_blksz(blk);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004818 }
Christopher Fauleta2097962019-07-15 16:25:33 +02004819 if (htx->extra != ULLONG_MAX)
4820 len += htx->extra;
4821
4822 /* Stores the request path. */
4823 lua_pushstring(L, "length");
4824 lua_pushinteger(L, len);
4825 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01004826
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004827 /* Create an empty array of HTTP request headers. */
4828 lua_pushstring(L, "response");
4829 lua_newtable(L);
4830 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01004831
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004832 /* Pop a class stream metatable and affect it to the table. */
4833 lua_rawgeti(L, LUA_REGISTRYINDEX, class_applet_http_ref);
4834 lua_setmetatable(L, -2);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004835
4836 return 1;
4837}
4838
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004839__LJMP static int hlua_applet_http_set_var(lua_State *L)
4840{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004841 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004842 struct stream *s;
4843 const char *name;
4844 size_t len;
4845 struct sample smp;
4846
Tim Duesterhus4e172c92020-05-19 13:49:42 +02004847 if (lua_gettop(L) < 3 || lua_gettop(L) > 4)
4848 WILL_LJMP(luaL_error(L, "'set_var' needs between 3 and 4 arguments"));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004849
4850 /* It is useles to retrieve the stream, but this function
4851 * runs only in a stream context.
4852 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004853 luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004854 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02004855 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004856
4857 /* Converts the third argument in a sample. */
Amaury Denoyellebc0af6a2020-10-29 17:21:20 +01004858 memset(&smp, 0, sizeof(smp));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004859 hlua_lua2smp(L, 3, &smp);
4860
4861 /* Store the sample in a variable. */
4862 smp_set_owner(&smp, s->be, s->sess, s, 0);
Tim Duesterhus4e172c92020-05-19 13:49:42 +02004863
4864 if (lua_gettop(L) == 4 && lua_toboolean(L, 4))
4865 lua_pushboolean(L, vars_set_by_name_ifexist(name, len, &smp) != 0);
4866 else
4867 lua_pushboolean(L, vars_set_by_name(name, len, &smp) != 0);
4868
Tim Duesterhus84ebc132020-05-19 13:49:41 +02004869 return 1;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004870}
4871
4872__LJMP static int hlua_applet_http_unset_var(lua_State *L)
4873{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004874 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004875 struct stream *s;
4876 const char *name;
4877 size_t len;
4878 struct sample smp;
4879
4880 MAY_LJMP(check_args(L, 2, "unset_var"));
4881
4882 /* It is useles to retrieve the stream, but this function
4883 * runs only in a stream context.
4884 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004885 luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004886 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02004887 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004888
4889 /* Unset the variable. */
4890 smp_set_owner(&smp, s->be, s->sess, s, 0);
Tim Duesterhus84ebc132020-05-19 13:49:41 +02004891 lua_pushboolean(L, vars_unset_by_name_ifexist(name, len, &smp) != 0);
4892 return 1;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004893}
4894
4895__LJMP static int hlua_applet_http_get_var(lua_State *L)
4896{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004897 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004898 struct stream *s;
4899 const char *name;
4900 size_t len;
4901 struct sample smp;
4902
4903 MAY_LJMP(check_args(L, 2, "get_var"));
4904
4905 /* It is useles to retrieve the stream, but this function
4906 * runs only in a stream context.
4907 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004908 luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004909 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02004910 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004911
4912 smp_set_owner(&smp, s->be, s->sess, s, 0);
Willy Tarreaue352b9d2021-09-03 11:52:38 +02004913 if (!vars_get_by_name(name, len, &smp, NULL)) {
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004914 lua_pushnil(L);
4915 return 1;
4916 }
4917
4918 return hlua_smp2lua(L, &smp);
4919}
4920
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004921__LJMP static int hlua_applet_http_set_priv(lua_State *L)
4922{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004923 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4924 struct stream *s = luactx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01004925 struct hlua *hlua;
4926
4927 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01004928 if (!s->hlua)
4929 return 0;
4930 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004931
4932 MAY_LJMP(check_args(L, 2, "set_priv"));
4933
4934 /* Remove previous value. */
Thierry FOURNIERe068b602017-04-26 13:27:05 +02004935 luaL_unref(L, LUA_REGISTRYINDEX, hlua->Mref);
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004936
4937 /* Get and store new value. */
4938 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
4939 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
4940
4941 return 0;
4942}
4943
4944__LJMP static int hlua_applet_http_get_priv(lua_State *L)
4945{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004946 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4947 struct stream *s = luactx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01004948 struct hlua *hlua;
4949
4950 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01004951 if (!s->hlua) {
4952 lua_pushnil(L);
4953 return 1;
4954 }
4955 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004956
4957 /* Push configuration index in the stack. */
4958 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
4959
4960 return 1;
4961}
4962
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004963/* If expected data not yet available, it returns a yield. This function
4964 * consumes the data in the buffer. It returns a string containing the
4965 * data. This string can be empty.
4966 */
Christopher Fauleta2097962019-07-15 16:25:33 +02004967__LJMP static int hlua_applet_http_getline_yield(lua_State *L, int status, lua_KContext ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004968{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004969 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Willy Tarreau0698c802022-05-11 14:09:57 +02004970 struct conn_stream *cs = appctx_cs(luactx->appctx);
Christopher Faulet908628c2022-03-25 16:43:49 +01004971 struct channel *req = cs_oc(cs);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004972 struct htx *htx;
4973 struct htx_blk *blk;
4974 size_t count;
4975 int stop = 0;
4976
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004977 htx = htx_from_buf(&req->buf);
4978 count = co_data(req);
Christopher Fauleta3f15502019-05-13 15:27:23 +02004979 blk = htx_get_first_blk(htx);
Christopher Fauletcc26b132018-12-18 21:20:57 +01004980
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004981 while (count && !stop && blk) {
4982 enum htx_blk_type type = htx_get_blk_type(blk);
4983 uint32_t sz = htx_get_blksz(blk);
4984 struct ist v;
4985 uint32_t vlen;
4986 char *nl;
4987
4988 vlen = sz;
4989 if (vlen > count) {
4990 if (type != HTX_BLK_DATA)
4991 break;
4992 vlen = count;
4993 }
4994
4995 switch (type) {
4996 case HTX_BLK_UNUSED:
4997 break;
4998
4999 case HTX_BLK_DATA:
5000 v = htx_get_blk_value(htx, blk);
5001 v.len = vlen;
5002 nl = istchr(v, '\n');
5003 if (nl != NULL) {
5004 stop = 1;
5005 vlen = nl - v.ptr + 1;
5006 }
Willy Tarreau7e702d12021-04-28 17:59:21 +02005007 luaL_addlstring(&luactx->b, v.ptr, vlen);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005008 break;
5009
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005010 case HTX_BLK_TLR:
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01005011 case HTX_BLK_EOT:
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005012 stop = 1;
5013 break;
5014
5015 default:
5016 break;
5017 }
5018
Willy Tarreau84240042022-02-28 16:51:23 +01005019 c_rew(req, vlen);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005020 count -= vlen;
5021 if (sz == vlen)
5022 blk = htx_remove_blk(htx, blk);
5023 else {
5024 htx_cut_data_blk(htx, blk, vlen);
5025 break;
5026 }
5027 }
5028
Christopher Fauleteccb31c2021-04-02 14:24:56 +02005029 /* The message was fully consumed and no more data are expected
5030 * (EOM flag set).
5031 */
5032 if (htx_is_empty(htx) && (htx->flags & HTX_FL_EOM))
5033 stop = 1;
5034
Christopher Faulet0ae79d02019-02-27 21:36:59 +01005035 htx_to_buf(htx, &req->buf);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005036 if (!stop) {
Christopher Fauleta0bdec32022-04-04 07:51:21 +02005037 cs_cant_get(cs);
Christopher Fauleta2097962019-07-15 16:25:33 +02005038 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_getline_yield, TICK_ETERNITY, 0));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005039 }
5040
5041 /* return the result. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005042 luaL_pushresult(&luactx->b);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005043 return 1;
5044}
5045
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005046
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08005047/* Check arguments for the function "hlua_channel_get_yield". */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005048__LJMP static int hlua_applet_http_getline(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005049{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005050 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005051
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005052 /* Initialise the string catenation. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005053 luaL_buffinit(L, &luactx->b);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005054
Christopher Fauleta2097962019-07-15 16:25:33 +02005055 return MAY_LJMP(hlua_applet_http_getline_yield(L, 0, 0));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005056}
5057
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005058/* If expected data not yet available, it returns a yield. This function
5059 * consumes the data in the buffer. It returns a string containing the
5060 * data. This string can be empty.
5061 */
Christopher Fauleta2097962019-07-15 16:25:33 +02005062__LJMP static int hlua_applet_http_recv_yield(lua_State *L, int status, lua_KContext ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005063{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005064 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Willy Tarreau0698c802022-05-11 14:09:57 +02005065 struct conn_stream *cs = appctx_cs(luactx->appctx);
Christopher Faulet908628c2022-03-25 16:43:49 +01005066 struct channel *req = cs_oc(cs);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005067 struct htx *htx;
5068 struct htx_blk *blk;
5069 size_t count;
5070 int len;
5071
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005072 htx = htx_from_buf(&req->buf);
5073 len = MAY_LJMP(luaL_checkinteger(L, 2));
5074 count = co_data(req);
Christopher Faulet29f17582019-05-23 11:03:26 +02005075 blk = htx_get_head_blk(htx);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005076 while (count && len && blk) {
5077 enum htx_blk_type type = htx_get_blk_type(blk);
5078 uint32_t sz = htx_get_blksz(blk);
5079 struct ist v;
5080 uint32_t vlen;
5081
5082 vlen = sz;
5083 if (len > 0 && vlen > len)
5084 vlen = len;
5085 if (vlen > count) {
5086 if (type != HTX_BLK_DATA)
5087 break;
5088 vlen = count;
5089 }
5090
5091 switch (type) {
5092 case HTX_BLK_UNUSED:
5093 break;
5094
5095 case HTX_BLK_DATA:
5096 v = htx_get_blk_value(htx, blk);
Willy Tarreau7e702d12021-04-28 17:59:21 +02005097 luaL_addlstring(&luactx->b, v.ptr, vlen);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005098 break;
5099
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005100 case HTX_BLK_TLR:
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01005101 case HTX_BLK_EOT:
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005102 len = 0;
5103 break;
5104
5105 default:
5106 break;
5107 }
5108
Willy Tarreau84240042022-02-28 16:51:23 +01005109 c_rew(req, vlen);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005110 count -= vlen;
5111 if (len > 0)
5112 len -= vlen;
5113 if (sz == vlen)
5114 blk = htx_remove_blk(htx, blk);
5115 else {
5116 htx_cut_data_blk(htx, blk, vlen);
5117 break;
5118 }
5119 }
5120
Christopher Fauleteccb31c2021-04-02 14:24:56 +02005121 /* The message was fully consumed and no more data are expected
5122 * (EOM flag set).
5123 */
5124 if (htx_is_empty(htx) && (htx->flags & HTX_FL_EOM))
5125 len = 0;
5126
Christopher Faulet0ae79d02019-02-27 21:36:59 +01005127 htx_to_buf(htx, &req->buf);
5128
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005129 /* If we are no other data available, yield waiting for new data. */
5130 if (len) {
5131 if (len > 0) {
5132 lua_pushinteger(L, len);
5133 lua_replace(L, 2);
5134 }
Christopher Fauleta0bdec32022-04-04 07:51:21 +02005135 cs_cant_get(cs);
Willy Tarreau9635e032018-10-16 17:52:55 +02005136 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005137 }
5138
5139 /* return the result. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005140 luaL_pushresult(&luactx->b);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005141 return 1;
5142}
5143
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08005144/* Check arguments for the function "hlua_channel_get_yield". */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005145__LJMP static int hlua_applet_http_recv(lua_State *L)
5146{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005147 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005148 int len = -1;
5149
5150 /* Check arguments. */
5151 if (lua_gettop(L) > 2)
5152 WILL_LJMP(luaL_error(L, "The 'recv' function requires between 1 and 2 arguments."));
5153 if (lua_gettop(L) >= 2) {
5154 len = MAY_LJMP(luaL_checkinteger(L, 2));
5155 lua_pop(L, 1);
5156 }
5157
Christopher Fauleta2097962019-07-15 16:25:33 +02005158 lua_pushinteger(L, len);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005159
Christopher Fauleta2097962019-07-15 16:25:33 +02005160 /* Initialise the string catenation. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005161 luaL_buffinit(L, &luactx->b);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005162
Christopher Fauleta2097962019-07-15 16:25:33 +02005163 return MAY_LJMP(hlua_applet_http_recv_yield(L, 0, 0));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005164}
5165
5166/* Append data in the output side of the buffer. This data is immediately
5167 * sent. The function returns the amount of data written. If the buffer
5168 * cannot contain the data, the function yields. The function returns -1
5169 * if the channel is closed.
5170 */
Christopher Fauleta2097962019-07-15 16:25:33 +02005171__LJMP static int hlua_applet_http_send_yield(lua_State *L, int status, lua_KContext ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005172{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005173 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Willy Tarreau0698c802022-05-11 14:09:57 +02005174 struct conn_stream *cs = appctx_cs(luactx->appctx);
Christopher Faulet908628c2022-03-25 16:43:49 +01005175 struct channel *res = cs_ic(cs);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005176 struct htx *htx = htx_from_buf(&res->buf);
5177 const char *data;
5178 size_t len;
5179 int l = MAY_LJMP(luaL_checkinteger(L, 3));
5180 int max;
5181
Christopher Faulet9060fc02019-07-03 11:39:30 +02005182 max = htx_get_max_blksz(htx, channel_htx_recv_max(res, htx));
Christopher Faulet4b0e9b22019-01-09 12:16:58 +01005183 if (!max)
5184 goto snd_yield;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005185
5186 data = MAY_LJMP(luaL_checklstring(L, 2, &len));
5187
5188 /* Get the max amount of data which can write as input in the channel. */
5189 if (max > (len - l))
5190 max = len - l;
5191
5192 /* Copy data. */
Willy Tarreau0a7ef022019-05-28 10:30:11 +02005193 max = htx_add_data(htx, ist2(data + l, max));
Christopher Fauletf6cce3f2019-02-27 21:20:09 +01005194 channel_add_input(res, max);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005195
5196 /* update counters. */
5197 l += max;
5198 lua_pop(L, 1);
5199 lua_pushinteger(L, l);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005200
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005201 /* If some data is not send, declares the situation to the
5202 * applet, and returns a yield.
5203 */
5204 if (l < len) {
Christopher Faulet4b0e9b22019-01-09 12:16:58 +01005205 snd_yield:
Christopher Faulet0ae79d02019-02-27 21:36:59 +01005206 htx_to_buf(htx, &res->buf);
Christopher Fauleta0bdec32022-04-04 07:51:21 +02005207 cs_rx_room_blk(cs);
Willy Tarreau9635e032018-10-16 17:52:55 +02005208 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005209 }
5210
Christopher Fauleta2097962019-07-15 16:25:33 +02005211 htx_to_buf(htx, &res->buf);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005212 return 1;
5213}
5214
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05005215/* Just a wrapper of "hlua_applet_send_yield". This wrapper permits
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005216 * yield the LUA process, and resume it without checking the
5217 * input arguments.
5218 */
5219__LJMP static int hlua_applet_http_send(lua_State *L)
5220{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005221 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005222 struct hlua_http_ctx *http_ctx = luactx->appctx->svcctx;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005223
5224 /* We want to send some data. Headers must be sent. */
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005225 if (!(http_ctx->flags & APPLET_HDR_SENT)) {
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005226 hlua_pusherror(L, "Lua: 'send' you must call start_response() before sending data.");
5227 WILL_LJMP(lua_error(L));
5228 }
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005229
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05005230 /* This integer is used for followinf the amount of data sent. */
Christopher Fauleta2097962019-07-15 16:25:33 +02005231 lua_pushinteger(L, 0);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005232
Christopher Fauleta2097962019-07-15 16:25:33 +02005233 return MAY_LJMP(hlua_applet_http_send_yield(L, 0, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005234}
5235
5236__LJMP static int hlua_applet_http_addheader(lua_State *L)
5237{
5238 const char *name;
5239 int ret;
5240
5241 MAY_LJMP(hlua_checkapplet_http(L, 1));
5242 name = MAY_LJMP(luaL_checkstring(L, 2));
5243 MAY_LJMP(luaL_checkstring(L, 3));
5244
5245 /* Push in the stack the "response" entry. */
5246 ret = lua_getfield(L, 1, "response");
5247 if (ret != LUA_TTABLE) {
5248 hlua_pusherror(L, "Lua: 'add_header' internal error: AppletHTTP['response'] "
5249 "is expected as an array. %s found", lua_typename(L, ret));
5250 WILL_LJMP(lua_error(L));
5251 }
5252
5253 /* check if the header is already registered if it is not
5254 * the case, register it.
5255 */
5256 ret = lua_getfield(L, -1, name);
5257 if (ret == LUA_TNIL) {
5258
5259 /* Entry not found. */
5260 lua_pop(L, 1); /* remove the nil. The "response" table is the top of the stack. */
5261
5262 /* Insert the new header name in the array in the top of the stack.
5263 * It left the new array in the top of the stack.
5264 */
5265 lua_newtable(L);
5266 lua_pushvalue(L, 2);
5267 lua_pushvalue(L, -2);
5268 lua_settable(L, -4);
5269
5270 } else if (ret != LUA_TTABLE) {
5271
5272 /* corruption error. */
5273 hlua_pusherror(L, "Lua: 'add_header' internal error: AppletHTTP['response']['%s'] "
5274 "is expected as an array. %s found", name, lua_typename(L, ret));
5275 WILL_LJMP(lua_error(L));
5276 }
5277
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -07005278 /* Now the top of thestack is an array of values. We push
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005279 * the header value as new entry.
5280 */
5281 lua_pushvalue(L, 3);
5282 ret = lua_rawlen(L, -2);
5283 lua_rawseti(L, -2, ret + 1);
5284 lua_pushboolean(L, 1);
5285 return 1;
5286}
5287
5288__LJMP static int hlua_applet_http_status(lua_State *L)
5289{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005290 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005291 int status = MAY_LJMP(luaL_checkinteger(L, 2));
Robin H. Johnson52f5db22017-01-01 13:10:52 -08005292 const char *reason = MAY_LJMP(luaL_optlstring(L, 3, NULL, NULL));
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005293 struct hlua_http_ctx *http_ctx = luactx->appctx->svcctx;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005294
5295 if (status < 100 || status > 599) {
5296 lua_pushboolean(L, 0);
5297 return 1;
5298 }
5299
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005300 http_ctx->status = status;
5301 http_ctx->reason = reason;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005302 lua_pushboolean(L, 1);
5303 return 1;
5304}
5305
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005306
Christopher Fauleta2097962019-07-15 16:25:33 +02005307__LJMP static int hlua_applet_http_send_response(lua_State *L)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005308{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005309 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005310 struct hlua_http_ctx *http_ctx = luactx->appctx->svcctx;
Willy Tarreau0698c802022-05-11 14:09:57 +02005311 struct conn_stream *cs = appctx_cs(luactx->appctx);
Christopher Faulet908628c2022-03-25 16:43:49 +01005312 struct channel *res = cs_ic(cs);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005313 struct htx *htx;
5314 struct htx_sl *sl;
5315 struct h1m h1m;
5316 const char *status, *reason;
5317 const char *name, *value;
5318 size_t nlen, vlen;
5319 unsigned int flags;
5320
5321 /* Send the message at once. */
5322 htx = htx_from_buf(&res->buf);
5323 h1m_init_res(&h1m);
5324
5325 /* Use the same http version than the request. */
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005326 status = ultoa_r(http_ctx->status, trash.area, trash.size);
5327 reason = http_ctx->reason;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005328 if (reason == NULL)
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005329 reason = http_get_reason(http_ctx->status);
5330 if (http_ctx->flags & APPLET_HTTP11) {
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005331 flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11);
5332 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.1"), ist(status), ist(reason));
5333 }
5334 else {
5335 flags = HTX_SL_F_IS_RESP;
5336 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.0"), ist(status), ist(reason));
5337 }
5338 if (!sl) {
5339 hlua_pusherror(L, "Lua applet http '%s': Failed to create response.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005340 luactx->appctx->rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005341 WILL_LJMP(lua_error(L));
5342 }
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005343 sl->info.res.status = http_ctx->status;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005344
5345 /* Get the array associated to the field "response" in the object AppletHTTP. */
5346 lua_pushvalue(L, 0);
5347 if (lua_getfield(L, 1, "response") != LUA_TTABLE) {
5348 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response'] missing.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005349 luactx->appctx->rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005350 WILL_LJMP(lua_error(L));
5351 }
5352
5353 /* Browse the list of headers. */
5354 lua_pushnil(L);
5355 while(lua_next(L, -2) != 0) {
5356 /* We expect a string as -2. */
5357 if (lua_type(L, -2) != LUA_TSTRING) {
5358 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response'][] element must be a string. got %s.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005359 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005360 lua_typename(L, lua_type(L, -2)));
5361 WILL_LJMP(lua_error(L));
5362 }
5363 name = lua_tolstring(L, -2, &nlen);
5364
5365 /* We expect an array as -1. */
5366 if (lua_type(L, -1) != LUA_TTABLE) {
5367 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 +02005368 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005369 name,
5370 lua_typename(L, lua_type(L, -1)));
5371 WILL_LJMP(lua_error(L));
5372 }
5373
5374 /* Browse the table who is on the top of the stack. */
5375 lua_pushnil(L);
5376 while(lua_next(L, -2) != 0) {
5377 int id;
5378
5379 /* We expect a number as -2. */
5380 if (lua_type(L, -2) != LUA_TNUMBER) {
5381 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 +02005382 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005383 name,
5384 lua_typename(L, lua_type(L, -2)));
5385 WILL_LJMP(lua_error(L));
5386 }
5387 id = lua_tointeger(L, -2);
5388
5389 /* We expect a string as -2. */
5390 if (lua_type(L, -1) != LUA_TSTRING) {
5391 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 +02005392 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005393 name, id,
5394 lua_typename(L, lua_type(L, -1)));
5395 WILL_LJMP(lua_error(L));
5396 }
5397 value = lua_tolstring(L, -1, &vlen);
5398
5399 /* Simple Protocol checks. */
Christopher Faulet545fbba2021-09-28 09:36:25 +02005400 if (isteqi(ist2(name, nlen), ist("transfer-encoding"))) {
5401 int ret;
5402
5403 ret = h1_parse_xfer_enc_header(&h1m, ist2(value, vlen));
5404 if (ret < 0) {
5405 hlua_pusherror(L, "Lua applet http '%s': Invalid '%s' header.\n",
5406 luactx->appctx->rule->arg.hlua_rule->fcn->name,
5407 name);
5408 WILL_LJMP(lua_error(L));
5409 }
5410 else if (ret == 0)
5411 goto next; /* Skip it */
5412 }
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005413 else if (isteqi(ist2(name, nlen), ist("content-length"))) {
5414 struct ist v = ist2(value, vlen);
5415 int ret;
5416
5417 ret = h1_parse_cont_len_header(&h1m, &v);
5418 if (ret < 0) {
5419 hlua_pusherror(L, "Lua applet http '%s': Invalid '%s' header.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005420 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005421 name);
5422 WILL_LJMP(lua_error(L));
5423 }
5424 else if (ret == 0)
5425 goto next; /* Skip it */
5426 }
5427
5428 /* Add a new header */
5429 if (!htx_add_header(htx, ist2(name, nlen), ist2(value, vlen))) {
5430 hlua_pusherror(L, "Lua applet http '%s': Failed to add header '%s' in the response.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005431 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005432 name);
5433 WILL_LJMP(lua_error(L));
5434 }
5435 next:
5436 /* Remove the array from the stack, and get next element with a remaining string. */
5437 lua_pop(L, 1);
5438 }
5439
5440 /* Remove the array from the stack, and get next element with a remaining string. */
5441 lua_pop(L, 1);
5442 }
5443
5444 if (h1m.flags & H1_MF_CHNK)
5445 h1m.flags &= ~H1_MF_CLEN;
5446 if (h1m.flags & (H1_MF_CLEN|H1_MF_CHNK))
5447 h1m.flags |= H1_MF_XFER_LEN;
5448
5449 /* Uset HTX start-line flags */
5450 if (h1m.flags & H1_MF_XFER_ENC)
5451 flags |= HTX_SL_F_XFER_ENC;
5452 if (h1m.flags & H1_MF_XFER_LEN) {
5453 flags |= HTX_SL_F_XFER_LEN;
5454 if (h1m.flags & H1_MF_CHNK)
5455 flags |= HTX_SL_F_CHNK;
5456 else if (h1m.flags & H1_MF_CLEN)
5457 flags |= HTX_SL_F_CLEN;
5458 if (h1m.body_len == 0)
5459 flags |= HTX_SL_F_BODYLESS;
5460 }
5461 sl->flags |= flags;
5462
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -07005463 /* If we don't have a content-length set, and the HTTP version is 1.1
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005464 * and the status code implies the presence of a message body, we must
5465 * announce a transfer encoding chunked. This is required by haproxy
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05005466 * for the keepalive compliance. If the applet announces a transfer-encoding
5467 * chunked itself, don't do anything.
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005468 */
5469 if ((flags & (HTX_SL_F_VER_11|HTX_SL_F_XFER_LEN)) == HTX_SL_F_VER_11 &&
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005470 http_ctx->status >= 200 && http_ctx->status != 204 && http_ctx->status != 304) {
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005471 /* Add a new header */
5472 sl->flags |= (HTX_SL_F_XFER_ENC|H1_MF_CHNK|H1_MF_XFER_LEN);
5473 if (!htx_add_header(htx, ist("transfer-encoding"), ist("chunked"))) {
5474 hlua_pusherror(L, "Lua applet http '%s': Failed to add header 'transfer-encoding' in the response.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005475 luactx->appctx->rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005476 WILL_LJMP(lua_error(L));
5477 }
5478 }
5479
5480 /* Finalize headers. */
5481 if (!htx_add_endof(htx, HTX_BLK_EOH)) {
5482 hlua_pusherror(L, "Lua applet http '%s': Failed create the response.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005483 luactx->appctx->rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005484 WILL_LJMP(lua_error(L));
5485 }
5486
5487 if (htx_used_space(htx) > b_size(&res->buf) - global.tune.maxrewrite) {
5488 b_reset(&res->buf);
5489 hlua_pusherror(L, "Lua: 'start_response': response header block too big");
5490 WILL_LJMP(lua_error(L));
5491 }
5492
5493 htx_to_buf(htx, &res->buf);
Christopher Fauletf6cce3f2019-02-27 21:20:09 +01005494 channel_add_input(res, htx->data);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005495
5496 /* Headers sent, set the flag. */
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005497 http_ctx->flags |= APPLET_HDR_SENT;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005498 return 0;
5499
5500}
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005501/* We will build the status line and the headers of the HTTP response.
5502 * We will try send at once if its not possible, we give back the hand
5503 * waiting for more room.
5504 */
Christopher Fauleta2097962019-07-15 16:25:33 +02005505__LJMP static int hlua_applet_http_start_response_yield(lua_State *L, int status, lua_KContext ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005506{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005507 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Willy Tarreau0698c802022-05-11 14:09:57 +02005508 struct conn_stream *cs = appctx_cs(luactx->appctx);
Christopher Faulet908628c2022-03-25 16:43:49 +01005509 struct channel *res = cs_ic(cs);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005510
5511 if (co_data(res)) {
Christopher Fauleta0bdec32022-04-04 07:51:21 +02005512 cs_rx_room_blk(cs);
Christopher Fauleta2097962019-07-15 16:25:33 +02005513 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_start_response_yield, TICK_ETERNITY, 0));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005514 }
Christopher Fauleta2097962019-07-15 16:25:33 +02005515 return MAY_LJMP(hlua_applet_http_send_response(L));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005516}
5517
5518
Christopher Fauleta2097962019-07-15 16:25:33 +02005519__LJMP static int hlua_applet_http_start_response(lua_State *L)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005520{
Christopher Fauleta2097962019-07-15 16:25:33 +02005521 return MAY_LJMP(hlua_applet_http_start_response_yield(L, 0, 0));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005522}
5523
Christopher Fauleta2097962019-07-15 16:25:33 +02005524/*
5525 *
5526 *
5527 * Class HTTP
5528 *
5529 *
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005530 */
Christopher Fauleta2097962019-07-15 16:25:33 +02005531
5532/* Returns a struct hlua_txn if the stack entry "ud" is
5533 * a class stream, otherwise it throws an error.
5534 */
5535__LJMP static struct hlua_txn *hlua_checkhttp(lua_State *L, int ud)
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005536{
Christopher Fauleta2097962019-07-15 16:25:33 +02005537 return MAY_LJMP(hlua_checkudata(L, ud, class_http_ref));
5538}
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005539
Christopher Fauleta2097962019-07-15 16:25:33 +02005540/* This function creates and push in the stack a HTTP object
5541 * according with a current TXN.
5542 */
5543static int hlua_http_new(lua_State *L, struct hlua_txn *txn)
5544{
5545 struct hlua_txn *htxn;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005546
Christopher Fauleta2097962019-07-15 16:25:33 +02005547 /* Check stack size. */
5548 if (!lua_checkstack(L, 3))
5549 return 0;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005550
Christopher Fauleta2097962019-07-15 16:25:33 +02005551 /* Create the object: obj[0] = userdata.
5552 * Note that the base of the Converters object is the
5553 * same than the TXN object.
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005554 */
Christopher Fauleta2097962019-07-15 16:25:33 +02005555 lua_newtable(L);
5556 htxn = lua_newuserdata(L, sizeof(*htxn));
5557 lua_rawseti(L, -2, 0);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005558
5559 htxn->s = txn->s;
5560 htxn->p = txn->p;
Christopher Faulet256b69a2019-05-23 11:14:21 +02005561 htxn->dir = txn->dir;
5562 htxn->flags = txn->flags;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005563
5564 /* Pop a class stream metatable and affect it to the table. */
5565 lua_rawgeti(L, LUA_REGISTRYINDEX, class_http_ref);
5566 lua_setmetatable(L, -2);
5567
5568 return 1;
5569}
5570
Christopher Fauletdf97ac42020-02-26 16:57:19 +01005571/* This function creates and returns an array containing the status-line
5572 * elements. This function does not fails.
5573 */
5574__LJMP static int hlua_http_get_stline(lua_State *L, struct htx_sl *sl)
5575{
5576 /* Create the table. */
5577 lua_newtable(L);
5578
5579 if (sl->flags & HTX_SL_F_IS_RESP) {
5580 lua_pushstring(L, "version");
5581 lua_pushlstring(L, HTX_SL_RES_VPTR(sl), HTX_SL_RES_VLEN(sl));
5582 lua_settable(L, -3);
5583 lua_pushstring(L, "code");
5584 lua_pushlstring(L, HTX_SL_RES_CPTR(sl), HTX_SL_RES_CLEN(sl));
5585 lua_settable(L, -3);
5586 lua_pushstring(L, "reason");
5587 lua_pushlstring(L, HTX_SL_RES_RPTR(sl), HTX_SL_RES_RLEN(sl));
5588 lua_settable(L, -3);
5589 }
5590 else {
5591 lua_pushstring(L, "method");
5592 lua_pushlstring(L, HTX_SL_REQ_MPTR(sl), HTX_SL_REQ_MLEN(sl));
5593 lua_settable(L, -3);
5594 lua_pushstring(L, "uri");
5595 lua_pushlstring(L, HTX_SL_REQ_UPTR(sl), HTX_SL_REQ_ULEN(sl));
5596 lua_settable(L, -3);
5597 lua_pushstring(L, "version");
5598 lua_pushlstring(L, HTX_SL_REQ_VPTR(sl), HTX_SL_REQ_VLEN(sl));
5599 lua_settable(L, -3);
5600 }
5601 return 1;
5602}
5603
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005604/* This function creates ans returns an array of HTTP headers.
5605 * This function does not fails. It is used as wrapper with the
5606 * 2 following functions.
5607 */
Christopher Faulet9d1332b2020-02-24 16:46:16 +01005608__LJMP static int hlua_http_get_headers(lua_State *L, struct http_msg *msg)
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005609{
Christopher Fauleta2097962019-07-15 16:25:33 +02005610 struct htx *htx;
5611 int32_t pos;
5612
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005613 /* Create the table. */
5614 lua_newtable(L);
5615
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005616
Christopher Fauleta2097962019-07-15 16:25:33 +02005617 htx = htxbuf(&msg->chn->buf);
5618 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
5619 struct htx_blk *blk = htx_get_blk(htx, pos);
5620 enum htx_blk_type type = htx_get_blk_type(blk);
5621 struct ist n, v;
5622 int len;
Christopher Faulet724a12c2018-12-13 22:12:15 +01005623
Christopher Fauleta2097962019-07-15 16:25:33 +02005624 if (type == HTX_BLK_HDR) {
5625 n = htx_get_blk_name(htx,blk);
5626 v = htx_get_blk_value(htx, blk);
Christopher Faulet724a12c2018-12-13 22:12:15 +01005627 }
Christopher Fauleta2097962019-07-15 16:25:33 +02005628 else if (type == HTX_BLK_EOH)
5629 break;
5630 else
5631 continue;
Christopher Faulet724a12c2018-12-13 22:12:15 +01005632
Christopher Fauleta2097962019-07-15 16:25:33 +02005633 /* Check for existing entry:
5634 * assume that the table is on the top of the stack, and
5635 * push the key in the stack, the function lua_gettable()
5636 * perform the lookup.
5637 */
5638 lua_pushlstring(L, n.ptr, n.len);
5639 lua_gettable(L, -2);
Christopher Faulet724a12c2018-12-13 22:12:15 +01005640
Christopher Fauleta2097962019-07-15 16:25:33 +02005641 switch (lua_type(L, -1)) {
5642 case LUA_TNIL:
5643 /* Table not found, create it. */
5644 lua_pop(L, 1); /* remove the nil value. */
5645 lua_pushlstring(L, n.ptr, n.len); /* push the header name as key. */
5646 lua_newtable(L); /* create and push empty table. */
5647 lua_pushlstring(L, v.ptr, v.len); /* push header value. */
5648 lua_rawseti(L, -2, 0); /* index header value (pop it). */
5649 lua_rawset(L, -3); /* index new table with header name (pop the values). */
Christopher Faulet724a12c2018-12-13 22:12:15 +01005650 break;
Christopher Faulet724a12c2018-12-13 22:12:15 +01005651
Christopher Fauleta2097962019-07-15 16:25:33 +02005652 case LUA_TTABLE:
5653 /* Entry found: push the value in the table. */
5654 len = lua_rawlen(L, -1);
5655 lua_pushlstring(L, v.ptr, v.len); /* push header value. */
5656 lua_rawseti(L, -2, len+1); /* index header value (pop it). */
5657 lua_pop(L, 1); /* remove the table (it is stored in the main table). */
5658 break;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005659
Christopher Fauleta2097962019-07-15 16:25:33 +02005660 default:
5661 /* Other cases are errors. */
5662 hlua_pusherror(L, "internal error during the parsing of headers.");
5663 WILL_LJMP(lua_error(L));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005664 }
5665 }
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005666 return 1;
5667}
5668
5669__LJMP static int hlua_http_req_get_headers(lua_State *L)
5670{
5671 struct hlua_txn *htxn;
5672
5673 MAY_LJMP(check_args(L, 1, "req_get_headers"));
5674 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5675
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005676 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005677 WILL_LJMP(lua_error(L));
5678
Christopher Faulet9d1332b2020-02-24 16:46:16 +01005679 return hlua_http_get_headers(L, &htxn->s->txn->req);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005680}
5681
5682__LJMP static int hlua_http_res_get_headers(lua_State *L)
5683{
5684 struct hlua_txn *htxn;
5685
5686 MAY_LJMP(check_args(L, 1, "res_get_headers"));
5687 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5688
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005689 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005690 WILL_LJMP(lua_error(L));
5691
Christopher Faulet9d1332b2020-02-24 16:46:16 +01005692 return hlua_http_get_headers(L, &htxn->s->txn->rsp);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005693}
5694
5695/* This function replace full header, or just a value in
5696 * the request or in the response. It is a wrapper fir the
5697 * 4 following functions.
5698 */
Christopher Fauletd1914aa2020-02-24 16:52:46 +01005699__LJMP static inline int hlua_http_rep_hdr(lua_State *L, struct http_msg *msg, int full)
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005700{
5701 size_t name_len;
5702 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
5703 const char *reg = MAY_LJMP(luaL_checkstring(L, 3));
5704 const char *value = MAY_LJMP(luaL_checkstring(L, 4));
Christopher Fauleta2097962019-07-15 16:25:33 +02005705 struct htx *htx;
Dragan Dosen26743032019-04-30 15:54:36 +02005706 struct my_regex *re;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005707
Dragan Dosen26743032019-04-30 15:54:36 +02005708 if (!(re = regex_comp(reg, 1, 1, NULL)))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005709 WILL_LJMP(luaL_argerror(L, 3, "invalid regex"));
5710
Christopher Fauleta2097962019-07-15 16:25:33 +02005711 htx = htxbuf(&msg->chn->buf);
Christopher Fauletd1914aa2020-02-24 16:52:46 +01005712 http_replace_hdrs(chn_strm(msg->chn), htx, ist2(name, name_len), value, re, full);
Dragan Dosen26743032019-04-30 15:54:36 +02005713 regex_free(re);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005714 return 0;
5715}
5716
5717__LJMP static int hlua_http_req_rep_hdr(lua_State *L)
5718{
5719 struct hlua_txn *htxn;
5720
5721 MAY_LJMP(check_args(L, 4, "req_rep_hdr"));
5722 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5723
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005724 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005725 WILL_LJMP(lua_error(L));
5726
Christopher Fauletd1914aa2020-02-24 16:52:46 +01005727 return MAY_LJMP(hlua_http_rep_hdr(L, &htxn->s->txn->req, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005728}
5729
5730__LJMP static int hlua_http_res_rep_hdr(lua_State *L)
5731{
5732 struct hlua_txn *htxn;
5733
5734 MAY_LJMP(check_args(L, 4, "res_rep_hdr"));
5735 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5736
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005737 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005738 WILL_LJMP(lua_error(L));
5739
Christopher Fauletd1914aa2020-02-24 16:52:46 +01005740 return MAY_LJMP(hlua_http_rep_hdr(L, &htxn->s->txn->rsp, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005741}
5742
5743__LJMP static int hlua_http_req_rep_val(lua_State *L)
5744{
5745 struct hlua_txn *htxn;
5746
5747 MAY_LJMP(check_args(L, 4, "req_rep_hdr"));
5748 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5749
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005750 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005751 WILL_LJMP(lua_error(L));
5752
Christopher Fauletd1914aa2020-02-24 16:52:46 +01005753 return MAY_LJMP(hlua_http_rep_hdr(L, &htxn->s->txn->req, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005754}
5755
5756__LJMP static int hlua_http_res_rep_val(lua_State *L)
5757{
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005758 struct hlua_txn *htxn;
5759
5760 MAY_LJMP(check_args(L, 4, "res_rep_val"));
5761 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5762
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005763 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005764 WILL_LJMP(lua_error(L));
5765
Christopher Fauletd1914aa2020-02-24 16:52:46 +01005766 return MAY_LJMP(hlua_http_rep_hdr(L, &htxn->s->txn->rsp, 0));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005767}
5768
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08005769/* This function deletes all the occurrences of an header.
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005770 * It is a wrapper for the 2 following functions.
5771 */
Christopher Fauletd31c7b32020-02-25 09:37:57 +01005772__LJMP static inline int hlua_http_del_hdr(lua_State *L, struct http_msg *msg)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005773{
5774 size_t len;
5775 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Christopher Fauleta2097962019-07-15 16:25:33 +02005776 struct htx *htx = htxbuf(&msg->chn->buf);
5777 struct http_hdr_ctx ctx;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005778
Christopher Fauleta2097962019-07-15 16:25:33 +02005779 ctx.blk = NULL;
5780 while (http_find_header(htx, ist2(name, len), &ctx, 1))
5781 http_remove_header(htx, &ctx);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005782 return 0;
5783}
5784
5785__LJMP static int hlua_http_req_del_hdr(lua_State *L)
5786{
5787 struct hlua_txn *htxn;
5788
5789 MAY_LJMP(check_args(L, 2, "req_del_hdr"));
5790 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5791
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005792 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005793 WILL_LJMP(lua_error(L));
5794
Christopher Fauletd31c7b32020-02-25 09:37:57 +01005795 return hlua_http_del_hdr(L, &htxn->s->txn->req);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005796}
5797
5798__LJMP static int hlua_http_res_del_hdr(lua_State *L)
5799{
5800 struct hlua_txn *htxn;
5801
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005802 MAY_LJMP(check_args(L, 2, "res_del_hdr"));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005803 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5804
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005805 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005806 WILL_LJMP(lua_error(L));
5807
Christopher Fauletd31c7b32020-02-25 09:37:57 +01005808 return hlua_http_del_hdr(L, &htxn->s->txn->rsp);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005809}
5810
5811/* This function adds an header. It is a wrapper used by
5812 * the 2 following functions.
5813 */
Christopher Fauletd31c7b32020-02-25 09:37:57 +01005814__LJMP static inline int hlua_http_add_hdr(lua_State *L, struct http_msg *msg)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005815{
5816 size_t name_len;
5817 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
5818 size_t value_len;
5819 const char *value = MAY_LJMP(luaL_checklstring(L, 3, &value_len));
Christopher Fauleta2097962019-07-15 16:25:33 +02005820 struct htx *htx = htxbuf(&msg->chn->buf);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005821
Christopher Fauleta2097962019-07-15 16:25:33 +02005822 lua_pushboolean(L, http_add_header(htx, ist2(name, name_len),
5823 ist2(value, value_len)));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005824 return 0;
5825}
5826
Christopher Fauletdf97ac42020-02-26 16:57:19 +01005827__LJMP static int hlua_http_req_add_hdr(lua_State *L)
5828{
5829 struct hlua_txn *htxn;
5830
5831 MAY_LJMP(check_args(L, 3, "req_add_hdr"));
5832 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5833
5834 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
5835 WILL_LJMP(lua_error(L));
5836
5837 return hlua_http_add_hdr(L, &htxn->s->txn->req);
5838}
5839
5840__LJMP static int hlua_http_res_add_hdr(lua_State *L)
5841{
5842 struct hlua_txn *htxn;
5843
5844 MAY_LJMP(check_args(L, 3, "res_add_hdr"));
5845 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5846
5847 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
5848 WILL_LJMP(lua_error(L));
5849
5850 return hlua_http_add_hdr(L, &htxn->s->txn->rsp);
5851}
5852
5853static int hlua_http_req_set_hdr(lua_State *L)
5854{
5855 struct hlua_txn *htxn;
5856
5857 MAY_LJMP(check_args(L, 3, "req_set_hdr"));
5858 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5859
5860 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
5861 WILL_LJMP(lua_error(L));
5862
5863 hlua_http_del_hdr(L, &htxn->s->txn->req);
5864 return hlua_http_add_hdr(L, &htxn->s->txn->req);
5865}
5866
5867static int hlua_http_res_set_hdr(lua_State *L)
5868{
5869 struct hlua_txn *htxn;
5870
5871 MAY_LJMP(check_args(L, 3, "res_set_hdr"));
5872 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5873
5874 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
5875 WILL_LJMP(lua_error(L));
5876
5877 hlua_http_del_hdr(L, &htxn->s->txn->rsp);
5878 return hlua_http_add_hdr(L, &htxn->s->txn->rsp);
5879}
5880
5881/* This function set the method. */
5882static int hlua_http_req_set_meth(lua_State *L)
5883{
5884 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5885 size_t name_len;
5886 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
5887
5888 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
5889 WILL_LJMP(lua_error(L));
5890
5891 lua_pushboolean(L, http_req_replace_stline(0, name, name_len, htxn->p, htxn->s) != -1);
5892 return 1;
5893}
5894
5895/* This function set the method. */
5896static int hlua_http_req_set_path(lua_State *L)
5897{
5898 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5899 size_t name_len;
5900 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
5901
5902 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
5903 WILL_LJMP(lua_error(L));
5904
5905 lua_pushboolean(L, http_req_replace_stline(1, name, name_len, htxn->p, htxn->s) != -1);
5906 return 1;
5907}
5908
5909/* This function set the query-string. */
5910static int hlua_http_req_set_query(lua_State *L)
5911{
5912 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5913 size_t name_len;
5914 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
5915
5916 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
5917 WILL_LJMP(lua_error(L));
5918
5919 /* Check length. */
5920 if (name_len > trash.size - 1) {
5921 lua_pushboolean(L, 0);
5922 return 1;
5923 }
5924
5925 /* Add the mark question as prefix. */
5926 chunk_reset(&trash);
5927 trash.area[trash.data++] = '?';
5928 memcpy(trash.area + trash.data, name, name_len);
5929 trash.data += name_len;
5930
5931 lua_pushboolean(L,
5932 http_req_replace_stline(2, trash.area, trash.data, htxn->p, htxn->s) != -1);
5933 return 1;
5934}
5935
5936/* This function set the uri. */
5937static int hlua_http_req_set_uri(lua_State *L)
5938{
5939 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5940 size_t name_len;
5941 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
5942
5943 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
5944 WILL_LJMP(lua_error(L));
5945
5946 lua_pushboolean(L, http_req_replace_stline(3, name, name_len, htxn->p, htxn->s) != -1);
5947 return 1;
5948}
5949
5950/* This function set the response code & optionally reason. */
5951static int hlua_http_res_set_status(lua_State *L)
5952{
5953 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5954 unsigned int code = MAY_LJMP(luaL_checkinteger(L, 2));
5955 const char *str = MAY_LJMP(luaL_optlstring(L, 3, NULL, NULL));
5956 const struct ist reason = ist2(str, (str ? strlen(str) : 0));
5957
5958 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
5959 WILL_LJMP(lua_error(L));
5960
5961 http_res_set_status(code, reason, htxn->s);
5962 return 0;
5963}
5964
5965/*
5966 *
5967 *
5968 * Class HTTPMessage
5969 *
5970 *
5971 */
5972
5973/* Returns a struct http_msg if the stack entry "ud" is a class HTTPMessage,
5974 * otherwise it throws an error.
5975 */
5976__LJMP static struct http_msg *hlua_checkhttpmsg(lua_State *L, int ud)
5977{
5978 return MAY_LJMP(hlua_checkudata(L, ud, class_http_msg_ref));
5979}
5980
5981/* Creates and pushes on the stack a HTTP object according with a current TXN.
5982 */
Christopher Faulet78c35472020-02-26 17:14:08 +01005983static int hlua_http_msg_new(lua_State *L, struct http_msg *msg)
Christopher Fauletdf97ac42020-02-26 16:57:19 +01005984{
5985 /* Check stack size. */
5986 if (!lua_checkstack(L, 3))
5987 return 0;
5988
5989 lua_newtable(L);
5990 lua_pushlightuserdata(L, msg);
5991 lua_rawseti(L, -2, 0);
5992
5993 /* Create the "channel" field that contains the request channel object. */
5994 lua_pushstring(L, "channel");
5995 if (!hlua_channel_new(L, msg->chn))
5996 return 0;
5997 lua_rawset(L, -3);
5998
5999 /* Pop a class stream metatable and affect it to the table. */
6000 lua_rawgeti(L, LUA_REGISTRYINDEX, class_http_msg_ref);
6001 lua_setmetatable(L, -2);
6002
6003 return 1;
6004}
6005
6006/* Helper function returning a filter attached to the HTTP message at the
6007 * position <ud> in the stack, filling the current offset and length of the
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006008 * filter. If no filter is attached, NULL is returned and <offset> and <len> are
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006009 * filled with output and input length respectively.
6010 */
6011static struct filter *hlua_http_msg_filter(lua_State *L, int ud, struct http_msg *msg, size_t *offset, size_t *len)
6012{
6013 struct channel *chn = msg->chn;
6014 struct htx *htx = htxbuf(&chn->buf);
6015 struct filter *filter = NULL;
6016
6017 *offset = co_data(msg->chn);
6018 *len = htx->data - co_data(msg->chn);
6019
6020 if (lua_getfield(L, ud, "__filter") == LUA_TLIGHTUSERDATA) {
6021 filter = lua_touserdata (L, -1);
6022 if (msg->msg_state >= HTTP_MSG_DATA) {
6023 struct hlua_flt_ctx *flt_ctx = filter->ctx;
6024
6025 *offset = flt_ctx->cur_off[CHN_IDX(chn)];
6026 *len = flt_ctx->cur_len[CHN_IDX(chn)];
6027 }
6028 }
6029
6030 lua_pop(L, 1);
6031 return filter;
6032}
6033
6034/* Returns true if the channel attached to the HTTP message is the response
6035 * channel.
6036 */
6037__LJMP static int hlua_http_msg_is_resp(lua_State *L)
6038{
6039 struct http_msg *msg;
6040
6041 MAY_LJMP(check_args(L, 1, "is_resp"));
6042 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6043
6044 lua_pushboolean(L, !!(msg->chn->flags & CF_ISRESP));
6045 return 1;
6046}
6047
6048/* Returns an array containing the elements status-line of the HTTP message. It relies
6049 * on hlua_http_get_stline().
6050 */
6051__LJMP static int hlua_http_msg_get_stline(lua_State *L)
6052{
6053 struct http_msg *msg;
6054 struct htx *htx;
6055 struct htx_sl *sl;
6056
6057 MAY_LJMP(check_args(L, 1, "get_stline"));
6058 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6059
6060 if (msg->msg_state > HTTP_MSG_BODY)
6061 WILL_LJMP(lua_error(L));
6062
6063 htx = htxbuf(&msg->chn->buf);
6064 sl = http_get_stline(htx);
6065 if (!sl)
6066 return 0;
6067 return hlua_http_get_stline(L, sl);
6068}
6069
6070/* Returns an array containing all headers of the HTTP message. it relies on
6071 * hlua_http_get_headers().
6072 */
6073__LJMP static int hlua_http_msg_get_headers(lua_State *L)
6074{
6075 struct http_msg *msg;
6076
6077 MAY_LJMP(check_args(L, 1, "get_headers"));
6078 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6079
6080 if (msg->msg_state > HTTP_MSG_BODY)
6081 WILL_LJMP(lua_error(L));
6082
6083 return hlua_http_get_headers(L, msg);
6084}
6085
6086/* Deletes all occurrences of an header in the HTTP message matching on its
6087 * name. It relies on hlua_http_del_hdr().
6088 */
6089__LJMP static int hlua_http_msg_del_hdr(lua_State *L)
6090{
6091 struct http_msg *msg;
6092
6093 MAY_LJMP(check_args(L, 2, "del_header"));
6094 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6095
6096 if (msg->msg_state > HTTP_MSG_BODY)
6097 WILL_LJMP(lua_error(L));
6098
6099 return hlua_http_del_hdr(L, msg);
6100}
6101
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006102/* Matches the full value line of all occurrences of an header in the HTTP
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006103 * message given its name against a regex and replaces it if it matches. It
6104 * relies on hlua_http_rep_hdr().
6105 */
6106__LJMP static int hlua_http_msg_rep_hdr(lua_State *L)
6107{
6108 struct http_msg *msg;
6109
6110 MAY_LJMP(check_args(L, 4, "rep_header"));
6111 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6112
6113 if (msg->msg_state > HTTP_MSG_BODY)
6114 WILL_LJMP(lua_error(L));
6115
6116 return hlua_http_rep_hdr(L, msg, 1);
6117}
6118
Ilya Shipitsinbd6b4be2021-10-15 16:18:21 +05006119/* Matches all comma-separated values of all occurrences of an header in the HTTP
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006120 * message given its name against a regex and replaces it if it matches. It
6121 * relies on hlua_http_rep_hdr().
6122 */
6123__LJMP static int hlua_http_msg_rep_val(lua_State *L)
6124{
6125 struct http_msg *msg;
6126
6127 MAY_LJMP(check_args(L, 4, "rep_value"));
6128 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6129
6130 if (msg->msg_state > HTTP_MSG_BODY)
6131 WILL_LJMP(lua_error(L));
6132
6133 return hlua_http_rep_hdr(L, msg, 0);
6134}
6135
6136/* Add an header in the HTTP message. It relies on hlua_http_add_hdr() */
6137__LJMP static int hlua_http_msg_add_hdr(lua_State *L)
6138{
6139 struct http_msg *msg;
6140
6141 MAY_LJMP(check_args(L, 3, "add_header"));
6142 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6143
6144 if (msg->msg_state > HTTP_MSG_BODY)
6145 WILL_LJMP(lua_error(L));
6146
6147 return hlua_http_add_hdr(L, msg);
6148}
6149
6150/* Add an header in the HTTP message removing existing headers with the same
6151 * name. It relies on hlua_http_del_hdr() and hlua_http_add_hdr().
6152 */
6153__LJMP static int hlua_http_msg_set_hdr(lua_State *L)
6154{
6155 struct http_msg *msg;
6156
6157 MAY_LJMP(check_args(L, 3, "set_header"));
6158 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6159
6160 if (msg->msg_state > HTTP_MSG_BODY)
6161 WILL_LJMP(lua_error(L));
6162
6163 hlua_http_del_hdr(L, msg);
6164 return hlua_http_add_hdr(L, msg);
6165}
6166
6167/* Rewrites the request method. It relies on http_req_replace_stline(). */
6168__LJMP static int hlua_http_msg_set_meth(lua_State *L)
6169{
6170 struct stream *s;
6171 struct http_msg *msg;
6172 const char *name;
6173 size_t name_len;
6174
6175 MAY_LJMP(check_args(L, 2, "set_method"));
6176 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6177 name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
6178
6179 if ((msg->chn->flags & CF_ISRESP) || msg->msg_state > HTTP_MSG_BODY)
6180 WILL_LJMP(lua_error(L));
6181
6182 s = chn_strm(msg->chn);
6183 lua_pushboolean(L, http_req_replace_stline(0, name, name_len, s->be, s) != -1);
6184 return 1;
6185}
6186
6187/* Rewrites the request path. It relies on http_req_replace_stline(). */
6188__LJMP static int hlua_http_msg_set_path(lua_State *L)
6189{
6190 struct stream *s;
6191 struct http_msg *msg;
6192 const char *name;
6193 size_t name_len;
6194
6195 MAY_LJMP(check_args(L, 2, "set_path"));
6196 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6197 name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
6198
6199 if ((msg->chn->flags & CF_ISRESP) || msg->msg_state > HTTP_MSG_BODY)
6200 WILL_LJMP(lua_error(L));
6201
6202 s = chn_strm(msg->chn);
6203 lua_pushboolean(L, http_req_replace_stline(1, name, name_len, s->be, s) != -1);
6204 return 1;
6205}
6206
6207/* Rewrites the request query-string. It relies on http_req_replace_stline(). */
6208__LJMP static int hlua_http_msg_set_query(lua_State *L)
6209{
6210 struct stream *s;
6211 struct http_msg *msg;
6212 const char *name;
6213 size_t name_len;
6214
6215 MAY_LJMP(check_args(L, 2, "set_query"));
6216 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6217 name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
6218
6219 if ((msg->chn->flags & CF_ISRESP) || msg->msg_state > HTTP_MSG_BODY)
6220 WILL_LJMP(lua_error(L));
6221
6222 /* Check length. */
6223 if (name_len > trash.size - 1) {
6224 lua_pushboolean(L, 0);
6225 return 1;
6226 }
6227
6228 /* Add the mark question as prefix. */
6229 chunk_reset(&trash);
6230 trash.area[trash.data++] = '?';
6231 memcpy(trash.area + trash.data, name, name_len);
6232 trash.data += name_len;
6233
6234 s = chn_strm(msg->chn);
6235 lua_pushboolean(L, http_req_replace_stline(2, trash.area, trash.data, s->be, s) != -1);
6236 return 1;
6237}
6238
6239/* Rewrites the request URI. It relies on http_req_replace_stline(). */
6240__LJMP static int hlua_http_msg_set_uri(lua_State *L)
6241{
6242 struct stream *s;
6243 struct http_msg *msg;
6244 const char *name;
6245 size_t name_len;
6246
6247 MAY_LJMP(check_args(L, 2, "set_uri"));
6248 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6249 name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
6250
6251 if ((msg->chn->flags & CF_ISRESP) || msg->msg_state > HTTP_MSG_BODY)
6252 WILL_LJMP(lua_error(L));
6253
6254 s = chn_strm(msg->chn);
6255 lua_pushboolean(L, http_req_replace_stline(3, name, name_len, s->be, s) != -1);
6256 return 1;
6257}
6258
6259/* Rewrites the response status code. It relies on http_res_set_status(). */
6260__LJMP static int hlua_http_msg_set_status(lua_State *L)
6261{
6262 struct http_msg *msg;
6263 unsigned int code;
6264 const char *reason;
6265 size_t reason_len;
6266
6267 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6268 code = MAY_LJMP(luaL_checkinteger(L, 2));
6269 reason = MAY_LJMP(luaL_optlstring(L, 3, NULL, &reason_len));
6270
6271 if (!(msg->chn->flags & CF_ISRESP) || msg->msg_state > HTTP_MSG_BODY)
6272 WILL_LJMP(lua_error(L));
6273
6274 lua_pushboolean(L, http_res_set_status(code, ist2(reason, reason_len), chn_strm(msg->chn)) != -1);
6275 return 1;
6276}
6277
6278/* Returns true if the HTTP message is full. */
6279__LJMP static int hlua_http_msg_is_full(lua_State *L)
6280{
6281 struct http_msg *msg;
6282
6283 MAY_LJMP(check_args(L, 1, "is_full"));
6284 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6285 lua_pushboolean(L, channel_full(msg->chn, 0));
6286 return 1;
6287}
6288
6289/* Returns true if the HTTP message may still receive data. */
6290__LJMP static int hlua_http_msg_may_recv(lua_State *L)
6291{
6292 struct http_msg *msg;
6293 struct htx *htx;
6294
6295 MAY_LJMP(check_args(L, 1, "may_recv"));
6296 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6297 htx = htxbuf(&msg->chn->buf);
6298 lua_pushboolean(L, (htx_expect_more(htx) && !channel_input_closed(msg->chn) && channel_may_recv(msg->chn)));
6299 return 1;
6300}
6301
6302/* Returns true if the HTTP message EOM was received */
6303__LJMP static int hlua_http_msg_is_eom(lua_State *L)
6304{
6305 struct http_msg *msg;
6306 struct htx *htx;
6307
6308 MAY_LJMP(check_args(L, 1, "may_recv"));
6309 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6310 htx = htxbuf(&msg->chn->buf);
6311 lua_pushboolean(L, !htx_expect_more(htx));
6312 return 1;
6313}
6314
6315/* Returns the number of bytes available in the input side of the HTTP
6316 * message. This function never fails.
6317 */
6318__LJMP static int hlua_http_msg_get_in_len(lua_State *L)
6319{
6320 struct http_msg *msg;
Christopher Fauleteae8afa2020-02-26 17:15:48 +01006321 size_t output, input;
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006322
6323 MAY_LJMP(check_args(L, 1, "input"));
6324 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
Christopher Fauleteae8afa2020-02-26 17:15:48 +01006325 hlua_http_msg_filter(L, 1, msg, &output, &input);
6326 lua_pushinteger(L, input);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006327 return 1;
6328}
6329
6330/* Returns the number of bytes available in the output side of the HTTP
6331 * message. This function never fails.
6332 */
6333__LJMP static int hlua_http_msg_get_out_len(lua_State *L)
6334{
6335 struct http_msg *msg;
Christopher Fauleteae8afa2020-02-26 17:15:48 +01006336 size_t output, input;
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006337
6338 MAY_LJMP(check_args(L, 1, "output"));
6339 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
Christopher Fauleteae8afa2020-02-26 17:15:48 +01006340 hlua_http_msg_filter(L, 1, msg, &output, &input);
6341 lua_pushinteger(L, output);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006342 return 1;
6343}
6344
6345/* Copies at most <len> bytes of DATA blocks from the HTTP message <msg>
6346 * starting at the offset <offset> and put it in a string LUA variables. It
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006347 * returns the built string length. It stops on the first non-DATA HTX
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006348 * block. This function is called during the payload filtering, so the headers
6349 * are already scheduled for output (from the filter point of view).
6350 */
6351static int _hlua_http_msg_dup(struct http_msg *msg, lua_State *L, size_t offset, size_t len)
6352{
6353 struct htx *htx = htxbuf(&msg->chn->buf);
6354 struct htx_blk *blk;
6355 struct htx_ret htxret;
6356 luaL_Buffer b;
6357 int ret = 0;
6358
6359 luaL_buffinit(L, &b);
6360 htxret = htx_find_offset(htx, offset);
6361 for (blk = htxret.blk, offset = htxret.ret; blk && len; blk = htx_get_next_blk(htx, blk)) {
6362 enum htx_blk_type type = htx_get_blk_type(blk);
6363 struct ist v;
6364
6365 switch (type) {
6366 case HTX_BLK_UNUSED:
6367 break;
6368
6369 case HTX_BLK_DATA:
6370 v = htx_get_blk_value(htx, blk);
Tim Duesterhusb113b5c2021-09-15 13:58:44 +02006371 v = istadv(v, offset);
Tim Duesterhus2471f5c2021-11-08 09:05:01 +01006372 v = isttrim(v, len);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006373
6374 luaL_addlstring(&b, v.ptr, v.len);
6375 ret += v.len;
6376 break;
6377
6378 default:
vishnu0af4bd72021-10-24 06:46:24 +05306379 if (!ret)
6380 goto no_data;
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006381 goto end;
6382 }
6383 offset = 0;
6384 }
6385
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006386end:
vishnu0af4bd72021-10-24 06:46:24 +05306387 if (!ret && (htx->flags & HTX_FL_EOM))
6388 goto no_data;
6389 luaL_pushresult(&b);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006390 return ret;
vishnu0af4bd72021-10-24 06:46:24 +05306391
6392 no_data:
6393 /* Remove the empty string and push nil on the stack */
6394 lua_pop(L, 1);
6395 lua_pushnil(L);
6396 return 0;
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006397}
6398
6399/* Copies the string <str> to the HTTP message <msg> at the offset
6400 * <offset>. This function returns -1 if data cannot be copied. Otherwise, it
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006401 * returns the amount of data written. This function is responsible to update
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006402 * the filter context.
6403 */
6404static int _hlua_http_msg_insert(struct http_msg *msg, struct filter *filter, struct ist str, size_t offset)
6405{
6406 struct htx *htx = htx_from_buf(&msg->chn->buf);
6407 struct htx_ret htxret;
6408 int /*max, */ret = 0;
6409
6410 /* Nothing to do, just return */
6411 if (unlikely(istlen(str) == 0))
6412 goto end;
6413
6414 if (istlen(str) > htx_free_data_space(htx)) {
6415 ret = -1;
6416 goto end;
6417 }
6418
6419 htxret = htx_find_offset(htx, offset);
6420 if (!htxret.blk || htx_get_blk_type(htxret.blk) != HTX_BLK_DATA) {
6421 if (!htx_add_last_data(htx, str))
6422 goto end;
6423 }
6424 else {
6425 struct ist v = htx_get_blk_value(htx, htxret.blk);
6426 v.ptr += htxret.ret;
6427 v.len = 0;
6428 if (!htx_replace_blk_value(htx, htxret.blk, v, str))
6429 goto end;
6430 }
6431 ret = str.len;
6432 if (ret) {
6433 struct hlua_flt_ctx *flt_ctx = filter->ctx;
6434 flt_update_offsets(filter, msg->chn, ret);
6435 flt_ctx->cur_len[CHN_IDX(msg->chn)] += ret;
6436 }
6437
6438 end:
6439 htx_to_buf(htx, &msg->chn->buf);
6440 return ret;
6441}
6442
6443/* Helper function removing at most <len> bytes of DATA blocks at the absolute
6444 * position <offset>. It stops on the first non-DATA HTX block. This function is
6445 * called during the payload filtering, so the headers are already scheduled for
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006446 * output (from the filter point of view). This function is responsible to
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006447 * update the filter context.
6448 */
6449static void _hlua_http_msg_delete(struct http_msg *msg, struct filter *filter, size_t offset, size_t len)
6450{
6451 struct hlua_flt_ctx *flt_ctx = filter->ctx;
6452 struct htx *htx = htx_from_buf(&msg->chn->buf);
6453 struct htx_blk *blk;
6454 struct htx_ret htxret;
6455 size_t ret = 0;
6456
6457 /* Be sure <len> is always the amount of DATA to remove */
6458 if (htx->data == offset+len && htx_get_tail_type(htx) == HTX_BLK_DATA) {
6459 htx_truncate(htx, offset);
6460 ret = len;
6461 goto end;
6462 }
6463
6464 htxret = htx_find_offset(htx, offset);
6465 blk = htxret.blk;
6466 if (htxret.ret) {
6467 struct ist v;
6468
6469 if (htx_get_blk_type(blk) != HTX_BLK_DATA)
6470 goto end;
6471 v = htx_get_blk_value(htx, blk);
6472 v.ptr += htxret.ret;
Tim Duesterhus2471f5c2021-11-08 09:05:01 +01006473 v = isttrim(v, len);
Tim Duesterhusb113b5c2021-09-15 13:58:44 +02006474 blk = htx_replace_blk_value(htx, blk, v, IST_NULL);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006475 len -= v.len;
6476 ret += v.len;
6477 }
6478
6479
6480 while (blk && len) {
6481 enum htx_blk_type type = htx_get_blk_type(blk);
6482 uint32_t sz = htx_get_blksz(blk);
6483
6484 switch (type) {
6485 case HTX_BLK_UNUSED:
6486 break;
6487
6488 case HTX_BLK_DATA:
6489 if (len < sz) {
6490 htx_cut_data_blk(htx, blk, len);
6491 ret += len;
6492 goto end;
6493 }
6494 break;
6495
6496 default:
6497 goto end;
6498 }
6499
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006500 /* Remove all the data block */
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006501 len -= sz;
6502 ret += sz;
6503 blk = htx_remove_blk(htx, blk);
6504 }
6505
6506end:
6507 flt_update_offsets(filter, msg->chn, -ret);
6508 flt_ctx->cur_len[CHN_IDX(msg->chn)] -= ret;
6509 /* WARNING: we don't call htx_to_buf() on purpose, because we don't want
6510 * to loose the EOM flag if the message is empty.
6511 */
6512}
6513
6514/* Copies input data found in an HTTP message. Unlike the channel function used
6515 * to duplicate raw data, this one can only be called inside a filter, from
6516 * http_payload callback. So it cannot yield. An exception is returned if it is
6517 * called from another callback. If nothing was copied, a nil value is pushed on
6518 * the stack.
6519 */
6520__LJMP static int hlua_http_msg_get_body(lua_State *L)
6521{
6522 struct http_msg *msg;
6523 struct filter *filter;
6524 size_t output, input;
6525 int offset, len;
6526
6527 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
6528 WILL_LJMP(luaL_error(L, "'data' expects at most 2 arguments"));
6529 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6530
6531 if (msg->msg_state < HTTP_MSG_DATA)
6532 WILL_LJMP(lua_error(L));
6533
6534 filter = hlua_http_msg_filter(L, 1, msg, &output, &input);
6535 if (!filter || !hlua_filter_from_payload(filter))
6536 WILL_LJMP(lua_error(L));
6537
6538 if (!ci_data(msg->chn) && channel_input_closed(msg->chn)) {
6539 lua_pushnil(L);
6540 return 1;
6541 }
6542
6543 offset = output;
6544 if (lua_gettop(L) > 1) {
6545 offset = MAY_LJMP(luaL_checkinteger(L, 2));
6546 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02006547 offset = MAX(0, (int)input + offset);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006548 offset += output;
6549 if (offset < output || offset > input + output) {
6550 lua_pushfstring(L, "offset out of range.");
6551 WILL_LJMP(lua_error(L));
6552 }
6553 }
6554 len = output + input - offset;
6555 if (lua_gettop(L) == 3) {
6556 len = MAY_LJMP(luaL_checkinteger(L, 3));
6557 if (!len)
6558 goto dup;
6559 if (len == -1)
6560 len = global.tune.bufsize;
6561 if (len < 0) {
6562 lua_pushfstring(L, "length out of range.");
6563 WILL_LJMP(lua_error(L));
6564 }
6565 }
6566
6567 dup:
6568 _hlua_http_msg_dup(msg, L, offset, len);
6569 return 1;
6570}
6571
6572/* Appends a string to the HTTP message, after all existing DATA blocks but
6573 * before the trailers, if any. It returns the amount of data written or -1 if
6574 * nothing was copied. Unlike the channel function used to append data, this one
6575 * can only be called inside a filter, from http_payload callback. So it cannot
6576 * yield. An exception is returned if it is called from another callback.
6577 */
6578__LJMP static int hlua_http_msg_append(lua_State *L)
6579{
6580 struct http_msg *msg;
6581 struct filter *filter;
6582 const char *str;
6583 size_t offset, len, sz;
6584 int ret;
6585
6586 MAY_LJMP(check_args(L, 2, "append"));
6587 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6588
6589 if (msg->msg_state < HTTP_MSG_DATA)
6590 WILL_LJMP(lua_error(L));
6591
6592 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
6593 filter = hlua_http_msg_filter(L, 1, msg, &offset, &len);
6594 if (!filter || !hlua_filter_from_payload(filter))
6595 WILL_LJMP(lua_error(L));
6596
6597 ret = _hlua_http_msg_insert(msg, filter, ist2(str, sz), offset+len);
6598 lua_pushinteger(L, ret);
6599 return 1;
6600}
6601
6602/* Prepends a string to the HTTP message, before all existing DATA blocks. It
6603 * returns the amount of data written or -1 if nothing was copied. Unlike the
6604 * channel function used to prepend data, this one can only be called inside a
6605 * filter, from http_payload callback. So it cannot yield. An exception is
6606 * returned if it is called from another callback.
6607 */
6608__LJMP static int hlua_http_msg_prepend(lua_State *L)
6609{
6610 struct http_msg *msg;
6611 struct filter *filter;
6612 const char *str;
6613 size_t offset, len, sz;
6614 int ret;
6615
6616 MAY_LJMP(check_args(L, 2, "prepend"));
6617 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006618
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006619 if (msg->msg_state < HTTP_MSG_DATA)
6620 WILL_LJMP(lua_error(L));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006621
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006622 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
6623 filter = hlua_http_msg_filter(L, 1, msg, &offset, &len);
6624 if (!filter || !hlua_filter_from_payload(filter))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006625 WILL_LJMP(lua_error(L));
6626
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006627 ret = _hlua_http_msg_insert(msg, filter, ist2(str, sz), offset);
6628 lua_pushinteger(L, ret);
6629 return 1;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006630}
6631
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006632/* Inserts a string to the HTTP message at a given offset. By default the string
6633 * is appended at the end of DATA blocks. It returns the amount of data written
6634 * or -1 if nothing was copied. Unlike the channel function used to insert data,
6635 * this one can only be called inside a filter, from http_payload callback. So
6636 * it cannot yield. An exception is returned if it is called from another
6637 * callback.
6638 */
6639__LJMP static int hlua_http_msg_insert_data(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006640{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006641 struct http_msg *msg;
6642 struct filter *filter;
6643 const char *str;
6644 size_t input, output, sz;
6645 int offset;
6646 int ret;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006647
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006648 if (lua_gettop(L) < 2 || lua_gettop(L) > 3)
6649 WILL_LJMP(luaL_error(L, "'insert' expects at least 1 argument and at most 2 arguments"));
6650 MAY_LJMP(check_args(L, 2, "insert"));
6651 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006652
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006653 if (msg->msg_state < HTTP_MSG_DATA)
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006654 WILL_LJMP(lua_error(L));
6655
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006656 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
6657 filter = hlua_http_msg_filter(L, 1, msg, &input, &output);
6658 if (!filter || !hlua_filter_from_payload(filter))
6659 WILL_LJMP(lua_error(L));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006660
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006661 offset = input + output;
6662 if (lua_gettop(L) > 2) {
6663 offset = MAY_LJMP(luaL_checkinteger(L, 3));
6664 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02006665 offset = MAX(0, (int)input + offset);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006666 offset += output;
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006667 if (offset < output || offset > output + input) {
6668 lua_pushfstring(L, "offset out of range.");
6669 WILL_LJMP(lua_error(L));
6670 }
6671 }
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006672
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006673 ret = _hlua_http_msg_insert(msg, filter, ist2(str, sz), offset);
6674 lua_pushinteger(L, ret);
6675 return 1;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006676}
6677
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006678/* Removes a given amount of data from the HTTP message at a given offset. By
6679 * default all DATA blocks are removed. It returns the amount of data
6680 * removed. Unlike the channel function used to remove data, this one can only
6681 * be called inside a filter, from http_payload callback. So it cannot yield. An
6682 * exception is returned if it is called from another callback.
6683 */
6684__LJMP static int hlua_http_msg_del_data(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006685{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006686 struct http_msg *msg;
6687 struct filter *filter;
6688 size_t input, output;
6689 int offset, len;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006690
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006691 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
Boyang Lie0c54352022-05-10 17:47:23 +00006692 WILL_LJMP(luaL_error(L, "'remove' expects at most 2 arguments"));
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006693 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006694
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006695 if (msg->msg_state < HTTP_MSG_DATA)
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006696 WILL_LJMP(lua_error(L));
6697
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006698 filter = hlua_http_msg_filter(L, 1, msg, &input, &output);
6699 if (!filter || !hlua_filter_from_payload(filter))
6700 WILL_LJMP(lua_error(L));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006701
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006702 offset = input + output;
Boyang Lie0c54352022-05-10 17:47:23 +00006703 if (lua_gettop(L) > 1) {
6704 offset = MAY_LJMP(luaL_checkinteger(L, 2));
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006705 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02006706 offset = MAX(0, (int)input + offset);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006707 offset += output;
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006708 if (offset < output || offset > output + input) {
6709 lua_pushfstring(L, "offset out of range.");
6710 WILL_LJMP(lua_error(L));
6711 }
6712 }
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006713
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006714 len = output + input - offset;
Boyang Lie0c54352022-05-10 17:47:23 +00006715 if (lua_gettop(L) == 3) {
6716 len = MAY_LJMP(luaL_checkinteger(L, 3));
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006717 if (!len)
6718 goto end;
6719 if (len == -1)
6720 len = output + input - offset;
6721 if (len < 0 || offset + len > output + input) {
6722 lua_pushfstring(L, "length out of range.");
6723 WILL_LJMP(lua_error(L));
6724 }
6725 }
6726
6727 _hlua_http_msg_delete(msg, filter, offset, len);
6728
6729 end:
6730 lua_pushinteger(L, len);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006731 return 1;
6732}
6733
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006734/* Replaces a given amount of data at the given offset by a string. By default,
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006735 * all remaining data are removed, accordingly to the filter context. It returns
6736 * the amount of data written or -1 if nothing was copied. Unlike the channel
6737 * function used to replace data, this one can only be called inside a filter,
6738 * from http_payload callback. So it cannot yield. An exception is returned if
6739 * it is called from another callback.
6740 */
6741__LJMP static int hlua_http_msg_set_data(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006742{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006743 struct http_msg *msg;
6744 struct filter *filter;
6745 struct htx *htx;
6746 const char *str;
6747 size_t input, output, sz;
6748 int offset, len;
6749 int ret;
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02006750
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006751 if (lua_gettop(L) < 2 || lua_gettop(L) > 4)
6752 WILL_LJMP(luaL_error(L, "'set' expects at least 1 argument and at most 3 arguments"));
6753 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6754
6755 if (msg->msg_state < HTTP_MSG_DATA)
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006756 WILL_LJMP(lua_error(L));
6757
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006758 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
6759 filter = hlua_http_msg_filter(L, 1, msg, &output, &input);
6760 if (!filter || !hlua_filter_from_payload(filter))
6761 WILL_LJMP(lua_error(L));
6762
6763 offset = output;
6764 if (lua_gettop(L) > 2) {
6765 offset = MAY_LJMP(luaL_checkinteger(L, 3));
6766 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02006767 offset = MAX(0, (int)input + offset);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006768 offset += output;
6769 if (offset < output || offset > input + output) {
6770 lua_pushfstring(L, "offset out of range.");
6771 WILL_LJMP(lua_error(L));
6772 }
6773 }
6774
6775 len = output + input - offset;
6776 if (lua_gettop(L) == 4) {
6777 len = MAY_LJMP(luaL_checkinteger(L, 4));
6778 if (!len)
6779 goto set;
6780 if (len == -1)
6781 len = output + input - offset;
6782 if (len < 0 || offset + len > output + input) {
6783 lua_pushfstring(L, "length out of range.");
6784 WILL_LJMP(lua_error(L));
6785 }
6786 }
6787
6788 set:
6789 /* Be sure we can copied the string once input data will be removed. */
6790 htx = htx_from_buf(&msg->chn->buf);
6791 if (sz > htx_free_data_space(htx) + len)
6792 lua_pushinteger(L, -1);
6793 else {
6794 _hlua_http_msg_delete(msg, filter, offset, len);
6795 ret = _hlua_http_msg_insert(msg, filter, ist2(str, sz), offset);
6796 lua_pushinteger(L, ret);
6797 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006798 return 1;
6799}
6800
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006801/* Prepends data into an HTTP message and forward it, from the filter point of
6802 * view. It returns the amount of data written or -1 if nothing was sent. Unlike
6803 * the channel function used to send data, this one can only be called inside a
6804 * filter, from http_payload callback. So it cannot yield. An exception is
6805 * returned if it is called from another callback.
6806 */
6807__LJMP static int hlua_http_msg_send(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006808{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006809 struct http_msg *msg;
6810 struct filter *filter;
6811 struct htx *htx;
6812 const char *str;
6813 size_t offset, len, sz;
6814 int ret;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006815
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006816 MAY_LJMP(check_args(L, 2, "send"));
6817 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6818
6819 if (msg->msg_state < HTTP_MSG_DATA)
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006820 WILL_LJMP(lua_error(L));
6821
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006822 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
6823 filter = hlua_http_msg_filter(L, 1, msg, &offset, &len);
6824 if (!filter || !hlua_filter_from_payload(filter))
6825 WILL_LJMP(lua_error(L));
6826
6827 /* Return an error if the channel's output is closed */
6828 if (unlikely(channel_output_closed(msg->chn))) {
6829 lua_pushinteger(L, -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006830 return 1;
6831 }
6832
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006833 htx = htx_from_buf(&msg->chn->buf);
6834 if (sz > htx_free_data_space(htx)) {
6835 lua_pushinteger(L, -1);
6836 return 1;
6837 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006838
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006839 ret = _hlua_http_msg_insert(msg, filter, ist2(str, sz), offset);
6840 if (ret > 0) {
6841 struct hlua_flt_ctx *flt_ctx = filter->ctx;
6842
6843 FLT_OFF(filter, msg->chn) += ret;
6844 flt_ctx->cur_len[CHN_IDX(msg->chn)] -= ret;
6845 flt_ctx->cur_off[CHN_IDX(msg->chn)] += ret;
6846 }
6847
6848 lua_pushinteger(L, ret);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006849 return 1;
6850}
6851
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006852/* Forwards a given amount of bytes. It return -1 if the channel's output is
6853 * closed. Otherwise, it returns the number of bytes forwarded. Unlike the
6854 * channel function used to forward data, this one can only be called inside a
6855 * filter, from http_payload callback. So it cannot yield. An exception is
6856 * returned if it is called from another callback. All other functions deal with
6857 * DATA block, this one not.
6858*/
6859__LJMP static int hlua_http_msg_forward(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006860{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006861 struct http_msg *msg;
6862 struct filter *filter;
6863 size_t offset, len;
6864 int fwd, ret = 0;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006865
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006866 MAY_LJMP(check_args(L, 2, "forward"));
6867 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6868
6869 if (msg->msg_state < HTTP_MSG_DATA)
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006870 WILL_LJMP(lua_error(L));
6871
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006872 fwd = MAY_LJMP(luaL_checkinteger(L, 2));
6873 filter = hlua_http_msg_filter(L, 1, msg, &offset, &len);
6874 if (!filter || !hlua_filter_from_payload(filter))
6875 WILL_LJMP(lua_error(L));
6876
6877 /* Nothing to do, just return */
6878 if (!fwd)
6879 goto end;
6880
6881 /* Return an error if the channel's output is closed */
6882 if (unlikely(channel_output_closed(msg->chn))) {
6883 ret = -1;
6884 goto end;
6885 }
6886
6887 ret = fwd;
6888 if (ret > len)
6889 ret = len;
6890
6891 if (ret) {
6892 struct hlua_flt_ctx *flt_ctx = filter->ctx;
6893
6894 FLT_OFF(filter, msg->chn) += ret;
6895 flt_ctx->cur_off[CHN_IDX(msg->chn)] += ret;
6896 flt_ctx->cur_len[CHN_IDX(msg->chn)] -= ret;
6897 }
6898
6899 end:
6900 lua_pushinteger(L, ret);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006901 return 1;
6902}
6903
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006904/* Set EOM flag on the HTX message.
6905 *
6906 * NOTE: Not sure it is a good idea to manipulate this flag but for now I don't
6907 * really know how to do without this feature.
6908 */
6909__LJMP static int hlua_http_msg_set_eom(lua_State *L)
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02006910{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006911 struct http_msg *msg;
6912 struct htx *htx;
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02006913
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006914 MAY_LJMP(check_args(L, 1, "set_eom"));
6915 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6916 htx = htxbuf(&msg->chn->buf);
6917 htx->flags |= HTX_FL_EOM;
6918 return 0;
6919}
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006920
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006921/* Unset EOM flag on the HTX message.
6922 *
6923 * NOTE: Not sure it is a good idea to manipulate this flag but for now I don't
6924 * really know how to do without this feature.
6925 */
6926__LJMP static int hlua_http_msg_unset_eom(lua_State *L)
6927{
6928 struct http_msg *msg;
6929 struct htx *htx;
6930
6931 MAY_LJMP(check_args(L, 1, "set_eom"));
6932 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6933 htx = htxbuf(&msg->chn->buf);
6934 htx->flags &= ~HTX_FL_EOM;
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02006935 return 0;
6936}
6937
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006938/*
6939 *
6940 *
William Lallemand3956c4e2021-09-21 16:25:15 +02006941 * Class HTTPClient
6942 *
6943 *
6944 */
6945__LJMP static struct hlua_httpclient *hlua_checkhttpclient(lua_State *L, int ud)
6946{
6947 return MAY_LJMP(hlua_checkudata(L, ud, class_httpclient_ref));
6948}
6949
William Lallemandf77f1de2021-09-28 19:10:38 +02006950
6951/* stops the httpclient and ask it to kill itself */
6952__LJMP static int hlua_httpclient_gc(lua_State *L)
6953{
6954 struct hlua_httpclient *hlua_hc;
6955
6956 MAY_LJMP(check_args(L, 1, "__gc"));
6957
6958 hlua_hc = MAY_LJMP(hlua_checkhttpclient(L, 1));
6959
6960 httpclient_stop_and_destroy(hlua_hc->hc);
6961
6962 hlua_hc->hc = NULL;
6963
6964
6965 return 0;
6966}
6967
6968
William Lallemand3956c4e2021-09-21 16:25:15 +02006969__LJMP static int hlua_httpclient_new(lua_State *L)
6970{
6971 struct hlua_httpclient *hlua_hc;
6972 struct hlua *hlua;
6973
6974 /* Get hlua struct, or NULL if we execute from main lua state */
6975 hlua = hlua_gethlua(L);
6976 if (!hlua)
6977 return 0;
6978
6979 /* Check stack size. */
6980 if (!lua_checkstack(L, 3)) {
6981 hlua_pusherror(L, "httpclient: full stack");
6982 goto err;
6983 }
6984 /* Create the object: obj[0] = userdata. */
6985 lua_newtable(L);
6986 hlua_hc = MAY_LJMP(lua_newuserdata(L, sizeof(*hlua_hc)));
6987 lua_rawseti(L, -2, 0);
6988 memset(hlua_hc, 0, sizeof(*hlua_hc));
6989
6990 hlua_hc->hc = httpclient_new(hlua, 0, IST_NULL);
6991 if (!hlua_hc->hc)
6992 goto err;
6993
6994 /* Pop a class stream metatable and affect it to the userdata. */
6995 lua_rawgeti(L, LUA_REGISTRYINDEX, class_httpclient_ref);
6996 lua_setmetatable(L, -2);
6997
6998 return 1;
6999
7000 err:
7001 WILL_LJMP(lua_error(L));
7002 return 0;
7003}
7004
7005
7006/*
7007 * Callback of the httpclient, this callback wakes the lua task up, once the
7008 * httpclient receives some data
7009 *
7010 */
7011
William Lallemandbd5739e2021-10-28 15:41:38 +02007012static void hlua_httpclient_cb(struct httpclient *hc)
William Lallemand3956c4e2021-09-21 16:25:15 +02007013{
7014 struct hlua *hlua = hc->caller;
7015
7016 if (!hlua || !hlua->task)
7017 return;
7018
7019 task_wakeup(hlua->task, TASK_WOKEN_MSG);
7020}
7021
7022/*
William Lallemandd7df73a2021-09-23 17:54:00 +02007023 * Fill the lua stack with headers from the httpclient response
7024 * This works the same way as the hlua_http_get_headers() function
7025 */
7026__LJMP static int hlua_httpclient_get_headers(lua_State *L, struct hlua_httpclient *hlua_hc)
7027{
7028 struct http_hdr *hdr;
7029
7030 lua_newtable(L);
7031
William Lallemandef574b22021-10-05 16:19:31 +02007032 for (hdr = hlua_hc->hc->res.hdrs; hdr && isttest(hdr->n); hdr++) {
William Lallemandd7df73a2021-09-23 17:54:00 +02007033 struct ist n, v;
7034 int len;
7035
7036 n = hdr->n;
7037 v = hdr->v;
7038
7039 /* Check for existing entry:
7040 * assume that the table is on the top of the stack, and
7041 * push the key in the stack, the function lua_gettable()
7042 * perform the lookup.
7043 */
7044
7045 lua_pushlstring(L, n.ptr, n.len);
7046 lua_gettable(L, -2);
7047
7048 switch (lua_type(L, -1)) {
7049 case LUA_TNIL:
7050 /* Table not found, create it. */
7051 lua_pop(L, 1); /* remove the nil value. */
7052 lua_pushlstring(L, n.ptr, n.len); /* push the header name as key. */
7053 lua_newtable(L); /* create and push empty table. */
7054 lua_pushlstring(L, v.ptr, v.len); /* push header value. */
7055 lua_rawseti(L, -2, 0); /* index header value (pop it). */
7056 lua_rawset(L, -3); /* index new table with header name (pop the values). */
7057 break;
7058
7059 case LUA_TTABLE:
7060 /* Entry found: push the value in the table. */
7061 len = lua_rawlen(L, -1);
7062 lua_pushlstring(L, v.ptr, v.len); /* push header value. */
7063 lua_rawseti(L, -2, len+1); /* index header value (pop it). */
7064 lua_pop(L, 1); /* remove the table (it is stored in the main table). */
7065 break;
7066
7067 default:
7068 /* Other cases are errors. */
7069 hlua_pusherror(L, "internal error during the parsing of headers.");
7070 WILL_LJMP(lua_error(L));
7071 }
7072 }
7073 return 1;
7074}
7075
7076/*
William Lallemand746e6f32021-10-06 10:57:44 +02007077 * Allocate and return an array of http_hdr ist extracted from the <headers> lua table
7078 *
7079 * Caller must free the result
7080 */
7081struct http_hdr *hlua_httpclient_table_to_hdrs(lua_State *L)
7082{
7083 struct http_hdr hdrs[global.tune.max_http_hdr];
7084 struct http_hdr *result = NULL;
7085 uint32_t hdr_num = 0;
7086
7087 lua_pushnil(L);
7088 while (lua_next(L, -2) != 0) {
7089 struct ist name, value;
7090 const char *n, *v;
7091 size_t nlen, vlen;
7092
7093 if (!lua_isstring(L, -2) || !lua_istable(L, -1)) {
7094 /* Skip element if the key is not a string or if the value is not a table */
7095 goto next_hdr;
7096 }
7097
7098 n = lua_tolstring(L, -2, &nlen);
7099 name = ist2(n, nlen);
7100
7101 /* Loop on header's values */
7102 lua_pushnil(L);
7103 while (lua_next(L, -2)) {
7104 if (!lua_isstring(L, -1)) {
7105 /* Skip the value if it is not a string */
7106 goto next_value;
7107 }
7108
7109 v = lua_tolstring(L, -1, &vlen);
7110 value = ist2(v, vlen);
7111 name = ist2(n, nlen);
7112
7113 hdrs[hdr_num].n = istdup(name);
7114 hdrs[hdr_num].v = istdup(value);
7115
7116 hdr_num++;
7117
7118 next_value:
7119 lua_pop(L, 1);
7120 }
7121
7122 next_hdr:
7123 lua_pop(L, 1);
7124
7125 }
7126
7127 if (hdr_num) {
7128 /* alloc and copy the headers in the httpclient struct */
Tim Duesterhus16cc16d2021-11-06 15:14:45 +01007129 result = calloc((hdr_num + 1), sizeof(*result));
William Lallemand746e6f32021-10-06 10:57:44 +02007130 if (!result)
7131 goto skip_headers;
7132 memcpy(result, hdrs, sizeof(struct http_hdr) * (hdr_num + 1));
7133
7134 result[hdr_num].n = IST_NULL;
7135 result[hdr_num].v = IST_NULL;
7136 }
7137
7138skip_headers:
William Lallemand746e6f32021-10-06 10:57:44 +02007139
7140 return result;
7141}
7142
7143
William Lallemandbd5739e2021-10-28 15:41:38 +02007144/*
7145 * For each yield, checks if there is some data in the httpclient and push them
7146 * in the lua buffer, once the httpclient finished its job, push the result on
7147 * the stack
7148 */
7149__LJMP static int hlua_httpclient_rcv_yield(lua_State *L, int status, lua_KContext ctx)
7150{
7151 struct buffer *tr;
7152 int res;
7153 struct hlua *hlua = hlua_gethlua(L);
7154 struct hlua_httpclient *hlua_hc = hlua_checkhttpclient(L, 1);
7155
7156
7157 tr = get_trash_chunk();
7158
7159 res = httpclient_res_xfer(hlua_hc->hc, tr);
7160 luaL_addlstring(&hlua_hc->b, b_orig(tr), res);
7161
7162 if (!httpclient_data(hlua_hc->hc) && httpclient_ended(hlua_hc->hc)) {
7163
7164 luaL_pushresult(&hlua_hc->b);
7165 lua_settable(L, -3);
7166
7167 lua_pushstring(L, "status");
7168 lua_pushinteger(L, hlua_hc->hc->res.status);
7169 lua_settable(L, -3);
7170
7171
7172 lua_pushstring(L, "reason");
7173 lua_pushlstring(L, hlua_hc->hc->res.reason.ptr, hlua_hc->hc->res.reason.len);
7174 lua_settable(L, -3);
7175
7176 lua_pushstring(L, "headers");
7177 hlua_httpclient_get_headers(L, hlua_hc);
7178 lua_settable(L, -3);
7179
7180 return 1;
7181 }
7182
7183 if (httpclient_data(hlua_hc->hc))
7184 task_wakeup(hlua->task, TASK_WOKEN_MSG);
7185
7186 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_httpclient_rcv_yield, TICK_ETERNITY, 0));
7187
7188 return 0;
7189}
7190
7191/*
7192 * Call this when trying to stream a body during a request
7193 */
7194__LJMP static int hlua_httpclient_snd_yield(lua_State *L, int status, lua_KContext ctx)
7195{
7196 struct hlua *hlua;
7197 struct hlua_httpclient *hlua_hc = hlua_checkhttpclient(L, 1);
7198 const char *body_str = NULL;
7199 int ret;
7200 int end = 0;
7201 size_t buf_len;
7202 size_t to_send = 0;
7203
7204 hlua = hlua_gethlua(L);
7205
7206 if (!hlua || !hlua->task)
7207 WILL_LJMP(luaL_error(L, "The 'get' function is only allowed in "
7208 "'frontend', 'backend' or 'task'"));
7209
7210 ret = lua_getfield(L, -1, "body");
7211 if (ret != LUA_TSTRING)
7212 goto rcv;
7213
7214 body_str = lua_tolstring(L, -1, &buf_len);
7215 lua_pop(L, 1);
7216
Christopher Fauletfc591292022-01-12 14:46:03 +01007217 to_send = buf_len - hlua_hc->sent;
William Lallemandbd5739e2021-10-28 15:41:38 +02007218
7219 if ((hlua_hc->sent + to_send) >= buf_len)
7220 end = 1;
7221
7222 /* the end flag is always set since we are using the whole remaining size */
7223 hlua_hc->sent += httpclient_req_xfer(hlua_hc->hc, ist2(body_str + hlua_hc->sent, to_send), end);
7224
7225 if (buf_len > hlua_hc->sent) {
7226 /* still need to process the buffer */
7227 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_httpclient_snd_yield, TICK_ETERNITY, 0));
7228 } else {
7229 goto rcv;
7230 /* we sent the whole request buffer we can recv */
7231 }
7232 return 0;
7233
7234rcv:
7235
7236 /* we return a "res" object */
7237 lua_newtable(L);
7238
William Lallemandbd5739e2021-10-28 15:41:38 +02007239 lua_pushstring(L, "body");
William Lallemandd1187eb2021-11-02 10:40:06 +01007240 luaL_buffinit(L, &hlua_hc->b);
William Lallemandbd5739e2021-10-28 15:41:38 +02007241
William Lallemand933fe392021-11-04 09:45:58 +01007242 task_wakeup(hlua->task, TASK_WOKEN_MSG);
William Lallemandbd5739e2021-10-28 15:41:38 +02007243 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_httpclient_rcv_yield, TICK_ETERNITY, 0));
7244
7245 return 1;
7246}
William Lallemand746e6f32021-10-06 10:57:44 +02007247
William Lallemand3956c4e2021-09-21 16:25:15 +02007248/*
William Lallemanddc2cc902021-10-26 11:43:26 +02007249 * Send an HTTP request and wait for a response
William Lallemand3956c4e2021-09-21 16:25:15 +02007250 */
7251
William Lallemanddc2cc902021-10-26 11:43:26 +02007252__LJMP static int hlua_httpclient_send(lua_State *L, enum http_meth_t meth)
William Lallemand3956c4e2021-09-21 16:25:15 +02007253{
7254 struct hlua_httpclient *hlua_hc;
William Lallemand746e6f32021-10-06 10:57:44 +02007255 struct http_hdr *hdrs = NULL;
7256 struct http_hdr *hdrs_i = NULL;
William Lallemand3956c4e2021-09-21 16:25:15 +02007257 struct hlua *hlua;
William Lallemand746e6f32021-10-06 10:57:44 +02007258 const char *url_str = NULL;
William Lallemanddec25c32021-10-25 19:48:37 +02007259 const char *body_str = NULL;
William Lallemandbd5739e2021-10-28 15:41:38 +02007260 size_t buf_len;
William Lallemand746e6f32021-10-06 10:57:44 +02007261 int ret;
William Lallemand3956c4e2021-09-21 16:25:15 +02007262
7263 hlua = hlua_gethlua(L);
7264
7265 if (!hlua || !hlua->task)
7266 WILL_LJMP(luaL_error(L, "The 'get' function is only allowed in "
7267 "'frontend', 'backend' or 'task'"));
7268
William Lallemand746e6f32021-10-06 10:57:44 +02007269 if (lua_gettop(L) != 2 || lua_type(L, -1) != LUA_TTABLE)
7270 WILL_LJMP(luaL_error(L, "'get' needs a table as argument"));
7271
William Lallemand4f4f2b72022-02-17 20:00:23 +01007272 hlua_hc = hlua_checkhttpclient(L, 1);
7273
William Lallemand7177a952022-03-03 15:33:12 +01007274 lua_pushnil(L); /* first key */
7275 while (lua_next(L, 2)) {
7276 if (strcmp(lua_tostring(L, -2), "dst") == 0) {
7277 if (httpclient_set_dst(hlua_hc->hc, lua_tostring(L, -1)) < 0)
7278 WILL_LJMP(luaL_error(L, "Can't use the 'dst' argument"));
William Lallemand4f4f2b72022-02-17 20:00:23 +01007279
William Lallemand7177a952022-03-03 15:33:12 +01007280 } else if (strcmp(lua_tostring(L, -2), "url") == 0) {
7281 if (lua_type(L, -1) != LUA_TSTRING)
7282 WILL_LJMP(luaL_error(L, "invalid parameter in 'url', must be a string"));
7283 url_str = lua_tostring(L, -1);
William Lallemand3956c4e2021-09-21 16:25:15 +02007284
William Lallemand7177a952022-03-03 15:33:12 +01007285 } else if (strcmp(lua_tostring(L, -2), "timeout") == 0) {
7286 if (lua_type(L, -1) != LUA_TNUMBER)
7287 WILL_LJMP(luaL_error(L, "invalid parameter in 'timeout', must be a number"));
7288 httpclient_set_timeout(hlua_hc->hc, lua_tointeger(L, -1));
William Lallemandb4a4ef62022-02-23 14:18:16 +01007289
William Lallemand7177a952022-03-03 15:33:12 +01007290 } else if (strcmp(lua_tostring(L, -2), "headers") == 0) {
7291 if (lua_type(L, -1) != LUA_TTABLE)
7292 WILL_LJMP(luaL_error(L, "invalid parameter in 'headers', must be a table"));
7293 hdrs = hlua_httpclient_table_to_hdrs(L);
William Lallemand79416cb2021-09-24 14:51:44 +02007294
William Lallemand7177a952022-03-03 15:33:12 +01007295 } else if (strcmp(lua_tostring(L, -2), "body") == 0) {
7296 if (lua_type(L, -1) != LUA_TSTRING)
7297 WILL_LJMP(luaL_error(L, "invalid parameter in 'body', must be a string"));
7298 body_str = lua_tolstring(L, -1, &buf_len);
William Lallemandbd5739e2021-10-28 15:41:38 +02007299
William Lallemand7177a952022-03-03 15:33:12 +01007300 } else {
7301 WILL_LJMP(luaL_error(L, "'%s' invalid parameter name", lua_tostring(L, -2)));
7302 }
7303 /* removes 'value'; keeps 'key' for next iteration */
7304 lua_pop(L, 1);
7305 }
William Lallemanddec25c32021-10-25 19:48:37 +02007306
William Lallemand746e6f32021-10-06 10:57:44 +02007307 if (!url_str) {
7308 WILL_LJMP(luaL_error(L, "'get' need a 'url' argument"));
7309 return 0;
7310 }
William Lallemand3956c4e2021-09-21 16:25:15 +02007311
William Lallemand10a37362022-03-02 16:18:26 +01007312 hlua_hc->sent = 0;
William Lallemand3956c4e2021-09-21 16:25:15 +02007313
7314 hlua_hc->hc->req.url = istdup(ist(url_str));
William Lallemanddc2cc902021-10-26 11:43:26 +02007315 hlua_hc->hc->req.meth = meth;
William Lallemand3956c4e2021-09-21 16:25:15 +02007316
7317 /* update the httpclient callbacks */
William Lallemandbd5739e2021-10-28 15:41:38 +02007318 hlua_hc->hc->ops.res_stline = hlua_httpclient_cb;
7319 hlua_hc->hc->ops.res_headers = hlua_httpclient_cb;
7320 hlua_hc->hc->ops.res_payload = hlua_httpclient_cb;
William Lallemand8f170c72022-03-15 10:52:07 +01007321 hlua_hc->hc->ops.res_end = hlua_httpclient_cb;
William Lallemand3956c4e2021-09-21 16:25:15 +02007322
William Lallemandbd5739e2021-10-28 15:41:38 +02007323 /* a body is available, it will use the request callback */
7324 if (body_str) {
7325 hlua_hc->hc->ops.req_payload = hlua_httpclient_cb;
7326 }
William Lallemand3956c4e2021-09-21 16:25:15 +02007327
William Lallemandbd5739e2021-10-28 15:41:38 +02007328 ret = httpclient_req_gen(hlua_hc->hc, hlua_hc->hc->req.url, meth, hdrs, IST_NULL);
William Lallemand3956c4e2021-09-21 16:25:15 +02007329
William Lallemand746e6f32021-10-06 10:57:44 +02007330 /* free the temporary headers array */
7331 hdrs_i = hdrs;
7332 while (hdrs_i && isttest(hdrs_i->n)) {
7333 istfree(&hdrs_i->n);
7334 istfree(&hdrs_i->v);
7335 hdrs_i++;
7336 }
7337 ha_free(&hdrs);
7338
7339
William Lallemand6137a9e2021-10-26 15:01:53 +02007340 if (ret != ERR_NONE) {
7341 WILL_LJMP(luaL_error(L, "Can't generate the HTTP request"));
7342 return 0;
7343 }
7344
William Lallemandc2d3db42022-04-26 11:46:13 +02007345 if (!httpclient_start(hlua_hc->hc))
7346 WILL_LJMP(luaL_error(L, "couldn't start the httpclient"));
William Lallemand6137a9e2021-10-26 15:01:53 +02007347
William Lallemandbd5739e2021-10-28 15:41:38 +02007348 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_httpclient_snd_yield, TICK_ETERNITY, 0));
William Lallemand3956c4e2021-09-21 16:25:15 +02007349
William Lallemand3956c4e2021-09-21 16:25:15 +02007350 return 0;
7351}
7352
7353/*
William Lallemanddc2cc902021-10-26 11:43:26 +02007354 * Sends an HTTP HEAD request and wait for a response
7355 *
7356 * httpclient:head(url, headers, payload)
7357 */
7358__LJMP static int hlua_httpclient_head(lua_State *L)
7359{
7360 return hlua_httpclient_send(L, HTTP_METH_HEAD);
7361}
7362
7363/*
7364 * Send an HTTP GET request and wait for a response
7365 *
7366 * httpclient:get(url, headers, payload)
7367 */
7368__LJMP static int hlua_httpclient_get(lua_State *L)
7369{
7370 return hlua_httpclient_send(L, HTTP_METH_GET);
7371
7372}
7373
7374/*
7375 * Sends an HTTP PUT request and wait for a response
7376 *
7377 * httpclient:put(url, headers, payload)
7378 */
7379__LJMP static int hlua_httpclient_put(lua_State *L)
7380{
7381 return hlua_httpclient_send(L, HTTP_METH_PUT);
7382}
7383
7384/*
7385 * Send an HTTP POST request and wait for a response
7386 *
7387 * httpclient:post(url, headers, payload)
7388 */
7389__LJMP static int hlua_httpclient_post(lua_State *L)
7390{
7391 return hlua_httpclient_send(L, HTTP_METH_POST);
7392}
7393
7394
7395/*
7396 * Sends an HTTP DELETE request and wait for a response
7397 *
7398 * httpclient:delete(url, headers, payload)
7399 */
7400__LJMP static int hlua_httpclient_delete(lua_State *L)
7401{
7402 return hlua_httpclient_send(L, HTTP_METH_DELETE);
7403}
7404
7405/*
William Lallemand3956c4e2021-09-21 16:25:15 +02007406 *
7407 *
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007408 * Class TXN
7409 *
7410 *
7411 */
7412
7413/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02007414 * a class stream, otherwise it throws an error.
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007415 */
7416__LJMP static struct hlua_txn *hlua_checktxn(lua_State *L, int ud)
7417{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02007418 return MAY_LJMP(hlua_checkudata(L, ud, class_txn_ref));
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007419}
7420
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007421__LJMP static int hlua_set_var(lua_State *L)
7422{
7423 struct hlua_txn *htxn;
7424 const char *name;
7425 size_t len;
7426 struct sample smp;
7427
Tim Duesterhus4e172c92020-05-19 13:49:42 +02007428 if (lua_gettop(L) < 3 || lua_gettop(L) > 4)
7429 WILL_LJMP(luaL_error(L, "'set_var' needs between 3 and 4 arguments"));
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007430
7431 /* It is useles to retrieve the stream, but this function
7432 * runs only in a stream context.
7433 */
7434 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7435 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
7436
7437 /* Converts the third argument in a sample. */
Amaury Denoyellebc0af6a2020-10-29 17:21:20 +01007438 memset(&smp, 0, sizeof(smp));
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007439 hlua_lua2smp(L, 3, &smp);
7440
7441 /* Store the sample in a variable. */
Willy Tarreau7560dd42016-03-10 16:28:58 +01007442 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
Tim Duesterhus4e172c92020-05-19 13:49:42 +02007443
7444 if (lua_gettop(L) == 4 && lua_toboolean(L, 4))
7445 lua_pushboolean(L, vars_set_by_name_ifexist(name, len, &smp) != 0);
7446 else
7447 lua_pushboolean(L, vars_set_by_name(name, len, &smp) != 0);
7448
Tim Duesterhus84ebc132020-05-19 13:49:41 +02007449 return 1;
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007450}
7451
Christopher Faulet85d79c92016-11-09 16:54:56 +01007452__LJMP static int hlua_unset_var(lua_State *L)
7453{
7454 struct hlua_txn *htxn;
7455 const char *name;
7456 size_t len;
7457 struct sample smp;
7458
7459 MAY_LJMP(check_args(L, 2, "unset_var"));
7460
7461 /* It is useles to retrieve the stream, but this function
7462 * runs only in a stream context.
7463 */
7464 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7465 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
7466
7467 /* Unset the variable. */
7468 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
Tim Duesterhus84ebc132020-05-19 13:49:41 +02007469 lua_pushboolean(L, vars_unset_by_name_ifexist(name, len, &smp) != 0);
7470 return 1;
Christopher Faulet85d79c92016-11-09 16:54:56 +01007471}
7472
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007473__LJMP static int hlua_get_var(lua_State *L)
7474{
7475 struct hlua_txn *htxn;
7476 const char *name;
7477 size_t len;
7478 struct sample smp;
7479
7480 MAY_LJMP(check_args(L, 2, "get_var"));
7481
7482 /* It is useles to retrieve the stream, but this function
7483 * runs only in a stream context.
7484 */
7485 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7486 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
7487
Willy Tarreau7560dd42016-03-10 16:28:58 +01007488 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
Willy Tarreaue352b9d2021-09-03 11:52:38 +02007489 if (!vars_get_by_name(name, len, &smp, NULL)) {
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007490 lua_pushnil(L);
7491 return 1;
7492 }
7493
7494 return hlua_smp2lua(L, &smp);
7495}
7496
Willy Tarreau59551662015-03-10 14:23:13 +01007497__LJMP static int hlua_set_priv(lua_State *L)
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007498{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007499 struct hlua *hlua;
7500
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007501 MAY_LJMP(check_args(L, 2, "set_priv"));
7502
Willy Tarreau87b09662015-04-03 00:22:06 +02007503 /* It is useles to retrieve the stream, but this function
7504 * runs only in a stream context.
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007505 */
7506 MAY_LJMP(hlua_checktxn(L, 1));
Thierry Fournier4234dbd2020-11-28 13:18:23 +01007507
7508 /* Get hlua struct, or NULL if we execute from main lua state */
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007509 hlua = hlua_gethlua(L);
Thierry Fournier4234dbd2020-11-28 13:18:23 +01007510 if (!hlua)
7511 return 0;
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007512
7513 /* Remove previous value. */
Thierry FOURNIERe068b602017-04-26 13:27:05 +02007514 luaL_unref(L, LUA_REGISTRYINDEX, hlua->Mref);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007515
7516 /* Get and store new value. */
7517 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
7518 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
7519
7520 return 0;
7521}
7522
Willy Tarreau59551662015-03-10 14:23:13 +01007523__LJMP static int hlua_get_priv(lua_State *L)
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007524{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007525 struct hlua *hlua;
7526
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007527 MAY_LJMP(check_args(L, 1, "get_priv"));
7528
Willy Tarreau87b09662015-04-03 00:22:06 +02007529 /* It is useles to retrieve the stream, but this function
7530 * runs only in a stream context.
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007531 */
7532 MAY_LJMP(hlua_checktxn(L, 1));
Thierry Fournier4234dbd2020-11-28 13:18:23 +01007533
7534 /* Get hlua struct, or NULL if we execute from main lua state */
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007535 hlua = hlua_gethlua(L);
Thierry Fournier4234dbd2020-11-28 13:18:23 +01007536 if (!hlua) {
7537 lua_pushnil(L);
7538 return 1;
7539 }
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007540
7541 /* Push configuration index in the stack. */
7542 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
7543
7544 return 1;
7545}
7546
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007547/* Create stack entry containing a class TXN. This function
7548 * return 0 if the stack does not contains free slots,
7549 * otherwise it returns 1.
7550 */
Thierry FOURNIERab00df62016-07-14 11:42:37 +02007551static int hlua_txn_new(lua_State *L, struct stream *s, struct proxy *p, int dir, int flags)
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007552{
Willy Tarreaude491382015-04-06 11:04:28 +02007553 struct hlua_txn *htxn;
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007554
7555 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01007556 if (!lua_checkstack(L, 3))
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007557 return 0;
7558
7559 /* NOTE: The allocation never fails. The failure
7560 * throw an error, and the function never returns.
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08007561 * if the throw is not available, the process is aborted.
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007562 */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01007563 /* Create the object: obj[0] = userdata. */
7564 lua_newtable(L);
Willy Tarreaude491382015-04-06 11:04:28 +02007565 htxn = lua_newuserdata(L, sizeof(*htxn));
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01007566 lua_rawseti(L, -2, 0);
7567
Willy Tarreaude491382015-04-06 11:04:28 +02007568 htxn->s = s;
7569 htxn->p = p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01007570 htxn->dir = dir;
Thierry FOURNIERab00df62016-07-14 11:42:37 +02007571 htxn->flags = flags;
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007572
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01007573 /* Create the "f" field that contains a list of fetches. */
7574 lua_pushstring(L, "f");
Thierry FOURNIERca988662015-12-20 18:43:03 +01007575 if (!hlua_fetches_new(L, htxn, HLUA_F_MAY_USE_HTTP))
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01007576 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007577 lua_rawset(L, -3);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01007578
7579 /* Create the "sf" field that contains a list of stringsafe fetches. */
7580 lua_pushstring(L, "sf");
Thierry FOURNIERca988662015-12-20 18:43:03 +01007581 if (!hlua_fetches_new(L, htxn, HLUA_F_MAY_USE_HTTP | HLUA_F_AS_STRING))
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01007582 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007583 lua_rawset(L, -3);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01007584
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007585 /* Create the "c" field that contains a list of converters. */
7586 lua_pushstring(L, "c");
Willy Tarreaude491382015-04-06 11:04:28 +02007587 if (!hlua_converters_new(L, htxn, 0))
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01007588 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007589 lua_rawset(L, -3);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01007590
7591 /* Create the "sc" field that contains a list of stringsafe converters. */
7592 lua_pushstring(L, "sc");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01007593 if (!hlua_converters_new(L, htxn, HLUA_F_AS_STRING))
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007594 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007595 lua_rawset(L, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007596
Thierry FOURNIER397826a2015-03-11 19:39:09 +01007597 /* Create the "req" field that contains the request channel object. */
7598 lua_pushstring(L, "req");
Willy Tarreau2a71af42015-03-10 13:51:50 +01007599 if (!hlua_channel_new(L, &s->req))
Thierry FOURNIER397826a2015-03-11 19:39:09 +01007600 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007601 lua_rawset(L, -3);
Thierry FOURNIER397826a2015-03-11 19:39:09 +01007602
7603 /* Create the "res" field that contains the response channel object. */
7604 lua_pushstring(L, "res");
Willy Tarreau2a71af42015-03-10 13:51:50 +01007605 if (!hlua_channel_new(L, &s->res))
Thierry FOURNIER397826a2015-03-11 19:39:09 +01007606 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007607 lua_rawset(L, -3);
Thierry FOURNIER397826a2015-03-11 19:39:09 +01007608
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007609 /* Creates the HTTP object is the current proxy allows http. */
7610 lua_pushstring(L, "http");
Christopher Faulet1bb6afa2021-03-08 17:57:53 +01007611 if (IS_HTX_STRM(s)) {
Willy Tarreaude491382015-04-06 11:04:28 +02007612 if (!hlua_http_new(L, htxn))
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007613 return 0;
7614 }
7615 else
7616 lua_pushnil(L);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007617 lua_rawset(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007618
Christopher Faulet78c35472020-02-26 17:14:08 +01007619 if ((htxn->flags & HLUA_TXN_CTX_MASK) == HLUA_TXN_FLT_CTX) {
7620 /* HTTPMessage object are created when a lua TXN is created from
7621 * a filter context only
7622 */
7623
7624 /* Creates the HTTP-Request object is the current proxy allows http. */
7625 lua_pushstring(L, "http_req");
7626 if (p->mode == PR_MODE_HTTP) {
7627 if (!hlua_http_msg_new(L, &s->txn->req))
7628 return 0;
7629 }
7630 else
7631 lua_pushnil(L);
7632 lua_rawset(L, -3);
7633
7634 /* Creates the HTTP-Response object is the current proxy allows http. */
7635 lua_pushstring(L, "http_res");
7636 if (p->mode == PR_MODE_HTTP) {
7637 if (!hlua_http_msg_new(L, &s->txn->rsp))
7638 return 0;
7639 }
7640 else
7641 lua_pushnil(L);
7642 lua_rawset(L, -3);
7643 }
7644
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007645 /* Pop a class sesison metatable and affect it to the userdata. */
7646 lua_rawgeti(L, LUA_REGISTRYINDEX, class_txn_ref);
7647 lua_setmetatable(L, -2);
7648
7649 return 1;
7650}
7651
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01007652__LJMP static int hlua_txn_deflog(lua_State *L)
7653{
7654 const char *msg;
7655 struct hlua_txn *htxn;
7656
7657 MAY_LJMP(check_args(L, 2, "deflog"));
7658 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7659 msg = MAY_LJMP(luaL_checkstring(L, 2));
7660
7661 hlua_sendlog(htxn->s->be, htxn->s->logs.level, msg);
7662 return 0;
7663}
7664
7665__LJMP static int hlua_txn_log(lua_State *L)
7666{
7667 int level;
7668 const char *msg;
7669 struct hlua_txn *htxn;
7670
7671 MAY_LJMP(check_args(L, 3, "log"));
7672 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7673 level = MAY_LJMP(luaL_checkinteger(L, 2));
7674 msg = MAY_LJMP(luaL_checkstring(L, 3));
7675
7676 if (level < 0 || level >= NB_LOG_LEVELS)
7677 WILL_LJMP(luaL_argerror(L, 1, "Invalid loglevel."));
7678
7679 hlua_sendlog(htxn->s->be, level, msg);
7680 return 0;
7681}
7682
7683__LJMP static int hlua_txn_log_debug(lua_State *L)
7684{
7685 const char *msg;
7686 struct hlua_txn *htxn;
7687
7688 MAY_LJMP(check_args(L, 2, "Debug"));
7689 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7690 msg = MAY_LJMP(luaL_checkstring(L, 2));
7691 hlua_sendlog(htxn->s->be, LOG_DEBUG, msg);
7692 return 0;
7693}
7694
7695__LJMP static int hlua_txn_log_info(lua_State *L)
7696{
7697 const char *msg;
7698 struct hlua_txn *htxn;
7699
7700 MAY_LJMP(check_args(L, 2, "Info"));
7701 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7702 msg = MAY_LJMP(luaL_checkstring(L, 2));
7703 hlua_sendlog(htxn->s->be, LOG_INFO, msg);
7704 return 0;
7705}
7706
7707__LJMP static int hlua_txn_log_warning(lua_State *L)
7708{
7709 const char *msg;
7710 struct hlua_txn *htxn;
7711
7712 MAY_LJMP(check_args(L, 2, "Warning"));
7713 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7714 msg = MAY_LJMP(luaL_checkstring(L, 2));
7715 hlua_sendlog(htxn->s->be, LOG_WARNING, msg);
7716 return 0;
7717}
7718
7719__LJMP static int hlua_txn_log_alert(lua_State *L)
7720{
7721 const char *msg;
7722 struct hlua_txn *htxn;
7723
7724 MAY_LJMP(check_args(L, 2, "Alert"));
7725 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7726 msg = MAY_LJMP(luaL_checkstring(L, 2));
7727 hlua_sendlog(htxn->s->be, LOG_ALERT, msg);
7728 return 0;
7729}
7730
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01007731__LJMP static int hlua_txn_set_loglevel(lua_State *L)
7732{
7733 struct hlua_txn *htxn;
7734 int ll;
7735
7736 MAY_LJMP(check_args(L, 2, "set_loglevel"));
7737 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7738 ll = MAY_LJMP(luaL_checkinteger(L, 2));
7739
7740 if (ll < 0 || ll > 7)
7741 WILL_LJMP(luaL_argerror(L, 2, "Bad log level. It must be between 0 and 7"));
7742
7743 htxn->s->logs.level = ll;
7744 return 0;
7745}
7746
7747__LJMP static int hlua_txn_set_tos(lua_State *L)
7748{
7749 struct hlua_txn *htxn;
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01007750 int tos;
7751
7752 MAY_LJMP(check_args(L, 2, "set_tos"));
7753 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7754 tos = MAY_LJMP(luaL_checkinteger(L, 2));
7755
Willy Tarreau1a18b542018-12-11 16:37:42 +01007756 conn_set_tos(objt_conn(htxn->s->sess->origin), tos);
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01007757 return 0;
7758}
7759
7760__LJMP static int hlua_txn_set_mark(lua_State *L)
7761{
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01007762 struct hlua_txn *htxn;
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01007763 int mark;
7764
7765 MAY_LJMP(check_args(L, 2, "set_mark"));
7766 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7767 mark = MAY_LJMP(luaL_checkinteger(L, 2));
7768
Lukas Tribus579e3e32019-08-11 18:03:45 +02007769 conn_set_mark(objt_conn(htxn->s->sess->origin), mark);
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01007770 return 0;
7771}
7772
Patrick Hemmer268a7072018-05-11 12:52:31 -04007773__LJMP static int hlua_txn_set_priority_class(lua_State *L)
7774{
7775 struct hlua_txn *htxn;
7776
7777 MAY_LJMP(check_args(L, 2, "set_priority_class"));
7778 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7779 htxn->s->priority_class = queue_limit_class(MAY_LJMP(luaL_checkinteger(L, 2)));
7780 return 0;
7781}
7782
7783__LJMP static int hlua_txn_set_priority_offset(lua_State *L)
7784{
7785 struct hlua_txn *htxn;
7786
7787 MAY_LJMP(check_args(L, 2, "set_priority_offset"));
7788 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7789 htxn->s->priority_offset = queue_limit_offset(MAY_LJMP(luaL_checkinteger(L, 2)));
7790 return 0;
7791}
7792
Christopher Faulet700d9e82020-01-31 12:21:52 +01007793/* Forward the Reply object to the client. This function converts the reply in
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05007794 * HTX an push it to into the response channel. It is response to forward the
Christopher Faulet700d9e82020-01-31 12:21:52 +01007795 * message and terminate the transaction. It returns 1 on success and 0 on
7796 * error. The Reply must be on top of the stack.
7797 */
7798__LJMP static int hlua_txn_forward_reply(lua_State *L, struct stream *s)
7799{
7800 struct htx *htx;
7801 struct htx_sl *sl;
7802 struct h1m h1m;
7803 const char *status, *reason, *body;
7804 size_t status_len, reason_len, body_len;
7805 int ret, code, flags;
7806
7807 code = 200;
7808 status = "200";
7809 status_len = 3;
7810 ret = lua_getfield(L, -1, "status");
7811 if (ret == LUA_TNUMBER) {
7812 code = lua_tointeger(L, -1);
7813 status = lua_tolstring(L, -1, &status_len);
7814 }
7815 lua_pop(L, 1);
7816
7817 reason = http_get_reason(code);
7818 reason_len = strlen(reason);
7819 ret = lua_getfield(L, -1, "reason");
7820 if (ret == LUA_TSTRING)
7821 reason = lua_tolstring(L, -1, &reason_len);
7822 lua_pop(L, 1);
7823
7824 body = NULL;
7825 body_len = 0;
7826 ret = lua_getfield(L, -1, "body");
7827 if (ret == LUA_TSTRING)
7828 body = lua_tolstring(L, -1, &body_len);
7829 lua_pop(L, 1);
7830
7831 /* Prepare the response before inserting the headers */
7832 h1m_init_res(&h1m);
7833 htx = htx_from_buf(&s->res.buf);
7834 channel_htx_truncate(&s->res, htx);
7835 if (s->txn->req.flags & HTTP_MSGF_VER_11) {
7836 flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11);
7837 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.1"),
7838 ist2(status, status_len), ist2(reason, reason_len));
7839 }
7840 else {
7841 flags = HTX_SL_F_IS_RESP;
7842 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.0"),
7843 ist2(status, status_len), ist2(reason, reason_len));
7844 }
7845 if (!sl)
7846 goto fail;
7847 sl->info.res.status = code;
7848
7849 /* Push in the stack the "headers" entry. */
7850 ret = lua_getfield(L, -1, "headers");
7851 if (ret != LUA_TTABLE)
7852 goto skip_headers;
7853
7854 lua_pushnil(L);
7855 while (lua_next(L, -2) != 0) {
7856 struct ist name, value;
7857 const char *n, *v;
7858 size_t nlen, vlen;
7859
7860 if (!lua_isstring(L, -2) || !lua_istable(L, -1)) {
7861 /* Skip element if the key is not a string or if the value is not a table */
7862 goto next_hdr;
7863 }
7864
7865 n = lua_tolstring(L, -2, &nlen);
7866 name = ist2(n, nlen);
7867 if (isteqi(name, ist("content-length"))) {
7868 /* Always skip content-length header. It will be added
7869 * later with the correct len
7870 */
7871 goto next_hdr;
7872 }
7873
7874 /* Loop on header's values */
7875 lua_pushnil(L);
7876 while (lua_next(L, -2)) {
7877 if (!lua_isstring(L, -1)) {
7878 /* Skip the value if it is not a string */
7879 goto next_value;
7880 }
7881
7882 v = lua_tolstring(L, -1, &vlen);
7883 value = ist2(v, vlen);
7884
7885 if (isteqi(name, ist("transfer-encoding")))
7886 h1_parse_xfer_enc_header(&h1m, value);
7887 if (!htx_add_header(htx, ist2(n, nlen), ist2(v, vlen)))
7888 goto fail;
7889
7890 next_value:
7891 lua_pop(L, 1);
7892 }
7893
7894 next_hdr:
7895 lua_pop(L, 1);
7896 }
7897 skip_headers:
7898 lua_pop(L, 1);
7899
7900 /* Update h1m flags: CLEN is set if CHNK is not present */
7901 if (!(h1m.flags & H1_MF_CHNK)) {
7902 const char *clen = ultoa(body_len);
7903
7904 h1m.flags |= H1_MF_CLEN;
7905 if (!htx_add_header(htx, ist("content-length"), ist(clen)))
7906 goto fail;
7907 }
7908 if (h1m.flags & (H1_MF_CLEN|H1_MF_CHNK))
7909 h1m.flags |= H1_MF_XFER_LEN;
7910
7911 /* Update HTX start-line flags */
7912 if (h1m.flags & H1_MF_XFER_ENC)
7913 flags |= HTX_SL_F_XFER_ENC;
7914 if (h1m.flags & H1_MF_XFER_LEN) {
7915 flags |= HTX_SL_F_XFER_LEN;
7916 if (h1m.flags & H1_MF_CHNK)
7917 flags |= HTX_SL_F_CHNK;
7918 else if (h1m.flags & H1_MF_CLEN)
7919 flags |= HTX_SL_F_CLEN;
7920 if (h1m.body_len == 0)
7921 flags |= HTX_SL_F_BODYLESS;
7922 }
7923 sl->flags |= flags;
7924
7925
7926 if (!htx_add_endof(htx, HTX_BLK_EOH) ||
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01007927 (body_len && !htx_add_data_atonce(htx, ist2(body, body_len))))
Christopher Faulet700d9e82020-01-31 12:21:52 +01007928 goto fail;
7929
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01007930 htx->flags |= HTX_FL_EOM;
7931
Christopher Faulet700d9e82020-01-31 12:21:52 +01007932 /* Now, forward the response and terminate the transaction */
7933 s->txn->status = code;
7934 htx_to_buf(htx, &s->res.buf);
7935 if (!http_forward_proxy_resp(s, 1))
7936 goto fail;
7937
7938 return 1;
7939
7940 fail:
7941 channel_htx_truncate(&s->res, htx);
7942 return 0;
7943}
7944
7945/* Terminate a transaction if called from a lua action. For TCP streams,
7946 * processing is just aborted. Nothing is returned to the client and all
7947 * arguments are ignored. For HTTP streams, if a reply is passed as argument, it
7948 * is forwarded to the client before terminating the transaction. On success,
7949 * the function exits with ACT_RET_DONE code. If an error occurred, it exits
7950 * with ACT_RET_ERR code. If this function is not called from a lua action, it
7951 * just exits without any processing.
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01007952 */
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02007953__LJMP static int hlua_txn_done(lua_State *L)
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01007954{
Willy Tarreaub2ccb562015-04-06 11:11:15 +02007955 struct hlua_txn *htxn;
Christopher Faulet700d9e82020-01-31 12:21:52 +01007956 struct stream *s;
7957 int finst;
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01007958
Willy Tarreaub2ccb562015-04-06 11:11:15 +02007959 htxn = MAY_LJMP(hlua_checktxn(L, 1));
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01007960
Christopher Faulet700d9e82020-01-31 12:21:52 +01007961 /* If the flags NOTERM is set, we cannot terminate the session, so we
7962 * just end the execution of the current lua code. */
7963 if (htxn->flags & HLUA_TXN_NOTERM)
Thierry FOURNIERab00df62016-07-14 11:42:37 +02007964 WILL_LJMP(hlua_done(L));
Thierry FOURNIERab00df62016-07-14 11:42:37 +02007965
Christopher Faulet700d9e82020-01-31 12:21:52 +01007966 s = htxn->s;
Christopher Fauletd8f0e072020-02-25 09:45:51 +01007967 if (!IS_HTX_STRM(htxn->s)) {
Christopher Faulet700d9e82020-01-31 12:21:52 +01007968 struct channel *req = &s->req;
7969 struct channel *res = &s->res;
Willy Tarreau81389672015-03-10 12:03:52 +01007970
Christopher Faulet700d9e82020-01-31 12:21:52 +01007971 channel_auto_read(req);
7972 channel_abort(req);
7973 channel_auto_close(req);
7974 channel_erase(req);
7975
7976 res->wex = tick_add_ifset(now_ms, res->wto);
7977 channel_auto_read(res);
7978 channel_auto_close(res);
7979 channel_shutr_now(res);
7980
7981 finst = ((htxn->dir == SMP_OPT_DIR_REQ) ? SF_FINST_R : SF_FINST_D);
7982 goto done;
Christopher Fauletfe6a71b2019-07-26 16:40:24 +02007983 }
Thierry FOURNIER10ec2142015-08-24 17:23:45 +02007984
Christopher Faulet700d9e82020-01-31 12:21:52 +01007985 if (lua_gettop(L) == 1 || !lua_istable(L, 2)) {
7986 /* No reply or invalid reply */
7987 s->txn->status = 0;
7988 http_reply_and_close(s, 0, NULL);
7989 }
7990 else {
7991 /* Remove extra args to have the reply on top of the stack */
7992 if (lua_gettop(L) > 2)
7993 lua_pop(L, lua_gettop(L) - 2);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01007994
Christopher Faulet700d9e82020-01-31 12:21:52 +01007995 if (!hlua_txn_forward_reply(L, s)) {
7996 if (!(s->flags & SF_ERR_MASK))
7997 s->flags |= SF_ERR_PRXCOND;
7998 lua_pushinteger(L, ACT_RET_ERR);
7999 WILL_LJMP(hlua_done(L));
8000 return 0; /* Never reached */
8001 }
Christopher Faulet4d0e2632019-07-16 10:52:40 +02008002 }
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02008003
Christopher Faulet700d9e82020-01-31 12:21:52 +01008004 finst = ((htxn->dir == SMP_OPT_DIR_REQ) ? SF_FINST_R : SF_FINST_H);
8005 if (htxn->dir == SMP_OPT_DIR_REQ) {
8006 /* let's log the request time */
8007 s->logs.tv_request = now;
8008 if (s->sess->fe == s->be) /* report it if the request was intercepted by the frontend */
Willy Tarreau4781b152021-04-06 13:53:36 +02008009 _HA_ATOMIC_INC(&s->sess->fe->fe_counters.intercepted_req);
Christopher Faulet700d9e82020-01-31 12:21:52 +01008010 }
Christopher Fauletfe6a71b2019-07-26 16:40:24 +02008011
Christopher Faulet700d9e82020-01-31 12:21:52 +01008012 done:
8013 if (!(s->flags & SF_ERR_MASK))
8014 s->flags |= SF_ERR_LOCAL;
8015 if (!(s->flags & SF_FINST_MASK))
8016 s->flags |= finst;
Christopher Fauletfe6a71b2019-07-26 16:40:24 +02008017
Christopher Faulete48d1dc2021-08-13 14:11:17 +02008018 if ((htxn->flags & HLUA_TXN_CTX_MASK) == HLUA_TXN_FLT_CTX)
8019 lua_pushinteger(L, -1);
8020 else
8021 lua_pushinteger(L, ACT_RET_ABRT);
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02008022 WILL_LJMP(hlua_done(L));
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01008023 return 0;
8024}
8025
Christopher Faulet700d9e82020-01-31 12:21:52 +01008026/*
8027 *
8028 *
8029 * Class REPLY
8030 *
8031 *
8032 */
8033
8034/* Pushes the TXN reply onto the top of the stack. If the stask does not have a
8035 * free slots, the function fails and returns 0;
8036 */
8037static int hlua_txn_reply_new(lua_State *L)
8038{
8039 struct hlua_txn *htxn;
8040 const char *reason, *body = NULL;
8041 int ret, status;
8042
8043 htxn = MAY_LJMP(hlua_checktxn(L, 1));
Christopher Fauletd8f0e072020-02-25 09:45:51 +01008044 if (!IS_HTX_STRM(htxn->s)) {
Christopher Faulet700d9e82020-01-31 12:21:52 +01008045 hlua_pusherror(L, "txn object is not an HTTP transaction.");
8046 WILL_LJMP(lua_error(L));
8047 }
8048
8049 /* Default value */
8050 status = 200;
8051 reason = http_get_reason(status);
8052
8053 if (lua_istable(L, 2)) {
8054 /* load status and reason from the table argument at index 2 */
8055 ret = lua_getfield(L, 2, "status");
8056 if (ret == LUA_TNIL)
8057 goto reason;
8058 else if (ret != LUA_TNUMBER) {
8059 /* invalid status: ignore the reason */
8060 goto body;
8061 }
8062 status = lua_tointeger(L, -1);
8063
8064 reason:
8065 lua_pop(L, 1); /* restore the stack: remove status */
8066 ret = lua_getfield(L, 2, "reason");
8067 if (ret == LUA_TSTRING)
8068 reason = lua_tostring(L, -1);
8069
8070 body:
8071 lua_pop(L, 1); /* restore the stack: remove invalid status or reason */
8072 ret = lua_getfield(L, 2, "body");
8073 if (ret == LUA_TSTRING)
8074 body = lua_tostring(L, -1);
8075 lua_pop(L, 1); /* restore the stack: remove body */
8076 }
8077
8078 /* Create the Reply table */
8079 lua_newtable(L);
8080
8081 /* Add status element */
8082 lua_pushstring(L, "status");
8083 lua_pushinteger(L, status);
8084 lua_settable(L, -3);
8085
8086 /* Add reason element */
8087 reason = http_get_reason(status);
8088 lua_pushstring(L, "reason");
8089 lua_pushstring(L, reason);
8090 lua_settable(L, -3);
8091
8092 /* Add body element, nil if undefined */
8093 lua_pushstring(L, "body");
8094 if (body)
8095 lua_pushstring(L, body);
8096 else
8097 lua_pushnil(L);
8098 lua_settable(L, -3);
8099
8100 /* Add headers element */
8101 lua_pushstring(L, "headers");
8102 lua_newtable(L);
8103
8104 /* stack: [ txn, <Arg:table>, <Reply:table>, "headers", <headers:table> ] */
8105 if (lua_istable(L, 2)) {
8106 /* load headers from the table argument at index 2. If it is a table, copy it. */
8107 ret = lua_getfield(L, 2, "headers");
8108 if (ret == LUA_TTABLE) {
8109 /* stack: [ ... <headers:table>, <table> ] */
8110 lua_pushnil(L);
8111 while (lua_next(L, -2) != 0) {
8112 /* stack: [ ... <headers:table>, <table>, k, v] */
8113 if (!lua_isstring(L, -1) && !lua_istable(L, -1)) {
8114 /* invalid value type, skip it */
8115 lua_pop(L, 1);
8116 continue;
8117 }
8118
8119
8120 /* Duplicate the key and swap it with the value. */
8121 lua_pushvalue(L, -2);
8122 lua_insert(L, -2);
8123 /* stack: [ ... <headers:table>, <table>, k, k, v ] */
8124
8125 lua_newtable(L);
8126 lua_insert(L, -2);
8127 /* stack: [ ... <headers:table>, <table>, k, k, <inner:table>, v ] */
8128
8129 if (lua_isstring(L, -1)) {
8130 /* push the value in the inner table */
8131 lua_rawseti(L, -2, 1);
8132 }
8133 else { /* table */
8134 lua_pushnil(L);
8135 while (lua_next(L, -2) != 0) {
8136 /* stack: [ ... <headers:table>, <table>, k, k, <inner:table>, <v:table>, k2, v2 ] */
8137 if (!lua_isstring(L, -1)) {
8138 /* invalid value type, skip it*/
8139 lua_pop(L, 1);
8140 continue;
8141 }
8142 /* push the value in the inner table */
8143 lua_rawseti(L, -4, lua_rawlen(L, -4) + 1);
8144 /* stack: [ ... <headers:table>, <table>, k, k, <inner:table>, <v:table>, k2 ] */
8145 }
8146 lua_pop(L, 1);
8147 /* stack: [ ... <headers:table>, <table>, k, k, <inner:table> ] */
8148 }
8149
8150 /* push (k,v) on the stack in the headers table:
8151 * stack: [ ... <headers:table>, <table>, k, k, v ]
8152 */
8153 lua_settable(L, -5);
8154 /* stack: [ ... <headers:table>, <table>, k ] */
8155 }
8156 }
8157 lua_pop(L, 1);
8158 }
8159 /* stack: [ txn, <Arg:table>, <Reply:table>, "headers", <headers:table> ] */
8160 lua_settable(L, -3);
8161 /* stack: [ txn, <Arg:table>, <Reply:table> ] */
8162
8163 /* Pop a class sesison metatable and affect it to the userdata. */
8164 lua_rawgeti(L, LUA_REGISTRYINDEX, class_txn_reply_ref);
8165 lua_setmetatable(L, -2);
8166 return 1;
8167}
8168
8169/* Set the reply status code, and optionally the reason. If no reason is
8170 * provided, the default one corresponding to the status code is used.
8171 */
8172__LJMP static int hlua_txn_reply_set_status(lua_State *L)
8173{
8174 int status = MAY_LJMP(luaL_checkinteger(L, 2));
8175 const char *reason = MAY_LJMP(luaL_optlstring(L, 3, NULL, NULL));
8176
8177 /* First argument (self) must be a table */
8178 luaL_checktype(L, 1, LUA_TTABLE);
8179
8180 if (status < 100 || status > 599) {
8181 lua_pushboolean(L, 0);
8182 return 1;
8183 }
8184 if (!reason)
8185 reason = http_get_reason(status);
8186
8187 lua_pushinteger(L, status);
8188 lua_setfield(L, 1, "status");
8189
8190 lua_pushstring(L, reason);
8191 lua_setfield(L, 1, "reason");
8192
8193 lua_pushboolean(L, 1);
8194 return 1;
8195}
8196
8197/* Add a header into the reply object. Each header name is associated to an
8198 * array of values in the "headers" table. If the header name is not found, a
8199 * new entry is created.
8200 */
8201__LJMP static int hlua_txn_reply_add_header(lua_State *L)
8202{
8203 const char *name = MAY_LJMP(luaL_checkstring(L, 2));
8204 const char *value = MAY_LJMP(luaL_checkstring(L, 3));
8205 int ret;
8206
8207 /* First argument (self) must be a table */
8208 luaL_checktype(L, 1, LUA_TTABLE);
8209
8210 /* Push in the stack the "headers" entry. */
8211 ret = lua_getfield(L, 1, "headers");
8212 if (ret != LUA_TTABLE) {
8213 hlua_pusherror(L, "Reply['headers'] is expected to a an array. %s found", lua_typename(L, ret));
8214 WILL_LJMP(lua_error(L));
8215 }
8216
8217 /* check if the header is already registered. If not, register it. */
8218 ret = lua_getfield(L, -1, name);
8219 if (ret == LUA_TNIL) {
8220 /* Entry not found. */
8221 lua_pop(L, 1); /* remove the nil. The "headers" table is the top of the stack. */
8222
8223 /* Insert the new header name in the array in the top of the stack.
8224 * It left the new array in the top of the stack.
8225 */
8226 lua_newtable(L);
8227 lua_pushstring(L, name);
8228 lua_pushvalue(L, -2);
8229 lua_settable(L, -4);
8230 }
8231 else if (ret != LUA_TTABLE) {
8232 hlua_pusherror(L, "Reply['headers']['%s'] is expected to be an array. %s found", name, lua_typename(L, ret));
8233 WILL_LJMP(lua_error(L));
8234 }
8235
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -07008236 /* Now the top of thestack is an array of values. We push
Christopher Faulet700d9e82020-01-31 12:21:52 +01008237 * the header value as new entry.
8238 */
8239 lua_pushstring(L, value);
8240 ret = lua_rawlen(L, -2);
8241 lua_rawseti(L, -2, ret + 1);
8242
8243 lua_pushboolean(L, 1);
8244 return 1;
8245}
8246
8247/* Remove all occurrences of a given header name. */
8248__LJMP static int hlua_txn_reply_del_header(lua_State *L)
8249{
8250 const char *name = MAY_LJMP(luaL_checkstring(L, 2));
8251 int ret;
8252
8253 /* First argument (self) must be a table */
8254 luaL_checktype(L, 1, LUA_TTABLE);
8255
8256 /* Push in the stack the "headers" entry. */
8257 ret = lua_getfield(L, 1, "headers");
8258 if (ret != LUA_TTABLE) {
8259 hlua_pusherror(L, "Reply['headers'] is expected to be an array. %s found", lua_typename(L, ret));
8260 WILL_LJMP(lua_error(L));
8261 }
8262
8263 lua_pushstring(L, name);
8264 lua_pushnil(L);
8265 lua_settable(L, -3);
8266
8267 lua_pushboolean(L, 1);
8268 return 1;
8269}
8270
8271/* Set the reply's body. Overwrite any existing entry. */
8272__LJMP static int hlua_txn_reply_set_body(lua_State *L)
8273{
8274 const char *payload = MAY_LJMP(luaL_checkstring(L, 2));
8275
8276 /* First argument (self) must be a table */
8277 luaL_checktype(L, 1, LUA_TTABLE);
8278
8279 lua_pushstring(L, payload);
8280 lua_setfield(L, 1, "body");
8281
8282 lua_pushboolean(L, 1);
8283 return 1;
8284}
8285
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01008286__LJMP static int hlua_log(lua_State *L)
8287{
8288 int level;
8289 const char *msg;
8290
8291 MAY_LJMP(check_args(L, 2, "log"));
8292 level = MAY_LJMP(luaL_checkinteger(L, 1));
8293 msg = MAY_LJMP(luaL_checkstring(L, 2));
8294
8295 if (level < 0 || level >= NB_LOG_LEVELS)
8296 WILL_LJMP(luaL_argerror(L, 1, "Invalid loglevel."));
8297
8298 hlua_sendlog(NULL, level, msg);
8299 return 0;
8300}
8301
8302__LJMP static int hlua_log_debug(lua_State *L)
8303{
8304 const char *msg;
8305
8306 MAY_LJMP(check_args(L, 1, "debug"));
8307 msg = MAY_LJMP(luaL_checkstring(L, 1));
8308 hlua_sendlog(NULL, LOG_DEBUG, msg);
8309 return 0;
8310}
8311
8312__LJMP static int hlua_log_info(lua_State *L)
8313{
8314 const char *msg;
8315
8316 MAY_LJMP(check_args(L, 1, "info"));
8317 msg = MAY_LJMP(luaL_checkstring(L, 1));
8318 hlua_sendlog(NULL, LOG_INFO, msg);
8319 return 0;
8320}
8321
8322__LJMP static int hlua_log_warning(lua_State *L)
8323{
8324 const char *msg;
8325
8326 MAY_LJMP(check_args(L, 1, "warning"));
8327 msg = MAY_LJMP(luaL_checkstring(L, 1));
8328 hlua_sendlog(NULL, LOG_WARNING, msg);
8329 return 0;
8330}
8331
8332__LJMP static int hlua_log_alert(lua_State *L)
8333{
8334 const char *msg;
8335
8336 MAY_LJMP(check_args(L, 1, "alert"));
8337 msg = MAY_LJMP(luaL_checkstring(L, 1));
8338 hlua_sendlog(NULL, LOG_ALERT, msg);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01008339 return 0;
8340}
8341
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01008342__LJMP static int hlua_sleep_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008343{
8344 int wakeup_ms = lua_tointeger(L, -1);
Willy Tarreau12c02702021-09-30 16:12:31 +02008345 if (!tick_is_expired(wakeup_ms, now_ms))
Willy Tarreau9635e032018-10-16 17:52:55 +02008346 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008347 return 0;
8348}
8349
8350__LJMP static int hlua_sleep(lua_State *L)
8351{
8352 unsigned int delay;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008353 unsigned int wakeup_ms;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008354
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008355 MAY_LJMP(check_args(L, 1, "sleep"));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008356
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01008357 delay = MAY_LJMP(luaL_checkinteger(L, 1)) * 1000;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008358 wakeup_ms = tick_add(now_ms, delay);
8359 lua_pushinteger(L, wakeup_ms);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008360
Willy Tarreau9635e032018-10-16 17:52:55 +02008361 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008362 return 0;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008363}
8364
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008365__LJMP static int hlua_msleep(lua_State *L)
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008366{
8367 unsigned int delay;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008368 unsigned int wakeup_ms;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008369
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008370 MAY_LJMP(check_args(L, 1, "msleep"));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008371
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01008372 delay = MAY_LJMP(luaL_checkinteger(L, 1));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008373 wakeup_ms = tick_add(now_ms, delay);
8374 lua_pushinteger(L, wakeup_ms);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008375
Willy Tarreau9635e032018-10-16 17:52:55 +02008376 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008377 return 0;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008378}
8379
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01008380/* This functionis an LUA binding. it permits to give back
8381 * the hand at the HAProxy scheduler. It is used when the
8382 * LUA processing consumes a lot of time.
8383 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01008384__LJMP static int hlua_yield_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008385{
8386 return 0;
8387}
8388
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01008389__LJMP static int hlua_yield(lua_State *L)
8390{
Willy Tarreau9635e032018-10-16 17:52:55 +02008391 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_yield_yield, TICK_ETERNITY, HLUA_CTRLYIELD));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008392 return 0;
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01008393}
8394
Thierry FOURNIER37196f42015-02-16 19:34:56 +01008395/* This function change the nice of the currently executed
8396 * task. It is used set low or high priority at the current
8397 * task.
8398 */
Willy Tarreau59551662015-03-10 14:23:13 +01008399__LJMP static int hlua_set_nice(lua_State *L)
Thierry FOURNIER37196f42015-02-16 19:34:56 +01008400{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01008401 struct hlua *hlua;
8402 int nice;
Thierry FOURNIER37196f42015-02-16 19:34:56 +01008403
Willy Tarreau80f5fae2015-02-27 16:38:20 +01008404 MAY_LJMP(check_args(L, 1, "set_nice"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01008405 nice = MAY_LJMP(luaL_checkinteger(L, 1));
Thierry FOURNIER37196f42015-02-16 19:34:56 +01008406
Thierry Fournier4234dbd2020-11-28 13:18:23 +01008407 /* Get hlua struct, or NULL if we execute from main lua state */
8408 hlua = hlua_gethlua(L);
8409
8410 /* If the task is not set, I'm in a start mode. */
Thierry FOURNIER37196f42015-02-16 19:34:56 +01008411 if (!hlua || !hlua->task)
8412 return 0;
8413
8414 if (nice < -1024)
8415 nice = -1024;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01008416 else if (nice > 1024)
Thierry FOURNIER37196f42015-02-16 19:34:56 +01008417 nice = 1024;
8418
8419 hlua->task->nice = nice;
8420 return 0;
8421}
8422
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08008423/* This function is used as a callback of a task. It is called by the
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008424 * HAProxy task subsystem when the task is awaked. The LUA runtime can
8425 * return an E_AGAIN signal, the emmiter of this signal must set a
8426 * signal to wake the task.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008427 *
8428 * Task wrapper are longjmp safe because the only one Lua code
8429 * executed is the safe hlua_ctx_resume();
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008430 */
Willy Tarreau144f84a2021-03-02 16:09:26 +01008431struct task *hlua_process_task(struct task *task, void *context, unsigned int state)
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008432{
Olivier Houchard9f6af332018-05-25 14:04:04 +02008433 struct hlua *hlua = context;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008434 enum hlua_exec status;
8435
Christopher Faulet5bc99722018-04-25 10:34:45 +02008436 if (task->thread_mask == MAX_THREADS_MASK)
8437 task_set_affinity(task, tid_bit);
8438
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008439 /* If it is the first call to the task, we must initialize the
8440 * execution timeouts.
8441 */
8442 if (!HLUA_IS_RUNNING(hlua))
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02008443 hlua->max_time = hlua_timeout_task;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008444
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008445 /* Execute the Lua code. */
8446 status = hlua_ctx_resume(hlua, 1);
8447
8448 switch (status) {
8449 /* finished or yield */
8450 case HLUA_E_OK:
8451 hlua_ctx_destroy(hlua);
Olivier Houchard3f795f72019-04-17 22:51:06 +02008452 task_destroy(task);
Tim Duesterhuscd235c62018-04-24 13:56:01 +02008453 task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008454 break;
8455
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01008456 case HLUA_E_AGAIN: /* co process or timeout wake me later. */
Thierry FOURNIERcb146882017-12-10 17:10:57 +01008457 notification_gc(&hlua->com);
PiBa-NLfe971b32018-05-02 22:27:14 +02008458 task->expire = hlua->wake_time;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008459 break;
8460
8461 /* finished with error. */
8462 case HLUA_E_ERRMSG:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008463 SEND_ERR(NULL, "Lua task: %s.\n", lua_tostring(hlua->T, -1));
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008464 hlua_ctx_destroy(hlua);
Olivier Houchard3f795f72019-04-17 22:51:06 +02008465 task_destroy(task);
Emeric Brun253e53e2017-10-17 18:58:40 +02008466 task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008467 break;
8468
8469 case HLUA_E_ERR:
8470 default:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008471 SEND_ERR(NULL, "Lua task: unknown error.\n");
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008472 hlua_ctx_destroy(hlua);
Olivier Houchard3f795f72019-04-17 22:51:06 +02008473 task_destroy(task);
Emeric Brun253e53e2017-10-17 18:58:40 +02008474 task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008475 break;
8476 }
Emeric Brun253e53e2017-10-17 18:58:40 +02008477 return task;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008478}
8479
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008480/* This function is an LUA binding that register LUA function to be
8481 * executed after the HAProxy configuration parsing and before the
8482 * HAProxy scheduler starts. This function expect only one LUA
8483 * argument that is a function. This function returns nothing, but
8484 * throws if an error is encountered.
8485 */
8486__LJMP static int hlua_register_init(lua_State *L)
8487{
8488 struct hlua_init_function *init;
8489 int ref;
8490
8491 MAY_LJMP(check_args(L, 1, "register_init"));
8492
8493 ref = MAY_LJMP(hlua_checkfunction(L, 1));
8494
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02008495 init = calloc(1, sizeof(*init));
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008496 if (!init)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01008497 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008498
8499 init->function_ref = ref;
Willy Tarreau2b718102021-04-21 07:32:39 +02008500 LIST_APPEND(&hlua_init_functions[hlua_state_id], &init->l);
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008501 return 0;
8502}
8503
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008504/* This functio is an LUA binding. It permits to register a task
8505 * executed in parallel of the main HAroxy activity. The task is
8506 * created and it is set in the HAProxy scheduler. It can be called
8507 * from the "init" section, "post init" or during the runtime.
8508 *
8509 * Lua prototype:
8510 *
8511 * <none> core.register_task(<function>)
8512 */
8513static int hlua_register_task(lua_State *L)
8514{
Christopher Faulet5294ec02021-04-12 12:24:47 +02008515 struct hlua *hlua = NULL;
8516 struct task *task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008517 int ref;
Thierry Fournier021d9862020-11-28 23:42:03 +01008518 int state_id;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008519
8520 MAY_LJMP(check_args(L, 1, "register_task"));
8521
8522 ref = MAY_LJMP(hlua_checkfunction(L, 1));
8523
Thierry Fournier75fc0292020-11-28 13:18:56 +01008524 /* Get the reference state. If the reference is NULL, L is the master
8525 * state, otherwise hlua->T is.
8526 */
8527 hlua = hlua_gethlua(L);
8528 if (hlua)
Thierry Fournier021d9862020-11-28 23:42:03 +01008529 /* we are in runtime processing */
8530 state_id = hlua->state_id;
Thierry Fournier75fc0292020-11-28 13:18:56 +01008531 else
Thierry Fournier021d9862020-11-28 23:42:03 +01008532 /* we are in initialization mode */
Thierry Fournierc7492592020-11-28 23:57:24 +01008533 state_id = hlua_state_id;
Thierry Fournier75fc0292020-11-28 13:18:56 +01008534
Willy Tarreaubafbe012017-11-24 17:34:44 +01008535 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008536 if (!hlua)
Christopher Faulet5294ec02021-04-12 12:24:47 +02008537 goto alloc_error;
Christopher Faulet1e8433f2021-03-24 15:03:01 +01008538 HLUA_INIT(hlua);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008539
Thierry Fournier59f11be2020-11-29 00:37:41 +01008540 /* We are in the common lua state, execute the task anywhere,
8541 * otherwise, inherit the current thread identifier
8542 */
8543 if (state_id == 0)
Willy Tarreaubeeabf52021-10-01 18:23:30 +02008544 task = task_new_anywhere();
Thierry Fournier59f11be2020-11-29 00:37:41 +01008545 else
Willy Tarreaubeeabf52021-10-01 18:23:30 +02008546 task = task_new_here();
Willy Tarreaue09101e2018-10-16 17:37:12 +02008547 if (!task)
Christopher Faulet5294ec02021-04-12 12:24:47 +02008548 goto alloc_error;
Willy Tarreaue09101e2018-10-16 17:37:12 +02008549
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008550 task->context = hlua;
8551 task->process = hlua_process_task;
8552
Thierry Fournier021d9862020-11-28 23:42:03 +01008553 if (!hlua_ctx_init(hlua, state_id, task, 1))
Christopher Faulet5294ec02021-04-12 12:24:47 +02008554 goto alloc_error;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008555
8556 /* Restore the function in the stack. */
8557 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ref);
8558 hlua->nargs = 0;
8559
8560 /* Schedule task. */
Willy Tarreaue3957f82021-09-30 16:17:37 +02008561 task_wakeup(task, TASK_WOKEN_INIT);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008562
8563 return 0;
Christopher Faulet5294ec02021-04-12 12:24:47 +02008564
8565 alloc_error:
8566 task_destroy(task);
8567 hlua_ctx_destroy(hlua);
8568 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
8569 return 0; /* Never reached */
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008570}
8571
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008572/* Wrapper called by HAProxy to execute an LUA converter. This wrapper
8573 * doesn't allow "yield" functions because the HAProxy engine cannot
8574 * resume converters.
8575 */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02008576static int hlua_sample_conv_wrapper(const struct arg *arg_p, struct sample *smp, void *private)
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008577{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02008578 struct hlua_function *fcn = private;
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02008579 struct stream *stream = smp->strm;
Thierry Fournierfd107a22016-02-19 19:57:23 +01008580 const char *error;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008581
Willy Tarreaube508f12016-03-10 11:47:01 +01008582 if (!stream)
8583 return 0;
8584
Willy Tarreau87b09662015-04-03 00:22:06 +02008585 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01008586 * Lua context can be not initialized. This behavior
8587 * permits to save performances because a systematic
8588 * Lua initialization cause 5% performances loss.
8589 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008590 if (!stream->hlua) {
Christopher Faulet1e8433f2021-03-24 15:03:01 +01008591 struct hlua *hlua;
8592
8593 hlua = pool_alloc(pool_head_hlua);
8594 if (!hlua) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008595 SEND_ERR(stream->be, "Lua converter '%s': can't initialize Lua context.\n", fcn->name);
8596 return 0;
8597 }
Christopher Faulet1e8433f2021-03-24 15:03:01 +01008598 HLUA_INIT(hlua);
8599 stream->hlua = hlua;
Thierry Fournierc7492592020-11-28 23:57:24 +01008600 if (!hlua_ctx_init(stream->hlua, fcn_ref_to_stack_id(fcn), stream->task, 0)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008601 SEND_ERR(stream->be, "Lua converter '%s': can't initialize Lua context.\n", fcn->name);
8602 return 0;
8603 }
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01008604 }
8605
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008606 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008607 if (!HLUA_IS_RUNNING(stream->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008608
8609 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008610 if (!SET_SAFE_LJMP(stream->hlua)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008611 if (lua_type(stream->hlua->T, -1) == LUA_TSTRING)
8612 error = lua_tostring(stream->hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +01008613 else
8614 error = "critical error";
8615 SEND_ERR(stream->be, "Lua converter '%s': %s.\n", fcn->name, error);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008616 return 0;
8617 }
8618
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008619 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008620 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008621 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008622 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008623 return 0;
8624 }
8625
8626 /* Restore the function in the stack. */
Thierry Fournierc7492592020-11-28 23:57:24 +01008627 lua_rawgeti(stream->hlua->T, LUA_REGISTRYINDEX, fcn->function_ref[stream->hlua->state_id]);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008628
8629 /* convert input sample and pust-it in the stack. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008630 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008631 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008632 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008633 return 0;
8634 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008635 hlua_smp2lua(stream->hlua->T, smp);
8636 stream->hlua->nargs = 1;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008637
8638 /* push keywords in the stack. */
8639 if (arg_p) {
8640 for (; arg_p->type != ARGT_STOP; arg_p++) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008641 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008642 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008643 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008644 return 0;
8645 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008646 hlua_arg2lua(stream->hlua->T, arg_p);
8647 stream->hlua->nargs++;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008648 }
8649 }
8650
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008651 /* We must initialize the execution timeouts. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008652 stream->hlua->max_time = hlua_timeout_session;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008653
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008654 /* At this point the execution is safe. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008655 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008656 }
8657
8658 /* Execute the function. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008659 switch (hlua_ctx_resume(stream->hlua, 0)) {
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008660 /* finished. */
8661 case HLUA_E_OK:
Thierry FOURNIERfd80df12017-05-12 16:32:20 +02008662 /* If the stack is empty, the function fails. */
8663 if (lua_gettop(stream->hlua->T) <= 0)
8664 return 0;
8665
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008666 /* Convert the returned value in sample. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008667 hlua_lua2smp(stream->hlua->T, -1, smp);
8668 lua_pop(stream->hlua->T, 1);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008669 return 1;
8670
8671 /* yield. */
8672 case HLUA_E_AGAIN:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008673 SEND_ERR(stream->be, "Lua converter '%s': cannot use yielded functions.\n", fcn->name);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008674 return 0;
8675
8676 /* finished with error. */
8677 case HLUA_E_ERRMSG:
8678 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008679 SEND_ERR(stream->be, "Lua converter '%s': %s.\n",
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008680 fcn->name, lua_tostring(stream->hlua->T, -1));
8681 lua_pop(stream->hlua->T, 1);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008682 return 0;
8683
Thierry Fournierd5b073c2018-05-21 19:42:47 +02008684 case HLUA_E_ETMOUT:
8685 SEND_ERR(stream->be, "Lua converter '%s': execution timeout.\n", fcn->name);
8686 return 0;
8687
8688 case HLUA_E_NOMEM:
8689 SEND_ERR(stream->be, "Lua converter '%s': out of memory error.\n", fcn->name);
8690 return 0;
8691
8692 case HLUA_E_YIELD:
8693 SEND_ERR(stream->be, "Lua converter '%s': yield functions like core.tcp() or core.sleep() are not allowed.\n", fcn->name);
8694 return 0;
8695
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008696 case HLUA_E_ERR:
8697 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008698 SEND_ERR(stream->be, "Lua converter '%s' returns an unknown error.\n", fcn->name);
Tim Duesterhus588b3142020-05-29 14:35:51 +02008699 /* fall through */
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008700
8701 default:
8702 return 0;
8703 }
8704}
8705
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008706/* Wrapper called by HAProxy to execute a sample-fetch. this wrapper
8707 * doesn't allow "yield" functions because the HAProxy engine cannot
Willy Tarreaube508f12016-03-10 11:47:01 +01008708 * resume sample-fetches. This function will be called by the sample
8709 * fetch engine to call lua-based fetch operations.
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008710 */
Thierry FOURNIER0786d052015-05-11 15:42:45 +02008711static int hlua_sample_fetch_wrapper(const struct arg *arg_p, struct sample *smp,
8712 const char *kw, void *private)
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008713{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02008714 struct hlua_function *fcn = private;
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02008715 struct stream *stream = smp->strm;
Thierry Fournierfd107a22016-02-19 19:57:23 +01008716 const char *error;
Christopher Faulet8c9e6bb2021-08-06 16:29:41 +02008717 unsigned int hflags = HLUA_TXN_NOTERM | HLUA_TXN_SMP_CTX;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008718
Willy Tarreaube508f12016-03-10 11:47:01 +01008719 if (!stream)
8720 return 0;
Christopher Fauletafd8f102018-11-08 11:34:21 +01008721
Willy Tarreau87b09662015-04-03 00:22:06 +02008722 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01008723 * Lua context can be not initialized. This behavior
8724 * permits to save performances because a systematic
8725 * Lua initialization cause 5% performances loss.
8726 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008727 if (!stream->hlua) {
Christopher Faulet1e8433f2021-03-24 15:03:01 +01008728 struct hlua *hlua;
8729
8730 hlua = pool_alloc(pool_head_hlua);
8731 if (!hlua) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008732 SEND_ERR(stream->be, "Lua sample-fetch '%s': can't initialize Lua context.\n", fcn->name);
8733 return 0;
8734 }
Christopher Faulet1e8433f2021-03-24 15:03:01 +01008735 hlua->T = NULL;
8736 stream->hlua = hlua;
Thierry Fournierc7492592020-11-28 23:57:24 +01008737 if (!hlua_ctx_init(stream->hlua, fcn_ref_to_stack_id(fcn), stream->task, 0)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008738 SEND_ERR(stream->be, "Lua sample-fetch '%s': can't initialize Lua context.\n", fcn->name);
8739 return 0;
8740 }
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01008741 }
8742
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008743 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008744 if (!HLUA_IS_RUNNING(stream->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008745
8746 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008747 if (!SET_SAFE_LJMP(stream->hlua)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008748 if (lua_type(stream->hlua->T, -1) == LUA_TSTRING)
8749 error = lua_tostring(stream->hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +01008750 else
8751 error = "critical error";
8752 SEND_ERR(smp->px, "Lua sample-fetch '%s': %s.\n", fcn->name, error);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008753 return 0;
8754 }
8755
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008756 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008757 if (!lua_checkstack(stream->hlua->T, 2)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008758 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008759 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008760 return 0;
8761 }
8762
8763 /* Restore the function in the stack. */
Thierry Fournierc7492592020-11-28 23:57:24 +01008764 lua_rawgeti(stream->hlua->T, LUA_REGISTRYINDEX, fcn->function_ref[stream->hlua->state_id]);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008765
8766 /* push arguments in the stack. */
Christopher Fauletbfab2dd2019-07-26 15:09:53 +02008767 if (!hlua_txn_new(stream->hlua->T, stream, smp->px, smp->opt & SMP_OPT_DIR, hflags)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008768 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008769 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008770 return 0;
8771 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008772 stream->hlua->nargs = 1;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008773
8774 /* push keywords in the stack. */
8775 for (; arg_p && arg_p->type != ARGT_STOP; arg_p++) {
8776 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008777 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008778 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008779 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008780 return 0;
8781 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008782 hlua_arg2lua(stream->hlua->T, arg_p);
8783 stream->hlua->nargs++;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008784 }
8785
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008786 /* We must initialize the execution timeouts. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008787 stream->hlua->max_time = hlua_timeout_session;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008788
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008789 /* At this point the execution is safe. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008790 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008791 }
8792
8793 /* Execute the function. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008794 switch (hlua_ctx_resume(stream->hlua, 0)) {
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008795 /* finished. */
8796 case HLUA_E_OK:
Thierry FOURNIERfd80df12017-05-12 16:32:20 +02008797 /* If the stack is empty, the function fails. */
8798 if (lua_gettop(stream->hlua->T) <= 0)
8799 return 0;
8800
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008801 /* Convert the returned value in sample. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008802 hlua_lua2smp(stream->hlua->T, -1, smp);
8803 lua_pop(stream->hlua->T, 1);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008804
8805 /* Set the end of execution flag. */
8806 smp->flags &= ~SMP_F_MAY_CHANGE;
8807 return 1;
8808
8809 /* yield. */
8810 case HLUA_E_AGAIN:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008811 SEND_ERR(smp->px, "Lua sample-fetch '%s': cannot use yielded functions.\n", fcn->name);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008812 return 0;
8813
8814 /* finished with error. */
8815 case HLUA_E_ERRMSG:
8816 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008817 SEND_ERR(smp->px, "Lua sample-fetch '%s': %s.\n",
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008818 fcn->name, lua_tostring(stream->hlua->T, -1));
8819 lua_pop(stream->hlua->T, 1);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008820 return 0;
8821
Thierry Fournierd5b073c2018-05-21 19:42:47 +02008822 case HLUA_E_ETMOUT:
Thierry Fournierd5b073c2018-05-21 19:42:47 +02008823 SEND_ERR(smp->px, "Lua sample-fetch '%s': execution timeout.\n", fcn->name);
8824 return 0;
8825
8826 case HLUA_E_NOMEM:
Thierry Fournierd5b073c2018-05-21 19:42:47 +02008827 SEND_ERR(smp->px, "Lua sample-fetch '%s': out of memory error.\n", fcn->name);
8828 return 0;
8829
8830 case HLUA_E_YIELD:
Thierry Fournierd5b073c2018-05-21 19:42:47 +02008831 SEND_ERR(smp->px, "Lua sample-fetch '%s': yield not allowed.\n", fcn->name);
8832 return 0;
8833
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008834 case HLUA_E_ERR:
8835 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008836 SEND_ERR(smp->px, "Lua sample-fetch '%s' returns an unknown error.\n", fcn->name);
Tim Duesterhus588b3142020-05-29 14:35:51 +02008837 /* fall through */
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008838
8839 default:
8840 return 0;
8841 }
8842}
8843
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008844/* This function is an LUA binding used for registering
8845 * "sample-conv" functions. It expects a converter name used
8846 * in the haproxy configuration file, and an LUA function.
8847 */
8848__LJMP static int hlua_register_converters(lua_State *L)
8849{
8850 struct sample_conv_kw_list *sck;
8851 const char *name;
8852 int ref;
8853 int len;
Christopher Fauletaa224302021-04-12 14:08:21 +02008854 struct hlua_function *fcn = NULL;
Thierry Fournierf67442e2020-11-28 20:41:07 +01008855 struct sample_conv *sc;
8856 struct buffer *trash;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008857
8858 MAY_LJMP(check_args(L, 2, "register_converters"));
8859
8860 /* First argument : converter name. */
8861 name = MAY_LJMP(luaL_checkstring(L, 1));
8862
8863 /* Second argument : lua function. */
8864 ref = MAY_LJMP(hlua_checkfunction(L, 2));
8865
Thierry Fournierf67442e2020-11-28 20:41:07 +01008866 /* Check if the converter is already registered */
8867 trash = get_trash_chunk();
8868 chunk_printf(trash, "lua.%s", name);
8869 sc = find_sample_conv(trash->area, trash->data);
8870 if (sc != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +01008871 fcn = sc->private;
8872 if (fcn->function_ref[hlua_state_id] != -1) {
8873 ha_warning("Trying to register converter 'lua.%s' more than once. "
8874 "This will become a hard error in version 2.5.\n", name);
8875 }
8876 fcn->function_ref[hlua_state_id] = ref;
8877 return 0;
Thierry Fournierf67442e2020-11-28 20:41:07 +01008878 }
8879
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008880 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02008881 sck = calloc(1, sizeof(*sck) + sizeof(struct sample_conv) * 2);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008882 if (!sck)
Christopher Fauletaa224302021-04-12 14:08:21 +02008883 goto alloc_error;
Thierry Fournier62a22aa2020-11-28 21:06:35 +01008884 fcn = new_hlua_function();
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008885 if (!fcn)
Christopher Fauletaa224302021-04-12 14:08:21 +02008886 goto alloc_error;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008887
8888 /* Fill fcn. */
8889 fcn->name = strdup(name);
8890 if (!fcn->name)
Christopher Fauletaa224302021-04-12 14:08:21 +02008891 goto alloc_error;
Thierry Fournierc7492592020-11-28 23:57:24 +01008892 fcn->function_ref[hlua_state_id] = ref;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008893
8894 /* List head */
8895 sck->list.n = sck->list.p = NULL;
8896
8897 /* converter keyword. */
8898 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02008899 sck->kw[0].kw = calloc(1, len);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008900 if (!sck->kw[0].kw)
Christopher Fauletaa224302021-04-12 14:08:21 +02008901 goto alloc_error;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008902
8903 snprintf((char *)sck->kw[0].kw, len, "lua.%s", name);
8904 sck->kw[0].process = hlua_sample_conv_wrapper;
David Carlier0c437f42016-04-27 16:21:56 +01008905 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 +01008906 sck->kw[0].val_args = NULL;
8907 sck->kw[0].in_type = SMP_T_STR;
8908 sck->kw[0].out_type = SMP_T_STR;
8909 sck->kw[0].private = fcn;
8910
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008911 /* Register this new converter */
8912 sample_register_convs(sck);
8913
8914 return 0;
Christopher Fauletaa224302021-04-12 14:08:21 +02008915
8916 alloc_error:
8917 release_hlua_function(fcn);
8918 ha_free(&sck);
8919 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
8920 return 0; /* Never reached */
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008921}
8922
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08008923/* This function is an LUA binding used for registering
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008924 * "sample-fetch" functions. It expects a converter name used
8925 * in the haproxy configuration file, and an LUA function.
8926 */
8927__LJMP static int hlua_register_fetches(lua_State *L)
8928{
8929 const char *name;
8930 int ref;
8931 int len;
8932 struct sample_fetch_kw_list *sfk;
Christopher Faulet2567f182021-04-12 14:11:50 +02008933 struct hlua_function *fcn = NULL;
Thierry Fournierf67442e2020-11-28 20:41:07 +01008934 struct sample_fetch *sf;
8935 struct buffer *trash;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008936
8937 MAY_LJMP(check_args(L, 2, "register_fetches"));
8938
8939 /* First argument : sample-fetch name. */
8940 name = MAY_LJMP(luaL_checkstring(L, 1));
8941
8942 /* Second argument : lua function. */
8943 ref = MAY_LJMP(hlua_checkfunction(L, 2));
8944
Thierry Fournierf67442e2020-11-28 20:41:07 +01008945 /* Check if the sample-fetch is already registered */
8946 trash = get_trash_chunk();
8947 chunk_printf(trash, "lua.%s", name);
8948 sf = find_sample_fetch(trash->area, trash->data);
8949 if (sf != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +01008950 fcn = sf->private;
8951 if (fcn->function_ref[hlua_state_id] != -1) {
8952 ha_warning("Trying to register sample-fetch 'lua.%s' more than once. "
8953 "This will become a hard error in version 2.5.\n", name);
8954 }
8955 fcn->function_ref[hlua_state_id] = ref;
8956 return 0;
Thierry Fournierf67442e2020-11-28 20:41:07 +01008957 }
8958
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008959 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02008960 sfk = calloc(1, sizeof(*sfk) + sizeof(struct sample_fetch) * 2);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008961 if (!sfk)
Christopher Faulet2567f182021-04-12 14:11:50 +02008962 goto alloc_error;
Thierry Fournier62a22aa2020-11-28 21:06:35 +01008963 fcn = new_hlua_function();
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008964 if (!fcn)
Christopher Faulet2567f182021-04-12 14:11:50 +02008965 goto alloc_error;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008966
8967 /* Fill fcn. */
8968 fcn->name = strdup(name);
8969 if (!fcn->name)
Christopher Faulet2567f182021-04-12 14:11:50 +02008970 goto alloc_error;
Thierry Fournierc7492592020-11-28 23:57:24 +01008971 fcn->function_ref[hlua_state_id] = ref;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008972
8973 /* List head */
8974 sfk->list.n = sfk->list.p = NULL;
8975
8976 /* sample-fetch keyword. */
8977 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02008978 sfk->kw[0].kw = calloc(1, len);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008979 if (!sfk->kw[0].kw)
Christopher Faulet2567f182021-04-12 14:11:50 +02008980 goto alloc_error;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008981
8982 snprintf((char *)sfk->kw[0].kw, len, "lua.%s", name);
8983 sfk->kw[0].process = hlua_sample_fetch_wrapper;
David Carlier0c437f42016-04-27 16:21:56 +01008984 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 +01008985 sfk->kw[0].val_args = NULL;
8986 sfk->kw[0].out_type = SMP_T_STR;
8987 sfk->kw[0].use = SMP_USE_HTTP_ANY;
8988 sfk->kw[0].val = 0;
8989 sfk->kw[0].private = fcn;
8990
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008991 /* Register this new fetch. */
8992 sample_register_fetches(sfk);
8993
8994 return 0;
Christopher Faulet2567f182021-04-12 14:11:50 +02008995
8996 alloc_error:
8997 release_hlua_function(fcn);
8998 ha_free(&sfk);
8999 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
9000 return 0; /* Never reached */
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009001}
9002
Christopher Faulet501465d2020-02-26 14:54:16 +01009003/* This function is a lua binding to set the wake_time.
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01009004 */
Christopher Faulet501465d2020-02-26 14:54:16 +01009005__LJMP static int hlua_set_wake_time(lua_State *L)
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01009006{
Thierry Fournier4234dbd2020-11-28 13:18:23 +01009007 struct hlua *hlua;
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01009008 unsigned int delay;
9009 unsigned int wakeup_ms;
9010
Thierry Fournier4234dbd2020-11-28 13:18:23 +01009011 /* Get hlua struct, or NULL if we execute from main lua state */
9012 hlua = hlua_gethlua(L);
9013 if (!hlua) {
9014 return 0;
9015 }
9016
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01009017 MAY_LJMP(check_args(L, 1, "wake_time"));
9018
9019 delay = MAY_LJMP(luaL_checkinteger(L, 1));
9020 wakeup_ms = tick_add(now_ms, delay);
9021 hlua->wake_time = wakeup_ms;
9022 return 0;
9023}
9024
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009025/* This function is a wrapper to execute each LUA function declared as an action
9026 * wrapper during the initialisation period. This function may return any
9027 * ACT_RET_* value. On error ACT_RET_CONT is returned and the action is
9028 * ignored. If the lua action yields, ACT_RET_YIELD is returned. On success, the
9029 * return value is the first element on the stack.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009030 */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009031static enum act_return hlua_action(struct act_rule *rule, struct proxy *px,
Willy Tarreau658b85b2015-09-27 10:00:49 +02009032 struct session *sess, struct stream *s, int flags)
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009033{
9034 char **arg;
Christopher Faulet8c9e6bb2021-08-06 16:29:41 +02009035 unsigned int hflags = HLUA_TXN_ACT_CTX;
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009036 int dir, act_ret = ACT_RET_CONT;
Thierry Fournierfd107a22016-02-19 19:57:23 +01009037 const char *error;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009038
9039 switch (rule->from) {
Christopher Fauletd8f0e072020-02-25 09:45:51 +01009040 case ACT_F_TCP_REQ_CNT: dir = SMP_OPT_DIR_REQ; break;
9041 case ACT_F_TCP_RES_CNT: dir = SMP_OPT_DIR_RES; break;
9042 case ACT_F_HTTP_REQ: dir = SMP_OPT_DIR_REQ; break;
9043 case ACT_F_HTTP_RES: dir = SMP_OPT_DIR_RES; break;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009044 default:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009045 SEND_ERR(px, "Lua: internal error while execute action.\n");
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009046 goto end;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009047 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009048
Willy Tarreau87b09662015-04-03 00:22:06 +02009049 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01009050 * Lua context can be not initialized. This behavior
9051 * permits to save performances because a systematic
9052 * Lua initialization cause 5% performances loss.
9053 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009054 if (!s->hlua) {
Christopher Faulet1e8433f2021-03-24 15:03:01 +01009055 struct hlua *hlua;
9056
9057 hlua = pool_alloc(pool_head_hlua);
9058 if (!hlua) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009059 SEND_ERR(px, "Lua action '%s': can't initialize Lua context.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009060 rule->arg.hlua_rule->fcn->name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009061 goto end;
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009062 }
Christopher Faulet1e8433f2021-03-24 15:03:01 +01009063 HLUA_INIT(hlua);
9064 s->hlua = hlua;
Thierry Fournierc7492592020-11-28 23:57:24 +01009065 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 +01009066 SEND_ERR(px, "Lua action '%s': can't initialize Lua context.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009067 rule->arg.hlua_rule->fcn->name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009068 goto end;
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009069 }
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01009070 }
9071
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009072 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009073 if (!HLUA_IS_RUNNING(s->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02009074
9075 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009076 if (!SET_SAFE_LJMP(s->hlua)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009077 if (lua_type(s->hlua->T, -1) == LUA_TSTRING)
9078 error = lua_tostring(s->hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +01009079 else
9080 error = "critical error";
9081 SEND_ERR(px, "Lua function '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009082 rule->arg.hlua_rule->fcn->name, error);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009083 goto end;
Thierry FOURNIERbabae282015-09-17 11:36:37 +02009084 }
9085
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009086 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009087 if (!lua_checkstack(s->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009088 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009089 rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009090 RESET_SAFE_LJMP(s->hlua);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009091 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009092 }
9093
9094 /* Restore the function in the stack. */
Thierry Fournierc7492592020-11-28 23:57:24 +01009095 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 +01009096
Willy Tarreau87b09662015-04-03 00:22:06 +02009097 /* Create and and push object stream in the stack. */
Christopher Fauletbfab2dd2019-07-26 15:09:53 +02009098 if (!hlua_txn_new(s->hlua->T, s, px, dir, hflags)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009099 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009100 rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009101 RESET_SAFE_LJMP(s->hlua);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009102 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009103 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009104 s->hlua->nargs = 1;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009105
9106 /* push keywords in the stack. */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009107 for (arg = rule->arg.hlua_rule->args; arg && *arg; arg++) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009108 if (!lua_checkstack(s->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009109 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009110 rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009111 RESET_SAFE_LJMP(s->hlua);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009112 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009113 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009114 lua_pushstring(s->hlua->T, *arg);
9115 s->hlua->nargs++;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009116 }
9117
Thierry FOURNIERbabae282015-09-17 11:36:37 +02009118 /* Now the execution is safe. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009119 RESET_SAFE_LJMP(s->hlua);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02009120
Thierry FOURNIERbd413492015-03-03 16:52:26 +01009121 /* We must initialize the execution timeouts. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009122 s->hlua->max_time = hlua_timeout_session;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009123 }
9124
9125 /* Execute the function. */
Christopher Faulet105ba6c2019-12-18 14:41:51 +01009126 switch (hlua_ctx_resume(s->hlua, !(flags & ACT_OPT_FINAL))) {
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009127 /* finished. */
9128 case HLUA_E_OK:
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009129 /* Catch the return value */
9130 if (lua_gettop(s->hlua->T) > 0)
9131 act_ret = lua_tointeger(s->hlua->T, -1);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009132
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01009133 /* Set timeout in the required channel. */
Christopher Faulet498c4832020-07-28 11:59:58 +02009134 if (act_ret == ACT_RET_YIELD) {
9135 if (flags & ACT_OPT_FINAL)
9136 goto err_yield;
9137
Christopher Faulet8f587ea2020-07-28 12:01:55 +02009138 if (dir == SMP_OPT_DIR_REQ)
9139 s->req.analyse_exp = tick_first((tick_is_expired(s->req.analyse_exp, now_ms) ? 0 : s->req.analyse_exp),
9140 s->hlua->wake_time);
9141 else
9142 s->res.analyse_exp = tick_first((tick_is_expired(s->res.analyse_exp, now_ms) ? 0 : s->res.analyse_exp),
9143 s->hlua->wake_time);
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01009144 }
9145 goto end;
9146
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009147 /* yield. */
9148 case HLUA_E_AGAIN:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01009149 /* Set timeout in the required channel. */
Christopher Faulet8f587ea2020-07-28 12:01:55 +02009150 if (dir == SMP_OPT_DIR_REQ)
9151 s->req.analyse_exp = tick_first((tick_is_expired(s->req.analyse_exp, now_ms) ? 0 : s->req.analyse_exp),
9152 s->hlua->wake_time);
9153 else
9154 s->res.analyse_exp = tick_first((tick_is_expired(s->res.analyse_exp, now_ms) ? 0 : s->res.analyse_exp),
9155 s->hlua->wake_time);
9156
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009157 /* Some actions can be wake up when a "write" event
9158 * is detected on a response channel. This is useful
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08009159 * only for actions targeted on the requests.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009160 */
Christopher Faulet51fa3582019-07-26 14:54:52 +02009161 if (HLUA_IS_WAKERESWR(s->hlua))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01009162 s->res.flags |= CF_WAKE_WRITE;
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009163 if (HLUA_IS_WAKEREQWR(s->hlua))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01009164 s->req.flags |= CF_WAKE_WRITE;
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009165 act_ret = ACT_RET_YIELD;
9166 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009167
9168 /* finished with error. */
9169 case HLUA_E_ERRMSG:
9170 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009171 SEND_ERR(px, "Lua function '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009172 rule->arg.hlua_rule->fcn->name, lua_tostring(s->hlua->T, -1));
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009173 lua_pop(s->hlua->T, 1);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009174 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009175
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009176 case HLUA_E_ETMOUT:
Thierry Fournierad5345f2020-11-29 02:05:57 +01009177 SEND_ERR(px, "Lua function '%s': execution timeout.\n", rule->arg.hlua_rule->fcn->name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009178 goto end;
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009179
9180 case HLUA_E_NOMEM:
Thierry Fournierad5345f2020-11-29 02:05:57 +01009181 SEND_ERR(px, "Lua function '%s': out of memory error.\n", rule->arg.hlua_rule->fcn->name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009182 goto end;
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009183
9184 case HLUA_E_YIELD:
Christopher Faulet498c4832020-07-28 11:59:58 +02009185 err_yield:
9186 act_ret = ACT_RET_CONT;
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009187 SEND_ERR(px, "Lua function '%s': aborting Lua processing on expired timeout.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009188 rule->arg.hlua_rule->fcn->name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009189 goto end;
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009190
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009191 case HLUA_E_ERR:
9192 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009193 SEND_ERR(px, "Lua function '%s' return an unknown error.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009194 rule->arg.hlua_rule->fcn->name);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009195
9196 default:
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009197 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009198 }
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009199
9200 end:
Christopher Faulet2361fd92020-07-30 10:40:58 +02009201 if (act_ret != ACT_RET_YIELD && s->hlua)
Christopher Faulet8f587ea2020-07-28 12:01:55 +02009202 s->hlua->wake_time = TICK_ETERNITY;
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009203 return act_ret;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009204}
9205
Willy Tarreau144f84a2021-03-02 16:09:26 +01009206struct task *hlua_applet_wakeup(struct task *t, void *context, unsigned int state)
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009207{
Olivier Houchard9f6af332018-05-25 14:04:04 +02009208 struct appctx *ctx = context;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009209
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009210 appctx_wakeup(ctx);
Willy Tarreaud9587412017-08-23 16:07:33 +02009211 t->expire = TICK_ETERNITY;
Willy Tarreaud1aa41f2017-07-21 16:41:56 +02009212 return t;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009213}
9214
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009215static int hlua_applet_tcp_init(struct appctx *ctx)
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009216{
Willy Tarreaue23f33b2022-05-06 14:07:13 +02009217 struct hlua_tcp_ctx *tcp_ctx = applet_reserve_svcctx(ctx, sizeof(*tcp_ctx));
Willy Tarreau0698c802022-05-11 14:09:57 +02009218 struct conn_stream *cs = appctx_cs(ctx);
Christopher Faulet908628c2022-03-25 16:43:49 +01009219 struct stream *strm = __cs_strm(cs);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009220 struct hlua *hlua;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009221 struct task *task;
9222 char **arg;
Thierry Fournierfd107a22016-02-19 19:57:23 +01009223 const char *error;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009224
Willy Tarreaubafbe012017-11-24 17:34:44 +01009225 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009226 if (!hlua) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009227 SEND_ERR(strm->be, "Lua applet tcp '%s': out of memory.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009228 ctx->rule->arg.hlua_rule->fcn->name);
Christopher Fauletc9929382022-05-12 11:52:27 +02009229 return -1;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009230 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009231 HLUA_INIT(hlua);
Willy Tarreaue23f33b2022-05-06 14:07:13 +02009232 tcp_ctx->hlua = hlua;
9233 tcp_ctx->flags = 0;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009234
9235 /* Create task used by signal to wakeup applets. */
Willy Tarreaubeeabf52021-10-01 18:23:30 +02009236 task = task_new_here();
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009237 if (!task) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009238 SEND_ERR(strm->be, "Lua applet tcp '%s': out of memory.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009239 ctx->rule->arg.hlua_rule->fcn->name);
Christopher Fauletc9929382022-05-12 11:52:27 +02009240 return -1;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009241 }
9242 task->nice = 0;
9243 task->context = ctx;
9244 task->process = hlua_applet_wakeup;
Willy Tarreaue23f33b2022-05-06 14:07:13 +02009245 tcp_ctx->task = task;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009246
9247 /* In the execution wrappers linked with a stream, the
9248 * Lua context can be not initialized. This behavior
9249 * permits to save performances because a systematic
9250 * Lua initialization cause 5% performances loss.
9251 */
Thierry Fournierc7492592020-11-28 23:57:24 +01009252 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 +01009253 SEND_ERR(strm->be, "Lua applet tcp '%s': can't initialize Lua context.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009254 ctx->rule->arg.hlua_rule->fcn->name);
Christopher Fauletc9929382022-05-12 11:52:27 +02009255 return -1;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009256 }
9257
9258 /* Set timeout according with the applet configuration. */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02009259 hlua->max_time = ctx->applet->timeout;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009260
9261 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009262 if (!SET_SAFE_LJMP(hlua)) {
Thierry Fournierfd107a22016-02-19 19:57:23 +01009263 if (lua_type(hlua->T, -1) == LUA_TSTRING)
9264 error = lua_tostring(hlua->T, -1);
9265 else
9266 error = "critical error";
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009267 SEND_ERR(strm->be, "Lua applet tcp '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009268 ctx->rule->arg.hlua_rule->fcn->name, error);
Christopher Fauletc9929382022-05-12 11:52:27 +02009269 return -1;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009270 }
9271
9272 /* Check stack available size. */
9273 if (!lua_checkstack(hlua->T, 1)) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009274 SEND_ERR(strm->be, "Lua applet tcp '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009275 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009276 RESET_SAFE_LJMP(hlua);
Christopher Fauletc9929382022-05-12 11:52:27 +02009277 return -1;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009278 }
9279
9280 /* Restore the function in the stack. */
Thierry Fournierc7492592020-11-28 23:57:24 +01009281 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ctx->rule->arg.hlua_rule->fcn->function_ref[hlua->state_id]);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009282
9283 /* Create and and push object stream in the stack. */
9284 if (!hlua_applet_tcp_new(hlua->T, ctx)) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009285 SEND_ERR(strm->be, "Lua applet tcp '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009286 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009287 RESET_SAFE_LJMP(hlua);
Christopher Fauletc9929382022-05-12 11:52:27 +02009288 return -1;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009289 }
9290 hlua->nargs = 1;
9291
9292 /* push keywords in the stack. */
9293 for (arg = ctx->rule->arg.hlua_rule->args; arg && *arg; arg++) {
9294 if (!lua_checkstack(hlua->T, 1)) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009295 SEND_ERR(strm->be, "Lua applet tcp '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009296 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009297 RESET_SAFE_LJMP(hlua);
Christopher Fauletc9929382022-05-12 11:52:27 +02009298 return -1;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009299 }
9300 lua_pushstring(hlua->T, *arg);
9301 hlua->nargs++;
9302 }
9303
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009304 RESET_SAFE_LJMP(hlua);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009305
9306 /* Wakeup the applet ASAP. */
Christopher Fauleta0bdec32022-04-04 07:51:21 +02009307 cs_cant_get(cs);
9308 cs_rx_endp_more(cs);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009309
Christopher Fauletc9929382022-05-12 11:52:27 +02009310 return 0;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009311}
9312
Willy Tarreau60409db2019-08-21 14:14:50 +02009313void hlua_applet_tcp_fct(struct appctx *ctx)
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009314{
Willy Tarreaue23f33b2022-05-06 14:07:13 +02009315 struct hlua_tcp_ctx *tcp_ctx = ctx->svcctx;
Willy Tarreau0698c802022-05-11 14:09:57 +02009316 struct conn_stream *cs = appctx_cs(ctx);
Christopher Faulet908628c2022-03-25 16:43:49 +01009317 struct stream *strm = __cs_strm(cs);
9318 struct channel *res = cs_ic(cs);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009319 struct act_rule *rule = ctx->rule;
9320 struct proxy *px = strm->be;
Willy Tarreaue23f33b2022-05-06 14:07:13 +02009321 struct hlua *hlua = tcp_ctx->hlua;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009322
9323 /* The applet execution is already done. */
Willy Tarreaue23f33b2022-05-06 14:07:13 +02009324 if (tcp_ctx->flags & APPLET_DONE) {
Olivier Houchard594c8c52018-08-28 14:41:31 +02009325 /* eat the whole request */
Christopher Faulet908628c2022-03-25 16:43:49 +01009326 co_skip(cs_oc(cs), co_data(cs_oc(cs)));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009327 return;
Olivier Houchard594c8c52018-08-28 14:41:31 +02009328 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009329
9330 /* If the stream is disconnect or closed, ldo nothing. */
Christopher Faulet62e75742022-03-31 09:16:34 +02009331 if (unlikely(cs->state == CS_ST_DIS || cs->state == CS_ST_CLO))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009332 return;
9333
9334 /* Execute the function. */
9335 switch (hlua_ctx_resume(hlua, 1)) {
9336 /* finished. */
9337 case HLUA_E_OK:
Willy Tarreaue23f33b2022-05-06 14:07:13 +02009338 tcp_ctx->flags |= APPLET_DONE;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009339
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009340 /* eat the whole request */
Christopher Faulet908628c2022-03-25 16:43:49 +01009341 co_skip(cs_oc(cs), co_data(cs_oc(cs)));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009342 res->flags |= CF_READ_NULL;
Christopher Fauletda098e62022-03-31 17:44:45 +02009343 cs_shutr(cs);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009344 return;
9345
9346 /* yield. */
9347 case HLUA_E_AGAIN:
Thierry Fournier0164f202016-02-20 17:47:43 +01009348 if (hlua->wake_time != TICK_ETERNITY)
Willy Tarreaue23f33b2022-05-06 14:07:13 +02009349 task_schedule(tcp_ctx->task, hlua->wake_time);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009350 return;
9351
9352 /* finished with error. */
9353 case HLUA_E_ERRMSG:
9354 /* Display log. */
9355 SEND_ERR(px, "Lua applet tcp '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009356 rule->arg.hlua_rule->fcn->name, lua_tostring(hlua->T, -1));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009357 lua_pop(hlua->T, 1);
9358 goto error;
9359
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009360 case HLUA_E_ETMOUT:
9361 SEND_ERR(px, "Lua applet tcp '%s': execution timeout.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009362 rule->arg.hlua_rule->fcn->name);
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009363 goto error;
9364
9365 case HLUA_E_NOMEM:
9366 SEND_ERR(px, "Lua applet tcp '%s': out of memory error.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009367 rule->arg.hlua_rule->fcn->name);
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009368 goto error;
9369
9370 case HLUA_E_YIELD: /* unexpected */
9371 SEND_ERR(px, "Lua applet tcp '%s': yield not allowed.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009372 rule->arg.hlua_rule->fcn->name);
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009373 goto error;
9374
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009375 case HLUA_E_ERR:
9376 /* Display log. */
9377 SEND_ERR(px, "Lua applet tcp '%s' return an unknown error.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009378 rule->arg.hlua_rule->fcn->name);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009379 goto error;
9380
9381 default:
9382 goto error;
9383 }
9384
9385error:
9386
9387 /* For all other cases, just close the stream. */
Christopher Fauletda098e62022-03-31 17:44:45 +02009388 cs_shutw(cs);
9389 cs_shutr(cs);
Willy Tarreaue23f33b2022-05-06 14:07:13 +02009390 tcp_ctx->flags |= APPLET_DONE;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009391}
9392
9393static void hlua_applet_tcp_release(struct appctx *ctx)
9394{
Willy Tarreaue23f33b2022-05-06 14:07:13 +02009395 struct hlua_tcp_ctx *tcp_ctx = ctx->svcctx;
9396
9397 task_destroy(tcp_ctx->task);
9398 tcp_ctx->task = NULL;
9399 hlua_ctx_destroy(tcp_ctx->hlua);
9400 tcp_ctx->hlua = NULL;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009401}
9402
Christopher Fauletc9929382022-05-12 11:52:27 +02009403/* The function returns 0 if the initialisation is complete or -1 if
9404 * an errors occurs. It also reserves the appctx for an hlua_http_ctx.
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009405 */
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009406static int hlua_applet_http_init(struct appctx *ctx)
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009407{
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009408 struct hlua_http_ctx *http_ctx = applet_reserve_svcctx(ctx, sizeof(*http_ctx));
Willy Tarreau0698c802022-05-11 14:09:57 +02009409 struct conn_stream *cs = appctx_cs(ctx);
Christopher Faulet908628c2022-03-25 16:43:49 +01009410 struct stream *strm = __cs_strm(cs);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009411 struct http_txn *txn;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009412 struct hlua *hlua;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009413 char **arg;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009414 struct task *task;
Thierry Fournierfd107a22016-02-19 19:57:23 +01009415 const char *error;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009416
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009417 txn = strm->txn;
Willy Tarreaubafbe012017-11-24 17:34:44 +01009418 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009419 if (!hlua) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009420 SEND_ERR(strm->be, "Lua applet http '%s': out of memory.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009421 ctx->rule->arg.hlua_rule->fcn->name);
Christopher Fauletc9929382022-05-12 11:52:27 +02009422 return -1;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009423 }
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009424 HLUA_INIT(hlua);
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009425 http_ctx->hlua = hlua;
9426 http_ctx->left_bytes = -1;
9427 http_ctx->flags = 0;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009428
Thierry FOURNIERd93ea2b2015-12-20 19:14:52 +01009429 if (txn->req.flags & HTTP_MSGF_VER_11)
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009430 http_ctx->flags |= APPLET_HTTP11;
Thierry FOURNIERd93ea2b2015-12-20 19:14:52 +01009431
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009432 /* Create task used by signal to wakeup applets. */
Willy Tarreaubeeabf52021-10-01 18:23:30 +02009433 task = task_new_here();
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009434 if (!task) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009435 SEND_ERR(strm->be, "Lua applet http '%s': out of memory.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009436 ctx->rule->arg.hlua_rule->fcn->name);
Christopher Fauletc9929382022-05-12 11:52:27 +02009437 return -1;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009438 }
9439 task->nice = 0;
9440 task->context = ctx;
9441 task->process = hlua_applet_wakeup;
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009442 http_ctx->task = task;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009443
9444 /* In the execution wrappers linked with a stream, the
9445 * Lua context can be not initialized. This behavior
9446 * permits to save performances because a systematic
9447 * Lua initialization cause 5% performances loss.
9448 */
Thierry Fournierc7492592020-11-28 23:57:24 +01009449 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 +01009450 SEND_ERR(strm->be, "Lua applet http '%s': can't initialize Lua context.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009451 ctx->rule->arg.hlua_rule->fcn->name);
Christopher Fauletc9929382022-05-12 11:52:27 +02009452 return -1;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009453 }
9454
9455 /* Set timeout according with the applet configuration. */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02009456 hlua->max_time = ctx->applet->timeout;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009457
9458 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009459 if (!SET_SAFE_LJMP(hlua)) {
Thierry Fournierfd107a22016-02-19 19:57:23 +01009460 if (lua_type(hlua->T, -1) == LUA_TSTRING)
9461 error = lua_tostring(hlua->T, -1);
9462 else
9463 error = "critical error";
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009464 SEND_ERR(strm->be, "Lua applet http '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009465 ctx->rule->arg.hlua_rule->fcn->name, error);
Christopher Fauletc9929382022-05-12 11:52:27 +02009466 return -1;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009467 }
9468
9469 /* Check stack available size. */
9470 if (!lua_checkstack(hlua->T, 1)) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009471 SEND_ERR(strm->be, "Lua applet http '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009472 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009473 RESET_SAFE_LJMP(hlua);
Christopher Fauletc9929382022-05-12 11:52:27 +02009474 return -1;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009475 }
9476
9477 /* Restore the function in the stack. */
Thierry Fournierc7492592020-11-28 23:57:24 +01009478 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ctx->rule->arg.hlua_rule->fcn->function_ref[hlua->state_id]);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009479
9480 /* Create and and push object stream in the stack. */
9481 if (!hlua_applet_http_new(hlua->T, ctx)) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009482 SEND_ERR(strm->be, "Lua applet http '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009483 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009484 RESET_SAFE_LJMP(hlua);
Christopher Fauletc9929382022-05-12 11:52:27 +02009485 return -1;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009486 }
9487 hlua->nargs = 1;
9488
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009489 /* push keywords in the stack. */
9490 for (arg = ctx->rule->arg.hlua_rule->args; arg && *arg; arg++) {
9491 if (!lua_checkstack(hlua->T, 1)) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009492 SEND_ERR(strm->be, "Lua applet http '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009493 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009494 RESET_SAFE_LJMP(hlua);
Christopher Fauletc9929382022-05-12 11:52:27 +02009495 return -1;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009496 }
9497 lua_pushstring(hlua->T, *arg);
9498 hlua->nargs++;
9499 }
9500
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009501 RESET_SAFE_LJMP(hlua);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009502
9503 /* Wakeup the applet when data is ready for read. */
Christopher Fauleta0bdec32022-04-04 07:51:21 +02009504 cs_cant_get(cs);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009505
Christopher Fauletc9929382022-05-12 11:52:27 +02009506 return 0;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009507}
9508
Willy Tarreau60409db2019-08-21 14:14:50 +02009509void hlua_applet_http_fct(struct appctx *ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009510{
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009511 struct hlua_http_ctx *http_ctx = ctx->svcctx;
Willy Tarreau0698c802022-05-11 14:09:57 +02009512 struct conn_stream *cs = appctx_cs(ctx);
Christopher Faulet908628c2022-03-25 16:43:49 +01009513 struct stream *strm = __cs_strm(cs);
9514 struct channel *req = cs_oc(cs);
9515 struct channel *res = cs_ic(cs);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009516 struct act_rule *rule = ctx->rule;
9517 struct proxy *px = strm->be;
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009518 struct hlua *hlua = http_ctx->hlua;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009519 struct htx *req_htx, *res_htx;
9520
9521 res_htx = htx_from_buf(&res->buf);
9522
9523 /* If the stream is disconnect or closed, ldo nothing. */
Christopher Faulet62e75742022-03-31 09:16:34 +02009524 if (unlikely(cs->state == CS_ST_DIS || cs->state == CS_ST_CLO))
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009525 goto out;
9526
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05009527 /* Check if the input buffer is available. */
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009528 if (!b_size(&res->buf)) {
Christopher Fauleta0bdec32022-04-04 07:51:21 +02009529 cs_rx_room_blk(cs);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009530 goto out;
9531 }
9532 /* check that the output is not closed */
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01009533 if (res->flags & (CF_SHUTW|CF_SHUTW_NOW|CF_SHUTR))
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009534 http_ctx->flags |= APPLET_DONE;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009535
9536 /* Set the currently running flag. */
9537 if (!HLUA_IS_RUNNING(hlua) &&
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009538 !(http_ctx->flags & APPLET_DONE)) {
Christopher Fauletbd878d22021-04-28 10:50:21 +02009539 if (!co_data(req)) {
Christopher Fauleta0bdec32022-04-04 07:51:21 +02009540 cs_cant_get(cs);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009541 goto out;
9542 }
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009543 }
9544
9545 /* Executes The applet if it is not done. */
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009546 if (!(http_ctx->flags & APPLET_DONE)) {
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009547
9548 /* Execute the function. */
9549 switch (hlua_ctx_resume(hlua, 1)) {
9550 /* finished. */
9551 case HLUA_E_OK:
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009552 http_ctx->flags |= APPLET_DONE;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009553 break;
9554
9555 /* yield. */
9556 case HLUA_E_AGAIN:
9557 if (hlua->wake_time != TICK_ETERNITY)
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009558 task_schedule(http_ctx->task, hlua->wake_time);
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01009559 goto out;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009560
9561 /* finished with error. */
9562 case HLUA_E_ERRMSG:
9563 /* Display log. */
9564 SEND_ERR(px, "Lua applet http '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009565 rule->arg.hlua_rule->fcn->name, lua_tostring(hlua->T, -1));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009566 lua_pop(hlua->T, 1);
9567 goto error;
9568
9569 case HLUA_E_ETMOUT:
9570 SEND_ERR(px, "Lua applet http '%s': execution timeout.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009571 rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009572 goto error;
9573
9574 case HLUA_E_NOMEM:
9575 SEND_ERR(px, "Lua applet http '%s': out of memory error.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009576 rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009577 goto error;
9578
9579 case HLUA_E_YIELD: /* unexpected */
9580 SEND_ERR(px, "Lua applet http '%s': yield not allowed.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009581 rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009582 goto error;
9583
9584 case HLUA_E_ERR:
9585 /* Display log. */
9586 SEND_ERR(px, "Lua applet http '%s' return an unknown error.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009587 rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009588 goto error;
9589
9590 default:
9591 goto error;
9592 }
9593 }
9594
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009595 if (http_ctx->flags & APPLET_DONE) {
9596 if (http_ctx->flags & APPLET_RSP_SENT)
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01009597 goto done;
9598
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009599 if (!(http_ctx->flags & APPLET_HDR_SENT))
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009600 goto error;
9601
Christopher Fauletf89af9c2022-04-07 10:07:18 +02009602 /* no more data are expected. If the response buffer is empty
9603 * for a chunked message, be sure to add something (EOT block in
9604 * this case) to have something to send. It is important to be
9605 * sure the EOM flags will be handled by the endpoint.
9606 */
9607 if (htx_is_empty(res_htx) && (strm->txn->rsp.flags & (HTTP_MSGF_XFER_LEN|HTTP_MSGF_CNT_LEN)) == HTTP_MSGF_XFER_LEN) {
9608 if (!htx_add_endof(res_htx, HTX_BLK_EOT)) {
Christopher Fauleta0bdec32022-04-04 07:51:21 +02009609 cs_rx_room_blk(cs);
Christopher Fauletf89af9c2022-04-07 10:07:18 +02009610 goto out;
9611 }
9612 channel_add_input(res, 1);
9613 }
9614
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01009615 res_htx->flags |= HTX_FL_EOM;
Christopher Fauletd8d27082022-03-07 15:50:54 +01009616 res->flags |= CF_EOI;
Willy Tarreau66435e52022-05-10 11:32:31 +02009617 ctx->endp->flags |= CS_EP_EOI;
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009618 strm->txn->status = http_ctx->status;
9619 http_ctx->flags |= APPLET_RSP_SENT;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009620 }
9621
9622 done:
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009623 if (http_ctx->flags & APPLET_DONE) {
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01009624 if (!(res->flags & CF_SHUTR)) {
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009625 res->flags |= CF_READ_NULL;
Christopher Fauletda098e62022-03-31 17:44:45 +02009626 cs_shutr(cs);
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01009627 }
9628
9629 /* eat the whole request */
9630 if (co_data(req)) {
9631 req_htx = htx_from_buf(&req->buf);
9632 co_htx_skip(req, req_htx, co_data(req));
9633 htx_to_buf(req_htx, &req->buf);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009634 }
9635 }
9636
9637 out:
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009638 htx_to_buf(res_htx, &res->buf);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009639 return;
9640
9641 error:
9642
9643 /* If we are in HTTP mode, and we are not send any
9644 * data, return a 500 server error in best effort:
9645 * if there is no room available in the buffer,
9646 * just close the connection.
9647 */
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009648 if (!(http_ctx->flags & APPLET_HDR_SENT)) {
Christopher Fauletf7346382019-07-17 22:02:08 +02009649 struct buffer *err = &http_err_chunks[HTTP_ERR_500];
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009650
9651 channel_erase(res);
9652 res->buf.data = b_data(err);
9653 memcpy(res->buf.area, b_head(err), b_data(err));
9654 res_htx = htx_from_buf(&res->buf);
Christopher Fauletf6cce3f2019-02-27 21:20:09 +01009655 channel_add_input(res, res_htx->data);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009656 }
9657 if (!(strm->flags & SF_ERR_MASK))
9658 strm->flags |= SF_ERR_RESOURCE;
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009659 http_ctx->flags |= APPLET_DONE;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009660 goto done;
9661}
9662
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009663static void hlua_applet_http_release(struct appctx *ctx)
9664{
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009665 struct hlua_http_ctx *http_ctx = ctx->svcctx;
9666
9667 task_destroy(http_ctx->task);
9668 http_ctx->task = NULL;
9669 hlua_ctx_destroy(http_ctx->hlua);
9670 http_ctx->hlua = NULL;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009671}
9672
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009673/* global {tcp|http}-request parser. Return ACT_RET_PRS_OK in
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05009674 * success case, else return ACT_RET_PRS_ERR.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02009675 *
9676 * This function can fail with an abort() due to an Lua critical error.
9677 * We are in the configuration parsing process of HAProxy, this abort() is
9678 * tolerated.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009679 */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009680static enum act_parse_ret action_register_lua(const char **args, int *cur_arg, struct proxy *px,
9681 struct act_rule *rule, char **err)
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009682{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02009683 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009684 int i;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009685
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009686 /* Memory for the rule. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02009687 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009688 if (!rule->arg.hlua_rule) {
9689 memprintf(err, "out of memory error");
Christopher Faulet528526f2021-04-12 14:37:32 +02009690 goto error;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009691 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009692
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009693 /* Memory for arguments. */
Tim Duesterhuse52b6e52020-09-12 20:26:43 +02009694 rule->arg.hlua_rule->args = calloc(fcn->nargs + 1,
9695 sizeof(*rule->arg.hlua_rule->args));
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009696 if (!rule->arg.hlua_rule->args) {
9697 memprintf(err, "out of memory error");
Christopher Faulet528526f2021-04-12 14:37:32 +02009698 goto error;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009699 }
9700
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009701 /* Reference the Lua function and store the reference. */
Thierry Fournierad5345f2020-11-29 02:05:57 +01009702 rule->arg.hlua_rule->fcn = fcn;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009703
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009704 /* Expect some arguments */
9705 for (i = 0; i < fcn->nargs; i++) {
Thierry FOURNIER1725c2e2019-01-06 19:38:49 +01009706 if (*args[*cur_arg] == '\0') {
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009707 memprintf(err, "expect %d arguments", fcn->nargs);
Christopher Faulet528526f2021-04-12 14:37:32 +02009708 goto error;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009709 }
Thierry FOURNIER1725c2e2019-01-06 19:38:49 +01009710 rule->arg.hlua_rule->args[i] = strdup(args[*cur_arg]);
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009711 if (!rule->arg.hlua_rule->args[i]) {
9712 memprintf(err, "out of memory error");
Christopher Faulet528526f2021-04-12 14:37:32 +02009713 goto error;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009714 }
9715 (*cur_arg)++;
9716 }
9717 rule->arg.hlua_rule->args[i] = NULL;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009718
Thierry FOURNIER42148732015-09-02 17:17:33 +02009719 rule->action = ACT_CUSTOM;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009720 rule->action_ptr = hlua_action;
Thierry FOURNIERafa80492015-08-19 09:04:15 +02009721 return ACT_RET_PRS_OK;
Christopher Faulet528526f2021-04-12 14:37:32 +02009722
9723 error:
9724 if (rule->arg.hlua_rule) {
9725 if (rule->arg.hlua_rule->args) {
9726 for (i = 0; i < fcn->nargs; i++)
9727 ha_free(&rule->arg.hlua_rule->args[i]);
9728 ha_free(&rule->arg.hlua_rule->args);
9729 }
9730 ha_free(&rule->arg.hlua_rule);
9731 }
9732 return ACT_RET_PRS_ERR;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009733}
9734
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009735static enum act_parse_ret action_register_service_http(const char **args, int *cur_arg, struct proxy *px,
9736 struct act_rule *rule, char **err)
9737{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02009738 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009739
Thierry FOURNIER718e2a72015-12-20 20:13:14 +01009740 /* HTTP applets are forbidden in tcp-request rules.
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05009741 * HTTP applet request requires everything initialized by
Thierry FOURNIER718e2a72015-12-20 20:13:14 +01009742 * "http_process_request" (analyzer flag AN_REQ_HTTP_INNER).
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05009743 * The applet will be immediately initialized, but its before
Thierry FOURNIER718e2a72015-12-20 20:13:14 +01009744 * the call of this analyzer.
9745 */
9746 if (rule->from != ACT_F_HTTP_REQ) {
9747 memprintf(err, "HTTP applets are forbidden from 'tcp-request' rulesets");
9748 return ACT_RET_PRS_ERR;
9749 }
9750
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009751 /* Memory for the rule. */
9752 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
9753 if (!rule->arg.hlua_rule) {
9754 memprintf(err, "out of memory error");
9755 return ACT_RET_PRS_ERR;
9756 }
9757
9758 /* Reference the Lua function and store the reference. */
Thierry Fournierad5345f2020-11-29 02:05:57 +01009759 rule->arg.hlua_rule->fcn = fcn;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009760
9761 /* TODO: later accept arguments. */
9762 rule->arg.hlua_rule->args = NULL;
9763
9764 /* Add applet pointer in the rule. */
9765 rule->applet.obj_type = OBJ_TYPE_APPLET;
9766 rule->applet.name = fcn->name;
9767 rule->applet.init = hlua_applet_http_init;
9768 rule->applet.fct = hlua_applet_http_fct;
9769 rule->applet.release = hlua_applet_http_release;
9770 rule->applet.timeout = hlua_timeout_applet;
9771
9772 return ACT_RET_PRS_OK;
9773}
9774
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009775/* This function is an LUA binding used for registering
9776 * "sample-conv" functions. It expects a converter name used
9777 * in the haproxy configuration file, and an LUA function.
9778 */
9779__LJMP static int hlua_register_action(lua_State *L)
9780{
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009781 struct action_kw_list *akl = NULL;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009782 const char *name;
9783 int ref;
9784 int len;
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009785 struct hlua_function *fcn = NULL;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009786 int nargs;
Thierry Fournierf67442e2020-11-28 20:41:07 +01009787 struct buffer *trash;
9788 struct action_kw *akw;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009789
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009790 /* Initialise the number of expected arguments at 0. */
9791 nargs = 0;
9792
9793 if (lua_gettop(L) < 3 || lua_gettop(L) > 4)
9794 WILL_LJMP(luaL_error(L, "'register_action' needs between 3 and 4 arguments"));
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009795
9796 /* First argument : converter name. */
9797 name = MAY_LJMP(luaL_checkstring(L, 1));
9798
9799 /* Second argument : environment. */
9800 if (lua_type(L, 2) != LUA_TTABLE)
9801 WILL_LJMP(luaL_error(L, "register_action: second argument must be a table of strings"));
9802
9803 /* Third argument : lua function. */
9804 ref = MAY_LJMP(hlua_checkfunction(L, 3));
9805
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08009806 /* Fourth argument : number of mandatory arguments expected on the configuration line. */
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009807 if (lua_gettop(L) >= 4)
9808 nargs = MAY_LJMP(luaL_checkinteger(L, 4));
9809
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08009810 /* browse the second argument as an array. */
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009811 lua_pushnil(L);
9812 while (lua_next(L, 2) != 0) {
9813 if (lua_type(L, -1) != LUA_TSTRING)
9814 WILL_LJMP(luaL_error(L, "register_action: second argument must be a table of strings"));
9815
Thierry Fournierf67442e2020-11-28 20:41:07 +01009816 /* Check if action exists */
9817 trash = get_trash_chunk();
9818 chunk_printf(trash, "lua.%s", name);
9819 if (strcmp(lua_tostring(L, -1), "tcp-req") == 0) {
9820 akw = tcp_req_cont_action(trash->area);
9821 } else if (strcmp(lua_tostring(L, -1), "tcp-res") == 0) {
9822 akw = tcp_res_cont_action(trash->area);
9823 } else if (strcmp(lua_tostring(L, -1), "http-req") == 0) {
9824 akw = action_http_req_custom(trash->area);
9825 } else if (strcmp(lua_tostring(L, -1), "http-res") == 0) {
9826 akw = action_http_res_custom(trash->area);
9827 } else {
9828 akw = NULL;
9829 }
9830 if (akw != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +01009831 fcn = akw->private;
9832 if (fcn->function_ref[hlua_state_id] != -1) {
9833 ha_warning("Trying to register action 'lua.%s' more than once. "
9834 "This will become a hard error in version 2.5.\n", name);
9835 }
9836 fcn->function_ref[hlua_state_id] = ref;
9837
9838 /* pop the environment string. */
9839 lua_pop(L, 1);
9840 continue;
Thierry Fournierf67442e2020-11-28 20:41:07 +01009841 }
9842
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009843 /* Check required environment. Only accepted "http" or "tcp". */
9844 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02009845 akl = calloc(1, sizeof(*akl) + sizeof(struct action_kw) * 2);
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009846 if (!akl)
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009847 goto alloc_error;;
Thierry Fournier62a22aa2020-11-28 21:06:35 +01009848 fcn = new_hlua_function();
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009849 if (!fcn)
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009850 goto alloc_error;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009851
9852 /* Fill fcn. */
9853 fcn->name = strdup(name);
9854 if (!fcn->name)
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009855 goto alloc_error;
Thierry Fournierc7492592020-11-28 23:57:24 +01009856 fcn->function_ref[hlua_state_id] = ref;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009857
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -07009858 /* Set the expected number of arguments. */
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009859 fcn->nargs = nargs;
9860
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009861 /* List head */
9862 akl->list.n = akl->list.p = NULL;
9863
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009864 /* action keyword. */
9865 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02009866 akl->kw[0].kw = calloc(1, len);
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009867 if (!akl->kw[0].kw)
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009868 goto alloc_error;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009869
9870 snprintf((char *)akl->kw[0].kw, len, "lua.%s", name);
9871
Amaury Denoyellee4a617c2021-05-06 15:33:09 +02009872 akl->kw[0].flags = 0;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009873 akl->kw[0].private = fcn;
9874 akl->kw[0].parse = action_register_lua;
9875
9876 /* select the action registering point. */
9877 if (strcmp(lua_tostring(L, -1), "tcp-req") == 0)
9878 tcp_req_cont_keywords_register(akl);
9879 else if (strcmp(lua_tostring(L, -1), "tcp-res") == 0)
9880 tcp_res_cont_keywords_register(akl);
9881 else if (strcmp(lua_tostring(L, -1), "http-req") == 0)
9882 http_req_keywords_register(akl);
9883 else if (strcmp(lua_tostring(L, -1), "http-res") == 0)
9884 http_res_keywords_register(akl);
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009885 else {
9886 release_hlua_function(fcn);
9887 if (akl)
9888 ha_free((char **)&(akl->kw[0].kw));
9889 ha_free(&akl);
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01009890 WILL_LJMP(luaL_error(L, "Lua action environment '%s' is unknown. "
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009891 "'tcp-req', 'tcp-res', 'http-req' or 'http-res' "
9892 "are expected.", lua_tostring(L, -1)));
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009893 }
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009894
9895 /* pop the environment string. */
9896 lua_pop(L, 1);
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009897
9898 /* reset for next loop */
9899 akl = NULL;
9900 fcn = NULL;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009901 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009902 return ACT_RET_PRS_OK;
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009903
9904 alloc_error:
9905 release_hlua_function(fcn);
9906 ha_free(&akl);
9907 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
9908 return 0; /* Never reached */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009909}
9910
9911static enum act_parse_ret action_register_service_tcp(const char **args, int *cur_arg, struct proxy *px,
9912 struct act_rule *rule, char **err)
9913{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02009914 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009915
Christopher Faulet280f85b2019-07-15 15:02:04 +02009916 if (px->mode == PR_MODE_HTTP) {
9917 memprintf(err, "Lua TCP services cannot be used on HTTP proxies");
Christopher Fauletafd8f102018-11-08 11:34:21 +01009918 return ACT_RET_PRS_ERR;
9919 }
9920
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009921 /* Memory for the rule. */
9922 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
9923 if (!rule->arg.hlua_rule) {
9924 memprintf(err, "out of memory error");
9925 return ACT_RET_PRS_ERR;
9926 }
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009927
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009928 /* Reference the Lua function and store the reference. */
Thierry Fournierad5345f2020-11-29 02:05:57 +01009929 rule->arg.hlua_rule->fcn = fcn;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009930
9931 /* TODO: later accept arguments. */
9932 rule->arg.hlua_rule->args = NULL;
9933
9934 /* Add applet pointer in the rule. */
9935 rule->applet.obj_type = OBJ_TYPE_APPLET;
9936 rule->applet.name = fcn->name;
9937 rule->applet.init = hlua_applet_tcp_init;
9938 rule->applet.fct = hlua_applet_tcp_fct;
9939 rule->applet.release = hlua_applet_tcp_release;
9940 rule->applet.timeout = hlua_timeout_applet;
9941
9942 return 0;
9943}
9944
9945/* This function is an LUA binding used for registering
9946 * "sample-conv" functions. It expects a converter name used
9947 * in the haproxy configuration file, and an LUA function.
9948 */
9949__LJMP static int hlua_register_service(lua_State *L)
9950{
9951 struct action_kw_list *akl;
9952 const char *name;
9953 const char *env;
9954 int ref;
9955 int len;
Christopher Faulet5c028d72021-04-12 15:11:44 +02009956 struct hlua_function *fcn = NULL;
Thierry Fournierf67442e2020-11-28 20:41:07 +01009957 struct buffer *trash;
9958 struct action_kw *akw;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009959
9960 MAY_LJMP(check_args(L, 3, "register_service"));
9961
9962 /* First argument : converter name. */
9963 name = MAY_LJMP(luaL_checkstring(L, 1));
9964
9965 /* Second argument : environment. */
9966 env = MAY_LJMP(luaL_checkstring(L, 2));
9967
9968 /* Third argument : lua function. */
9969 ref = MAY_LJMP(hlua_checkfunction(L, 3));
9970
Thierry Fournierf67442e2020-11-28 20:41:07 +01009971 /* Check for service already registered */
9972 trash = get_trash_chunk();
9973 chunk_printf(trash, "lua.%s", name);
9974 akw = service_find(trash->area);
9975 if (akw != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +01009976 fcn = akw->private;
9977 if (fcn->function_ref[hlua_state_id] != -1) {
9978 ha_warning("Trying to register service 'lua.%s' more than once. "
9979 "This will become a hard error in version 2.5.\n", name);
9980 }
9981 fcn->function_ref[hlua_state_id] = ref;
9982 return 0;
Thierry Fournierf67442e2020-11-28 20:41:07 +01009983 }
9984
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009985 /* Allocate and fill the sample fetch keyword struct. */
9986 akl = calloc(1, sizeof(*akl) + sizeof(struct action_kw) * 2);
9987 if (!akl)
Christopher Faulet5c028d72021-04-12 15:11:44 +02009988 goto alloc_error;
Thierry Fournier62a22aa2020-11-28 21:06:35 +01009989 fcn = new_hlua_function();
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009990 if (!fcn)
Christopher Faulet5c028d72021-04-12 15:11:44 +02009991 goto alloc_error;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009992
9993 /* Fill fcn. */
9994 len = strlen("<lua.>") + strlen(name) + 1;
9995 fcn->name = calloc(1, len);
9996 if (!fcn->name)
Christopher Faulet5c028d72021-04-12 15:11:44 +02009997 goto alloc_error;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009998 snprintf((char *)fcn->name, len, "<lua.%s>", name);
Thierry Fournierc7492592020-11-28 23:57:24 +01009999 fcn->function_ref[hlua_state_id] = ref;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010000
10001 /* List head */
10002 akl->list.n = akl->list.p = NULL;
10003
10004 /* converter keyword. */
10005 len = strlen("lua.") + strlen(name) + 1;
10006 akl->kw[0].kw = calloc(1, len);
10007 if (!akl->kw[0].kw)
Christopher Faulet5c028d72021-04-12 15:11:44 +020010008 goto alloc_error;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010009
10010 snprintf((char *)akl->kw[0].kw, len, "lua.%s", name);
10011
Thierry FOURNIER / OZON.IO02564fd2016-11-12 11:07:05 +010010012 /* Check required environment. Only accepted "http" or "tcp". */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010013 if (strcmp(env, "tcp") == 0)
10014 akl->kw[0].parse = action_register_service_tcp;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010015 else if (strcmp(env, "http") == 0)
10016 akl->kw[0].parse = action_register_service_http;
Christopher Faulet5c028d72021-04-12 15:11:44 +020010017 else {
10018 release_hlua_function(fcn);
10019 if (akl)
10020 ha_free((char **)&(akl->kw[0].kw));
10021 ha_free(&akl);
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +010010022 WILL_LJMP(luaL_error(L, "Lua service environment '%s' is unknown. "
Eric Salamafe7456f2017-12-21 14:30:07 +010010023 "'tcp' or 'http' are expected.", env));
Christopher Faulet5c028d72021-04-12 15:11:44 +020010024 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010025
Amaury Denoyellee4a617c2021-05-06 15:33:09 +020010026 akl->kw[0].flags = 0;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010027 akl->kw[0].private = fcn;
10028
10029 /* End of array. */
10030 memset(&akl->kw[1], 0, sizeof(*akl->kw));
10031
10032 /* Register this new converter */
10033 service_keywords_register(akl);
10034
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010035 return 0;
Christopher Faulet5c028d72021-04-12 15:11:44 +020010036
10037 alloc_error:
10038 release_hlua_function(fcn);
10039 ha_free(&akl);
10040 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
10041 return 0; /* Never reached */
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010042}
10043
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010044/* This function initialises Lua cli handler. It copies the
10045 * arguments in the Lua stack and create channel IO objects.
10046 */
Aurélien Nephtaliabbf6072018-04-18 13:26:46 +020010047static int hlua_cli_parse_fct(char **args, char *payload, struct appctx *appctx, void *private)
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010048{
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010049 struct hlua_cli_ctx *ctx = applet_reserve_svcctx(appctx, sizeof(*ctx));
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010050 struct hlua *hlua;
10051 struct hlua_function *fcn;
10052 int i;
10053 const char *error;
10054
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010055 fcn = private;
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010056 ctx->fcn = private;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +010010057
Willy Tarreaubafbe012017-11-24 17:34:44 +010010058 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +010010059 if (!hlua) {
10060 SEND_ERR(NULL, "Lua cli '%s': out of memory.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +010010061 return 1;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +010010062 }
10063 HLUA_INIT(hlua);
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010064 ctx->hlua = hlua;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010065
10066 /* Create task used by signal to wakeup applets.
Ilya Shipitsind4259502020-04-08 01:07:56 +050010067 * We use the same wakeup function than the Lua applet_tcp and
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010068 * applet_http. It is absolutely compatible.
10069 */
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010070 ctx->task = task_new_here();
10071 if (!ctx->task) {
Thierry FOURNIERffbf5692016-12-16 11:14:06 +010010072 SEND_ERR(NULL, "Lua cli '%s': out of memory.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +010010073 goto error;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010074 }
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010075 ctx->task->nice = 0;
10076 ctx->task->context = appctx;
10077 ctx->task->process = hlua_applet_wakeup;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010078
10079 /* Initialises the Lua context */
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010080 if (!hlua_ctx_init(hlua, fcn_ref_to_stack_id(fcn), ctx->task, 0)) {
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010081 SEND_ERR(NULL, "Lua cli '%s': can't initialize Lua context.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +010010082 goto error;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010083 }
10084
10085 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010086 if (!SET_SAFE_LJMP(hlua)) {
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010087 if (lua_type(hlua->T, -1) == LUA_TSTRING)
10088 error = lua_tostring(hlua->T, -1);
10089 else
10090 error = "critical error";
10091 SEND_ERR(NULL, "Lua cli '%s': %s.\n", fcn->name, error);
10092 goto error;
10093 }
10094
10095 /* Check stack available size. */
10096 if (!lua_checkstack(hlua->T, 2)) {
10097 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
10098 goto error;
10099 }
10100
10101 /* Restore the function in the stack. */
Thierry Fournierc7492592020-11-28 23:57:24 +010010102 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, fcn->function_ref[hlua->state_id]);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010103
10104 /* Once the arguments parsed, the CLI is like an AppletTCP,
10105 * so push AppletTCP in the stack.
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010106 */
10107 if (!hlua_applet_tcp_new(hlua->T, appctx)) {
10108 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
10109 goto error;
10110 }
10111 hlua->nargs = 1;
10112
10113 /* push keywords in the stack. */
10114 for (i = 0; *args[i]; i++) {
10115 /* Check stack available size. */
10116 if (!lua_checkstack(hlua->T, 1)) {
10117 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
10118 goto error;
10119 }
10120 lua_pushstring(hlua->T, args[i]);
10121 hlua->nargs++;
10122 }
10123
10124 /* We must initialize the execution timeouts. */
10125 hlua->max_time = hlua_timeout_session;
10126
10127 /* At this point the execution is safe. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010128 RESET_SAFE_LJMP(hlua);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010129
10130 /* It's ok */
10131 return 0;
10132
10133 /* It's not ok. */
10134error:
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010135 RESET_SAFE_LJMP(hlua);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010136 hlua_ctx_destroy(hlua);
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010137 ctx->hlua = NULL;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010138 return 1;
10139}
10140
10141static int hlua_cli_io_handler_fct(struct appctx *appctx)
10142{
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010143 struct hlua_cli_ctx *ctx = appctx->svcctx;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010144 struct hlua *hlua;
Christopher Faulet908628c2022-03-25 16:43:49 +010010145 struct conn_stream *cs;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010146 struct hlua_function *fcn;
10147
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010148 hlua = ctx->hlua;
Willy Tarreau0698c802022-05-11 14:09:57 +020010149 cs = appctx_cs(appctx);
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010150 fcn = ctx->fcn;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010151
10152 /* If the stream is disconnect or closed, ldo nothing. */
Christopher Faulet62e75742022-03-31 09:16:34 +020010153 if (unlikely(cs->state == CS_ST_DIS || cs->state == CS_ST_CLO))
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010154 return 1;
10155
10156 /* Execute the function. */
10157 switch (hlua_ctx_resume(hlua, 1)) {
10158
10159 /* finished. */
10160 case HLUA_E_OK:
10161 return 1;
10162
10163 /* yield. */
10164 case HLUA_E_AGAIN:
10165 /* We want write. */
10166 if (HLUA_IS_WAKERESWR(hlua))
Christopher Fauleta0bdec32022-04-04 07:51:21 +020010167 cs_rx_room_blk(cs);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010168 /* Set the timeout. */
10169 if (hlua->wake_time != TICK_ETERNITY)
10170 task_schedule(hlua->task, hlua->wake_time);
10171 return 0;
10172
10173 /* finished with error. */
10174 case HLUA_E_ERRMSG:
10175 /* Display log. */
10176 SEND_ERR(NULL, "Lua cli '%s': %s.\n",
10177 fcn->name, lua_tostring(hlua->T, -1));
10178 lua_pop(hlua->T, 1);
10179 return 1;
10180
Thierry Fournierd5b073c2018-05-21 19:42:47 +020010181 case HLUA_E_ETMOUT:
10182 SEND_ERR(NULL, "Lua converter '%s': execution timeout.\n",
10183 fcn->name);
10184 return 1;
10185
10186 case HLUA_E_NOMEM:
10187 SEND_ERR(NULL, "Lua converter '%s': out of memory error.\n",
10188 fcn->name);
10189 return 1;
10190
10191 case HLUA_E_YIELD: /* unexpected */
10192 SEND_ERR(NULL, "Lua converter '%s': yield not allowed.\n",
10193 fcn->name);
10194 return 1;
10195
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010196 case HLUA_E_ERR:
10197 /* Display log. */
10198 SEND_ERR(NULL, "Lua cli '%s' return an unknown error.\n",
10199 fcn->name);
10200 return 1;
10201
10202 default:
10203 return 1;
10204 }
10205
10206 return 1;
10207}
10208
10209static void hlua_cli_io_release_fct(struct appctx *appctx)
10210{
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010211 struct hlua_cli_ctx *ctx = appctx->svcctx;
10212
10213 hlua_ctx_destroy(ctx->hlua);
10214 ctx->hlua = NULL;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010215}
10216
10217/* This function is an LUA binding used for registering
10218 * new keywords in the cli. It expects a list of keywords
10219 * which are the "path". It is limited to 5 keywords. A
10220 * description of the command, a function to be executed
10221 * for the parsing and a function for io handlers.
10222 */
10223__LJMP static int hlua_register_cli(lua_State *L)
10224{
10225 struct cli_kw_list *cli_kws;
10226 const char *message;
10227 int ref_io;
10228 int len;
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010229 struct hlua_function *fcn = NULL;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010230 int index;
10231 int i;
Thierry Fournierf67442e2020-11-28 20:41:07 +010010232 struct buffer *trash;
10233 const char *kw[5];
10234 struct cli_kw *cli_kw;
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010235 const char *errmsg;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010236
10237 MAY_LJMP(check_args(L, 3, "register_cli"));
10238
10239 /* First argument : an array of maximum 5 keywords. */
10240 if (!lua_istable(L, 1))
10241 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table"));
10242
10243 /* Second argument : string with contextual message. */
10244 message = MAY_LJMP(luaL_checkstring(L, 2));
10245
10246 /* Third and fourth argument : lua function. */
10247 ref_io = MAY_LJMP(hlua_checkfunction(L, 3));
10248
Thierry Fournierf67442e2020-11-28 20:41:07 +010010249 /* Check for CLI service already registered */
10250 trash = get_trash_chunk();
10251 index = 0;
10252 lua_pushnil(L);
10253 memset(kw, 0, sizeof(kw));
10254 while (lua_next(L, 1) != 0) {
10255 if (index >= CLI_PREFIX_KW_NB)
10256 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table with a maximum of 5 entries"));
10257 if (lua_type(L, -1) != LUA_TSTRING)
10258 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table filled with strings"));
10259 kw[index] = lua_tostring(L, -1);
10260 if (index == 0)
10261 chunk_printf(trash, "%s", kw[index]);
10262 else
10263 chunk_appendf(trash, " %s", kw[index]);
10264 index++;
10265 lua_pop(L, 1);
10266 }
10267 cli_kw = cli_find_kw_exact((char **)kw);
10268 if (cli_kw != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +010010269 fcn = cli_kw->private;
10270 if (fcn->function_ref[hlua_state_id] != -1) {
10271 ha_warning("Trying to register CLI keyword 'lua.%s' more than once. "
10272 "This will become a hard error in version 2.5.\n", trash->area);
10273 }
10274 fcn->function_ref[hlua_state_id] = ref_io;
10275 return 0;
Thierry Fournierf67442e2020-11-28 20:41:07 +010010276 }
10277
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010278 /* Allocate and fill the sample fetch keyword struct. */
10279 cli_kws = calloc(1, sizeof(*cli_kws) + sizeof(struct cli_kw) * 2);
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010280 if (!cli_kws) {
10281 errmsg = "Lua out of memory error.";
10282 goto error;
10283 }
Thierry Fournier62a22aa2020-11-28 21:06:35 +010010284 fcn = new_hlua_function();
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010285 if (!fcn) {
10286 errmsg = "Lua out of memory error.";
10287 goto error;
10288 }
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010289
10290 /* Fill path. */
10291 index = 0;
10292 lua_pushnil(L);
10293 while(lua_next(L, 1) != 0) {
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010294 if (index >= 5) {
10295 errmsg = "1st argument must be a table with a maximum of 5 entries";
10296 goto error;
10297 }
10298 if (lua_type(L, -1) != LUA_TSTRING) {
10299 errmsg = "1st argument must be a table filled with strings";
10300 goto error;
10301 }
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010302 cli_kws->kw[0].str_kw[index] = strdup(lua_tostring(L, -1));
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010303 if (!cli_kws->kw[0].str_kw[index]) {
10304 errmsg = "Lua out of memory error.";
10305 goto error;
10306 }
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010307 index++;
10308 lua_pop(L, 1);
10309 }
10310
10311 /* Copy help message. */
10312 cli_kws->kw[0].usage = strdup(message);
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010313 if (!cli_kws->kw[0].usage) {
10314 errmsg = "Lua out of memory error.";
10315 goto error;
10316 }
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010317
10318 /* Fill fcn io handler. */
10319 len = strlen("<lua.cli>") + 1;
10320 for (i = 0; i < index; i++)
10321 len += strlen(cli_kws->kw[0].str_kw[i]) + 1;
10322 fcn->name = calloc(1, len);
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010323 if (!fcn->name) {
10324 errmsg = "Lua out of memory error.";
10325 goto error;
10326 }
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010327 strncat((char *)fcn->name, "<lua.cli", len);
10328 for (i = 0; i < index; i++) {
10329 strncat((char *)fcn->name, ".", len);
10330 strncat((char *)fcn->name, cli_kws->kw[0].str_kw[i], len);
10331 }
10332 strncat((char *)fcn->name, ">", len);
Thierry Fournierc7492592020-11-28 23:57:24 +010010333 fcn->function_ref[hlua_state_id] = ref_io;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010334
10335 /* Fill last entries. */
10336 cli_kws->kw[0].private = fcn;
10337 cli_kws->kw[0].parse = hlua_cli_parse_fct;
10338 cli_kws->kw[0].io_handler = hlua_cli_io_handler_fct;
10339 cli_kws->kw[0].io_release = hlua_cli_io_release_fct;
10340
10341 /* Register this new converter */
10342 cli_register_kw(cli_kws);
10343
10344 return 0;
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010345
10346 error:
10347 release_hlua_function(fcn);
10348 if (cli_kws) {
10349 for (i = 0; i < index; i++)
10350 ha_free((char **)&(cli_kws->kw[0].str_kw[i]));
10351 ha_free((char **)&(cli_kws->kw[0].usage));
10352 }
10353 ha_free(&cli_kws);
10354 WILL_LJMP(luaL_error(L, errmsg));
10355 return 0; /* Never reached */
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010356}
10357
Christopher Faulet69c581a2021-05-31 08:54:04 +020010358static int hlua_filter_init_per_thread(struct proxy *px, struct flt_conf *fconf)
10359{
10360 struct hlua_flt_config *conf = fconf->conf;
10361 lua_State *L;
10362 int error, pos, state_id, flt_ref;
10363
10364 state_id = reg_flt_to_stack_id(conf->reg);
10365 L = hlua_states[state_id];
10366 pos = lua_gettop(L);
10367
10368 /* The filter parsing function */
10369 lua_rawgeti(L, LUA_REGISTRYINDEX, conf->reg->fun_ref[state_id]);
10370
10371 /* Push the filter class on the stack and resolve all callbacks */
10372 lua_rawgeti(L, LUA_REGISTRYINDEX, conf->reg->flt_ref[state_id]);
10373
10374 /* Duplicate the filter class so each filter will have its own copy */
10375 lua_newtable(L);
10376 lua_pushnil(L);
10377
10378 while (lua_next(L, pos+2)) {
10379 lua_pushvalue(L, -2);
10380 lua_insert(L, -2);
10381 lua_settable(L, -4);
10382 }
10383 flt_ref = luaL_ref(L, LUA_REGISTRYINDEX);
10384
10385 /* Remove the original lua filter class from the stack */
10386 lua_pop(L, 1);
10387
10388 /* Push the copy on the stack */
10389 lua_rawgeti(L, LUA_REGISTRYINDEX, flt_ref);
10390
10391 /* extra args are pushed in a table */
10392 lua_newtable(L);
10393 for (pos = 0; conf->args[pos]; pos++) {
10394 /* Check stack available size. */
10395 if (!lua_checkstack(L, 1)) {
10396 ha_alert("Lua filter '%s' : Lua error : full stack.", conf->reg->name);
10397 goto error;
10398 }
10399 lua_pushstring(L, conf->args[pos]);
10400 lua_rawseti(L, -2, lua_rawlen(L, -2) + 1);
10401 }
10402
10403 error = lua_pcall(L, 2, LUA_MULTRET, 0);
10404 switch (error) {
10405 case LUA_OK:
10406 /* replace the filter ref */
10407 conf->ref[state_id] = flt_ref;
10408 break;
10409 case LUA_ERRRUN:
10410 ha_alert("Lua filter '%s' : runtime error : %s", conf->reg->name, lua_tostring(L, -1));
10411 goto error;
10412 case LUA_ERRMEM:
10413 ha_alert("Lua filter '%s' : out of memory error", conf->reg->name);
10414 goto error;
10415 case LUA_ERRERR:
10416 ha_alert("Lua filter '%s' : message handler error : %s", conf->reg->name, lua_tostring(L, -1));
10417 goto error;
10418#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM <= 503
10419 case LUA_ERRGCMM:
10420 ha_alert("Lua filter '%s' : garbage collector error : %s", conf->reg->name, lua_tostring(L, -1));
10421 goto error;
10422#endif
10423 default:
Ilya Shipitsinff0f2782021-08-22 22:18:07 +050010424 ha_alert("Lua filter '%s' : unknown error : %s", conf->reg->name, lua_tostring(L, -1));
Christopher Faulet69c581a2021-05-31 08:54:04 +020010425 goto error;
10426 }
10427
10428 lua_settop(L, 0);
10429 return 0;
10430
10431 error:
10432 lua_settop(L, 0);
10433 return -1;
10434}
10435
10436static void hlua_filter_deinit_per_thread(struct proxy *px, struct flt_conf *fconf)
10437{
10438 struct hlua_flt_config *conf = fconf->conf;
10439 lua_State *L;
10440 int state_id;
10441
10442 if (!conf)
10443 return;
10444
10445 state_id = reg_flt_to_stack_id(conf->reg);
10446 L = hlua_states[state_id];
10447 luaL_unref(L, LUA_REGISTRYINDEX, conf->ref[state_id]);
10448}
10449
10450static int hlua_filter_init(struct proxy *px, struct flt_conf *fconf)
10451{
10452 struct hlua_flt_config *conf = fconf->conf;
10453 int state_id = reg_flt_to_stack_id(conf->reg);
10454
10455 /* Rely on per-thread init for global scripts */
10456 if (!state_id)
10457 return hlua_filter_init_per_thread(px, fconf);
10458 return 0;
10459}
10460
10461static void hlua_filter_deinit(struct proxy *px, struct flt_conf *fconf)
10462{
10463
10464 if (fconf->conf) {
10465 struct hlua_flt_config *conf = fconf->conf;
10466 int state_id = reg_flt_to_stack_id(conf->reg);
10467 int pos;
10468
10469 /* Rely on per-thread deinit for global scripts */
10470 if (!state_id)
10471 hlua_filter_deinit_per_thread(px, fconf);
10472
10473 for (pos = 0; conf->args[pos]; pos++)
10474 free(conf->args[pos]);
10475 free(conf->args);
10476 }
10477 ha_free(&fconf->conf);
10478 ha_free((char **)&fconf->id);
10479 ha_free(&fconf->ops);
10480}
10481
10482static int hlua_filter_new(struct stream *s, struct filter *filter)
10483{
10484 struct hlua_flt_config *conf = FLT_CONF(filter);
10485 struct hlua_flt_ctx *flt_ctx = NULL;
10486 int ret = 1;
10487
10488 /* In the execution wrappers linked with a stream, the
10489 * Lua context can be not initialized. This behavior
10490 * permits to save performances because a systematic
10491 * Lua initialization cause 5% performances loss.
10492 */
10493 if (!s->hlua) {
10494 struct hlua *hlua;
10495
10496 hlua = pool_alloc(pool_head_hlua);
10497 if (!hlua) {
10498 SEND_ERR(s->be, "Lua filter '%s': can't initialize Lua context.\n",
10499 conf->reg->name);
10500 ret = 0;
10501 goto end;
10502 }
10503 HLUA_INIT(hlua);
10504 s->hlua = hlua;
10505 if (!hlua_ctx_init(s->hlua, reg_flt_to_stack_id(conf->reg), s->task, 0)) {
10506 SEND_ERR(s->be, "Lua filter '%s': can't initialize Lua context.\n",
10507 conf->reg->name);
10508 ret = 0;
10509 goto end;
10510 }
10511 }
10512
10513 flt_ctx = pool_zalloc(pool_head_hlua_flt_ctx);
10514 if (!flt_ctx) {
10515 SEND_ERR(s->be, "Lua filter '%s': can't initialize filter Lua context.\n",
10516 conf->reg->name);
10517 ret = 0;
10518 goto end;
10519 }
10520 flt_ctx->hlua[0] = pool_alloc(pool_head_hlua);
10521 flt_ctx->hlua[1] = pool_alloc(pool_head_hlua);
10522 if (!flt_ctx->hlua[0] || !flt_ctx->hlua[1]) {
10523 SEND_ERR(s->be, "Lua filter '%s': can't initialize filter Lua context.\n",
10524 conf->reg->name);
10525 ret = 0;
10526 goto end;
10527 }
10528 HLUA_INIT(flt_ctx->hlua[0]);
10529 HLUA_INIT(flt_ctx->hlua[1]);
10530 if (!hlua_ctx_init(flt_ctx->hlua[0], reg_flt_to_stack_id(conf->reg), s->task, 0) ||
10531 !hlua_ctx_init(flt_ctx->hlua[1], reg_flt_to_stack_id(conf->reg), s->task, 0)) {
10532 SEND_ERR(s->be, "Lua filter '%s': can't initialize filter Lua context.\n",
10533 conf->reg->name);
10534 ret = 0;
10535 goto end;
10536 }
10537
10538 if (!HLUA_IS_RUNNING(s->hlua)) {
10539 /* The following Lua calls can fail. */
10540 if (!SET_SAFE_LJMP(s->hlua)) {
10541 const char *error;
10542
10543 if (lua_type(s->hlua->T, -1) == LUA_TSTRING)
10544 error = lua_tostring(s->hlua->T, -1);
10545 else
10546 error = "critical error";
10547 SEND_ERR(s->be, "Lua filter '%s': %s.\n", conf->reg->name, error);
10548 ret = 0;
10549 goto end;
10550 }
10551
10552 /* Check stack size. */
10553 if (!lua_checkstack(s->hlua->T, 1)) {
10554 SEND_ERR(s->be, "Lua filter '%s': full stack.\n", conf->reg->name);
Tim Duesterhus22817382021-09-11 23:17:25 +020010555 RESET_SAFE_LJMP(s->hlua);
Christopher Faulet69c581a2021-05-31 08:54:04 +020010556 ret = 0;
10557 goto end;
10558 }
10559
10560 lua_rawgeti(s->hlua->T, LUA_REGISTRYINDEX, conf->ref[s->hlua->state_id]);
10561 if (lua_getfield(s->hlua->T, -1, "new") != LUA_TFUNCTION) {
10562 SEND_ERR(s->be, "Lua filter '%s': 'new' field is not a function.\n",
10563 conf->reg->name);
10564 RESET_SAFE_LJMP(s->hlua);
10565 ret = 0;
10566 goto end;
10567 }
10568 lua_insert(s->hlua->T, -2);
10569
10570 /* Push the copy on the stack */
10571 s->hlua->nargs = 1;
10572
10573 /* We must initialize the execution timeouts. */
10574 s->hlua->max_time = hlua_timeout_session;
10575
10576 /* At this point the execution is safe. */
10577 RESET_SAFE_LJMP(s->hlua);
10578 }
10579
10580 switch (hlua_ctx_resume(s->hlua, 0)) {
10581 case HLUA_E_OK:
10582 /* Nothing returned or not a table, ignore the filter for current stream */
10583 if (!lua_gettop(s->hlua->T) || !lua_istable(s->hlua->T, 1)) {
10584 ret = 0;
10585 goto end;
10586 }
10587
10588 /* Attached the filter pointer to the ctx */
10589 lua_pushstring(s->hlua->T, "__filter");
10590 lua_pushlightuserdata(s->hlua->T, filter);
10591 lua_settable(s->hlua->T, -3);
10592
10593 /* Save a ref on the filter ctx */
10594 lua_pushvalue(s->hlua->T, 1);
10595 flt_ctx->ref = luaL_ref(s->hlua->T, LUA_REGISTRYINDEX);
10596 filter->ctx = flt_ctx;
10597 break;
10598 case HLUA_E_ERRMSG:
10599 SEND_ERR(s->be, "Lua filter '%s' : %s.\n", conf->reg->name, lua_tostring(s->hlua->T, -1));
10600 ret = -1;
10601 goto end;
10602 case HLUA_E_ETMOUT:
10603 SEND_ERR(s->be, "Lua filter '%s' : 'new' execution timeout.\n", conf->reg->name);
10604 ret = 0;
10605 goto end;
10606 case HLUA_E_NOMEM:
10607 SEND_ERR(s->be, "Lua filter '%s' : out of memory error.\n", conf->reg->name);
10608 ret = 0;
10609 goto end;
10610 case HLUA_E_AGAIN:
10611 case HLUA_E_YIELD:
10612 SEND_ERR(s->be, "Lua filter '%s': yield functions like core.tcp() or core.sleep()"
10613 " are not allowed from 'new' function.\n", conf->reg->name);
10614 ret = 0;
10615 goto end;
10616 case HLUA_E_ERR:
10617 SEND_ERR(s->be, "Lua filter '%s': 'new' returns an unknown error.\n", conf->reg->name);
10618 ret = 0;
10619 goto end;
10620 default:
10621 ret = 0;
10622 goto end;
10623 }
10624
10625 end:
10626 if (s->hlua)
10627 lua_settop(s->hlua->T, 0);
10628 if (ret <= 0) {
10629 if (flt_ctx) {
10630 hlua_ctx_destroy(flt_ctx->hlua[0]);
10631 hlua_ctx_destroy(flt_ctx->hlua[1]);
10632 pool_free(pool_head_hlua_flt_ctx, flt_ctx);
10633 }
10634 }
10635 return ret;
10636}
10637
10638static void hlua_filter_delete(struct stream *s, struct filter *filter)
10639{
10640 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10641
10642 luaL_unref(s->hlua->T, LUA_REGISTRYINDEX, flt_ctx->ref);
10643 hlua_ctx_destroy(flt_ctx->hlua[0]);
10644 hlua_ctx_destroy(flt_ctx->hlua[1]);
10645 pool_free(pool_head_hlua_flt_ctx, flt_ctx);
10646 filter->ctx = NULL;
10647}
10648
Christopher Faulet9f55a502020-02-25 15:21:02 +010010649static int hlua_filter_from_payload(struct filter *filter)
10650{
10651 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10652
10653 return (flt_ctx && !!(flt_ctx->flags & HLUA_FLT_CTX_FL_PAYLOAD));
10654}
10655
Christopher Fauletc404f112020-02-26 15:03:09 +010010656static int hlua_filter_callback(struct stream *s, struct filter *filter, const char *fun,
10657 int dir, unsigned int flags)
10658{
10659 struct hlua *flt_hlua;
10660 struct hlua_flt_config *conf = FLT_CONF(filter);
10661 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10662 unsigned int hflags = HLUA_TXN_FLT_CTX;
10663 int ret = 1;
10664
10665 flt_hlua = flt_ctx->hlua[(dir == SMP_OPT_DIR_REQ ? 0 : 1)];
10666 if (!flt_hlua)
10667 goto end;
10668
10669 if (!HLUA_IS_RUNNING(flt_hlua)) {
10670 int extra_idx = lua_gettop(flt_hlua->T);
10671
10672 /* The following Lua calls can fail. */
10673 if (!SET_SAFE_LJMP(flt_hlua)) {
10674 const char *error;
10675
10676 if (lua_type(flt_hlua->T, -1) == LUA_TSTRING)
10677 error = lua_tostring(flt_hlua->T, -1);
10678 else
10679 error = "critical error";
10680 SEND_ERR(s->be, "Lua filter '%s': %s.\n", conf->reg->name, error);
10681 goto end;
10682 }
10683
10684 /* Check stack size. */
10685 if (!lua_checkstack(flt_hlua->T, 3)) {
10686 SEND_ERR(s->be, "Lua filter '%s': full stack.\n", conf->reg->name);
10687 RESET_SAFE_LJMP(flt_hlua);
10688 goto end;
10689 }
10690
10691 lua_rawgeti(flt_hlua->T, LUA_REGISTRYINDEX, flt_ctx->ref);
10692 if (lua_getfield(flt_hlua->T, -1, fun) != LUA_TFUNCTION) {
10693 RESET_SAFE_LJMP(flt_hlua);
10694 goto end;
10695 }
10696 lua_insert(flt_hlua->T, -2);
10697
10698 if (!hlua_txn_new(flt_hlua->T, s, s->be, dir, hflags)) {
10699 SEND_ERR(s->be, "Lua filter '%s': full stack.\n", conf->reg->name);
10700 RESET_SAFE_LJMP(flt_hlua);
10701 goto end;
10702 }
10703 flt_hlua->nargs = 2;
10704
10705 if (flags & HLUA_FLT_CB_ARG_CHN) {
10706 if (dir == SMP_OPT_DIR_REQ)
10707 lua_getfield(flt_hlua->T, -1, "req");
10708 else
10709 lua_getfield(flt_hlua->T, -1, "res");
10710 if (lua_type(flt_hlua->T, -1) == LUA_TTABLE) {
10711 lua_pushstring(flt_hlua->T, "__filter");
10712 lua_pushlightuserdata(flt_hlua->T, filter);
10713 lua_settable(flt_hlua->T, -3);
10714 }
10715 flt_hlua->nargs++;
10716 }
10717 else if (flags & HLUA_FLT_CB_ARG_HTTP_MSG) {
Christopher Fauleteae8afa2020-02-26 17:15:48 +010010718 if (dir == SMP_OPT_DIR_REQ)
10719 lua_getfield(flt_hlua->T, -1, "http_req");
10720 else
10721 lua_getfield(flt_hlua->T, -1, "http_res");
10722 if (lua_type(flt_hlua->T, -1) == LUA_TTABLE) {
10723 lua_pushstring(flt_hlua->T, "__filter");
10724 lua_pushlightuserdata(flt_hlua->T, filter);
10725 lua_settable(flt_hlua->T, -3);
10726 }
10727 flt_hlua->nargs++;
Christopher Fauletc404f112020-02-26 15:03:09 +010010728 }
10729
10730 /* Check stack size. */
10731 if (!lua_checkstack(flt_hlua->T, 1)) {
10732 SEND_ERR(s->be, "Lua filter '%s': full stack.\n", conf->reg->name);
10733 RESET_SAFE_LJMP(flt_hlua);
10734 goto end;
10735 }
10736
10737 while (extra_idx--) {
10738 lua_pushvalue(flt_hlua->T, 1);
10739 lua_remove(flt_hlua->T, 1);
10740 flt_hlua->nargs++;
10741 }
10742
10743 /* We must initialize the execution timeouts. */
10744 flt_hlua->max_time = hlua_timeout_session;
10745
10746 /* At this point the execution is safe. */
10747 RESET_SAFE_LJMP(flt_hlua);
10748 }
10749
10750 switch (hlua_ctx_resume(flt_hlua, !(flags & HLUA_FLT_CB_FINAL))) {
10751 case HLUA_E_OK:
10752 /* Catch the return value if it required */
10753 if ((flags & HLUA_FLT_CB_RETVAL) && lua_gettop(flt_hlua->T) > 0) {
10754 ret = lua_tointeger(flt_hlua->T, -1);
10755 lua_settop(flt_hlua->T, 0); /* Empty the stack. */
10756 }
10757
10758 /* Set timeout in the required channel. */
10759 if (flt_hlua->wake_time != TICK_ETERNITY) {
10760 if (dir == SMP_OPT_DIR_REQ)
10761 s->req.analyse_exp = flt_hlua->wake_time;
10762 else
10763 s->res.analyse_exp = flt_hlua->wake_time;
10764 }
10765 break;
10766 case HLUA_E_AGAIN:
10767 /* Set timeout in the required channel. */
10768 if (flt_hlua->wake_time != TICK_ETERNITY) {
10769 if (dir == SMP_OPT_DIR_REQ)
10770 s->req.analyse_exp = flt_hlua->wake_time;
10771 else
10772 s->res.analyse_exp = flt_hlua->wake_time;
10773 }
10774 /* Some actions can be wake up when a "write" event
10775 * is detected on a response channel. This is useful
10776 * only for actions targeted on the requests.
10777 */
10778 if (HLUA_IS_WAKERESWR(flt_hlua))
10779 s->res.flags |= CF_WAKE_WRITE;
10780 if (HLUA_IS_WAKEREQWR(flt_hlua))
10781 s->req.flags |= CF_WAKE_WRITE;
10782 ret = 0;
10783 goto end;
10784 case HLUA_E_ERRMSG:
10785 SEND_ERR(s->be, "Lua filter '%s' : %s.\n", conf->reg->name, lua_tostring(flt_hlua->T, -1));
10786 ret = -1;
10787 goto end;
10788 case HLUA_E_ETMOUT:
10789 SEND_ERR(s->be, "Lua filter '%s' : '%s' callback execution timeout.\n", conf->reg->name, fun);
10790 goto end;
10791 case HLUA_E_NOMEM:
10792 SEND_ERR(s->be, "Lua filter '%s' : out of memory error.\n", conf->reg->name);
10793 goto end;
10794 case HLUA_E_YIELD:
10795 SEND_ERR(s->be, "Lua filter '%s': yield functions like core.tcp() or core.sleep()"
10796 " are not allowed from '%s' callback.\n", conf->reg->name, fun);
10797 goto end;
10798 case HLUA_E_ERR:
10799 SEND_ERR(s->be, "Lua filter '%s': '%s' returns an unknown error.\n", conf->reg->name, fun);
10800 goto end;
10801 default:
10802 goto end;
10803 }
10804
10805
10806 end:
10807 return ret;
10808}
10809
10810static int hlua_filter_start_analyze(struct stream *s, struct filter *filter, struct channel *chn)
10811{
10812 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10813
10814 flt_ctx->flags = 0;
10815 return hlua_filter_callback(s, filter, "start_analyze",
10816 (!(chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES),
10817 (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_RETVAL | HLUA_FLT_CB_ARG_CHN));
10818}
10819
10820static int hlua_filter_end_analyze(struct stream *s, struct filter *filter, struct channel *chn)
10821{
10822 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10823
10824 flt_ctx->flags &= ~HLUA_FLT_CTX_FL_PAYLOAD;
10825 return hlua_filter_callback(s, filter, "end_analyze",
10826 (!(chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES),
10827 (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_RETVAL | HLUA_FLT_CB_ARG_CHN));
10828}
10829
Christopher Fauleteae8afa2020-02-26 17:15:48 +010010830static int hlua_filter_http_headers(struct stream *s, struct filter *filter, struct http_msg *msg)
10831{
10832 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10833
10834 flt_ctx->flags &= ~HLUA_FLT_CTX_FL_PAYLOAD;
10835 return hlua_filter_callback(s, filter, "http_headers",
10836 (!(msg->chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES),
10837 (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_RETVAL | HLUA_FLT_CB_ARG_HTTP_MSG));
10838}
10839
10840static int hlua_filter_http_payload(struct stream *s, struct filter *filter, struct http_msg *msg,
10841 unsigned int offset, unsigned int len)
10842{
10843 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10844 struct hlua *flt_hlua;
10845 int dir = (!(msg->chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES);
10846 int idx = (dir == SMP_OPT_DIR_REQ ? 0 : 1);
10847 int ret;
10848
10849 flt_hlua = flt_ctx->hlua[idx];
10850 flt_ctx->cur_off[idx] = offset;
10851 flt_ctx->cur_len[idx] = len;
10852 flt_ctx->flags |= HLUA_FLT_CTX_FL_PAYLOAD;
10853 ret = hlua_filter_callback(s, filter, "http_payload", dir, (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_ARG_HTTP_MSG));
10854 if (ret != -1) {
10855 ret = flt_ctx->cur_len[idx];
10856 if (lua_gettop(flt_hlua->T) > 0) {
10857 ret = lua_tointeger(flt_hlua->T, -1);
10858 if (ret > flt_ctx->cur_len[idx])
10859 ret = flt_ctx->cur_len[idx];
10860 lua_settop(flt_hlua->T, 0); /* Empty the stack. */
10861 }
10862 }
10863 return ret;
10864}
10865
10866static int hlua_filter_http_end(struct stream *s, struct filter *filter, struct http_msg *msg)
10867{
10868 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10869
10870 flt_ctx->flags &= ~HLUA_FLT_CTX_FL_PAYLOAD;
10871 return hlua_filter_callback(s, filter, "http_end",
10872 (!(msg->chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES),
10873 (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_RETVAL | HLUA_FLT_CB_ARG_HTTP_MSG));
10874}
10875
Christopher Fauletc404f112020-02-26 15:03:09 +010010876static int hlua_filter_tcp_payload(struct stream *s, struct filter *filter, struct channel *chn,
10877 unsigned int offset, unsigned int len)
10878{
10879 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10880 struct hlua *flt_hlua;
10881 int dir = (!(chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES);
10882 int idx = (dir == SMP_OPT_DIR_REQ ? 0 : 1);
10883 int ret;
10884
10885 flt_hlua = flt_ctx->hlua[idx];
10886 flt_ctx->cur_off[idx] = offset;
10887 flt_ctx->cur_len[idx] = len;
10888 flt_ctx->flags |= HLUA_FLT_CTX_FL_PAYLOAD;
10889 ret = hlua_filter_callback(s, filter, "tcp_payload", dir, (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_ARG_CHN));
10890 if (ret != -1) {
10891 ret = flt_ctx->cur_len[idx];
10892 if (lua_gettop(flt_hlua->T) > 0) {
10893 ret = lua_tointeger(flt_hlua->T, -1);
10894 if (ret > flt_ctx->cur_len[idx])
10895 ret = flt_ctx->cur_len[idx];
10896 lua_settop(flt_hlua->T, 0); /* Empty the stack. */
10897 }
10898 }
10899 return ret;
10900}
10901
Christopher Faulet69c581a2021-05-31 08:54:04 +020010902static int hlua_filter_parse_fct(char **args, int *cur_arg, struct proxy *px,
10903 struct flt_conf *fconf, char **err, void *private)
10904{
10905 struct hlua_reg_filter *reg_flt = private;
10906 lua_State *L;
10907 struct hlua_flt_config *conf = NULL;
10908 const char *flt_id = NULL;
10909 int state_id, pos, flt_flags = 0;
10910 struct flt_ops *hlua_flt_ops = NULL;
10911
10912 state_id = reg_flt_to_stack_id(reg_flt);
10913 L = hlua_states[state_id];
10914
10915 /* Initialize the filter ops with default callbacks */
10916 hlua_flt_ops = calloc(1, sizeof(*hlua_flt_ops));
Christopher Fauletc86bb872021-08-13 08:33:57 +020010917 if (!hlua_flt_ops)
10918 goto error;
Christopher Faulet69c581a2021-05-31 08:54:04 +020010919 hlua_flt_ops->init = hlua_filter_init;
10920 hlua_flt_ops->deinit = hlua_filter_deinit;
10921 if (state_id) {
10922 /* Set per-thread callback if script is loaded per-thread */
10923 hlua_flt_ops->init_per_thread = hlua_filter_init_per_thread;
10924 hlua_flt_ops->deinit_per_thread = hlua_filter_deinit_per_thread;
10925 }
10926 hlua_flt_ops->attach = hlua_filter_new;
10927 hlua_flt_ops->detach = hlua_filter_delete;
10928
10929 /* Push the filter class on the stack and resolve all callbacks */
10930 lua_rawgeti(L, LUA_REGISTRYINDEX, reg_flt->flt_ref[state_id]);
10931
Christopher Fauletc404f112020-02-26 15:03:09 +010010932 if (lua_getfield(L, -1, "start_analyze") == LUA_TFUNCTION)
10933 hlua_flt_ops->channel_start_analyze = hlua_filter_start_analyze;
10934 lua_pop(L, 1);
10935 if (lua_getfield(L, -1, "end_analyze") == LUA_TFUNCTION)
10936 hlua_flt_ops->channel_end_analyze = hlua_filter_end_analyze;
10937 lua_pop(L, 1);
Christopher Fauleteae8afa2020-02-26 17:15:48 +010010938 if (lua_getfield(L, -1, "http_headers") == LUA_TFUNCTION)
10939 hlua_flt_ops->http_headers = hlua_filter_http_headers;
10940 lua_pop(L, 1);
10941 if (lua_getfield(L, -1, "http_payload") == LUA_TFUNCTION)
10942 hlua_flt_ops->http_payload = hlua_filter_http_payload;
10943 lua_pop(L, 1);
10944 if (lua_getfield(L, -1, "http_end") == LUA_TFUNCTION)
10945 hlua_flt_ops->http_end = hlua_filter_http_end;
10946 lua_pop(L, 1);
Christopher Fauletc404f112020-02-26 15:03:09 +010010947 if (lua_getfield(L, -1, "tcp_payload") == LUA_TFUNCTION)
10948 hlua_flt_ops->tcp_payload = hlua_filter_tcp_payload;
10949 lua_pop(L, 1);
Christopher Faulet69c581a2021-05-31 08:54:04 +020010950
10951 /* Get id and flags of the filter class */
10952 if (lua_getfield(L, -1, "id") == LUA_TSTRING)
10953 flt_id = lua_tostring(L, -1);
10954 lua_pop(L, 1);
10955 if (lua_getfield(L, -1, "flags") == LUA_TNUMBER)
10956 flt_flags = lua_tointeger(L, -1);
10957 lua_pop(L, 1);
10958
10959 /* Create the filter config */
10960 conf = calloc(1, sizeof(*conf));
Christopher Fauletc86bb872021-08-13 08:33:57 +020010961 if (!conf)
Christopher Faulet69c581a2021-05-31 08:54:04 +020010962 goto error;
Christopher Faulet69c581a2021-05-31 08:54:04 +020010963 conf->reg = reg_flt;
10964
10965 /* duplicate args */
10966 for (pos = 0; *args[*cur_arg + 1 + pos]; pos++);
10967 conf->args = calloc(pos + 1, sizeof(*conf->args));
Christopher Fauletc86bb872021-08-13 08:33:57 +020010968 if (!conf->args)
10969 goto error;
10970 for (pos = 0; *args[*cur_arg + 1 + pos]; pos++) {
Christopher Faulet69c581a2021-05-31 08:54:04 +020010971 conf->args[pos] = strdup(args[*cur_arg + 1 + pos]);
Christopher Fauletc86bb872021-08-13 08:33:57 +020010972 if (!conf->args[pos])
10973 goto error;
10974 }
Christopher Faulet69c581a2021-05-31 08:54:04 +020010975 conf->args[pos] = NULL;
10976 *cur_arg += pos + 1;
10977
Christopher Fauletc86bb872021-08-13 08:33:57 +020010978 if (flt_id) {
10979 fconf->id = strdup(flt_id);
10980 if (!fconf->id)
10981 goto error;
10982 }
Christopher Faulet69c581a2021-05-31 08:54:04 +020010983 fconf->flags = flt_flags;
10984 fconf->conf = conf;
10985 fconf->ops = hlua_flt_ops;
10986
10987 lua_settop(L, 0);
10988 return 0;
10989
10990 error:
Christopher Fauletc86bb872021-08-13 08:33:57 +020010991 memprintf(err, "Lua filter '%s' : Lua out of memory error", reg_flt->name);
Christopher Faulet69c581a2021-05-31 08:54:04 +020010992 free(hlua_flt_ops);
Christopher Fauletc86bb872021-08-13 08:33:57 +020010993 if (conf && conf->args) {
10994 for (pos = 0; conf->args[pos]; pos++)
10995 free(conf->args[pos]);
10996 free(conf->args);
10997 }
Christopher Faulet69c581a2021-05-31 08:54:04 +020010998 free(conf);
Christopher Fauletc86bb872021-08-13 08:33:57 +020010999 free((char *)fconf->id);
Christopher Faulet69c581a2021-05-31 08:54:04 +020011000 lua_settop(L, 0);
11001 return -1;
11002}
11003
Christopher Fauletc404f112020-02-26 15:03:09 +010011004__LJMP static int hlua_register_data_filter(lua_State *L)
11005{
11006 struct filter *filter;
11007 struct channel *chn;
11008
11009 MAY_LJMP(check_args(L, 2, "register_data_filter"));
11010 MAY_LJMP(luaL_checktype(L, 1, LUA_TTABLE));
11011 chn = MAY_LJMP(hlua_checkchannel(L, 2));
11012
11013 lua_getfield(L, 1, "__filter");
11014 MAY_LJMP(luaL_checktype(L, -1, LUA_TLIGHTUSERDATA));
11015 filter = lua_touserdata (L, -1);
11016 lua_pop(L, 1);
11017
11018 register_data_filter(chn_strm(chn), chn, filter);
11019 return 1;
11020}
11021
11022__LJMP static int hlua_unregister_data_filter(lua_State *L)
11023{
11024 struct filter *filter;
11025 struct channel *chn;
11026
11027 MAY_LJMP(check_args(L, 2, "unregister_data_filter"));
11028 MAY_LJMP(luaL_checktype(L, 1, LUA_TTABLE));
11029 chn = MAY_LJMP(hlua_checkchannel(L, 2));
11030
11031 lua_getfield(L, 1, "__filter");
11032 MAY_LJMP(luaL_checktype(L, -1, LUA_TLIGHTUSERDATA));
11033 filter = lua_touserdata (L, -1);
11034 lua_pop(L, 1);
11035
11036 unregister_data_filter(chn_strm(chn), chn, filter);
11037 return 1;
11038}
11039
Christopher Faulet69c581a2021-05-31 08:54:04 +020011040/* This function is an LUA binding used for registering a filter. It expects a
Ilya Shipitsinff0f2782021-08-22 22:18:07 +050011041 * filter name used in the haproxy configuration file and a LUA function to
Christopher Faulet69c581a2021-05-31 08:54:04 +020011042 * parse configuration arguments.
11043 */
11044__LJMP static int hlua_register_filter(lua_State *L)
11045{
11046 struct buffer *trash;
11047 struct flt_kw_list *fkl;
11048 struct flt_kw *fkw;
11049 const char *name;
11050 struct hlua_reg_filter *reg_flt= NULL;
11051 int flt_ref, fun_ref;
11052 int len;
11053
11054 MAY_LJMP(check_args(L, 3, "register_filter"));
11055
11056 /* First argument : filter name. */
11057 name = MAY_LJMP(luaL_checkstring(L, 1));
11058
11059 /* Second argument : The filter class */
11060 flt_ref = MAY_LJMP(hlua_checktable(L, 2));
11061
11062 /* Third argument : lua function. */
11063 fun_ref = MAY_LJMP(hlua_checkfunction(L, 3));
11064
11065 trash = get_trash_chunk();
11066 chunk_printf(trash, "lua.%s", name);
11067 fkw = flt_find_kw(trash->area);
11068 if (fkw != NULL) {
11069 reg_flt = fkw->private;
11070 if (reg_flt->flt_ref[hlua_state_id] != -1 || reg_flt->fun_ref[hlua_state_id] != -1) {
11071 ha_warning("Trying to register filter 'lua.%s' more than once. "
11072 "This will become a hard error in version 2.5.\n", name);
11073 }
11074 reg_flt->flt_ref[hlua_state_id] = flt_ref;
11075 reg_flt->fun_ref[hlua_state_id] = fun_ref;
11076 return 0;
11077 }
11078
11079 fkl = calloc(1, sizeof(*fkl) + sizeof(struct flt_kw) * 2);
11080 if (!fkl)
11081 goto alloc_error;
11082 fkl->scope = "HLUA";
11083
11084 reg_flt = new_hlua_reg_filter(name);
11085 if (!reg_flt)
11086 goto alloc_error;
11087
11088 reg_flt->flt_ref[hlua_state_id] = flt_ref;
11089 reg_flt->fun_ref[hlua_state_id] = fun_ref;
11090
11091 /* The filter keyword */
11092 len = strlen("lua.") + strlen(name) + 1;
11093 fkl->kw[0].kw = calloc(1, len);
11094 if (!fkl->kw[0].kw)
11095 goto alloc_error;
11096
11097 snprintf((char *)fkl->kw[0].kw, len, "lua.%s", name);
11098
11099 fkl->kw[0].parse = hlua_filter_parse_fct;
11100 fkl->kw[0].private = reg_flt;
11101 memset(&fkl->kw[1], 0, sizeof(*fkl->kw));
11102
11103 /* Register this new filter */
11104 flt_register_keywords(fkl);
11105
11106 return 0;
11107
11108 alloc_error:
11109 release_hlua_reg_filter(reg_flt);
11110 ha_free(&fkl);
11111 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
11112 return 0; /* Never reached */
11113}
11114
Thierry FOURNIERbd413492015-03-03 16:52:26 +010011115static int hlua_read_timeout(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011116 const struct proxy *defpx, const char *file, int line,
Thierry FOURNIERbd413492015-03-03 16:52:26 +010011117 char **err, unsigned int *timeout)
11118{
11119 const char *error;
11120
11121 error = parse_time_err(args[1], timeout, TIME_UNIT_MS);
Willy Tarreau9faebe32019-06-07 19:00:37 +020011122 if (error == PARSE_TIME_OVER) {
11123 memprintf(err, "timer overflow in argument <%s> to <%s> (maximum value is 2147483647 ms or ~24.8 days)",
11124 args[1], args[0]);
11125 return -1;
11126 }
11127 else if (error == PARSE_TIME_UNDER) {
11128 memprintf(err, "timer underflow in argument <%s> to <%s> (minimum non-null value is 1 ms)",
11129 args[1], args[0]);
11130 return -1;
11131 }
11132 else if (error) {
Thierry FOURNIERbd413492015-03-03 16:52:26 +010011133 memprintf(err, "%s: invalid timeout", args[0]);
11134 return -1;
11135 }
11136 return 0;
11137}
11138
11139static int hlua_session_timeout(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011140 const struct proxy *defpx, const char *file, int line,
Thierry FOURNIERbd413492015-03-03 16:52:26 +010011141 char **err)
11142{
11143 return hlua_read_timeout(args, section_type, curpx, defpx,
11144 file, line, err, &hlua_timeout_session);
11145}
11146
11147static int hlua_task_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)
11150{
11151 return hlua_read_timeout(args, section_type, curpx, defpx,
11152 file, line, err, &hlua_timeout_task);
11153}
11154
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020011155static int hlua_applet_timeout(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011156 const struct proxy *defpx, const char *file, int line,
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020011157 char **err)
11158{
11159 return hlua_read_timeout(args, section_type, curpx, defpx,
11160 file, line, err, &hlua_timeout_applet);
11161}
11162
Thierry FOURNIERee9f8022015-03-03 17:37:37 +010011163static int hlua_forced_yield(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011164 const struct proxy *defpx, const char *file, int line,
Thierry FOURNIERee9f8022015-03-03 17:37:37 +010011165 char **err)
11166{
11167 char *error;
11168
11169 hlua_nb_instruction = strtoll(args[1], &error, 10);
11170 if (*error != '\0') {
11171 memprintf(err, "%s: invalid number", args[0]);
11172 return -1;
11173 }
11174 return 0;
11175}
11176
Willy Tarreau32f61e22015-03-18 17:54:59 +010011177static int hlua_parse_maxmem(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011178 const struct proxy *defpx, const char *file, int line,
Willy Tarreau32f61e22015-03-18 17:54:59 +010011179 char **err)
11180{
11181 char *error;
11182
11183 if (*(args[1]) == 0) {
11184 memprintf(err, "'%s' expects an integer argument (Lua memory size in MB).\n", args[0]);
11185 return -1;
11186 }
11187 hlua_global_allocator.limit = strtoll(args[1], &error, 10) * 1024L * 1024L;
11188 if (*error != '\0') {
11189 memprintf(err, "%s: invalid number %s (error at '%c')", args[0], args[1], *error);
11190 return -1;
11191 }
11192 return 0;
11193}
11194
11195
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011196/* This function is called by the main configuration key "lua-load". It loads and
11197 * execute an lua file during the parsing of the HAProxy configuration file. It is
11198 * the main lua entry point.
11199 *
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -080011200 * This function runs with the HAProxy keywords API. It returns -1 if an error
11201 * occurs, otherwise it returns 0.
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011202 *
11203 * In some error case, LUA set an error message in top of the stack. This function
11204 * returns this error message in the HAProxy logs and pop it from the stack.
Thierry FOURNIERbabae282015-09-17 11:36:37 +020011205 *
11206 * This function can fail with an abort() due to an Lua critical error.
11207 * We are in the configuration parsing process of HAProxy, this abort() is
11208 * tolerated.
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011209 */
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011210static int hlua_load_state(char *filename, lua_State *L, char **err)
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011211{
11212 int error;
11213
11214 /* Just load and compile the file. */
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011215 error = luaL_loadfile(L, filename);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011216 if (error) {
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011217 memprintf(err, "error in Lua file '%s': %s", filename, lua_tostring(L, -1));
11218 lua_pop(L, 1);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011219 return -1;
11220 }
11221
11222 /* If no syntax error where detected, execute the code. */
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011223 error = lua_pcall(L, 0, LUA_MULTRET, 0);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011224 switch (error) {
11225 case LUA_OK:
11226 break;
11227 case LUA_ERRRUN:
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011228 memprintf(err, "Lua runtime error: %s\n", lua_tostring(L, -1));
11229 lua_pop(L, 1);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011230 return -1;
11231 case LUA_ERRMEM:
Thierry Fournierde6145f2020-11-29 00:55:53 +010011232 memprintf(err, "Lua out of memory error\n");
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011233 return -1;
11234 case LUA_ERRERR:
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011235 memprintf(err, "Lua message handler error: %s\n", lua_tostring(L, -1));
11236 lua_pop(L, 1);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011237 return -1;
Christopher Faulet08ed98f2020-07-28 10:33:25 +020011238#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM <= 503
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011239 case LUA_ERRGCMM:
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011240 memprintf(err, "Lua garbage collector error: %s\n", lua_tostring(L, -1));
11241 lua_pop(L, 1);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011242 return -1;
Christopher Faulet08ed98f2020-07-28 10:33:25 +020011243#endif
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011244 default:
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011245 memprintf(err, "Lua unknown error: %s\n", lua_tostring(L, -1));
11246 lua_pop(L, 1);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011247 return -1;
11248 }
11249
11250 return 0;
11251}
11252
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011253static int hlua_load(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011254 const struct proxy *defpx, const char *file, int line,
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011255 char **err)
11256{
11257 if (*(args[1]) == 0) {
11258 memprintf(err, "'%s' expects a file name as parameter.\n", args[0]);
11259 return -1;
11260 }
11261
Thierry Fournier59f11be2020-11-29 00:37:41 +010011262 /* loading for global state */
Thierry Fournierc7492592020-11-28 23:57:24 +010011263 hlua_state_id = 0;
Willy Tarreau43ab05b2021-09-28 09:43:11 +020011264 ha_set_thread(NULL);
Thierry Fournierafc63e22020-11-28 17:06:51 +010011265 return hlua_load_state(args[1], hlua_states[0], err);
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011266}
11267
Thierry Fournier59f11be2020-11-29 00:37:41 +010011268static int hlua_load_per_thread(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011269 const struct proxy *defpx, const char *file, int line,
Thierry Fournier59f11be2020-11-29 00:37:41 +010011270 char **err)
11271{
11272 int len;
11273
11274 if (*(args[1]) == 0) {
11275 memprintf(err, "'%s' expects a file as parameter.\n", args[0]);
11276 return -1;
11277 }
11278
11279 if (per_thread_load == NULL) {
11280 /* allocate the first entry large enough to store the final NULL */
11281 per_thread_load = calloc(1, sizeof(*per_thread_load));
11282 if (per_thread_load == NULL) {
11283 memprintf(err, "out of memory error");
11284 return -1;
11285 }
11286 }
11287
11288 /* count used entries */
11289 for (len = 0; per_thread_load[len] != NULL; len++)
11290 ;
11291
11292 per_thread_load = realloc(per_thread_load, (len + 2) * sizeof(*per_thread_load));
11293 if (per_thread_load == NULL) {
11294 memprintf(err, "out of memory error");
11295 return -1;
11296 }
11297
11298 per_thread_load[len] = strdup(args[1]);
11299 per_thread_load[len + 1] = NULL;
11300
11301 if (per_thread_load[len] == NULL) {
11302 memprintf(err, "out of memory error");
11303 return -1;
11304 }
11305
11306 /* loading for thread 1 only */
11307 hlua_state_id = 1;
Willy Tarreau43ab05b2021-09-28 09:43:11 +020011308 ha_set_thread(NULL);
Thierry Fournier59f11be2020-11-29 00:37:41 +010011309 return hlua_load_state(args[1], hlua_states[1], err);
11310}
11311
Tim Duesterhusc9fc9f22020-01-12 13:55:39 +010011312/* Prepend the given <path> followed by a semicolon to the `package.<type>` variable
11313 * in the given <ctx>.
11314 */
Thierry Fournier3fb9e512020-11-28 10:13:12 +010011315static int hlua_prepend_path(lua_State *L, char *type, char *path)
Tim Duesterhusc9fc9f22020-01-12 13:55:39 +010011316{
Thierry Fournier3fb9e512020-11-28 10:13:12 +010011317 lua_getglobal(L, "package"); /* push package variable */
11318 lua_pushstring(L, path); /* push given path */
11319 lua_pushstring(L, ";"); /* push semicolon */
11320 lua_getfield(L, -3, type); /* push old path */
11321 lua_concat(L, 3); /* concatenate to new path */
11322 lua_setfield(L, -2, type); /* store new path */
11323 lua_pop(L, 1); /* pop package variable */
Tim Duesterhusc9fc9f22020-01-12 13:55:39 +010011324
11325 return 0;
11326}
11327
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010011328static int hlua_config_prepend_path(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011329 const struct proxy *defpx, const char *file, int line,
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010011330 char **err)
11331{
11332 char *path;
11333 char *type = "path";
Tim Duesterhus621e74a2021-01-03 20:04:36 +010011334 struct prepend_path *p = NULL;
Bertrand Jacquin7fbc7702021-11-24 21:16:06 +000011335 size_t i;
Thierry Fournier59f11be2020-11-29 00:37:41 +010011336
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010011337 if (too_many_args(2, args, err, NULL)) {
Tim Duesterhus621e74a2021-01-03 20:04:36 +010011338 goto err;
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010011339 }
11340
11341 if (!(*args[1])) {
11342 memprintf(err, "'%s' expects to receive a <path> as argument", args[0]);
Tim Duesterhus621e74a2021-01-03 20:04:36 +010011343 goto err;
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010011344 }
11345 path = args[1];
11346
11347 if (*args[2]) {
11348 if (strcmp(args[2], "path") != 0 && strcmp(args[2], "cpath") != 0) {
11349 memprintf(err, "'%s' expects <type> to either be 'path' or 'cpath'", args[0]);
Tim Duesterhus621e74a2021-01-03 20:04:36 +010011350 goto err;
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010011351 }
11352 type = args[2];
11353 }
11354
Thierry Fournier59f11be2020-11-29 00:37:41 +010011355 p = calloc(1, sizeof(*p));
11356 if (p == NULL) {
Tim Duesterhusf89d43a2021-01-03 20:04:37 +010011357 memprintf(err, "memory allocation failed");
Tim Duesterhus621e74a2021-01-03 20:04:36 +010011358 goto err;
Thierry Fournier59f11be2020-11-29 00:37:41 +010011359 }
11360 p->path = strdup(path);
11361 if (p->path == NULL) {
Tim Duesterhusf89d43a2021-01-03 20:04:37 +010011362 memprintf(err, "memory allocation failed");
Tim Duesterhus621e74a2021-01-03 20:04:36 +010011363 goto err2;
Thierry Fournier59f11be2020-11-29 00:37:41 +010011364 }
11365 p->type = strdup(type);
11366 if (p->type == NULL) {
Tim Duesterhusf89d43a2021-01-03 20:04:37 +010011367 memprintf(err, "memory allocation failed");
Tim Duesterhus621e74a2021-01-03 20:04:36 +010011368 goto err2;
Thierry Fournier59f11be2020-11-29 00:37:41 +010011369 }
Willy Tarreau2b718102021-04-21 07:32:39 +020011370 LIST_APPEND(&prepend_path_list, &p->l);
Thierry Fournier59f11be2020-11-29 00:37:41 +010011371
Tim Duesterhus9e5e5862021-10-11 18:51:08 +020011372 /* Handle the global state and the per-thread state for the first
11373 * thread. The remaining threads will be initialized based on
11374 * prepend_path_list.
11375 */
Bertrand Jacquin7fbc7702021-11-24 21:16:06 +000011376 for (i = 0; i < 2; i++) {
Tim Duesterhus9e5e5862021-10-11 18:51:08 +020011377 lua_State *L = hlua_states[i];
11378 const char *error;
11379
11380 if (setjmp(safe_ljmp_env) != 0) {
11381 lua_atpanic(L, hlua_panic_safe);
11382 if (lua_type(L, -1) == LUA_TSTRING)
11383 error = lua_tostring(L, -1);
11384 else
11385 error = "critical error";
11386 fprintf(stderr, "lua-prepend-path: %s.\n", error);
11387 exit(1);
11388 } else {
11389 lua_atpanic(L, hlua_panic_ljmp);
11390 }
11391
11392 hlua_prepend_path(L, type, path);
11393
11394 lua_atpanic(L, hlua_panic_safe);
11395 }
11396
Thierry Fournier59f11be2020-11-29 00:37:41 +010011397 return 0;
Tim Duesterhus621e74a2021-01-03 20:04:36 +010011398
11399err2:
11400 free(p->type);
11401 free(p->path);
11402err:
11403 free(p);
11404 return -1;
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010011405}
11406
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011407/* configuration keywords declaration */
11408static struct cfg_kw_list cfg_kws = {{ },{
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010011409 { CFG_GLOBAL, "lua-prepend-path", hlua_config_prepend_path },
Thierry FOURNIERbd413492015-03-03 16:52:26 +010011410 { CFG_GLOBAL, "lua-load", hlua_load },
Thierry Fournier59f11be2020-11-29 00:37:41 +010011411 { CFG_GLOBAL, "lua-load-per-thread", hlua_load_per_thread },
Thierry FOURNIERbd413492015-03-03 16:52:26 +010011412 { CFG_GLOBAL, "tune.lua.session-timeout", hlua_session_timeout },
11413 { CFG_GLOBAL, "tune.lua.task-timeout", hlua_task_timeout },
Thierry FOURNIER56da1012015-10-01 08:42:31 +020011414 { CFG_GLOBAL, "tune.lua.service-timeout", hlua_applet_timeout },
Thierry FOURNIERee9f8022015-03-03 17:37:37 +010011415 { CFG_GLOBAL, "tune.lua.forced-yield", hlua_forced_yield },
Willy Tarreau32f61e22015-03-18 17:54:59 +010011416 { CFG_GLOBAL, "tune.lua.maxmem", hlua_parse_maxmem },
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011417 { 0, NULL, NULL },
11418}};
11419
Willy Tarreau0108d902018-11-25 19:14:37 +010011420INITCALL1(STG_REGISTER, cfg_register_keywords, &cfg_kws);
11421
William Lallemand52139182022-03-30 15:05:42 +020011422#ifdef USE_OPENSSL
Christopher Fauletafd8f102018-11-08 11:34:21 +010011423
William Lallemand30fcca12022-03-30 12:03:12 +020011424/*
11425 * This function replace a ckch_store by another one, and rebuild the ckch_inst and all its dependencies.
11426 * It does the sam as "cli_io_handler_commit_cert" but for lua, the major
11427 * difference is that the yield in lua and for the CLI is not handled the same
11428 * way.
11429 */
11430__LJMP static int hlua_ckch_commit_yield(lua_State *L, int status, lua_KContext ctx)
11431{
11432 struct ckch_inst **lua_ckchi = lua_touserdata(L, -1);
11433 struct ckch_store **lua_ckchs = lua_touserdata(L, -2);
11434 struct ckch_inst *ckchi = *lua_ckchi;
11435 struct ckch_store *old_ckchs = lua_ckchs[0];
11436 struct ckch_store *new_ckchs = lua_ckchs[1];
11437 struct hlua *hlua;
11438 char *err = NULL;
11439 int y = 1;
11440
11441 hlua = hlua_gethlua(L);
11442
11443 /* get the first ckchi to copy */
11444 if (ckchi == NULL)
11445 ckchi = LIST_ELEM(old_ckchs->ckch_inst.n, typeof(ckchi), by_ckchs);
11446
11447 /* walk through the old ckch_inst and creates new ckch_inst using the updated ckchs */
11448 list_for_each_entry_from(ckchi, &old_ckchs->ckch_inst, by_ckchs) {
11449 struct ckch_inst *new_inst;
11450
11451 /* it takes a lot of CPU to creates SSL_CTXs, so we yield every 10 CKCH instances */
11452 if (y % 10 == 0) {
11453
11454 *lua_ckchi = ckchi;
11455
11456 task_wakeup(hlua->task, TASK_WOKEN_MSG);
11457 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_ckch_commit_yield, TICK_ETERNITY, 0));
11458 }
11459
11460 if (ckch_inst_rebuild(new_ckchs, ckchi, &new_inst, &err))
11461 goto error;
11462
11463 /* link the new ckch_inst to the duplicate */
11464 LIST_APPEND(&new_ckchs->ckch_inst, &new_inst->by_ckchs);
11465 y++;
11466 }
11467
11468 /* The generation is finished, we can insert everything */
11469 ckch_store_replace(old_ckchs, new_ckchs);
11470
11471 lua_pop(L, 2); /* pop the lua_ckchs and ckchi */
11472
11473 HA_SPIN_UNLOCK(CKCH_LOCK, &ckch_lock);
11474
11475 return 0;
11476
11477error:
11478 ckch_store_free(new_ckchs);
11479 HA_SPIN_UNLOCK(CKCH_LOCK, &ckch_lock);
11480 WILL_LJMP(luaL_error(L, "%s", err));
11481 free(err);
11482
11483 return 0;
11484}
11485
11486/*
11487 * Replace a ckch_store <filename> in the ckchs_tree with a ckch_store created
11488 * from the table in parameter.
11489 *
11490 * This is equivalent to "set ssl cert" + "commit ssl cert" over the CLI, which
11491 * means it does not need to have a transaction since everything is done in the
11492 * same function.
11493 *
11494 * CertCache.set{filename="", crt="", key="", sctl="", ocsp="", issuer=""}
11495 *
11496 */
11497__LJMP static int hlua_ckch_set(lua_State *L)
11498{
11499 struct hlua *hlua;
11500 struct ckch_inst **lua_ckchi;
11501 struct ckch_store **lua_ckchs;
11502 struct ckch_store *old_ckchs = NULL;
11503 struct ckch_store *new_ckchs = NULL;
11504 int errcode = 0;
11505 char *err = NULL;
11506 struct cert_exts *cert_ext = NULL;
11507 char *filename;
11508 struct cert_key_and_chain *ckch;
11509 int ret;
11510
11511 if (lua_type(L, -1) != LUA_TTABLE)
11512 WILL_LJMP(luaL_error(L, "'CertCache.set' needs a table as argument"));
11513
11514 hlua = hlua_gethlua(L);
11515
11516 /* FIXME: this should not return an error but should come back later */
11517 if (HA_SPIN_TRYLOCK(CKCH_LOCK, &ckch_lock))
11518 WILL_LJMP(luaL_error(L, "CertCache already under lock"));
11519
11520 ret = lua_getfield(L, -1, "filename");
11521 if (ret != LUA_TSTRING) {
11522 memprintf(&err, "%sNo filename specified!\n", err ? err : "");
11523 errcode |= ERR_ALERT | ERR_FATAL;
11524 goto end;
11525 }
11526 filename = (char *)lua_tostring(L, -1);
11527
11528
11529 /* look for the filename in the tree */
11530 old_ckchs = ckchs_lookup(filename);
11531 if (!old_ckchs) {
11532 memprintf(&err, "%sCan't replace a certificate which is not referenced by the configuration!\n", err ? err : "");
11533 errcode |= ERR_ALERT | ERR_FATAL;
11534 goto end;
11535 }
11536 /* TODO: handle extra_files_noext */
11537
11538 new_ckchs = ckchs_dup(old_ckchs);
11539 if (!new_ckchs) {
11540 memprintf(&err, "%sCannot allocate memory!\n", err ? err : "");
11541 errcode |= ERR_ALERT | ERR_FATAL;
11542 goto end;
11543 }
11544
11545 ckch = new_ckchs->ckch;
11546
11547 /* loop on the field in the table, which have the same name as the
11548 * possible extensions of files */
11549 lua_pushnil(L);
11550 while (lua_next(L, 1)) {
11551 int i;
11552 const char *field = lua_tostring(L, -2);
11553 char *payload = (char *)lua_tostring(L, -1);
11554
11555 if (!field || strcmp(field, "filename") == 0) {
11556 lua_pop(L, 1);
11557 continue;
11558 }
11559
11560 for (i = 0; field && cert_exts[i].ext != NULL; i++) {
11561 if (strcmp(field, cert_exts[i].ext) == 0) {
11562 cert_ext = &cert_exts[i];
11563 break;
11564 }
11565 }
11566
11567 /* this is the default type, the field is not supported */
11568 if (cert_ext == NULL) {
11569 memprintf(&err, "%sUnsupported field '%s'\n", err ? err : "", field);
11570 errcode |= ERR_ALERT | ERR_FATAL;
11571 goto end;
11572 }
11573
11574 /* appply the change on the duplicate */
11575 if (cert_exts->load(filename, payload, ckch, &err) != 0) {
11576 memprintf(&err, "%sCan't load the payload\n", err ? err : "");
11577 errcode |= ERR_ALERT | ERR_FATAL;
11578 goto end;
11579 }
11580 lua_pop(L, 1);
11581 }
11582
11583 /* store the pointers on the lua stack */
11584 lua_ckchs = lua_newuserdata(L, sizeof(struct ckch_store *) * 2);
11585 lua_ckchs[0] = old_ckchs;
11586 lua_ckchs[1] = new_ckchs;
11587 lua_ckchi = lua_newuserdata(L, sizeof(struct ckch_inst *));
11588 *lua_ckchi = NULL;
11589
11590 task_wakeup(hlua->task, TASK_WOKEN_MSG);
11591 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_ckch_commit_yield, TICK_ETERNITY, 0));
11592
11593end:
11594 HA_SPIN_UNLOCK(CKCH_LOCK, &ckch_lock);
11595
11596 if (errcode & ERR_CODE) {
11597 ckch_store_free(new_ckchs);
11598 WILL_LJMP(luaL_error(L, "%s", err));
11599 }
11600 free(err);
11601
11602 return 0;
11603}
11604
William Lallemand52139182022-03-30 15:05:42 +020011605#else
11606
11607__LJMP static int hlua_ckch_set(lua_State *L)
11608{
11609 WILL_LJMP(luaL_error(L, "'CertCache.set' needs an HAProxy built with OpenSSL"));
11610
11611 return 0;
11612}
11613#endif /* ! USE_OPENSSL */
11614
11615
11616
Thierry FOURNIERbabae282015-09-17 11:36:37 +020011617/* This function can fail with an abort() due to an Lua critical error.
11618 * We are in the initialisation process of HAProxy, this abort() is
11619 * tolerated.
11620 */
Thierry Fournierb8cef172020-11-28 15:37:17 +010011621int hlua_post_init_state(lua_State *L)
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010011622{
11623 struct hlua_init_function *init;
11624 const char *msg;
11625 enum hlua_exec ret;
Thierry Fournierfd107a22016-02-19 19:57:23 +010011626 const char *error;
Thierry Fournier670db242020-11-28 10:49:59 +010011627 const char *kind;
11628 const char *trace;
11629 int return_status = 1;
11630#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM >= 504
11631 int nres;
11632#endif
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010011633
Willy Tarreaucdb53462020-12-02 12:12:00 +010011634 /* disable memory limit checks if limit is not set */
11635 if (!hlua_global_allocator.limit)
11636 hlua_global_allocator.limit = ~hlua_global_allocator.limit;
11637
Ilya Shipitsin856aabc2020-04-16 23:51:34 +050011638 /* Call post initialisation function in safe environment. */
Thierry Fournier3c539322020-11-28 16:05:05 +010011639 if (setjmp(safe_ljmp_env) != 0) {
11640 lua_atpanic(L, hlua_panic_safe);
Thierry Fournierb8cef172020-11-28 15:37:17 +010011641 if (lua_type(L, -1) == LUA_TSTRING)
11642 error = lua_tostring(L, -1);
Thierry Fournier3d4a6752016-02-19 20:53:30 +010011643 else
11644 error = "critical error";
11645 fprintf(stderr, "Lua post-init: %s.\n", error);
11646 exit(1);
Thierry Fournier3c539322020-11-28 16:05:05 +010011647 } else {
11648 lua_atpanic(L, hlua_panic_ljmp);
Thierry Fournier3d4a6752016-02-19 20:53:30 +010011649 }
Frédéric Lécaille54f2bcf2018-08-29 13:46:24 +020011650
Thierry Fournierb8cef172020-11-28 15:37:17 +010011651 hlua_fcn_post_init(L);
Thierry Fournier3d4a6752016-02-19 20:53:30 +010011652
Thierry Fournierc7492592020-11-28 23:57:24 +010011653 list_for_each_entry(init, &hlua_init_functions[hlua_state_id], l) {
Thierry Fournierb8cef172020-11-28 15:37:17 +010011654 lua_rawgeti(L, LUA_REGISTRYINDEX, init->function_ref);
Thierry Fournier670db242020-11-28 10:49:59 +010011655
11656#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM >= 504
Thierry Fournierb8cef172020-11-28 15:37:17 +010011657 ret = lua_resume(L, L, 0, &nres);
Thierry Fournier670db242020-11-28 10:49:59 +010011658#else
Thierry Fournierb8cef172020-11-28 15:37:17 +010011659 ret = lua_resume(L, L, 0);
Thierry Fournier670db242020-11-28 10:49:59 +010011660#endif
11661 kind = NULL;
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010011662 switch (ret) {
Thierry Fournier670db242020-11-28 10:49:59 +010011663
11664 case LUA_OK:
Thierry Fournierb8cef172020-11-28 15:37:17 +010011665 lua_pop(L, -1);
Thierry Fournier13d08b72020-11-28 11:02:58 +010011666 break;
Thierry Fournier670db242020-11-28 10:49:59 +010011667
11668 case LUA_ERRERR:
11669 kind = "message handler error";
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -070011670 /* Fall through */
Thierry Fournier670db242020-11-28 10:49:59 +010011671 case LUA_ERRRUN:
11672 if (!kind)
11673 kind = "runtime error";
Thierry Fournierb8cef172020-11-28 15:37:17 +010011674 msg = lua_tostring(L, -1);
11675 lua_settop(L, 0); /* Empty the stack. */
11676 lua_pop(L, 1);
Christopher Fauletd09cc512021-03-24 14:48:45 +010011677 trace = hlua_traceback(L, ", ");
Thierry Fournier670db242020-11-28 10:49:59 +010011678 if (msg)
11679 ha_alert("Lua init: %s: '%s' from %s\n", kind, msg, trace);
11680 else
11681 ha_alert("Lua init: unknown %s from %s\n", kind, trace);
11682 return_status = 0;
11683 break;
11684
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010011685 default:
Thierry Fournier670db242020-11-28 10:49:59 +010011686 /* Unknown error */
11687 kind = "Unknown error";
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -070011688 /* Fall through */
Thierry Fournier670db242020-11-28 10:49:59 +010011689 case LUA_YIELD:
11690 /* yield is not configured at this step, this state doesn't happen */
11691 if (!kind)
11692 kind = "yield not allowed";
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -070011693 /* Fall through */
Thierry Fournier670db242020-11-28 10:49:59 +010011694 case LUA_ERRMEM:
11695 if (!kind)
11696 kind = "out of memory error";
Thierry Fournierb8cef172020-11-28 15:37:17 +010011697 lua_settop(L, 0);
11698 lua_pop(L, 1);
Christopher Fauletd09cc512021-03-24 14:48:45 +010011699 trace = hlua_traceback(L, ", ");
Thierry Fournier670db242020-11-28 10:49:59 +010011700 ha_alert("Lua init: %s: %s\n", kind, trace);
11701 return_status = 0;
11702 break;
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010011703 }
Thierry Fournier670db242020-11-28 10:49:59 +010011704 if (!return_status)
11705 break;
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010011706 }
Thierry Fournier3c539322020-11-28 16:05:05 +010011707
11708 lua_atpanic(L, hlua_panic_safe);
Thierry Fournier670db242020-11-28 10:49:59 +010011709 return return_status;
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010011710}
11711
Thierry Fournierb8cef172020-11-28 15:37:17 +010011712int hlua_post_init()
11713{
Thierry Fournier59f11be2020-11-29 00:37:41 +010011714 int ret;
11715 int i;
11716 int errors;
11717 char *err = NULL;
11718 struct hlua_function *fcn;
Christopher Faulet69c581a2021-05-31 08:54:04 +020011719 struct hlua_reg_filter *reg_flt;
Thierry Fournier59f11be2020-11-29 00:37:41 +010011720
Willy Tarreaub1310492021-08-30 09:35:18 +020011721#if defined(USE_OPENSSL)
Thierry Fournierb8cef172020-11-28 15:37:17 +010011722 /* Initialize SSL server. */
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010011723 if (socket_ssl->xprt->prepare_srv) {
Thierry Fournierb8cef172020-11-28 15:37:17 +010011724 int saved_used_backed = global.ssl_used_backend;
11725 // don't affect maxconn automatic computation
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010011726 socket_ssl->xprt->prepare_srv(socket_ssl);
Thierry Fournierb8cef172020-11-28 15:37:17 +010011727 global.ssl_used_backend = saved_used_backed;
11728 }
11729#endif
11730
Thierry Fournierc7492592020-11-28 23:57:24 +010011731 /* Perform post init of common thread */
11732 hlua_state_id = 0;
Willy Tarreau43ab05b2021-09-28 09:43:11 +020011733 ha_set_thread(&ha_thread_info[0]);
Thierry Fournier59f11be2020-11-29 00:37:41 +010011734 ret = hlua_post_init_state(hlua_states[hlua_state_id]);
11735 if (ret == 0)
11736 return 0;
11737
11738 /* init remaining lua states and load files */
11739 for (hlua_state_id = 2; hlua_state_id < global.nbthread + 1; hlua_state_id++) {
11740
11741 /* set thread context */
Willy Tarreau43ab05b2021-09-28 09:43:11 +020011742 ha_set_thread(&ha_thread_info[hlua_state_id - 1]);
Thierry Fournier59f11be2020-11-29 00:37:41 +010011743
11744 /* Init lua state */
11745 hlua_states[hlua_state_id] = hlua_init_state(hlua_state_id);
11746
11747 /* Load lua files */
11748 for (i = 0; per_thread_load && per_thread_load[i]; i++) {
11749 ret = hlua_load_state(per_thread_load[i], hlua_states[hlua_state_id], &err);
11750 if (ret != 0) {
11751 ha_alert("Lua init: %s\n", err);
11752 return 0;
11753 }
11754 }
11755 }
11756
11757 /* Reset thread context */
Willy Tarreau43ab05b2021-09-28 09:43:11 +020011758 ha_set_thread(NULL);
Thierry Fournier59f11be2020-11-29 00:37:41 +010011759
11760 /* Execute post init for all states */
11761 for (hlua_state_id = 1; hlua_state_id < global.nbthread + 1; hlua_state_id++) {
11762
11763 /* set thread context */
Willy Tarreau43ab05b2021-09-28 09:43:11 +020011764 ha_set_thread(&ha_thread_info[hlua_state_id - 1]);
Thierry Fournier59f11be2020-11-29 00:37:41 +010011765
11766 /* run post init */
11767 ret = hlua_post_init_state(hlua_states[hlua_state_id]);
11768 if (ret == 0)
11769 return 0;
11770 }
11771
11772 /* Reset thread context */
Willy Tarreau43ab05b2021-09-28 09:43:11 +020011773 ha_set_thread(NULL);
Thierry Fournier59f11be2020-11-29 00:37:41 +010011774
11775 /* control functions registering. Each function must have:
11776 * - only the function_ref[0] set positive and all other to -1
11777 * - only the function_ref[0] set to -1 and all other positive
11778 * This ensure a same reference is not used both in shared
11779 * lua state and thread dedicated lua state. Note: is the case
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +050011780 * reach, the shared state is priority, but the bug will be
Thierry Fournier59f11be2020-11-29 00:37:41 +010011781 * complicated to found for the end user.
11782 */
11783 errors = 0;
11784 list_for_each_entry(fcn, &referenced_functions, l) {
11785 ret = 0;
11786 for (i = 1; i < global.nbthread + 1; i++) {
11787 if (fcn->function_ref[i] == -1)
11788 ret--;
11789 else
11790 ret++;
11791 }
11792 if (abs(ret) != global.nbthread) {
11793 ha_alert("Lua function '%s' is not referenced in all thread. "
11794 "Expect function in all thread or in none thread.\n", fcn->name);
11795 errors++;
11796 continue;
11797 }
11798
11799 if ((fcn->function_ref[0] == -1) == (ret < 0)) {
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +050011800 ha_alert("Lua function '%s' is referenced both ins shared Lua context (through lua-load) "
11801 "and per-thread Lua context (through lua-load-per-thread). these two context "
Thierry Fournier59f11be2020-11-29 00:37:41 +010011802 "exclusive.\n", fcn->name);
11803 errors++;
11804 }
11805 }
11806
Christopher Faulet69c581a2021-05-31 08:54:04 +020011807 /* Do the same with registered filters */
11808 list_for_each_entry(reg_flt, &referenced_filters, l) {
11809 ret = 0;
11810 for (i = 1; i < global.nbthread + 1; i++) {
11811 if (reg_flt->flt_ref[i] == -1)
11812 ret--;
11813 else
11814 ret++;
11815 }
11816 if (abs(ret) != global.nbthread) {
11817 ha_alert("Lua filter '%s' is not referenced in all thread. "
11818 "Expect function in all thread or in none thread.\n", reg_flt->name);
11819 errors++;
11820 continue;
11821 }
11822
11823 if ((reg_flt->flt_ref[0] == -1) == (ret < 0)) {
11824 ha_alert("Lua filter '%s' is referenced both ins shared Lua context (through lua-load) "
11825 "and per-thread Lua context (through lua-load-per-thread). these two context "
11826 "exclusive.\n", fcn->name);
11827 errors++;
11828 }
11829 }
11830
11831
Thierry Fournier59f11be2020-11-29 00:37:41 +010011832 if (errors > 0)
11833 return 0;
11834
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +050011835 /* after this point, this global will no longer be used, so set to
Thierry Fournier59f11be2020-11-29 00:37:41 +010011836 * -1 in order to have probably a segfault if someone use it
11837 */
11838 hlua_state_id = -1;
11839
11840 return 1;
Thierry Fournierb8cef172020-11-28 15:37:17 +010011841}
11842
Willy Tarreau32f61e22015-03-18 17:54:59 +010011843/* The memory allocator used by the Lua stack. <ud> is a pointer to the
11844 * allocator's context. <ptr> is the pointer to alloc/free/realloc. <osize>
11845 * is the previously allocated size or the kind of object in case of a new
Willy Tarreaud36c7fa2020-12-02 12:26:29 +010011846 * allocation. <nsize> is the requested new size. A new allocation is
11847 * indicated by <ptr> being NULL. A free is indicated by <nsize> being
Willy Tarreaucdb53462020-12-02 12:12:00 +010011848 * zero. This one verifies that the limits are respected but is optimized
11849 * for the fast case where limits are not used, hence stats are not updated.
Willy Tarreaua5efdff2021-10-22 16:00:02 +020011850 *
11851 * Warning: while this API ressembles glibc's realloc() a lot, glibc surpasses
11852 * POSIX by making realloc(ptr,0) an effective free(), but others do not do
11853 * that and will simply allocate zero as if it were the result of malloc(0),
11854 * so mapping this onto realloc() will lead to memory leaks on non-glibc
11855 * systems.
Willy Tarreau32f61e22015-03-18 17:54:59 +010011856 */
11857static void *hlua_alloc(void *ud, void *ptr, size_t osize, size_t nsize)
11858{
11859 struct hlua_mem_allocator *zone = ud;
Willy Tarreaucdb53462020-12-02 12:12:00 +010011860 size_t limit, old, new;
11861
11862 /* a limit of ~0 means unlimited and boot complete, so there's no need
11863 * for accounting anymore.
11864 */
Willy Tarreaua5efdff2021-10-22 16:00:02 +020011865 if (likely(~zone->limit == 0)) {
11866 if (!nsize)
11867 ha_free(&ptr);
11868 else
11869 ptr = realloc(ptr, nsize);
11870 return ptr;
11871 }
Willy Tarreau32f61e22015-03-18 17:54:59 +010011872
Willy Tarreaud36c7fa2020-12-02 12:26:29 +010011873 if (!ptr)
11874 osize = 0;
Willy Tarreau32f61e22015-03-18 17:54:59 +010011875
Willy Tarreaucdb53462020-12-02 12:12:00 +010011876 /* enforce strict limits across all threads */
11877 limit = zone->limit;
11878 old = _HA_ATOMIC_LOAD(&zone->allocated);
11879 do {
11880 new = old + nsize - osize;
11881 if (unlikely(nsize && limit && new > limit))
11882 return NULL;
11883 } while (!_HA_ATOMIC_CAS(&zone->allocated, &old, new));
Willy Tarreau32f61e22015-03-18 17:54:59 +010011884
Willy Tarreaua5efdff2021-10-22 16:00:02 +020011885 if (!nsize)
11886 ha_free(&ptr);
11887 else
11888 ptr = realloc(ptr, nsize);
Willy Tarreaucdb53462020-12-02 12:12:00 +010011889
11890 if (unlikely(!ptr && nsize)) // failed
11891 _HA_ATOMIC_SUB(&zone->allocated, nsize - osize);
11892
11893 __ha_barrier_atomic_store();
Willy Tarreau32f61e22015-03-18 17:54:59 +010011894 return ptr;
11895}
11896
Thierry Fournierecb83c22020-11-28 15:49:44 +010011897/* This function can fail with an abort() due to a Lua critical error.
Thierry FOURNIERbabae282015-09-17 11:36:37 +020011898 * We are in the initialisation process of HAProxy, this abort() is
11899 * tolerated.
11900 */
Thierry Fournierecb83c22020-11-28 15:49:44 +010011901lua_State *hlua_init_state(int thread_num)
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +010011902{
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010011903 int i;
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010011904 int idx;
11905 struct sample_fetch *sf;
Thierry FOURNIER594afe72015-03-10 23:58:30 +010011906 struct sample_conv *sc;
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010011907 char *p;
Thierry Fournierfd107a22016-02-19 19:57:23 +010011908 const char *error_msg;
Thierry Fournier4234dbd2020-11-28 13:18:23 +010011909 void **context;
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011910 lua_State *L;
Thierry Fournier59f11be2020-11-29 00:37:41 +010011911 struct prepend_path *pp;
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010011912
Thierry FOURNIER380d0932015-01-23 14:27:52 +010011913 /* Init main lua stack. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011914 L = lua_newstate(hlua_alloc, &hlua_global_allocator);
Thierry FOURNIER380d0932015-01-23 14:27:52 +010011915
Thierry Fournier4234dbd2020-11-28 13:18:23 +010011916 /* Initialise Lua context to NULL */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011917 context = lua_getextraspace(L);
Thierry Fournier4234dbd2020-11-28 13:18:23 +010011918 *context = NULL;
11919
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -080011920 /* From this point, until the end of the initialisation function,
Thierry FOURNIERbabae282015-09-17 11:36:37 +020011921 * the Lua function can fail with an abort. We are in the initialisation
11922 * process of HAProxy, this abort() is tolerated.
11923 */
11924
Thierry Fournier3c539322020-11-28 16:05:05 +010011925 /* Call post initialisation function in safe environment. */
11926 if (setjmp(safe_ljmp_env) != 0) {
11927 lua_atpanic(L, hlua_panic_safe);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011928 if (lua_type(L, -1) == LUA_TSTRING)
11929 error_msg = lua_tostring(L, -1);
Thierry Fournier2f05cc62020-11-28 16:08:02 +010011930 else
11931 error_msg = "critical error";
11932 fprintf(stderr, "Lua init: %s.\n", error_msg);
11933 exit(1);
Thierry Fournier3c539322020-11-28 16:05:05 +010011934 } else {
11935 lua_atpanic(L, hlua_panic_ljmp);
Thierry Fournier2f05cc62020-11-28 16:08:02 +010011936 }
11937
Thierry FOURNIER380d0932015-01-23 14:27:52 +010011938 /* Initialise lua. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011939 luaL_openlibs(L);
Tim Duesterhus541fe1e2020-01-12 13:55:41 +010011940#define HLUA_PREPEND_PATH_TOSTRING1(x) #x
11941#define HLUA_PREPEND_PATH_TOSTRING(x) HLUA_PREPEND_PATH_TOSTRING1(x)
11942#ifdef HLUA_PREPEND_PATH
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011943 hlua_prepend_path(L, "path", HLUA_PREPEND_PATH_TOSTRING(HLUA_PREPEND_PATH));
Tim Duesterhus541fe1e2020-01-12 13:55:41 +010011944#endif
11945#ifdef HLUA_PREPEND_CPATH
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011946 hlua_prepend_path(L, "cpath", HLUA_PREPEND_PATH_TOSTRING(HLUA_PREPEND_CPATH));
Tim Duesterhus541fe1e2020-01-12 13:55:41 +010011947#endif
11948#undef HLUA_PREPEND_PATH_TOSTRING
11949#undef HLUA_PREPEND_PATH_TOSTRING1
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010011950
Thierry Fournier59f11be2020-11-29 00:37:41 +010011951 /* Apply configured prepend path */
11952 list_for_each_entry(pp, &prepend_path_list, l)
11953 hlua_prepend_path(L, pp->type, pp->path);
11954
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010011955 /*
11956 *
11957 * Create "core" object.
11958 *
11959 */
11960
Thierry FOURNIERa2d8c652015-03-11 17:29:39 +010011961 /* This table entry is the object "core" base. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011962 lua_newtable(L);
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010011963
Thierry Fournierecb83c22020-11-28 15:49:44 +010011964 /* set the thread id */
11965 hlua_class_const_int(L, "thread", thread_num);
11966
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010011967 /* Push the loglevel constants. */
Willy Tarreau80f5fae2015-02-27 16:38:20 +010011968 for (i = 0; i < NB_LOG_LEVELS; i++)
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011969 hlua_class_const_int(L, log_levels[i], i);
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010011970
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010011971 /* Register special functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011972 hlua_class_function(L, "register_init", hlua_register_init);
11973 hlua_class_function(L, "register_task", hlua_register_task);
11974 hlua_class_function(L, "register_fetches", hlua_register_fetches);
11975 hlua_class_function(L, "register_converters", hlua_register_converters);
11976 hlua_class_function(L, "register_action", hlua_register_action);
11977 hlua_class_function(L, "register_service", hlua_register_service);
11978 hlua_class_function(L, "register_cli", hlua_register_cli);
Christopher Faulet69c581a2021-05-31 08:54:04 +020011979 hlua_class_function(L, "register_filter", hlua_register_filter);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011980 hlua_class_function(L, "yield", hlua_yield);
11981 hlua_class_function(L, "set_nice", hlua_set_nice);
11982 hlua_class_function(L, "sleep", hlua_sleep);
11983 hlua_class_function(L, "msleep", hlua_msleep);
11984 hlua_class_function(L, "add_acl", hlua_add_acl);
11985 hlua_class_function(L, "del_acl", hlua_del_acl);
11986 hlua_class_function(L, "set_map", hlua_set_map);
11987 hlua_class_function(L, "del_map", hlua_del_map);
11988 hlua_class_function(L, "tcp", hlua_socket_new);
William Lallemand3956c4e2021-09-21 16:25:15 +020011989 hlua_class_function(L, "httpclient", hlua_httpclient_new);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011990 hlua_class_function(L, "log", hlua_log);
11991 hlua_class_function(L, "Debug", hlua_log_debug);
11992 hlua_class_function(L, "Info", hlua_log_info);
11993 hlua_class_function(L, "Warning", hlua_log_warning);
11994 hlua_class_function(L, "Alert", hlua_log_alert);
11995 hlua_class_function(L, "done", hlua_done);
11996 hlua_fcn_reg_core_fcn(L);
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010011997
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011998 lua_setglobal(L, "core");
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010011999
12000 /*
12001 *
Christopher Faulet0f3c8902020-01-31 18:57:12 +010012002 * Create "act" object.
12003 *
12004 */
12005
12006 /* This table entry is the object "act" base. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012007 lua_newtable(L);
Christopher Faulet0f3c8902020-01-31 18:57:12 +010012008
12009 /* push action return constants */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012010 hlua_class_const_int(L, "CONTINUE", ACT_RET_CONT);
12011 hlua_class_const_int(L, "STOP", ACT_RET_STOP);
12012 hlua_class_const_int(L, "YIELD", ACT_RET_YIELD);
12013 hlua_class_const_int(L, "ERROR", ACT_RET_ERR);
12014 hlua_class_const_int(L, "DONE", ACT_RET_DONE);
12015 hlua_class_const_int(L, "DENY", ACT_RET_DENY);
12016 hlua_class_const_int(L, "ABORT", ACT_RET_ABRT);
12017 hlua_class_const_int(L, "INVALID", ACT_RET_INV);
Christopher Faulet0f3c8902020-01-31 18:57:12 +010012018
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012019 hlua_class_function(L, "wake_time", hlua_set_wake_time);
Christopher Faulet2c2c2e32020-01-31 19:07:52 +010012020
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012021 lua_setglobal(L, "act");
Christopher Faulet0f3c8902020-01-31 18:57:12 +010012022
12023 /*
12024 *
Christopher Faulet69c581a2021-05-31 08:54:04 +020012025 * Create "Filter" object.
12026 *
12027 */
12028
12029 /* This table entry is the object "filter" base. */
12030 lua_newtable(L);
12031
12032 /* push flags and constants */
12033 hlua_class_const_int(L, "CONTINUE", 1);
12034 hlua_class_const_int(L, "WAIT", 0);
12035 hlua_class_const_int(L, "ERROR", -1);
12036
12037 hlua_class_const_int(L, "FLT_CFG_FL_HTX", FLT_CFG_FL_HTX);
12038
Christopher Fauletc404f112020-02-26 15:03:09 +010012039 hlua_class_function(L, "wake_time", hlua_set_wake_time);
12040 hlua_class_function(L, "register_data_filter", hlua_register_data_filter);
12041 hlua_class_function(L, "unregister_data_filter", hlua_unregister_data_filter);
12042
Christopher Faulet69c581a2021-05-31 08:54:04 +020012043 lua_setglobal(L, "filter");
12044
12045 /*
12046 *
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012047 * Register class Map
12048 *
12049 */
12050
12051 /* This table entry is the object "Map" base. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012052 lua_newtable(L);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012053
12054 /* register pattern types. */
12055 for (i=0; i<PAT_MATCH_NUM; i++)
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012056 hlua_class_const_int(L, pat_match_names[i], i);
Thierry FOURNIER4dc71972017-01-28 08:33:08 +010012057 for (i=0; i<PAT_MATCH_NUM; i++) {
Willy Tarreau843b7cb2018-07-13 10:54:26 +020012058 snprintf(trash.area, trash.size, "_%s", pat_match_names[i]);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012059 hlua_class_const_int(L, trash.area, i);
Thierry FOURNIER4dc71972017-01-28 08:33:08 +010012060 }
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012061
12062 /* register constructor. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012063 hlua_class_function(L, "new", hlua_map_new);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012064
12065 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012066 lua_newtable(L);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012067
Ilya Shipitsind4259502020-04-08 01:07:56 +050012068 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012069 lua_pushstring(L, "__index");
12070 lua_newtable(L);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012071
12072 /* Register . */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012073 hlua_class_function(L, "lookup", hlua_map_lookup);
12074 hlua_class_function(L, "slookup", hlua_map_slookup);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012075
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012076 lua_rawset(L, -3);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012077
Thierry Fournier45e78d72016-02-19 18:34:46 +010012078 /* Register previous table in the registry with reference and named entry.
12079 * The function hlua_register_metatable() pops the stack, so we
12080 * previously create a copy of the table.
12081 */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012082 lua_pushvalue(L, -1); /* Copy the -1 entry and push it on the stack. */
12083 class_map_ref = hlua_register_metatable(L, CLASS_MAP);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012084
12085 /* Assign the metatable to the mai Map object. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012086 lua_setmetatable(L, -2);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012087
12088 /* Set a name to the table. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012089 lua_setglobal(L, "Map");
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012090
12091 /*
12092 *
William Lallemand30fcca12022-03-30 12:03:12 +020012093 * Register "CertCache" class
12094 *
12095 */
12096
12097 /* Create and fill the metatable. */
12098 lua_newtable(L);
12099 /* Register */
12100 hlua_class_function(L, "set", hlua_ckch_set);
12101 lua_setglobal(L, CLASS_CERTCACHE); /* Create global object called Regex */
12102
12103 /*
12104 *
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010012105 * Register class Channel
12106 *
12107 */
12108
12109 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012110 lua_newtable(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010012111
Ilya Shipitsind4259502020-04-08 01:07:56 +050012112 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012113 lua_pushstring(L, "__index");
12114 lua_newtable(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010012115
12116 /* Register . */
Christopher Faulet6a79fc12021-08-06 16:02:36 +020012117 hlua_class_function(L, "data", hlua_channel_get_data);
12118 hlua_class_function(L, "line", hlua_channel_get_line);
12119 hlua_class_function(L, "set", hlua_channel_set_data);
12120 hlua_class_function(L, "remove", hlua_channel_del_data);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012121 hlua_class_function(L, "append", hlua_channel_append);
Christopher Faulet6a79fc12021-08-06 16:02:36 +020012122 hlua_class_function(L, "prepend", hlua_channel_prepend);
12123 hlua_class_function(L, "insert", hlua_channel_insert_data);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012124 hlua_class_function(L, "send", hlua_channel_send);
12125 hlua_class_function(L, "forward", hlua_channel_forward);
Christopher Faulet6a79fc12021-08-06 16:02:36 +020012126 hlua_class_function(L, "input", hlua_channel_get_in_len);
12127 hlua_class_function(L, "output", hlua_channel_get_out_len);
12128 hlua_class_function(L, "may_recv", hlua_channel_may_recv);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012129 hlua_class_function(L, "is_full", hlua_channel_is_full);
12130 hlua_class_function(L, "is_resp", hlua_channel_is_resp);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010012131
Christopher Faulet6a79fc12021-08-06 16:02:36 +020012132 /* Deprecated API */
12133 hlua_class_function(L, "get", hlua_channel_get);
12134 hlua_class_function(L, "dup", hlua_channel_dup);
12135 hlua_class_function(L, "getline", hlua_channel_getline);
12136 hlua_class_function(L, "get_in_len", hlua_channel_get_in_len);
12137 hlua_class_function(L, "get_out_len", hlua_channel_get_out_len);
12138
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012139 lua_rawset(L, -3);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010012140
12141 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012142 class_channel_ref = hlua_register_metatable(L, CLASS_CHANNEL);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010012143
12144 /*
12145 *
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010012146 * Register class Fetches
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010012147 *
12148 */
12149
12150 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012151 lua_newtable(L);
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010012152
Ilya Shipitsind4259502020-04-08 01:07:56 +050012153 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012154 lua_pushstring(L, "__index");
12155 lua_newtable(L);
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010012156
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010012157 /* Browse existing fetches and create the associated
12158 * object method.
12159 */
12160 sf = NULL;
12161 while ((sf = sample_fetch_getnext(sf, &idx)) != NULL) {
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010012162 /* gL.Tua doesn't support '.' and '-' in the function names, replace it
12163 * by an underscore.
12164 */
Willy Tarreau5ef96562021-08-26 16:48:53 +020012165 strlcpy2(trash.area, sf->kw, trash.size);
Willy Tarreau843b7cb2018-07-13 10:54:26 +020012166 for (p = trash.area; *p; p++)
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010012167 if (*p == '.' || *p == '-' || *p == '+')
12168 *p = '_';
12169
12170 /* Register the function. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012171 lua_pushstring(L, trash.area);
12172 lua_pushlightuserdata(L, sf);
12173 lua_pushcclosure(L, hlua_run_sample_fetch, 1);
12174 lua_rawset(L, -3);
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010012175 }
12176
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012177 lua_rawset(L, -3);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010012178
12179 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012180 class_fetches_ref = hlua_register_metatable(L, CLASS_FETCHES);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010012181
12182 /*
12183 *
Thierry FOURNIER594afe72015-03-10 23:58:30 +010012184 * Register class Converters
12185 *
12186 */
12187
12188 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012189 lua_newtable(L);
Thierry FOURNIER594afe72015-03-10 23:58:30 +010012190
12191 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012192 lua_pushstring(L, "__index");
12193 lua_newtable(L);
Thierry FOURNIER594afe72015-03-10 23:58:30 +010012194
12195 /* Browse existing converters and create the associated
12196 * object method.
12197 */
12198 sc = NULL;
12199 while ((sc = sample_conv_getnext(sc, &idx)) != NULL) {
Thierry FOURNIER594afe72015-03-10 23:58:30 +010012200 /* gL.Tua doesn't support '.' and '-' in the function names, replace it
12201 * by an underscore.
12202 */
Willy Tarreau5ef96562021-08-26 16:48:53 +020012203 strlcpy2(trash.area, sc->kw, trash.size);
Willy Tarreau843b7cb2018-07-13 10:54:26 +020012204 for (p = trash.area; *p; p++)
Thierry FOURNIER594afe72015-03-10 23:58:30 +010012205 if (*p == '.' || *p == '-' || *p == '+')
12206 *p = '_';
12207
12208 /* Register the function. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012209 lua_pushstring(L, trash.area);
12210 lua_pushlightuserdata(L, sc);
12211 lua_pushcclosure(L, hlua_run_sample_conv, 1);
12212 lua_rawset(L, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +010012213 }
12214
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012215 lua_rawset(L, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +010012216
12217 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012218 class_converters_ref = hlua_register_metatable(L, CLASS_CONVERTERS);
Thierry FOURNIER594afe72015-03-10 23:58:30 +010012219
12220 /*
12221 *
Thierry FOURNIER08504f42015-03-16 14:17:08 +010012222 * Register class HTTP
12223 *
12224 */
12225
12226 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012227 lua_newtable(L);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010012228
Ilya Shipitsind4259502020-04-08 01:07:56 +050012229 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012230 lua_pushstring(L, "__index");
12231 lua_newtable(L);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010012232
12233 /* Register Lua functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012234 hlua_class_function(L, "req_get_headers",hlua_http_req_get_headers);
12235 hlua_class_function(L, "req_del_header", hlua_http_req_del_hdr);
12236 hlua_class_function(L, "req_rep_header", hlua_http_req_rep_hdr);
12237 hlua_class_function(L, "req_rep_value", hlua_http_req_rep_val);
12238 hlua_class_function(L, "req_add_header", hlua_http_req_add_hdr);
12239 hlua_class_function(L, "req_set_header", hlua_http_req_set_hdr);
12240 hlua_class_function(L, "req_set_method", hlua_http_req_set_meth);
12241 hlua_class_function(L, "req_set_path", hlua_http_req_set_path);
12242 hlua_class_function(L, "req_set_query", hlua_http_req_set_query);
12243 hlua_class_function(L, "req_set_uri", hlua_http_req_set_uri);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010012244
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012245 hlua_class_function(L, "res_get_headers",hlua_http_res_get_headers);
12246 hlua_class_function(L, "res_del_header", hlua_http_res_del_hdr);
12247 hlua_class_function(L, "res_rep_header", hlua_http_res_rep_hdr);
12248 hlua_class_function(L, "res_rep_value", hlua_http_res_rep_val);
12249 hlua_class_function(L, "res_add_header", hlua_http_res_add_hdr);
12250 hlua_class_function(L, "res_set_header", hlua_http_res_set_hdr);
12251 hlua_class_function(L, "res_set_status", hlua_http_res_set_status);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010012252
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012253 lua_rawset(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010012254
12255 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012256 class_http_ref = hlua_register_metatable(L, CLASS_HTTP);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010012257
Christopher Fauletdf97ac42020-02-26 16:57:19 +010012258 /*
12259 *
12260 * Register class HTTPMessage
12261 *
12262 */
12263
12264 /* Create and fill the metatable. */
12265 lua_newtable(L);
12266
Ilya Shipitsinff0f2782021-08-22 22:18:07 +050012267 /* Create and fill the __index entry. */
Christopher Fauletdf97ac42020-02-26 16:57:19 +010012268 lua_pushstring(L, "__index");
12269 lua_newtable(L);
12270
12271 /* Register Lua functions. */
12272 hlua_class_function(L, "is_resp", hlua_http_msg_is_resp);
12273 hlua_class_function(L, "get_stline", hlua_http_msg_get_stline);
12274 hlua_class_function(L, "get_headers", hlua_http_msg_get_headers);
12275 hlua_class_function(L, "del_header", hlua_http_msg_del_hdr);
12276 hlua_class_function(L, "rep_header", hlua_http_msg_rep_hdr);
12277 hlua_class_function(L, "rep_value", hlua_http_msg_rep_val);
12278 hlua_class_function(L, "add_header", hlua_http_msg_add_hdr);
12279 hlua_class_function(L, "set_header", hlua_http_msg_set_hdr);
12280 hlua_class_function(L, "set_method", hlua_http_msg_set_meth);
12281 hlua_class_function(L, "set_path", hlua_http_msg_set_path);
12282 hlua_class_function(L, "set_query", hlua_http_msg_set_query);
12283 hlua_class_function(L, "set_uri", hlua_http_msg_set_uri);
12284 hlua_class_function(L, "set_status", hlua_http_msg_set_status);
12285 hlua_class_function(L, "is_full", hlua_http_msg_is_full);
12286 hlua_class_function(L, "may_recv", hlua_http_msg_may_recv);
12287 hlua_class_function(L, "eom", hlua_http_msg_is_eom);
12288 hlua_class_function(L, "input", hlua_http_msg_get_in_len);
12289 hlua_class_function(L, "output", hlua_http_msg_get_out_len);
12290
12291 hlua_class_function(L, "body", hlua_http_msg_get_body);
12292 hlua_class_function(L, "set", hlua_http_msg_set_data);
12293 hlua_class_function(L, "remove", hlua_http_msg_del_data);
12294 hlua_class_function(L, "append", hlua_http_msg_append);
12295 hlua_class_function(L, "prepend", hlua_http_msg_prepend);
12296 hlua_class_function(L, "insert", hlua_http_msg_insert_data);
12297 hlua_class_function(L, "set_eom", hlua_http_msg_set_eom);
12298 hlua_class_function(L, "unset_eom", hlua_http_msg_unset_eom);
12299
12300 hlua_class_function(L, "send", hlua_http_msg_send);
12301 hlua_class_function(L, "forward", hlua_http_msg_forward);
12302
12303 lua_rawset(L, -3);
12304
12305 /* Register previous table in the registry with reference and named entry. */
12306 class_http_msg_ref = hlua_register_metatable(L, CLASS_HTTP_MSG);
William Lallemand3956c4e2021-09-21 16:25:15 +020012307
12308 /*
12309 *
12310 * Register class HTTPClient
12311 *
12312 */
12313
12314 /* Create and fill the metatable. */
12315 lua_newtable(L);
12316 lua_pushstring(L, "__index");
12317 lua_newtable(L);
12318 hlua_class_function(L, "get", hlua_httpclient_get);
William Lallemanddc2cc902021-10-26 11:43:26 +020012319 hlua_class_function(L, "head", hlua_httpclient_head);
12320 hlua_class_function(L, "put", hlua_httpclient_put);
12321 hlua_class_function(L, "post", hlua_httpclient_post);
12322 hlua_class_function(L, "delete", hlua_httpclient_delete);
William Lallemand3956c4e2021-09-21 16:25:15 +020012323 lua_settable(L, -3); /* Sets the __index entry. */
William Lallemandf77f1de2021-09-28 19:10:38 +020012324 /* Register the garbage collector entry. */
12325 lua_pushstring(L, "__gc");
12326 lua_pushcclosure(L, hlua_httpclient_gc, 0);
12327 lua_settable(L, -3); /* Push the last 2 entries in the table at index -3 */
12328
William Lallemand3956c4e2021-09-21 16:25:15 +020012329
12330
12331 class_httpclient_ref = hlua_register_metatable(L, CLASS_HTTPCLIENT);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010012332 /*
12333 *
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020012334 * Register class AppletTCP
12335 *
12336 */
12337
12338 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012339 lua_newtable(L);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020012340
Ilya Shipitsind4259502020-04-08 01:07:56 +050012341 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012342 lua_pushstring(L, "__index");
12343 lua_newtable(L);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020012344
12345 /* Register Lua functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012346 hlua_class_function(L, "getline", hlua_applet_tcp_getline);
12347 hlua_class_function(L, "receive", hlua_applet_tcp_recv);
12348 hlua_class_function(L, "send", hlua_applet_tcp_send);
12349 hlua_class_function(L, "set_priv", hlua_applet_tcp_set_priv);
12350 hlua_class_function(L, "get_priv", hlua_applet_tcp_get_priv);
12351 hlua_class_function(L, "set_var", hlua_applet_tcp_set_var);
12352 hlua_class_function(L, "unset_var", hlua_applet_tcp_unset_var);
12353 hlua_class_function(L, "get_var", hlua_applet_tcp_get_var);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020012354
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012355 lua_settable(L, -3);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020012356
12357 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012358 class_applet_tcp_ref = hlua_register_metatable(L, CLASS_APPLET_TCP);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020012359
12360 /*
12361 *
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020012362 * Register class AppletHTTP
12363 *
12364 */
12365
12366 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012367 lua_newtable(L);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020012368
Ilya Shipitsind4259502020-04-08 01:07:56 +050012369 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012370 lua_pushstring(L, "__index");
12371 lua_newtable(L);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020012372
12373 /* Register Lua functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012374 hlua_class_function(L, "set_priv", hlua_applet_http_set_priv);
12375 hlua_class_function(L, "get_priv", hlua_applet_http_get_priv);
12376 hlua_class_function(L, "set_var", hlua_applet_http_set_var);
12377 hlua_class_function(L, "unset_var", hlua_applet_http_unset_var);
12378 hlua_class_function(L, "get_var", hlua_applet_http_get_var);
12379 hlua_class_function(L, "getline", hlua_applet_http_getline);
12380 hlua_class_function(L, "receive", hlua_applet_http_recv);
12381 hlua_class_function(L, "send", hlua_applet_http_send);
12382 hlua_class_function(L, "add_header", hlua_applet_http_addheader);
12383 hlua_class_function(L, "set_status", hlua_applet_http_status);
12384 hlua_class_function(L, "start_response", hlua_applet_http_start_response);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020012385
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012386 lua_settable(L, -3);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020012387
12388 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012389 class_applet_http_ref = hlua_register_metatable(L, CLASS_APPLET_HTTP);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020012390
12391 /*
12392 *
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010012393 * Register class TXN
12394 *
12395 */
12396
12397 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012398 lua_newtable(L);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010012399
Ilya Shipitsind4259502020-04-08 01:07:56 +050012400 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012401 lua_pushstring(L, "__index");
12402 lua_newtable(L);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010012403
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +010012404 /* Register Lua functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012405 hlua_class_function(L, "set_priv", hlua_set_priv);
12406 hlua_class_function(L, "get_priv", hlua_get_priv);
12407 hlua_class_function(L, "set_var", hlua_set_var);
12408 hlua_class_function(L, "unset_var", hlua_unset_var);
12409 hlua_class_function(L, "get_var", hlua_get_var);
12410 hlua_class_function(L, "done", hlua_txn_done);
12411 hlua_class_function(L, "reply", hlua_txn_reply_new);
12412 hlua_class_function(L, "set_loglevel", hlua_txn_set_loglevel);
12413 hlua_class_function(L, "set_tos", hlua_txn_set_tos);
12414 hlua_class_function(L, "set_mark", hlua_txn_set_mark);
12415 hlua_class_function(L, "set_priority_class", hlua_txn_set_priority_class);
12416 hlua_class_function(L, "set_priority_offset", hlua_txn_set_priority_offset);
12417 hlua_class_function(L, "deflog", hlua_txn_deflog);
12418 hlua_class_function(L, "log", hlua_txn_log);
12419 hlua_class_function(L, "Debug", hlua_txn_log_debug);
12420 hlua_class_function(L, "Info", hlua_txn_log_info);
12421 hlua_class_function(L, "Warning", hlua_txn_log_warning);
12422 hlua_class_function(L, "Alert", hlua_txn_log_alert);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +010012423
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012424 lua_rawset(L, -3);
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010012425
12426 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012427 class_txn_ref = hlua_register_metatable(L, CLASS_TXN);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012428
12429 /*
12430 *
Christopher Faulet700d9e82020-01-31 12:21:52 +010012431 * Register class reply
12432 *
12433 */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012434 lua_newtable(L);
12435 lua_pushstring(L, "__index");
12436 lua_newtable(L);
12437 hlua_class_function(L, "set_status", hlua_txn_reply_set_status);
12438 hlua_class_function(L, "add_header", hlua_txn_reply_add_header);
12439 hlua_class_function(L, "del_header", hlua_txn_reply_del_header);
12440 hlua_class_function(L, "set_body", hlua_txn_reply_set_body);
12441 lua_settable(L, -3); /* Sets the __index entry. */
12442 class_txn_reply_ref = luaL_ref(L, LUA_REGISTRYINDEX);
Christopher Faulet700d9e82020-01-31 12:21:52 +010012443
12444
12445 /*
12446 *
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012447 * Register class Socket
12448 *
12449 */
12450
12451 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012452 lua_newtable(L);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012453
Ilya Shipitsind4259502020-04-08 01:07:56 +050012454 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012455 lua_pushstring(L, "__index");
12456 lua_newtable(L);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012457
Baptiste Assmann84bb4932015-03-02 21:40:06 +010012458#ifdef USE_OPENSSL
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012459 hlua_class_function(L, "connect_ssl", hlua_socket_connect_ssl);
Baptiste Assmann84bb4932015-03-02 21:40:06 +010012460#endif
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012461 hlua_class_function(L, "connect", hlua_socket_connect);
12462 hlua_class_function(L, "send", hlua_socket_send);
12463 hlua_class_function(L, "receive", hlua_socket_receive);
12464 hlua_class_function(L, "close", hlua_socket_close);
12465 hlua_class_function(L, "getpeername", hlua_socket_getpeername);
12466 hlua_class_function(L, "getsockname", hlua_socket_getsockname);
12467 hlua_class_function(L, "setoption", hlua_socket_setoption);
12468 hlua_class_function(L, "settimeout", hlua_socket_settimeout);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012469
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012470 lua_rawset(L, -3); /* Push the last 2 entries in the table at index -3 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012471
12472 /* Register the garbage collector entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012473 lua_pushstring(L, "__gc");
12474 lua_pushcclosure(L, hlua_socket_gc, 0);
12475 lua_rawset(L, -3); /* Push the last 2 entries in the table at index -3 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012476
12477 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012478 class_socket_ref = hlua_register_metatable(L, CLASS_SOCKET);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012479
Thierry Fournieraafc7772020-12-04 11:47:47 +010012480 lua_atpanic(L, hlua_panic_safe);
12481
12482 return L;
12483}
12484
12485void hlua_init(void) {
12486 int i;
Amaury Denoyelle239fdbf2021-03-24 10:22:03 +010012487 char *errmsg;
Thierry Fournieraafc7772020-12-04 11:47:47 +010012488#ifdef USE_OPENSSL
12489 struct srv_kw *kw;
12490 int tmp_error;
12491 char *error;
12492 char *args[] = { /* SSL client configuration. */
12493 "ssl",
12494 "verify",
12495 "none",
12496 NULL
12497 };
12498#endif
12499
12500 /* Init post init function list head */
12501 for (i = 0; i < MAX_THREADS + 1; i++)
12502 LIST_INIT(&hlua_init_functions[i]);
12503
12504 /* Init state for common/shared lua parts */
12505 hlua_state_id = 0;
Willy Tarreau43ab05b2021-09-28 09:43:11 +020012506 ha_set_thread(NULL);
Thierry Fournieraafc7772020-12-04 11:47:47 +010012507 hlua_states[0] = hlua_init_state(0);
12508
12509 /* Init state 1 for thread 0. We have at least one thread. */
12510 hlua_state_id = 1;
Willy Tarreau43ab05b2021-09-28 09:43:11 +020012511 ha_set_thread(NULL);
Thierry Fournieraafc7772020-12-04 11:47:47 +010012512 hlua_states[1] = hlua_init_state(1);
12513
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012514 /* Proxy and server configuration initialisation. */
William Lallemand6bb77b92021-07-28 15:48:16 +020012515 socket_proxy = alloc_new_proxy("LUA-SOCKET", PR_CAP_FE|PR_CAP_BE|PR_CAP_INT, &errmsg);
Amaury Denoyelle239fdbf2021-03-24 10:22:03 +010012516 if (!socket_proxy) {
12517 fprintf(stderr, "Lua init: %s\n", errmsg);
12518 exit(1);
12519 }
12520 proxy_preset_defaults(socket_proxy);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012521
12522 /* Init TCP server: unchanged parameters */
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010012523 socket_tcp = new_server(socket_proxy);
12524 if (!socket_tcp) {
12525 fprintf(stderr, "Lua init: failed to allocate tcp server socket\n");
12526 exit(1);
12527 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012528
12529#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012530 /* Init TCP server: unchanged parameters */
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010012531 socket_ssl = new_server(socket_proxy);
12532 if (!socket_ssl) {
12533 fprintf(stderr, "Lua init: failed to allocate ssl server socket\n");
12534 exit(1);
12535 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012536
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010012537 socket_ssl->use_ssl = 1;
12538 socket_ssl->xprt = xprt_get(XPRT_SSL);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012539
Bertrand Jacquin80839ff2021-01-21 19:14:46 +000012540 for (i = 0; args[i] != NULL; i++) {
12541 if ((kw = srv_find_kw(args[i])) != NULL) { /* Maybe it's registered server keyword */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012542 /*
12543 *
12544 * If the keyword is not known, we can search in the registered
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -080012545 * server keywords. This is useful to configure special SSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012546 * features like client certificates and ssl_verify.
12547 *
12548 */
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010012549 tmp_error = kw->parse(args, &i, socket_proxy, socket_ssl, &error);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012550 if (tmp_error != 0) {
12551 fprintf(stderr, "INTERNAL ERROR: %s\n", error);
12552 abort(); /* This must be never arrives because the command line
12553 not editable by the user. */
12554 }
Bertrand Jacquin80839ff2021-01-21 19:14:46 +000012555 i += kw->skip;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012556 }
12557 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012558#endif
Thierry Fournier75933d42016-01-21 09:30:18 +010012559
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +010012560}
Willy Tarreaubb57d942016-12-21 19:04:56 +010012561
Tim Duesterhusd0c0ca22020-07-04 11:53:26 +020012562static void hlua_deinit()
12563{
Willy Tarreau186f3762020-12-04 11:48:12 +010012564 int thr;
Christopher Faulet69c581a2021-05-31 08:54:04 +020012565 struct hlua_reg_filter *reg_flt, *reg_flt_bck;
12566
12567 list_for_each_entry_safe(reg_flt, reg_flt_bck, &referenced_filters, l)
12568 release_hlua_reg_filter(reg_flt);
Willy Tarreau186f3762020-12-04 11:48:12 +010012569
12570 for (thr = 0; thr < MAX_THREADS+1; thr++) {
12571 if (hlua_states[thr])
12572 lua_close(hlua_states[thr]);
12573 }
Willy Tarreau430bf4a2021-03-04 09:45:32 +010012574
Amaury Denoyellebc2ebfa2021-08-25 15:34:53 +020012575 srv_drop(socket_tcp);
Willy Tarreau430bf4a2021-03-04 09:45:32 +010012576
Willy Tarreau0f143af2021-03-05 10:41:48 +010012577#ifdef USE_OPENSSL
Amaury Denoyellebc2ebfa2021-08-25 15:34:53 +020012578 srv_drop(socket_ssl);
Willy Tarreau0f143af2021-03-05 10:41:48 +010012579#endif
Amaury Denoyelle239fdbf2021-03-24 10:22:03 +010012580
12581 free_proxy(socket_proxy);
Tim Duesterhusd0c0ca22020-07-04 11:53:26 +020012582}
12583
12584REGISTER_POST_DEINIT(hlua_deinit);
12585
Willy Tarreau80713382018-11-26 10:19:54 +010012586static void hlua_register_build_options(void)
12587{
Willy Tarreaubb57d942016-12-21 19:04:56 +010012588 char *ptr = NULL;
Willy Tarreau80713382018-11-26 10:19:54 +010012589
Willy Tarreaubb57d942016-12-21 19:04:56 +010012590 memprintf(&ptr, "Built with Lua version : %s", LUA_RELEASE);
12591 hap_register_build_opts(ptr, 1);
12592}
Willy Tarreau80713382018-11-26 10:19:54 +010012593
12594INITCALL0(STG_REGISTER, hlua_register_build_options);