blob: 19932a5b121635ffd2344882ec2dc0457fea040a [file] [log] [blame]
Thierry Fourniere726b142016-02-11 17:57:57 +01001/*
2 * Lua unsafe core engine
3 *
4 * Copyright 2015-2016 Thierry Fournier <tfournier@arpalert.org>
5 *
6 * This program is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU General Public License
8 * as published by the Free Software Foundation; either version
9 * 2 of the License, or (at your option) any later version.
10 *
11 */
12
Bertrand Jacquinf4c12d42021-01-21 21:14:07 +000013#define _GNU_SOURCE
14
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +010015#include <ctype.h>
Thierry FOURNIERbabae282015-09-17 11:36:37 +020016#include <setjmp.h>
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +010017
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +010018#include <lauxlib.h>
19#include <lua.h>
20#include <lualib.h>
21
Thierry FOURNIER463119c2015-03-10 00:35:36 +010022#if !defined(LUA_VERSION_NUM) || LUA_VERSION_NUM < 503
23#error "Requires Lua 5.3 or later."
Cyril Bontédc0306e2015-03-02 00:08:40 +010024#endif
25
Willy Tarreau8d2b7772020-05-27 10:58:19 +020026#include <import/ebpttree.h>
Thierry FOURNIER380d0932015-01-23 14:27:52 +010027
Willy Tarreaub2551052020-06-09 09:07:15 +020028#include <haproxy/api.h>
29#include <haproxy/applet.h>
Willy Tarreaudfd3de82020-06-04 23:46:14 +020030#include <haproxy/arg.h>
Christopher Fauletd25d9262020-08-06 11:04:46 +020031#include <haproxy/auth.h>
Willy Tarreau6be78492020-06-05 00:00:29 +020032#include <haproxy/cfgparse.h>
Willy Tarreauf1d32c42020-06-04 21:07:02 +020033#include <haproxy/channel.h>
Willy Tarreau83487a82020-06-04 20:19:54 +020034#include <haproxy/cli.h>
Willy Tarreau55542642021-10-08 09:33:24 +020035#include <haproxy/clock.h>
Willy Tarreau7ea393d2020-06-04 18:02:10 +020036#include <haproxy/connection.h>
Christopher Faulet69c581a2021-05-31 08:54:04 +020037#include <haproxy/filters.h>
Willy Tarreau5413a872020-06-02 19:33:08 +020038#include <haproxy/h1.h>
Willy Tarreau86416052020-06-04 09:20:54 +020039#include <haproxy/hlua.h>
Willy Tarreau8c794002020-06-04 10:05:25 +020040#include <haproxy/hlua_fcn.h>
Willy Tarreauc2b1ff02020-06-04 21:21:03 +020041#include <haproxy/http_ana.h>
William Lallemand3956c4e2021-09-21 16:25:15 +020042#include <haproxy/http_client.h>
Willy Tarreau126ba3a2020-06-04 18:26:43 +020043#include <haproxy/http_fetch.h>
Willy Tarreaub2551052020-06-09 09:07:15 +020044#include <haproxy/http_htx.h>
Willy Tarreauc761f842020-06-04 11:40:28 +020045#include <haproxy/http_rules.h>
Willy Tarreau36979d92020-06-05 17:27:29 +020046#include <haproxy/log.h>
Willy Tarreau2cd58092020-06-04 15:10:43 +020047#include <haproxy/map.h>
Willy Tarreau8efbdfb2020-06-04 11:29:21 +020048#include <haproxy/obj_type.h>
Willy Tarreau225a90a2020-06-04 15:06:28 +020049#include <haproxy/pattern.h>
Willy Tarreau469509b2020-06-04 15:13:30 +020050#include <haproxy/payload.h>
Willy Tarreau3d6ee402021-05-08 20:28:07 +020051#include <haproxy/proxy.h>
Willy Tarreaub2551052020-06-09 09:07:15 +020052#include <haproxy/regex.h>
Willy Tarreaue6ce10b2020-06-04 15:33:47 +020053#include <haproxy/sample.h>
Willy Tarreau5edca2f2022-05-27 09:25:10 +020054#include <haproxy/sc_strm.h>
Willy Tarreau198e92a2021-03-05 10:23:32 +010055#include <haproxy/server.h>
Willy Tarreau48d25b32020-06-04 18:58:52 +020056#include <haproxy/session.h>
William Lallemand30fcca12022-03-30 12:03:12 +020057#include <haproxy/ssl_ckch.h>
58#include <haproxy/ssl_sock.h>
Willy Tarreau2eec9b52020-06-04 19:58:55 +020059#include <haproxy/stats-t.h>
Willy Tarreaucb086c62022-05-27 09:47:12 +020060#include <haproxy/stconn.h>
Willy Tarreaudfd3de82020-06-04 23:46:14 +020061#include <haproxy/stream.h>
Willy Tarreaucea0e1b2020-06-04 17:25:40 +020062#include <haproxy/task.h>
Willy Tarreau8b550af2020-06-04 17:42:48 +020063#include <haproxy/tcp_rules.h>
Willy Tarreaub2551052020-06-09 09:07:15 +020064#include <haproxy/thread.h>
Willy Tarreau48fbcae2020-06-03 18:09:46 +020065#include <haproxy/tools.h>
Willy Tarreaua1718922020-06-04 16:25:31 +020066#include <haproxy/vars.h>
Willy Tarreaub2551052020-06-09 09:07:15 +020067#include <haproxy/xref.h>
68
Thierry FOURNIER380d0932015-01-23 14:27:52 +010069
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +010070/* Lua uses longjmp to perform yield or throwing errors. This
71 * macro is used only for identifying the function that can
72 * not return because a longjmp is executed.
73 * __LJMP marks a prototype of hlua file that can use longjmp.
74 * WILL_LJMP() marks an lua function that will use longjmp.
75 * MAY_LJMP() marks an lua function that may use longjmp.
76 */
77#define __LJMP
Willy Tarreau4e7cc332018-10-20 17:45:48 +020078#define WILL_LJMP(func) do { func; my_unreachable(); } while(0)
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +010079#define MAY_LJMP(func) func
80
Thierry FOURNIERbabae282015-09-17 11:36:37 +020081/* This couple of function executes securely some Lua calls outside of
82 * the lua runtime environment. Each Lua call can return a longjmp
83 * if it encounter a memory error.
84 *
85 * Lua documentation extract:
86 *
87 * If an error happens outside any protected environment, Lua calls
88 * a panic function (see lua_atpanic) and then calls abort, thus
89 * exiting the host application. Your panic function can avoid this
90 * exit by never returning (e.g., doing a long jump to your own
91 * recovery point outside Lua).
92 *
93 * The panic function runs as if it were a message handler (see
Willy Tarreau3dfb7da2022-03-02 22:33:39 +010094 * #2.3); in particular, the error message is at the top of the
Thierry FOURNIERbabae282015-09-17 11:36:37 +020095 * stack. However, there is no guarantee about stack space. To push
96 * anything on the stack, the panic function must first check the
Willy Tarreau3dfb7da2022-03-02 22:33:39 +010097 * available space (see #4.2).
Thierry FOURNIERbabae282015-09-17 11:36:37 +020098 *
99 * We must check all the Lua entry point. This includes:
100 * - The include/proto/hlua.h exported functions
101 * - the task wrapper function
102 * - The action wrapper function
103 * - The converters wrapper function
104 * - The sample-fetch wrapper functions
105 *
Ilya Shipitsin46a030c2020-07-05 16:36:08 +0500106 * It is tolerated that the initialisation function returns an abort.
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -0800107 * Before each Lua abort, an error message is written on stderr.
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200108 *
109 * The macro SET_SAFE_LJMP initialise the longjmp. The Macro
110 * RESET_SAFE_LJMP reset the longjmp. These function must be macro
111 * because they must be exists in the program stack when the longjmp
112 * is called.
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +0200113 *
114 * Note that the Lua processing is not really thread safe. It provides
115 * heavy system which consists to add our own lock function in the Lua
116 * code and recompile the library. This system will probably not accepted
117 * by maintainers of various distribs.
118 *
Ilya Shipitsin856aabc2020-04-16 23:51:34 +0500119 * Our main execution point of the Lua is the function lua_resume(). A
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +0200120 * quick looking on the Lua sources displays a lua_lock() a the start
121 * of function and a lua_unlock() at the end of the function. So I
122 * conclude that the Lua thread safe mode just perform a mutex around
123 * all execution. So I prefer to do this in the HAProxy code, it will be
124 * easier for distro maintainers.
125 *
126 * Note that the HAProxy lua functions rounded by the macro SET_SAFE_LJMP
127 * and RESET_SAFE_LJMP manipulates the Lua stack, so it will be careful
128 * to set mutex around these functions.
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200129 */
Willy Tarreau86abe442018-11-25 20:12:18 +0100130__decl_spinlock(hlua_global_lock);
Thierry FOURNIERffbad792017-07-12 11:39:04 +0200131THREAD_LOCAL jmp_buf safe_ljmp_env;
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200132static int hlua_panic_safe(lua_State *L) { return 0; }
Willy Tarreau6a510902021-07-14 19:41:25 +0200133static int hlua_panic_ljmp(lua_State *L) { WILL_LJMP(longjmp(safe_ljmp_env, 1)); return 0; }
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200134
Thierry Fournier62a22aa2020-11-28 21:06:35 +0100135/* This is the chained list of struct hlua_function referenced
136 * for haproxy action, sample-fetches, converters, cli and
137 * applet bindings. It is used for a post-initialisation control.
138 */
139static struct list referenced_functions = LIST_HEAD_INIT(referenced_functions);
140
Thierry Fournierc7492592020-11-28 23:57:24 +0100141/* This variable is used only during initialization to identify the Lua state
142 * currently being initialized. 0 is the common lua state, 1 to n are the Lua
143 * states dedicated to each thread (in this case hlua_state_id==tid+1).
144 */
145static int hlua_state_id;
146
Thierry Fournier59f11be2020-11-29 00:37:41 +0100147/* This is a NULL-terminated list of lua file which are referenced to load per thread */
Thierry Fournierae6b5682022-09-19 09:04:16 +0200148static char ***per_thread_load = NULL;
Thierry Fournier59f11be2020-11-29 00:37:41 +0100149
150lua_State *hlua_init_state(int thread_id);
151
Willy Tarreau1e7bef12021-08-20 15:47:25 +0200152/* This function takes the Lua global lock. Keep this function's visibility
153 * global so that it can appear in stack dumps and performance profiles!
154 */
155void lua_take_global_lock()
156{
157 HA_SPIN_LOCK(LUA_LOCK, &hlua_global_lock);
158}
159
160static inline void lua_drop_global_lock()
161{
162 HA_SPIN_UNLOCK(LUA_LOCK, &hlua_global_lock);
163}
164
Thierry Fournier7cbe5042020-11-28 17:02:21 +0100165#define SET_SAFE_LJMP_L(__L, __HLUA) \
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200166 ({ \
167 int ret; \
Thierry Fournier021d9862020-11-28 23:42:03 +0100168 if ((__HLUA)->state_id == 0) \
Willy Tarreau1e7bef12021-08-20 15:47:25 +0200169 lua_take_global_lock(); \
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200170 if (setjmp(safe_ljmp_env) != 0) { \
171 lua_atpanic(__L, hlua_panic_safe); \
172 ret = 0; \
Thierry Fournier021d9862020-11-28 23:42:03 +0100173 if ((__HLUA)->state_id == 0) \
Willy Tarreau1e7bef12021-08-20 15:47:25 +0200174 lua_drop_global_lock(); \
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200175 } else { \
176 lua_atpanic(__L, hlua_panic_ljmp); \
177 ret = 1; \
178 } \
179 ret; \
180 })
181
182/* If we are the last function catching Lua errors, we
183 * must reset the panic function.
184 */
Thierry Fournier7cbe5042020-11-28 17:02:21 +0100185#define RESET_SAFE_LJMP_L(__L, __HLUA) \
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200186 do { \
187 lua_atpanic(__L, hlua_panic_safe); \
Thierry Fournier021d9862020-11-28 23:42:03 +0100188 if ((__HLUA)->state_id == 0) \
Willy Tarreau1e7bef12021-08-20 15:47:25 +0200189 lua_drop_global_lock(); \
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200190 } while(0)
191
Thierry Fournier7cbe5042020-11-28 17:02:21 +0100192#define SET_SAFE_LJMP(__HLUA) \
193 SET_SAFE_LJMP_L((__HLUA)->T, __HLUA)
194
195#define RESET_SAFE_LJMP(__HLUA) \
196 RESET_SAFE_LJMP_L((__HLUA)->T, __HLUA)
197
198#define SET_SAFE_LJMP_PARENT(__HLUA) \
Thierry Fournier021d9862020-11-28 23:42:03 +0100199 SET_SAFE_LJMP_L(hlua_states[(__HLUA)->state_id], __HLUA)
Thierry Fournier7cbe5042020-11-28 17:02:21 +0100200
201#define RESET_SAFE_LJMP_PARENT(__HLUA) \
Thierry Fournier021d9862020-11-28 23:42:03 +0100202 RESET_SAFE_LJMP_L(hlua_states[(__HLUA)->state_id], __HLUA)
Thierry Fournier7cbe5042020-11-28 17:02:21 +0100203
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +0200204/* Applet status flags */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200205#define APPLET_DONE 0x01 /* applet processing is done. */
Christopher Faulet18c2e8d2019-03-01 12:02:08 +0100206/* unused: 0x02 */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200207#define APPLET_HDR_SENT 0x04 /* Response header sent. */
Christopher Fauleta2097962019-07-15 16:25:33 +0200208/* unused: 0x08, 0x10 */
Thierry FOURNIERd93ea2b2015-12-20 19:14:52 +0100209#define APPLET_HTTP11 0x20 /* Last chunk sent. */
Christopher Faulet56a3d6e2019-02-27 22:06:23 +0100210#define APPLET_RSP_SENT 0x40 /* The response was fully sent */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200211
Thierry Fournierafc63e22020-11-28 17:06:51 +0100212/* The main Lua execution context. The 0 index is the
213 * common state shared by all threads.
214 */
Willy Tarreau186f3762020-12-04 11:48:12 +0100215static lua_State *hlua_states[MAX_THREADS + 1];
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100216
Christopher Fauletc404f112020-02-26 15:03:09 +0100217#define HLUA_FLT_CB_FINAL 0x00000001
218#define HLUA_FLT_CB_RETVAL 0x00000002
219#define HLUA_FLT_CB_ARG_CHN 0x00000004
220#define HLUA_FLT_CB_ARG_HTTP_MSG 0x00000008
221
Christopher Faulet9f55a502020-02-25 15:21:02 +0100222#define HLUA_FLT_CTX_FL_PAYLOAD 0x00000001
223
Christopher Faulet69c581a2021-05-31 08:54:04 +0200224struct hlua_reg_filter {
225 char *name;
226 int flt_ref[MAX_THREADS + 1];
227 int fun_ref[MAX_THREADS + 1];
228 struct list l;
229};
230
231struct hlua_flt_config {
232 struct hlua_reg_filter *reg;
233 int ref[MAX_THREADS + 1];
234 char **args;
235};
236
237struct hlua_flt_ctx {
238 int ref; /* ref to the filter lua object */
239 struct hlua *hlua[2]; /* lua runtime context (0: request, 1: response) */
240 unsigned int cur_off[2]; /* current offset (0: request, 1: response) */
241 unsigned int cur_len[2]; /* current forwardable length (0: request, 1: response) */
242 unsigned int flags; /* HLUA_FLT_CTX_FL_* */
243};
244
Willy Tarreau5321da92022-05-06 11:57:34 +0200245/* appctx context used by the cosockets */
246struct hlua_csk_ctx {
247 int connected;
248 struct xref xref; /* cross reference with the Lua object owner. */
249 struct list wake_on_read;
250 struct list wake_on_write;
251 struct appctx *appctx;
252 int die;
253};
254
Willy Tarreaue23f33b2022-05-06 14:07:13 +0200255/* appctx context used by TCP services */
256struct hlua_tcp_ctx {
257 struct hlua *hlua;
258 int flags;
259 struct task *task;
260};
261
Willy Tarreauaa229cc2022-05-06 14:26:10 +0200262/* appctx context used by HTTP services */
263struct hlua_http_ctx {
264 struct hlua *hlua;
265 int left_bytes; /* The max amount of bytes that we can read. */
266 int flags;
267 int status;
268 const char *reason;
269 struct task *task;
270};
271
Willy Tarreaubcda5f62022-05-03 18:13:39 +0200272/* used by registered CLI keywords */
273struct hlua_cli_ctx {
274 struct hlua *hlua;
275 struct task *task;
276 struct hlua_function *fcn;
277};
278
Christopher Faulet69c581a2021-05-31 08:54:04 +0200279DECLARE_STATIC_POOL(pool_head_hlua_flt_ctx, "hlua_flt_ctx", sizeof(struct hlua_flt_ctx));
280
Christopher Faulet9f55a502020-02-25 15:21:02 +0100281static int hlua_filter_from_payload(struct filter *filter);
282
Christopher Faulet69c581a2021-05-31 08:54:04 +0200283/* This is the chained list of struct hlua_flt referenced
284 * for haproxy filters. It is used for a post-initialisation control.
285 */
286static struct list referenced_filters = LIST_HEAD_INIT(referenced_filters);
287
288
Thierry FOURNIERebed6e92016-12-16 11:54:07 +0100289/* This is the memory pool containing struct lua for applets
290 * (including cli).
291 */
Willy Tarreau8ceae722018-11-26 11:58:30 +0100292DECLARE_STATIC_POOL(pool_head_hlua, "hlua", sizeof(struct hlua));
Thierry FOURNIERebed6e92016-12-16 11:54:07 +0100293
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +0100294/* Used for Socket connection. */
Amaury Denoyelle239fdbf2021-03-24 10:22:03 +0100295static struct proxy *socket_proxy;
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +0100296static struct server *socket_tcp;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +0100297#ifdef USE_OPENSSL
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +0100298static struct server *socket_ssl;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +0100299#endif
300
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +0100301/* List head of the function called at the initialisation time. */
Thierry Fournierc7492592020-11-28 23:57:24 +0100302struct list hlua_init_functions[MAX_THREADS + 1];
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +0100303
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +0100304/* The following variables contains the reference of the different
305 * Lua classes. These references are useful for identify metadata
306 * associated with an object.
307 */
Thierry FOURNIER65f34c62015-02-16 20:11:43 +0100308static int class_txn_ref;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +0100309static int class_socket_ref;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +0100310static int class_channel_ref;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +0100311static int class_fetches_ref;
Thierry FOURNIER594afe72015-03-10 23:58:30 +0100312static int class_converters_ref;
Thierry FOURNIER08504f42015-03-16 14:17:08 +0100313static int class_http_ref;
Christopher Fauletdf97ac42020-02-26 16:57:19 +0100314static int class_http_msg_ref;
William Lallemand3956c4e2021-09-21 16:25:15 +0200315static int class_httpclient_ref;
Thierry FOURNIER3def3932015-04-07 11:27:54 +0200316static int class_map_ref;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +0200317static int class_applet_tcp_ref;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200318static int class_applet_http_ref;
Christopher Faulet700d9e82020-01-31 12:21:52 +0100319static int class_txn_reply_ref;
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +0100320
Thierry FOURNIERbd413492015-03-03 16:52:26 +0100321/* Global Lua execution timeout. By default Lua, execution linked
Willy Tarreau87b09662015-04-03 00:22:06 +0200322 * with stream (actions, sample-fetches and converters) have a
Thierry FOURNIERbd413492015-03-03 16:52:26 +0100323 * short timeout. Lua linked with tasks doesn't have a timeout
324 * because a task may remain alive during all the haproxy execution.
325 */
326static unsigned int hlua_timeout_session = 4000; /* session timeout. */
327static unsigned int hlua_timeout_task = TICK_ETERNITY; /* task timeout. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +0200328static unsigned int hlua_timeout_applet = 4000; /* applet timeout. */
Thierry FOURNIERbd413492015-03-03 16:52:26 +0100329
Thierry FOURNIERee9f8022015-03-03 17:37:37 +0100330/* Interrupts the Lua processing each "hlua_nb_instruction" instructions.
331 * it is used for preventing infinite loops.
332 *
333 * I test the scheer with an infinite loop containing one incrementation
334 * and one test. I run this loop between 10 seconds, I raise a ceil of
335 * 710M loops from one interrupt each 9000 instructions, so I fix the value
336 * to one interrupt each 10 000 instructions.
337 *
338 * configured | Number of
339 * instructions | loops executed
340 * between two | in milions
341 * forced yields |
342 * ---------------+---------------
343 * 10 | 160
344 * 500 | 670
345 * 1000 | 680
346 * 5000 | 700
347 * 7000 | 700
348 * 8000 | 700
349 * 9000 | 710 <- ceil
350 * 10000 | 710
351 * 100000 | 710
352 * 1000000 | 710
353 *
354 */
355static unsigned int hlua_nb_instruction = 10000;
356
Willy Tarreaucdb53462020-12-02 12:12:00 +0100357/* Descriptor for the memory allocation state. The limit is pre-initialised to
358 * 0 until it is replaced by "tune.lua.maxmem" during the config parsing, or it
359 * is replaced with ~0 during post_init after everything was loaded. This way
360 * it is guaranteed that if limit is ~0 the boot is complete and that if it's
361 * zero it's not yet limited and proper accounting is required.
Willy Tarreau32f61e22015-03-18 17:54:59 +0100362 */
363struct hlua_mem_allocator {
364 size_t allocated;
365 size_t limit;
366};
367
Willy Tarreaucdb53462020-12-02 12:12:00 +0100368static struct hlua_mem_allocator hlua_global_allocator THREAD_ALIGNED(64);
Willy Tarreau32f61e22015-03-18 17:54:59 +0100369
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100370/* These functions converts types between HAProxy internal args or
371 * sample and LUA types. Another function permits to check if the
372 * LUA stack contains arguments according with an required ARG_T
373 * format.
374 */
375static int hlua_arg2lua(lua_State *L, const struct arg *arg);
376static int hlua_lua2arg(lua_State *L, int ud, struct arg *arg);
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100377__LJMP static int hlua_lua2arg_check(lua_State *L, int first, struct arg *argp,
David Carlier0c437f42016-04-27 16:21:56 +0100378 uint64_t mask, struct proxy *p);
Willy Tarreau5eadada2015-03-10 17:28:54 +0100379static int hlua_smp2lua(lua_State *L, struct sample *smp);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100380static int hlua_smp2lua_str(lua_State *L, struct sample *smp);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100381static int hlua_lua2smp(lua_State *L, int ud, struct sample *smp);
382
Christopher Faulet9d1332b2020-02-24 16:46:16 +0100383__LJMP static int hlua_http_get_headers(lua_State *L, struct http_msg *msg);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200384
Thierry Fournier59f11be2020-11-29 00:37:41 +0100385struct prepend_path {
386 struct list l;
387 char *type;
388 char *path;
389};
390
391static struct list prepend_path_list = LIST_HEAD_INIT(prepend_path_list);
392
Thierry FOURNIER23bc3752015-09-11 19:15:43 +0200393#define SEND_ERR(__be, __fmt, __args...) \
394 do { \
395 send_log(__be, LOG_ERR, __fmt, ## __args); \
396 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE)) \
Christopher Faulet767a84b2017-11-24 16:50:31 +0100397 ha_alert(__fmt, ## __args); \
Thierry FOURNIER23bc3752015-09-11 19:15:43 +0200398 } while (0)
399
Thierry Fournier62a22aa2020-11-28 21:06:35 +0100400static inline struct hlua_function *new_hlua_function()
401{
402 struct hlua_function *fcn;
Thierry Fournierc7492592020-11-28 23:57:24 +0100403 int i;
Thierry Fournier62a22aa2020-11-28 21:06:35 +0100404
405 fcn = calloc(1, sizeof(*fcn));
406 if (!fcn)
407 return NULL;
Willy Tarreau2b718102021-04-21 07:32:39 +0200408 LIST_APPEND(&referenced_functions, &fcn->l);
Thierry Fournierc7492592020-11-28 23:57:24 +0100409 for (i = 0; i < MAX_THREADS + 1; i++)
410 fcn->function_ref[i] = -1;
Thierry Fournier62a22aa2020-11-28 21:06:35 +0100411 return fcn;
412}
413
Christopher Fauletdda44442021-04-12 14:05:43 +0200414static inline void release_hlua_function(struct hlua_function *fcn)
415{
416 if (!fcn)
417 return;
418 if (fcn->name)
419 ha_free(&fcn->name);
Willy Tarreau2b718102021-04-21 07:32:39 +0200420 LIST_DELETE(&fcn->l);
Christopher Fauletdda44442021-04-12 14:05:43 +0200421 ha_free(&fcn);
422}
423
Thierry Fournierc7492592020-11-28 23:57:24 +0100424/* If the common state is set, the stack id is 0, otherwise it is the tid + 1 */
425static inline int fcn_ref_to_stack_id(struct hlua_function *fcn)
426{
427 if (fcn->function_ref[0] == -1)
428 return tid + 1;
429 return 0;
430}
431
Christopher Faulet69c581a2021-05-31 08:54:04 +0200432/* Create a new registered filter. Only its name is filled */
433static inline struct hlua_reg_filter *new_hlua_reg_filter(const char *name)
434{
435 struct hlua_reg_filter *reg_flt;
436 int i;
437
438 reg_flt = calloc(1, sizeof(*reg_flt));
439 if (!reg_flt)
440 return NULL;
441 reg_flt->name = strdup(name);
442 if (!reg_flt->name) {
443 free(reg_flt);
444 return NULL;
445 }
446 LIST_APPEND(&referenced_filters, &reg_flt->l);
447 for (i = 0; i < MAX_THREADS + 1; i++) {
448 reg_flt->flt_ref[i] = -1;
449 reg_flt->fun_ref[i] = -1;
450 }
451 return reg_flt;
452}
453
454/* Release a registered filter */
455static inline void release_hlua_reg_filter(struct hlua_reg_filter *reg_flt)
456{
457 if (!reg_flt)
458 return;
459 if (reg_flt->name)
460 ha_free(&reg_flt->name);
461 LIST_DELETE(&reg_flt->l);
462 ha_free(&reg_flt);
463}
464
465/* If the common state is set, the stack id is 0, otherwise it is the tid + 1 */
466static inline int reg_flt_to_stack_id(struct hlua_reg_filter *reg_flt)
467{
468 if (reg_flt->fun_ref[0] == -1)
469 return tid + 1;
470 return 0;
471}
472
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100473/* Used to check an Lua function type in the stack. It creates and
474 * returns a reference of the function. This function throws an
475 * error if the rgument is not a "function".
476 */
477__LJMP unsigned int hlua_checkfunction(lua_State *L, int argno)
478{
479 if (!lua_isfunction(L, argno)) {
Thierry FOURNIERfd1e9552018-02-23 18:41:18 +0100480 const char *msg = lua_pushfstring(L, "function expected, got %s", luaL_typename(L, argno));
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100481 WILL_LJMP(luaL_argerror(L, argno, msg));
482 }
483 lua_pushvalue(L, argno);
484 return luaL_ref(L, LUA_REGISTRYINDEX);
485}
486
Christopher Fauletba9e21d2020-02-25 10:20:04 +0100487/* Used to check an Lua table type in the stack. It creates and
488 * returns a reference of the table. This function throws an
489 * error if the rgument is not a "table".
490 */
491__LJMP unsigned int hlua_checktable(lua_State *L, int argno)
492{
493 if (!lua_istable(L, argno)) {
494 const char *msg = lua_pushfstring(L, "table expected, got %s", luaL_typename(L, argno));
495 WILL_LJMP(luaL_argerror(L, argno, msg));
496 }
497 lua_pushvalue(L, argno);
498 return luaL_ref(L, LUA_REGISTRYINDEX);
499}
500
Christopher Fauletd09cc512021-03-24 14:48:45 +0100501__LJMP const char *hlua_traceback(lua_State *L, const char* sep)
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200502{
503 lua_Debug ar;
504 int level = 0;
Willy Tarreau83061a82018-07-13 11:56:34 +0200505 struct buffer *msg = get_trash_chunk();
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200506
507 while (lua_getstack(L, level++, &ar)) {
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200508 /* Fill fields:
509 * 'S': fills in the fields source, short_src, linedefined, lastlinedefined, and what;
510 * 'l': fills in the field currentline;
511 * 'n': fills in the field name and namewhat;
512 * 't': fills in the field istailcall;
513 */
514 lua_getinfo(L, "Slnt", &ar);
515
Willy Tarreau5c143402022-06-19 17:35:53 +0200516 /* skip these empty entries, usually they come from deep C functions */
517 if (ar.currentline < 0 && *ar.what == 'C' && !*ar.namewhat && !ar.name)
518 continue;
519
520 /* Add separator */
521 if (b_data(msg))
522 chunk_appendf(msg, "%s", sep);
523
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200524 /* Append code localisation */
525 if (ar.currentline > 0)
Christopher Fauletd09cc512021-03-24 14:48:45 +0100526 chunk_appendf(msg, "%s:%d: ", ar.short_src, ar.currentline);
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200527 else
Christopher Fauletd09cc512021-03-24 14:48:45 +0100528 chunk_appendf(msg, "%s: ", ar.short_src);
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200529
530 /*
531 * Get function name
532 *
533 * if namewhat is no empty, name is defined.
534 * what contains "Lua" for Lua function, "C" for C function,
535 * or "main" for main code.
536 */
537 if (*ar.namewhat != '\0' && ar.name != NULL) /* is there a name from code? */
Christopher Fauletd09cc512021-03-24 14:48:45 +0100538 chunk_appendf(msg, "in %s '%s'", ar.namewhat, ar.name); /* use it */
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200539
540 else if (*ar.what == 'm') /* "main", the code is not executed in a function */
Christopher Fauletd09cc512021-03-24 14:48:45 +0100541 chunk_appendf(msg, "in main chunk");
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200542
543 else if (*ar.what != 'C') /* for Lua functions, use <file:line> */
Christopher Fauletd09cc512021-03-24 14:48:45 +0100544 chunk_appendf(msg, "in function line %d", ar.linedefined);
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200545
546 else /* nothing left... */
547 chunk_appendf(msg, "?");
548
549
550 /* Display tailed call */
551 if (ar.istailcall)
552 chunk_appendf(msg, " ...");
553 }
554
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200555 return msg->area;
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200556}
557
558
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100559/* This function check the number of arguments available in the
560 * stack. If the number of arguments available is not the same
Ilya Shipitsinc02a23f2020-05-06 00:53:22 +0500561 * then <nb> an error is thrown.
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100562 */
563__LJMP static inline void check_args(lua_State *L, int nb, char *fcn)
564{
565 if (lua_gettop(L) == nb)
566 return;
567 WILL_LJMP(luaL_error(L, "'%s' needs %d arguments", fcn, nb));
568}
569
Mark Lakes22154b42018-01-29 14:38:40 -0800570/* This function pushes an error string prefixed by the file name
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100571 * and the line number where the error is encountered.
572 */
573static int hlua_pusherror(lua_State *L, const char *fmt, ...)
574{
575 va_list argp;
576 va_start(argp, fmt);
577 luaL_where(L, 1);
578 lua_pushvfstring(L, fmt, argp);
579 va_end(argp);
580 lua_concat(L, 2);
581 return 1;
582}
583
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100584/* This functions is used with sample fetch and converters. It
585 * converts the HAProxy configuration argument in a lua stack
586 * values.
587 *
588 * It takes an array of "arg", and each entry of the array is
589 * converted and pushed in the LUA stack.
590 */
591static int hlua_arg2lua(lua_State *L, const struct arg *arg)
592{
593 switch (arg->type) {
594 case ARGT_SINT:
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100595 case ARGT_TIME:
596 case ARGT_SIZE:
Thierry FOURNIERf90838b2015-03-06 13:48:32 +0100597 lua_pushinteger(L, arg->data.sint);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100598 break;
599
600 case ARGT_STR:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200601 lua_pushlstring(L, arg->data.str.area, arg->data.str.data);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100602 break;
603
604 case ARGT_IPV4:
605 case ARGT_IPV6:
606 case ARGT_MSK4:
607 case ARGT_MSK6:
608 case ARGT_FE:
609 case ARGT_BE:
610 case ARGT_TAB:
611 case ARGT_SRV:
612 case ARGT_USR:
613 case ARGT_MAP:
614 default:
615 lua_pushnil(L);
616 break;
617 }
618 return 1;
619}
620
Ilya Shipitsinc02a23f2020-05-06 00:53:22 +0500621/* This function take one entry in an LUA stack at the index "ud",
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100622 * and try to convert it in an HAProxy argument entry. This is useful
Ilya Shipitsind4259502020-04-08 01:07:56 +0500623 * with sample fetch wrappers. The input arguments are given to the
624 * lua wrapper and converted as arg list by the function.
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100625 */
626static int hlua_lua2arg(lua_State *L, int ud, struct arg *arg)
627{
628 switch (lua_type(L, ud)) {
629
630 case LUA_TNUMBER:
631 case LUA_TBOOLEAN:
632 arg->type = ARGT_SINT;
633 arg->data.sint = lua_tointeger(L, ud);
634 break;
635
636 case LUA_TSTRING:
637 arg->type = ARGT_STR;
Tim Duesterhus2e89dec2019-09-29 23:03:08 +0200638 arg->data.str.area = (char *)lua_tolstring(L, ud, &arg->data.str.data);
Tim Duesterhus29d2e8a2019-09-29 23:03:07 +0200639 /* We don't know the actual size of the underlying allocation, so be conservative. */
Christopher Fauletfdea1b62020-08-06 08:29:18 +0200640 arg->data.str.size = arg->data.str.data+1; /* count the terminating null byte */
Tim Duesterhus29d2e8a2019-09-29 23:03:07 +0200641 arg->data.str.head = 0;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100642 break;
643
644 case LUA_TUSERDATA:
645 case LUA_TNIL:
646 case LUA_TTABLE:
647 case LUA_TFUNCTION:
648 case LUA_TTHREAD:
649 case LUA_TLIGHTUSERDATA:
650 arg->type = ARGT_SINT;
Thierry FOURNIERbf65cd42015-07-20 17:45:02 +0200651 arg->data.sint = 0;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100652 break;
653 }
654 return 1;
655}
656
657/* the following functions are used to convert a struct sample
658 * in Lua type. This useful to convert the return of the
Ilya Shipitsind4259502020-04-08 01:07:56 +0500659 * fetches or converters.
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100660 */
Willy Tarreau5eadada2015-03-10 17:28:54 +0100661static int hlua_smp2lua(lua_State *L, struct sample *smp)
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100662{
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200663 switch (smp->data.type) {
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100664 case SMP_T_SINT:
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100665 case SMP_T_BOOL:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200666 lua_pushinteger(L, smp->data.u.sint);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100667 break;
668
669 case SMP_T_BIN:
670 case SMP_T_STR:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200671 lua_pushlstring(L, smp->data.u.str.area, smp->data.u.str.data);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100672 break;
673
674 case SMP_T_METH:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200675 switch (smp->data.u.meth.meth) {
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100676 case HTTP_METH_OPTIONS: lua_pushstring(L, "OPTIONS"); break;
677 case HTTP_METH_GET: lua_pushstring(L, "GET"); break;
678 case HTTP_METH_HEAD: lua_pushstring(L, "HEAD"); break;
679 case HTTP_METH_POST: lua_pushstring(L, "POST"); break;
680 case HTTP_METH_PUT: lua_pushstring(L, "PUT"); break;
681 case HTTP_METH_DELETE: lua_pushstring(L, "DELETE"); break;
682 case HTTP_METH_TRACE: lua_pushstring(L, "TRACE"); break;
683 case HTTP_METH_CONNECT: lua_pushstring(L, "CONNECT"); break;
684 case HTTP_METH_OTHER:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200685 lua_pushlstring(L, smp->data.u.meth.str.area, smp->data.u.meth.str.data);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100686 break;
687 default:
688 lua_pushnil(L);
689 break;
690 }
691 break;
692
693 case SMP_T_IPV4:
694 case SMP_T_IPV6:
695 case SMP_T_ADDR: /* This type is never used to qualify a sample. */
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200696 if (sample_casts[smp->data.type][SMP_T_STR] &&
697 sample_casts[smp->data.type][SMP_T_STR](smp))
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200698 lua_pushlstring(L, smp->data.u.str.area, smp->data.u.str.data);
Willy Tarreau5eadada2015-03-10 17:28:54 +0100699 else
700 lua_pushnil(L);
701 break;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100702 default:
703 lua_pushnil(L);
704 break;
705 }
706 return 1;
707}
708
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100709/* the following functions are used to convert a struct sample
710 * in Lua strings. This is useful to convert the return of the
Ilya Shipitsind4259502020-04-08 01:07:56 +0500711 * fetches or converters.
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100712 */
713static int hlua_smp2lua_str(lua_State *L, struct sample *smp)
714{
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200715 switch (smp->data.type) {
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100716
717 case SMP_T_BIN:
718 case SMP_T_STR:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200719 lua_pushlstring(L, smp->data.u.str.area, smp->data.u.str.data);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100720 break;
721
722 case SMP_T_METH:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200723 switch (smp->data.u.meth.meth) {
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100724 case HTTP_METH_OPTIONS: lua_pushstring(L, "OPTIONS"); break;
725 case HTTP_METH_GET: lua_pushstring(L, "GET"); break;
726 case HTTP_METH_HEAD: lua_pushstring(L, "HEAD"); break;
727 case HTTP_METH_POST: lua_pushstring(L, "POST"); break;
728 case HTTP_METH_PUT: lua_pushstring(L, "PUT"); break;
729 case HTTP_METH_DELETE: lua_pushstring(L, "DELETE"); break;
730 case HTTP_METH_TRACE: lua_pushstring(L, "TRACE"); break;
731 case HTTP_METH_CONNECT: lua_pushstring(L, "CONNECT"); break;
732 case HTTP_METH_OTHER:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200733 lua_pushlstring(L, smp->data.u.meth.str.area, smp->data.u.meth.str.data);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100734 break;
735 default:
736 lua_pushstring(L, "");
737 break;
738 }
739 break;
740
741 case SMP_T_SINT:
742 case SMP_T_BOOL:
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100743 case SMP_T_IPV4:
744 case SMP_T_IPV6:
745 case SMP_T_ADDR: /* This type is never used to qualify a sample. */
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200746 if (sample_casts[smp->data.type][SMP_T_STR] &&
747 sample_casts[smp->data.type][SMP_T_STR](smp))
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200748 lua_pushlstring(L, smp->data.u.str.area, smp->data.u.str.data);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100749 else
750 lua_pushstring(L, "");
751 break;
752 default:
753 lua_pushstring(L, "");
754 break;
755 }
756 return 1;
757}
758
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100759/* the following functions are used to convert an Lua type in a
760 * struct sample. This is useful to provide data from a converter
761 * to the LUA code.
762 */
763static int hlua_lua2smp(lua_State *L, int ud, struct sample *smp)
764{
765 switch (lua_type(L, ud)) {
766
767 case LUA_TNUMBER:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200768 smp->data.type = SMP_T_SINT;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200769 smp->data.u.sint = lua_tointeger(L, ud);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100770 break;
771
772
773 case LUA_TBOOLEAN:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200774 smp->data.type = SMP_T_BOOL;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200775 smp->data.u.sint = lua_toboolean(L, ud);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100776 break;
777
778 case LUA_TSTRING:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200779 smp->data.type = SMP_T_STR;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100780 smp->flags |= SMP_F_CONST;
Tim Duesterhus2e89dec2019-09-29 23:03:08 +0200781 smp->data.u.str.area = (char *)lua_tolstring(L, ud, &smp->data.u.str.data);
Tim Duesterhus29d2e8a2019-09-29 23:03:07 +0200782 /* We don't know the actual size of the underlying allocation, so be conservative. */
Christopher Fauletfdea1b62020-08-06 08:29:18 +0200783 smp->data.u.str.size = smp->data.u.str.data+1; /* count the terminating null byte */
Tim Duesterhus29d2e8a2019-09-29 23:03:07 +0200784 smp->data.u.str.head = 0;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100785 break;
786
787 case LUA_TUSERDATA:
788 case LUA_TNIL:
789 case LUA_TTABLE:
790 case LUA_TFUNCTION:
791 case LUA_TTHREAD:
792 case LUA_TLIGHTUSERDATA:
Thierry FOURNIER93405e12015-08-26 14:19:03 +0200793 case LUA_TNONE:
794 default:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200795 smp->data.type = SMP_T_BOOL;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200796 smp->data.u.sint = 0;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100797 break;
798 }
799 return 1;
800}
801
Ilya Shipitsind4259502020-04-08 01:07:56 +0500802/* This function check the "argp" built by another conversion function
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -0800803 * is in accord with the expected argp defined by the "mask". The function
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100804 * returns true or false. It can be adjust the types if there compatibles.
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100805 *
Ilya Shipitsinc02a23f2020-05-06 00:53:22 +0500806 * This function assumes that the argp argument contains ARGM_NBARGS + 1
Willy Tarreauee0d7272021-07-16 10:26:56 +0200807 * entries and that there is at least one stop at the last position.
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100808 */
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100809__LJMP int hlua_lua2arg_check(lua_State *L, int first, struct arg *argp,
David Carlier0c437f42016-04-27 16:21:56 +0100810 uint64_t mask, struct proxy *p)
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100811{
812 int min_arg;
Willy Tarreauee0d7272021-07-16 10:26:56 +0200813 int idx;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100814 struct proxy *px;
Christopher Fauletd25d9262020-08-06 11:04:46 +0200815 struct userlist *ul;
Christopher Fauletfd2e9062020-08-06 11:10:57 +0200816 struct my_regex *reg;
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200817 const char *msg = NULL;
Christopher Fauletfd2e9062020-08-06 11:10:57 +0200818 char *sname, *pname, *err = NULL;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100819
820 idx = 0;
821 min_arg = ARGM(mask);
822 mask >>= ARGM_BITS;
823
824 while (1) {
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200825 struct buffer tmp = BUF_NULL;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100826
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100827 /* Check for mandatory arguments. */
828 if (argp[idx].type == ARGT_STOP) {
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100829 if (idx < min_arg) {
830
831 /* If miss other argument than the first one, we return an error. */
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200832 if (idx > 0) {
833 msg = "Mandatory argument expected";
834 goto error;
835 }
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100836
837 /* If first argument have a certain type, some default values
838 * may be used. See the function smp_resolve_args().
839 */
840 switch (mask & ARGT_MASK) {
841
842 case ARGT_FE:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200843 if (!(p->cap & PR_CAP_FE)) {
844 msg = "Mandatory argument expected";
845 goto error;
846 }
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100847 argp[idx].data.prx = p;
848 argp[idx].type = ARGT_FE;
849 argp[idx+1].type = ARGT_STOP;
850 break;
851
852 case ARGT_BE:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200853 if (!(p->cap & PR_CAP_BE)) {
854 msg = "Mandatory argument expected";
855 goto error;
856 }
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100857 argp[idx].data.prx = p;
858 argp[idx].type = ARGT_BE;
859 argp[idx+1].type = ARGT_STOP;
860 break;
861
862 case ARGT_TAB:
Olivier Houchard14f62682022-09-13 00:35:53 +0200863 if (!p->table) {
864 msg = "Mandatory argument expected";
865 goto error;
866 }
867 argp[idx].data.t = p->table;
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100868 argp[idx].type = ARGT_TAB;
869 argp[idx+1].type = ARGT_STOP;
870 break;
871
872 default:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200873 msg = "Mandatory argument expected";
874 goto error;
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100875 break;
876 }
877 }
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200878 break;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100879 }
880
Ilya Shipitsin856aabc2020-04-16 23:51:34 +0500881 /* Check for exceed the number of required argument. */
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100882 if ((mask & ARGT_MASK) == ARGT_STOP &&
883 argp[idx].type != ARGT_STOP) {
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200884 msg = "Last argument expected";
885 goto error;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100886 }
887
888 if ((mask & ARGT_MASK) == ARGT_STOP &&
889 argp[idx].type == ARGT_STOP) {
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200890 break;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100891 }
892
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200893 /* Convert some argument types. All string in argp[] are for not
894 * duplicated yet.
895 */
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100896 switch (mask & ARGT_MASK) {
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100897 case ARGT_SINT:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200898 if (argp[idx].type != ARGT_SINT) {
899 msg = "integer expected";
900 goto error;
901 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100902 argp[idx].type = ARGT_SINT;
903 break;
904
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100905 case ARGT_TIME:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200906 if (argp[idx].type != ARGT_SINT) {
907 msg = "integer expected";
908 goto error;
909 }
Thierry FOURNIER29176f32015-07-07 00:41:29 +0200910 argp[idx].type = ARGT_TIME;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100911 break;
912
913 case ARGT_SIZE:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200914 if (argp[idx].type != ARGT_SINT) {
915 msg = "integer expected";
916 goto error;
917 }
Thierry FOURNIER29176f32015-07-07 00:41:29 +0200918 argp[idx].type = ARGT_SIZE;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100919 break;
920
921 case ARGT_FE:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200922 if (argp[idx].type != ARGT_STR) {
923 msg = "string expected";
924 goto error;
925 }
Christopher Fauletfdea1b62020-08-06 08:29:18 +0200926 argp[idx].data.prx = proxy_fe_by_name(argp[idx].data.str.area);
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200927 if (!argp[idx].data.prx) {
928 msg = "frontend doesn't exist";
929 goto error;
930 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100931 argp[idx].type = ARGT_FE;
932 break;
933
934 case ARGT_BE:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200935 if (argp[idx].type != ARGT_STR) {
936 msg = "string expected";
937 goto error;
938 }
Christopher Fauletfdea1b62020-08-06 08:29:18 +0200939 argp[idx].data.prx = proxy_be_by_name(argp[idx].data.str.area);
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200940 if (!argp[idx].data.prx) {
941 msg = "backend doesn't exist";
942 goto error;
943 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100944 argp[idx].type = ARGT_BE;
945 break;
946
947 case ARGT_TAB:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200948 if (argp[idx].type != ARGT_STR) {
949 msg = "string expected";
950 goto error;
951 }
Christopher Fauletfdea1b62020-08-06 08:29:18 +0200952 argp[idx].data.t = stktable_find_by_name(argp[idx].data.str.area);
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200953 if (!argp[idx].data.t) {
954 msg = "table doesn't exist";
955 goto error;
956 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100957 argp[idx].type = ARGT_TAB;
958 break;
959
960 case ARGT_SRV:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200961 if (argp[idx].type != ARGT_STR) {
962 msg = "string expected";
963 goto error;
964 }
Christopher Fauletfdea1b62020-08-06 08:29:18 +0200965 sname = strrchr(argp[idx].data.str.area, '/');
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100966 if (sname) {
967 *sname++ = '\0';
Christopher Fauletfdea1b62020-08-06 08:29:18 +0200968 pname = argp[idx].data.str.area;
Willy Tarreau9e0bb102015-05-26 11:24:42 +0200969 px = proxy_be_by_name(pname);
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200970 if (!px) {
971 msg = "backend doesn't exist";
972 goto error;
973 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100974 }
975 else {
Christopher Fauletfdea1b62020-08-06 08:29:18 +0200976 sname = argp[idx].data.str.area;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100977 px = p;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100978 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100979 argp[idx].data.srv = findserver(px, sname);
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200980 if (!argp[idx].data.srv) {
981 msg = "server doesn't exist";
982 goto error;
983 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100984 argp[idx].type = ARGT_SRV;
985 break;
986
987 case ARGT_IPV4:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200988 if (argp[idx].type != ARGT_STR) {
989 msg = "string expected";
990 goto error;
991 }
992 if (inet_pton(AF_INET, argp[idx].data.str.area, &argp[idx].data.ipv4)) {
993 msg = "invalid IPv4 address";
994 goto error;
995 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100996 argp[idx].type = ARGT_IPV4;
997 break;
998
999 case ARGT_MSK4:
Christopher Faulete663a6e2020-08-07 09:11:22 +02001000 if (argp[idx].type == ARGT_SINT)
1001 len2mask4(argp[idx].data.sint, &argp[idx].data.ipv4);
1002 else if (argp[idx].type == ARGT_STR) {
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001003 if (!str2mask(argp[idx].data.str.area, &argp[idx].data.ipv4)) {
1004 msg = "invalid IPv4 mask";
1005 goto error;
1006 }
1007 }
1008 else {
1009 msg = "integer or string expected";
1010 goto error;
Christopher Faulete663a6e2020-08-07 09:11:22 +02001011 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001012 argp[idx].type = ARGT_MSK4;
1013 break;
1014
1015 case ARGT_IPV6:
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001016 if (argp[idx].type != ARGT_STR) {
1017 msg = "string expected";
1018 goto error;
1019 }
1020 if (inet_pton(AF_INET6, argp[idx].data.str.area, &argp[idx].data.ipv6)) {
1021 msg = "invalid IPv6 address";
1022 goto error;
1023 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001024 argp[idx].type = ARGT_IPV6;
1025 break;
1026
1027 case ARGT_MSK6:
Christopher Faulete663a6e2020-08-07 09:11:22 +02001028 if (argp[idx].type == ARGT_SINT)
1029 len2mask6(argp[idx].data.sint, &argp[idx].data.ipv6);
1030 else if (argp[idx].type == ARGT_STR) {
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001031 if (!str2mask6(argp[idx].data.str.area, &argp[idx].data.ipv6)) {
1032 msg = "invalid IPv6 mask";
1033 goto error;
1034 }
1035 }
1036 else {
1037 msg = "integer or string expected";
1038 goto error;
Christopher Faulete663a6e2020-08-07 09:11:22 +02001039 }
Tim Duesterhusb814da62018-01-25 16:24:50 +01001040 argp[idx].type = ARGT_MSK6;
1041 break;
1042
Christopher Fauletfd2e9062020-08-06 11:10:57 +02001043 case ARGT_REG:
1044 if (argp[idx].type != ARGT_STR) {
1045 msg = "string expected";
1046 goto error;
1047 }
1048 reg = regex_comp(argp[idx].data.str.area, !(argp[idx].type_flags & ARGF_REG_ICASE), 1, &err);
1049 if (!reg) {
1050 msg = lua_pushfstring(L, "error compiling regex '%s' : '%s'",
1051 argp[idx].data.str.area, err);
1052 free(err);
1053 goto error;
1054 }
1055 argp[idx].type = ARGT_REG;
1056 argp[idx].data.reg = reg;
1057 break;
1058
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001059 case ARGT_USR:
Christopher Fauletd25d9262020-08-06 11:04:46 +02001060 if (argp[idx].type != ARGT_STR) {
1061 msg = "string expected";
1062 goto error;
1063 }
1064 if (p->uri_auth && p->uri_auth->userlist &&
Tim Duesterhuse5ff1412021-01-02 22:31:53 +01001065 strcmp(p->uri_auth->userlist->name, argp[idx].data.str.area) == 0)
Christopher Fauletd25d9262020-08-06 11:04:46 +02001066 ul = p->uri_auth->userlist;
1067 else
1068 ul = auth_find_userlist(argp[idx].data.str.area);
1069
1070 if (!ul) {
1071 msg = lua_pushfstring(L, "unable to find userlist '%s'", argp[idx].data.str.area);
1072 goto error;
1073 }
1074 argp[idx].type = ARGT_USR;
1075 argp[idx].data.usr = ul;
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001076 break;
1077
1078 case ARGT_STR:
1079 if (!chunk_dup(&tmp, &argp[idx].data.str)) {
1080 msg = "unable to duplicate string arg";
1081 goto error;
1082 }
1083 argp[idx].data.str = tmp;
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001084 break;
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001085
Christopher Fauletd25d9262020-08-06 11:04:46 +02001086 case ARGT_MAP:
Christopher Fauletd25d9262020-08-06 11:04:46 +02001087 msg = "type not yet supported";
1088 goto error;
1089 break;
1090
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001091 }
1092
1093 /* Check for type of argument. */
1094 if ((mask & ARGT_MASK) != argp[idx].type) {
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001095 msg = lua_pushfstring(L, "'%s' expected, got '%s'",
1096 arg_type_names[(mask & ARGT_MASK)],
1097 arg_type_names[argp[idx].type & ARGT_MASK]);
1098 goto error;
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001099 }
1100
1101 /* Next argument. */
1102 mask >>= ARGT_BITS;
1103 idx++;
1104 }
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001105 return 0;
1106
1107 error:
Olivier Houchardca431612022-09-13 00:31:17 +02001108 argp[idx].type = ARGT_STOP;
Willy Tarreauee0d7272021-07-16 10:26:56 +02001109 free_args(argp);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001110 WILL_LJMP(luaL_argerror(L, first + idx, msg));
1111 return 0; /* Never reached */
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001112}
1113
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001114/*
Ilya Shipitsinc02a23f2020-05-06 00:53:22 +05001115 * The following functions are used to make correspondence between the the
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001116 * executed lua pointer and the "struct hlua *" that contain the context.
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001117 *
1118 * - hlua_gethlua : return the hlua context associated with an lua_State.
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001119 * - hlua_sethlua : create the association between hlua context and lua_state.
1120 */
1121static inline struct hlua *hlua_gethlua(lua_State *L)
1122{
Thierry FOURNIER38c5fd62015-03-10 02:40:29 +01001123 struct hlua **hlua = lua_getextraspace(L);
1124 return *hlua;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001125}
1126static inline void hlua_sethlua(struct hlua *hlua)
1127{
Thierry FOURNIER38c5fd62015-03-10 02:40:29 +01001128 struct hlua **hlua_store = lua_getextraspace(hlua->T);
1129 *hlua_store = hlua;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001130}
1131
Willy Tarreau0b7b6392022-06-19 17:39:33 +02001132/* Will return a non-NULL string indicating the Lua call trace if the caller
1133 * currently is executing from within a Lua function. One line per entry will
1134 * be emitted, and each extra line will be prefixed with <pfx>. If a current
1135 * Lua function is not detected, NULL is returned.
1136 */
1137const char *hlua_show_current_location(const char *pfx)
1138{
1139 lua_State *L;
1140 lua_Debug ar;
1141
1142 /* global or per-thread stack initializing ? */
1143 if (hlua_state_id != -1 && (L = hlua_states[hlua_state_id]) && lua_getstack(L, 0, &ar))
1144 return hlua_traceback(L, pfx);
1145
1146 /* per-thread stack running ? */
1147 if (hlua_states[tid + 1] && (L = hlua_states[tid + 1]) && lua_getstack(L, 0, &ar))
1148 return hlua_traceback(L, pfx);
1149
1150 /* global stack running ? */
1151 if (hlua_states[0] && (L = hlua_states[0]) && lua_getstack(L, 0, &ar))
1152 return hlua_traceback(L, pfx);
1153
1154 return NULL;
1155}
1156
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01001157/* This function is used to send logs. It try to send on screen (stderr)
1158 * and on the default syslog server.
1159 */
1160static inline void hlua_sendlog(struct proxy *px, int level, const char *msg)
1161{
1162 struct tm tm;
1163 char *p;
1164
1165 /* Cleanup the log message. */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001166 p = trash.area;
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01001167 for (; *msg != '\0'; msg++, p++) {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001168 if (p >= trash.area + trash.size - 1) {
Thierry FOURNIERccf00632015-09-16 12:47:03 +02001169 /* Break the message if exceed the buffer size. */
1170 *(p-4) = ' ';
1171 *(p-3) = '.';
1172 *(p-2) = '.';
1173 *(p-1) = '.';
1174 break;
1175 }
Willy Tarreau90807112020-02-25 08:16:33 +01001176 if (isprint((unsigned char)*msg))
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01001177 *p = *msg;
1178 else
1179 *p = '.';
1180 }
1181 *p = '\0';
1182
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001183 send_log(px, level, "%s\n", trash.area);
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01001184 if (!(global.mode & MODE_QUIET) || (global.mode & (MODE_VERBOSE | MODE_STARTING))) {
Christopher Fauletf98d8212020-10-02 18:13:52 +02001185 if (level == LOG_DEBUG && !(global.mode & MODE_DEBUG))
1186 return;
1187
Willy Tarreaua678b432015-08-28 10:14:59 +02001188 get_localtime(date.tv_sec, &tm);
1189 fprintf(stderr, "[%s] %03d/%02d%02d%02d (%d) : %s\n",
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01001190 log_levels[level], tm.tm_yday, tm.tm_hour, tm.tm_min, tm.tm_sec,
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001191 (int)getpid(), trash.area);
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01001192 fflush(stderr);
1193 }
1194}
1195
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001196/* This function just ensure that the yield will be always
1197 * returned with a timeout and permit to set some flags
1198 */
1199__LJMP void hlua_yieldk(lua_State *L, int nresults, int ctx,
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001200 lua_KFunction k, int timeout, unsigned int flags)
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001201{
Thierry Fournier4234dbd2020-11-28 13:18:23 +01001202 struct hlua *hlua;
1203
1204 /* Get hlua struct, or NULL if we execute from main lua state */
1205 hlua = hlua_gethlua(L);
1206 if (!hlua) {
1207 return;
1208 }
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001209
1210 /* Set the wake timeout. If timeout is required, we set
1211 * the expiration time.
1212 */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001213 hlua->wake_time = timeout;
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001214
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01001215 hlua->flags |= flags;
1216
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001217 /* Process the yield. */
Willy Tarreau9635e032018-10-16 17:52:55 +02001218 MAY_LJMP(lua_yieldk(L, nresults, ctx, k));
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001219}
1220
Willy Tarreau87b09662015-04-03 00:22:06 +02001221/* This function initialises the Lua environment stored in the stream.
1222 * It must be called at the start of the stream. This function creates
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001223 * an LUA coroutine. It can not be use to crete the main LUA context.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02001224 *
1225 * This function is particular. it initialises a new Lua thread. If the
1226 * initialisation fails (example: out of memory error), the lua function
1227 * throws an error (longjmp).
1228 *
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +01001229 * In some case (at least one), this function can be called from safe
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001230 * environment, so we must not initialise it. While the support of
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +01001231 * threads appear, the safe environment set a lock to ensure only one
1232 * Lua execution at a time. If we initialize safe environment in another
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001233 * safe environment, we have a dead lock.
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +01001234 *
1235 * set "already_safe" true if the context is initialized form safe
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001236 * Lua function.
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +01001237 *
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001238 * This function manipulates two Lua stacks: the main and the thread. Only
Thierry FOURNIERbabae282015-09-17 11:36:37 +02001239 * the main stack can fail. The thread is not manipulated. This function
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001240 * MUST NOT manipulate the created thread stack state, because it is not
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001241 * protected against errors thrown by the thread stack.
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001242 */
Thierry Fournier021d9862020-11-28 23:42:03 +01001243int hlua_ctx_init(struct hlua *lua, int state_id, struct task *task, int already_safe)
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001244{
1245 lua->Mref = LUA_REFNIL;
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001246 lua->flags = 0;
Willy Tarreauf31af932020-01-14 09:59:38 +01001247 lua->gc_count = 0;
Christopher Fauletbc275a92020-02-26 14:55:16 +01001248 lua->wake_time = TICK_ETERNITY;
Thierry Fournier021d9862020-11-28 23:42:03 +01001249 lua->state_id = state_id;
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01001250 LIST_INIT(&lua->com);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001251 if (!already_safe) {
1252 if (!SET_SAFE_LJMP_PARENT(lua)) {
1253 lua->Tref = LUA_REFNIL;
1254 return 0;
1255 }
1256 }
Thierry Fournier021d9862020-11-28 23:42:03 +01001257 lua->T = lua_newthread(hlua_states[state_id]);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001258 if (!lua->T) {
1259 lua->Tref = LUA_REFNIL;
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +01001260 if (!already_safe)
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001261 RESET_SAFE_LJMP_PARENT(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001262 return 0;
1263 }
1264 hlua_sethlua(lua);
Thierry Fournier021d9862020-11-28 23:42:03 +01001265 lua->Tref = luaL_ref(hlua_states[state_id], LUA_REGISTRYINDEX);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001266 lua->task = task;
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +01001267 if (!already_safe)
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001268 RESET_SAFE_LJMP_PARENT(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001269 return 1;
1270}
1271
Willy Tarreau87b09662015-04-03 00:22:06 +02001272/* Used to destroy the Lua coroutine when the attached stream or task
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001273 * is destroyed. The destroy also the memory context. The struct "lua"
1274 * is not freed.
1275 */
1276void hlua_ctx_destroy(struct hlua *lua)
1277{
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01001278 if (!lua)
Thierry FOURNIERa718b292015-03-04 16:48:34 +01001279 return;
1280
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01001281 if (!lua->T)
1282 goto end;
1283
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01001284 /* Purge all the pending signals. */
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001285 notification_purge(&lua->com);
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01001286
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001287 if (!SET_SAFE_LJMP(lua))
Thierry FOURNIER75d02082017-07-12 13:41:33 +02001288 return;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001289 luaL_unref(lua->T, LUA_REGISTRYINDEX, lua->Mref);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001290 RESET_SAFE_LJMP(lua);
Thierry FOURNIER5a50a852015-09-23 16:59:28 +02001291
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001292 if (!SET_SAFE_LJMP_PARENT(lua))
Thierry FOURNIER75d02082017-07-12 13:41:33 +02001293 return;
Thierry Fournier021d9862020-11-28 23:42:03 +01001294 luaL_unref(hlua_states[lua->state_id], LUA_REGISTRYINDEX, lua->Tref);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001295 RESET_SAFE_LJMP_PARENT(lua);
Thierry FOURNIER5a50a852015-09-23 16:59:28 +02001296 /* Forces a garbage collecting process. If the Lua program is finished
1297 * without error, we run the GC on the thread pointer. Its freed all
1298 * the unused memory.
1299 * If the thread is finnish with an error or is currently yielded,
1300 * it seems that the GC applied on the thread doesn't clean anything,
1301 * so e run the GC on the main thread.
1302 * NOTE: maybe this action locks all the Lua threads untiml the en of
1303 * the garbage collection.
1304 */
Willy Tarreauf31af932020-01-14 09:59:38 +01001305 if (lua->gc_count) {
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001306 if (!SET_SAFE_LJMP_PARENT(lua))
Thierry FOURNIER75d02082017-07-12 13:41:33 +02001307 return;
Thierry Fournier021d9862020-11-28 23:42:03 +01001308 lua_gc(hlua_states[lua->state_id], LUA_GCCOLLECT, 0);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001309 RESET_SAFE_LJMP_PARENT(lua);
Thierry FOURNIER7c39ab42015-09-27 22:53:33 +02001310 }
Thierry FOURNIER5a50a852015-09-23 16:59:28 +02001311
Thierry FOURNIERa7b536b2015-09-21 22:50:24 +02001312 lua->T = NULL;
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01001313
1314end:
Willy Tarreaubafbe012017-11-24 17:34:44 +01001315 pool_free(pool_head_hlua, lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001316}
1317
1318/* This function is used to restore the Lua context when a coroutine
1319 * fails. This function copy the common memory between old coroutine
1320 * and the new coroutine. The old coroutine is destroyed, and its
1321 * replaced by the new coroutine.
1322 * If the flag "keep_msg" is set, the last entry of the old is assumed
1323 * as string error message and it is copied in the new stack.
1324 */
1325static int hlua_ctx_renew(struct hlua *lua, int keep_msg)
1326{
1327 lua_State *T;
1328 int new_ref;
1329
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001330 /* New Lua coroutine. */
Thierry Fournier021d9862020-11-28 23:42:03 +01001331 T = lua_newthread(hlua_states[lua->state_id]);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001332 if (!T)
1333 return 0;
1334
1335 /* Copy last error message. */
1336 if (keep_msg)
1337 lua_xmove(lua->T, T, 1);
1338
1339 /* Copy data between the coroutines. */
1340 lua_rawgeti(lua->T, LUA_REGISTRYINDEX, lua->Mref);
1341 lua_xmove(lua->T, T, 1);
Ilya Shipitsin46a030c2020-07-05 16:36:08 +05001342 new_ref = luaL_ref(T, LUA_REGISTRYINDEX); /* Value popped. */
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001343
1344 /* Destroy old data. */
1345 luaL_unref(lua->T, LUA_REGISTRYINDEX, lua->Mref);
1346
1347 /* The thread is garbage collected by Lua. */
Thierry Fournier021d9862020-11-28 23:42:03 +01001348 luaL_unref(hlua_states[lua->state_id], LUA_REGISTRYINDEX, lua->Tref);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001349
1350 /* Fill the struct with the new coroutine values. */
1351 lua->Mref = new_ref;
1352 lua->T = T;
Thierry Fournier021d9862020-11-28 23:42:03 +01001353 lua->Tref = luaL_ref(hlua_states[lua->state_id], LUA_REGISTRYINDEX);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001354
1355 /* Set context. */
1356 hlua_sethlua(lua);
1357
1358 return 1;
1359}
1360
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001361void hlua_hook(lua_State *L, lua_Debug *ar)
1362{
Thierry Fournier4234dbd2020-11-28 13:18:23 +01001363 struct hlua *hlua;
1364
1365 /* Get hlua struct, or NULL if we execute from main lua state */
1366 hlua = hlua_gethlua(L);
1367 if (!hlua)
1368 return;
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001369
1370 /* Lua cannot yield when its returning from a function,
1371 * so, we can fix the interrupt hook to 1 instruction,
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001372 * expecting that the function is finished.
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001373 */
1374 if (lua_gethookmask(L) & LUA_MASKRET) {
1375 lua_sethook(hlua->T, hlua_hook, LUA_MASKCOUNT, 1);
1376 return;
1377 }
1378
1379 /* restore the interrupt condition. */
1380 lua_sethook(hlua->T, hlua_hook, LUA_MASKCOUNT, hlua_nb_instruction);
1381
1382 /* If we interrupt the Lua processing in yieldable state, we yield.
1383 * If the state is not yieldable, trying yield causes an error.
1384 */
1385 if (lua_isyieldable(L))
Willy Tarreau9635e032018-10-16 17:52:55 +02001386 MAY_LJMP(hlua_yieldk(L, 0, 0, NULL, TICK_ETERNITY, HLUA_CTRLYIELD));
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001387
Thierry FOURNIERa85cfb12015-03-13 14:50:06 +01001388 /* If we cannot yield, update the clock and check the timeout. */
Willy Tarreau55542642021-10-08 09:33:24 +02001389 clock_update_date(0, 1);
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001390 hlua->run_time += now_ms - hlua->start_time;
1391 if (hlua->max_time && hlua->run_time >= hlua->max_time) {
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001392 lua_pushfstring(L, "execution timeout");
1393 WILL_LJMP(lua_error(L));
1394 }
1395
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001396 /* Update the start time. */
1397 hlua->start_time = now_ms;
1398
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001399 /* Try to interrupt the process at the end of the current
1400 * unyieldable function.
1401 */
1402 lua_sethook(hlua->T, hlua_hook, LUA_MASKRET|LUA_MASKCOUNT, hlua_nb_instruction);
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001403}
1404
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001405/* This function start or resumes the Lua stack execution. If the flag
1406 * "yield_allowed" if no set and the LUA stack execution returns a yield
1407 * The function return an error.
1408 *
1409 * The function can returns 4 values:
1410 * - HLUA_E_OK : The execution is terminated without any errors.
1411 * - HLUA_E_AGAIN : The execution must continue at the next associated
1412 * task wakeup.
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001413 * - HLUA_E_ERRMSG : An error has occurred, an error message is set in
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001414 * the top of the stack.
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001415 * - HLUA_E_ERR : An error has occurred without error message.
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001416 *
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001417 * If an error occurred, the stack is renewed and it is ready to run new
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001418 * LUA code.
1419 */
1420static enum hlua_exec hlua_ctx_resume(struct hlua *lua, int yield_allowed)
1421{
Christopher Faulet08ed98f2020-07-28 10:33:25 +02001422#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM >= 504
1423 int nres;
1424#endif
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001425 int ret;
1426 const char *msg;
Thierry FOURNIERfc044c92018-06-07 14:40:48 +02001427 const char *trace;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001428
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001429 /* Initialise run time counter. */
1430 if (!HLUA_IS_RUNNING(lua))
1431 lua->run_time = 0;
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001432
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +02001433 /* Lock the whole Lua execution. This lock must be before the
1434 * label "resume_execution".
1435 */
Thierry Fournier021d9862020-11-28 23:42:03 +01001436 if (lua->state_id == 0)
Willy Tarreau1e7bef12021-08-20 15:47:25 +02001437 lua_take_global_lock();
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +02001438
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001439resume_execution:
1440
1441 /* This hook interrupts the Lua processing each 'hlua_nb_instruction'
1442 * instructions. it is used for preventing infinite loops.
1443 */
1444 lua_sethook(lua->T, hlua_hook, LUA_MASKCOUNT, hlua_nb_instruction);
1445
Thierry FOURNIER1bfc09b2015-03-05 17:10:14 +01001446 /* Remove all flags except the running flags. */
Thierry FOURNIER2f3867f2015-09-28 01:02:01 +02001447 HLUA_SET_RUN(lua);
1448 HLUA_CLR_CTRLYIELD(lua);
1449 HLUA_CLR_WAKERESWR(lua);
1450 HLUA_CLR_WAKEREQWR(lua);
Christopher Faulet1f43a342021-08-04 17:58:21 +02001451 HLUA_CLR_NOYIELD(lua);
1452 if (!yield_allowed)
1453 HLUA_SET_NOYIELD(lua);
Thierry FOURNIER1bfc09b2015-03-05 17:10:14 +01001454
Christopher Fauletbc275a92020-02-26 14:55:16 +01001455 /* Update the start time and reset wake_time. */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001456 lua->start_time = now_ms;
Christopher Fauletbc275a92020-02-26 14:55:16 +01001457 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001458
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001459 /* Call the function. */
Christopher Faulet08ed98f2020-07-28 10:33:25 +02001460#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM >= 504
Thierry Fournier021d9862020-11-28 23:42:03 +01001461 ret = lua_resume(lua->T, hlua_states[lua->state_id], lua->nargs, &nres);
Christopher Faulet08ed98f2020-07-28 10:33:25 +02001462#else
Thierry Fournier021d9862020-11-28 23:42:03 +01001463 ret = lua_resume(lua->T, hlua_states[lua->state_id], lua->nargs);
Christopher Faulet08ed98f2020-07-28 10:33:25 +02001464#endif
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001465 switch (ret) {
1466
1467 case LUA_OK:
1468 ret = HLUA_E_OK;
1469 break;
1470
1471 case LUA_YIELD:
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001472 /* Check if the execution timeout is expired. It it is the case, we
1473 * break the Lua execution.
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001474 */
Willy Tarreau55542642021-10-08 09:33:24 +02001475 clock_update_date(0, 1);
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001476 lua->run_time += now_ms - lua->start_time;
1477 if (lua->max_time && lua->run_time > lua->max_time) {
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001478 lua_settop(lua->T, 0); /* Empty the stack. */
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001479 ret = HLUA_E_ETMOUT;
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001480 break;
1481 }
1482 /* Process the forced yield. if the general yield is not allowed or
1483 * if no task were associated this the current Lua execution
1484 * coroutine, we resume the execution. Else we want to return in the
1485 * scheduler and we want to be waked up again, to continue the
1486 * current Lua execution. So we schedule our own task.
1487 */
1488 if (HLUA_IS_CTRLYIELDING(lua)) {
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001489 if (!yield_allowed || !lua->task)
1490 goto resume_execution;
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001491 task_wakeup(lua->task, TASK_WOKEN_MSG);
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001492 }
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001493 if (!yield_allowed) {
1494 lua_settop(lua->T, 0); /* Empty the stack. */
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001495 ret = HLUA_E_YIELD;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001496 break;
1497 }
1498 ret = HLUA_E_AGAIN;
1499 break;
1500
1501 case LUA_ERRRUN:
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001502
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001503 /* Special exit case. The traditional exit is returned as an error
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001504 * because the errors ares the only one mean to return immediately
1505 * from and lua execution.
1506 */
1507 if (lua->flags & HLUA_EXIT) {
1508 ret = HLUA_E_OK;
Christopher Faulet7716cdf2020-01-29 11:53:30 +01001509 hlua_ctx_renew(lua, 1);
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001510 break;
1511 }
1512
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001513 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001514 if (!lua_checkstack(lua->T, 1)) {
1515 ret = HLUA_E_ERR;
1516 break;
1517 }
1518 msg = lua_tostring(lua->T, -1);
1519 lua_settop(lua->T, 0); /* Empty the stack. */
1520 lua_pop(lua->T, 1);
Christopher Fauletd09cc512021-03-24 14:48:45 +01001521 trace = hlua_traceback(lua->T, ", ");
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001522 if (msg)
Thierry Fournier46278ff2020-11-29 11:48:12 +01001523 lua_pushfstring(lua->T, "[state-id %d] runtime error: %s from %s", lua->state_id, msg, trace);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001524 else
Thierry Fournier46278ff2020-11-29 11:48:12 +01001525 lua_pushfstring(lua->T, "[state-id %d] unknown runtime error from %s", lua->state_id, trace);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001526 ret = HLUA_E_ERRMSG;
1527 break;
1528
1529 case LUA_ERRMEM:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001530 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001531 lua_settop(lua->T, 0); /* Empty the stack. */
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001532 ret = HLUA_E_NOMEM;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001533 break;
1534
1535 case LUA_ERRERR:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001536 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001537 if (!lua_checkstack(lua->T, 1)) {
1538 ret = HLUA_E_ERR;
1539 break;
1540 }
1541 msg = lua_tostring(lua->T, -1);
1542 lua_settop(lua->T, 0); /* Empty the stack. */
1543 lua_pop(lua->T, 1);
1544 if (msg)
Thierry Fournier46278ff2020-11-29 11:48:12 +01001545 lua_pushfstring(lua->T, "[state-id %d] message handler error: %s", lua->state_id, msg);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001546 else
Thierry Fournier46278ff2020-11-29 11:48:12 +01001547 lua_pushfstring(lua->T, "[state-id %d] message handler error", lua->state_id);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001548 ret = HLUA_E_ERRMSG;
1549 break;
1550
1551 default:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001552 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001553 lua_settop(lua->T, 0); /* Empty the stack. */
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001554 ret = HLUA_E_ERR;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001555 break;
1556 }
1557
1558 switch (ret) {
1559 case HLUA_E_AGAIN:
1560 break;
1561
1562 case HLUA_E_ERRMSG:
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001563 notification_purge(&lua->com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001564 hlua_ctx_renew(lua, 1);
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001565 HLUA_CLR_RUN(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001566 break;
1567
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001568 case HLUA_E_ETMOUT:
1569 case HLUA_E_NOMEM:
1570 case HLUA_E_YIELD:
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001571 case HLUA_E_ERR:
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001572 HLUA_CLR_RUN(lua);
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001573 notification_purge(&lua->com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001574 hlua_ctx_renew(lua, 0);
1575 break;
1576
1577 case HLUA_E_OK:
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001578 HLUA_CLR_RUN(lua);
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001579 notification_purge(&lua->com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001580 break;
1581 }
1582
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +02001583 /* This is the main exit point, remove the Lua lock. */
Thierry Fournier021d9862020-11-28 23:42:03 +01001584 if (lua->state_id == 0)
Willy Tarreau1e7bef12021-08-20 15:47:25 +02001585 lua_drop_global_lock();
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +02001586
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001587 return ret;
1588}
1589
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001590/* This function exit the current code. */
1591__LJMP static int hlua_done(lua_State *L)
1592{
Thierry Fournier4234dbd2020-11-28 13:18:23 +01001593 struct hlua *hlua;
1594
1595 /* Get hlua struct, or NULL if we execute from main lua state */
1596 hlua = hlua_gethlua(L);
1597 if (!hlua)
1598 return 0;
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001599
1600 hlua->flags |= HLUA_EXIT;
1601 WILL_LJMP(lua_error(L));
1602
1603 return 0;
1604}
1605
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001606/* This function is an LUA binding. It provides a function
1607 * for deleting ACL from a referenced ACL file.
1608 */
1609__LJMP static int hlua_del_acl(lua_State *L)
1610{
1611 const char *name;
1612 const char *key;
1613 struct pat_ref *ref;
1614
1615 MAY_LJMP(check_args(L, 2, "del_acl"));
1616
1617 name = MAY_LJMP(luaL_checkstring(L, 1));
1618 key = MAY_LJMP(luaL_checkstring(L, 2));
1619
1620 ref = pat_ref_lookup(name);
1621 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001622 WILL_LJMP(luaL_error(L, "'del_acl': unknown acl file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001623
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001624 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001625 pat_ref_delete(ref, key);
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001626 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001627 return 0;
1628}
1629
1630/* This function is an LUA binding. It provides a function
1631 * for deleting map entry from a referenced map file.
1632 */
1633static int hlua_del_map(lua_State *L)
1634{
1635 const char *name;
1636 const char *key;
1637 struct pat_ref *ref;
1638
1639 MAY_LJMP(check_args(L, 2, "del_map"));
1640
1641 name = MAY_LJMP(luaL_checkstring(L, 1));
1642 key = MAY_LJMP(luaL_checkstring(L, 2));
1643
1644 ref = pat_ref_lookup(name);
1645 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001646 WILL_LJMP(luaL_error(L, "'del_map': unknown acl file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001647
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001648 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001649 pat_ref_delete(ref, key);
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001650 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001651 return 0;
1652}
1653
1654/* This function is an LUA binding. It provides a function
1655 * for adding ACL pattern from a referenced ACL file.
1656 */
1657static int hlua_add_acl(lua_State *L)
1658{
1659 const char *name;
1660 const char *key;
1661 struct pat_ref *ref;
1662
1663 MAY_LJMP(check_args(L, 2, "add_acl"));
1664
1665 name = MAY_LJMP(luaL_checkstring(L, 1));
1666 key = MAY_LJMP(luaL_checkstring(L, 2));
1667
1668 ref = pat_ref_lookup(name);
1669 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001670 WILL_LJMP(luaL_error(L, "'add_acl': unknown acl file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001671
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001672 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001673 if (pat_ref_find_elt(ref, key) == NULL)
1674 pat_ref_add(ref, key, NULL, NULL);
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001675 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001676 return 0;
1677}
1678
1679/* This function is an LUA binding. It provides a function
1680 * for setting map pattern and sample from a referenced map
1681 * file.
1682 */
1683static int hlua_set_map(lua_State *L)
1684{
1685 const char *name;
1686 const char *key;
1687 const char *value;
1688 struct pat_ref *ref;
1689
1690 MAY_LJMP(check_args(L, 3, "set_map"));
1691
1692 name = MAY_LJMP(luaL_checkstring(L, 1));
1693 key = MAY_LJMP(luaL_checkstring(L, 2));
1694 value = MAY_LJMP(luaL_checkstring(L, 3));
1695
1696 ref = pat_ref_lookup(name);
1697 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001698 WILL_LJMP(luaL_error(L, "'set_map': unknown map file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001699
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001700 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001701 if (pat_ref_find_elt(ref, key) != NULL)
1702 pat_ref_set(ref, key, value, NULL);
1703 else
1704 pat_ref_add(ref, key, value, NULL);
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001705 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001706 return 0;
1707}
1708
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01001709/* A class is a lot of memory that contain data. This data can be a table,
1710 * an integer or user data. This data is associated with a metatable. This
Ilya Shipitsinc02a23f2020-05-06 00:53:22 +05001711 * metatable have an original version registered in the global context with
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01001712 * the name of the object (_G[<name>] = <metable> ).
1713 *
1714 * A metable is a table that modify the standard behavior of a standard
1715 * access to the associated data. The entries of this new metatable are
1716 * defined as is:
1717 *
1718 * http://lua-users.org/wiki/MetatableEvents
1719 *
1720 * __index
1721 *
1722 * we access an absent field in a table, the result is nil. This is
1723 * true, but it is not the whole truth. Actually, such access triggers
1724 * the interpreter to look for an __index metamethod: If there is no
1725 * such method, as usually happens, then the access results in nil;
1726 * otherwise, the metamethod will provide the result.
1727 *
1728 * Control 'prototype' inheritance. When accessing "myTable[key]" and
1729 * the key does not appear in the table, but the metatable has an __index
1730 * property:
1731 *
1732 * - if the value is a function, the function is called, passing in the
1733 * table and the key; the return value of that function is returned as
1734 * the result.
1735 *
1736 * - if the value is another table, the value of the key in that table is
1737 * asked for and returned (and if it doesn't exist in that table, but that
1738 * table's metatable has an __index property, then it continues on up)
1739 *
1740 * - Use "rawget(myTable,key)" to skip this metamethod.
1741 *
1742 * http://www.lua.org/pil/13.4.1.html
1743 *
1744 * __newindex
1745 *
1746 * Like __index, but control property assignment.
1747 *
1748 * __mode - Control weak references. A string value with one or both
1749 * of the characters 'k' and 'v' which specifies that the the
1750 * keys and/or values in the table are weak references.
1751 *
1752 * __call - Treat a table like a function. When a table is followed by
1753 * parenthesis such as "myTable( 'foo' )" and the metatable has
1754 * a __call key pointing to a function, that function is invoked
1755 * (passing any specified arguments) and the return value is
1756 * returned.
1757 *
1758 * __metatable - Hide the metatable. When "getmetatable( myTable )" is
1759 * called, if the metatable for myTable has a __metatable
1760 * key, the value of that key is returned instead of the
1761 * actual metatable.
1762 *
1763 * __tostring - Control string representation. When the builtin
1764 * "tostring( myTable )" function is called, if the metatable
1765 * for myTable has a __tostring property set to a function,
1766 * that function is invoked (passing myTable to it) and the
1767 * return value is used as the string representation.
1768 *
1769 * __len - Control table length. When the table length is requested using
1770 * the length operator ( '#' ), if the metatable for myTable has
1771 * a __len key pointing to a function, that function is invoked
1772 * (passing myTable to it) and the return value used as the value
1773 * of "#myTable".
1774 *
1775 * __gc - Userdata finalizer code. When userdata is set to be garbage
1776 * collected, if the metatable has a __gc field pointing to a
1777 * function, that function is first invoked, passing the userdata
1778 * to it. The __gc metamethod is not called for tables.
1779 * (See http://lua-users.org/lists/lua-l/2006-11/msg00508.html)
1780 *
1781 * Special metamethods for redefining standard operators:
1782 * http://www.lua.org/pil/13.1.html
1783 *
1784 * __add "+"
1785 * __sub "-"
1786 * __mul "*"
1787 * __div "/"
1788 * __unm "!"
1789 * __pow "^"
1790 * __concat ".."
1791 *
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001792 * Special methods for redefining standard relations
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01001793 * http://www.lua.org/pil/13.2.html
1794 *
1795 * __eq "=="
1796 * __lt "<"
1797 * __le "<="
1798 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001799
1800/*
1801 *
1802 *
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001803 * Class Map
1804 *
1805 *
1806 */
1807
1808/* Returns a struct hlua_map if the stack entry "ud" is
1809 * a class session, otherwise it throws an error.
1810 */
1811__LJMP static struct map_descriptor *hlua_checkmap(lua_State *L, int ud)
1812{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02001813 return MAY_LJMP(hlua_checkudata(L, ud, class_map_ref));
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001814}
1815
1816/* This function is the map constructor. It don't need
1817 * the class Map object. It creates and return a new Map
1818 * object. It must be called only during "body" or "init"
1819 * context because it process some filesystem accesses.
1820 */
1821__LJMP static int hlua_map_new(struct lua_State *L)
1822{
1823 const char *fn;
1824 int match = PAT_MATCH_STR;
1825 struct sample_conv conv;
1826 const char *file = "";
1827 int line = 0;
1828 lua_Debug ar;
1829 char *err = NULL;
1830 struct arg args[2];
1831
1832 if (lua_gettop(L) < 1 || lua_gettop(L) > 2)
1833 WILL_LJMP(luaL_error(L, "'new' needs at least 1 argument."));
1834
1835 fn = MAY_LJMP(luaL_checkstring(L, 1));
1836
1837 if (lua_gettop(L) >= 2) {
1838 match = MAY_LJMP(luaL_checkinteger(L, 2));
1839 if (match < 0 || match >= PAT_MATCH_NUM)
1840 WILL_LJMP(luaL_error(L, "'new' needs a valid match method."));
1841 }
1842
1843 /* Get Lua filename and line number. */
1844 if (lua_getstack(L, 1, &ar)) { /* check function at level */
1845 lua_getinfo(L, "Sl", &ar); /* get info about it */
1846 if (ar.currentline > 0) { /* is there info? */
1847 file = ar.short_src;
1848 line = ar.currentline;
1849 }
1850 }
1851
1852 /* fill fake sample_conv struct. */
1853 conv.kw = ""; /* unused. */
1854 conv.process = NULL; /* unused. */
1855 conv.arg_mask = 0; /* unused. */
1856 conv.val_args = NULL; /* unused. */
1857 conv.out_type = SMP_T_STR;
1858 conv.private = (void *)(long)match;
1859 switch (match) {
1860 case PAT_MATCH_STR: conv.in_type = SMP_T_STR; break;
1861 case PAT_MATCH_BEG: conv.in_type = SMP_T_STR; break;
1862 case PAT_MATCH_SUB: conv.in_type = SMP_T_STR; break;
1863 case PAT_MATCH_DIR: conv.in_type = SMP_T_STR; break;
1864 case PAT_MATCH_DOM: conv.in_type = SMP_T_STR; break;
1865 case PAT_MATCH_END: conv.in_type = SMP_T_STR; break;
1866 case PAT_MATCH_REG: conv.in_type = SMP_T_STR; break;
Thierry FOURNIER07ee64e2015-07-06 23:43:03 +02001867 case PAT_MATCH_INT: conv.in_type = SMP_T_SINT; break;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001868 case PAT_MATCH_IP: conv.in_type = SMP_T_ADDR; break;
1869 default:
1870 WILL_LJMP(luaL_error(L, "'new' doesn't support this match mode."));
1871 }
1872
1873 /* fill fake args. */
1874 args[0].type = ARGT_STR;
Christopher Faulet73292e92020-08-06 08:40:09 +02001875 args[0].data.str.area = strdup(fn);
1876 args[0].data.str.data = strlen(fn);
1877 args[0].data.str.size = args[0].data.str.data+1;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001878 args[1].type = ARGT_STOP;
1879
1880 /* load the map. */
1881 if (!sample_load_map(args, &conv, file, line, &err)) {
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +05001882 /* error case: we can't use luaL_error because we must
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001883 * free the err variable.
1884 */
1885 luaL_where(L, 1);
1886 lua_pushfstring(L, "'new': %s.", err);
1887 lua_concat(L, 2);
1888 free(err);
Christopher Faulet6ad7df42020-08-07 11:45:18 +02001889 chunk_destroy(&args[0].data.str);
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001890 WILL_LJMP(lua_error(L));
1891 }
1892
1893 /* create the lua object. */
1894 lua_newtable(L);
1895 lua_pushlightuserdata(L, args[0].data.map);
1896 lua_rawseti(L, -2, 0);
1897
1898 /* Pop a class Map metatable and affect it to the userdata. */
1899 lua_rawgeti(L, LUA_REGISTRYINDEX, class_map_ref);
1900 lua_setmetatable(L, -2);
1901
1902
1903 return 1;
1904}
1905
1906__LJMP static inline int _hlua_map_lookup(struct lua_State *L, int str)
1907{
1908 struct map_descriptor *desc;
1909 struct pattern *pat;
1910 struct sample smp;
1911
1912 MAY_LJMP(check_args(L, 2, "lookup"));
1913 desc = MAY_LJMP(hlua_checkmap(L, 1));
Thierry FOURNIER07ee64e2015-07-06 23:43:03 +02001914 if (desc->pat.expect_type == SMP_T_SINT) {
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02001915 smp.data.type = SMP_T_SINT;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +02001916 smp.data.u.sint = MAY_LJMP(luaL_checkinteger(L, 2));
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001917 }
1918 else {
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02001919 smp.data.type = SMP_T_STR;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001920 smp.flags = SMP_F_CONST;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001921 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 +01001922 smp.data.u.str.size = smp.data.u.str.data + 1;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001923 }
1924
1925 pat = pattern_exec_match(&desc->pat, &smp, 1);
Thierry FOURNIER503bb092015-08-19 08:35:43 +02001926 if (!pat || !pat->data) {
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001927 if (str)
1928 lua_pushstring(L, "");
1929 else
1930 lua_pushnil(L);
1931 return 1;
1932 }
1933
1934 /* The Lua pattern must return a string, so we can't check the returned type */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001935 lua_pushlstring(L, pat->data->u.str.area, pat->data->u.str.data);
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001936 return 1;
1937}
1938
1939__LJMP static int hlua_map_lookup(struct lua_State *L)
1940{
1941 return _hlua_map_lookup(L, 0);
1942}
1943
1944__LJMP static int hlua_map_slookup(struct lua_State *L)
1945{
1946 return _hlua_map_lookup(L, 1);
1947}
1948
1949/*
1950 *
1951 *
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001952 * Class Socket
1953 *
1954 *
1955 */
1956
1957__LJMP static struct hlua_socket *hlua_checksocket(lua_State *L, int ud)
1958{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02001959 return MAY_LJMP(hlua_checkudata(L, ud, class_socket_ref));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001960}
1961
1962/* This function is the handler called for each I/O on the established
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001963 * connection. It is used for notify space available to send or data
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001964 * received.
1965 */
Willy Tarreau00a37f02015-04-13 12:05:19 +02001966static void hlua_socket_handler(struct appctx *appctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001967{
Willy Tarreau5321da92022-05-06 11:57:34 +02001968 struct hlua_csk_ctx *ctx = appctx->svcctx;
Willy Tarreauc12b3212022-05-27 11:08:15 +02001969 struct stconn *sc = appctx_sc(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001970
Willy Tarreau5321da92022-05-06 11:57:34 +02001971 if (ctx->die) {
Willy Tarreau3e7be362022-05-27 10:35:27 +02001972 sc_shutw(sc);
1973 sc_shutr(sc);
1974 sc_ic(sc)->flags |= CF_READ_NULL;
Willy Tarreau5321da92022-05-06 11:57:34 +02001975 notification_wake(&ctx->wake_on_read);
1976 notification_wake(&ctx->wake_on_write);
Willy Tarreau3e7be362022-05-27 10:35:27 +02001977 stream_shutdown(__sc_strm(sc), SF_ERR_KILLED);
Thierry FOURNIERb13b20a2017-07-16 20:48:54 +02001978 }
1979
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +05001980 /* If we can't write, wakeup the pending write signals. */
Willy Tarreau3e7be362022-05-27 10:35:27 +02001981 if (channel_output_closed(sc_ic(sc)))
Willy Tarreau5321da92022-05-06 11:57:34 +02001982 notification_wake(&ctx->wake_on_write);
Thierry FOURNIER6d695e62015-09-27 19:29:38 +02001983
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +05001984 /* If we can't read, wakeup the pending read signals. */
Willy Tarreau3e7be362022-05-27 10:35:27 +02001985 if (channel_input_closed(sc_oc(sc)))
Willy Tarreau5321da92022-05-06 11:57:34 +02001986 notification_wake(&ctx->wake_on_read);
Thierry FOURNIER6d695e62015-09-27 19:29:38 +02001987
Willy Tarreau5a0b25d2019-07-18 18:01:14 +02001988 /* if the connection is not established, inform the stream that we want
Thierry FOURNIER316e3192015-09-04 18:25:53 +02001989 * to be notified whenever the connection completes.
1990 */
Willy Tarreau3e7be362022-05-27 10:35:27 +02001991 if (sc_opposite(sc)->state < SC_ST_EST) {
Willy Tarreau90e8b452022-05-25 18:21:43 +02001992 applet_need_more_data(appctx);
Willy Tarreaub23edc82022-05-24 16:49:03 +02001993 se_need_remote_conn(appctx->sedesc);
Willy Tarreau4164eb92022-05-25 15:42:03 +02001994 applet_have_more_data(appctx);
Willy Tarreaud4da1962015-04-20 01:31:23 +02001995 return;
Thierry FOURNIER316e3192015-09-04 18:25:53 +02001996 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001997
1998 /* This function is called after the connect. */
Willy Tarreau5321da92022-05-06 11:57:34 +02001999 ctx->connected = 1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002000
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002001 /* Wake the tasks which wants to write if the buffer have available space. */
Willy Tarreau3e7be362022-05-27 10:35:27 +02002002 if (channel_may_recv(sc_ic(sc)))
Willy Tarreau5321da92022-05-06 11:57:34 +02002003 notification_wake(&ctx->wake_on_write);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002004
2005 /* Wake the tasks which wants to read if the buffer contains data. */
Willy Tarreau3e7be362022-05-27 10:35:27 +02002006 if (!channel_is_empty(sc_oc(sc)))
Willy Tarreau5321da92022-05-06 11:57:34 +02002007 notification_wake(&ctx->wake_on_read);
Thierry FOURNIER101b9762018-05-27 01:27:40 +02002008
2009 /* Some data were injected in the buffer, notify the stream
2010 * interface.
2011 */
Willy Tarreau3e7be362022-05-27 10:35:27 +02002012 if (!channel_is_empty(sc_ic(sc)))
2013 sc_update(sc);
Thierry FOURNIER101b9762018-05-27 01:27:40 +02002014
2015 /* If write notifications are registered, we considers we want
Willy Tarreau3367d412018-11-15 10:57:41 +01002016 * to write, so we clear the blocking flag.
Thierry FOURNIER101b9762018-05-27 01:27:40 +02002017 */
Willy Tarreau5321da92022-05-06 11:57:34 +02002018 if (notification_registered(&ctx->wake_on_write))
Willy Tarreau4164eb92022-05-25 15:42:03 +02002019 applet_have_more_data(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002020}
2021
Christopher Faulet5f35a3e2022-05-12 15:31:05 +02002022static int hlua_socket_init(struct appctx *appctx)
2023{
2024 struct hlua_csk_ctx *ctx = appctx->svcctx;
2025 struct stream *s;
2026
2027 if (appctx_finalize_startup(appctx, socket_proxy, &BUF_NULL) == -1)
2028 goto error;
2029
2030 s = appctx_strm(appctx);
2031
Willy Tarreau4596fe22022-05-17 19:07:51 +02002032 /* Configure "right" stream connector. This stconn is used to connect
Christopher Faulet5f35a3e2022-05-12 15:31:05 +02002033 * and retrieve data from the server. The connection is initialized
2034 * with the "struct server".
2035 */
Willy Tarreau74568cf2022-05-27 09:03:30 +02002036 sc_set_state(s->scb, SC_ST_ASS);
Christopher Faulet5f35a3e2022-05-12 15:31:05 +02002037
2038 /* Force destination server. */
2039 s->flags |= SF_DIRECT | SF_ASSIGNED | SF_BE_ASSIGNED;
2040 s->target = &socket_tcp->obj_type;
2041
2042 ctx->appctx = appctx;
2043 return 0;
2044
2045 error:
2046 return -1;
2047}
2048
Willy Tarreau87b09662015-04-03 00:22:06 +02002049/* This function is called when the "struct stream" is destroyed.
2050 * Remove the link from the object to this stream.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002051 * Wake all the pending signals.
2052 */
Willy Tarreau00a37f02015-04-13 12:05:19 +02002053static void hlua_socket_release(struct appctx *appctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002054{
Willy Tarreau5321da92022-05-06 11:57:34 +02002055 struct hlua_csk_ctx *ctx = appctx->svcctx;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002056 struct xref *peer;
2057
Christopher Faulet5f35a3e2022-05-12 15:31:05 +02002058 /* Remove my link in the original objects. */
Willy Tarreau5321da92022-05-06 11:57:34 +02002059 peer = xref_get_peer_and_lock(&ctx->xref);
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002060 if (peer)
Willy Tarreau5321da92022-05-06 11:57:34 +02002061 xref_disconnect(&ctx->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002062
2063 /* Wake all the task waiting for me. */
Willy Tarreau5321da92022-05-06 11:57:34 +02002064 notification_wake(&ctx->wake_on_read);
2065 notification_wake(&ctx->wake_on_write);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002066}
2067
2068/* If the garbage collectio of the object is launch, nobody
Willy Tarreau87b09662015-04-03 00:22:06 +02002069 * uses this object. If the stream does not exists, just quit.
2070 * Send the shutdown signal to the stream. In some cases,
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002071 * pending signal can rest in the read and write lists. destroy
2072 * it.
2073 */
2074__LJMP static int hlua_socket_gc(lua_State *L)
2075{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002076 struct hlua_socket *socket;
Willy Tarreau5321da92022-05-06 11:57:34 +02002077 struct hlua_csk_ctx *ctx;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002078 struct xref *peer;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002079
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002080 MAY_LJMP(check_args(L, 1, "__gc"));
2081
2082 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002083 peer = xref_get_peer_and_lock(&socket->xref);
2084 if (!peer)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002085 return 0;
Willy Tarreau5321da92022-05-06 11:57:34 +02002086
2087 ctx = container_of(peer, struct hlua_csk_ctx, xref);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002088
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002089 /* Set the flag which destroy the session. */
Willy Tarreau5321da92022-05-06 11:57:34 +02002090 ctx->die = 1;
2091 appctx_wakeup(ctx->appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002092
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002093 /* Remove all reference between the Lua stack and the coroutine stream. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002094 xref_disconnect(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002095 return 0;
2096}
2097
2098/* The close function send shutdown signal and break the
Willy Tarreau87b09662015-04-03 00:22:06 +02002099 * links between the stream and the object.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002100 */
sada05ed3302018-05-11 11:48:18 -07002101__LJMP static int hlua_socket_close_helper(lua_State *L)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002102{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002103 struct hlua_socket *socket;
Willy Tarreau5321da92022-05-06 11:57:34 +02002104 struct hlua_csk_ctx *ctx;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002105 struct xref *peer;
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002106 struct hlua *hlua;
2107
2108 /* Get hlua struct, or NULL if we execute from main lua state */
2109 hlua = hlua_gethlua(L);
2110 if (!hlua)
2111 return 0;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002112
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002113 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002114
2115 /* Check if we run on the same thread than the xreator thread.
2116 * We cannot access to the socket if the thread is different.
2117 */
2118 if (socket->tid != tid)
2119 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2120
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002121 peer = xref_get_peer_and_lock(&socket->xref);
2122 if (!peer)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002123 return 0;
Willy Tarreauf31af932020-01-14 09:59:38 +01002124
2125 hlua->gc_count--;
Willy Tarreau5321da92022-05-06 11:57:34 +02002126 ctx = container_of(peer, struct hlua_csk_ctx, xref);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002127
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002128 /* Set the flag which destroy the session. */
Willy Tarreau5321da92022-05-06 11:57:34 +02002129 ctx->die = 1;
2130 appctx_wakeup(ctx->appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002131
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002132 /* Remove all reference between the Lua stack and the coroutine stream. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002133 xref_disconnect(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002134 return 0;
2135}
2136
sada05ed3302018-05-11 11:48:18 -07002137/* The close function calls close_helper.
2138 */
2139__LJMP static int hlua_socket_close(lua_State *L)
2140{
2141 MAY_LJMP(check_args(L, 1, "close"));
2142 return hlua_socket_close_helper(L);
2143}
2144
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002145/* This Lua function assumes that the stack contain three parameters.
2146 * 1 - USERDATA containing a struct socket
2147 * 2 - INTEGER with values of the macro defined below
2148 * If the integer is -1, we must read at most one line.
2149 * If the integer is -2, we ust read all the data until the
2150 * end of the stream.
2151 * If the integer is positive value, we must read a number of
2152 * bytes corresponding to this value.
2153 */
2154#define HLSR_READ_LINE (-1)
2155#define HLSR_READ_ALL (-2)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002156__LJMP static int hlua_socket_receive_yield(struct lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002157{
2158 struct hlua_socket *socket = MAY_LJMP(hlua_checksocket(L, 1));
2159 int wanted = lua_tointeger(L, 2);
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002160 struct hlua *hlua;
Willy Tarreau5321da92022-05-06 11:57:34 +02002161 struct hlua_csk_ctx *csk_ctx;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002162 struct appctx *appctx;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02002163 size_t len;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002164 int nblk;
Willy Tarreau206ba832018-06-14 15:27:31 +02002165 const char *blk1;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02002166 size_t len1;
Willy Tarreau206ba832018-06-14 15:27:31 +02002167 const char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02002168 size_t len2;
Thierry FOURNIER00543922015-03-09 18:35:06 +01002169 int skip_at_end = 0;
Willy Tarreau81389672015-03-10 12:03:52 +01002170 struct channel *oc;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002171 struct stream *s;
2172 struct xref *peer;
Thierry FOURNIER8c126c72018-05-25 16:27:44 +02002173 int missing_bytes;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002174
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002175 /* Get hlua struct, or NULL if we execute from main lua state */
2176 hlua = hlua_gethlua(L);
2177
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002178 /* Check if this lua stack is schedulable. */
2179 if (!hlua || !hlua->task)
2180 WILL_LJMP(luaL_error(L, "The 'receive' function is only allowed in "
2181 "'frontend', 'backend' or 'task'"));
2182
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002183 /* Check if we run on the same thread than the xreator thread.
2184 * We cannot access to the socket if the thread is different.
2185 */
2186 if (socket->tid != tid)
2187 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2188
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002189 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002190 peer = xref_get_peer_and_lock(&socket->xref);
2191 if (!peer)
2192 goto no_peer;
Willy Tarreau5321da92022-05-06 11:57:34 +02002193
2194 csk_ctx = container_of(peer, struct hlua_csk_ctx, xref);
2195 appctx = csk_ctx->appctx;
Willy Tarreau0698c802022-05-11 14:09:57 +02002196 s = appctx_strm(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002197
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002198 oc = &s->res;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002199 if (wanted == HLSR_READ_LINE) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002200 /* Read line. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02002201 nblk = co_getline_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002202 if (nblk < 0) /* Connection close. */
2203 goto connection_closed;
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002204 if (nblk == 0) /* No data available. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002205 goto connection_empty;
Thierry FOURNIER00543922015-03-09 18:35:06 +01002206
2207 /* remove final \r\n. */
2208 if (nblk == 1) {
2209 if (blk1[len1-1] == '\n') {
2210 len1--;
2211 skip_at_end++;
2212 if (blk1[len1-1] == '\r') {
2213 len1--;
2214 skip_at_end++;
2215 }
2216 }
2217 }
2218 else {
2219 if (blk2[len2-1] == '\n') {
2220 len2--;
2221 skip_at_end++;
2222 if (blk2[len2-1] == '\r') {
2223 len2--;
2224 skip_at_end++;
2225 }
2226 }
2227 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002228 }
2229
2230 else if (wanted == HLSR_READ_ALL) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002231 /* Read all the available data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02002232 nblk = co_getblk_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002233 if (nblk < 0) /* Connection close. */
2234 goto connection_closed;
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002235 if (nblk == 0) /* No data available. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002236 goto connection_empty;
2237 }
2238
2239 else {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002240 /* Read a block of data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02002241 nblk = co_getblk_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002242 if (nblk < 0) /* Connection close. */
2243 goto connection_closed;
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002244 if (nblk == 0) /* No data available. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002245 goto connection_empty;
2246
Thierry FOURNIER8c126c72018-05-25 16:27:44 +02002247 missing_bytes = wanted - socket->b.n;
2248 if (len1 > missing_bytes) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002249 nblk = 1;
Thierry FOURNIER8c126c72018-05-25 16:27:44 +02002250 len1 = missing_bytes;
2251 } if (nblk == 2 && len1 + len2 > missing_bytes)
2252 len2 = missing_bytes - len1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002253 }
2254
2255 len = len1;
2256
2257 luaL_addlstring(&socket->b, blk1, len1);
2258 if (nblk == 2) {
2259 len += len2;
2260 luaL_addlstring(&socket->b, blk2, len2);
2261 }
2262
2263 /* Consume data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02002264 co_skip(oc, len + skip_at_end);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002265
2266 /* Don't wait anything. */
Thierry FOURNIER7e4ee472018-05-25 15:03:50 +02002267 appctx_wakeup(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002268
2269 /* If the pattern reclaim to read all the data
2270 * in the connection, got out.
2271 */
2272 if (wanted == HLSR_READ_ALL)
2273 goto connection_empty;
Thierry FOURNIER8c126c72018-05-25 16:27:44 +02002274 else if (wanted >= 0 && socket->b.n < wanted)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002275 goto connection_empty;
2276
2277 /* Return result. */
2278 luaL_pushresult(&socket->b);
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002279 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002280 return 1;
2281
2282connection_closed:
2283
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002284 xref_unlock(&socket->xref, peer);
2285
2286no_peer:
2287
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002288 /* If the buffer containds data. */
2289 if (socket->b.n > 0) {
2290 luaL_pushresult(&socket->b);
2291 return 1;
2292 }
2293 lua_pushnil(L);
2294 lua_pushstring(L, "connection closed.");
2295 return 2;
2296
2297connection_empty:
2298
Willy Tarreau5321da92022-05-06 11:57:34 +02002299 if (!notification_new(&hlua->com, &csk_ctx->wake_on_read, hlua->task)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002300 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002301 WILL_LJMP(luaL_error(L, "out of memory"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002302 }
2303 xref_unlock(&socket->xref, peer);
Willy Tarreau9635e032018-10-16 17:52:55 +02002304 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_receive_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002305 return 0;
2306}
2307
Tim Duesterhusb33754c2018-01-04 19:32:14 +01002308/* This Lua function gets two parameters. The first one can be string
2309 * or a number. If the string is "*l", the user requires one line. If
2310 * the string is "*a", the user requires all the contents of the stream.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002311 * If the value is a number, the user require a number of bytes equal
2312 * to the value. The default value is "*l" (a line).
2313 *
Tim Duesterhusb33754c2018-01-04 19:32:14 +01002314 * This parameter with a variable type is converted in integer. This
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002315 * integer takes this values:
2316 * -1 : read a line
2317 * -2 : read all the stream
Tim Duesterhusb33754c2018-01-04 19:32:14 +01002318 * >0 : amount of bytes.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002319 *
Tim Duesterhusb33754c2018-01-04 19:32:14 +01002320 * The second parameter is optional. It contains a string that must be
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002321 * concatenated with the read data.
2322 */
2323__LJMP static int hlua_socket_receive(struct lua_State *L)
2324{
2325 int wanted = HLSR_READ_LINE;
2326 const char *pattern;
Christopher Fauletc31b2002021-05-03 10:11:13 +02002327 int lastarg, type;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002328 char *error;
2329 size_t len;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002330 struct hlua_socket *socket;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002331
2332 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
2333 WILL_LJMP(luaL_error(L, "The 'receive' function requires between 1 and 3 arguments."));
2334
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002335 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002336
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002337 /* Check if we run on the same thread than the xreator thread.
2338 * We cannot access to the socket if the thread is different.
2339 */
2340 if (socket->tid != tid)
2341 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2342
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002343 /* check for pattern. */
2344 if (lua_gettop(L) >= 2) {
2345 type = lua_type(L, 2);
2346 if (type == LUA_TSTRING) {
2347 pattern = lua_tostring(L, 2);
2348 if (strcmp(pattern, "*a") == 0)
2349 wanted = HLSR_READ_ALL;
2350 else if (strcmp(pattern, "*l") == 0)
2351 wanted = HLSR_READ_LINE;
2352 else {
2353 wanted = strtoll(pattern, &error, 10);
2354 if (*error != '\0')
2355 WILL_LJMP(luaL_error(L, "Unsupported pattern."));
2356 }
2357 }
2358 else if (type == LUA_TNUMBER) {
2359 wanted = lua_tointeger(L, 2);
2360 if (wanted < 0)
2361 WILL_LJMP(luaL_error(L, "Unsupported size."));
2362 }
2363 }
2364
2365 /* Set pattern. */
2366 lua_pushinteger(L, wanted);
Tim Duesterhusc6e377e2018-01-04 19:32:13 +01002367
2368 /* Check if we would replace the top by itself. */
2369 if (lua_gettop(L) != 2)
2370 lua_replace(L, 2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002371
Christopher Fauletc31b2002021-05-03 10:11:13 +02002372 /* Save index of the top of the stack because since buffers are used, it
2373 * may change
2374 */
2375 lastarg = lua_gettop(L);
2376
Tim Duesterhusb33754c2018-01-04 19:32:14 +01002377 /* init buffer, and fill it with prefix. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002378 luaL_buffinit(L, &socket->b);
2379
2380 /* Check prefix. */
Christopher Fauletc31b2002021-05-03 10:11:13 +02002381 if (lastarg >= 3) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002382 if (lua_type(L, 3) != LUA_TSTRING)
2383 WILL_LJMP(luaL_error(L, "Expect a 'string' for the prefix"));
2384 pattern = lua_tolstring(L, 3, &len);
2385 luaL_addlstring(&socket->b, pattern, len);
2386 }
2387
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002388 return __LJMP(hlua_socket_receive_yield(L, 0, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002389}
2390
2391/* Write the Lua input string in the output buffer.
Mark Lakes22154b42018-01-29 14:38:40 -08002392 * This function returns a yield if no space is available.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002393 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002394static int hlua_socket_write_yield(struct lua_State *L,int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002395{
2396 struct hlua_socket *socket;
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002397 struct hlua *hlua;
Willy Tarreau5321da92022-05-06 11:57:34 +02002398 struct hlua_csk_ctx *csk_ctx;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002399 struct appctx *appctx;
2400 size_t buf_len;
2401 const char *buf;
2402 int len;
2403 int send_len;
2404 int sent;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002405 struct xref *peer;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002406 struct stream *s;
Willy Tarreau3e7be362022-05-27 10:35:27 +02002407 struct stconn *sc;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002408
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002409 /* Get hlua struct, or NULL if we execute from main lua state */
2410 hlua = hlua_gethlua(L);
2411
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002412 /* Check if this lua stack is schedulable. */
2413 if (!hlua || !hlua->task)
2414 WILL_LJMP(luaL_error(L, "The 'write' function is only allowed in "
2415 "'frontend', 'backend' or 'task'"));
2416
2417 /* Get object */
2418 socket = MAY_LJMP(hlua_checksocket(L, 1));
2419 buf = MAY_LJMP(luaL_checklstring(L, 2, &buf_len));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002420 sent = MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002421
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002422 /* Check if we run on the same thread than the xreator thread.
2423 * We cannot access to the socket if the thread is different.
2424 */
2425 if (socket->tid != tid)
2426 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2427
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002428 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002429 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002430 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002431 lua_pushinteger(L, -1);
2432 return 1;
2433 }
Willy Tarreau5321da92022-05-06 11:57:34 +02002434
2435 csk_ctx = container_of(peer, struct hlua_csk_ctx, xref);
2436 appctx = csk_ctx->appctx;
Willy Tarreauc12b3212022-05-27 11:08:15 +02002437 sc = appctx_sc(appctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02002438 s = __sc_strm(sc);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002439
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002440 /* Check for connection close. */
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002441 if (channel_output_closed(&s->req)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002442 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002443 lua_pushinteger(L, -1);
2444 return 1;
2445 }
2446
2447 /* Update the input buffer data. */
2448 buf += sent;
2449 send_len = buf_len - sent;
2450
2451 /* All the data are sent. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002452 if (sent >= buf_len) {
2453 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002454 return 1; /* Implicitly return the length sent. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002455 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002456
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002457 /* Check if the buffer is available because HAProxy doesn't allocate
Thierry FOURNIER486d52a2015-03-09 17:51:43 +01002458 * the request buffer if its not required.
2459 */
Willy Tarreauc9fa0482018-07-10 17:43:27 +02002460 if (s->req.buf.size == 0) {
Willy Tarreau3e7be362022-05-27 10:35:27 +02002461 if (!sc_alloc_ibuf(sc, &appctx->buffer_wait))
Christopher Faulet33834b12016-12-19 09:29:06 +01002462 goto hlua_socket_write_yield_return;
Thierry FOURNIER486d52a2015-03-09 17:51:43 +01002463 }
2464
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002465 /* Check for available space. */
Willy Tarreauc9fa0482018-07-10 17:43:27 +02002466 len = b_room(&s->req.buf);
Christopher Faulet33834b12016-12-19 09:29:06 +01002467 if (len <= 0) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002468 goto hlua_socket_write_yield_return;
Christopher Faulet33834b12016-12-19 09:29:06 +01002469 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002470
2471 /* send data */
2472 if (len < send_len)
2473 send_len = len;
Thierry FOURNIER66b89192018-05-27 01:14:47 +02002474 len = ci_putblk(&s->req, buf, send_len);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002475
2476 /* "Not enough space" (-1), "Buffer too little to contain
2477 * the data" (-2) are not expected because the available length
2478 * is tested.
2479 * Other unknown error are also not expected.
2480 */
2481 if (len <= 0) {
Willy Tarreaubc18da12015-03-13 14:00:47 +01002482 if (len == -1)
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002483 s->req.flags |= CF_WAKE_WRITE;
Willy Tarreaubc18da12015-03-13 14:00:47 +01002484
sada05ed3302018-05-11 11:48:18 -07002485 MAY_LJMP(hlua_socket_close_helper(L));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002486 lua_pop(L, 1);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002487 lua_pushinteger(L, -1);
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002488 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002489 return 1;
2490 }
2491
2492 /* update buffers. */
Thierry FOURNIER101b9762018-05-27 01:27:40 +02002493 appctx_wakeup(appctx);
Willy Tarreaude70fa12015-09-26 11:25:05 +02002494
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002495 s->req.rex = TICK_ETERNITY;
2496 s->res.wex = TICK_ETERNITY;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002497
2498 /* Update length sent. */
2499 lua_pop(L, 1);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002500 lua_pushinteger(L, sent + len);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002501
2502 /* All the data buffer is sent ? */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002503 if (sent + len >= buf_len) {
2504 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002505 return 1;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002506 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002507
2508hlua_socket_write_yield_return:
Willy Tarreau5321da92022-05-06 11:57:34 +02002509 if (!notification_new(&hlua->com, &csk_ctx->wake_on_write, hlua->task)) {
Thierry FOURNIERba42fcd2018-05-27 00:59:48 +02002510 xref_unlock(&socket->xref, peer);
2511 WILL_LJMP(luaL_error(L, "out of memory"));
2512 }
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002513 xref_unlock(&socket->xref, peer);
Willy Tarreau9635e032018-10-16 17:52:55 +02002514 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_write_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002515 return 0;
2516}
2517
2518/* This function initiate the send of data. It just check the input
2519 * parameters and push an integer in the Lua stack that contain the
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002520 * amount of data written to the buffer. This is used by the function
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002521 * "hlua_socket_write_yield" that can yield.
2522 *
2523 * The Lua function gets between 3 and 4 parameters. The first one is
2524 * the associated object. The second is a string buffer. The third is
2525 * a facultative integer that represents where is the buffer position
2526 * of the start of the data that can send. The first byte is the
2527 * position "1". The default value is "1". The fourth argument is a
2528 * facultative integer that represents where is the buffer position
2529 * of the end of the data that can send. The default is the last byte.
2530 */
2531static int hlua_socket_send(struct lua_State *L)
2532{
2533 int i;
2534 int j;
2535 const char *buf;
2536 size_t buf_len;
2537
2538 /* Check number of arguments. */
2539 if (lua_gettop(L) < 2 || lua_gettop(L) > 4)
2540 WILL_LJMP(luaL_error(L, "'send' needs between 2 and 4 arguments"));
2541
2542 /* Get the string. */
2543 buf = MAY_LJMP(luaL_checklstring(L, 2, &buf_len));
2544
2545 /* Get and check j. */
2546 if (lua_gettop(L) == 4) {
2547 j = MAY_LJMP(luaL_checkinteger(L, 4));
2548 if (j < 0)
2549 j = buf_len + j + 1;
2550 if (j > buf_len)
2551 j = buf_len + 1;
2552 lua_pop(L, 1);
2553 }
2554 else
2555 j = buf_len;
2556
2557 /* Get and check i. */
2558 if (lua_gettop(L) == 3) {
2559 i = MAY_LJMP(luaL_checkinteger(L, 3));
2560 if (i < 0)
2561 i = buf_len + i + 1;
2562 if (i > buf_len)
2563 i = buf_len + 1;
2564 lua_pop(L, 1);
2565 } else
2566 i = 1;
2567
2568 /* Check bth i and j. */
2569 if (i > j) {
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002570 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002571 return 1;
2572 }
2573 if (i == 0 && j == 0) {
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002574 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002575 return 1;
2576 }
2577 if (i == 0)
2578 i = 1;
2579 if (j == 0)
2580 j = 1;
2581
2582 /* Pop the string. */
2583 lua_pop(L, 1);
2584
2585 /* Update the buffer length. */
2586 buf += i - 1;
2587 buf_len = j - i + 1;
2588 lua_pushlstring(L, buf, buf_len);
2589
2590 /* This unsigned is used to remember the amount of sent data. */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002591 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002592
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002593 return MAY_LJMP(hlua_socket_write_yield(L, 0, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002594}
2595
Willy Tarreau22b0a682015-06-17 19:43:49 +02002596#define SOCKET_INFO_MAX_LEN sizeof("[0000:0000:0000:0000:0000:0000:0000:0000]:12345")
Christopher Faulete6465b32021-10-22 15:36:08 +02002597__LJMP static inline int hlua_socket_info(struct lua_State *L, const struct sockaddr_storage *addr)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002598{
2599 static char buffer[SOCKET_INFO_MAX_LEN];
2600 int ret;
2601 int len;
2602 char *p;
2603
2604 ret = addr_to_str(addr, buffer+1, SOCKET_INFO_MAX_LEN-1);
2605 if (ret <= 0) {
2606 lua_pushnil(L);
2607 return 1;
2608 }
2609
2610 if (ret == AF_UNIX) {
2611 lua_pushstring(L, buffer+1);
2612 return 1;
2613 }
2614 else if (ret == AF_INET6) {
2615 buffer[0] = '[';
2616 len = strlen(buffer);
2617 buffer[len] = ']';
2618 len++;
2619 buffer[len] = ':';
2620 len++;
2621 p = buffer;
2622 }
2623 else if (ret == AF_INET) {
2624 p = buffer + 1;
2625 len = strlen(p);
2626 p[len] = ':';
2627 len++;
2628 }
2629 else {
2630 lua_pushnil(L);
2631 return 1;
2632 }
2633
2634 if (port_to_str(addr, p + len, SOCKET_INFO_MAX_LEN-1 - len) <= 0) {
2635 lua_pushnil(L);
2636 return 1;
2637 }
2638
2639 lua_pushstring(L, p);
2640 return 1;
2641}
2642
2643/* Returns information about the peer of the connection. */
2644__LJMP static int hlua_socket_getpeername(struct lua_State *L)
2645{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002646 struct hlua_socket *socket;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002647 struct xref *peer;
2648 struct appctx *appctx;
Willy Tarreau3e7be362022-05-27 10:35:27 +02002649 struct stconn *sc;
Christopher Faulet16f16af2021-10-27 09:34:56 +02002650 const struct sockaddr_storage *dst;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002651 int ret;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002652
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002653 MAY_LJMP(check_args(L, 1, "getpeername"));
2654
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002655 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002656
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002657 /* Check if we run on the same thread than the xreator thread.
2658 * We cannot access to the socket if the thread is different.
2659 */
2660 if (socket->tid != tid)
2661 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2662
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002663 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002664 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002665 if (!peer) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002666 lua_pushnil(L);
2667 return 1;
2668 }
Willy Tarreau5321da92022-05-06 11:57:34 +02002669
2670 appctx = container_of(peer, struct hlua_csk_ctx, xref)->appctx;
Willy Tarreauc12b3212022-05-27 11:08:15 +02002671 sc = appctx_sc(appctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02002672 dst = sc_dst(sc_opposite(sc));
Christopher Faulet16f16af2021-10-27 09:34:56 +02002673 if (!dst) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002674 xref_unlock(&socket->xref, peer);
Willy Tarreaua71f6422016-11-16 17:00:14 +01002675 lua_pushnil(L);
2676 return 1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002677 }
2678
Christopher Faulet16f16af2021-10-27 09:34:56 +02002679 ret = MAY_LJMP(hlua_socket_info(L, dst));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002680 xref_unlock(&socket->xref, peer);
2681 return ret;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002682}
2683
2684/* Returns information about my connection side. */
2685static int hlua_socket_getsockname(struct lua_State *L)
2686{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002687 struct hlua_socket *socket;
2688 struct connection *conn;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002689 struct appctx *appctx;
2690 struct xref *peer;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002691 struct stream *s;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002692 int ret;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002693
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002694 MAY_LJMP(check_args(L, 1, "getsockname"));
2695
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002696 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002697
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002698 /* Check if we run on the same thread than the xreator thread.
2699 * We cannot access to the socket if the thread is different.
2700 */
2701 if (socket->tid != tid)
2702 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2703
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002704 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002705 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002706 if (!peer) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002707 lua_pushnil(L);
2708 return 1;
2709 }
Willy Tarreau5321da92022-05-06 11:57:34 +02002710
2711 appctx = container_of(peer, struct hlua_csk_ctx, xref)->appctx;
Willy Tarreau0698c802022-05-11 14:09:57 +02002712 s = appctx_strm(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002713
Willy Tarreaufd9417b2022-05-18 16:23:22 +02002714 conn = sc_conn(s->scb);
Willy Tarreau5a0b25d2019-07-18 18:01:14 +02002715 if (!conn || !conn_get_src(conn)) {
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 return 1;
2719 }
2720
Willy Tarreau9da9a6f2019-07-17 14:49:44 +02002721 ret = hlua_socket_info(L, conn->src);
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002722 xref_unlock(&socket->xref, peer);
2723 return ret;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002724}
2725
2726/* This struct define the applet. */
Willy Tarreau30576452015-04-13 13:50:30 +02002727static struct applet update_applet = {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002728 .obj_type = OBJ_TYPE_APPLET,
2729 .name = "<LUA_TCP>",
2730 .fct = hlua_socket_handler,
Christopher Faulet5f35a3e2022-05-12 15:31:05 +02002731 .init = hlua_socket_init,
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002732 .release = hlua_socket_release,
2733};
2734
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002735__LJMP static int hlua_socket_connect_yield(struct lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002736{
2737 struct hlua_socket *socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002738 struct hlua *hlua;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002739 struct xref *peer;
Willy Tarreau5321da92022-05-06 11:57:34 +02002740 struct hlua_csk_ctx *csk_ctx;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002741 struct appctx *appctx;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002742 struct stream *s;
2743
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002744 /* Get hlua struct, or NULL if we execute from main lua state */
2745 hlua = hlua_gethlua(L);
2746 if (!hlua)
2747 return 0;
2748
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002749 /* Check if we run on the same thread than the xreator thread.
2750 * We cannot access to the socket if the thread is different.
2751 */
2752 if (socket->tid != tid)
2753 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2754
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002755 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002756 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002757 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002758 lua_pushnil(L);
2759 lua_pushstring(L, "Can't connect");
2760 return 2;
2761 }
Willy Tarreau5321da92022-05-06 11:57:34 +02002762
2763 csk_ctx = container_of(peer, struct hlua_csk_ctx, xref);
2764 appctx = csk_ctx->appctx;
Willy Tarreau0698c802022-05-11 14:09:57 +02002765 s = appctx_strm(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002766
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002767 /* Check if we run on the same thread than the xreator thread.
2768 * We cannot access to the socket if the thread is different.
2769 */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002770 if (socket->tid != tid) {
2771 xref_unlock(&socket->xref, peer);
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002772 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002773 }
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002774
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002775 /* Check for connection close. */
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002776 if (!hlua || channel_output_closed(&s->req)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002777 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002778 lua_pushnil(L);
2779 lua_pushstring(L, "Can't connect");
2780 return 2;
2781 }
2782
Willy Tarreau8e7c6e62022-05-18 17:58:02 +02002783 appctx = __sc_appctx(s->scf);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002784
2785 /* Check for connection established. */
Willy Tarreau5321da92022-05-06 11:57:34 +02002786 if (csk_ctx->connected) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002787 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002788 lua_pushinteger(L, 1);
2789 return 1;
2790 }
2791
Willy Tarreau5321da92022-05-06 11:57:34 +02002792 if (!notification_new(&hlua->com, &csk_ctx->wake_on_write, hlua->task)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002793 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002794 WILL_LJMP(luaL_error(L, "out of memory error"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002795 }
2796 xref_unlock(&socket->xref, peer);
Willy Tarreau9635e032018-10-16 17:52:55 +02002797 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_connect_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002798 return 0;
2799}
2800
2801/* This function fail or initite the connection. */
2802__LJMP static int hlua_socket_connect(struct lua_State *L)
2803{
2804 struct hlua_socket *socket;
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002805 int port = -1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002806 const char *ip;
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002807 struct hlua *hlua;
Willy Tarreau5321da92022-05-06 11:57:34 +02002808 struct hlua_csk_ctx *csk_ctx;
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002809 struct appctx *appctx;
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002810 int low, high;
2811 struct sockaddr_storage *addr;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002812 struct xref *peer;
Willy Tarreau3e7be362022-05-27 10:35:27 +02002813 struct stconn *sc;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002814 struct stream *s;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002815
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002816 if (lua_gettop(L) < 2)
2817 WILL_LJMP(luaL_error(L, "connect: need at least 2 arguments"));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002818
2819 /* Get args. */
2820 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002821
2822 /* Check if we run on the same thread than the xreator thread.
2823 * We cannot access to the socket if the thread is different.
2824 */
2825 if (socket->tid != tid)
2826 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2827
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002828 ip = MAY_LJMP(luaL_checkstring(L, 2));
Tim Duesterhus6edab862018-01-06 19:04:45 +01002829 if (lua_gettop(L) >= 3) {
2830 luaL_Buffer b;
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002831 port = MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002832
Tim Duesterhus6edab862018-01-06 19:04:45 +01002833 /* Force the ip to end with a colon, to support IPv6 addresses
2834 * that are not enclosed within square brackets.
2835 */
2836 if (port > 0) {
2837 luaL_buffinit(L, &b);
2838 luaL_addstring(&b, ip);
2839 luaL_addchar(&b, ':');
2840 luaL_pushresult(&b);
2841 ip = lua_tolstring(L, lua_gettop(L), NULL);
2842 }
2843 }
2844
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002845 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002846 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002847 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002848 lua_pushnil(L);
2849 return 1;
2850 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002851
2852 /* Parse ip address. */
Willy Tarreau5fc93282020-09-16 18:25:03 +02002853 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 +02002854 if (!addr) {
2855 xref_unlock(&socket->xref, peer);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002856 WILL_LJMP(luaL_error(L, "connect: cannot parse destination address '%s'", ip));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002857 }
Willy Tarreau9da9a6f2019-07-17 14:49:44 +02002858
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002859 /* Set port. */
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002860 if (low == 0) {
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02002861 if (addr->ss_family == AF_INET) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002862 if (port == -1) {
2863 xref_unlock(&socket->xref, peer);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002864 WILL_LJMP(luaL_error(L, "connect: port missing"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002865 }
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02002866 ((struct sockaddr_in *)addr)->sin_port = htons(port);
2867 } else if (addr->ss_family == AF_INET6) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002868 if (port == -1) {
2869 xref_unlock(&socket->xref, peer);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002870 WILL_LJMP(luaL_error(L, "connect: port missing"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002871 }
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02002872 ((struct sockaddr_in6 *)addr)->sin6_port = htons(port);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002873 }
2874 }
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02002875
Willy Tarreau5321da92022-05-06 11:57:34 +02002876 csk_ctx = container_of(peer, struct hlua_csk_ctx, xref);
2877 appctx = csk_ctx->appctx;
Willy Tarreauc12b3212022-05-27 11:08:15 +02002878 sc = appctx_sc(appctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02002879 s = __sc_strm(sc);
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02002880
Willy Tarreau3e7be362022-05-27 10:35:27 +02002881 if (!sockaddr_alloc(&sc_opposite(sc)->dst, addr, sizeof(*addr))) {
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02002882 xref_unlock(&socket->xref, peer);
2883 WILL_LJMP(luaL_error(L, "connect: internal error"));
2884 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002885
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002886 /* Get hlua struct, or NULL if we execute from main lua state */
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002887 hlua = hlua_gethlua(L);
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002888 if (!hlua)
2889 return 0;
Willy Tarreaubdc97a82015-08-24 15:42:28 +02002890
2891 /* inform the stream that we want to be notified whenever the
2892 * connection completes.
2893 */
Willy Tarreau90e8b452022-05-25 18:21:43 +02002894 applet_need_more_data(appctx);
Willy Tarreau4164eb92022-05-25 15:42:03 +02002895 applet_have_more_data(appctx);
Thierry FOURNIER8c8fbbe2015-09-26 17:02:35 +02002896 appctx_wakeup(appctx);
Willy Tarreaubdc97a82015-08-24 15:42:28 +02002897
Willy Tarreauf31af932020-01-14 09:59:38 +01002898 hlua->gc_count++;
Thierry FOURNIER7c39ab42015-09-27 22:53:33 +02002899
Willy Tarreau5321da92022-05-06 11:57:34 +02002900 if (!notification_new(&hlua->com, &csk_ctx->wake_on_write, hlua->task)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002901 xref_unlock(&socket->xref, peer);
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002902 WILL_LJMP(luaL_error(L, "out of memory"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002903 }
2904 xref_unlock(&socket->xref, peer);
PiBa-NL706d5ee2018-05-05 23:51:42 +02002905
2906 task_wakeup(s->task, TASK_WOKEN_INIT);
2907 /* Return yield waiting for connection. */
2908
Willy Tarreau9635e032018-10-16 17:52:55 +02002909 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_connect_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002910
2911 return 0;
2912}
2913
Baptiste Assmann84bb4932015-03-02 21:40:06 +01002914#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002915__LJMP static int hlua_socket_connect_ssl(struct lua_State *L)
2916{
2917 struct hlua_socket *socket;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002918 struct xref *peer;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002919 struct stream *s;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002920
2921 MAY_LJMP(check_args(L, 3, "connect_ssl"));
2922 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002923
2924 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002925 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002926 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002927 lua_pushnil(L);
2928 return 1;
2929 }
Willy Tarreau5321da92022-05-06 11:57:34 +02002930
Willy Tarreau0698c802022-05-11 14:09:57 +02002931 s = appctx_strm(container_of(peer, struct hlua_csk_ctx, xref)->appctx);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002932
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +01002933 s->target = &socket_ssl->obj_type;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002934 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002935 return MAY_LJMP(hlua_socket_connect(L));
2936}
Baptiste Assmann84bb4932015-03-02 21:40:06 +01002937#endif
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002938
2939__LJMP static int hlua_socket_setoption(struct lua_State *L)
2940{
2941 return 0;
2942}
2943
2944__LJMP static int hlua_socket_settimeout(struct lua_State *L)
2945{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002946 struct hlua_socket *socket;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002947 int tmout;
Mark Lakes56cc1252018-03-27 09:48:06 +02002948 double dtmout;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002949 struct xref *peer;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002950 struct stream *s;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002951
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002952 MAY_LJMP(check_args(L, 2, "settimeout"));
2953
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002954 socket = MAY_LJMP(hlua_checksocket(L, 1));
Mark Lakes56cc1252018-03-27 09:48:06 +02002955
Cyril Bonté7ee465f2018-08-19 22:08:50 +02002956 /* convert the timeout to millis */
2957 dtmout = MAY_LJMP(luaL_checknumber(L, 2)) * 1000;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002958
Thierry Fournier17a921b2018-03-08 09:59:02 +01002959 /* Check for negative values */
Mark Lakes56cc1252018-03-27 09:48:06 +02002960 if (dtmout < 0)
Thierry Fournier17a921b2018-03-08 09:59:02 +01002961 WILL_LJMP(luaL_error(L, "settimeout: cannot set negatives values"));
2962
Mark Lakes56cc1252018-03-27 09:48:06 +02002963 if (dtmout > INT_MAX) /* overflow check */
Cyril Bonté7ee465f2018-08-19 22:08:50 +02002964 WILL_LJMP(luaL_error(L, "settimeout: cannot set values larger than %d ms", INT_MAX));
Mark Lakes56cc1252018-03-27 09:48:06 +02002965
2966 tmout = MS_TO_TICKS((int)dtmout);
Cyril Bonté7ee465f2018-08-19 22:08:50 +02002967 if (tmout == 0)
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05002968 tmout++; /* very small timeouts are adjusted to a minimum of 1ms */
Mark Lakes56cc1252018-03-27 09:48:06 +02002969
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002970 /* Check if we run on the same thread than the xreator thread.
2971 * We cannot access to the socket if the thread is different.
2972 */
2973 if (socket->tid != tid)
2974 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2975
Mark Lakes56cc1252018-03-27 09:48:06 +02002976 /* check for connection break. If some data were read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002977 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002978 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002979 hlua_pusherror(L, "socket: not yet initialised, you can't set timeouts.");
2980 WILL_LJMP(lua_error(L));
2981 return 0;
2982 }
Willy Tarreau5321da92022-05-06 11:57:34 +02002983
Willy Tarreau0698c802022-05-11 14:09:57 +02002984 s = appctx_strm(container_of(peer, struct hlua_csk_ctx, xref)->appctx);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002985
Cyril Bonté7bb63452018-08-17 23:51:02 +02002986 s->sess->fe->timeout.connect = tmout;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002987 s->req.rto = tmout;
2988 s->req.wto = tmout;
2989 s->res.rto = tmout;
2990 s->res.wto = tmout;
Cyril Bonté7bb63452018-08-17 23:51:02 +02002991 s->req.rex = tick_add_ifset(now_ms, tmout);
2992 s->req.wex = tick_add_ifset(now_ms, tmout);
2993 s->res.rex = tick_add_ifset(now_ms, tmout);
2994 s->res.wex = tick_add_ifset(now_ms, tmout);
2995
2996 s->task->expire = tick_add_ifset(now_ms, tmout);
2997 task_queue(s->task);
2998
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002999 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003000
Thierry Fourniere9636f12018-03-08 09:54:32 +01003001 lua_pushinteger(L, 1);
Tim Duesterhus119a5f12018-01-06 19:16:25 +01003002 return 1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003003}
3004
3005__LJMP static int hlua_socket_new(lua_State *L)
3006{
3007 struct hlua_socket *socket;
Willy Tarreau5321da92022-05-06 11:57:34 +02003008 struct hlua_csk_ctx *ctx;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003009 struct appctx *appctx;
3010
3011 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003012 if (!lua_checkstack(L, 3)) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003013 hlua_pusherror(L, "socket: full stack");
3014 goto out_fail_conf;
3015 }
3016
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003017 /* Create the object: obj[0] = userdata. */
3018 lua_newtable(L);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003019 socket = MAY_LJMP(lua_newuserdata(L, sizeof(*socket)));
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003020 lua_rawseti(L, -2, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003021 memset(socket, 0, sizeof(*socket));
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02003022 socket->tid = tid;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003023
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05003024 /* Check if the various memory pools are initialized. */
Willy Tarreaubafbe012017-11-24 17:34:44 +01003025 if (!pool_head_stream || !pool_head_buffer) {
Thierry FOURNIER4a6170c2015-03-09 17:07:10 +01003026 hlua_pusherror(L, "socket: uninitialized pools.");
3027 goto out_fail_conf;
3028 }
3029
Willy Tarreau87b09662015-04-03 00:22:06 +02003030 /* Pop a class stream metatable and affect it to the userdata. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003031 lua_rawgeti(L, LUA_REGISTRYINDEX, class_socket_ref);
3032 lua_setmetatable(L, -2);
3033
Willy Tarreaud420a972015-04-06 00:39:18 +02003034 /* Create the applet context */
Christopher Faulet6095d572022-05-16 17:09:48 +02003035 appctx = appctx_new_here(&update_applet, NULL);
Willy Tarreau61cf7c82015-04-06 00:48:33 +02003036 if (!appctx) {
3037 hlua_pusherror(L, "socket: out of memory");
Christopher Fauleta9e8b392022-03-23 11:01:09 +01003038 goto out_fail_conf;
Willy Tarreau61cf7c82015-04-06 00:48:33 +02003039 }
Willy Tarreau5321da92022-05-06 11:57:34 +02003040 ctx = applet_reserve_svcctx(appctx, sizeof(*ctx));
3041 ctx->connected = 0;
Willy Tarreau5321da92022-05-06 11:57:34 +02003042 ctx->die = 0;
3043 LIST_INIT(&ctx->wake_on_write);
3044 LIST_INIT(&ctx->wake_on_read);
Willy Tarreaub2bf8332015-04-04 15:58:58 +02003045
Christopher Faulet5f35a3e2022-05-12 15:31:05 +02003046 if (appctx_init(appctx) == -1) {
3047 hlua_pusherror(L, "socket: fail to init applet.");
Christopher Faulet13a35e52021-12-20 15:34:16 +01003048 goto out_fail_appctx;
3049 }
3050
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003051 /* Initialise cross reference between stream and Lua socket object. */
Willy Tarreau5321da92022-05-06 11:57:34 +02003052 xref_create(&socket->xref, &ctx->xref);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003053 return 1;
3054
Christopher Faulet13a35e52021-12-20 15:34:16 +01003055 out_fail_appctx:
Christopher Faulet5f35a3e2022-05-12 15:31:05 +02003056 appctx_free_on_early_error(appctx);
Willy Tarreaud420a972015-04-06 00:39:18 +02003057 out_fail_conf:
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003058 WILL_LJMP(lua_error(L));
3059 return 0;
3060}
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01003061
3062/*
3063 *
3064 *
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003065 * Class Channel
3066 *
3067 *
3068 */
3069
3070/* Returns the struct hlua_channel join to the class channel in the
3071 * stack entry "ud" or throws an argument error.
3072 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01003073__LJMP static struct channel *hlua_checkchannel(lua_State *L, int ud)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003074{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003075 return MAY_LJMP(hlua_checkudata(L, ud, class_channel_ref));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003076}
3077
Willy Tarreau47860ed2015-03-10 14:07:50 +01003078/* Pushes the channel onto the top of the stack. If the stask does not have a
3079 * free slots, the function fails and returns 0;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003080 */
Willy Tarreau2a71af42015-03-10 13:51:50 +01003081static int hlua_channel_new(lua_State *L, struct channel *channel)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003082{
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003083 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003084 if (!lua_checkstack(L, 3))
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003085 return 0;
3086
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003087 lua_newtable(L);
Willy Tarreau47860ed2015-03-10 14:07:50 +01003088 lua_pushlightuserdata(L, channel);
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003089 lua_rawseti(L, -2, 0);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003090
3091 /* Pop a class sesison metatable and affect it to the userdata. */
3092 lua_rawgeti(L, LUA_REGISTRYINDEX, class_channel_ref);
3093 lua_setmetatable(L, -2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003094 return 1;
3095}
3096
Christopher Faulet9f55a502020-02-25 15:21:02 +01003097/* Helper function returning a filter attached to a channel at the position <ud>
3098 * in the stack, filling the current offset and length of the filter. If no
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05003099 * filter is attached, NULL is returned and <offset> and <len> are not
Christopher Faulet9f55a502020-02-25 15:21:02 +01003100 * initialized.
3101 */
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003102static 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 +01003103{
3104 struct filter *filter = NULL;
3105
3106 if (lua_getfield(L, ud, "__filter") == LUA_TLIGHTUSERDATA) {
3107 struct hlua_flt_ctx *flt_ctx;
3108
3109 filter = lua_touserdata (L, -1);
3110 flt_ctx = filter->ctx;
3111 if (hlua_filter_from_payload(filter)) {
3112 *offset = flt_ctx->cur_off[CHN_IDX(chn)];
3113 *len = flt_ctx->cur_len[CHN_IDX(chn)];
3114 }
3115 }
3116
3117 lua_pop(L, 1);
3118 return filter;
3119}
3120
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003121/* Copies <len> bytes of data present in the channel's buffer, starting at the
3122* offset <offset>, and put it in a LUA string variable. It is the caller
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003123* responsibility to ensure <len> and <offset> are valid. It always return the
3124* length of the built string. <len> may be 0, in this case, an empty string is
3125* created and 0 is returned.
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003126*/
3127static inline int _hlua_channel_dup(struct channel *chn, lua_State *L, size_t offset, size_t len)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003128{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003129 size_t block1, block2;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003130 luaL_Buffer b;
3131
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003132 block1 = len;
3133 if (block1 > b_contig_data(&chn->buf, b_peek_ofs(&chn->buf, offset)))
3134 block1 = b_contig_data(&chn->buf, b_peek_ofs(&chn->buf, offset));
3135 block2 = len - block1;
3136
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003137 luaL_buffinit(L, &b);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003138 luaL_addlstring(&b, b_peek(&chn->buf, offset), block1);
3139 if (block2)
3140 luaL_addlstring(&b, b_orig(&chn->buf), block2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003141 luaL_pushresult(&b);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003142 return len;
3143}
3144
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003145/* Inserts the string <str> to the channel's buffer at the offset <offset>. This
3146 * function returns -1 if data cannot be copied. Otherwise, it returns the
3147 * number of bytes copied.
3148 */
3149static int _hlua_channel_insert(struct channel *chn, lua_State *L, struct ist str, size_t offset)
3150{
3151 int ret = 0;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003152
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003153 /* Nothing to do, just return */
3154 if (unlikely(istlen(str) == 0))
3155 goto end;
3156
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003157 if (istlen(str) > c_room(chn)) {
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003158 ret = -1;
3159 goto end;
3160 }
3161 ret = b_insert_blk(&chn->buf, offset, istptr(str), istlen(str));
3162
3163 end:
3164 return ret;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003165}
3166
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003167/* Removes <len> bytes of data at the absolute position <offset>.
3168 */
3169static void _hlua_channel_delete(struct channel *chn, size_t offset, size_t len)
3170{
3171 size_t end = offset + len;
3172
3173 if (b_peek(&chn->buf, end) != b_tail(&chn->buf))
3174 b_move(&chn->buf, b_peek_ofs(&chn->buf, end),
3175 b_data(&chn->buf) - end, -len);
3176 b_sub(&chn->buf, len);
3177}
3178
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003179/* Copies input data in the channel's buffer. It is possible to set a specific
3180 * offset (0 by default) and a length (all remaining input data starting for the
3181 * offset by default). If there is not enough input data and more data can be
3182 * received, this function yields.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003183 *
3184 * From an action, All input data are considered. For a filter, the offset and
3185 * the length of input data to consider are retrieved from the filter context.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003186 */
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003187__LJMP static int hlua_channel_get_data_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003188{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003189 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003190 struct filter *filter;
3191 size_t input, output;
3192 int offset, len;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003193
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003194 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003195
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003196 output = co_data(chn);
3197 input = ci_data(chn);
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003198
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003199 filter = hlua_channel_filter(L, 1, chn, &output, &input);
3200 if (filter && !hlua_filter_from_payload(filter))
3201 WILL_LJMP(lua_error(L));
3202
3203 offset = output;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003204 if (lua_gettop(L) > 1) {
3205 offset = MAY_LJMP(luaL_checkinteger(L, 2));
3206 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02003207 offset = MAX(0, (int)input + offset);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003208 offset += output;
3209 if (offset < output || offset > input + output) {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003210 lua_pushfstring(L, "offset out of range.");
3211 WILL_LJMP(lua_error(L));
3212 }
3213 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003214 len = output + input - offset;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003215 if (lua_gettop(L) == 3) {
3216 len = MAY_LJMP(luaL_checkinteger(L, 3));
3217 if (!len)
3218 goto dup;
3219 if (len == -1)
3220 len = global.tune.bufsize;
3221 if (len < 0) {
3222 lua_pushfstring(L, "length out of range.");
3223 WILL_LJMP(lua_error(L));
3224 }
3225 }
3226
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003227 if (offset + len > output + input) {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003228 if (!HLUA_CANT_YIELD(hlua_gethlua(L)) && !channel_input_closed(chn) && channel_may_recv(chn)) {
3229 /* Yield waiting for more data, as requested */
3230 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_get_data_yield, TICK_ETERNITY, 0));
3231 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003232 len = output + input - offset;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003233 }
3234
3235 dup:
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003236 _hlua_channel_dup(chn, L, offset, len);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003237 return 1;
3238}
3239
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003240/* Copies the first line (including the trailing LF) of input data in the
3241 * channel's buffer. It is possible to set a specific offset (0 by default) and
3242 * a length (all remaining input data starting for the offset by default). If
3243 * there is not enough input data and more data can be received, the function
3244 * yields. If a length is explicitly specified, no more data are
3245 * copied. Otherwise, if no LF is found and more data can be received, this
3246 * function yields.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003247 *
3248 * From an action, All input data are considered. For a filter, the offset and
3249 * the length of input data to consider are retrieved from the filter context.
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003250 */
3251__LJMP static int hlua_channel_get_line_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003252{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003253 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003254 struct filter *filter;
3255 size_t l, input, output;
3256 int offset, len;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003257
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003258 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003259 output = co_data(chn);
3260 input = ci_data(chn);
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003261
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003262 filter = hlua_channel_filter(L, 1, chn, &output, &input);
3263 if (filter && !hlua_filter_from_payload(filter))
3264 WILL_LJMP(lua_error(L));
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003265
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003266 offset = output;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003267 if (lua_gettop(L) > 1) {
3268 offset = MAY_LJMP(luaL_checkinteger(L, 2));
3269 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02003270 offset = MAX(0, (int)input + offset);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003271 offset += output;
3272 if (offset < output || offset > input + output) {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003273 lua_pushfstring(L, "offset out of range.");
3274 WILL_LJMP(lua_error(L));
3275 }
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003276 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003277
3278 len = output + input - offset;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003279 if (lua_gettop(L) == 3) {
3280 len = MAY_LJMP(luaL_checkinteger(L, 3));
3281 if (!len)
3282 goto dup;
3283 if (len == -1)
3284 len = global.tune.bufsize;
3285 if (len < 0) {
3286 lua_pushfstring(L, "length out of range.");
3287 WILL_LJMP(lua_error(L));
3288 }
3289 }
3290
3291 for (l = 0; l < len; l++) {
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003292 if (l + offset >= output + input)
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003293 break;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003294 if (*(b_peek(&chn->buf, offset + l)) == '\n') {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003295 len = l+1;
3296 goto dup;
3297 }
3298 }
3299
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003300 if (offset + len > output + input) {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003301 if (!HLUA_CANT_YIELD(hlua_gethlua(L)) && !channel_input_closed(chn) && channel_may_recv(chn)) {
3302 /* Yield waiting for more data */
3303 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_get_line_yield, TICK_ETERNITY, 0));
3304 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003305 len = output + input - offset;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003306 }
3307
3308 dup:
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003309 _hlua_channel_dup(chn, L, offset, len);
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003310 return 1;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003311}
3312
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003313/* [ DEPRECATED ]
3314 *
3315 * Duplicate all input data foud in the channel's buffer. The data are not
3316 * removed from the buffer. This function relies on _hlua_channel_dup().
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003317 *
3318 * From an action, All input data are considered. For a filter, the offset and
3319 * the length of input data to consider are retrieved from the filter context.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003320 */
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003321__LJMP static int hlua_channel_dup(lua_State *L)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003322{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003323 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003324 struct filter *filter;
3325 size_t offset, len;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003326
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003327 MAY_LJMP(check_args(L, 1, "dup"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003328 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003329 if (IS_HTX_STRM(chn_strm(chn))) {
3330 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3331 WILL_LJMP(lua_error(L));
3332 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003333
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003334 offset = co_data(chn);
3335 len = ci_data(chn);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003336
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003337 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3338 if (filter && !hlua_filter_from_payload(filter))
3339 WILL_LJMP(lua_error(L));
3340
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003341 if (!ci_data(chn) && channel_input_closed(chn)) {
3342 lua_pushnil(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003343 return 1;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003344 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003345
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003346 _hlua_channel_dup(chn, L, offset, len);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003347 return 1;
3348}
3349
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003350/* [ DEPRECATED ]
3351 *
3352 * Get all input data foud in the channel's buffer. The data are removed from
3353 * the buffer after the copy. This function relies on _hlua_channel_dup() and
3354 * _hlua_channel_delete().
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003355 *
3356 * From an action, All input data are considered. For a filter, the offset and
3357 * the length of input data to consider are retrieved from the filter context.
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003358 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003359__LJMP static int hlua_channel_get(lua_State *L)
3360{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003361 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003362 struct filter *filter;
3363 size_t offset, len;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003364 int ret;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003365
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003366 MAY_LJMP(check_args(L, 1, "get"));
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003367 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3368 if (IS_HTX_STRM(chn_strm(chn))) {
3369 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3370 WILL_LJMP(lua_error(L));
3371 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003372
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003373 offset = co_data(chn);
3374 len = ci_data(chn);
3375
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);
3382 return 1;
3383 }
3384
3385 ret = _hlua_channel_dup(chn, L, offset, len);
3386 _hlua_channel_delete(chn, offset, ret);
3387 return 1;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003388}
3389
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003390/* This functions consumes and returns one line. If the channel is closed,
3391 * and the last data does not contains a final '\n', the data are returned
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003392 * without the final '\n'. When no more data are available, it returns nil
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003393 * value.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003394 *
3395 * From an action, All input data are considered. For a filter, the offset and
3396 * the length of input data to consider are retrieved from the filter context.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003397 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003398__LJMP static int hlua_channel_getline_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003399{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003400 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003401 struct filter *filter;
3402 size_t l, offset, len;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003403 int ret;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003404
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003405 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003406
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003407 offset = co_data(chn);
3408 len = ci_data(chn);
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003409
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003410 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3411 if (filter && !hlua_filter_from_payload(filter))
3412 WILL_LJMP(lua_error(L));
3413
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003414 if (!ci_data(chn) && channel_input_closed(chn)) {
3415 lua_pushnil(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003416 return 1;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003417 }
3418
3419 for (l = 0; l < len; l++) {
3420 if (*(b_peek(&chn->buf, offset+l)) == '\n') {
3421 len = l+1;
3422 goto dup;
3423 }
3424 }
3425
3426 if (!HLUA_CANT_YIELD(hlua_gethlua(L)) && !channel_input_closed(chn) && channel_may_recv(chn)) {
3427 /* Yield waiting for more data */
3428 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_getline_yield, TICK_ETERNITY, 0));
3429 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003430
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003431 dup:
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003432 ret = _hlua_channel_dup(chn, L, offset, len);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003433 _hlua_channel_delete(chn, offset, ret);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003434 return 1;
3435}
3436
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003437/* [ DEPRECATED ]
3438 *
3439 * Check arguments for the function "hlua_channel_getline_yield".
3440 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003441__LJMP static int hlua_channel_getline(lua_State *L)
3442{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003443 struct channel *chn;
3444
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003445 MAY_LJMP(check_args(L, 1, "getline"));
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003446 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3447 if (IS_HTX_STRM(chn_strm(chn))) {
3448 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3449 WILL_LJMP(lua_error(L));
3450 }
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003451 return MAY_LJMP(hlua_channel_getline_yield(L, 0, 0));
3452}
3453
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003454/* Retrieves a given amount of input data at the given offset. By default all
3455 * available input data are returned. The offset may be negactive to start from
3456 * the end of input data. The length may be -1 to set it to the maximum buffer
3457 * size.
3458 */
3459__LJMP static int hlua_channel_get_data(lua_State *L)
3460{
3461 struct channel *chn;
3462
3463 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
3464 WILL_LJMP(luaL_error(L, "'data' expects at most 2 arguments"));
3465 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3466 if (IS_HTX_STRM(chn_strm(chn))) {
3467 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3468 WILL_LJMP(lua_error(L));
3469 }
3470 return MAY_LJMP(hlua_channel_get_data_yield(L, 0, 0));
3471}
3472
3473/* Retrieves a given amount of input data at the given offset. By default all
3474 * available input data are returned. The offset may be negactive to start from
3475 * the end of input data. The length may be -1 to set it to the maximum buffer
3476 * size.
3477 */
3478__LJMP static int hlua_channel_get_line(lua_State *L)
3479{
3480 struct channel *chn;
3481
3482 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
3483 WILL_LJMP(luaL_error(L, "'line' expects at most 2 arguments"));
3484 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3485 if (IS_HTX_STRM(chn_strm(chn))) {
3486 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3487 WILL_LJMP(lua_error(L));
3488 }
3489 return MAY_LJMP(hlua_channel_get_line_yield(L, 0, 0));
3490}
3491
3492/* Appends a string into the input side of channel. It returns the length of the
3493 * written string, or -1 if the channel is closed or if the buffer size is too
3494 * little for the data. 0 may be returned if nothing is copied. This function
3495 * does not yield.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003496 *
3497 * For a filter, the context is updated on success.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003498 */
Christopher Faulet23976d92021-08-06 09:59:49 +02003499__LJMP static int hlua_channel_append(lua_State *L)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003500{
Christopher Faulet23976d92021-08-06 09:59:49 +02003501 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003502 struct filter *filter;
Christopher Faulet23976d92021-08-06 09:59:49 +02003503 const char *str;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003504 size_t sz, offset, len;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003505 int ret;
Christopher Faulet23976d92021-08-06 09:59:49 +02003506
3507 MAY_LJMP(check_args(L, 2, "append"));
3508 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003509 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
Christopher Faulet1bb6afa2021-03-08 17:57:53 +01003510 if (IS_HTX_STRM(chn_strm(chn))) {
Thierry Fournier77016da2020-08-15 14:35:51 +02003511 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
Christopher Faulet3f829a42018-12-13 21:56:45 +01003512 WILL_LJMP(lua_error(L));
Thierry Fournier77016da2020-08-15 14:35:51 +02003513 }
Christopher Faulet3f829a42018-12-13 21:56:45 +01003514
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003515 offset = co_data(chn);
3516 len = ci_data(chn);
3517
3518 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3519 if (filter && !hlua_filter_from_payload(filter))
3520 WILL_LJMP(lua_error(L));
3521
3522 ret = _hlua_channel_insert(chn, L, ist2(str, sz), offset);
3523 if (ret > 0 && filter) {
3524 struct hlua_flt_ctx *flt_ctx = filter->ctx;
3525
3526 flt_update_offsets(filter, chn, ret);
3527 flt_ctx->cur_len[CHN_IDX(chn)] += ret;
3528 }
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003529 lua_pushinteger(L, ret);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003530 return 1;
3531}
3532
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003533/* Prepends a string into the input side of channel. It returns the length of the
3534 * written string, or -1 if the channel is closed or if the buffer size is too
3535 * little for the data. 0 may be returned if nothing is copied. This function
3536 * does not yield.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003537 *
3538 * For a filter, the context is updated on success.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003539 */
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003540__LJMP static int hlua_channel_prepend(lua_State *L)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003541{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003542 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003543 struct filter *filter;
Christopher Faulet23976d92021-08-06 09:59:49 +02003544 const char *str;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003545 size_t sz, offset, len;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003546 int ret;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003547
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003548 MAY_LJMP(check_args(L, 2, "prepend"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003549 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003550 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
3551 if (IS_HTX_STRM(chn_strm(chn))) {
3552 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3553 WILL_LJMP(lua_error(L));
3554 }
3555
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003556 offset = co_data(chn);
3557 len = ci_data(chn);
3558
3559 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3560 if (filter && !hlua_filter_from_payload(filter))
3561 WILL_LJMP(lua_error(L));
3562
3563 ret = _hlua_channel_insert(chn, L, ist2(str, sz), offset);
3564 if (ret > 0 && filter) {
3565 struct hlua_flt_ctx *flt_ctx = filter->ctx;
3566
3567 flt_update_offsets(filter, chn, ret);
3568 flt_ctx->cur_len[CHN_IDX(chn)] += ret;
3569 }
3570
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003571 lua_pushinteger(L, ret);
3572 return 1;
3573}
3574
3575/* Inserts a given amount of input data at the given offset by a string
Aurelien DARRAGONafb7daf2022-10-04 12:16:05 +02003576 * content. By default the string is appended in front of input data. It
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003577 * returns the length of the written string, or -1 if the channel is closed or
3578 * if the buffer size is too little for the data.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003579 *
3580 * For a filter, the context is updated on success.
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003581 */
3582__LJMP static int hlua_channel_insert_data(lua_State *L)
3583{
3584 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003585 struct filter *filter;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003586 const char *str;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003587 size_t sz, input, output;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003588 int ret, offset;
3589
3590 if (lua_gettop(L) < 2 || lua_gettop(L) > 3)
3591 WILL_LJMP(luaL_error(L, "'insert' expects at least 1 argument and at most 2 arguments"));
3592 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3593 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003594
3595 output = co_data(chn);
3596 input = ci_data(chn);
3597
3598 filter = hlua_channel_filter(L, 1, chn, &output, &input);
3599 if (filter && !hlua_filter_from_payload(filter))
3600 WILL_LJMP(lua_error(L));
3601
Aurelien DARRAGONafb7daf2022-10-04 12:16:05 +02003602 offset = output;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003603 if (lua_gettop(L) > 2) {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003604 offset = MAY_LJMP(luaL_checkinteger(L, 3));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003605 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02003606 offset = MAX(0, (int)input + offset);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003607 offset += output;
Aurelien DARRAGONafb7daf2022-10-04 12:16:05 +02003608 if (offset > output + input) {
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003609 lua_pushfstring(L, "offset out of range.");
3610 WILL_LJMP(lua_error(L));
3611 }
3612 }
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003613 if (IS_HTX_STRM(chn_strm(chn))) {
3614 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3615 WILL_LJMP(lua_error(L));
3616 }
3617
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003618 ret = _hlua_channel_insert(chn, L, ist2(str, sz), offset);
3619 if (ret > 0 && filter) {
3620 struct hlua_flt_ctx *flt_ctx = filter->ctx;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003621
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003622 flt_update_offsets(filter, chn, ret);
3623 flt_ctx->cur_len[CHN_IDX(chn)] += ret;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003624 }
3625
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003626 lua_pushinteger(L, ret);
3627 return 1;
3628}
3629/* Replaces a given amount of input data at the given offset by a string
3630 * content. By default all remaining data are removed (offset = 0 and len =
3631 * -1). It returns the length of the written string, or -1 if the channel is
3632 * closed or if the buffer size is too little for the data.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003633 *
3634 * For a filter, the context is updated on success.
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003635 */
3636__LJMP static int hlua_channel_set_data(lua_State *L)
3637{
3638 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003639 struct filter *filter;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003640 const char *str;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003641 size_t sz, input, output;
3642 int ret, offset, len;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003643
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003644 if (lua_gettop(L) < 2 || lua_gettop(L) > 4)
3645 WILL_LJMP(luaL_error(L, "'set' expects at least 1 argument and at most 3 arguments"));
3646 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3647 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003648
Christopher Faulet1bb6afa2021-03-08 17:57:53 +01003649 if (IS_HTX_STRM(chn_strm(chn))) {
Thierry Fournier77016da2020-08-15 14:35:51 +02003650 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
Christopher Faulet3f829a42018-12-13 21:56:45 +01003651 WILL_LJMP(lua_error(L));
Thierry Fournier77016da2020-08-15 14:35:51 +02003652 }
Christopher Faulet3f829a42018-12-13 21:56:45 +01003653
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003654 output = co_data(chn);
3655 input = ci_data(chn);
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003656
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003657 filter = hlua_channel_filter(L, 1, chn, &output, &input);
3658 if (filter && !hlua_filter_from_payload(filter))
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003659 WILL_LJMP(lua_error(L));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003660
3661 offset = output;
3662 if (lua_gettop(L) > 2) {
3663 offset = MAY_LJMP(luaL_checkinteger(L, 3));
3664 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02003665 offset = MAX(0, (int)input + offset);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003666 offset += output;
3667 if (offset < output || offset > input + output) {
3668 lua_pushfstring(L, "offset out of range.");
3669 WILL_LJMP(lua_error(L));
3670 }
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003671 }
3672
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003673 len = output + input - offset;
3674 if (lua_gettop(L) == 4) {
3675 len = MAY_LJMP(luaL_checkinteger(L, 4));
3676 if (!len)
3677 goto set;
3678 if (len == -1)
3679 len = output + input - offset;
3680 if (len < 0 || offset + len > output + input) {
3681 lua_pushfstring(L, "length out of range.");
3682 WILL_LJMP(lua_error(L));
3683 }
3684 }
3685
3686 set:
Christopher Faulet23976d92021-08-06 09:59:49 +02003687 /* Be sure we can copied the string once input data will be removed. */
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003688 if (sz > c_room(chn) + len)
Christopher Faulet23976d92021-08-06 09:59:49 +02003689 lua_pushinteger(L, -1);
3690 else {
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003691 _hlua_channel_delete(chn, offset, len);
3692 ret = _hlua_channel_insert(chn, L, ist2(str, sz), offset);
3693 if (filter) {
3694 struct hlua_flt_ctx *flt_ctx = filter->ctx;
3695
3696 len -= (ret > 0 ? ret : 0);
3697 flt_update_offsets(filter, chn, -len);
3698 flt_ctx->cur_len[CHN_IDX(chn)] -= len;
3699 }
3700
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003701 lua_pushinteger(L, ret);
Christopher Faulet23976d92021-08-06 09:59:49 +02003702 }
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003703 return 1;
3704}
3705
3706/* Removes a given amount of input data at the given offset. By default all
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003707 * input data are removed (offset = 0 and len = -1). It returns the amount of
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003708 * the removed data.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003709 *
3710 * For a filter, the context is updated on success.
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003711 */
3712__LJMP static int hlua_channel_del_data(lua_State *L)
3713{
3714 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003715 struct filter *filter;
3716 size_t input, output;
3717 int offset, len;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003718
3719 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
3720 WILL_LJMP(luaL_error(L, "'remove' expects at most 2 arguments"));
3721 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003722
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003723 if (IS_HTX_STRM(chn_strm(chn))) {
3724 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3725 WILL_LJMP(lua_error(L));
3726 }
3727
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003728 output = co_data(chn);
3729 input = ci_data(chn);
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003730
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003731 filter = hlua_channel_filter(L, 1, chn, &output, &input);
3732 if (filter && !hlua_filter_from_payload(filter))
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003733 WILL_LJMP(lua_error(L));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003734
3735 offset = output;
Boyang Lie0c54352022-05-10 17:47:23 +00003736 if (lua_gettop(L) > 1) {
3737 offset = MAY_LJMP(luaL_checkinteger(L, 2));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003738 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02003739 offset = MAX(0, (int)input + offset);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003740 offset += output;
3741 if (offset < output || offset > input + output) {
3742 lua_pushfstring(L, "offset out of range.");
3743 WILL_LJMP(lua_error(L));
3744 }
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003745 }
3746
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003747 len = output + input - offset;
Boyang Lie0c54352022-05-10 17:47:23 +00003748 if (lua_gettop(L) == 3) {
3749 len = MAY_LJMP(luaL_checkinteger(L, 3));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003750 if (!len)
3751 goto end;
3752 if (len == -1)
3753 len = output + input - offset;
3754 if (len < 0 || offset + len > output + input) {
3755 lua_pushfstring(L, "length out of range.");
3756 WILL_LJMP(lua_error(L));
3757 }
3758 }
3759
3760 _hlua_channel_delete(chn, offset, len);
3761 if (filter) {
3762 struct hlua_flt_ctx *flt_ctx = filter->ctx;
3763
3764 flt_update_offsets(filter, chn, -len);
3765 flt_ctx->cur_len[CHN_IDX(chn)] -= len;
3766 }
3767
3768 end:
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003769 lua_pushinteger(L, len);
Christopher Faulet23976d92021-08-06 09:59:49 +02003770 return 1;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003771}
3772
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003773/* Append data in the output side of the buffer. This data is immediately
3774 * sent. The function returns the amount of data written. If the buffer
3775 * cannot contain the data, the function yields. The function returns -1
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003776 * if the channel is closed.
3777 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003778__LJMP static int hlua_channel_send_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003779{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003780 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003781 struct filter *filter;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003782 const char *str;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003783 size_t offset, len, sz;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003784 int l, ret;
Thierry Fournier4234dbd2020-11-28 13:18:23 +01003785 struct hlua *hlua;
3786
3787 /* Get hlua struct, or NULL if we execute from main lua state */
3788 hlua = hlua_gethlua(L);
3789 if (!hlua) {
3790 lua_pushnil(L);
3791 return 1;
3792 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003793
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003794 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3795 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
3796 l = MAY_LJMP(luaL_checkinteger(L, 3));
Christopher Faulet3f829a42018-12-13 21:56:45 +01003797
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003798 offset = co_data(chn);
3799 len = ci_data(chn);
3800
3801 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3802 if (filter && !hlua_filter_from_payload(filter))
3803 WILL_LJMP(lua_error(L));
3804
3805
Willy Tarreau47860ed2015-03-10 14:07:50 +01003806 if (unlikely(channel_output_closed(chn))) {
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003807 lua_pushinteger(L, -1);
3808 return 1;
3809 }
3810
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003811 len = c_room(chn);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003812 if (len > sz -l) {
3813 if (filter) {
3814 lua_pushinteger(L, -1);
3815 return 1;
3816 }
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003817 len = sz - l;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003818 }
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01003819
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003820 ret = _hlua_channel_insert(chn, L, ist2(str, len), offset);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003821 if (ret == -1) {
3822 lua_pop(L, 1);
3823 lua_pushinteger(L, -1);
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01003824 return 1;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003825 }
3826 if (ret) {
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003827 if (filter) {
3828 struct hlua_flt_ctx *flt_ctx = filter->ctx;
3829
3830
3831 flt_update_offsets(filter, chn, ret);
3832 FLT_OFF(filter, chn) += ret;
3833 flt_ctx->cur_off[CHN_IDX(chn)] += ret;
3834 }
3835 else
3836 c_adv(chn, ret);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003837
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003838 l += ret;
3839 lua_pop(L, 1);
3840 lua_pushinteger(L, l);
3841 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003842
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003843 if (l < sz) {
3844 /* Yield only if the channel's output is not empty.
3845 * Otherwise it means we cannot add more data. */
3846 if (co_data(chn) == 0 || HLUA_CANT_YIELD(hlua_gethlua(L)))
Christopher Faulet2e60aa42021-08-05 11:58:37 +02003847 return 1;
3848
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003849 /* If we are waiting for space in the response buffer, we
3850 * must set the flag WAKERESWR. This flag required the task
3851 * wake up if any activity is detected on the response buffer.
3852 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01003853 if (chn->flags & CF_ISRESP)
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003854 HLUA_SET_WAKERESWR(hlua);
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01003855 else
3856 HLUA_SET_WAKEREQWR(hlua);
Willy Tarreau9635e032018-10-16 17:52:55 +02003857 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003858 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003859
3860 return 1;
3861}
3862
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05003863/* Just a wrapper of "_hlua_channel_send". This wrapper permits
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003864 * yield the LUA process, and resume it without checking the
3865 * input arguments.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003866 *
3867 * This function cannot be called from a filter.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003868 */
3869__LJMP static int hlua_channel_send(lua_State *L)
3870{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003871 struct channel *chn;
3872
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003873 MAY_LJMP(check_args(L, 2, "send"));
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003874 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3875 if (IS_HTX_STRM(chn_strm(chn))) {
3876 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3877 WILL_LJMP(lua_error(L));
3878 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003879 lua_pushinteger(L, 0);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003880 return MAY_LJMP(hlua_channel_send_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003881}
3882
3883/* This function forward and amount of butes. The data pass from
3884 * the input side of the buffer to the output side, and can be
3885 * forwarded. This function never fails.
3886 *
3887 * The Lua function takes an amount of bytes to be forwarded in
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05003888 * input. It returns the number of bytes forwarded.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003889 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003890__LJMP static int hlua_channel_forward_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003891{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003892 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003893 struct filter *filter;
3894 size_t offset, len, fwd;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003895 int l, max;
Thierry Fournier4234dbd2020-11-28 13:18:23 +01003896 struct hlua *hlua;
3897
3898 /* Get hlua struct, or NULL if we execute from main lua state */
3899 hlua = hlua_gethlua(L);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003900 if (!hlua) {
3901 lua_pushnil(L);
Thierry Fournier4234dbd2020-11-28 13:18:23 +01003902 return 1;
Thierry Fournier77016da2020-08-15 14:35:51 +02003903 }
Christopher Faulet3f829a42018-12-13 21:56:45 +01003904
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003905 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003906 fwd = MAY_LJMP(luaL_checkinteger(L, 2));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003907 l = MAY_LJMP(luaL_checkinteger(L, -1));
3908
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003909 offset = co_data(chn);
3910 len = ci_data(chn);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003911
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003912 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3913 if (filter && !hlua_filter_from_payload(filter))
3914 WILL_LJMP(lua_error(L));
3915
3916 max = fwd - l;
3917 if (max > len)
3918 max = len;
3919
3920 if (filter) {
3921 struct hlua_flt_ctx *flt_ctx = filter->ctx;
3922
3923 FLT_OFF(filter, chn) += max;
3924 flt_ctx->cur_off[CHN_IDX(chn)] += max;
3925 flt_ctx->cur_len[CHN_IDX(chn)] -= max;
3926 }
3927 else
3928 channel_forward(chn, max);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003929
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003930 l += max;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003931 lua_pop(L, 1);
3932 lua_pushinteger(L, l);
3933
3934 /* Check if it miss bytes to forward. */
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003935 if (l < fwd) {
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003936 /* The the input channel or the output channel are closed, we
3937 * must return the amount of data forwarded.
3938 */
Christopher Faulet2e60aa42021-08-05 11:58:37 +02003939 if (channel_input_closed(chn) || channel_output_closed(chn) || HLUA_CANT_YIELD(hlua_gethlua(L)))
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003940 return 1;
3941
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003942 /* If we are waiting for space data in the response buffer, we
3943 * must set the flag WAKERESWR. This flag required the task
3944 * wake up if any activity is detected on the response buffer.
3945 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01003946 if (chn->flags & CF_ISRESP)
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003947 HLUA_SET_WAKERESWR(hlua);
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01003948 else
3949 HLUA_SET_WAKEREQWR(hlua);
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003950
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003951 /* Otherwise, we can yield waiting for new data in the inpout side. */
Willy Tarreau9635e032018-10-16 17:52:55 +02003952 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_forward_yield, TICK_ETERNITY, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003953 }
3954
3955 return 1;
3956}
3957
3958/* Just check the input and prepare the stack for the previous
3959 * function "hlua_channel_forward_yield"
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003960 *
3961 * This function cannot be called from a filter.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003962 */
3963__LJMP static int hlua_channel_forward(lua_State *L)
3964{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003965 struct channel *chn;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003966
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003967 MAY_LJMP(check_args(L, 2, "forward"));
3968 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3969 if (IS_HTX_STRM(chn_strm(chn))) {
3970 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3971 WILL_LJMP(lua_error(L));
3972 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003973 lua_pushinteger(L, 0);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003974 return MAY_LJMP(hlua_channel_forward_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003975}
3976
3977/* Just returns the number of bytes available in the input
3978 * side of the buffer. This function never fails.
3979 */
3980__LJMP static int hlua_channel_get_in_len(lua_State *L)
3981{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003982 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003983 struct filter *filter;
3984 size_t output, input;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003985
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003986 MAY_LJMP(check_args(L, 1, "input"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003987 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003988
3989 output = co_data(chn);
3990 input = ci_data(chn);
3991 filter = hlua_channel_filter(L, 1, chn, &output, &input);
3992 if (filter || !IS_HTX_STRM(chn_strm(chn)))
3993 lua_pushinteger(L, input);
3994 else {
Christopher Fauleta3ceac12018-12-14 13:39:09 +01003995 struct htx *htx = htxbuf(&chn->buf);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003996
Christopher Fauleta3ceac12018-12-14 13:39:09 +01003997 lua_pushinteger(L, htx->data - co_data(chn));
3998 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003999 return 1;
4000}
4001
Thierry FOURNIER / OZON.IO65192f32016-11-07 15:28:40 +01004002/* Returns true if the channel is full. */
4003__LJMP static int hlua_channel_is_full(lua_State *L)
4004{
4005 struct channel *chn;
Thierry FOURNIER / OZON.IO65192f32016-11-07 15:28:40 +01004006
4007 MAY_LJMP(check_args(L, 1, "is_full"));
4008 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Faulet0ec740e2020-02-26 11:59:19 +01004009 /* ignore the reserve, we are not on a producer side (ie in an
4010 * applet).
4011 */
4012 lua_pushboolean(L, channel_full(chn, 0));
Thierry FOURNIER / OZON.IO65192f32016-11-07 15:28:40 +01004013 return 1;
4014}
4015
Christopher Faulet6a79fc12021-08-06 16:02:36 +02004016/* Returns true if the channel may still receive data. */
4017__LJMP static int hlua_channel_may_recv(lua_State *L)
4018{
4019 struct channel *chn;
4020
4021 MAY_LJMP(check_args(L, 1, "may_recv"));
4022 chn = MAY_LJMP(hlua_checkchannel(L, 1));
4023 lua_pushboolean(L, (!channel_input_closed(chn) && channel_may_recv(chn)));
4024 return 1;
4025}
4026
Christopher Faulet2ac9ba22020-02-25 10:15:50 +01004027/* Returns true if the channel is the response channel. */
4028__LJMP static int hlua_channel_is_resp(lua_State *L)
4029{
4030 struct channel *chn;
4031
4032 MAY_LJMP(check_args(L, 1, "is_resp"));
4033 chn = MAY_LJMP(hlua_checkchannel(L, 1));
4034
4035 lua_pushboolean(L, !!(chn->flags & CF_ISRESP));
4036 return 1;
4037}
4038
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004039/* Just returns the number of bytes available in the output
4040 * side of the buffer. This function never fails.
4041 */
4042__LJMP static int hlua_channel_get_out_len(lua_State *L)
4043{
Willy Tarreau47860ed2015-03-10 14:07:50 +01004044 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004045 size_t output, input;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004046
Christopher Faulet6a79fc12021-08-06 16:02:36 +02004047 MAY_LJMP(check_args(L, 1, "output"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004048 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004049
4050 output = co_data(chn);
4051 input = ci_data(chn);
4052 hlua_channel_filter(L, 1, chn, &output, &input);
4053
4054 lua_pushinteger(L, output);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004055 return 1;
4056}
4057
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004058/*
4059 *
4060 *
4061 * Class Fetches
4062 *
4063 *
4064 */
4065
4066/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02004067 * a class stream, otherwise it throws an error.
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004068 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004069__LJMP static struct hlua_smp *hlua_checkfetches(lua_State *L, int ud)
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004070{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004071 return MAY_LJMP(hlua_checkudata(L, ud, class_fetches_ref));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004072}
4073
4074/* This function creates and push in the stack a fetch object according
4075 * with a current TXN.
4076 */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004077static int hlua_fetches_new(lua_State *L, struct hlua_txn *txn, unsigned int flags)
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004078{
Willy Tarreau7073c472015-04-06 11:15:40 +02004079 struct hlua_smp *hsmp;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004080
4081 /* Check stack size. */
4082 if (!lua_checkstack(L, 3))
4083 return 0;
4084
4085 /* Create the object: obj[0] = userdata.
4086 * Note that the base of the Fetches object is the
4087 * transaction object.
4088 */
4089 lua_newtable(L);
Willy Tarreau7073c472015-04-06 11:15:40 +02004090 hsmp = lua_newuserdata(L, sizeof(*hsmp));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004091 lua_rawseti(L, -2, 0);
4092
Willy Tarreau7073c472015-04-06 11:15:40 +02004093 hsmp->s = txn->s;
4094 hsmp->p = txn->p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01004095 hsmp->dir = txn->dir;
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004096 hsmp->flags = flags;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004097
4098 /* Pop a class sesison metatable and affect it to the userdata. */
4099 lua_rawgeti(L, LUA_REGISTRYINDEX, class_fetches_ref);
4100 lua_setmetatable(L, -2);
4101
4102 return 1;
4103}
4104
4105/* This function is an LUA binding. It is called with each sample-fetch.
4106 * It uses closure argument to store the associated sample-fetch. It
4107 * returns only one argument or throws an error. An error is thrown
4108 * only if an error is encountered during the argument parsing. If
4109 * the "sample-fetch" function fails, nil is returned.
4110 */
4111__LJMP static int hlua_run_sample_fetch(lua_State *L)
4112{
Willy Tarreaub2ccb562015-04-06 11:11:15 +02004113 struct hlua_smp *hsmp;
Willy Tarreau2ec22742015-03-10 14:27:20 +01004114 struct sample_fetch *f;
Frédéric Lécaillef874a832018-06-15 13:56:04 +02004115 struct arg args[ARGM_NBARGS + 1] = {{0}};
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004116 int i;
4117 struct sample smp;
4118
4119 /* Get closure arguments. */
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004120 f = lua_touserdata(L, lua_upvalueindex(1));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004121
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004122 /* Get traditional arguments. */
Willy Tarreaub2ccb562015-04-06 11:11:15 +02004123 hsmp = MAY_LJMP(hlua_checkfetches(L, 1));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004124
Thierry FOURNIERca988662015-12-20 18:43:03 +01004125 /* Check execution authorization. */
4126 if (f->use & SMP_USE_HTTP_ANY &&
4127 !(hsmp->flags & HLUA_F_MAY_USE_HTTP)) {
4128 lua_pushfstring(L, "the sample-fetch '%s' needs an HTTP parser which "
4129 "is not available in Lua services", f->kw);
4130 WILL_LJMP(lua_error(L));
4131 }
4132
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004133 /* Get extra arguments. */
4134 for (i = 0; i < lua_gettop(L) - 1; i++) {
4135 if (i >= ARGM_NBARGS)
4136 break;
4137 hlua_lua2arg(L, i + 2, &args[i]);
4138 }
4139 args[i].type = ARGT_STOP;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004140 args[i].data.str.area = NULL;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004141
4142 /* Check arguments. */
Willy Tarreaub2ccb562015-04-06 11:11:15 +02004143 MAY_LJMP(hlua_lua2arg_check(L, 2, args, f->arg_mask, hsmp->p));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004144
4145 /* Run the special args checker. */
Willy Tarreau2ec22742015-03-10 14:27:20 +01004146 if (f->val_args && !f->val_args(args, NULL)) {
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004147 lua_pushfstring(L, "error in arguments");
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004148 goto error;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004149 }
4150
4151 /* Initialise the sample. */
4152 memset(&smp, 0, sizeof(smp));
4153
4154 /* Run the sample fetch process. */
Willy Tarreau1777ea62016-03-10 16:15:46 +01004155 smp_set_owner(&smp, hsmp->p, hsmp->s->sess, hsmp->s, hsmp->dir & SMP_OPT_DIR);
Thierry FOURNIER0786d052015-05-11 15:42:45 +02004156 if (!f->process(args, &smp, f->kw, f->private)) {
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004157 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004158 lua_pushstring(L, "");
4159 else
4160 lua_pushnil(L);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004161 goto end;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004162 }
4163
4164 /* Convert the returned sample in lua value. */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004165 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004166 hlua_smp2lua_str(L, &smp);
4167 else
4168 hlua_smp2lua(L, &smp);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004169
4170 end:
Willy Tarreauee0d7272021-07-16 10:26:56 +02004171 free_args(args);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004172 return 1;
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004173
4174 error:
Willy Tarreauee0d7272021-07-16 10:26:56 +02004175 free_args(args);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004176 WILL_LJMP(lua_error(L));
4177 return 0; /* Never reached */
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004178}
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004179
4180/*
4181 *
4182 *
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004183 * Class Converters
4184 *
4185 *
4186 */
4187
4188/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02004189 * a class stream, otherwise it throws an error.
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004190 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004191__LJMP static struct hlua_smp *hlua_checkconverters(lua_State *L, int ud)
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004192{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004193 return MAY_LJMP(hlua_checkudata(L, ud, class_converters_ref));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004194}
4195
4196/* This function creates and push in the stack a Converters object
4197 * according with a current TXN.
4198 */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004199static int hlua_converters_new(lua_State *L, struct hlua_txn *txn, unsigned int flags)
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004200{
Willy Tarreau7073c472015-04-06 11:15:40 +02004201 struct hlua_smp *hsmp;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004202
4203 /* Check stack size. */
4204 if (!lua_checkstack(L, 3))
4205 return 0;
4206
4207 /* Create the object: obj[0] = userdata.
4208 * Note that the base of the Converters object is the
4209 * same than the TXN object.
4210 */
4211 lua_newtable(L);
Willy Tarreau7073c472015-04-06 11:15:40 +02004212 hsmp = lua_newuserdata(L, sizeof(*hsmp));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004213 lua_rawseti(L, -2, 0);
4214
Willy Tarreau7073c472015-04-06 11:15:40 +02004215 hsmp->s = txn->s;
4216 hsmp->p = txn->p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01004217 hsmp->dir = txn->dir;
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004218 hsmp->flags = flags;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004219
Willy Tarreau87b09662015-04-03 00:22:06 +02004220 /* Pop a class stream metatable and affect it to the table. */
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004221 lua_rawgeti(L, LUA_REGISTRYINDEX, class_converters_ref);
4222 lua_setmetatable(L, -2);
4223
4224 return 1;
4225}
4226
4227/* This function is an LUA binding. It is called with each converter.
4228 * It uses closure argument to store the associated converter. It
4229 * returns only one argument or throws an error. An error is thrown
4230 * only if an error is encountered during the argument parsing. If
4231 * the converter function function fails, nil is returned.
4232 */
4233__LJMP static int hlua_run_sample_conv(lua_State *L)
4234{
Willy Tarreauda5f1082015-04-06 11:17:13 +02004235 struct hlua_smp *hsmp;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004236 struct sample_conv *conv;
Frédéric Lécaillef874a832018-06-15 13:56:04 +02004237 struct arg args[ARGM_NBARGS + 1] = {{0}};
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004238 int i;
4239 struct sample smp;
4240
4241 /* Get closure arguments. */
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004242 conv = lua_touserdata(L, lua_upvalueindex(1));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004243
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004244 /* Get traditional arguments. */
Willy Tarreauda5f1082015-04-06 11:17:13 +02004245 hsmp = MAY_LJMP(hlua_checkconverters(L, 1));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004246
4247 /* Get extra arguments. */
4248 for (i = 0; i < lua_gettop(L) - 2; i++) {
4249 if (i >= ARGM_NBARGS)
4250 break;
4251 hlua_lua2arg(L, i + 3, &args[i]);
4252 }
4253 args[i].type = ARGT_STOP;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004254 args[i].data.str.area = NULL;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004255
4256 /* Check arguments. */
Willy Tarreauda5f1082015-04-06 11:17:13 +02004257 MAY_LJMP(hlua_lua2arg_check(L, 3, args, conv->arg_mask, hsmp->p));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004258
4259 /* Run the special args checker. */
4260 if (conv->val_args && !conv->val_args(args, conv, "", 0, NULL)) {
4261 hlua_pusherror(L, "error in arguments");
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004262 goto error;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004263 }
4264
4265 /* Initialise the sample. */
Amaury Denoyellebc0af6a2020-10-29 17:21:20 +01004266 memset(&smp, 0, sizeof(smp));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004267 if (!hlua_lua2smp(L, 2, &smp)) {
4268 hlua_pusherror(L, "error in the input argument");
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004269 goto error;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004270 }
4271
Willy Tarreau1777ea62016-03-10 16:15:46 +01004272 smp_set_owner(&smp, hsmp->p, hsmp->s->sess, hsmp->s, hsmp->dir & SMP_OPT_DIR);
4273
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004274 /* Apply expected cast. */
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02004275 if (!sample_casts[smp.data.type][conv->in_type]) {
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004276 hlua_pusherror(L, "invalid input argument: cannot cast '%s' to '%s'",
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02004277 smp_to_type[smp.data.type], smp_to_type[conv->in_type]);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004278 goto error;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004279 }
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02004280 if (sample_casts[smp.data.type][conv->in_type] != c_none &&
4281 !sample_casts[smp.data.type][conv->in_type](&smp)) {
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004282 hlua_pusherror(L, "error during the input argument casting");
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004283 goto error;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004284 }
4285
4286 /* Run the sample conversion process. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02004287 if (!conv->process(args, &smp, conv->private)) {
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004288 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004289 lua_pushstring(L, "");
4290 else
Willy Tarreaua678b432015-08-28 10:14:59 +02004291 lua_pushnil(L);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004292 goto end;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004293 }
4294
4295 /* Convert the returned sample in lua value. */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004296 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004297 hlua_smp2lua_str(L, &smp);
4298 else
4299 hlua_smp2lua(L, &smp);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004300 end:
Willy Tarreauee0d7272021-07-16 10:26:56 +02004301 free_args(args);
Willy Tarreaua678b432015-08-28 10:14:59 +02004302 return 1;
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004303
4304 error:
Willy Tarreauee0d7272021-07-16 10:26:56 +02004305 free_args(args);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004306 WILL_LJMP(lua_error(L));
4307 return 0; /* Never reached */
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004308}
4309
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004310/*
4311 *
4312 *
4313 * Class AppletTCP
4314 *
4315 *
4316 */
4317
4318/* Returns a struct hlua_txn if the stack entry "ud" is
4319 * a class stream, otherwise it throws an error.
4320 */
4321__LJMP static struct hlua_appctx *hlua_checkapplet_tcp(lua_State *L, int ud)
4322{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004323 return MAY_LJMP(hlua_checkudata(L, ud, class_applet_tcp_ref));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004324}
4325
4326/* This function creates and push in the stack an Applet object
4327 * according with a current TXN.
4328 */
4329static int hlua_applet_tcp_new(lua_State *L, struct appctx *ctx)
4330{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004331 struct hlua_appctx *luactx;
Willy Tarreau0698c802022-05-11 14:09:57 +02004332 struct stream *s = appctx_strm(ctx);
Christopher Faulet2da02ae2022-02-24 13:45:27 +01004333 struct proxy *p;
4334
4335 ALREADY_CHECKED(s);
4336 p = s->be;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004337
4338 /* Check stack size. */
4339 if (!lua_checkstack(L, 3))
4340 return 0;
4341
4342 /* Create the object: obj[0] = userdata.
4343 * Note that the base of the Converters object is the
4344 * same than the TXN object.
4345 */
4346 lua_newtable(L);
Willy Tarreau7e702d12021-04-28 17:59:21 +02004347 luactx = lua_newuserdata(L, sizeof(*luactx));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004348 lua_rawseti(L, -2, 0);
Willy Tarreau7e702d12021-04-28 17:59:21 +02004349 luactx->appctx = ctx;
4350 luactx->htxn.s = s;
4351 luactx->htxn.p = p;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004352
4353 /* Create the "f" field that contains a list of fetches. */
4354 lua_pushstring(L, "f");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004355 if (!hlua_fetches_new(L, &luactx->htxn, 0))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004356 return 0;
4357 lua_settable(L, -3);
4358
4359 /* Create the "sf" field that contains a list of stringsafe fetches. */
4360 lua_pushstring(L, "sf");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004361 if (!hlua_fetches_new(L, &luactx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004362 return 0;
4363 lua_settable(L, -3);
4364
4365 /* Create the "c" field that contains a list of converters. */
4366 lua_pushstring(L, "c");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004367 if (!hlua_converters_new(L, &luactx->htxn, 0))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004368 return 0;
4369 lua_settable(L, -3);
4370
4371 /* Create the "sc" field that contains a list of stringsafe converters. */
4372 lua_pushstring(L, "sc");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004373 if (!hlua_converters_new(L, &luactx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004374 return 0;
4375 lua_settable(L, -3);
4376
4377 /* Pop a class stream metatable and affect it to the table. */
4378 lua_rawgeti(L, LUA_REGISTRYINDEX, class_applet_tcp_ref);
4379 lua_setmetatable(L, -2);
4380
4381 return 1;
4382}
4383
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004384__LJMP static int hlua_applet_tcp_set_var(lua_State *L)
4385{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004386 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004387 struct stream *s;
4388 const char *name;
4389 size_t len;
4390 struct sample smp;
4391
Tim Duesterhus4e172c92020-05-19 13:49:42 +02004392 if (lua_gettop(L) < 3 || lua_gettop(L) > 4)
4393 WILL_LJMP(luaL_error(L, "'set_var' needs between 3 and 4 arguments"));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004394
4395 /* It is useles to retrieve the stream, but this function
4396 * runs only in a stream context.
4397 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004398 luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004399 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02004400 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004401
4402 /* Converts the third argument in a sample. */
Amaury Denoyellebc0af6a2020-10-29 17:21:20 +01004403 memset(&smp, 0, sizeof(smp));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004404 hlua_lua2smp(L, 3, &smp);
4405
4406 /* Store the sample in a variable. */
4407 smp_set_owner(&smp, s->be, s->sess, s, 0);
Tim Duesterhus4e172c92020-05-19 13:49:42 +02004408
4409 if (lua_gettop(L) == 4 && lua_toboolean(L, 4))
4410 lua_pushboolean(L, vars_set_by_name_ifexist(name, len, &smp) != 0);
4411 else
4412 lua_pushboolean(L, vars_set_by_name(name, len, &smp) != 0);
4413
Tim Duesterhus84ebc132020-05-19 13:49:41 +02004414 return 1;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004415}
4416
4417__LJMP static int hlua_applet_tcp_unset_var(lua_State *L)
4418{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004419 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004420 struct stream *s;
4421 const char *name;
4422 size_t len;
4423 struct sample smp;
4424
4425 MAY_LJMP(check_args(L, 2, "unset_var"));
4426
4427 /* It is useles to retrieve the stream, but this function
4428 * runs only in a stream context.
4429 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004430 luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004431 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02004432 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004433
4434 /* Unset the variable. */
4435 smp_set_owner(&smp, s->be, s->sess, s, 0);
Tim Duesterhus84ebc132020-05-19 13:49:41 +02004436 lua_pushboolean(L, vars_unset_by_name_ifexist(name, len, &smp) != 0);
4437 return 1;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004438}
4439
4440__LJMP static int hlua_applet_tcp_get_var(lua_State *L)
4441{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004442 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004443 struct stream *s;
4444 const char *name;
4445 size_t len;
4446 struct sample smp;
4447
4448 MAY_LJMP(check_args(L, 2, "get_var"));
4449
4450 /* It is useles to retrieve the stream, but this function
4451 * runs only in a stream context.
4452 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004453 luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004454 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02004455 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004456
4457 smp_set_owner(&smp, s->be, s->sess, s, 0);
Willy Tarreaue352b9d2021-09-03 11:52:38 +02004458 if (!vars_get_by_name(name, len, &smp, NULL)) {
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004459 lua_pushnil(L);
4460 return 1;
4461 }
4462
4463 return hlua_smp2lua(L, &smp);
4464}
4465
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004466__LJMP static int hlua_applet_tcp_set_priv(lua_State *L)
4467{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004468 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
4469 struct stream *s = luactx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01004470 struct hlua *hlua;
4471
4472 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01004473 if (!s->hlua)
4474 return 0;
4475 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004476
4477 MAY_LJMP(check_args(L, 2, "set_priv"));
4478
4479 /* Remove previous value. */
Thierry FOURNIERe068b602017-04-26 13:27:05 +02004480 luaL_unref(L, LUA_REGISTRYINDEX, hlua->Mref);
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004481
4482 /* Get and store new value. */
4483 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
4484 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
4485
4486 return 0;
4487}
4488
4489__LJMP static int hlua_applet_tcp_get_priv(lua_State *L)
4490{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004491 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
4492 struct stream *s = luactx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01004493 struct hlua *hlua;
4494
4495 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01004496 if (!s->hlua) {
4497 lua_pushnil(L);
4498 return 1;
4499 }
4500 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004501
4502 /* Push configuration index in the stack. */
4503 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
4504
4505 return 1;
4506}
4507
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004508/* If expected data not yet available, it returns a yield. This function
4509 * consumes the data in the buffer. It returns a string containing the
4510 * data. This string can be empty.
4511 */
4512__LJMP static int hlua_applet_tcp_getline_yield(lua_State *L, int status, lua_KContext ctx)
4513{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004514 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Willy Tarreauc12b3212022-05-27 11:08:15 +02004515 struct stconn *sc = appctx_sc(luactx->appctx);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004516 int ret;
Willy Tarreau206ba832018-06-14 15:27:31 +02004517 const char *blk1;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004518 size_t len1;
Willy Tarreau206ba832018-06-14 15:27:31 +02004519 const char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004520 size_t len2;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004521
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004522 /* Read the maximum amount of data available. */
Willy Tarreau3e7be362022-05-27 10:35:27 +02004523 ret = co_getline_nc(sc_oc(sc), &blk1, &len1, &blk2, &len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004524
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004525 /* Data not yet available. return yield. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004526 if (ret == 0) {
Willy Tarreau90e8b452022-05-25 18:21:43 +02004527 applet_need_more_data(luactx->appctx);
Willy Tarreau9635e032018-10-16 17:52:55 +02004528 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_getline_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004529 }
4530
4531 /* End of data: commit the total strings and return. */
4532 if (ret < 0) {
Willy Tarreau7e702d12021-04-28 17:59:21 +02004533 luaL_pushresult(&luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004534 return 1;
4535 }
4536
4537 /* Ensure that the block 2 length is usable. */
4538 if (ret == 1)
4539 len2 = 0;
4540
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -07004541 /* don't check the max length read and don't check. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004542 luaL_addlstring(&luactx->b, blk1, len1);
4543 luaL_addlstring(&luactx->b, blk2, len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004544
4545 /* Consume input channel output buffer data. */
Willy Tarreau3e7be362022-05-27 10:35:27 +02004546 co_skip(sc_oc(sc), len1 + len2);
Willy Tarreau7e702d12021-04-28 17:59:21 +02004547 luaL_pushresult(&luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004548 return 1;
4549}
4550
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004551/* Check arguments for the function "hlua_channel_get_yield". */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004552__LJMP static int hlua_applet_tcp_getline(lua_State *L)
4553{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004554 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004555
4556 /* Initialise the string catenation. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004557 luaL_buffinit(L, &luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004558
4559 return MAY_LJMP(hlua_applet_tcp_getline_yield(L, 0, 0));
4560}
4561
4562/* If expected data not yet available, it returns a yield. This function
4563 * consumes the data in the buffer. It returns a string containing the
4564 * data. This string can be empty.
4565 */
4566__LJMP static int hlua_applet_tcp_recv_yield(lua_State *L, int status, lua_KContext ctx)
4567{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004568 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Willy Tarreauc12b3212022-05-27 11:08:15 +02004569 struct stconn *sc = appctx_sc(luactx->appctx);
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004570 size_t len = MAY_LJMP(luaL_checkinteger(L, 2));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004571 int ret;
Willy Tarreau206ba832018-06-14 15:27:31 +02004572 const char *blk1;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004573 size_t len1;
Willy Tarreau206ba832018-06-14 15:27:31 +02004574 const char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004575 size_t len2;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004576
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004577 /* Read the maximum amount of data available. */
Willy Tarreau3e7be362022-05-27 10:35:27 +02004578 ret = co_getblk_nc(sc_oc(sc), &blk1, &len1, &blk2, &len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004579
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004580 /* Data not yet available. return yield. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004581 if (ret == 0) {
Willy Tarreau90e8b452022-05-25 18:21:43 +02004582 applet_need_more_data(luactx->appctx);
Willy Tarreau9635e032018-10-16 17:52:55 +02004583 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004584 }
4585
4586 /* End of data: commit the total strings and return. */
4587 if (ret < 0) {
Willy Tarreau7e702d12021-04-28 17:59:21 +02004588 luaL_pushresult(&luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004589 return 1;
4590 }
4591
4592 /* Ensure that the block 2 length is usable. */
4593 if (ret == 1)
4594 len2 = 0;
4595
4596 if (len == -1) {
4597
4598 /* If len == -1, catenate all the data avalaile and
4599 * yield because we want to get all the data until
4600 * the end of data stream.
4601 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004602 luaL_addlstring(&luactx->b, blk1, len1);
4603 luaL_addlstring(&luactx->b, blk2, len2);
Willy Tarreau3e7be362022-05-27 10:35:27 +02004604 co_skip(sc_oc(sc), len1 + len2);
Willy Tarreau90e8b452022-05-25 18:21:43 +02004605 applet_need_more_data(luactx->appctx);
Willy Tarreau9635e032018-10-16 17:52:55 +02004606 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004607
4608 } else {
4609
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05004610 /* Copy the first block caping to the length required. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004611 if (len1 > len)
4612 len1 = len;
Willy Tarreau7e702d12021-04-28 17:59:21 +02004613 luaL_addlstring(&luactx->b, blk1, len1);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004614 len -= len1;
4615
4616 /* Copy the second block. */
4617 if (len2 > len)
4618 len2 = len;
Willy Tarreau7e702d12021-04-28 17:59:21 +02004619 luaL_addlstring(&luactx->b, blk2, len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004620 len -= len2;
4621
4622 /* Consume input channel output buffer data. */
Willy Tarreau3e7be362022-05-27 10:35:27 +02004623 co_skip(sc_oc(sc), len1 + len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004624
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004625 /* If there is no other data available, yield waiting for new data. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004626 if (len > 0) {
4627 lua_pushinteger(L, len);
4628 lua_replace(L, 2);
Willy Tarreau90e8b452022-05-25 18:21:43 +02004629 applet_need_more_data(luactx->appctx);
Willy Tarreau9635e032018-10-16 17:52:55 +02004630 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004631 }
4632
4633 /* return the result. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004634 luaL_pushresult(&luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004635 return 1;
4636 }
4637
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004638 /* we never execute this */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004639 hlua_pusherror(L, "Lua: internal error");
4640 WILL_LJMP(lua_error(L));
4641 return 0;
4642}
4643
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004644/* Check arguments for the function "hlua_channel_get_yield". */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004645__LJMP static int hlua_applet_tcp_recv(lua_State *L)
4646{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004647 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004648 int len = -1;
4649
4650 if (lua_gettop(L) > 2)
4651 WILL_LJMP(luaL_error(L, "The 'recv' function requires between 1 and 2 arguments."));
4652 if (lua_gettop(L) >= 2) {
4653 len = MAY_LJMP(luaL_checkinteger(L, 2));
4654 lua_pop(L, 1);
4655 }
4656
4657 /* Confirm or set the required length */
4658 lua_pushinteger(L, len);
4659
4660 /* Initialise the string catenation. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004661 luaL_buffinit(L, &luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004662
4663 return MAY_LJMP(hlua_applet_tcp_recv_yield(L, 0, 0));
4664}
4665
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004666/* Append data in the output side of the buffer. This data is immediately
4667 * sent. The function returns the amount of data written. If the buffer
4668 * cannot contain the data, the function yields. The function returns -1
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004669 * if the channel is closed.
4670 */
4671__LJMP static int hlua_applet_tcp_send_yield(lua_State *L, int status, lua_KContext ctx)
4672{
4673 size_t len;
Willy Tarreau7e702d12021-04-28 17:59:21 +02004674 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004675 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
4676 int l = MAY_LJMP(luaL_checkinteger(L, 3));
Willy Tarreauc12b3212022-05-27 11:08:15 +02004677 struct stconn *sc = appctx_sc(luactx->appctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02004678 struct channel *chn = sc_ic(sc);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004679 int max;
4680
4681 /* Get the max amount of data which can write as input in the channel. */
4682 max = channel_recv_max(chn);
4683 if (max > (len - l))
4684 max = len - l;
4685
4686 /* Copy data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02004687 ci_putblk(chn, str + l, max);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004688
4689 /* update counters. */
4690 l += max;
4691 lua_pop(L, 1);
4692 lua_pushinteger(L, l);
4693
4694 /* If some data is not send, declares the situation to the
4695 * applet, and returns a yield.
4696 */
4697 if (l < len) {
Willy Tarreau3e7be362022-05-27 10:35:27 +02004698 sc_need_room(sc);
Willy Tarreau9635e032018-10-16 17:52:55 +02004699 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004700 }
4701
4702 return 1;
4703}
4704
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05004705/* Just a wrapper of "hlua_applet_tcp_send_yield". This wrapper permits
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004706 * yield the LUA process, and resume it without checking the
4707 * input arguments.
4708 */
4709__LJMP static int hlua_applet_tcp_send(lua_State *L)
4710{
4711 MAY_LJMP(check_args(L, 2, "send"));
4712 lua_pushinteger(L, 0);
4713
4714 return MAY_LJMP(hlua_applet_tcp_send_yield(L, 0, 0));
4715}
4716
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004717/*
4718 *
4719 *
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004720 * Class AppletHTTP
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004721 *
4722 *
4723 */
4724
4725/* Returns a struct hlua_txn if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02004726 * a class stream, otherwise it throws an error.
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004727 */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004728__LJMP static struct hlua_appctx *hlua_checkapplet_http(lua_State *L, int ud)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004729{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004730 return MAY_LJMP(hlua_checkudata(L, ud, class_applet_http_ref));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004731}
4732
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004733/* This function creates and push in the stack an Applet object
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004734 * according with a current TXN.
Willy Tarreauaa229cc2022-05-06 14:26:10 +02004735 * It relies on the caller to have already reserved the room in ctx->svcctx
4736 * for the local storage of hlua_http_ctx.
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004737 */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004738static int hlua_applet_http_new(lua_State *L, struct appctx *ctx)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004739{
Willy Tarreauaa229cc2022-05-06 14:26:10 +02004740 struct hlua_http_ctx *http_ctx = ctx->svcctx;
Willy Tarreau7e702d12021-04-28 17:59:21 +02004741 struct hlua_appctx *luactx;
Thierry FOURNIER841475e2015-12-11 17:10:09 +01004742 struct hlua_txn htxn;
Willy Tarreau0698c802022-05-11 14:09:57 +02004743 struct stream *s = appctx_strm(ctx);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004744 struct proxy *px = s->be;
Christopher Fauleta2097962019-07-15 16:25:33 +02004745 struct htx *htx;
4746 struct htx_blk *blk;
4747 struct htx_sl *sl;
4748 struct ist path;
4749 unsigned long long len = 0;
4750 int32_t pos;
Amaury Denoyellec453f952021-07-06 11:40:12 +02004751 struct http_uri_parser parser;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004752
4753 /* Check stack size. */
4754 if (!lua_checkstack(L, 3))
4755 return 0;
4756
4757 /* Create the object: obj[0] = userdata.
4758 * Note that the base of the Converters object is the
4759 * same than the TXN object.
4760 */
4761 lua_newtable(L);
Willy Tarreau7e702d12021-04-28 17:59:21 +02004762 luactx = lua_newuserdata(L, sizeof(*luactx));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004763 lua_rawseti(L, -2, 0);
Willy Tarreau7e702d12021-04-28 17:59:21 +02004764 luactx->appctx = ctx;
Willy Tarreauaa229cc2022-05-06 14:26:10 +02004765 http_ctx->status = 200; /* Default status code returned. */
4766 http_ctx->reason = NULL; /* Use default reason based on status */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004767 luactx->htxn.s = s;
4768 luactx->htxn.p = px;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004769
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004770 /* Create the "f" field that contains a list of fetches. */
4771 lua_pushstring(L, "f");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004772 if (!hlua_fetches_new(L, &luactx->htxn, 0))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004773 return 0;
4774 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004775
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004776 /* Create the "sf" field that contains a list of stringsafe fetches. */
4777 lua_pushstring(L, "sf");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004778 if (!hlua_fetches_new(L, &luactx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004779 return 0;
4780 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004781
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004782 /* Create the "c" field that contains a list of converters. */
4783 lua_pushstring(L, "c");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004784 if (!hlua_converters_new(L, &luactx->htxn, 0))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004785 return 0;
4786 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004787
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004788 /* Create the "sc" field that contains a list of stringsafe converters. */
4789 lua_pushstring(L, "sc");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004790 if (!hlua_converters_new(L, &luactx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004791 return 0;
4792 lua_settable(L, -3);
Willy Tarreaueee5b512015-04-03 23:46:31 +02004793
Christopher Fauleta2097962019-07-15 16:25:33 +02004794 htx = htxbuf(&s->req.buf);
4795 blk = htx_get_first_blk(htx);
Christopher Fauletea009732019-11-18 15:50:25 +01004796 BUG_ON(!blk || htx_get_blk_type(blk) != HTX_BLK_REQ_SL);
Christopher Fauleta2097962019-07-15 16:25:33 +02004797 sl = htx_get_blk_ptr(htx, blk);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004798
Christopher Fauleta2097962019-07-15 16:25:33 +02004799 /* Stores the request method. */
4800 lua_pushstring(L, "method");
4801 lua_pushlstring(L, HTX_SL_REQ_MPTR(sl), HTX_SL_REQ_MLEN(sl));
4802 lua_settable(L, -3);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004803
Christopher Fauleta2097962019-07-15 16:25:33 +02004804 /* Stores the http version. */
4805 lua_pushstring(L, "version");
4806 lua_pushlstring(L, HTX_SL_REQ_VPTR(sl), HTX_SL_REQ_VLEN(sl));
4807 lua_settable(L, -3);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004808
Christopher Fauleta2097962019-07-15 16:25:33 +02004809 /* creates an array of headers. hlua_http_get_headers() crates and push
4810 * the array on the top of the stack.
4811 */
4812 lua_pushstring(L, "headers");
4813 htxn.s = s;
4814 htxn.p = px;
4815 htxn.dir = SMP_OPT_DIR_REQ;
Christopher Faulet9d1332b2020-02-24 16:46:16 +01004816 if (!hlua_http_get_headers(L, &htxn.s->txn->req))
Christopher Fauleta2097962019-07-15 16:25:33 +02004817 return 0;
4818 lua_settable(L, -3);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004819
Amaury Denoyellec453f952021-07-06 11:40:12 +02004820 parser = http_uri_parser_init(htx_sl_req_uri(sl));
4821 path = http_parse_path(&parser);
Tim Duesterhused526372020-03-05 17:56:33 +01004822 if (isttest(path)) {
Christopher Fauleta2097962019-07-15 16:25:33 +02004823 char *p, *q, *end;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004824
Christopher Fauleta2097962019-07-15 16:25:33 +02004825 p = path.ptr;
Tim Duesterhus4c8f75f2021-11-06 15:14:44 +01004826 end = istend(path);
Christopher Fauleta2097962019-07-15 16:25:33 +02004827 q = p;
4828 while (q < end && *q != '?')
4829 q++;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004830
Thierry FOURNIER7d388632017-02-22 02:06:16 +01004831 /* Stores the request path. */
Christopher Fauleta2097962019-07-15 16:25:33 +02004832 lua_pushstring(L, "path");
4833 lua_pushlstring(L, p, q - p);
Thierry FOURNIER7d388632017-02-22 02:06:16 +01004834 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01004835
Christopher Fauleta2097962019-07-15 16:25:33 +02004836 /* Stores the query string. */
4837 lua_pushstring(L, "qs");
4838 if (*q == '?')
4839 q++;
4840 lua_pushlstring(L, q, end - q);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004841 lua_settable(L, -3);
Christopher Fauleta2097962019-07-15 16:25:33 +02004842 }
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004843
Christopher Fauleta2097962019-07-15 16:25:33 +02004844 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
4845 struct htx_blk *blk = htx_get_blk(htx, pos);
4846 enum htx_blk_type type = htx_get_blk_type(blk);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004847
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01004848 if (type == HTX_BLK_TLR || type == HTX_BLK_EOT)
Christopher Fauleta2097962019-07-15 16:25:33 +02004849 break;
4850 if (type == HTX_BLK_DATA)
4851 len += htx_get_blksz(blk);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004852 }
Christopher Fauleta2097962019-07-15 16:25:33 +02004853 if (htx->extra != ULLONG_MAX)
4854 len += htx->extra;
4855
4856 /* Stores the request path. */
4857 lua_pushstring(L, "length");
4858 lua_pushinteger(L, len);
4859 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01004860
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004861 /* Create an empty array of HTTP request headers. */
4862 lua_pushstring(L, "response");
4863 lua_newtable(L);
4864 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01004865
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004866 /* Pop a class stream metatable and affect it to the table. */
4867 lua_rawgeti(L, LUA_REGISTRYINDEX, class_applet_http_ref);
4868 lua_setmetatable(L, -2);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004869
4870 return 1;
4871}
4872
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004873__LJMP static int hlua_applet_http_set_var(lua_State *L)
4874{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004875 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004876 struct stream *s;
4877 const char *name;
4878 size_t len;
4879 struct sample smp;
4880
Tim Duesterhus4e172c92020-05-19 13:49:42 +02004881 if (lua_gettop(L) < 3 || lua_gettop(L) > 4)
4882 WILL_LJMP(luaL_error(L, "'set_var' needs between 3 and 4 arguments"));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004883
4884 /* It is useles to retrieve the stream, but this function
4885 * runs only in a stream context.
4886 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004887 luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004888 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02004889 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004890
4891 /* Converts the third argument in a sample. */
Amaury Denoyellebc0af6a2020-10-29 17:21:20 +01004892 memset(&smp, 0, sizeof(smp));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004893 hlua_lua2smp(L, 3, &smp);
4894
4895 /* Store the sample in a variable. */
4896 smp_set_owner(&smp, s->be, s->sess, s, 0);
Tim Duesterhus4e172c92020-05-19 13:49:42 +02004897
4898 if (lua_gettop(L) == 4 && lua_toboolean(L, 4))
4899 lua_pushboolean(L, vars_set_by_name_ifexist(name, len, &smp) != 0);
4900 else
4901 lua_pushboolean(L, vars_set_by_name(name, len, &smp) != 0);
4902
Tim Duesterhus84ebc132020-05-19 13:49:41 +02004903 return 1;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004904}
4905
4906__LJMP static int hlua_applet_http_unset_var(lua_State *L)
4907{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004908 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004909 struct stream *s;
4910 const char *name;
4911 size_t len;
4912 struct sample smp;
4913
4914 MAY_LJMP(check_args(L, 2, "unset_var"));
4915
4916 /* It is useles to retrieve the stream, but this function
4917 * runs only in a stream context.
4918 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004919 luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004920 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02004921 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004922
4923 /* Unset the variable. */
4924 smp_set_owner(&smp, s->be, s->sess, s, 0);
Tim Duesterhus84ebc132020-05-19 13:49:41 +02004925 lua_pushboolean(L, vars_unset_by_name_ifexist(name, len, &smp) != 0);
4926 return 1;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004927}
4928
4929__LJMP static int hlua_applet_http_get_var(lua_State *L)
4930{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004931 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004932 struct stream *s;
4933 const char *name;
4934 size_t len;
4935 struct sample smp;
4936
4937 MAY_LJMP(check_args(L, 2, "get_var"));
4938
4939 /* It is useles to retrieve the stream, but this function
4940 * runs only in a stream context.
4941 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004942 luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004943 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02004944 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004945
4946 smp_set_owner(&smp, s->be, s->sess, s, 0);
Willy Tarreaue352b9d2021-09-03 11:52:38 +02004947 if (!vars_get_by_name(name, len, &smp, NULL)) {
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004948 lua_pushnil(L);
4949 return 1;
4950 }
4951
4952 return hlua_smp2lua(L, &smp);
4953}
4954
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004955__LJMP static int hlua_applet_http_set_priv(lua_State *L)
4956{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004957 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4958 struct stream *s = luactx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01004959 struct hlua *hlua;
4960
4961 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01004962 if (!s->hlua)
4963 return 0;
4964 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004965
4966 MAY_LJMP(check_args(L, 2, "set_priv"));
4967
4968 /* Remove previous value. */
Thierry FOURNIERe068b602017-04-26 13:27:05 +02004969 luaL_unref(L, LUA_REGISTRYINDEX, hlua->Mref);
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004970
4971 /* Get and store new value. */
4972 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
4973 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
4974
4975 return 0;
4976}
4977
4978__LJMP static int hlua_applet_http_get_priv(lua_State *L)
4979{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004980 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4981 struct stream *s = luactx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01004982 struct hlua *hlua;
4983
4984 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01004985 if (!s->hlua) {
4986 lua_pushnil(L);
4987 return 1;
4988 }
4989 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004990
4991 /* Push configuration index in the stack. */
4992 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
4993
4994 return 1;
4995}
4996
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004997/* If expected data not yet available, it returns a yield. This function
4998 * consumes the data in the buffer. It returns a string containing the
4999 * data. This string can be empty.
5000 */
Christopher Fauleta2097962019-07-15 16:25:33 +02005001__LJMP static int hlua_applet_http_getline_yield(lua_State *L, int status, lua_KContext ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005002{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005003 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Willy Tarreauc12b3212022-05-27 11:08:15 +02005004 struct stconn *sc = appctx_sc(luactx->appctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02005005 struct channel *req = sc_oc(sc);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005006 struct htx *htx;
5007 struct htx_blk *blk;
5008 size_t count;
5009 int stop = 0;
5010
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005011 htx = htx_from_buf(&req->buf);
5012 count = co_data(req);
Christopher Fauleta3f15502019-05-13 15:27:23 +02005013 blk = htx_get_first_blk(htx);
Christopher Fauletcc26b132018-12-18 21:20:57 +01005014
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005015 while (count && !stop && blk) {
5016 enum htx_blk_type type = htx_get_blk_type(blk);
5017 uint32_t sz = htx_get_blksz(blk);
5018 struct ist v;
5019 uint32_t vlen;
5020 char *nl;
5021
5022 vlen = sz;
5023 if (vlen > count) {
5024 if (type != HTX_BLK_DATA)
5025 break;
5026 vlen = count;
5027 }
5028
5029 switch (type) {
5030 case HTX_BLK_UNUSED:
5031 break;
5032
5033 case HTX_BLK_DATA:
5034 v = htx_get_blk_value(htx, blk);
5035 v.len = vlen;
5036 nl = istchr(v, '\n');
5037 if (nl != NULL) {
5038 stop = 1;
5039 vlen = nl - v.ptr + 1;
5040 }
Willy Tarreau7e702d12021-04-28 17:59:21 +02005041 luaL_addlstring(&luactx->b, v.ptr, vlen);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005042 break;
5043
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005044 case HTX_BLK_TLR:
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01005045 case HTX_BLK_EOT:
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005046 stop = 1;
5047 break;
5048
5049 default:
5050 break;
5051 }
5052
Willy Tarreau84240042022-02-28 16:51:23 +01005053 c_rew(req, vlen);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005054 count -= vlen;
5055 if (sz == vlen)
5056 blk = htx_remove_blk(htx, blk);
5057 else {
5058 htx_cut_data_blk(htx, blk, vlen);
5059 break;
5060 }
5061 }
5062
Christopher Fauleteccb31c2021-04-02 14:24:56 +02005063 /* The message was fully consumed and no more data are expected
5064 * (EOM flag set).
5065 */
Christopher Faulet4a209722022-08-29 15:37:16 +02005066 if (htx_is_empty(htx) && (req->flags & CF_EOI))
Christopher Fauleteccb31c2021-04-02 14:24:56 +02005067 stop = 1;
5068
Christopher Faulet0ae79d02019-02-27 21:36:59 +01005069 htx_to_buf(htx, &req->buf);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005070 if (!stop) {
Willy Tarreau90e8b452022-05-25 18:21:43 +02005071 applet_need_more_data(luactx->appctx);
Christopher Fauleta2097962019-07-15 16:25:33 +02005072 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_getline_yield, TICK_ETERNITY, 0));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005073 }
5074
5075 /* return the result. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005076 luaL_pushresult(&luactx->b);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005077 return 1;
5078}
5079
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005080
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08005081/* Check arguments for the function "hlua_channel_get_yield". */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005082__LJMP static int hlua_applet_http_getline(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005083{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005084 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005085
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005086 /* Initialise the string catenation. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005087 luaL_buffinit(L, &luactx->b);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005088
Christopher Fauleta2097962019-07-15 16:25:33 +02005089 return MAY_LJMP(hlua_applet_http_getline_yield(L, 0, 0));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005090}
5091
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005092/* If expected data not yet available, it returns a yield. This function
5093 * consumes the data in the buffer. It returns a string containing the
5094 * data. This string can be empty.
5095 */
Christopher Fauleta2097962019-07-15 16:25:33 +02005096__LJMP static int hlua_applet_http_recv_yield(lua_State *L, int status, lua_KContext ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005097{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005098 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Willy Tarreauc12b3212022-05-27 11:08:15 +02005099 struct stconn *sc = appctx_sc(luactx->appctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02005100 struct channel *req = sc_oc(sc);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005101 struct htx *htx;
5102 struct htx_blk *blk;
5103 size_t count;
5104 int len;
5105
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005106 htx = htx_from_buf(&req->buf);
5107 len = MAY_LJMP(luaL_checkinteger(L, 2));
5108 count = co_data(req);
Christopher Faulet29f17582019-05-23 11:03:26 +02005109 blk = htx_get_head_blk(htx);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005110 while (count && len && blk) {
5111 enum htx_blk_type type = htx_get_blk_type(blk);
5112 uint32_t sz = htx_get_blksz(blk);
5113 struct ist v;
5114 uint32_t vlen;
5115
5116 vlen = sz;
5117 if (len > 0 && vlen > len)
5118 vlen = len;
5119 if (vlen > count) {
5120 if (type != HTX_BLK_DATA)
5121 break;
5122 vlen = count;
5123 }
5124
5125 switch (type) {
5126 case HTX_BLK_UNUSED:
5127 break;
5128
5129 case HTX_BLK_DATA:
5130 v = htx_get_blk_value(htx, blk);
Willy Tarreau7e702d12021-04-28 17:59:21 +02005131 luaL_addlstring(&luactx->b, v.ptr, vlen);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005132 break;
5133
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005134 case HTX_BLK_TLR:
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01005135 case HTX_BLK_EOT:
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005136 len = 0;
5137 break;
5138
5139 default:
5140 break;
5141 }
5142
Willy Tarreau84240042022-02-28 16:51:23 +01005143 c_rew(req, vlen);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005144 count -= vlen;
5145 if (len > 0)
5146 len -= vlen;
5147 if (sz == vlen)
5148 blk = htx_remove_blk(htx, blk);
5149 else {
5150 htx_cut_data_blk(htx, blk, vlen);
5151 break;
5152 }
5153 }
5154
Christopher Fauleteccb31c2021-04-02 14:24:56 +02005155 /* The message was fully consumed and no more data are expected
5156 * (EOM flag set).
5157 */
Christopher Faulet4a209722022-08-29 15:37:16 +02005158 if (htx_is_empty(htx) && (req->flags & CF_EOI))
Christopher Fauleteccb31c2021-04-02 14:24:56 +02005159 len = 0;
5160
Christopher Faulet0ae79d02019-02-27 21:36:59 +01005161 htx_to_buf(htx, &req->buf);
5162
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005163 /* If we are no other data available, yield waiting for new data. */
5164 if (len) {
5165 if (len > 0) {
5166 lua_pushinteger(L, len);
5167 lua_replace(L, 2);
5168 }
Willy Tarreau90e8b452022-05-25 18:21:43 +02005169 applet_need_more_data(luactx->appctx);
Willy Tarreau9635e032018-10-16 17:52:55 +02005170 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005171 }
5172
5173 /* return the result. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005174 luaL_pushresult(&luactx->b);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005175 return 1;
5176}
5177
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08005178/* Check arguments for the function "hlua_channel_get_yield". */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005179__LJMP static int hlua_applet_http_recv(lua_State *L)
5180{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005181 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005182 int len = -1;
5183
5184 /* Check arguments. */
5185 if (lua_gettop(L) > 2)
5186 WILL_LJMP(luaL_error(L, "The 'recv' function requires between 1 and 2 arguments."));
5187 if (lua_gettop(L) >= 2) {
5188 len = MAY_LJMP(luaL_checkinteger(L, 2));
5189 lua_pop(L, 1);
5190 }
5191
Christopher Fauleta2097962019-07-15 16:25:33 +02005192 lua_pushinteger(L, len);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005193
Christopher Fauleta2097962019-07-15 16:25:33 +02005194 /* Initialise the string catenation. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005195 luaL_buffinit(L, &luactx->b);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005196
Christopher Fauleta2097962019-07-15 16:25:33 +02005197 return MAY_LJMP(hlua_applet_http_recv_yield(L, 0, 0));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005198}
5199
5200/* Append data in the output side of the buffer. This data is immediately
5201 * sent. The function returns the amount of data written. If the buffer
5202 * cannot contain the data, the function yields. The function returns -1
5203 * if the channel is closed.
5204 */
Christopher Fauleta2097962019-07-15 16:25:33 +02005205__LJMP static int hlua_applet_http_send_yield(lua_State *L, int status, lua_KContext ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005206{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005207 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Willy Tarreauc12b3212022-05-27 11:08:15 +02005208 struct stconn *sc = appctx_sc(luactx->appctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02005209 struct channel *res = sc_ic(sc);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005210 struct htx *htx = htx_from_buf(&res->buf);
5211 const char *data;
5212 size_t len;
5213 int l = MAY_LJMP(luaL_checkinteger(L, 3));
5214 int max;
5215
Christopher Faulet9060fc02019-07-03 11:39:30 +02005216 max = htx_get_max_blksz(htx, channel_htx_recv_max(res, htx));
Christopher Faulet4b0e9b22019-01-09 12:16:58 +01005217 if (!max)
5218 goto snd_yield;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005219
5220 data = MAY_LJMP(luaL_checklstring(L, 2, &len));
5221
5222 /* Get the max amount of data which can write as input in the channel. */
5223 if (max > (len - l))
5224 max = len - l;
5225
5226 /* Copy data. */
Willy Tarreau0a7ef022019-05-28 10:30:11 +02005227 max = htx_add_data(htx, ist2(data + l, max));
Christopher Fauletf6cce3f2019-02-27 21:20:09 +01005228 channel_add_input(res, max);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005229
5230 /* update counters. */
5231 l += max;
5232 lua_pop(L, 1);
5233 lua_pushinteger(L, l);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005234
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005235 /* If some data is not send, declares the situation to the
5236 * applet, and returns a yield.
5237 */
5238 if (l < len) {
Christopher Faulet4b0e9b22019-01-09 12:16:58 +01005239 snd_yield:
Christopher Faulet0ae79d02019-02-27 21:36:59 +01005240 htx_to_buf(htx, &res->buf);
Willy Tarreau3e7be362022-05-27 10:35:27 +02005241 sc_need_room(sc);
Willy Tarreau9635e032018-10-16 17:52:55 +02005242 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005243 }
5244
Christopher Fauleta2097962019-07-15 16:25:33 +02005245 htx_to_buf(htx, &res->buf);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005246 return 1;
5247}
5248
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05005249/* Just a wrapper of "hlua_applet_send_yield". This wrapper permits
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005250 * yield the LUA process, and resume it without checking the
5251 * input arguments.
5252 */
5253__LJMP static int hlua_applet_http_send(lua_State *L)
5254{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005255 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005256 struct hlua_http_ctx *http_ctx = luactx->appctx->svcctx;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005257
5258 /* We want to send some data. Headers must be sent. */
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005259 if (!(http_ctx->flags & APPLET_HDR_SENT)) {
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005260 hlua_pusherror(L, "Lua: 'send' you must call start_response() before sending data.");
5261 WILL_LJMP(lua_error(L));
5262 }
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005263
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05005264 /* This integer is used for followinf the amount of data sent. */
Christopher Fauleta2097962019-07-15 16:25:33 +02005265 lua_pushinteger(L, 0);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005266
Christopher Fauleta2097962019-07-15 16:25:33 +02005267 return MAY_LJMP(hlua_applet_http_send_yield(L, 0, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005268}
5269
5270__LJMP static int hlua_applet_http_addheader(lua_State *L)
5271{
5272 const char *name;
5273 int ret;
5274
5275 MAY_LJMP(hlua_checkapplet_http(L, 1));
5276 name = MAY_LJMP(luaL_checkstring(L, 2));
5277 MAY_LJMP(luaL_checkstring(L, 3));
5278
5279 /* Push in the stack the "response" entry. */
5280 ret = lua_getfield(L, 1, "response");
5281 if (ret != LUA_TTABLE) {
5282 hlua_pusherror(L, "Lua: 'add_header' internal error: AppletHTTP['response'] "
5283 "is expected as an array. %s found", lua_typename(L, ret));
5284 WILL_LJMP(lua_error(L));
5285 }
5286
5287 /* check if the header is already registered if it is not
5288 * the case, register it.
5289 */
5290 ret = lua_getfield(L, -1, name);
5291 if (ret == LUA_TNIL) {
5292
5293 /* Entry not found. */
5294 lua_pop(L, 1); /* remove the nil. The "response" table is the top of the stack. */
5295
5296 /* Insert the new header name in the array in the top of the stack.
5297 * It left the new array in the top of the stack.
5298 */
5299 lua_newtable(L);
5300 lua_pushvalue(L, 2);
5301 lua_pushvalue(L, -2);
5302 lua_settable(L, -4);
5303
5304 } else if (ret != LUA_TTABLE) {
5305
5306 /* corruption error. */
5307 hlua_pusherror(L, "Lua: 'add_header' internal error: AppletHTTP['response']['%s'] "
5308 "is expected as an array. %s found", name, lua_typename(L, ret));
5309 WILL_LJMP(lua_error(L));
5310 }
5311
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -07005312 /* Now the top of thestack is an array of values. We push
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005313 * the header value as new entry.
5314 */
5315 lua_pushvalue(L, 3);
5316 ret = lua_rawlen(L, -2);
5317 lua_rawseti(L, -2, ret + 1);
5318 lua_pushboolean(L, 1);
5319 return 1;
5320}
5321
5322__LJMP static int hlua_applet_http_status(lua_State *L)
5323{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005324 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005325 int status = MAY_LJMP(luaL_checkinteger(L, 2));
Robin H. Johnson52f5db22017-01-01 13:10:52 -08005326 const char *reason = MAY_LJMP(luaL_optlstring(L, 3, NULL, NULL));
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005327 struct hlua_http_ctx *http_ctx = luactx->appctx->svcctx;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005328
5329 if (status < 100 || status > 599) {
5330 lua_pushboolean(L, 0);
5331 return 1;
5332 }
5333
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005334 http_ctx->status = status;
5335 http_ctx->reason = reason;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005336 lua_pushboolean(L, 1);
5337 return 1;
5338}
5339
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005340
Christopher Fauleta2097962019-07-15 16:25:33 +02005341__LJMP static int hlua_applet_http_send_response(lua_State *L)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005342{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005343 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005344 struct hlua_http_ctx *http_ctx = luactx->appctx->svcctx;
Willy Tarreauc12b3212022-05-27 11:08:15 +02005345 struct stconn *sc = appctx_sc(luactx->appctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02005346 struct channel *res = sc_ic(sc);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005347 struct htx *htx;
5348 struct htx_sl *sl;
5349 struct h1m h1m;
5350 const char *status, *reason;
5351 const char *name, *value;
5352 size_t nlen, vlen;
5353 unsigned int flags;
5354
5355 /* Send the message at once. */
5356 htx = htx_from_buf(&res->buf);
5357 h1m_init_res(&h1m);
5358
5359 /* Use the same http version than the request. */
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005360 status = ultoa_r(http_ctx->status, trash.area, trash.size);
5361 reason = http_ctx->reason;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005362 if (reason == NULL)
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005363 reason = http_get_reason(http_ctx->status);
5364 if (http_ctx->flags & APPLET_HTTP11) {
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005365 flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11);
5366 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.1"), ist(status), ist(reason));
5367 }
5368 else {
5369 flags = HTX_SL_F_IS_RESP;
5370 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.0"), ist(status), ist(reason));
5371 }
5372 if (!sl) {
5373 hlua_pusherror(L, "Lua applet http '%s': Failed to create response.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005374 luactx->appctx->rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005375 WILL_LJMP(lua_error(L));
5376 }
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005377 sl->info.res.status = http_ctx->status;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005378
5379 /* Get the array associated to the field "response" in the object AppletHTTP. */
Aurelien DARRAGONcd341d52022-09-29 12:00:04 +02005380 /* FIXME: according to Lua doc, 0 is considered to be invalid index? */
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005381 lua_pushvalue(L, 0);
5382 if (lua_getfield(L, 1, "response") != LUA_TTABLE) {
5383 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response'] missing.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005384 luactx->appctx->rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005385 WILL_LJMP(lua_error(L));
5386 }
5387
5388 /* Browse the list of headers. */
5389 lua_pushnil(L);
5390 while(lua_next(L, -2) != 0) {
5391 /* We expect a string as -2. */
5392 if (lua_type(L, -2) != LUA_TSTRING) {
5393 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response'][] element must be a string. got %s.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005394 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005395 lua_typename(L, lua_type(L, -2)));
5396 WILL_LJMP(lua_error(L));
5397 }
5398 name = lua_tolstring(L, -2, &nlen);
5399
5400 /* We expect an array as -1. */
5401 if (lua_type(L, -1) != LUA_TTABLE) {
5402 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 +02005403 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005404 name,
5405 lua_typename(L, lua_type(L, -1)));
5406 WILL_LJMP(lua_error(L));
5407 }
5408
5409 /* Browse the table who is on the top of the stack. */
5410 lua_pushnil(L);
5411 while(lua_next(L, -2) != 0) {
5412 int id;
5413
5414 /* We expect a number as -2. */
5415 if (lua_type(L, -2) != LUA_TNUMBER) {
5416 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 +02005417 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005418 name,
5419 lua_typename(L, lua_type(L, -2)));
5420 WILL_LJMP(lua_error(L));
5421 }
5422 id = lua_tointeger(L, -2);
5423
5424 /* We expect a string as -2. */
5425 if (lua_type(L, -1) != LUA_TSTRING) {
5426 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 +02005427 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005428 name, id,
5429 lua_typename(L, lua_type(L, -1)));
5430 WILL_LJMP(lua_error(L));
5431 }
5432 value = lua_tolstring(L, -1, &vlen);
5433
5434 /* Simple Protocol checks. */
Christopher Faulet545fbba2021-09-28 09:36:25 +02005435 if (isteqi(ist2(name, nlen), ist("transfer-encoding"))) {
5436 int ret;
5437
5438 ret = h1_parse_xfer_enc_header(&h1m, ist2(value, vlen));
5439 if (ret < 0) {
5440 hlua_pusherror(L, "Lua applet http '%s': Invalid '%s' header.\n",
5441 luactx->appctx->rule->arg.hlua_rule->fcn->name,
5442 name);
5443 WILL_LJMP(lua_error(L));
5444 }
5445 else if (ret == 0)
5446 goto next; /* Skip it */
5447 }
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005448 else if (isteqi(ist2(name, nlen), ist("content-length"))) {
5449 struct ist v = ist2(value, vlen);
5450 int ret;
5451
5452 ret = h1_parse_cont_len_header(&h1m, &v);
5453 if (ret < 0) {
5454 hlua_pusherror(L, "Lua applet http '%s': Invalid '%s' header.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005455 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005456 name);
5457 WILL_LJMP(lua_error(L));
5458 }
5459 else if (ret == 0)
5460 goto next; /* Skip it */
5461 }
5462
5463 /* Add a new header */
5464 if (!htx_add_header(htx, ist2(name, nlen), ist2(value, vlen))) {
5465 hlua_pusherror(L, "Lua applet http '%s': Failed to add header '%s' in the response.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005466 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005467 name);
5468 WILL_LJMP(lua_error(L));
5469 }
5470 next:
5471 /* Remove the array from the stack, and get next element with a remaining string. */
5472 lua_pop(L, 1);
5473 }
5474
5475 /* Remove the array from the stack, and get next element with a remaining string. */
5476 lua_pop(L, 1);
5477 }
5478
5479 if (h1m.flags & H1_MF_CHNK)
5480 h1m.flags &= ~H1_MF_CLEN;
5481 if (h1m.flags & (H1_MF_CLEN|H1_MF_CHNK))
5482 h1m.flags |= H1_MF_XFER_LEN;
5483
5484 /* Uset HTX start-line flags */
5485 if (h1m.flags & H1_MF_XFER_ENC)
5486 flags |= HTX_SL_F_XFER_ENC;
5487 if (h1m.flags & H1_MF_XFER_LEN) {
5488 flags |= HTX_SL_F_XFER_LEN;
5489 if (h1m.flags & H1_MF_CHNK)
5490 flags |= HTX_SL_F_CHNK;
5491 else if (h1m.flags & H1_MF_CLEN)
5492 flags |= HTX_SL_F_CLEN;
5493 if (h1m.body_len == 0)
5494 flags |= HTX_SL_F_BODYLESS;
5495 }
5496 sl->flags |= flags;
5497
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -07005498 /* If we don't have a content-length set, and the HTTP version is 1.1
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005499 * and the status code implies the presence of a message body, we must
5500 * announce a transfer encoding chunked. This is required by haproxy
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05005501 * for the keepalive compliance. If the applet announces a transfer-encoding
5502 * chunked itself, don't do anything.
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005503 */
5504 if ((flags & (HTX_SL_F_VER_11|HTX_SL_F_XFER_LEN)) == HTX_SL_F_VER_11 &&
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005505 http_ctx->status >= 200 && http_ctx->status != 204 && http_ctx->status != 304) {
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005506 /* Add a new header */
5507 sl->flags |= (HTX_SL_F_XFER_ENC|H1_MF_CHNK|H1_MF_XFER_LEN);
5508 if (!htx_add_header(htx, ist("transfer-encoding"), ist("chunked"))) {
5509 hlua_pusherror(L, "Lua applet http '%s': Failed to add header 'transfer-encoding' in the response.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005510 luactx->appctx->rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005511 WILL_LJMP(lua_error(L));
5512 }
5513 }
5514
5515 /* Finalize headers. */
5516 if (!htx_add_endof(htx, HTX_BLK_EOH)) {
5517 hlua_pusherror(L, "Lua applet http '%s': Failed create the response.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005518 luactx->appctx->rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005519 WILL_LJMP(lua_error(L));
5520 }
5521
5522 if (htx_used_space(htx) > b_size(&res->buf) - global.tune.maxrewrite) {
5523 b_reset(&res->buf);
5524 hlua_pusherror(L, "Lua: 'start_response': response header block too big");
5525 WILL_LJMP(lua_error(L));
5526 }
5527
5528 htx_to_buf(htx, &res->buf);
Christopher Fauletf6cce3f2019-02-27 21:20:09 +01005529 channel_add_input(res, htx->data);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005530
5531 /* Headers sent, set the flag. */
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005532 http_ctx->flags |= APPLET_HDR_SENT;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005533 return 0;
5534
5535}
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005536/* We will build the status line and the headers of the HTTP response.
5537 * We will try send at once if its not possible, we give back the hand
5538 * waiting for more room.
5539 */
Christopher Fauleta2097962019-07-15 16:25:33 +02005540__LJMP static int hlua_applet_http_start_response_yield(lua_State *L, int status, lua_KContext ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005541{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005542 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Willy Tarreauc12b3212022-05-27 11:08:15 +02005543 struct stconn *sc = appctx_sc(luactx->appctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02005544 struct channel *res = sc_ic(sc);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005545
5546 if (co_data(res)) {
Willy Tarreau3e7be362022-05-27 10:35:27 +02005547 sc_need_room(sc);
Christopher Fauleta2097962019-07-15 16:25:33 +02005548 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_start_response_yield, TICK_ETERNITY, 0));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005549 }
Christopher Fauleta2097962019-07-15 16:25:33 +02005550 return MAY_LJMP(hlua_applet_http_send_response(L));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005551}
5552
5553
Christopher Fauleta2097962019-07-15 16:25:33 +02005554__LJMP static int hlua_applet_http_start_response(lua_State *L)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005555{
Christopher Fauleta2097962019-07-15 16:25:33 +02005556 return MAY_LJMP(hlua_applet_http_start_response_yield(L, 0, 0));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005557}
5558
Christopher Fauleta2097962019-07-15 16:25:33 +02005559/*
5560 *
5561 *
5562 * Class HTTP
5563 *
5564 *
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005565 */
Christopher Fauleta2097962019-07-15 16:25:33 +02005566
5567/* Returns a struct hlua_txn if the stack entry "ud" is
5568 * a class stream, otherwise it throws an error.
5569 */
5570__LJMP static struct hlua_txn *hlua_checkhttp(lua_State *L, int ud)
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005571{
Christopher Fauleta2097962019-07-15 16:25:33 +02005572 return MAY_LJMP(hlua_checkudata(L, ud, class_http_ref));
5573}
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005574
Christopher Fauleta2097962019-07-15 16:25:33 +02005575/* This function creates and push in the stack a HTTP object
5576 * according with a current TXN.
5577 */
5578static int hlua_http_new(lua_State *L, struct hlua_txn *txn)
5579{
5580 struct hlua_txn *htxn;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005581
Christopher Fauleta2097962019-07-15 16:25:33 +02005582 /* Check stack size. */
5583 if (!lua_checkstack(L, 3))
5584 return 0;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005585
Christopher Fauleta2097962019-07-15 16:25:33 +02005586 /* Create the object: obj[0] = userdata.
5587 * Note that the base of the Converters object is the
5588 * same than the TXN object.
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005589 */
Christopher Fauleta2097962019-07-15 16:25:33 +02005590 lua_newtable(L);
5591 htxn = lua_newuserdata(L, sizeof(*htxn));
5592 lua_rawseti(L, -2, 0);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005593
5594 htxn->s = txn->s;
5595 htxn->p = txn->p;
Christopher Faulet256b69a2019-05-23 11:14:21 +02005596 htxn->dir = txn->dir;
5597 htxn->flags = txn->flags;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005598
5599 /* Pop a class stream metatable and affect it to the table. */
5600 lua_rawgeti(L, LUA_REGISTRYINDEX, class_http_ref);
5601 lua_setmetatable(L, -2);
5602
5603 return 1;
5604}
5605
Christopher Fauletdf97ac42020-02-26 16:57:19 +01005606/* This function creates and returns an array containing the status-line
5607 * elements. This function does not fails.
5608 */
5609__LJMP static int hlua_http_get_stline(lua_State *L, struct htx_sl *sl)
5610{
5611 /* Create the table. */
5612 lua_newtable(L);
5613
5614 if (sl->flags & HTX_SL_F_IS_RESP) {
5615 lua_pushstring(L, "version");
5616 lua_pushlstring(L, HTX_SL_RES_VPTR(sl), HTX_SL_RES_VLEN(sl));
5617 lua_settable(L, -3);
5618 lua_pushstring(L, "code");
5619 lua_pushlstring(L, HTX_SL_RES_CPTR(sl), HTX_SL_RES_CLEN(sl));
5620 lua_settable(L, -3);
5621 lua_pushstring(L, "reason");
5622 lua_pushlstring(L, HTX_SL_RES_RPTR(sl), HTX_SL_RES_RLEN(sl));
5623 lua_settable(L, -3);
5624 }
5625 else {
5626 lua_pushstring(L, "method");
5627 lua_pushlstring(L, HTX_SL_REQ_MPTR(sl), HTX_SL_REQ_MLEN(sl));
5628 lua_settable(L, -3);
5629 lua_pushstring(L, "uri");
5630 lua_pushlstring(L, HTX_SL_REQ_UPTR(sl), HTX_SL_REQ_ULEN(sl));
5631 lua_settable(L, -3);
5632 lua_pushstring(L, "version");
5633 lua_pushlstring(L, HTX_SL_REQ_VPTR(sl), HTX_SL_REQ_VLEN(sl));
5634 lua_settable(L, -3);
5635 }
5636 return 1;
5637}
5638
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005639/* This function creates ans returns an array of HTTP headers.
5640 * This function does not fails. It is used as wrapper with the
5641 * 2 following functions.
5642 */
Christopher Faulet9d1332b2020-02-24 16:46:16 +01005643__LJMP static int hlua_http_get_headers(lua_State *L, struct http_msg *msg)
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005644{
Christopher Fauleta2097962019-07-15 16:25:33 +02005645 struct htx *htx;
5646 int32_t pos;
5647
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005648 /* Create the table. */
5649 lua_newtable(L);
5650
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005651
Christopher Fauleta2097962019-07-15 16:25:33 +02005652 htx = htxbuf(&msg->chn->buf);
5653 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
5654 struct htx_blk *blk = htx_get_blk(htx, pos);
5655 enum htx_blk_type type = htx_get_blk_type(blk);
5656 struct ist n, v;
5657 int len;
Christopher Faulet724a12c2018-12-13 22:12:15 +01005658
Christopher Fauleta2097962019-07-15 16:25:33 +02005659 if (type == HTX_BLK_HDR) {
5660 n = htx_get_blk_name(htx,blk);
5661 v = htx_get_blk_value(htx, blk);
Christopher Faulet724a12c2018-12-13 22:12:15 +01005662 }
Christopher Fauleta2097962019-07-15 16:25:33 +02005663 else if (type == HTX_BLK_EOH)
5664 break;
5665 else
5666 continue;
Christopher Faulet724a12c2018-12-13 22:12:15 +01005667
Christopher Fauleta2097962019-07-15 16:25:33 +02005668 /* Check for existing entry:
5669 * assume that the table is on the top of the stack, and
5670 * push the key in the stack, the function lua_gettable()
5671 * perform the lookup.
5672 */
5673 lua_pushlstring(L, n.ptr, n.len);
5674 lua_gettable(L, -2);
Christopher Faulet724a12c2018-12-13 22:12:15 +01005675
Christopher Fauleta2097962019-07-15 16:25:33 +02005676 switch (lua_type(L, -1)) {
5677 case LUA_TNIL:
5678 /* Table not found, create it. */
5679 lua_pop(L, 1); /* remove the nil value. */
5680 lua_pushlstring(L, n.ptr, n.len); /* push the header name as key. */
5681 lua_newtable(L); /* create and push empty table. */
5682 lua_pushlstring(L, v.ptr, v.len); /* push header value. */
5683 lua_rawseti(L, -2, 0); /* index header value (pop it). */
5684 lua_rawset(L, -3); /* index new table with header name (pop the values). */
Christopher Faulet724a12c2018-12-13 22:12:15 +01005685 break;
Christopher Faulet724a12c2018-12-13 22:12:15 +01005686
Christopher Fauleta2097962019-07-15 16:25:33 +02005687 case LUA_TTABLE:
5688 /* Entry found: push the value in the table. */
5689 len = lua_rawlen(L, -1);
5690 lua_pushlstring(L, v.ptr, v.len); /* push header value. */
5691 lua_rawseti(L, -2, len+1); /* index header value (pop it). */
5692 lua_pop(L, 1); /* remove the table (it is stored in the main table). */
5693 break;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005694
Christopher Fauleta2097962019-07-15 16:25:33 +02005695 default:
5696 /* Other cases are errors. */
5697 hlua_pusherror(L, "internal error during the parsing of headers.");
5698 WILL_LJMP(lua_error(L));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005699 }
5700 }
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005701 return 1;
5702}
5703
5704__LJMP static int hlua_http_req_get_headers(lua_State *L)
5705{
5706 struct hlua_txn *htxn;
5707
5708 MAY_LJMP(check_args(L, 1, "req_get_headers"));
5709 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5710
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005711 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005712 WILL_LJMP(lua_error(L));
5713
Christopher Faulet9d1332b2020-02-24 16:46:16 +01005714 return hlua_http_get_headers(L, &htxn->s->txn->req);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005715}
5716
5717__LJMP static int hlua_http_res_get_headers(lua_State *L)
5718{
5719 struct hlua_txn *htxn;
5720
5721 MAY_LJMP(check_args(L, 1, "res_get_headers"));
5722 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5723
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005724 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005725 WILL_LJMP(lua_error(L));
5726
Christopher Faulet9d1332b2020-02-24 16:46:16 +01005727 return hlua_http_get_headers(L, &htxn->s->txn->rsp);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005728}
5729
5730/* This function replace full header, or just a value in
5731 * the request or in the response. It is a wrapper fir the
5732 * 4 following functions.
5733 */
Christopher Fauletd1914aa2020-02-24 16:52:46 +01005734__LJMP static inline int hlua_http_rep_hdr(lua_State *L, struct http_msg *msg, int full)
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005735{
5736 size_t name_len;
5737 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
5738 const char *reg = MAY_LJMP(luaL_checkstring(L, 3));
5739 const char *value = MAY_LJMP(luaL_checkstring(L, 4));
Christopher Fauleta2097962019-07-15 16:25:33 +02005740 struct htx *htx;
Dragan Dosen26743032019-04-30 15:54:36 +02005741 struct my_regex *re;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005742
Dragan Dosen26743032019-04-30 15:54:36 +02005743 if (!(re = regex_comp(reg, 1, 1, NULL)))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005744 WILL_LJMP(luaL_argerror(L, 3, "invalid regex"));
5745
Christopher Fauleta2097962019-07-15 16:25:33 +02005746 htx = htxbuf(&msg->chn->buf);
Christopher Fauletd1914aa2020-02-24 16:52:46 +01005747 http_replace_hdrs(chn_strm(msg->chn), htx, ist2(name, name_len), value, re, full);
Dragan Dosen26743032019-04-30 15:54:36 +02005748 regex_free(re);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005749 return 0;
5750}
5751
5752__LJMP static int hlua_http_req_rep_hdr(lua_State *L)
5753{
5754 struct hlua_txn *htxn;
5755
5756 MAY_LJMP(check_args(L, 4, "req_rep_hdr"));
5757 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5758
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005759 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005760 WILL_LJMP(lua_error(L));
5761
Christopher Fauletd1914aa2020-02-24 16:52:46 +01005762 return MAY_LJMP(hlua_http_rep_hdr(L, &htxn->s->txn->req, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005763}
5764
5765__LJMP static int hlua_http_res_rep_hdr(lua_State *L)
5766{
5767 struct hlua_txn *htxn;
5768
5769 MAY_LJMP(check_args(L, 4, "res_rep_hdr"));
5770 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5771
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005772 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005773 WILL_LJMP(lua_error(L));
5774
Christopher Fauletd1914aa2020-02-24 16:52:46 +01005775 return MAY_LJMP(hlua_http_rep_hdr(L, &htxn->s->txn->rsp, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005776}
5777
5778__LJMP static int hlua_http_req_rep_val(lua_State *L)
5779{
5780 struct hlua_txn *htxn;
5781
5782 MAY_LJMP(check_args(L, 4, "req_rep_hdr"));
5783 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5784
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005785 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005786 WILL_LJMP(lua_error(L));
5787
Christopher Fauletd1914aa2020-02-24 16:52:46 +01005788 return MAY_LJMP(hlua_http_rep_hdr(L, &htxn->s->txn->req, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005789}
5790
5791__LJMP static int hlua_http_res_rep_val(lua_State *L)
5792{
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005793 struct hlua_txn *htxn;
5794
5795 MAY_LJMP(check_args(L, 4, "res_rep_val"));
5796 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5797
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005798 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005799 WILL_LJMP(lua_error(L));
5800
Christopher Fauletd1914aa2020-02-24 16:52:46 +01005801 return MAY_LJMP(hlua_http_rep_hdr(L, &htxn->s->txn->rsp, 0));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005802}
5803
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08005804/* This function deletes all the occurrences of an header.
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005805 * It is a wrapper for the 2 following functions.
5806 */
Christopher Fauletd31c7b32020-02-25 09:37:57 +01005807__LJMP static inline int hlua_http_del_hdr(lua_State *L, struct http_msg *msg)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005808{
5809 size_t len;
5810 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Christopher Fauleta2097962019-07-15 16:25:33 +02005811 struct htx *htx = htxbuf(&msg->chn->buf);
5812 struct http_hdr_ctx ctx;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005813
Christopher Fauleta2097962019-07-15 16:25:33 +02005814 ctx.blk = NULL;
5815 while (http_find_header(htx, ist2(name, len), &ctx, 1))
5816 http_remove_header(htx, &ctx);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005817 return 0;
5818}
5819
5820__LJMP static int hlua_http_req_del_hdr(lua_State *L)
5821{
5822 struct hlua_txn *htxn;
5823
5824 MAY_LJMP(check_args(L, 2, "req_del_hdr"));
5825 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5826
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005827 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005828 WILL_LJMP(lua_error(L));
5829
Christopher Fauletd31c7b32020-02-25 09:37:57 +01005830 return hlua_http_del_hdr(L, &htxn->s->txn->req);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005831}
5832
5833__LJMP static int hlua_http_res_del_hdr(lua_State *L)
5834{
5835 struct hlua_txn *htxn;
5836
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005837 MAY_LJMP(check_args(L, 2, "res_del_hdr"));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005838 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5839
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005840 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005841 WILL_LJMP(lua_error(L));
5842
Christopher Fauletd31c7b32020-02-25 09:37:57 +01005843 return hlua_http_del_hdr(L, &htxn->s->txn->rsp);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005844}
5845
5846/* This function adds an header. It is a wrapper used by
5847 * the 2 following functions.
5848 */
Christopher Fauletd31c7b32020-02-25 09:37:57 +01005849__LJMP static inline int hlua_http_add_hdr(lua_State *L, struct http_msg *msg)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005850{
5851 size_t name_len;
5852 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
5853 size_t value_len;
5854 const char *value = MAY_LJMP(luaL_checklstring(L, 3, &value_len));
Christopher Fauleta2097962019-07-15 16:25:33 +02005855 struct htx *htx = htxbuf(&msg->chn->buf);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005856
Christopher Fauleta2097962019-07-15 16:25:33 +02005857 lua_pushboolean(L, http_add_header(htx, ist2(name, name_len),
5858 ist2(value, value_len)));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005859 return 0;
5860}
5861
Christopher Fauletdf97ac42020-02-26 16:57:19 +01005862__LJMP static int hlua_http_req_add_hdr(lua_State *L)
5863{
5864 struct hlua_txn *htxn;
5865
5866 MAY_LJMP(check_args(L, 3, "req_add_hdr"));
5867 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5868
5869 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
5870 WILL_LJMP(lua_error(L));
5871
5872 return hlua_http_add_hdr(L, &htxn->s->txn->req);
5873}
5874
5875__LJMP static int hlua_http_res_add_hdr(lua_State *L)
5876{
5877 struct hlua_txn *htxn;
5878
5879 MAY_LJMP(check_args(L, 3, "res_add_hdr"));
5880 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5881
5882 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
5883 WILL_LJMP(lua_error(L));
5884
5885 return hlua_http_add_hdr(L, &htxn->s->txn->rsp);
5886}
5887
5888static int hlua_http_req_set_hdr(lua_State *L)
5889{
5890 struct hlua_txn *htxn;
5891
5892 MAY_LJMP(check_args(L, 3, "req_set_hdr"));
5893 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5894
5895 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
5896 WILL_LJMP(lua_error(L));
5897
5898 hlua_http_del_hdr(L, &htxn->s->txn->req);
5899 return hlua_http_add_hdr(L, &htxn->s->txn->req);
5900}
5901
5902static int hlua_http_res_set_hdr(lua_State *L)
5903{
5904 struct hlua_txn *htxn;
5905
5906 MAY_LJMP(check_args(L, 3, "res_set_hdr"));
5907 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5908
5909 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
5910 WILL_LJMP(lua_error(L));
5911
5912 hlua_http_del_hdr(L, &htxn->s->txn->rsp);
5913 return hlua_http_add_hdr(L, &htxn->s->txn->rsp);
5914}
5915
5916/* This function set the method. */
5917static int hlua_http_req_set_meth(lua_State *L)
5918{
5919 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5920 size_t name_len;
5921 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
5922
5923 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
5924 WILL_LJMP(lua_error(L));
5925
5926 lua_pushboolean(L, http_req_replace_stline(0, name, name_len, htxn->p, htxn->s) != -1);
5927 return 1;
5928}
5929
5930/* This function set the method. */
5931static int hlua_http_req_set_path(lua_State *L)
5932{
5933 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5934 size_t name_len;
5935 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
5936
5937 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
5938 WILL_LJMP(lua_error(L));
5939
5940 lua_pushboolean(L, http_req_replace_stline(1, name, name_len, htxn->p, htxn->s) != -1);
5941 return 1;
5942}
5943
5944/* This function set the query-string. */
5945static int hlua_http_req_set_query(lua_State *L)
5946{
5947 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5948 size_t name_len;
5949 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
5950
5951 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
5952 WILL_LJMP(lua_error(L));
5953
5954 /* Check length. */
5955 if (name_len > trash.size - 1) {
5956 lua_pushboolean(L, 0);
5957 return 1;
5958 }
5959
5960 /* Add the mark question as prefix. */
5961 chunk_reset(&trash);
5962 trash.area[trash.data++] = '?';
5963 memcpy(trash.area + trash.data, name, name_len);
5964 trash.data += name_len;
5965
5966 lua_pushboolean(L,
5967 http_req_replace_stline(2, trash.area, trash.data, htxn->p, htxn->s) != -1);
5968 return 1;
5969}
5970
5971/* This function set the uri. */
5972static int hlua_http_req_set_uri(lua_State *L)
5973{
5974 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5975 size_t name_len;
5976 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
5977
5978 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
5979 WILL_LJMP(lua_error(L));
5980
5981 lua_pushboolean(L, http_req_replace_stline(3, name, name_len, htxn->p, htxn->s) != -1);
5982 return 1;
5983}
5984
5985/* This function set the response code & optionally reason. */
5986static int hlua_http_res_set_status(lua_State *L)
5987{
5988 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5989 unsigned int code = MAY_LJMP(luaL_checkinteger(L, 2));
5990 const char *str = MAY_LJMP(luaL_optlstring(L, 3, NULL, NULL));
5991 const struct ist reason = ist2(str, (str ? strlen(str) : 0));
5992
5993 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
5994 WILL_LJMP(lua_error(L));
5995
5996 http_res_set_status(code, reason, htxn->s);
5997 return 0;
5998}
5999
6000/*
6001 *
6002 *
6003 * Class HTTPMessage
6004 *
6005 *
6006 */
6007
6008/* Returns a struct http_msg if the stack entry "ud" is a class HTTPMessage,
6009 * otherwise it throws an error.
6010 */
6011__LJMP static struct http_msg *hlua_checkhttpmsg(lua_State *L, int ud)
6012{
6013 return MAY_LJMP(hlua_checkudata(L, ud, class_http_msg_ref));
6014}
6015
6016/* Creates and pushes on the stack a HTTP object according with a current TXN.
6017 */
Christopher Faulet78c35472020-02-26 17:14:08 +01006018static int hlua_http_msg_new(lua_State *L, struct http_msg *msg)
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006019{
6020 /* Check stack size. */
6021 if (!lua_checkstack(L, 3))
6022 return 0;
6023
6024 lua_newtable(L);
6025 lua_pushlightuserdata(L, msg);
6026 lua_rawseti(L, -2, 0);
6027
6028 /* Create the "channel" field that contains the request channel object. */
6029 lua_pushstring(L, "channel");
6030 if (!hlua_channel_new(L, msg->chn))
6031 return 0;
6032 lua_rawset(L, -3);
6033
6034 /* Pop a class stream metatable and affect it to the table. */
6035 lua_rawgeti(L, LUA_REGISTRYINDEX, class_http_msg_ref);
6036 lua_setmetatable(L, -2);
6037
6038 return 1;
6039}
6040
6041/* Helper function returning a filter attached to the HTTP message at the
6042 * position <ud> in the stack, filling the current offset and length of the
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006043 * filter. If no filter is attached, NULL is returned and <offset> and <len> are
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006044 * filled with output and input length respectively.
6045 */
6046static struct filter *hlua_http_msg_filter(lua_State *L, int ud, struct http_msg *msg, size_t *offset, size_t *len)
6047{
6048 struct channel *chn = msg->chn;
6049 struct htx *htx = htxbuf(&chn->buf);
6050 struct filter *filter = NULL;
6051
6052 *offset = co_data(msg->chn);
6053 *len = htx->data - co_data(msg->chn);
6054
6055 if (lua_getfield(L, ud, "__filter") == LUA_TLIGHTUSERDATA) {
6056 filter = lua_touserdata (L, -1);
6057 if (msg->msg_state >= HTTP_MSG_DATA) {
6058 struct hlua_flt_ctx *flt_ctx = filter->ctx;
6059
6060 *offset = flt_ctx->cur_off[CHN_IDX(chn)];
6061 *len = flt_ctx->cur_len[CHN_IDX(chn)];
6062 }
6063 }
6064
6065 lua_pop(L, 1);
6066 return filter;
6067}
6068
6069/* Returns true if the channel attached to the HTTP message is the response
6070 * channel.
6071 */
6072__LJMP static int hlua_http_msg_is_resp(lua_State *L)
6073{
6074 struct http_msg *msg;
6075
6076 MAY_LJMP(check_args(L, 1, "is_resp"));
6077 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6078
6079 lua_pushboolean(L, !!(msg->chn->flags & CF_ISRESP));
6080 return 1;
6081}
6082
6083/* Returns an array containing the elements status-line of the HTTP message. It relies
6084 * on hlua_http_get_stline().
6085 */
6086__LJMP static int hlua_http_msg_get_stline(lua_State *L)
6087{
6088 struct http_msg *msg;
6089 struct htx *htx;
6090 struct htx_sl *sl;
6091
6092 MAY_LJMP(check_args(L, 1, "get_stline"));
6093 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6094
6095 if (msg->msg_state > HTTP_MSG_BODY)
6096 WILL_LJMP(lua_error(L));
6097
6098 htx = htxbuf(&msg->chn->buf);
6099 sl = http_get_stline(htx);
6100 if (!sl)
6101 return 0;
6102 return hlua_http_get_stline(L, sl);
6103}
6104
6105/* Returns an array containing all headers of the HTTP message. it relies on
6106 * hlua_http_get_headers().
6107 */
6108__LJMP static int hlua_http_msg_get_headers(lua_State *L)
6109{
6110 struct http_msg *msg;
6111
6112 MAY_LJMP(check_args(L, 1, "get_headers"));
6113 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6114
6115 if (msg->msg_state > HTTP_MSG_BODY)
6116 WILL_LJMP(lua_error(L));
6117
6118 return hlua_http_get_headers(L, msg);
6119}
6120
6121/* Deletes all occurrences of an header in the HTTP message matching on its
6122 * name. It relies on hlua_http_del_hdr().
6123 */
6124__LJMP static int hlua_http_msg_del_hdr(lua_State *L)
6125{
6126 struct http_msg *msg;
6127
6128 MAY_LJMP(check_args(L, 2, "del_header"));
6129 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6130
6131 if (msg->msg_state > HTTP_MSG_BODY)
6132 WILL_LJMP(lua_error(L));
6133
6134 return hlua_http_del_hdr(L, msg);
6135}
6136
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006137/* Matches the full value line of all occurrences of an header in the HTTP
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006138 * message given its name against a regex and replaces it if it matches. It
6139 * relies on hlua_http_rep_hdr().
6140 */
6141__LJMP static int hlua_http_msg_rep_hdr(lua_State *L)
6142{
6143 struct http_msg *msg;
6144
6145 MAY_LJMP(check_args(L, 4, "rep_header"));
6146 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6147
6148 if (msg->msg_state > HTTP_MSG_BODY)
6149 WILL_LJMP(lua_error(L));
6150
6151 return hlua_http_rep_hdr(L, msg, 1);
6152}
6153
Ilya Shipitsinbd6b4be2021-10-15 16:18:21 +05006154/* Matches all comma-separated values of all occurrences of an header in the HTTP
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006155 * message given its name against a regex and replaces it if it matches. It
6156 * relies on hlua_http_rep_hdr().
6157 */
6158__LJMP static int hlua_http_msg_rep_val(lua_State *L)
6159{
6160 struct http_msg *msg;
6161
6162 MAY_LJMP(check_args(L, 4, "rep_value"));
6163 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6164
6165 if (msg->msg_state > HTTP_MSG_BODY)
6166 WILL_LJMP(lua_error(L));
6167
6168 return hlua_http_rep_hdr(L, msg, 0);
6169}
6170
6171/* Add an header in the HTTP message. It relies on hlua_http_add_hdr() */
6172__LJMP static int hlua_http_msg_add_hdr(lua_State *L)
6173{
6174 struct http_msg *msg;
6175
6176 MAY_LJMP(check_args(L, 3, "add_header"));
6177 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6178
6179 if (msg->msg_state > HTTP_MSG_BODY)
6180 WILL_LJMP(lua_error(L));
6181
6182 return hlua_http_add_hdr(L, msg);
6183}
6184
6185/* Add an header in the HTTP message removing existing headers with the same
6186 * name. It relies on hlua_http_del_hdr() and hlua_http_add_hdr().
6187 */
6188__LJMP static int hlua_http_msg_set_hdr(lua_State *L)
6189{
6190 struct http_msg *msg;
6191
6192 MAY_LJMP(check_args(L, 3, "set_header"));
6193 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6194
6195 if (msg->msg_state > HTTP_MSG_BODY)
6196 WILL_LJMP(lua_error(L));
6197
6198 hlua_http_del_hdr(L, msg);
6199 return hlua_http_add_hdr(L, msg);
6200}
6201
6202/* Rewrites the request method. It relies on http_req_replace_stline(). */
6203__LJMP static int hlua_http_msg_set_meth(lua_State *L)
6204{
6205 struct stream *s;
6206 struct http_msg *msg;
6207 const char *name;
6208 size_t name_len;
6209
6210 MAY_LJMP(check_args(L, 2, "set_method"));
6211 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6212 name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
6213
6214 if ((msg->chn->flags & CF_ISRESP) || msg->msg_state > HTTP_MSG_BODY)
6215 WILL_LJMP(lua_error(L));
6216
6217 s = chn_strm(msg->chn);
6218 lua_pushboolean(L, http_req_replace_stline(0, name, name_len, s->be, s) != -1);
6219 return 1;
6220}
6221
6222/* Rewrites the request path. It relies on http_req_replace_stline(). */
6223__LJMP static int hlua_http_msg_set_path(lua_State *L)
6224{
6225 struct stream *s;
6226 struct http_msg *msg;
6227 const char *name;
6228 size_t name_len;
6229
6230 MAY_LJMP(check_args(L, 2, "set_path"));
6231 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6232 name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
6233
6234 if ((msg->chn->flags & CF_ISRESP) || msg->msg_state > HTTP_MSG_BODY)
6235 WILL_LJMP(lua_error(L));
6236
6237 s = chn_strm(msg->chn);
6238 lua_pushboolean(L, http_req_replace_stline(1, name, name_len, s->be, s) != -1);
6239 return 1;
6240}
6241
6242/* Rewrites the request query-string. It relies on http_req_replace_stline(). */
6243__LJMP static int hlua_http_msg_set_query(lua_State *L)
6244{
6245 struct stream *s;
6246 struct http_msg *msg;
6247 const char *name;
6248 size_t name_len;
6249
6250 MAY_LJMP(check_args(L, 2, "set_query"));
6251 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6252 name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
6253
6254 if ((msg->chn->flags & CF_ISRESP) || msg->msg_state > HTTP_MSG_BODY)
6255 WILL_LJMP(lua_error(L));
6256
6257 /* Check length. */
6258 if (name_len > trash.size - 1) {
6259 lua_pushboolean(L, 0);
6260 return 1;
6261 }
6262
6263 /* Add the mark question as prefix. */
6264 chunk_reset(&trash);
6265 trash.area[trash.data++] = '?';
6266 memcpy(trash.area + trash.data, name, name_len);
6267 trash.data += name_len;
6268
6269 s = chn_strm(msg->chn);
6270 lua_pushboolean(L, http_req_replace_stline(2, trash.area, trash.data, s->be, s) != -1);
6271 return 1;
6272}
6273
6274/* Rewrites the request URI. It relies on http_req_replace_stline(). */
6275__LJMP static int hlua_http_msg_set_uri(lua_State *L)
6276{
6277 struct stream *s;
6278 struct http_msg *msg;
6279 const char *name;
6280 size_t name_len;
6281
6282 MAY_LJMP(check_args(L, 2, "set_uri"));
6283 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6284 name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
6285
6286 if ((msg->chn->flags & CF_ISRESP) || msg->msg_state > HTTP_MSG_BODY)
6287 WILL_LJMP(lua_error(L));
6288
6289 s = chn_strm(msg->chn);
6290 lua_pushboolean(L, http_req_replace_stline(3, name, name_len, s->be, s) != -1);
6291 return 1;
6292}
6293
6294/* Rewrites the response status code. It relies on http_res_set_status(). */
6295__LJMP static int hlua_http_msg_set_status(lua_State *L)
6296{
6297 struct http_msg *msg;
6298 unsigned int code;
6299 const char *reason;
6300 size_t reason_len;
6301
6302 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6303 code = MAY_LJMP(luaL_checkinteger(L, 2));
6304 reason = MAY_LJMP(luaL_optlstring(L, 3, NULL, &reason_len));
6305
6306 if (!(msg->chn->flags & CF_ISRESP) || msg->msg_state > HTTP_MSG_BODY)
6307 WILL_LJMP(lua_error(L));
6308
6309 lua_pushboolean(L, http_res_set_status(code, ist2(reason, reason_len), chn_strm(msg->chn)) != -1);
6310 return 1;
6311}
6312
6313/* Returns true if the HTTP message is full. */
6314__LJMP static int hlua_http_msg_is_full(lua_State *L)
6315{
6316 struct http_msg *msg;
6317
6318 MAY_LJMP(check_args(L, 1, "is_full"));
6319 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6320 lua_pushboolean(L, channel_full(msg->chn, 0));
6321 return 1;
6322}
6323
6324/* Returns true if the HTTP message may still receive data. */
6325__LJMP static int hlua_http_msg_may_recv(lua_State *L)
6326{
6327 struct http_msg *msg;
6328 struct htx *htx;
6329
6330 MAY_LJMP(check_args(L, 1, "may_recv"));
6331 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6332 htx = htxbuf(&msg->chn->buf);
6333 lua_pushboolean(L, (htx_expect_more(htx) && !channel_input_closed(msg->chn) && channel_may_recv(msg->chn)));
6334 return 1;
6335}
6336
6337/* Returns true if the HTTP message EOM was received */
6338__LJMP static int hlua_http_msg_is_eom(lua_State *L)
6339{
6340 struct http_msg *msg;
6341 struct htx *htx;
6342
6343 MAY_LJMP(check_args(L, 1, "may_recv"));
6344 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6345 htx = htxbuf(&msg->chn->buf);
6346 lua_pushboolean(L, !htx_expect_more(htx));
6347 return 1;
6348}
6349
6350/* Returns the number of bytes available in the input side of the HTTP
6351 * message. This function never fails.
6352 */
6353__LJMP static int hlua_http_msg_get_in_len(lua_State *L)
6354{
6355 struct http_msg *msg;
Christopher Fauleteae8afa2020-02-26 17:15:48 +01006356 size_t output, input;
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006357
6358 MAY_LJMP(check_args(L, 1, "input"));
6359 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
Christopher Fauleteae8afa2020-02-26 17:15:48 +01006360 hlua_http_msg_filter(L, 1, msg, &output, &input);
6361 lua_pushinteger(L, input);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006362 return 1;
6363}
6364
6365/* Returns the number of bytes available in the output side of the HTTP
6366 * message. This function never fails.
6367 */
6368__LJMP static int hlua_http_msg_get_out_len(lua_State *L)
6369{
6370 struct http_msg *msg;
Christopher Fauleteae8afa2020-02-26 17:15:48 +01006371 size_t output, input;
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006372
6373 MAY_LJMP(check_args(L, 1, "output"));
6374 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
Christopher Fauleteae8afa2020-02-26 17:15:48 +01006375 hlua_http_msg_filter(L, 1, msg, &output, &input);
6376 lua_pushinteger(L, output);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006377 return 1;
6378}
6379
6380/* Copies at most <len> bytes of DATA blocks from the HTTP message <msg>
6381 * starting at the offset <offset> and put it in a string LUA variables. It
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006382 * returns the built string length. It stops on the first non-DATA HTX
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006383 * block. This function is called during the payload filtering, so the headers
6384 * are already scheduled for output (from the filter point of view).
6385 */
6386static int _hlua_http_msg_dup(struct http_msg *msg, lua_State *L, size_t offset, size_t len)
6387{
6388 struct htx *htx = htxbuf(&msg->chn->buf);
6389 struct htx_blk *blk;
6390 struct htx_ret htxret;
6391 luaL_Buffer b;
6392 int ret = 0;
6393
6394 luaL_buffinit(L, &b);
6395 htxret = htx_find_offset(htx, offset);
6396 for (blk = htxret.blk, offset = htxret.ret; blk && len; blk = htx_get_next_blk(htx, blk)) {
6397 enum htx_blk_type type = htx_get_blk_type(blk);
6398 struct ist v;
6399
6400 switch (type) {
6401 case HTX_BLK_UNUSED:
6402 break;
6403
6404 case HTX_BLK_DATA:
6405 v = htx_get_blk_value(htx, blk);
Tim Duesterhusb113b5c2021-09-15 13:58:44 +02006406 v = istadv(v, offset);
Tim Duesterhus2471f5c2021-11-08 09:05:01 +01006407 v = isttrim(v, len);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006408
6409 luaL_addlstring(&b, v.ptr, v.len);
6410 ret += v.len;
6411 break;
6412
6413 default:
vishnu0af4bd72021-10-24 06:46:24 +05306414 if (!ret)
6415 goto no_data;
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006416 goto end;
6417 }
6418 offset = 0;
6419 }
6420
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006421end:
vishnu0af4bd72021-10-24 06:46:24 +05306422 if (!ret && (htx->flags & HTX_FL_EOM))
6423 goto no_data;
6424 luaL_pushresult(&b);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006425 return ret;
vishnu0af4bd72021-10-24 06:46:24 +05306426
6427 no_data:
6428 /* Remove the empty string and push nil on the stack */
6429 lua_pop(L, 1);
6430 lua_pushnil(L);
6431 return 0;
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006432}
6433
6434/* Copies the string <str> to the HTTP message <msg> at the offset
6435 * <offset>. This function returns -1 if data cannot be copied. Otherwise, it
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006436 * returns the amount of data written. This function is responsible to update
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006437 * the filter context.
6438 */
6439static int _hlua_http_msg_insert(struct http_msg *msg, struct filter *filter, struct ist str, size_t offset)
6440{
6441 struct htx *htx = htx_from_buf(&msg->chn->buf);
6442 struct htx_ret htxret;
6443 int /*max, */ret = 0;
6444
6445 /* Nothing to do, just return */
6446 if (unlikely(istlen(str) == 0))
6447 goto end;
6448
6449 if (istlen(str) > htx_free_data_space(htx)) {
6450 ret = -1;
6451 goto end;
6452 }
6453
6454 htxret = htx_find_offset(htx, offset);
6455 if (!htxret.blk || htx_get_blk_type(htxret.blk) != HTX_BLK_DATA) {
6456 if (!htx_add_last_data(htx, str))
6457 goto end;
6458 }
6459 else {
6460 struct ist v = htx_get_blk_value(htx, htxret.blk);
6461 v.ptr += htxret.ret;
6462 v.len = 0;
6463 if (!htx_replace_blk_value(htx, htxret.blk, v, str))
6464 goto end;
6465 }
6466 ret = str.len;
6467 if (ret) {
6468 struct hlua_flt_ctx *flt_ctx = filter->ctx;
6469 flt_update_offsets(filter, msg->chn, ret);
6470 flt_ctx->cur_len[CHN_IDX(msg->chn)] += ret;
6471 }
6472
6473 end:
6474 htx_to_buf(htx, &msg->chn->buf);
6475 return ret;
6476}
6477
6478/* Helper function removing at most <len> bytes of DATA blocks at the absolute
6479 * position <offset>. It stops on the first non-DATA HTX block. This function is
6480 * called during the payload filtering, so the headers are already scheduled for
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006481 * output (from the filter point of view). This function is responsible to
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006482 * update the filter context.
6483 */
6484static void _hlua_http_msg_delete(struct http_msg *msg, struct filter *filter, size_t offset, size_t len)
6485{
6486 struct hlua_flt_ctx *flt_ctx = filter->ctx;
6487 struct htx *htx = htx_from_buf(&msg->chn->buf);
6488 struct htx_blk *blk;
6489 struct htx_ret htxret;
6490 size_t ret = 0;
6491
6492 /* Be sure <len> is always the amount of DATA to remove */
6493 if (htx->data == offset+len && htx_get_tail_type(htx) == HTX_BLK_DATA) {
Aurelien DARRAGONbcbcf982022-09-28 19:08:15 +02006494 /* When htx tail type == HTX_BLK_DATA, no need to take care
6495 * of special blocks like HTX_BLK_EOT.
6496 * We simply truncate after offset
6497 * (truncate targeted blk and discard the following ones)
6498 */
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006499 htx_truncate(htx, offset);
6500 ret = len;
6501 goto end;
6502 }
6503
6504 htxret = htx_find_offset(htx, offset);
6505 blk = htxret.blk;
6506 if (htxret.ret) {
Aurelien DARRAGONbcbcf982022-09-28 19:08:15 +02006507 /* dealing with offset: we need to trim targeted blk */
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006508 struct ist v;
6509
6510 if (htx_get_blk_type(blk) != HTX_BLK_DATA)
6511 goto end;
Aurelien DARRAGONbcbcf982022-09-28 19:08:15 +02006512
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006513 v = htx_get_blk_value(htx, blk);
6514 v.ptr += htxret.ret;
Aurelien DARRAGONbcbcf982022-09-28 19:08:15 +02006515 v.len -= htxret.ret;
6516
Tim Duesterhus2471f5c2021-11-08 09:05:01 +01006517 v = isttrim(v, len);
Aurelien DARRAGONbcbcf982022-09-28 19:08:15 +02006518 /* trimming data in blk: discard everything after the offset
6519 * (replace 'v' with 'IST_NULL')
6520 */
Tim Duesterhusb113b5c2021-09-15 13:58:44 +02006521 blk = htx_replace_blk_value(htx, blk, v, IST_NULL);
Aurelien DARRAGONbcbcf982022-09-28 19:08:15 +02006522 if (blk && v.len < len) {
6523 /* In this case, caller wants to keep removing data,
6524 * but we need to spare current blk
6525 * because it was already trimmed
6526 */
6527 blk = htx_get_next_blk(htx, blk);
6528 }
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006529 len -= v.len;
6530 ret += v.len;
6531 }
6532
6533
6534 while (blk && len) {
Aurelien DARRAGONbcbcf982022-09-28 19:08:15 +02006535 /* there is more data that needs to be discarded */
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006536 enum htx_blk_type type = htx_get_blk_type(blk);
6537 uint32_t sz = htx_get_blksz(blk);
6538
6539 switch (type) {
6540 case HTX_BLK_UNUSED:
6541 break;
6542
6543 case HTX_BLK_DATA:
6544 if (len < sz) {
Aurelien DARRAGONbcbcf982022-09-28 19:08:15 +02006545 /* don't discard whole blk, only part of it
6546 * (from the beginning)
6547 */
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006548 htx_cut_data_blk(htx, blk, len);
6549 ret += len;
6550 goto end;
6551 }
6552 break;
6553
6554 default:
Aurelien DARRAGONbcbcf982022-09-28 19:08:15 +02006555 /* HTX_BLK_EOT blk won't be removed */
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006556 goto end;
6557 }
6558
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006559 /* Remove all the data block */
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006560 len -= sz;
6561 ret += sz;
6562 blk = htx_remove_blk(htx, blk);
6563 }
6564
6565end:
6566 flt_update_offsets(filter, msg->chn, -ret);
6567 flt_ctx->cur_len[CHN_IDX(msg->chn)] -= ret;
6568 /* WARNING: we don't call htx_to_buf() on purpose, because we don't want
6569 * to loose the EOM flag if the message is empty.
6570 */
6571}
6572
6573/* Copies input data found in an HTTP message. Unlike the channel function used
6574 * to duplicate raw data, this one can only be called inside a filter, from
6575 * http_payload callback. So it cannot yield. An exception is returned if it is
6576 * called from another callback. If nothing was copied, a nil value is pushed on
6577 * the stack.
6578 */
6579__LJMP static int hlua_http_msg_get_body(lua_State *L)
6580{
6581 struct http_msg *msg;
6582 struct filter *filter;
6583 size_t output, input;
6584 int offset, len;
6585
6586 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
6587 WILL_LJMP(luaL_error(L, "'data' expects at most 2 arguments"));
6588 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6589
6590 if (msg->msg_state < HTTP_MSG_DATA)
6591 WILL_LJMP(lua_error(L));
6592
6593 filter = hlua_http_msg_filter(L, 1, msg, &output, &input);
6594 if (!filter || !hlua_filter_from_payload(filter))
6595 WILL_LJMP(lua_error(L));
6596
6597 if (!ci_data(msg->chn) && channel_input_closed(msg->chn)) {
6598 lua_pushnil(L);
6599 return 1;
6600 }
6601
6602 offset = output;
6603 if (lua_gettop(L) > 1) {
6604 offset = MAY_LJMP(luaL_checkinteger(L, 2));
6605 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02006606 offset = MAX(0, (int)input + offset);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006607 offset += output;
6608 if (offset < output || offset > input + output) {
6609 lua_pushfstring(L, "offset out of range.");
6610 WILL_LJMP(lua_error(L));
6611 }
6612 }
6613 len = output + input - offset;
6614 if (lua_gettop(L) == 3) {
6615 len = MAY_LJMP(luaL_checkinteger(L, 3));
6616 if (!len)
6617 goto dup;
6618 if (len == -1)
6619 len = global.tune.bufsize;
6620 if (len < 0) {
6621 lua_pushfstring(L, "length out of range.");
6622 WILL_LJMP(lua_error(L));
6623 }
6624 }
6625
6626 dup:
6627 _hlua_http_msg_dup(msg, L, offset, len);
6628 return 1;
6629}
6630
6631/* Appends a string to the HTTP message, after all existing DATA blocks but
6632 * before the trailers, if any. It returns the amount of data written or -1 if
6633 * nothing was copied. Unlike the channel function used to append data, this one
6634 * can only be called inside a filter, from http_payload callback. So it cannot
6635 * yield. An exception is returned if it is called from another callback.
6636 */
6637__LJMP static int hlua_http_msg_append(lua_State *L)
6638{
6639 struct http_msg *msg;
6640 struct filter *filter;
6641 const char *str;
6642 size_t offset, len, sz;
6643 int ret;
6644
6645 MAY_LJMP(check_args(L, 2, "append"));
6646 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6647
6648 if (msg->msg_state < HTTP_MSG_DATA)
6649 WILL_LJMP(lua_error(L));
6650
6651 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
6652 filter = hlua_http_msg_filter(L, 1, msg, &offset, &len);
6653 if (!filter || !hlua_filter_from_payload(filter))
6654 WILL_LJMP(lua_error(L));
6655
6656 ret = _hlua_http_msg_insert(msg, filter, ist2(str, sz), offset+len);
6657 lua_pushinteger(L, ret);
6658 return 1;
6659}
6660
6661/* Prepends a string to the HTTP message, before all existing DATA blocks. It
6662 * returns the amount of data written or -1 if nothing was copied. Unlike the
6663 * channel function used to prepend data, this one can only be called inside a
6664 * filter, from http_payload callback. So it cannot yield. An exception is
6665 * returned if it is called from another callback.
6666 */
6667__LJMP static int hlua_http_msg_prepend(lua_State *L)
6668{
6669 struct http_msg *msg;
6670 struct filter *filter;
6671 const char *str;
6672 size_t offset, len, sz;
6673 int ret;
6674
6675 MAY_LJMP(check_args(L, 2, "prepend"));
6676 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006677
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006678 if (msg->msg_state < HTTP_MSG_DATA)
6679 WILL_LJMP(lua_error(L));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006680
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006681 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
6682 filter = hlua_http_msg_filter(L, 1, msg, &offset, &len);
6683 if (!filter || !hlua_filter_from_payload(filter))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006684 WILL_LJMP(lua_error(L));
6685
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006686 ret = _hlua_http_msg_insert(msg, filter, ist2(str, sz), offset);
6687 lua_pushinteger(L, ret);
6688 return 1;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006689}
6690
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006691/* Inserts a string to the HTTP message at a given offset. By default the string
6692 * is appended at the end of DATA blocks. It returns the amount of data written
6693 * or -1 if nothing was copied. Unlike the channel function used to insert data,
6694 * this one can only be called inside a filter, from http_payload callback. So
6695 * it cannot yield. An exception is returned if it is called from another
6696 * callback.
6697 */
6698__LJMP static int hlua_http_msg_insert_data(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006699{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006700 struct http_msg *msg;
6701 struct filter *filter;
6702 const char *str;
6703 size_t input, output, sz;
6704 int offset;
6705 int ret;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006706
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006707 if (lua_gettop(L) < 2 || lua_gettop(L) > 3)
6708 WILL_LJMP(luaL_error(L, "'insert' expects at least 1 argument and at most 2 arguments"));
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006709 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006710
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006711 if (msg->msg_state < HTTP_MSG_DATA)
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006712 WILL_LJMP(lua_error(L));
6713
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006714 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
Aurelien DARRAGON7fdba0a2022-09-28 16:03:45 +02006715 filter = hlua_http_msg_filter(L, 1, msg, &output, &input);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006716 if (!filter || !hlua_filter_from_payload(filter))
6717 WILL_LJMP(lua_error(L));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006718
Aurelien DARRAGON7fdba0a2022-09-28 16:03:45 +02006719 offset = output;
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006720 if (lua_gettop(L) > 2) {
6721 offset = MAY_LJMP(luaL_checkinteger(L, 3));
6722 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02006723 offset = MAX(0, (int)input + offset);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006724 offset += output;
Aurelien DARRAGON7fdba0a2022-09-28 16:03:45 +02006725 if (offset > output + input) {
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006726 lua_pushfstring(L, "offset out of range.");
6727 WILL_LJMP(lua_error(L));
6728 }
6729 }
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006730
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006731 ret = _hlua_http_msg_insert(msg, filter, ist2(str, sz), offset);
6732 lua_pushinteger(L, ret);
6733 return 1;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006734}
6735
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006736/* Removes a given amount of data from the HTTP message at a given offset. By
6737 * default all DATA blocks are removed. It returns the amount of data
6738 * removed. Unlike the channel function used to remove data, this one can only
6739 * be called inside a filter, from http_payload callback. So it cannot yield. An
6740 * exception is returned if it is called from another callback.
6741 */
6742__LJMP static int hlua_http_msg_del_data(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006743{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006744 struct http_msg *msg;
6745 struct filter *filter;
6746 size_t input, output;
6747 int offset, len;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006748
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006749 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
Boyang Lie0c54352022-05-10 17:47:23 +00006750 WILL_LJMP(luaL_error(L, "'remove' expects at most 2 arguments"));
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006751 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006752
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006753 if (msg->msg_state < HTTP_MSG_DATA)
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006754 WILL_LJMP(lua_error(L));
6755
Aurelien DARRAGONd7c71b02022-09-28 15:52:18 +02006756 filter = hlua_http_msg_filter(L, 1, msg, &output, &input);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006757 if (!filter || !hlua_filter_from_payload(filter))
6758 WILL_LJMP(lua_error(L));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006759
Aurelien DARRAGONd7c71b02022-09-28 15:52:18 +02006760 offset = output;
Boyang Lie0c54352022-05-10 17:47:23 +00006761 if (lua_gettop(L) > 1) {
6762 offset = MAY_LJMP(luaL_checkinteger(L, 2));
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006763 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02006764 offset = MAX(0, (int)input + offset);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006765 offset += output;
Aurelien DARRAGONd7c71b02022-09-28 15:52:18 +02006766 if (offset > output + input) {
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006767 lua_pushfstring(L, "offset out of range.");
6768 WILL_LJMP(lua_error(L));
6769 }
6770 }
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006771
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006772 len = output + input - offset;
Boyang Lie0c54352022-05-10 17:47:23 +00006773 if (lua_gettop(L) == 3) {
6774 len = MAY_LJMP(luaL_checkinteger(L, 3));
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006775 if (!len)
6776 goto end;
6777 if (len == -1)
6778 len = output + input - offset;
6779 if (len < 0 || offset + len > output + input) {
6780 lua_pushfstring(L, "length out of range.");
6781 WILL_LJMP(lua_error(L));
6782 }
6783 }
6784
6785 _hlua_http_msg_delete(msg, filter, offset, len);
6786
6787 end:
6788 lua_pushinteger(L, len);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006789 return 1;
6790}
6791
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006792/* Replaces a given amount of data at the given offset by a string. By default,
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006793 * all remaining data are removed, accordingly to the filter context. It returns
6794 * the amount of data written or -1 if nothing was copied. Unlike the channel
6795 * function used to replace data, this one can only be called inside a filter,
6796 * from http_payload callback. So it cannot yield. An exception is returned if
6797 * it is called from another callback.
6798 */
6799__LJMP static int hlua_http_msg_set_data(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006800{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006801 struct http_msg *msg;
6802 struct filter *filter;
6803 struct htx *htx;
6804 const char *str;
6805 size_t input, output, sz;
6806 int offset, len;
6807 int ret;
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02006808
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006809 if (lua_gettop(L) < 2 || lua_gettop(L) > 4)
6810 WILL_LJMP(luaL_error(L, "'set' expects at least 1 argument and at most 3 arguments"));
6811 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6812
6813 if (msg->msg_state < HTTP_MSG_DATA)
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006814 WILL_LJMP(lua_error(L));
6815
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006816 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
6817 filter = hlua_http_msg_filter(L, 1, msg, &output, &input);
6818 if (!filter || !hlua_filter_from_payload(filter))
6819 WILL_LJMP(lua_error(L));
6820
6821 offset = output;
6822 if (lua_gettop(L) > 2) {
6823 offset = MAY_LJMP(luaL_checkinteger(L, 3));
6824 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02006825 offset = MAX(0, (int)input + offset);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006826 offset += output;
6827 if (offset < output || offset > input + output) {
6828 lua_pushfstring(L, "offset out of range.");
6829 WILL_LJMP(lua_error(L));
6830 }
6831 }
6832
6833 len = output + input - offset;
6834 if (lua_gettop(L) == 4) {
6835 len = MAY_LJMP(luaL_checkinteger(L, 4));
6836 if (!len)
6837 goto set;
6838 if (len == -1)
6839 len = output + input - offset;
6840 if (len < 0 || offset + len > output + input) {
6841 lua_pushfstring(L, "length out of range.");
6842 WILL_LJMP(lua_error(L));
6843 }
6844 }
6845
6846 set:
6847 /* Be sure we can copied the string once input data will be removed. */
6848 htx = htx_from_buf(&msg->chn->buf);
6849 if (sz > htx_free_data_space(htx) + len)
6850 lua_pushinteger(L, -1);
6851 else {
6852 _hlua_http_msg_delete(msg, filter, offset, len);
6853 ret = _hlua_http_msg_insert(msg, filter, ist2(str, sz), offset);
6854 lua_pushinteger(L, ret);
6855 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006856 return 1;
6857}
6858
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006859/* Prepends data into an HTTP message and forward it, from the filter point of
6860 * view. It returns the amount of data written or -1 if nothing was sent. Unlike
6861 * the channel function used to send data, this one can only be called inside a
6862 * filter, from http_payload callback. So it cannot yield. An exception is
6863 * returned if it is called from another callback.
6864 */
6865__LJMP static int hlua_http_msg_send(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006866{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006867 struct http_msg *msg;
6868 struct filter *filter;
6869 struct htx *htx;
6870 const char *str;
6871 size_t offset, len, sz;
6872 int ret;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006873
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006874 MAY_LJMP(check_args(L, 2, "send"));
6875 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6876
6877 if (msg->msg_state < HTTP_MSG_DATA)
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006878 WILL_LJMP(lua_error(L));
6879
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006880 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
6881 filter = hlua_http_msg_filter(L, 1, msg, &offset, &len);
6882 if (!filter || !hlua_filter_from_payload(filter))
6883 WILL_LJMP(lua_error(L));
6884
6885 /* Return an error if the channel's output is closed */
6886 if (unlikely(channel_output_closed(msg->chn))) {
6887 lua_pushinteger(L, -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006888 return 1;
6889 }
6890
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006891 htx = htx_from_buf(&msg->chn->buf);
6892 if (sz > htx_free_data_space(htx)) {
6893 lua_pushinteger(L, -1);
6894 return 1;
6895 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006896
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006897 ret = _hlua_http_msg_insert(msg, filter, ist2(str, sz), offset);
6898 if (ret > 0) {
6899 struct hlua_flt_ctx *flt_ctx = filter->ctx;
6900
6901 FLT_OFF(filter, msg->chn) += ret;
6902 flt_ctx->cur_len[CHN_IDX(msg->chn)] -= ret;
6903 flt_ctx->cur_off[CHN_IDX(msg->chn)] += ret;
6904 }
6905
6906 lua_pushinteger(L, ret);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006907 return 1;
6908}
6909
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006910/* Forwards a given amount of bytes. It return -1 if the channel's output is
6911 * closed. Otherwise, it returns the number of bytes forwarded. Unlike the
6912 * channel function used to forward data, this one can only be called inside a
6913 * filter, from http_payload callback. So it cannot yield. An exception is
6914 * returned if it is called from another callback. All other functions deal with
6915 * DATA block, this one not.
6916*/
6917__LJMP static int hlua_http_msg_forward(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006918{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006919 struct http_msg *msg;
6920 struct filter *filter;
6921 size_t offset, len;
6922 int fwd, ret = 0;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006923
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006924 MAY_LJMP(check_args(L, 2, "forward"));
6925 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6926
6927 if (msg->msg_state < HTTP_MSG_DATA)
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006928 WILL_LJMP(lua_error(L));
6929
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006930 fwd = MAY_LJMP(luaL_checkinteger(L, 2));
6931 filter = hlua_http_msg_filter(L, 1, msg, &offset, &len);
6932 if (!filter || !hlua_filter_from_payload(filter))
6933 WILL_LJMP(lua_error(L));
6934
6935 /* Nothing to do, just return */
6936 if (!fwd)
6937 goto end;
6938
6939 /* Return an error if the channel's output is closed */
6940 if (unlikely(channel_output_closed(msg->chn))) {
6941 ret = -1;
6942 goto end;
6943 }
6944
6945 ret = fwd;
6946 if (ret > len)
6947 ret = len;
6948
6949 if (ret) {
6950 struct hlua_flt_ctx *flt_ctx = filter->ctx;
6951
6952 FLT_OFF(filter, msg->chn) += ret;
6953 flt_ctx->cur_off[CHN_IDX(msg->chn)] += ret;
6954 flt_ctx->cur_len[CHN_IDX(msg->chn)] -= ret;
6955 }
6956
6957 end:
6958 lua_pushinteger(L, ret);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006959 return 1;
6960}
6961
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006962/* Set EOM flag on the HTX message.
6963 *
6964 * NOTE: Not sure it is a good idea to manipulate this flag but for now I don't
6965 * really know how to do without this feature.
6966 */
6967__LJMP static int hlua_http_msg_set_eom(lua_State *L)
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02006968{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006969 struct http_msg *msg;
6970 struct htx *htx;
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02006971
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006972 MAY_LJMP(check_args(L, 1, "set_eom"));
6973 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6974 htx = htxbuf(&msg->chn->buf);
6975 htx->flags |= HTX_FL_EOM;
6976 return 0;
6977}
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006978
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006979/* Unset EOM flag on the HTX message.
6980 *
6981 * NOTE: Not sure it is a good idea to manipulate this flag but for now I don't
6982 * really know how to do without this feature.
6983 */
6984__LJMP static int hlua_http_msg_unset_eom(lua_State *L)
6985{
6986 struct http_msg *msg;
6987 struct htx *htx;
6988
6989 MAY_LJMP(check_args(L, 1, "set_eom"));
6990 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6991 htx = htxbuf(&msg->chn->buf);
6992 htx->flags &= ~HTX_FL_EOM;
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02006993 return 0;
6994}
6995
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006996/*
6997 *
6998 *
William Lallemand3956c4e2021-09-21 16:25:15 +02006999 * Class HTTPClient
7000 *
7001 *
7002 */
7003__LJMP static struct hlua_httpclient *hlua_checkhttpclient(lua_State *L, int ud)
7004{
7005 return MAY_LJMP(hlua_checkudata(L, ud, class_httpclient_ref));
7006}
7007
William Lallemandf77f1de2021-09-28 19:10:38 +02007008
7009/* stops the httpclient and ask it to kill itself */
7010__LJMP static int hlua_httpclient_gc(lua_State *L)
7011{
7012 struct hlua_httpclient *hlua_hc;
7013
7014 MAY_LJMP(check_args(L, 1, "__gc"));
7015
7016 hlua_hc = MAY_LJMP(hlua_checkhttpclient(L, 1));
7017
7018 httpclient_stop_and_destroy(hlua_hc->hc);
7019
7020 hlua_hc->hc = NULL;
7021
7022
7023 return 0;
7024}
7025
7026
William Lallemand3956c4e2021-09-21 16:25:15 +02007027__LJMP static int hlua_httpclient_new(lua_State *L)
7028{
7029 struct hlua_httpclient *hlua_hc;
7030 struct hlua *hlua;
7031
7032 /* Get hlua struct, or NULL if we execute from main lua state */
7033 hlua = hlua_gethlua(L);
7034 if (!hlua)
7035 return 0;
7036
7037 /* Check stack size. */
7038 if (!lua_checkstack(L, 3)) {
7039 hlua_pusherror(L, "httpclient: full stack");
7040 goto err;
7041 }
7042 /* Create the object: obj[0] = userdata. */
7043 lua_newtable(L);
7044 hlua_hc = MAY_LJMP(lua_newuserdata(L, sizeof(*hlua_hc)));
7045 lua_rawseti(L, -2, 0);
7046 memset(hlua_hc, 0, sizeof(*hlua_hc));
7047
7048 hlua_hc->hc = httpclient_new(hlua, 0, IST_NULL);
7049 if (!hlua_hc->hc)
7050 goto err;
7051
7052 /* Pop a class stream metatable and affect it to the userdata. */
7053 lua_rawgeti(L, LUA_REGISTRYINDEX, class_httpclient_ref);
7054 lua_setmetatable(L, -2);
7055
7056 return 1;
7057
7058 err:
7059 WILL_LJMP(lua_error(L));
7060 return 0;
7061}
7062
7063
7064/*
7065 * Callback of the httpclient, this callback wakes the lua task up, once the
7066 * httpclient receives some data
7067 *
7068 */
7069
William Lallemandbd5739e2021-10-28 15:41:38 +02007070static void hlua_httpclient_cb(struct httpclient *hc)
William Lallemand3956c4e2021-09-21 16:25:15 +02007071{
7072 struct hlua *hlua = hc->caller;
7073
7074 if (!hlua || !hlua->task)
7075 return;
7076
7077 task_wakeup(hlua->task, TASK_WOKEN_MSG);
7078}
7079
7080/*
William Lallemandd7df73a2021-09-23 17:54:00 +02007081 * Fill the lua stack with headers from the httpclient response
7082 * This works the same way as the hlua_http_get_headers() function
7083 */
7084__LJMP static int hlua_httpclient_get_headers(lua_State *L, struct hlua_httpclient *hlua_hc)
7085{
7086 struct http_hdr *hdr;
7087
7088 lua_newtable(L);
7089
William Lallemandef574b22021-10-05 16:19:31 +02007090 for (hdr = hlua_hc->hc->res.hdrs; hdr && isttest(hdr->n); hdr++) {
William Lallemandd7df73a2021-09-23 17:54:00 +02007091 struct ist n, v;
7092 int len;
7093
7094 n = hdr->n;
7095 v = hdr->v;
7096
7097 /* Check for existing entry:
7098 * assume that the table is on the top of the stack, and
7099 * push the key in the stack, the function lua_gettable()
7100 * perform the lookup.
7101 */
7102
7103 lua_pushlstring(L, n.ptr, n.len);
7104 lua_gettable(L, -2);
7105
7106 switch (lua_type(L, -1)) {
7107 case LUA_TNIL:
7108 /* Table not found, create it. */
7109 lua_pop(L, 1); /* remove the nil value. */
7110 lua_pushlstring(L, n.ptr, n.len); /* push the header name as key. */
7111 lua_newtable(L); /* create and push empty table. */
7112 lua_pushlstring(L, v.ptr, v.len); /* push header value. */
7113 lua_rawseti(L, -2, 0); /* index header value (pop it). */
7114 lua_rawset(L, -3); /* index new table with header name (pop the values). */
7115 break;
7116
7117 case LUA_TTABLE:
7118 /* Entry found: push the value in the table. */
7119 len = lua_rawlen(L, -1);
7120 lua_pushlstring(L, v.ptr, v.len); /* push header value. */
7121 lua_rawseti(L, -2, len+1); /* index header value (pop it). */
7122 lua_pop(L, 1); /* remove the table (it is stored in the main table). */
7123 break;
7124
7125 default:
7126 /* Other cases are errors. */
7127 hlua_pusherror(L, "internal error during the parsing of headers.");
7128 WILL_LJMP(lua_error(L));
7129 }
7130 }
7131 return 1;
7132}
7133
7134/*
William Lallemand746e6f32021-10-06 10:57:44 +02007135 * Allocate and return an array of http_hdr ist extracted from the <headers> lua table
7136 *
7137 * Caller must free the result
7138 */
7139struct http_hdr *hlua_httpclient_table_to_hdrs(lua_State *L)
7140{
7141 struct http_hdr hdrs[global.tune.max_http_hdr];
7142 struct http_hdr *result = NULL;
7143 uint32_t hdr_num = 0;
7144
7145 lua_pushnil(L);
7146 while (lua_next(L, -2) != 0) {
7147 struct ist name, value;
7148 const char *n, *v;
7149 size_t nlen, vlen;
7150
7151 if (!lua_isstring(L, -2) || !lua_istable(L, -1)) {
7152 /* Skip element if the key is not a string or if the value is not a table */
7153 goto next_hdr;
7154 }
7155
7156 n = lua_tolstring(L, -2, &nlen);
7157 name = ist2(n, nlen);
7158
7159 /* Loop on header's values */
7160 lua_pushnil(L);
7161 while (lua_next(L, -2)) {
7162 if (!lua_isstring(L, -1)) {
7163 /* Skip the value if it is not a string */
7164 goto next_value;
7165 }
7166
7167 v = lua_tolstring(L, -1, &vlen);
7168 value = ist2(v, vlen);
7169 name = ist2(n, nlen);
7170
7171 hdrs[hdr_num].n = istdup(name);
7172 hdrs[hdr_num].v = istdup(value);
7173
7174 hdr_num++;
7175
7176 next_value:
7177 lua_pop(L, 1);
7178 }
7179
7180 next_hdr:
7181 lua_pop(L, 1);
7182
7183 }
7184
7185 if (hdr_num) {
7186 /* alloc and copy the headers in the httpclient struct */
Tim Duesterhus16cc16d2021-11-06 15:14:45 +01007187 result = calloc((hdr_num + 1), sizeof(*result));
William Lallemand746e6f32021-10-06 10:57:44 +02007188 if (!result)
7189 goto skip_headers;
7190 memcpy(result, hdrs, sizeof(struct http_hdr) * (hdr_num + 1));
7191
7192 result[hdr_num].n = IST_NULL;
7193 result[hdr_num].v = IST_NULL;
7194 }
7195
7196skip_headers:
William Lallemand746e6f32021-10-06 10:57:44 +02007197
7198 return result;
7199}
7200
7201
William Lallemandbd5739e2021-10-28 15:41:38 +02007202/*
7203 * For each yield, checks if there is some data in the httpclient and push them
7204 * in the lua buffer, once the httpclient finished its job, push the result on
7205 * the stack
7206 */
7207__LJMP static int hlua_httpclient_rcv_yield(lua_State *L, int status, lua_KContext ctx)
7208{
7209 struct buffer *tr;
7210 int res;
7211 struct hlua *hlua = hlua_gethlua(L);
7212 struct hlua_httpclient *hlua_hc = hlua_checkhttpclient(L, 1);
7213
7214
7215 tr = get_trash_chunk();
7216
7217 res = httpclient_res_xfer(hlua_hc->hc, tr);
7218 luaL_addlstring(&hlua_hc->b, b_orig(tr), res);
7219
7220 if (!httpclient_data(hlua_hc->hc) && httpclient_ended(hlua_hc->hc)) {
7221
7222 luaL_pushresult(&hlua_hc->b);
7223 lua_settable(L, -3);
7224
7225 lua_pushstring(L, "status");
7226 lua_pushinteger(L, hlua_hc->hc->res.status);
7227 lua_settable(L, -3);
7228
7229
7230 lua_pushstring(L, "reason");
7231 lua_pushlstring(L, hlua_hc->hc->res.reason.ptr, hlua_hc->hc->res.reason.len);
7232 lua_settable(L, -3);
7233
7234 lua_pushstring(L, "headers");
7235 hlua_httpclient_get_headers(L, hlua_hc);
7236 lua_settable(L, -3);
7237
7238 return 1;
7239 }
7240
7241 if (httpclient_data(hlua_hc->hc))
7242 task_wakeup(hlua->task, TASK_WOKEN_MSG);
7243
7244 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_httpclient_rcv_yield, TICK_ETERNITY, 0));
7245
7246 return 0;
7247}
7248
7249/*
7250 * Call this when trying to stream a body during a request
7251 */
7252__LJMP static int hlua_httpclient_snd_yield(lua_State *L, int status, lua_KContext ctx)
7253{
7254 struct hlua *hlua;
7255 struct hlua_httpclient *hlua_hc = hlua_checkhttpclient(L, 1);
7256 const char *body_str = NULL;
7257 int ret;
7258 int end = 0;
7259 size_t buf_len;
7260 size_t to_send = 0;
7261
7262 hlua = hlua_gethlua(L);
7263
7264 if (!hlua || !hlua->task)
7265 WILL_LJMP(luaL_error(L, "The 'get' function is only allowed in "
7266 "'frontend', 'backend' or 'task'"));
7267
7268 ret = lua_getfield(L, -1, "body");
7269 if (ret != LUA_TSTRING)
7270 goto rcv;
7271
7272 body_str = lua_tolstring(L, -1, &buf_len);
7273 lua_pop(L, 1);
7274
Christopher Fauletfc591292022-01-12 14:46:03 +01007275 to_send = buf_len - hlua_hc->sent;
William Lallemandbd5739e2021-10-28 15:41:38 +02007276
7277 if ((hlua_hc->sent + to_send) >= buf_len)
7278 end = 1;
7279
7280 /* the end flag is always set since we are using the whole remaining size */
7281 hlua_hc->sent += httpclient_req_xfer(hlua_hc->hc, ist2(body_str + hlua_hc->sent, to_send), end);
7282
7283 if (buf_len > hlua_hc->sent) {
7284 /* still need to process the buffer */
7285 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_httpclient_snd_yield, TICK_ETERNITY, 0));
7286 } else {
7287 goto rcv;
7288 /* we sent the whole request buffer we can recv */
7289 }
7290 return 0;
7291
7292rcv:
7293
7294 /* we return a "res" object */
7295 lua_newtable(L);
7296
William Lallemandbd5739e2021-10-28 15:41:38 +02007297 lua_pushstring(L, "body");
William Lallemandd1187eb2021-11-02 10:40:06 +01007298 luaL_buffinit(L, &hlua_hc->b);
William Lallemandbd5739e2021-10-28 15:41:38 +02007299
William Lallemand933fe392021-11-04 09:45:58 +01007300 task_wakeup(hlua->task, TASK_WOKEN_MSG);
William Lallemandbd5739e2021-10-28 15:41:38 +02007301 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_httpclient_rcv_yield, TICK_ETERNITY, 0));
7302
7303 return 1;
7304}
William Lallemand746e6f32021-10-06 10:57:44 +02007305
William Lallemand3956c4e2021-09-21 16:25:15 +02007306/*
William Lallemanddc2cc902021-10-26 11:43:26 +02007307 * Send an HTTP request and wait for a response
William Lallemand3956c4e2021-09-21 16:25:15 +02007308 */
7309
William Lallemanddc2cc902021-10-26 11:43:26 +02007310__LJMP static int hlua_httpclient_send(lua_State *L, enum http_meth_t meth)
William Lallemand3956c4e2021-09-21 16:25:15 +02007311{
7312 struct hlua_httpclient *hlua_hc;
William Lallemand746e6f32021-10-06 10:57:44 +02007313 struct http_hdr *hdrs = NULL;
7314 struct http_hdr *hdrs_i = NULL;
William Lallemand3956c4e2021-09-21 16:25:15 +02007315 struct hlua *hlua;
William Lallemand746e6f32021-10-06 10:57:44 +02007316 const char *url_str = NULL;
William Lallemanddec25c32021-10-25 19:48:37 +02007317 const char *body_str = NULL;
William Lallemandbd5739e2021-10-28 15:41:38 +02007318 size_t buf_len;
William Lallemand746e6f32021-10-06 10:57:44 +02007319 int ret;
William Lallemand3956c4e2021-09-21 16:25:15 +02007320
7321 hlua = hlua_gethlua(L);
7322
7323 if (!hlua || !hlua->task)
7324 WILL_LJMP(luaL_error(L, "The 'get' function is only allowed in "
7325 "'frontend', 'backend' or 'task'"));
7326
William Lallemand746e6f32021-10-06 10:57:44 +02007327 if (lua_gettop(L) != 2 || lua_type(L, -1) != LUA_TTABLE)
7328 WILL_LJMP(luaL_error(L, "'get' needs a table as argument"));
7329
William Lallemand4f4f2b72022-02-17 20:00:23 +01007330 hlua_hc = hlua_checkhttpclient(L, 1);
7331
William Lallemand7177a952022-03-03 15:33:12 +01007332 lua_pushnil(L); /* first key */
7333 while (lua_next(L, 2)) {
7334 if (strcmp(lua_tostring(L, -2), "dst") == 0) {
7335 if (httpclient_set_dst(hlua_hc->hc, lua_tostring(L, -1)) < 0)
7336 WILL_LJMP(luaL_error(L, "Can't use the 'dst' argument"));
William Lallemand4f4f2b72022-02-17 20:00:23 +01007337
William Lallemand7177a952022-03-03 15:33:12 +01007338 } else if (strcmp(lua_tostring(L, -2), "url") == 0) {
7339 if (lua_type(L, -1) != LUA_TSTRING)
7340 WILL_LJMP(luaL_error(L, "invalid parameter in 'url', must be a string"));
7341 url_str = lua_tostring(L, -1);
William Lallemand3956c4e2021-09-21 16:25:15 +02007342
William Lallemand7177a952022-03-03 15:33:12 +01007343 } else if (strcmp(lua_tostring(L, -2), "timeout") == 0) {
7344 if (lua_type(L, -1) != LUA_TNUMBER)
7345 WILL_LJMP(luaL_error(L, "invalid parameter in 'timeout', must be a number"));
7346 httpclient_set_timeout(hlua_hc->hc, lua_tointeger(L, -1));
William Lallemandb4a4ef62022-02-23 14:18:16 +01007347
William Lallemand7177a952022-03-03 15:33:12 +01007348 } else if (strcmp(lua_tostring(L, -2), "headers") == 0) {
7349 if (lua_type(L, -1) != LUA_TTABLE)
7350 WILL_LJMP(luaL_error(L, "invalid parameter in 'headers', must be a table"));
7351 hdrs = hlua_httpclient_table_to_hdrs(L);
William Lallemand79416cb2021-09-24 14:51:44 +02007352
William Lallemand7177a952022-03-03 15:33:12 +01007353 } else if (strcmp(lua_tostring(L, -2), "body") == 0) {
7354 if (lua_type(L, -1) != LUA_TSTRING)
7355 WILL_LJMP(luaL_error(L, "invalid parameter in 'body', must be a string"));
7356 body_str = lua_tolstring(L, -1, &buf_len);
William Lallemandbd5739e2021-10-28 15:41:38 +02007357
William Lallemand7177a952022-03-03 15:33:12 +01007358 } else {
7359 WILL_LJMP(luaL_error(L, "'%s' invalid parameter name", lua_tostring(L, -2)));
7360 }
7361 /* removes 'value'; keeps 'key' for next iteration */
7362 lua_pop(L, 1);
7363 }
William Lallemanddec25c32021-10-25 19:48:37 +02007364
William Lallemand746e6f32021-10-06 10:57:44 +02007365 if (!url_str) {
7366 WILL_LJMP(luaL_error(L, "'get' need a 'url' argument"));
7367 return 0;
7368 }
William Lallemand3956c4e2021-09-21 16:25:15 +02007369
William Lallemand10a37362022-03-02 16:18:26 +01007370 hlua_hc->sent = 0;
William Lallemand3956c4e2021-09-21 16:25:15 +02007371
7372 hlua_hc->hc->req.url = istdup(ist(url_str));
William Lallemanddc2cc902021-10-26 11:43:26 +02007373 hlua_hc->hc->req.meth = meth;
William Lallemand3956c4e2021-09-21 16:25:15 +02007374
7375 /* update the httpclient callbacks */
William Lallemandbd5739e2021-10-28 15:41:38 +02007376 hlua_hc->hc->ops.res_stline = hlua_httpclient_cb;
7377 hlua_hc->hc->ops.res_headers = hlua_httpclient_cb;
7378 hlua_hc->hc->ops.res_payload = hlua_httpclient_cb;
William Lallemand8f170c72022-03-15 10:52:07 +01007379 hlua_hc->hc->ops.res_end = hlua_httpclient_cb;
William Lallemand3956c4e2021-09-21 16:25:15 +02007380
William Lallemandbd5739e2021-10-28 15:41:38 +02007381 /* a body is available, it will use the request callback */
7382 if (body_str) {
7383 hlua_hc->hc->ops.req_payload = hlua_httpclient_cb;
7384 }
William Lallemand3956c4e2021-09-21 16:25:15 +02007385
William Lallemandbd5739e2021-10-28 15:41:38 +02007386 ret = httpclient_req_gen(hlua_hc->hc, hlua_hc->hc->req.url, meth, hdrs, IST_NULL);
William Lallemand3956c4e2021-09-21 16:25:15 +02007387
William Lallemand746e6f32021-10-06 10:57:44 +02007388 /* free the temporary headers array */
7389 hdrs_i = hdrs;
7390 while (hdrs_i && isttest(hdrs_i->n)) {
7391 istfree(&hdrs_i->n);
7392 istfree(&hdrs_i->v);
7393 hdrs_i++;
7394 }
7395 ha_free(&hdrs);
7396
7397
William Lallemand6137a9e2021-10-26 15:01:53 +02007398 if (ret != ERR_NONE) {
7399 WILL_LJMP(luaL_error(L, "Can't generate the HTTP request"));
7400 return 0;
7401 }
7402
William Lallemandc2d3db42022-04-26 11:46:13 +02007403 if (!httpclient_start(hlua_hc->hc))
7404 WILL_LJMP(luaL_error(L, "couldn't start the httpclient"));
William Lallemand6137a9e2021-10-26 15:01:53 +02007405
William Lallemandbd5739e2021-10-28 15:41:38 +02007406 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_httpclient_snd_yield, TICK_ETERNITY, 0));
William Lallemand3956c4e2021-09-21 16:25:15 +02007407
William Lallemand3956c4e2021-09-21 16:25:15 +02007408 return 0;
7409}
7410
7411/*
William Lallemanddc2cc902021-10-26 11:43:26 +02007412 * Sends an HTTP HEAD request and wait for a response
7413 *
7414 * httpclient:head(url, headers, payload)
7415 */
7416__LJMP static int hlua_httpclient_head(lua_State *L)
7417{
7418 return hlua_httpclient_send(L, HTTP_METH_HEAD);
7419}
7420
7421/*
7422 * Send an HTTP GET request and wait for a response
7423 *
7424 * httpclient:get(url, headers, payload)
7425 */
7426__LJMP static int hlua_httpclient_get(lua_State *L)
7427{
7428 return hlua_httpclient_send(L, HTTP_METH_GET);
7429
7430}
7431
7432/*
7433 * Sends an HTTP PUT request and wait for a response
7434 *
7435 * httpclient:put(url, headers, payload)
7436 */
7437__LJMP static int hlua_httpclient_put(lua_State *L)
7438{
7439 return hlua_httpclient_send(L, HTTP_METH_PUT);
7440}
7441
7442/*
7443 * Send an HTTP POST request and wait for a response
7444 *
7445 * httpclient:post(url, headers, payload)
7446 */
7447__LJMP static int hlua_httpclient_post(lua_State *L)
7448{
7449 return hlua_httpclient_send(L, HTTP_METH_POST);
7450}
7451
7452
7453/*
7454 * Sends an HTTP DELETE request and wait for a response
7455 *
7456 * httpclient:delete(url, headers, payload)
7457 */
7458__LJMP static int hlua_httpclient_delete(lua_State *L)
7459{
7460 return hlua_httpclient_send(L, HTTP_METH_DELETE);
7461}
7462
7463/*
William Lallemand3956c4e2021-09-21 16:25:15 +02007464 *
7465 *
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007466 * Class TXN
7467 *
7468 *
7469 */
7470
7471/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02007472 * a class stream, otherwise it throws an error.
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007473 */
7474__LJMP static struct hlua_txn *hlua_checktxn(lua_State *L, int ud)
7475{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02007476 return MAY_LJMP(hlua_checkudata(L, ud, class_txn_ref));
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007477}
7478
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007479__LJMP static int hlua_set_var(lua_State *L)
7480{
7481 struct hlua_txn *htxn;
7482 const char *name;
7483 size_t len;
7484 struct sample smp;
7485
Tim Duesterhus4e172c92020-05-19 13:49:42 +02007486 if (lua_gettop(L) < 3 || lua_gettop(L) > 4)
7487 WILL_LJMP(luaL_error(L, "'set_var' needs between 3 and 4 arguments"));
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007488
7489 /* It is useles to retrieve the stream, but this function
7490 * runs only in a stream context.
7491 */
7492 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7493 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
7494
7495 /* Converts the third argument in a sample. */
Amaury Denoyellebc0af6a2020-10-29 17:21:20 +01007496 memset(&smp, 0, sizeof(smp));
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007497 hlua_lua2smp(L, 3, &smp);
7498
7499 /* Store the sample in a variable. */
Willy Tarreau7560dd42016-03-10 16:28:58 +01007500 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
Tim Duesterhus4e172c92020-05-19 13:49:42 +02007501
7502 if (lua_gettop(L) == 4 && lua_toboolean(L, 4))
7503 lua_pushboolean(L, vars_set_by_name_ifexist(name, len, &smp) != 0);
7504 else
7505 lua_pushboolean(L, vars_set_by_name(name, len, &smp) != 0);
7506
Tim Duesterhus84ebc132020-05-19 13:49:41 +02007507 return 1;
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007508}
7509
Christopher Faulet85d79c92016-11-09 16:54:56 +01007510__LJMP static int hlua_unset_var(lua_State *L)
7511{
7512 struct hlua_txn *htxn;
7513 const char *name;
7514 size_t len;
7515 struct sample smp;
7516
7517 MAY_LJMP(check_args(L, 2, "unset_var"));
7518
7519 /* It is useles to retrieve the stream, but this function
7520 * runs only in a stream context.
7521 */
7522 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7523 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
7524
7525 /* Unset the variable. */
7526 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
Tim Duesterhus84ebc132020-05-19 13:49:41 +02007527 lua_pushboolean(L, vars_unset_by_name_ifexist(name, len, &smp) != 0);
7528 return 1;
Christopher Faulet85d79c92016-11-09 16:54:56 +01007529}
7530
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007531__LJMP static int hlua_get_var(lua_State *L)
7532{
7533 struct hlua_txn *htxn;
7534 const char *name;
7535 size_t len;
7536 struct sample smp;
7537
7538 MAY_LJMP(check_args(L, 2, "get_var"));
7539
7540 /* It is useles to retrieve the stream, but this function
7541 * runs only in a stream context.
7542 */
7543 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7544 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
7545
Willy Tarreau7560dd42016-03-10 16:28:58 +01007546 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
Willy Tarreaue352b9d2021-09-03 11:52:38 +02007547 if (!vars_get_by_name(name, len, &smp, NULL)) {
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007548 lua_pushnil(L);
7549 return 1;
7550 }
7551
7552 return hlua_smp2lua(L, &smp);
7553}
7554
Willy Tarreau59551662015-03-10 14:23:13 +01007555__LJMP static int hlua_set_priv(lua_State *L)
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007556{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007557 struct hlua *hlua;
7558
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007559 MAY_LJMP(check_args(L, 2, "set_priv"));
7560
Willy Tarreau87b09662015-04-03 00:22:06 +02007561 /* It is useles to retrieve the stream, but this function
7562 * runs only in a stream context.
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007563 */
7564 MAY_LJMP(hlua_checktxn(L, 1));
Thierry Fournier4234dbd2020-11-28 13:18:23 +01007565
7566 /* Get hlua struct, or NULL if we execute from main lua state */
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007567 hlua = hlua_gethlua(L);
Thierry Fournier4234dbd2020-11-28 13:18:23 +01007568 if (!hlua)
7569 return 0;
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007570
7571 /* Remove previous value. */
Thierry FOURNIERe068b602017-04-26 13:27:05 +02007572 luaL_unref(L, LUA_REGISTRYINDEX, hlua->Mref);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007573
7574 /* Get and store new value. */
7575 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
7576 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
7577
7578 return 0;
7579}
7580
Willy Tarreau59551662015-03-10 14:23:13 +01007581__LJMP static int hlua_get_priv(lua_State *L)
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007582{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007583 struct hlua *hlua;
7584
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007585 MAY_LJMP(check_args(L, 1, "get_priv"));
7586
Willy Tarreau87b09662015-04-03 00:22:06 +02007587 /* It is useles to retrieve the stream, but this function
7588 * runs only in a stream context.
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007589 */
7590 MAY_LJMP(hlua_checktxn(L, 1));
Thierry Fournier4234dbd2020-11-28 13:18:23 +01007591
7592 /* Get hlua struct, or NULL if we execute from main lua state */
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007593 hlua = hlua_gethlua(L);
Thierry Fournier4234dbd2020-11-28 13:18:23 +01007594 if (!hlua) {
7595 lua_pushnil(L);
7596 return 1;
7597 }
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007598
7599 /* Push configuration index in the stack. */
7600 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
7601
7602 return 1;
7603}
7604
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007605/* Create stack entry containing a class TXN. This function
7606 * return 0 if the stack does not contains free slots,
7607 * otherwise it returns 1.
7608 */
Thierry FOURNIERab00df62016-07-14 11:42:37 +02007609static int hlua_txn_new(lua_State *L, struct stream *s, struct proxy *p, int dir, int flags)
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007610{
Willy Tarreaude491382015-04-06 11:04:28 +02007611 struct hlua_txn *htxn;
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007612
7613 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01007614 if (!lua_checkstack(L, 3))
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007615 return 0;
7616
7617 /* NOTE: The allocation never fails. The failure
7618 * throw an error, and the function never returns.
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08007619 * if the throw is not available, the process is aborted.
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007620 */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01007621 /* Create the object: obj[0] = userdata. */
7622 lua_newtable(L);
Willy Tarreaude491382015-04-06 11:04:28 +02007623 htxn = lua_newuserdata(L, sizeof(*htxn));
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01007624 lua_rawseti(L, -2, 0);
7625
Willy Tarreaude491382015-04-06 11:04:28 +02007626 htxn->s = s;
7627 htxn->p = p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01007628 htxn->dir = dir;
Thierry FOURNIERab00df62016-07-14 11:42:37 +02007629 htxn->flags = flags;
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007630
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01007631 /* Create the "f" field that contains a list of fetches. */
7632 lua_pushstring(L, "f");
Thierry FOURNIERca988662015-12-20 18:43:03 +01007633 if (!hlua_fetches_new(L, htxn, HLUA_F_MAY_USE_HTTP))
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01007634 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007635 lua_rawset(L, -3);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01007636
7637 /* Create the "sf" field that contains a list of stringsafe fetches. */
7638 lua_pushstring(L, "sf");
Thierry FOURNIERca988662015-12-20 18:43:03 +01007639 if (!hlua_fetches_new(L, htxn, HLUA_F_MAY_USE_HTTP | HLUA_F_AS_STRING))
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01007640 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007641 lua_rawset(L, -3);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01007642
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007643 /* Create the "c" field that contains a list of converters. */
7644 lua_pushstring(L, "c");
Willy Tarreaude491382015-04-06 11:04:28 +02007645 if (!hlua_converters_new(L, htxn, 0))
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01007646 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007647 lua_rawset(L, -3);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01007648
7649 /* Create the "sc" field that contains a list of stringsafe converters. */
7650 lua_pushstring(L, "sc");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01007651 if (!hlua_converters_new(L, htxn, HLUA_F_AS_STRING))
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007652 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007653 lua_rawset(L, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007654
Thierry FOURNIER397826a2015-03-11 19:39:09 +01007655 /* Create the "req" field that contains the request channel object. */
7656 lua_pushstring(L, "req");
Willy Tarreau2a71af42015-03-10 13:51:50 +01007657 if (!hlua_channel_new(L, &s->req))
Thierry FOURNIER397826a2015-03-11 19:39:09 +01007658 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007659 lua_rawset(L, -3);
Thierry FOURNIER397826a2015-03-11 19:39:09 +01007660
7661 /* Create the "res" field that contains the response channel object. */
7662 lua_pushstring(L, "res");
Willy Tarreau2a71af42015-03-10 13:51:50 +01007663 if (!hlua_channel_new(L, &s->res))
Thierry FOURNIER397826a2015-03-11 19:39:09 +01007664 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007665 lua_rawset(L, -3);
Thierry FOURNIER397826a2015-03-11 19:39:09 +01007666
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007667 /* Creates the HTTP object is the current proxy allows http. */
7668 lua_pushstring(L, "http");
Christopher Faulet1bb6afa2021-03-08 17:57:53 +01007669 if (IS_HTX_STRM(s)) {
Willy Tarreaude491382015-04-06 11:04:28 +02007670 if (!hlua_http_new(L, htxn))
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007671 return 0;
7672 }
7673 else
7674 lua_pushnil(L);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007675 lua_rawset(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007676
Christopher Faulet78c35472020-02-26 17:14:08 +01007677 if ((htxn->flags & HLUA_TXN_CTX_MASK) == HLUA_TXN_FLT_CTX) {
7678 /* HTTPMessage object are created when a lua TXN is created from
7679 * a filter context only
7680 */
7681
7682 /* Creates the HTTP-Request object is the current proxy allows http. */
7683 lua_pushstring(L, "http_req");
7684 if (p->mode == PR_MODE_HTTP) {
7685 if (!hlua_http_msg_new(L, &s->txn->req))
7686 return 0;
7687 }
7688 else
7689 lua_pushnil(L);
7690 lua_rawset(L, -3);
7691
7692 /* Creates the HTTP-Response object is the current proxy allows http. */
7693 lua_pushstring(L, "http_res");
7694 if (p->mode == PR_MODE_HTTP) {
7695 if (!hlua_http_msg_new(L, &s->txn->rsp))
7696 return 0;
7697 }
7698 else
7699 lua_pushnil(L);
7700 lua_rawset(L, -3);
7701 }
7702
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007703 /* Pop a class sesison metatable and affect it to the userdata. */
7704 lua_rawgeti(L, LUA_REGISTRYINDEX, class_txn_ref);
7705 lua_setmetatable(L, -2);
7706
7707 return 1;
7708}
7709
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01007710__LJMP static int hlua_txn_deflog(lua_State *L)
7711{
7712 const char *msg;
7713 struct hlua_txn *htxn;
7714
7715 MAY_LJMP(check_args(L, 2, "deflog"));
7716 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7717 msg = MAY_LJMP(luaL_checkstring(L, 2));
7718
7719 hlua_sendlog(htxn->s->be, htxn->s->logs.level, msg);
7720 return 0;
7721}
7722
7723__LJMP static int hlua_txn_log(lua_State *L)
7724{
7725 int level;
7726 const char *msg;
7727 struct hlua_txn *htxn;
7728
7729 MAY_LJMP(check_args(L, 3, "log"));
7730 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7731 level = MAY_LJMP(luaL_checkinteger(L, 2));
7732 msg = MAY_LJMP(luaL_checkstring(L, 3));
7733
7734 if (level < 0 || level >= NB_LOG_LEVELS)
7735 WILL_LJMP(luaL_argerror(L, 1, "Invalid loglevel."));
7736
7737 hlua_sendlog(htxn->s->be, level, msg);
7738 return 0;
7739}
7740
7741__LJMP static int hlua_txn_log_debug(lua_State *L)
7742{
7743 const char *msg;
7744 struct hlua_txn *htxn;
7745
7746 MAY_LJMP(check_args(L, 2, "Debug"));
7747 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7748 msg = MAY_LJMP(luaL_checkstring(L, 2));
7749 hlua_sendlog(htxn->s->be, LOG_DEBUG, msg);
7750 return 0;
7751}
7752
7753__LJMP static int hlua_txn_log_info(lua_State *L)
7754{
7755 const char *msg;
7756 struct hlua_txn *htxn;
7757
7758 MAY_LJMP(check_args(L, 2, "Info"));
7759 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7760 msg = MAY_LJMP(luaL_checkstring(L, 2));
7761 hlua_sendlog(htxn->s->be, LOG_INFO, msg);
7762 return 0;
7763}
7764
7765__LJMP static int hlua_txn_log_warning(lua_State *L)
7766{
7767 const char *msg;
7768 struct hlua_txn *htxn;
7769
7770 MAY_LJMP(check_args(L, 2, "Warning"));
7771 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7772 msg = MAY_LJMP(luaL_checkstring(L, 2));
7773 hlua_sendlog(htxn->s->be, LOG_WARNING, msg);
7774 return 0;
7775}
7776
7777__LJMP static int hlua_txn_log_alert(lua_State *L)
7778{
7779 const char *msg;
7780 struct hlua_txn *htxn;
7781
7782 MAY_LJMP(check_args(L, 2, "Alert"));
7783 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7784 msg = MAY_LJMP(luaL_checkstring(L, 2));
7785 hlua_sendlog(htxn->s->be, LOG_ALERT, msg);
7786 return 0;
7787}
7788
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01007789__LJMP static int hlua_txn_set_loglevel(lua_State *L)
7790{
7791 struct hlua_txn *htxn;
7792 int ll;
7793
7794 MAY_LJMP(check_args(L, 2, "set_loglevel"));
7795 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7796 ll = MAY_LJMP(luaL_checkinteger(L, 2));
7797
7798 if (ll < 0 || ll > 7)
7799 WILL_LJMP(luaL_argerror(L, 2, "Bad log level. It must be between 0 and 7"));
7800
7801 htxn->s->logs.level = ll;
7802 return 0;
7803}
7804
7805__LJMP static int hlua_txn_set_tos(lua_State *L)
7806{
7807 struct hlua_txn *htxn;
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01007808 int tos;
7809
7810 MAY_LJMP(check_args(L, 2, "set_tos"));
7811 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7812 tos = MAY_LJMP(luaL_checkinteger(L, 2));
7813
Willy Tarreau1a18b542018-12-11 16:37:42 +01007814 conn_set_tos(objt_conn(htxn->s->sess->origin), tos);
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01007815 return 0;
7816}
7817
7818__LJMP static int hlua_txn_set_mark(lua_State *L)
7819{
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01007820 struct hlua_txn *htxn;
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01007821 int mark;
7822
7823 MAY_LJMP(check_args(L, 2, "set_mark"));
7824 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7825 mark = MAY_LJMP(luaL_checkinteger(L, 2));
7826
Lukas Tribus579e3e32019-08-11 18:03:45 +02007827 conn_set_mark(objt_conn(htxn->s->sess->origin), mark);
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01007828 return 0;
7829}
7830
Patrick Hemmer268a7072018-05-11 12:52:31 -04007831__LJMP static int hlua_txn_set_priority_class(lua_State *L)
7832{
7833 struct hlua_txn *htxn;
7834
7835 MAY_LJMP(check_args(L, 2, "set_priority_class"));
7836 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7837 htxn->s->priority_class = queue_limit_class(MAY_LJMP(luaL_checkinteger(L, 2)));
7838 return 0;
7839}
7840
7841__LJMP static int hlua_txn_set_priority_offset(lua_State *L)
7842{
7843 struct hlua_txn *htxn;
7844
7845 MAY_LJMP(check_args(L, 2, "set_priority_offset"));
7846 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7847 htxn->s->priority_offset = queue_limit_offset(MAY_LJMP(luaL_checkinteger(L, 2)));
7848 return 0;
7849}
7850
Christopher Faulet700d9e82020-01-31 12:21:52 +01007851/* Forward the Reply object to the client. This function converts the reply in
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05007852 * HTX an push it to into the response channel. It is response to forward the
Christopher Faulet700d9e82020-01-31 12:21:52 +01007853 * message and terminate the transaction. It returns 1 on success and 0 on
7854 * error. The Reply must be on top of the stack.
7855 */
7856__LJMP static int hlua_txn_forward_reply(lua_State *L, struct stream *s)
7857{
7858 struct htx *htx;
7859 struct htx_sl *sl;
7860 struct h1m h1m;
7861 const char *status, *reason, *body;
7862 size_t status_len, reason_len, body_len;
7863 int ret, code, flags;
7864
7865 code = 200;
7866 status = "200";
7867 status_len = 3;
7868 ret = lua_getfield(L, -1, "status");
7869 if (ret == LUA_TNUMBER) {
7870 code = lua_tointeger(L, -1);
7871 status = lua_tolstring(L, -1, &status_len);
7872 }
7873 lua_pop(L, 1);
7874
7875 reason = http_get_reason(code);
7876 reason_len = strlen(reason);
7877 ret = lua_getfield(L, -1, "reason");
7878 if (ret == LUA_TSTRING)
7879 reason = lua_tolstring(L, -1, &reason_len);
7880 lua_pop(L, 1);
7881
7882 body = NULL;
7883 body_len = 0;
7884 ret = lua_getfield(L, -1, "body");
7885 if (ret == LUA_TSTRING)
7886 body = lua_tolstring(L, -1, &body_len);
7887 lua_pop(L, 1);
7888
7889 /* Prepare the response before inserting the headers */
7890 h1m_init_res(&h1m);
7891 htx = htx_from_buf(&s->res.buf);
7892 channel_htx_truncate(&s->res, htx);
7893 if (s->txn->req.flags & HTTP_MSGF_VER_11) {
7894 flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11);
7895 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.1"),
7896 ist2(status, status_len), ist2(reason, reason_len));
7897 }
7898 else {
7899 flags = HTX_SL_F_IS_RESP;
7900 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.0"),
7901 ist2(status, status_len), ist2(reason, reason_len));
7902 }
7903 if (!sl)
7904 goto fail;
7905 sl->info.res.status = code;
7906
7907 /* Push in the stack the "headers" entry. */
7908 ret = lua_getfield(L, -1, "headers");
7909 if (ret != LUA_TTABLE)
7910 goto skip_headers;
7911
7912 lua_pushnil(L);
7913 while (lua_next(L, -2) != 0) {
7914 struct ist name, value;
7915 const char *n, *v;
7916 size_t nlen, vlen;
7917
7918 if (!lua_isstring(L, -2) || !lua_istable(L, -1)) {
7919 /* Skip element if the key is not a string or if the value is not a table */
7920 goto next_hdr;
7921 }
7922
7923 n = lua_tolstring(L, -2, &nlen);
7924 name = ist2(n, nlen);
7925 if (isteqi(name, ist("content-length"))) {
7926 /* Always skip content-length header. It will be added
7927 * later with the correct len
7928 */
7929 goto next_hdr;
7930 }
7931
7932 /* Loop on header's values */
7933 lua_pushnil(L);
7934 while (lua_next(L, -2)) {
7935 if (!lua_isstring(L, -1)) {
7936 /* Skip the value if it is not a string */
7937 goto next_value;
7938 }
7939
7940 v = lua_tolstring(L, -1, &vlen);
7941 value = ist2(v, vlen);
7942
7943 if (isteqi(name, ist("transfer-encoding")))
7944 h1_parse_xfer_enc_header(&h1m, value);
7945 if (!htx_add_header(htx, ist2(n, nlen), ist2(v, vlen)))
7946 goto fail;
7947
7948 next_value:
7949 lua_pop(L, 1);
7950 }
7951
7952 next_hdr:
7953 lua_pop(L, 1);
7954 }
7955 skip_headers:
7956 lua_pop(L, 1);
7957
7958 /* Update h1m flags: CLEN is set if CHNK is not present */
7959 if (!(h1m.flags & H1_MF_CHNK)) {
7960 const char *clen = ultoa(body_len);
7961
7962 h1m.flags |= H1_MF_CLEN;
7963 if (!htx_add_header(htx, ist("content-length"), ist(clen)))
7964 goto fail;
7965 }
7966 if (h1m.flags & (H1_MF_CLEN|H1_MF_CHNK))
7967 h1m.flags |= H1_MF_XFER_LEN;
7968
7969 /* Update HTX start-line flags */
7970 if (h1m.flags & H1_MF_XFER_ENC)
7971 flags |= HTX_SL_F_XFER_ENC;
7972 if (h1m.flags & H1_MF_XFER_LEN) {
7973 flags |= HTX_SL_F_XFER_LEN;
7974 if (h1m.flags & H1_MF_CHNK)
7975 flags |= HTX_SL_F_CHNK;
7976 else if (h1m.flags & H1_MF_CLEN)
7977 flags |= HTX_SL_F_CLEN;
7978 if (h1m.body_len == 0)
7979 flags |= HTX_SL_F_BODYLESS;
7980 }
7981 sl->flags |= flags;
7982
7983
7984 if (!htx_add_endof(htx, HTX_BLK_EOH) ||
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01007985 (body_len && !htx_add_data_atonce(htx, ist2(body, body_len))))
Christopher Faulet700d9e82020-01-31 12:21:52 +01007986 goto fail;
7987
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01007988 htx->flags |= HTX_FL_EOM;
7989
Christopher Faulet700d9e82020-01-31 12:21:52 +01007990 /* Now, forward the response and terminate the transaction */
7991 s->txn->status = code;
7992 htx_to_buf(htx, &s->res.buf);
7993 if (!http_forward_proxy_resp(s, 1))
7994 goto fail;
7995
7996 return 1;
7997
7998 fail:
7999 channel_htx_truncate(&s->res, htx);
8000 return 0;
8001}
8002
8003/* Terminate a transaction if called from a lua action. For TCP streams,
8004 * processing is just aborted. Nothing is returned to the client and all
8005 * arguments are ignored. For HTTP streams, if a reply is passed as argument, it
8006 * is forwarded to the client before terminating the transaction. On success,
8007 * the function exits with ACT_RET_DONE code. If an error occurred, it exits
8008 * with ACT_RET_ERR code. If this function is not called from a lua action, it
8009 * just exits without any processing.
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01008010 */
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02008011__LJMP static int hlua_txn_done(lua_State *L)
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01008012{
Willy Tarreaub2ccb562015-04-06 11:11:15 +02008013 struct hlua_txn *htxn;
Christopher Faulet700d9e82020-01-31 12:21:52 +01008014 struct stream *s;
8015 int finst;
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01008016
Willy Tarreaub2ccb562015-04-06 11:11:15 +02008017 htxn = MAY_LJMP(hlua_checktxn(L, 1));
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01008018
Christopher Faulet700d9e82020-01-31 12:21:52 +01008019 /* If the flags NOTERM is set, we cannot terminate the session, so we
8020 * just end the execution of the current lua code. */
8021 if (htxn->flags & HLUA_TXN_NOTERM)
Thierry FOURNIERab00df62016-07-14 11:42:37 +02008022 WILL_LJMP(hlua_done(L));
Thierry FOURNIERab00df62016-07-14 11:42:37 +02008023
Christopher Faulet700d9e82020-01-31 12:21:52 +01008024 s = htxn->s;
Christopher Fauletd8f0e072020-02-25 09:45:51 +01008025 if (!IS_HTX_STRM(htxn->s)) {
Christopher Faulet700d9e82020-01-31 12:21:52 +01008026 struct channel *req = &s->req;
8027 struct channel *res = &s->res;
Willy Tarreau81389672015-03-10 12:03:52 +01008028
Christopher Faulet700d9e82020-01-31 12:21:52 +01008029 channel_auto_read(req);
8030 channel_abort(req);
8031 channel_auto_close(req);
8032 channel_erase(req);
8033
8034 res->wex = tick_add_ifset(now_ms, res->wto);
8035 channel_auto_read(res);
8036 channel_auto_close(res);
8037 channel_shutr_now(res);
8038
8039 finst = ((htxn->dir == SMP_OPT_DIR_REQ) ? SF_FINST_R : SF_FINST_D);
8040 goto done;
Christopher Fauletfe6a71b2019-07-26 16:40:24 +02008041 }
Thierry FOURNIER10ec2142015-08-24 17:23:45 +02008042
Christopher Faulet700d9e82020-01-31 12:21:52 +01008043 if (lua_gettop(L) == 1 || !lua_istable(L, 2)) {
8044 /* No reply or invalid reply */
8045 s->txn->status = 0;
8046 http_reply_and_close(s, 0, NULL);
8047 }
8048 else {
8049 /* Remove extra args to have the reply on top of the stack */
8050 if (lua_gettop(L) > 2)
8051 lua_pop(L, lua_gettop(L) - 2);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01008052
Christopher Faulet700d9e82020-01-31 12:21:52 +01008053 if (!hlua_txn_forward_reply(L, s)) {
8054 if (!(s->flags & SF_ERR_MASK))
8055 s->flags |= SF_ERR_PRXCOND;
8056 lua_pushinteger(L, ACT_RET_ERR);
8057 WILL_LJMP(hlua_done(L));
8058 return 0; /* Never reached */
8059 }
Christopher Faulet4d0e2632019-07-16 10:52:40 +02008060 }
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02008061
Christopher Faulet700d9e82020-01-31 12:21:52 +01008062 finst = ((htxn->dir == SMP_OPT_DIR_REQ) ? SF_FINST_R : SF_FINST_H);
8063 if (htxn->dir == SMP_OPT_DIR_REQ) {
8064 /* let's log the request time */
8065 s->logs.tv_request = now;
8066 if (s->sess->fe == s->be) /* report it if the request was intercepted by the frontend */
Willy Tarreau4781b152021-04-06 13:53:36 +02008067 _HA_ATOMIC_INC(&s->sess->fe->fe_counters.intercepted_req);
Christopher Faulet700d9e82020-01-31 12:21:52 +01008068 }
Christopher Fauletfe6a71b2019-07-26 16:40:24 +02008069
Christopher Faulet700d9e82020-01-31 12:21:52 +01008070 done:
8071 if (!(s->flags & SF_ERR_MASK))
8072 s->flags |= SF_ERR_LOCAL;
8073 if (!(s->flags & SF_FINST_MASK))
8074 s->flags |= finst;
Christopher Fauletfe6a71b2019-07-26 16:40:24 +02008075
Christopher Faulete48d1dc2021-08-13 14:11:17 +02008076 if ((htxn->flags & HLUA_TXN_CTX_MASK) == HLUA_TXN_FLT_CTX)
8077 lua_pushinteger(L, -1);
8078 else
8079 lua_pushinteger(L, ACT_RET_ABRT);
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02008080 WILL_LJMP(hlua_done(L));
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01008081 return 0;
8082}
8083
Christopher Faulet700d9e82020-01-31 12:21:52 +01008084/*
8085 *
8086 *
8087 * Class REPLY
8088 *
8089 *
8090 */
8091
8092/* Pushes the TXN reply onto the top of the stack. If the stask does not have a
8093 * free slots, the function fails and returns 0;
8094 */
8095static int hlua_txn_reply_new(lua_State *L)
8096{
8097 struct hlua_txn *htxn;
8098 const char *reason, *body = NULL;
8099 int ret, status;
8100
8101 htxn = MAY_LJMP(hlua_checktxn(L, 1));
Christopher Fauletd8f0e072020-02-25 09:45:51 +01008102 if (!IS_HTX_STRM(htxn->s)) {
Christopher Faulet700d9e82020-01-31 12:21:52 +01008103 hlua_pusherror(L, "txn object is not an HTTP transaction.");
8104 WILL_LJMP(lua_error(L));
8105 }
8106
8107 /* Default value */
8108 status = 200;
8109 reason = http_get_reason(status);
8110
8111 if (lua_istable(L, 2)) {
8112 /* load status and reason from the table argument at index 2 */
8113 ret = lua_getfield(L, 2, "status");
8114 if (ret == LUA_TNIL)
8115 goto reason;
8116 else if (ret != LUA_TNUMBER) {
8117 /* invalid status: ignore the reason */
8118 goto body;
8119 }
8120 status = lua_tointeger(L, -1);
8121
8122 reason:
8123 lua_pop(L, 1); /* restore the stack: remove status */
8124 ret = lua_getfield(L, 2, "reason");
8125 if (ret == LUA_TSTRING)
8126 reason = lua_tostring(L, -1);
8127
8128 body:
8129 lua_pop(L, 1); /* restore the stack: remove invalid status or reason */
8130 ret = lua_getfield(L, 2, "body");
8131 if (ret == LUA_TSTRING)
8132 body = lua_tostring(L, -1);
8133 lua_pop(L, 1); /* restore the stack: remove body */
8134 }
8135
8136 /* Create the Reply table */
8137 lua_newtable(L);
8138
8139 /* Add status element */
8140 lua_pushstring(L, "status");
8141 lua_pushinteger(L, status);
8142 lua_settable(L, -3);
8143
8144 /* Add reason element */
8145 reason = http_get_reason(status);
8146 lua_pushstring(L, "reason");
8147 lua_pushstring(L, reason);
8148 lua_settable(L, -3);
8149
8150 /* Add body element, nil if undefined */
8151 lua_pushstring(L, "body");
8152 if (body)
8153 lua_pushstring(L, body);
8154 else
8155 lua_pushnil(L);
8156 lua_settable(L, -3);
8157
8158 /* Add headers element */
8159 lua_pushstring(L, "headers");
8160 lua_newtable(L);
8161
8162 /* stack: [ txn, <Arg:table>, <Reply:table>, "headers", <headers:table> ] */
8163 if (lua_istable(L, 2)) {
8164 /* load headers from the table argument at index 2. If it is a table, copy it. */
8165 ret = lua_getfield(L, 2, "headers");
8166 if (ret == LUA_TTABLE) {
8167 /* stack: [ ... <headers:table>, <table> ] */
8168 lua_pushnil(L);
8169 while (lua_next(L, -2) != 0) {
8170 /* stack: [ ... <headers:table>, <table>, k, v] */
8171 if (!lua_isstring(L, -1) && !lua_istable(L, -1)) {
8172 /* invalid value type, skip it */
8173 lua_pop(L, 1);
8174 continue;
8175 }
8176
8177
8178 /* Duplicate the key and swap it with the value. */
8179 lua_pushvalue(L, -2);
8180 lua_insert(L, -2);
8181 /* stack: [ ... <headers:table>, <table>, k, k, v ] */
8182
8183 lua_newtable(L);
8184 lua_insert(L, -2);
8185 /* stack: [ ... <headers:table>, <table>, k, k, <inner:table>, v ] */
8186
8187 if (lua_isstring(L, -1)) {
8188 /* push the value in the inner table */
8189 lua_rawseti(L, -2, 1);
8190 }
8191 else { /* table */
8192 lua_pushnil(L);
8193 while (lua_next(L, -2) != 0) {
8194 /* stack: [ ... <headers:table>, <table>, k, k, <inner:table>, <v:table>, k2, v2 ] */
8195 if (!lua_isstring(L, -1)) {
8196 /* invalid value type, skip it*/
8197 lua_pop(L, 1);
8198 continue;
8199 }
8200 /* push the value in the inner table */
8201 lua_rawseti(L, -4, lua_rawlen(L, -4) + 1);
8202 /* stack: [ ... <headers:table>, <table>, k, k, <inner:table>, <v:table>, k2 ] */
8203 }
8204 lua_pop(L, 1);
8205 /* stack: [ ... <headers:table>, <table>, k, k, <inner:table> ] */
8206 }
8207
8208 /* push (k,v) on the stack in the headers table:
8209 * stack: [ ... <headers:table>, <table>, k, k, v ]
8210 */
8211 lua_settable(L, -5);
8212 /* stack: [ ... <headers:table>, <table>, k ] */
8213 }
8214 }
8215 lua_pop(L, 1);
8216 }
8217 /* stack: [ txn, <Arg:table>, <Reply:table>, "headers", <headers:table> ] */
8218 lua_settable(L, -3);
8219 /* stack: [ txn, <Arg:table>, <Reply:table> ] */
8220
8221 /* Pop a class sesison metatable and affect it to the userdata. */
8222 lua_rawgeti(L, LUA_REGISTRYINDEX, class_txn_reply_ref);
8223 lua_setmetatable(L, -2);
8224 return 1;
8225}
8226
8227/* Set the reply status code, and optionally the reason. If no reason is
8228 * provided, the default one corresponding to the status code is used.
8229 */
8230__LJMP static int hlua_txn_reply_set_status(lua_State *L)
8231{
8232 int status = MAY_LJMP(luaL_checkinteger(L, 2));
8233 const char *reason = MAY_LJMP(luaL_optlstring(L, 3, NULL, NULL));
8234
8235 /* First argument (self) must be a table */
8236 luaL_checktype(L, 1, LUA_TTABLE);
8237
8238 if (status < 100 || status > 599) {
8239 lua_pushboolean(L, 0);
8240 return 1;
8241 }
8242 if (!reason)
8243 reason = http_get_reason(status);
8244
8245 lua_pushinteger(L, status);
8246 lua_setfield(L, 1, "status");
8247
8248 lua_pushstring(L, reason);
8249 lua_setfield(L, 1, "reason");
8250
8251 lua_pushboolean(L, 1);
8252 return 1;
8253}
8254
8255/* Add a header into the reply object. Each header name is associated to an
8256 * array of values in the "headers" table. If the header name is not found, a
8257 * new entry is created.
8258 */
8259__LJMP static int hlua_txn_reply_add_header(lua_State *L)
8260{
8261 const char *name = MAY_LJMP(luaL_checkstring(L, 2));
8262 const char *value = MAY_LJMP(luaL_checkstring(L, 3));
8263 int ret;
8264
8265 /* First argument (self) must be a table */
8266 luaL_checktype(L, 1, LUA_TTABLE);
8267
8268 /* Push in the stack the "headers" entry. */
8269 ret = lua_getfield(L, 1, "headers");
8270 if (ret != LUA_TTABLE) {
8271 hlua_pusherror(L, "Reply['headers'] is expected to a an array. %s found", lua_typename(L, ret));
8272 WILL_LJMP(lua_error(L));
8273 }
8274
8275 /* check if the header is already registered. If not, register it. */
8276 ret = lua_getfield(L, -1, name);
8277 if (ret == LUA_TNIL) {
8278 /* Entry not found. */
8279 lua_pop(L, 1); /* remove the nil. The "headers" table is the top of the stack. */
8280
8281 /* Insert the new header name in the array in the top of the stack.
8282 * It left the new array in the top of the stack.
8283 */
8284 lua_newtable(L);
8285 lua_pushstring(L, name);
8286 lua_pushvalue(L, -2);
8287 lua_settable(L, -4);
8288 }
8289 else if (ret != LUA_TTABLE) {
8290 hlua_pusherror(L, "Reply['headers']['%s'] is expected to be an array. %s found", name, lua_typename(L, ret));
8291 WILL_LJMP(lua_error(L));
8292 }
8293
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -07008294 /* Now the top of thestack is an array of values. We push
Christopher Faulet700d9e82020-01-31 12:21:52 +01008295 * the header value as new entry.
8296 */
8297 lua_pushstring(L, value);
8298 ret = lua_rawlen(L, -2);
8299 lua_rawseti(L, -2, ret + 1);
8300
8301 lua_pushboolean(L, 1);
8302 return 1;
8303}
8304
8305/* Remove all occurrences of a given header name. */
8306__LJMP static int hlua_txn_reply_del_header(lua_State *L)
8307{
8308 const char *name = MAY_LJMP(luaL_checkstring(L, 2));
8309 int ret;
8310
8311 /* First argument (self) must be a table */
8312 luaL_checktype(L, 1, LUA_TTABLE);
8313
8314 /* Push in the stack the "headers" entry. */
8315 ret = lua_getfield(L, 1, "headers");
8316 if (ret != LUA_TTABLE) {
8317 hlua_pusherror(L, "Reply['headers'] is expected to be an array. %s found", lua_typename(L, ret));
8318 WILL_LJMP(lua_error(L));
8319 }
8320
8321 lua_pushstring(L, name);
8322 lua_pushnil(L);
8323 lua_settable(L, -3);
8324
8325 lua_pushboolean(L, 1);
8326 return 1;
8327}
8328
8329/* Set the reply's body. Overwrite any existing entry. */
8330__LJMP static int hlua_txn_reply_set_body(lua_State *L)
8331{
8332 const char *payload = MAY_LJMP(luaL_checkstring(L, 2));
8333
8334 /* First argument (self) must be a table */
8335 luaL_checktype(L, 1, LUA_TTABLE);
8336
8337 lua_pushstring(L, payload);
8338 lua_setfield(L, 1, "body");
8339
8340 lua_pushboolean(L, 1);
8341 return 1;
8342}
8343
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01008344__LJMP static int hlua_log(lua_State *L)
8345{
8346 int level;
8347 const char *msg;
8348
8349 MAY_LJMP(check_args(L, 2, "log"));
8350 level = MAY_LJMP(luaL_checkinteger(L, 1));
8351 msg = MAY_LJMP(luaL_checkstring(L, 2));
8352
8353 if (level < 0 || level >= NB_LOG_LEVELS)
8354 WILL_LJMP(luaL_argerror(L, 1, "Invalid loglevel."));
8355
8356 hlua_sendlog(NULL, level, msg);
8357 return 0;
8358}
8359
8360__LJMP static int hlua_log_debug(lua_State *L)
8361{
8362 const char *msg;
8363
8364 MAY_LJMP(check_args(L, 1, "debug"));
8365 msg = MAY_LJMP(luaL_checkstring(L, 1));
8366 hlua_sendlog(NULL, LOG_DEBUG, msg);
8367 return 0;
8368}
8369
8370__LJMP static int hlua_log_info(lua_State *L)
8371{
8372 const char *msg;
8373
8374 MAY_LJMP(check_args(L, 1, "info"));
8375 msg = MAY_LJMP(luaL_checkstring(L, 1));
8376 hlua_sendlog(NULL, LOG_INFO, msg);
8377 return 0;
8378}
8379
8380__LJMP static int hlua_log_warning(lua_State *L)
8381{
8382 const char *msg;
8383
8384 MAY_LJMP(check_args(L, 1, "warning"));
8385 msg = MAY_LJMP(luaL_checkstring(L, 1));
8386 hlua_sendlog(NULL, LOG_WARNING, msg);
8387 return 0;
8388}
8389
8390__LJMP static int hlua_log_alert(lua_State *L)
8391{
8392 const char *msg;
8393
8394 MAY_LJMP(check_args(L, 1, "alert"));
8395 msg = MAY_LJMP(luaL_checkstring(L, 1));
8396 hlua_sendlog(NULL, LOG_ALERT, msg);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01008397 return 0;
8398}
8399
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01008400__LJMP static int hlua_sleep_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008401{
8402 int wakeup_ms = lua_tointeger(L, -1);
Willy Tarreau12c02702021-09-30 16:12:31 +02008403 if (!tick_is_expired(wakeup_ms, now_ms))
Willy Tarreau9635e032018-10-16 17:52:55 +02008404 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008405 return 0;
8406}
8407
8408__LJMP static int hlua_sleep(lua_State *L)
8409{
8410 unsigned int delay;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008411 unsigned int wakeup_ms;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008412
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008413 MAY_LJMP(check_args(L, 1, "sleep"));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008414
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01008415 delay = MAY_LJMP(luaL_checkinteger(L, 1)) * 1000;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008416 wakeup_ms = tick_add(now_ms, delay);
8417 lua_pushinteger(L, wakeup_ms);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008418
Willy Tarreau9635e032018-10-16 17:52:55 +02008419 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008420 return 0;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008421}
8422
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008423__LJMP static int hlua_msleep(lua_State *L)
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008424{
8425 unsigned int delay;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008426 unsigned int wakeup_ms;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008427
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008428 MAY_LJMP(check_args(L, 1, "msleep"));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008429
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01008430 delay = MAY_LJMP(luaL_checkinteger(L, 1));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008431 wakeup_ms = tick_add(now_ms, delay);
8432 lua_pushinteger(L, wakeup_ms);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008433
Willy Tarreau9635e032018-10-16 17:52:55 +02008434 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008435 return 0;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008436}
8437
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01008438/* This functionis an LUA binding. it permits to give back
8439 * the hand at the HAProxy scheduler. It is used when the
8440 * LUA processing consumes a lot of time.
8441 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01008442__LJMP static int hlua_yield_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008443{
8444 return 0;
8445}
8446
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01008447__LJMP static int hlua_yield(lua_State *L)
8448{
Willy Tarreau9635e032018-10-16 17:52:55 +02008449 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_yield_yield, TICK_ETERNITY, HLUA_CTRLYIELD));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008450 return 0;
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01008451}
8452
Thierry FOURNIER37196f42015-02-16 19:34:56 +01008453/* This function change the nice of the currently executed
8454 * task. It is used set low or high priority at the current
8455 * task.
8456 */
Willy Tarreau59551662015-03-10 14:23:13 +01008457__LJMP static int hlua_set_nice(lua_State *L)
Thierry FOURNIER37196f42015-02-16 19:34:56 +01008458{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01008459 struct hlua *hlua;
8460 int nice;
Thierry FOURNIER37196f42015-02-16 19:34:56 +01008461
Willy Tarreau80f5fae2015-02-27 16:38:20 +01008462 MAY_LJMP(check_args(L, 1, "set_nice"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01008463 nice = MAY_LJMP(luaL_checkinteger(L, 1));
Thierry FOURNIER37196f42015-02-16 19:34:56 +01008464
Thierry Fournier4234dbd2020-11-28 13:18:23 +01008465 /* Get hlua struct, or NULL if we execute from main lua state */
8466 hlua = hlua_gethlua(L);
8467
8468 /* If the task is not set, I'm in a start mode. */
Thierry FOURNIER37196f42015-02-16 19:34:56 +01008469 if (!hlua || !hlua->task)
8470 return 0;
8471
8472 if (nice < -1024)
8473 nice = -1024;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01008474 else if (nice > 1024)
Thierry FOURNIER37196f42015-02-16 19:34:56 +01008475 nice = 1024;
8476
8477 hlua->task->nice = nice;
8478 return 0;
8479}
8480
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08008481/* This function is used as a callback of a task. It is called by the
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008482 * HAProxy task subsystem when the task is awaked. The LUA runtime can
8483 * return an E_AGAIN signal, the emmiter of this signal must set a
8484 * signal to wake the task.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008485 *
8486 * Task wrapper are longjmp safe because the only one Lua code
8487 * executed is the safe hlua_ctx_resume();
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008488 */
Willy Tarreau144f84a2021-03-02 16:09:26 +01008489struct task *hlua_process_task(struct task *task, void *context, unsigned int state)
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008490{
Olivier Houchard9f6af332018-05-25 14:04:04 +02008491 struct hlua *hlua = context;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008492 enum hlua_exec status;
8493
Willy Tarreau6ef52f42022-06-15 14:19:48 +02008494 if (task->tid < 0)
8495 task->tid = tid;
8496
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008497 /* If it is the first call to the task, we must initialize the
8498 * execution timeouts.
8499 */
8500 if (!HLUA_IS_RUNNING(hlua))
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02008501 hlua->max_time = hlua_timeout_task;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008502
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008503 /* Execute the Lua code. */
8504 status = hlua_ctx_resume(hlua, 1);
8505
8506 switch (status) {
8507 /* finished or yield */
8508 case HLUA_E_OK:
8509 hlua_ctx_destroy(hlua);
Olivier Houchard3f795f72019-04-17 22:51:06 +02008510 task_destroy(task);
Tim Duesterhuscd235c62018-04-24 13:56:01 +02008511 task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008512 break;
8513
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01008514 case HLUA_E_AGAIN: /* co process or timeout wake me later. */
Thierry FOURNIERcb146882017-12-10 17:10:57 +01008515 notification_gc(&hlua->com);
PiBa-NLfe971b32018-05-02 22:27:14 +02008516 task->expire = hlua->wake_time;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008517 break;
8518
8519 /* finished with error. */
8520 case HLUA_E_ERRMSG:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008521 SEND_ERR(NULL, "Lua task: %s.\n", lua_tostring(hlua->T, -1));
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008522 hlua_ctx_destroy(hlua);
Olivier Houchard3f795f72019-04-17 22:51:06 +02008523 task_destroy(task);
Emeric Brun253e53e2017-10-17 18:58:40 +02008524 task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008525 break;
8526
8527 case HLUA_E_ERR:
8528 default:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008529 SEND_ERR(NULL, "Lua task: unknown error.\n");
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008530 hlua_ctx_destroy(hlua);
Olivier Houchard3f795f72019-04-17 22:51:06 +02008531 task_destroy(task);
Emeric Brun253e53e2017-10-17 18:58:40 +02008532 task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008533 break;
8534 }
Emeric Brun253e53e2017-10-17 18:58:40 +02008535 return task;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008536}
8537
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008538/* This function is an LUA binding that register LUA function to be
8539 * executed after the HAProxy configuration parsing and before the
8540 * HAProxy scheduler starts. This function expect only one LUA
8541 * argument that is a function. This function returns nothing, but
8542 * throws if an error is encountered.
8543 */
8544__LJMP static int hlua_register_init(lua_State *L)
8545{
8546 struct hlua_init_function *init;
8547 int ref;
8548
8549 MAY_LJMP(check_args(L, 1, "register_init"));
8550
8551 ref = MAY_LJMP(hlua_checkfunction(L, 1));
8552
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02008553 init = calloc(1, sizeof(*init));
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008554 if (!init)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01008555 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008556
8557 init->function_ref = ref;
Willy Tarreau2b718102021-04-21 07:32:39 +02008558 LIST_APPEND(&hlua_init_functions[hlua_state_id], &init->l);
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008559 return 0;
8560}
8561
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008562/* This functio is an LUA binding. It permits to register a task
8563 * executed in parallel of the main HAroxy activity. The task is
8564 * created and it is set in the HAProxy scheduler. It can be called
8565 * from the "init" section, "post init" or during the runtime.
8566 *
8567 * Lua prototype:
8568 *
8569 * <none> core.register_task(<function>)
8570 */
8571static int hlua_register_task(lua_State *L)
8572{
Christopher Faulet5294ec02021-04-12 12:24:47 +02008573 struct hlua *hlua = NULL;
8574 struct task *task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008575 int ref;
Thierry Fournier021d9862020-11-28 23:42:03 +01008576 int state_id;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008577
8578 MAY_LJMP(check_args(L, 1, "register_task"));
8579
8580 ref = MAY_LJMP(hlua_checkfunction(L, 1));
8581
Thierry Fournier75fc0292020-11-28 13:18:56 +01008582 /* Get the reference state. If the reference is NULL, L is the master
8583 * state, otherwise hlua->T is.
8584 */
8585 hlua = hlua_gethlua(L);
8586 if (hlua)
Thierry Fournier021d9862020-11-28 23:42:03 +01008587 /* we are in runtime processing */
8588 state_id = hlua->state_id;
Thierry Fournier75fc0292020-11-28 13:18:56 +01008589 else
Thierry Fournier021d9862020-11-28 23:42:03 +01008590 /* we are in initialization mode */
Thierry Fournierc7492592020-11-28 23:57:24 +01008591 state_id = hlua_state_id;
Thierry Fournier75fc0292020-11-28 13:18:56 +01008592
Willy Tarreaubafbe012017-11-24 17:34:44 +01008593 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008594 if (!hlua)
Christopher Faulet5294ec02021-04-12 12:24:47 +02008595 goto alloc_error;
Christopher Faulet1e8433f2021-03-24 15:03:01 +01008596 HLUA_INIT(hlua);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008597
Thierry Fournier59f11be2020-11-29 00:37:41 +01008598 /* We are in the common lua state, execute the task anywhere,
8599 * otherwise, inherit the current thread identifier
8600 */
8601 if (state_id == 0)
Willy Tarreaubeeabf52021-10-01 18:23:30 +02008602 task = task_new_anywhere();
Thierry Fournier59f11be2020-11-29 00:37:41 +01008603 else
Willy Tarreaubeeabf52021-10-01 18:23:30 +02008604 task = task_new_here();
Willy Tarreaue09101e2018-10-16 17:37:12 +02008605 if (!task)
Christopher Faulet5294ec02021-04-12 12:24:47 +02008606 goto alloc_error;
Willy Tarreaue09101e2018-10-16 17:37:12 +02008607
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008608 task->context = hlua;
8609 task->process = hlua_process_task;
8610
Thierry Fournier021d9862020-11-28 23:42:03 +01008611 if (!hlua_ctx_init(hlua, state_id, task, 1))
Christopher Faulet5294ec02021-04-12 12:24:47 +02008612 goto alloc_error;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008613
8614 /* Restore the function in the stack. */
8615 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ref);
8616 hlua->nargs = 0;
8617
8618 /* Schedule task. */
Willy Tarreaue3957f82021-09-30 16:17:37 +02008619 task_wakeup(task, TASK_WOKEN_INIT);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008620
8621 return 0;
Christopher Faulet5294ec02021-04-12 12:24:47 +02008622
8623 alloc_error:
8624 task_destroy(task);
8625 hlua_ctx_destroy(hlua);
8626 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
8627 return 0; /* Never reached */
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008628}
8629
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008630/* Wrapper called by HAProxy to execute an LUA converter. This wrapper
8631 * doesn't allow "yield" functions because the HAProxy engine cannot
8632 * resume converters.
8633 */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02008634static int hlua_sample_conv_wrapper(const struct arg *arg_p, struct sample *smp, void *private)
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008635{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02008636 struct hlua_function *fcn = private;
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02008637 struct stream *stream = smp->strm;
Thierry Fournierfd107a22016-02-19 19:57:23 +01008638 const char *error;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008639
Willy Tarreaube508f12016-03-10 11:47:01 +01008640 if (!stream)
8641 return 0;
8642
Willy Tarreau87b09662015-04-03 00:22:06 +02008643 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01008644 * Lua context can be not initialized. This behavior
8645 * permits to save performances because a systematic
8646 * Lua initialization cause 5% performances loss.
8647 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008648 if (!stream->hlua) {
Christopher Faulet1e8433f2021-03-24 15:03:01 +01008649 struct hlua *hlua;
8650
8651 hlua = pool_alloc(pool_head_hlua);
8652 if (!hlua) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008653 SEND_ERR(stream->be, "Lua converter '%s': can't initialize Lua context.\n", fcn->name);
8654 return 0;
8655 }
Christopher Faulet1e8433f2021-03-24 15:03:01 +01008656 HLUA_INIT(hlua);
8657 stream->hlua = hlua;
Thierry Fournierc7492592020-11-28 23:57:24 +01008658 if (!hlua_ctx_init(stream->hlua, fcn_ref_to_stack_id(fcn), stream->task, 0)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008659 SEND_ERR(stream->be, "Lua converter '%s': can't initialize Lua context.\n", fcn->name);
8660 return 0;
8661 }
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01008662 }
8663
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008664 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008665 if (!HLUA_IS_RUNNING(stream->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008666
8667 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008668 if (!SET_SAFE_LJMP(stream->hlua)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008669 if (lua_type(stream->hlua->T, -1) == LUA_TSTRING)
8670 error = lua_tostring(stream->hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +01008671 else
8672 error = "critical error";
8673 SEND_ERR(stream->be, "Lua converter '%s': %s.\n", fcn->name, error);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008674 return 0;
8675 }
8676
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008677 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008678 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008679 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008680 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008681 return 0;
8682 }
8683
8684 /* Restore the function in the stack. */
Thierry Fournierc7492592020-11-28 23:57:24 +01008685 lua_rawgeti(stream->hlua->T, LUA_REGISTRYINDEX, fcn->function_ref[stream->hlua->state_id]);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008686
8687 /* convert input sample and pust-it in the stack. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008688 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008689 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008690 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008691 return 0;
8692 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008693 hlua_smp2lua(stream->hlua->T, smp);
8694 stream->hlua->nargs = 1;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008695
8696 /* push keywords in the stack. */
8697 if (arg_p) {
8698 for (; arg_p->type != ARGT_STOP; arg_p++) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008699 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008700 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008701 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008702 return 0;
8703 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008704 hlua_arg2lua(stream->hlua->T, arg_p);
8705 stream->hlua->nargs++;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008706 }
8707 }
8708
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008709 /* We must initialize the execution timeouts. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008710 stream->hlua->max_time = hlua_timeout_session;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008711
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008712 /* At this point the execution is safe. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008713 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008714 }
8715
8716 /* Execute the function. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008717 switch (hlua_ctx_resume(stream->hlua, 0)) {
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008718 /* finished. */
8719 case HLUA_E_OK:
Thierry FOURNIERfd80df12017-05-12 16:32:20 +02008720 /* If the stack is empty, the function fails. */
8721 if (lua_gettop(stream->hlua->T) <= 0)
8722 return 0;
8723
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008724 /* Convert the returned value in sample. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008725 hlua_lua2smp(stream->hlua->T, -1, smp);
8726 lua_pop(stream->hlua->T, 1);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008727 return 1;
8728
8729 /* yield. */
8730 case HLUA_E_AGAIN:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008731 SEND_ERR(stream->be, "Lua converter '%s': cannot use yielded functions.\n", fcn->name);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008732 return 0;
8733
8734 /* finished with error. */
8735 case HLUA_E_ERRMSG:
8736 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008737 SEND_ERR(stream->be, "Lua converter '%s': %s.\n",
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008738 fcn->name, lua_tostring(stream->hlua->T, -1));
8739 lua_pop(stream->hlua->T, 1);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008740 return 0;
8741
Thierry Fournierd5b073c2018-05-21 19:42:47 +02008742 case HLUA_E_ETMOUT:
8743 SEND_ERR(stream->be, "Lua converter '%s': execution timeout.\n", fcn->name);
8744 return 0;
8745
8746 case HLUA_E_NOMEM:
8747 SEND_ERR(stream->be, "Lua converter '%s': out of memory error.\n", fcn->name);
8748 return 0;
8749
8750 case HLUA_E_YIELD:
8751 SEND_ERR(stream->be, "Lua converter '%s': yield functions like core.tcp() or core.sleep() are not allowed.\n", fcn->name);
8752 return 0;
8753
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008754 case HLUA_E_ERR:
8755 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008756 SEND_ERR(stream->be, "Lua converter '%s' returns an unknown error.\n", fcn->name);
Tim Duesterhus588b3142020-05-29 14:35:51 +02008757 /* fall through */
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008758
8759 default:
8760 return 0;
8761 }
8762}
8763
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008764/* Wrapper called by HAProxy to execute a sample-fetch. this wrapper
8765 * doesn't allow "yield" functions because the HAProxy engine cannot
Willy Tarreaube508f12016-03-10 11:47:01 +01008766 * resume sample-fetches. This function will be called by the sample
8767 * fetch engine to call lua-based fetch operations.
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008768 */
Thierry FOURNIER0786d052015-05-11 15:42:45 +02008769static int hlua_sample_fetch_wrapper(const struct arg *arg_p, struct sample *smp,
8770 const char *kw, void *private)
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008771{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02008772 struct hlua_function *fcn = private;
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02008773 struct stream *stream = smp->strm;
Thierry Fournierfd107a22016-02-19 19:57:23 +01008774 const char *error;
Christopher Faulet8c9e6bb2021-08-06 16:29:41 +02008775 unsigned int hflags = HLUA_TXN_NOTERM | HLUA_TXN_SMP_CTX;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008776
Willy Tarreaube508f12016-03-10 11:47:01 +01008777 if (!stream)
8778 return 0;
Christopher Fauletafd8f102018-11-08 11:34:21 +01008779
Willy Tarreau87b09662015-04-03 00:22:06 +02008780 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01008781 * Lua context can be not initialized. This behavior
8782 * permits to save performances because a systematic
8783 * Lua initialization cause 5% performances loss.
8784 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008785 if (!stream->hlua) {
Christopher Faulet1e8433f2021-03-24 15:03:01 +01008786 struct hlua *hlua;
8787
8788 hlua = pool_alloc(pool_head_hlua);
8789 if (!hlua) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008790 SEND_ERR(stream->be, "Lua sample-fetch '%s': can't initialize Lua context.\n", fcn->name);
8791 return 0;
8792 }
Christopher Faulet1e8433f2021-03-24 15:03:01 +01008793 hlua->T = NULL;
8794 stream->hlua = hlua;
Thierry Fournierc7492592020-11-28 23:57:24 +01008795 if (!hlua_ctx_init(stream->hlua, fcn_ref_to_stack_id(fcn), stream->task, 0)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008796 SEND_ERR(stream->be, "Lua sample-fetch '%s': can't initialize Lua context.\n", fcn->name);
8797 return 0;
8798 }
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01008799 }
8800
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008801 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008802 if (!HLUA_IS_RUNNING(stream->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008803
8804 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008805 if (!SET_SAFE_LJMP(stream->hlua)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008806 if (lua_type(stream->hlua->T, -1) == LUA_TSTRING)
8807 error = lua_tostring(stream->hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +01008808 else
8809 error = "critical error";
8810 SEND_ERR(smp->px, "Lua sample-fetch '%s': %s.\n", fcn->name, error);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008811 return 0;
8812 }
8813
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008814 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008815 if (!lua_checkstack(stream->hlua->T, 2)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008816 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008817 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008818 return 0;
8819 }
8820
8821 /* Restore the function in the stack. */
Thierry Fournierc7492592020-11-28 23:57:24 +01008822 lua_rawgeti(stream->hlua->T, LUA_REGISTRYINDEX, fcn->function_ref[stream->hlua->state_id]);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008823
8824 /* push arguments in the stack. */
Christopher Fauletbfab2dd2019-07-26 15:09:53 +02008825 if (!hlua_txn_new(stream->hlua->T, stream, smp->px, smp->opt & SMP_OPT_DIR, hflags)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008826 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008827 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008828 return 0;
8829 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008830 stream->hlua->nargs = 1;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008831
8832 /* push keywords in the stack. */
8833 for (; arg_p && arg_p->type != ARGT_STOP; arg_p++) {
8834 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008835 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008836 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008837 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008838 return 0;
8839 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008840 hlua_arg2lua(stream->hlua->T, arg_p);
8841 stream->hlua->nargs++;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008842 }
8843
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008844 /* We must initialize the execution timeouts. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008845 stream->hlua->max_time = hlua_timeout_session;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008846
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008847 /* At this point the execution is safe. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008848 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008849 }
8850
8851 /* Execute the function. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008852 switch (hlua_ctx_resume(stream->hlua, 0)) {
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008853 /* finished. */
8854 case HLUA_E_OK:
Thierry FOURNIERfd80df12017-05-12 16:32:20 +02008855 /* If the stack is empty, the function fails. */
8856 if (lua_gettop(stream->hlua->T) <= 0)
8857 return 0;
8858
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008859 /* Convert the returned value in sample. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008860 hlua_lua2smp(stream->hlua->T, -1, smp);
8861 lua_pop(stream->hlua->T, 1);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008862
8863 /* Set the end of execution flag. */
8864 smp->flags &= ~SMP_F_MAY_CHANGE;
8865 return 1;
8866
8867 /* yield. */
8868 case HLUA_E_AGAIN:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008869 SEND_ERR(smp->px, "Lua sample-fetch '%s': cannot use yielded functions.\n", fcn->name);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008870 return 0;
8871
8872 /* finished with error. */
8873 case HLUA_E_ERRMSG:
8874 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008875 SEND_ERR(smp->px, "Lua sample-fetch '%s': %s.\n",
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008876 fcn->name, lua_tostring(stream->hlua->T, -1));
8877 lua_pop(stream->hlua->T, 1);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008878 return 0;
8879
Thierry Fournierd5b073c2018-05-21 19:42:47 +02008880 case HLUA_E_ETMOUT:
Thierry Fournierd5b073c2018-05-21 19:42:47 +02008881 SEND_ERR(smp->px, "Lua sample-fetch '%s': execution timeout.\n", fcn->name);
8882 return 0;
8883
8884 case HLUA_E_NOMEM:
Thierry Fournierd5b073c2018-05-21 19:42:47 +02008885 SEND_ERR(smp->px, "Lua sample-fetch '%s': out of memory error.\n", fcn->name);
8886 return 0;
8887
8888 case HLUA_E_YIELD:
Thierry Fournierd5b073c2018-05-21 19:42:47 +02008889 SEND_ERR(smp->px, "Lua sample-fetch '%s': yield not allowed.\n", fcn->name);
8890 return 0;
8891
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008892 case HLUA_E_ERR:
8893 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008894 SEND_ERR(smp->px, "Lua sample-fetch '%s' returns an unknown error.\n", fcn->name);
Tim Duesterhus588b3142020-05-29 14:35:51 +02008895 /* fall through */
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008896
8897 default:
8898 return 0;
8899 }
8900}
8901
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008902/* This function is an LUA binding used for registering
8903 * "sample-conv" functions. It expects a converter name used
8904 * in the haproxy configuration file, and an LUA function.
8905 */
8906__LJMP static int hlua_register_converters(lua_State *L)
8907{
8908 struct sample_conv_kw_list *sck;
8909 const char *name;
8910 int ref;
8911 int len;
Christopher Fauletaa224302021-04-12 14:08:21 +02008912 struct hlua_function *fcn = NULL;
Thierry Fournierf67442e2020-11-28 20:41:07 +01008913 struct sample_conv *sc;
8914 struct buffer *trash;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008915
8916 MAY_LJMP(check_args(L, 2, "register_converters"));
8917
8918 /* First argument : converter name. */
8919 name = MAY_LJMP(luaL_checkstring(L, 1));
8920
8921 /* Second argument : lua function. */
8922 ref = MAY_LJMP(hlua_checkfunction(L, 2));
8923
Thierry Fournierf67442e2020-11-28 20:41:07 +01008924 /* Check if the converter is already registered */
8925 trash = get_trash_chunk();
8926 chunk_printf(trash, "lua.%s", name);
8927 sc = find_sample_conv(trash->area, trash->data);
8928 if (sc != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +01008929 fcn = sc->private;
8930 if (fcn->function_ref[hlua_state_id] != -1) {
8931 ha_warning("Trying to register converter 'lua.%s' more than once. "
8932 "This will become a hard error in version 2.5.\n", name);
8933 }
8934 fcn->function_ref[hlua_state_id] = ref;
8935 return 0;
Thierry Fournierf67442e2020-11-28 20:41:07 +01008936 }
8937
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008938 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02008939 sck = calloc(1, sizeof(*sck) + sizeof(struct sample_conv) * 2);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008940 if (!sck)
Christopher Fauletaa224302021-04-12 14:08:21 +02008941 goto alloc_error;
Thierry Fournier62a22aa2020-11-28 21:06:35 +01008942 fcn = new_hlua_function();
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008943 if (!fcn)
Christopher Fauletaa224302021-04-12 14:08:21 +02008944 goto alloc_error;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008945
8946 /* Fill fcn. */
8947 fcn->name = strdup(name);
8948 if (!fcn->name)
Christopher Fauletaa224302021-04-12 14:08:21 +02008949 goto alloc_error;
Thierry Fournierc7492592020-11-28 23:57:24 +01008950 fcn->function_ref[hlua_state_id] = ref;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008951
8952 /* List head */
8953 sck->list.n = sck->list.p = NULL;
8954
8955 /* converter keyword. */
8956 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02008957 sck->kw[0].kw = calloc(1, len);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008958 if (!sck->kw[0].kw)
Christopher Fauletaa224302021-04-12 14:08:21 +02008959 goto alloc_error;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008960
8961 snprintf((char *)sck->kw[0].kw, len, "lua.%s", name);
8962 sck->kw[0].process = hlua_sample_conv_wrapper;
David Carlier0c437f42016-04-27 16:21:56 +01008963 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 +01008964 sck->kw[0].val_args = NULL;
8965 sck->kw[0].in_type = SMP_T_STR;
8966 sck->kw[0].out_type = SMP_T_STR;
8967 sck->kw[0].private = fcn;
8968
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008969 /* Register this new converter */
8970 sample_register_convs(sck);
8971
8972 return 0;
Christopher Fauletaa224302021-04-12 14:08:21 +02008973
8974 alloc_error:
8975 release_hlua_function(fcn);
8976 ha_free(&sck);
8977 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
8978 return 0; /* Never reached */
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008979}
8980
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08008981/* This function is an LUA binding used for registering
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008982 * "sample-fetch" functions. It expects a converter name used
8983 * in the haproxy configuration file, and an LUA function.
8984 */
8985__LJMP static int hlua_register_fetches(lua_State *L)
8986{
8987 const char *name;
8988 int ref;
8989 int len;
8990 struct sample_fetch_kw_list *sfk;
Christopher Faulet2567f182021-04-12 14:11:50 +02008991 struct hlua_function *fcn = NULL;
Thierry Fournierf67442e2020-11-28 20:41:07 +01008992 struct sample_fetch *sf;
8993 struct buffer *trash;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008994
8995 MAY_LJMP(check_args(L, 2, "register_fetches"));
8996
8997 /* First argument : sample-fetch name. */
8998 name = MAY_LJMP(luaL_checkstring(L, 1));
8999
9000 /* Second argument : lua function. */
9001 ref = MAY_LJMP(hlua_checkfunction(L, 2));
9002
Thierry Fournierf67442e2020-11-28 20:41:07 +01009003 /* Check if the sample-fetch is already registered */
9004 trash = get_trash_chunk();
9005 chunk_printf(trash, "lua.%s", name);
9006 sf = find_sample_fetch(trash->area, trash->data);
9007 if (sf != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +01009008 fcn = sf->private;
9009 if (fcn->function_ref[hlua_state_id] != -1) {
9010 ha_warning("Trying to register sample-fetch 'lua.%s' more than once. "
9011 "This will become a hard error in version 2.5.\n", name);
9012 }
9013 fcn->function_ref[hlua_state_id] = ref;
9014 return 0;
Thierry Fournierf67442e2020-11-28 20:41:07 +01009015 }
9016
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009017 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02009018 sfk = calloc(1, sizeof(*sfk) + sizeof(struct sample_fetch) * 2);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009019 if (!sfk)
Christopher Faulet2567f182021-04-12 14:11:50 +02009020 goto alloc_error;
Thierry Fournier62a22aa2020-11-28 21:06:35 +01009021 fcn = new_hlua_function();
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009022 if (!fcn)
Christopher Faulet2567f182021-04-12 14:11:50 +02009023 goto alloc_error;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009024
9025 /* Fill fcn. */
9026 fcn->name = strdup(name);
9027 if (!fcn->name)
Christopher Faulet2567f182021-04-12 14:11:50 +02009028 goto alloc_error;
Thierry Fournierc7492592020-11-28 23:57:24 +01009029 fcn->function_ref[hlua_state_id] = ref;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009030
9031 /* List head */
9032 sfk->list.n = sfk->list.p = NULL;
9033
9034 /* sample-fetch keyword. */
9035 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02009036 sfk->kw[0].kw = calloc(1, len);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009037 if (!sfk->kw[0].kw)
Christopher Faulet2567f182021-04-12 14:11:50 +02009038 goto alloc_error;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009039
9040 snprintf((char *)sfk->kw[0].kw, len, "lua.%s", name);
9041 sfk->kw[0].process = hlua_sample_fetch_wrapper;
David Carlier0c437f42016-04-27 16:21:56 +01009042 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 +01009043 sfk->kw[0].val_args = NULL;
9044 sfk->kw[0].out_type = SMP_T_STR;
9045 sfk->kw[0].use = SMP_USE_HTTP_ANY;
9046 sfk->kw[0].val = 0;
9047 sfk->kw[0].private = fcn;
9048
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009049 /* Register this new fetch. */
9050 sample_register_fetches(sfk);
9051
9052 return 0;
Christopher Faulet2567f182021-04-12 14:11:50 +02009053
9054 alloc_error:
9055 release_hlua_function(fcn);
9056 ha_free(&sfk);
9057 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
9058 return 0; /* Never reached */
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009059}
9060
Christopher Faulet501465d2020-02-26 14:54:16 +01009061/* This function is a lua binding to set the wake_time.
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01009062 */
Christopher Faulet501465d2020-02-26 14:54:16 +01009063__LJMP static int hlua_set_wake_time(lua_State *L)
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01009064{
Thierry Fournier4234dbd2020-11-28 13:18:23 +01009065 struct hlua *hlua;
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01009066 unsigned int delay;
9067 unsigned int wakeup_ms;
9068
Thierry Fournier4234dbd2020-11-28 13:18:23 +01009069 /* Get hlua struct, or NULL if we execute from main lua state */
9070 hlua = hlua_gethlua(L);
9071 if (!hlua) {
9072 return 0;
9073 }
9074
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01009075 MAY_LJMP(check_args(L, 1, "wake_time"));
9076
9077 delay = MAY_LJMP(luaL_checkinteger(L, 1));
9078 wakeup_ms = tick_add(now_ms, delay);
9079 hlua->wake_time = wakeup_ms;
9080 return 0;
9081}
9082
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009083/* This function is a wrapper to execute each LUA function declared as an action
9084 * wrapper during the initialisation period. This function may return any
9085 * ACT_RET_* value. On error ACT_RET_CONT is returned and the action is
9086 * ignored. If the lua action yields, ACT_RET_YIELD is returned. On success, the
9087 * return value is the first element on the stack.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009088 */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009089static enum act_return hlua_action(struct act_rule *rule, struct proxy *px,
Willy Tarreau658b85b2015-09-27 10:00:49 +02009090 struct session *sess, struct stream *s, int flags)
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009091{
9092 char **arg;
Christopher Faulet8c9e6bb2021-08-06 16:29:41 +02009093 unsigned int hflags = HLUA_TXN_ACT_CTX;
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009094 int dir, act_ret = ACT_RET_CONT;
Thierry Fournierfd107a22016-02-19 19:57:23 +01009095 const char *error;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009096
9097 switch (rule->from) {
Christopher Fauletd8f0e072020-02-25 09:45:51 +01009098 case ACT_F_TCP_REQ_CNT: dir = SMP_OPT_DIR_REQ; break;
9099 case ACT_F_TCP_RES_CNT: dir = SMP_OPT_DIR_RES; break;
9100 case ACT_F_HTTP_REQ: dir = SMP_OPT_DIR_REQ; break;
9101 case ACT_F_HTTP_RES: dir = SMP_OPT_DIR_RES; break;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009102 default:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009103 SEND_ERR(px, "Lua: internal error while execute action.\n");
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009104 goto end;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009105 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009106
Willy Tarreau87b09662015-04-03 00:22:06 +02009107 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01009108 * Lua context can be not initialized. This behavior
9109 * permits to save performances because a systematic
9110 * Lua initialization cause 5% performances loss.
9111 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009112 if (!s->hlua) {
Christopher Faulet1e8433f2021-03-24 15:03:01 +01009113 struct hlua *hlua;
9114
9115 hlua = pool_alloc(pool_head_hlua);
9116 if (!hlua) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009117 SEND_ERR(px, "Lua action '%s': can't initialize Lua context.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009118 rule->arg.hlua_rule->fcn->name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009119 goto end;
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009120 }
Christopher Faulet1e8433f2021-03-24 15:03:01 +01009121 HLUA_INIT(hlua);
9122 s->hlua = hlua;
Thierry Fournierc7492592020-11-28 23:57:24 +01009123 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 +01009124 SEND_ERR(px, "Lua action '%s': can't initialize Lua context.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009125 rule->arg.hlua_rule->fcn->name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009126 goto end;
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009127 }
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01009128 }
9129
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009130 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009131 if (!HLUA_IS_RUNNING(s->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02009132
9133 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009134 if (!SET_SAFE_LJMP(s->hlua)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009135 if (lua_type(s->hlua->T, -1) == LUA_TSTRING)
9136 error = lua_tostring(s->hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +01009137 else
9138 error = "critical error";
9139 SEND_ERR(px, "Lua function '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009140 rule->arg.hlua_rule->fcn->name, error);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009141 goto end;
Thierry FOURNIERbabae282015-09-17 11:36:37 +02009142 }
9143
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009144 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009145 if (!lua_checkstack(s->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009146 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009147 rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009148 RESET_SAFE_LJMP(s->hlua);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009149 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009150 }
9151
9152 /* Restore the function in the stack. */
Thierry Fournierc7492592020-11-28 23:57:24 +01009153 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 +01009154
Willy Tarreau87b09662015-04-03 00:22:06 +02009155 /* Create and and push object stream in the stack. */
Christopher Fauletbfab2dd2019-07-26 15:09:53 +02009156 if (!hlua_txn_new(s->hlua->T, s, px, dir, hflags)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009157 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009158 rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009159 RESET_SAFE_LJMP(s->hlua);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009160 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009161 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009162 s->hlua->nargs = 1;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009163
9164 /* push keywords in the stack. */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009165 for (arg = rule->arg.hlua_rule->args; arg && *arg; arg++) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009166 if (!lua_checkstack(s->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009167 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009168 rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009169 RESET_SAFE_LJMP(s->hlua);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009170 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009171 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009172 lua_pushstring(s->hlua->T, *arg);
9173 s->hlua->nargs++;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009174 }
9175
Thierry FOURNIERbabae282015-09-17 11:36:37 +02009176 /* Now the execution is safe. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009177 RESET_SAFE_LJMP(s->hlua);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02009178
Thierry FOURNIERbd413492015-03-03 16:52:26 +01009179 /* We must initialize the execution timeouts. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009180 s->hlua->max_time = hlua_timeout_session;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009181 }
9182
9183 /* Execute the function. */
Christopher Faulet105ba6c2019-12-18 14:41:51 +01009184 switch (hlua_ctx_resume(s->hlua, !(flags & ACT_OPT_FINAL))) {
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009185 /* finished. */
9186 case HLUA_E_OK:
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009187 /* Catch the return value */
9188 if (lua_gettop(s->hlua->T) > 0)
9189 act_ret = lua_tointeger(s->hlua->T, -1);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009190
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01009191 /* Set timeout in the required channel. */
Christopher Faulet498c4832020-07-28 11:59:58 +02009192 if (act_ret == ACT_RET_YIELD) {
9193 if (flags & ACT_OPT_FINAL)
9194 goto err_yield;
9195
Christopher Faulet8f587ea2020-07-28 12:01:55 +02009196 if (dir == SMP_OPT_DIR_REQ)
9197 s->req.analyse_exp = tick_first((tick_is_expired(s->req.analyse_exp, now_ms) ? 0 : s->req.analyse_exp),
9198 s->hlua->wake_time);
9199 else
9200 s->res.analyse_exp = tick_first((tick_is_expired(s->res.analyse_exp, now_ms) ? 0 : s->res.analyse_exp),
9201 s->hlua->wake_time);
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01009202 }
9203 goto end;
9204
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009205 /* yield. */
9206 case HLUA_E_AGAIN:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01009207 /* Set timeout in the required channel. */
Christopher Faulet8f587ea2020-07-28 12:01:55 +02009208 if (dir == SMP_OPT_DIR_REQ)
9209 s->req.analyse_exp = tick_first((tick_is_expired(s->req.analyse_exp, now_ms) ? 0 : s->req.analyse_exp),
9210 s->hlua->wake_time);
9211 else
9212 s->res.analyse_exp = tick_first((tick_is_expired(s->res.analyse_exp, now_ms) ? 0 : s->res.analyse_exp),
9213 s->hlua->wake_time);
9214
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009215 /* Some actions can be wake up when a "write" event
9216 * is detected on a response channel. This is useful
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08009217 * only for actions targeted on the requests.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009218 */
Christopher Faulet51fa3582019-07-26 14:54:52 +02009219 if (HLUA_IS_WAKERESWR(s->hlua))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01009220 s->res.flags |= CF_WAKE_WRITE;
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009221 if (HLUA_IS_WAKEREQWR(s->hlua))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01009222 s->req.flags |= CF_WAKE_WRITE;
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009223 act_ret = ACT_RET_YIELD;
9224 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009225
9226 /* finished with error. */
9227 case HLUA_E_ERRMSG:
9228 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009229 SEND_ERR(px, "Lua function '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009230 rule->arg.hlua_rule->fcn->name, lua_tostring(s->hlua->T, -1));
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009231 lua_pop(s->hlua->T, 1);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009232 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009233
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009234 case HLUA_E_ETMOUT:
Thierry Fournierad5345f2020-11-29 02:05:57 +01009235 SEND_ERR(px, "Lua function '%s': execution timeout.\n", rule->arg.hlua_rule->fcn->name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009236 goto end;
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009237
9238 case HLUA_E_NOMEM:
Thierry Fournierad5345f2020-11-29 02:05:57 +01009239 SEND_ERR(px, "Lua function '%s': out of memory error.\n", rule->arg.hlua_rule->fcn->name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009240 goto end;
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009241
9242 case HLUA_E_YIELD:
Christopher Faulet498c4832020-07-28 11:59:58 +02009243 err_yield:
9244 act_ret = ACT_RET_CONT;
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009245 SEND_ERR(px, "Lua function '%s': aborting Lua processing on expired timeout.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009246 rule->arg.hlua_rule->fcn->name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009247 goto end;
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009248
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009249 case HLUA_E_ERR:
9250 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009251 SEND_ERR(px, "Lua function '%s' return an unknown error.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009252 rule->arg.hlua_rule->fcn->name);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009253
9254 default:
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009255 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009256 }
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009257
9258 end:
Christopher Faulet2361fd92020-07-30 10:40:58 +02009259 if (act_ret != ACT_RET_YIELD && s->hlua)
Christopher Faulet8f587ea2020-07-28 12:01:55 +02009260 s->hlua->wake_time = TICK_ETERNITY;
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009261 return act_ret;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009262}
9263
Willy Tarreau144f84a2021-03-02 16:09:26 +01009264struct task *hlua_applet_wakeup(struct task *t, void *context, unsigned int state)
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009265{
Olivier Houchard9f6af332018-05-25 14:04:04 +02009266 struct appctx *ctx = context;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009267
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009268 appctx_wakeup(ctx);
Willy Tarreaud9587412017-08-23 16:07:33 +02009269 t->expire = TICK_ETERNITY;
Willy Tarreaud1aa41f2017-07-21 16:41:56 +02009270 return t;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009271}
9272
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009273static int hlua_applet_tcp_init(struct appctx *ctx)
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009274{
Willy Tarreaue23f33b2022-05-06 14:07:13 +02009275 struct hlua_tcp_ctx *tcp_ctx = applet_reserve_svcctx(ctx, sizeof(*tcp_ctx));
Willy Tarreauc12b3212022-05-27 11:08:15 +02009276 struct stconn *sc = appctx_sc(ctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02009277 struct stream *strm = __sc_strm(sc);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009278 struct hlua *hlua;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009279 struct task *task;
9280 char **arg;
Thierry Fournierfd107a22016-02-19 19:57:23 +01009281 const char *error;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009282
Willy Tarreaubafbe012017-11-24 17:34:44 +01009283 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009284 if (!hlua) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009285 SEND_ERR(strm->be, "Lua applet tcp '%s': out of memory.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009286 ctx->rule->arg.hlua_rule->fcn->name);
Christopher Fauletc9929382022-05-12 11:52:27 +02009287 return -1;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009288 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009289 HLUA_INIT(hlua);
Willy Tarreaue23f33b2022-05-06 14:07:13 +02009290 tcp_ctx->hlua = hlua;
9291 tcp_ctx->flags = 0;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009292
9293 /* Create task used by signal to wakeup applets. */
Willy Tarreaubeeabf52021-10-01 18:23:30 +02009294 task = task_new_here();
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009295 if (!task) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009296 SEND_ERR(strm->be, "Lua applet tcp '%s': out of memory.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009297 ctx->rule->arg.hlua_rule->fcn->name);
Christopher Fauletc9929382022-05-12 11:52:27 +02009298 return -1;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009299 }
9300 task->nice = 0;
9301 task->context = ctx;
9302 task->process = hlua_applet_wakeup;
Willy Tarreaue23f33b2022-05-06 14:07:13 +02009303 tcp_ctx->task = task;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009304
9305 /* In the execution wrappers linked with a stream, the
9306 * Lua context can be not initialized. This behavior
9307 * permits to save performances because a systematic
9308 * Lua initialization cause 5% performances loss.
9309 */
Thierry Fournierc7492592020-11-28 23:57:24 +01009310 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 +01009311 SEND_ERR(strm->be, "Lua applet tcp '%s': can't initialize Lua context.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009312 ctx->rule->arg.hlua_rule->fcn->name);
Christopher Fauletc9929382022-05-12 11:52:27 +02009313 return -1;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009314 }
9315
9316 /* Set timeout according with the applet configuration. */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02009317 hlua->max_time = ctx->applet->timeout;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009318
9319 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009320 if (!SET_SAFE_LJMP(hlua)) {
Thierry Fournierfd107a22016-02-19 19:57:23 +01009321 if (lua_type(hlua->T, -1) == LUA_TSTRING)
9322 error = lua_tostring(hlua->T, -1);
9323 else
9324 error = "critical error";
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009325 SEND_ERR(strm->be, "Lua applet tcp '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009326 ctx->rule->arg.hlua_rule->fcn->name, error);
Christopher Fauletc9929382022-05-12 11:52:27 +02009327 return -1;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009328 }
9329
9330 /* Check stack available size. */
9331 if (!lua_checkstack(hlua->T, 1)) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009332 SEND_ERR(strm->be, "Lua applet tcp '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009333 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009334 RESET_SAFE_LJMP(hlua);
Christopher Fauletc9929382022-05-12 11:52:27 +02009335 return -1;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009336 }
9337
9338 /* Restore the function in the stack. */
Thierry Fournierc7492592020-11-28 23:57:24 +01009339 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ctx->rule->arg.hlua_rule->fcn->function_ref[hlua->state_id]);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009340
9341 /* Create and and push object stream in the stack. */
9342 if (!hlua_applet_tcp_new(hlua->T, ctx)) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009343 SEND_ERR(strm->be, "Lua applet tcp '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009344 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009345 RESET_SAFE_LJMP(hlua);
Christopher Fauletc9929382022-05-12 11:52:27 +02009346 return -1;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009347 }
9348 hlua->nargs = 1;
9349
9350 /* push keywords in the stack. */
9351 for (arg = ctx->rule->arg.hlua_rule->args; arg && *arg; arg++) {
9352 if (!lua_checkstack(hlua->T, 1)) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009353 SEND_ERR(strm->be, "Lua applet tcp '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009354 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009355 RESET_SAFE_LJMP(hlua);
Christopher Fauletc9929382022-05-12 11:52:27 +02009356 return -1;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009357 }
9358 lua_pushstring(hlua->T, *arg);
9359 hlua->nargs++;
9360 }
9361
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009362 RESET_SAFE_LJMP(hlua);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009363
9364 /* Wakeup the applet ASAP. */
Willy Tarreau90e8b452022-05-25 18:21:43 +02009365 applet_need_more_data(ctx);
Willy Tarreau4164eb92022-05-25 15:42:03 +02009366 applet_have_more_data(ctx);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009367
Christopher Fauletc9929382022-05-12 11:52:27 +02009368 return 0;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009369}
9370
Willy Tarreau60409db2019-08-21 14:14:50 +02009371void hlua_applet_tcp_fct(struct appctx *ctx)
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009372{
Willy Tarreaue23f33b2022-05-06 14:07:13 +02009373 struct hlua_tcp_ctx *tcp_ctx = ctx->svcctx;
Willy Tarreauc12b3212022-05-27 11:08:15 +02009374 struct stconn *sc = appctx_sc(ctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02009375 struct stream *strm = __sc_strm(sc);
9376 struct channel *res = sc_ic(sc);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009377 struct act_rule *rule = ctx->rule;
9378 struct proxy *px = strm->be;
Willy Tarreaue23f33b2022-05-06 14:07:13 +02009379 struct hlua *hlua = tcp_ctx->hlua;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009380
9381 /* The applet execution is already done. */
Willy Tarreaue23f33b2022-05-06 14:07:13 +02009382 if (tcp_ctx->flags & APPLET_DONE) {
Olivier Houchard594c8c52018-08-28 14:41:31 +02009383 /* eat the whole request */
Willy Tarreau3e7be362022-05-27 10:35:27 +02009384 co_skip(sc_oc(sc), co_data(sc_oc(sc)));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009385 return;
Olivier Houchard594c8c52018-08-28 14:41:31 +02009386 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009387
9388 /* If the stream is disconnect or closed, ldo nothing. */
Willy Tarreau3e7be362022-05-27 10:35:27 +02009389 if (unlikely(sc->state == SC_ST_DIS || sc->state == SC_ST_CLO))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009390 return;
9391
9392 /* Execute the function. */
9393 switch (hlua_ctx_resume(hlua, 1)) {
9394 /* finished. */
9395 case HLUA_E_OK:
Willy Tarreaue23f33b2022-05-06 14:07:13 +02009396 tcp_ctx->flags |= APPLET_DONE;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009397
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009398 /* eat the whole request */
Willy Tarreau3e7be362022-05-27 10:35:27 +02009399 co_skip(sc_oc(sc), co_data(sc_oc(sc)));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009400 res->flags |= CF_READ_NULL;
Willy Tarreau3e7be362022-05-27 10:35:27 +02009401 sc_shutr(sc);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009402 return;
9403
9404 /* yield. */
9405 case HLUA_E_AGAIN:
Thierry Fournier0164f202016-02-20 17:47:43 +01009406 if (hlua->wake_time != TICK_ETERNITY)
Willy Tarreaue23f33b2022-05-06 14:07:13 +02009407 task_schedule(tcp_ctx->task, hlua->wake_time);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009408 return;
9409
9410 /* finished with error. */
9411 case HLUA_E_ERRMSG:
9412 /* Display log. */
9413 SEND_ERR(px, "Lua applet tcp '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009414 rule->arg.hlua_rule->fcn->name, lua_tostring(hlua->T, -1));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009415 lua_pop(hlua->T, 1);
9416 goto error;
9417
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009418 case HLUA_E_ETMOUT:
9419 SEND_ERR(px, "Lua applet tcp '%s': execution timeout.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009420 rule->arg.hlua_rule->fcn->name);
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009421 goto error;
9422
9423 case HLUA_E_NOMEM:
9424 SEND_ERR(px, "Lua applet tcp '%s': out of memory error.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009425 rule->arg.hlua_rule->fcn->name);
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009426 goto error;
9427
9428 case HLUA_E_YIELD: /* unexpected */
9429 SEND_ERR(px, "Lua applet tcp '%s': yield not allowed.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009430 rule->arg.hlua_rule->fcn->name);
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009431 goto error;
9432
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009433 case HLUA_E_ERR:
9434 /* Display log. */
9435 SEND_ERR(px, "Lua applet tcp '%s' return an unknown error.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009436 rule->arg.hlua_rule->fcn->name);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009437 goto error;
9438
9439 default:
9440 goto error;
9441 }
9442
9443error:
9444
9445 /* For all other cases, just close the stream. */
Willy Tarreau3e7be362022-05-27 10:35:27 +02009446 sc_shutw(sc);
9447 sc_shutr(sc);
Willy Tarreaue23f33b2022-05-06 14:07:13 +02009448 tcp_ctx->flags |= APPLET_DONE;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009449}
9450
9451static void hlua_applet_tcp_release(struct appctx *ctx)
9452{
Willy Tarreaue23f33b2022-05-06 14:07:13 +02009453 struct hlua_tcp_ctx *tcp_ctx = ctx->svcctx;
9454
9455 task_destroy(tcp_ctx->task);
9456 tcp_ctx->task = NULL;
9457 hlua_ctx_destroy(tcp_ctx->hlua);
9458 tcp_ctx->hlua = NULL;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009459}
9460
Christopher Fauletc9929382022-05-12 11:52:27 +02009461/* The function returns 0 if the initialisation is complete or -1 if
9462 * an errors occurs. It also reserves the appctx for an hlua_http_ctx.
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009463 */
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009464static int hlua_applet_http_init(struct appctx *ctx)
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009465{
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009466 struct hlua_http_ctx *http_ctx = applet_reserve_svcctx(ctx, sizeof(*http_ctx));
Willy Tarreauc12b3212022-05-27 11:08:15 +02009467 struct stconn *sc = appctx_sc(ctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02009468 struct stream *strm = __sc_strm(sc);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009469 struct http_txn *txn;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009470 struct hlua *hlua;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009471 char **arg;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009472 struct task *task;
Thierry Fournierfd107a22016-02-19 19:57:23 +01009473 const char *error;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009474
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009475 txn = strm->txn;
Willy Tarreaubafbe012017-11-24 17:34:44 +01009476 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009477 if (!hlua) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009478 SEND_ERR(strm->be, "Lua applet http '%s': out of memory.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009479 ctx->rule->arg.hlua_rule->fcn->name);
Christopher Fauletc9929382022-05-12 11:52:27 +02009480 return -1;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009481 }
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009482 HLUA_INIT(hlua);
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009483 http_ctx->hlua = hlua;
9484 http_ctx->left_bytes = -1;
9485 http_ctx->flags = 0;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009486
Thierry FOURNIERd93ea2b2015-12-20 19:14:52 +01009487 if (txn->req.flags & HTTP_MSGF_VER_11)
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009488 http_ctx->flags |= APPLET_HTTP11;
Thierry FOURNIERd93ea2b2015-12-20 19:14:52 +01009489
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009490 /* Create task used by signal to wakeup applets. */
Willy Tarreaubeeabf52021-10-01 18:23:30 +02009491 task = task_new_here();
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009492 if (!task) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009493 SEND_ERR(strm->be, "Lua applet http '%s': out of memory.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009494 ctx->rule->arg.hlua_rule->fcn->name);
Christopher Fauletc9929382022-05-12 11:52:27 +02009495 return -1;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009496 }
9497 task->nice = 0;
9498 task->context = ctx;
9499 task->process = hlua_applet_wakeup;
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009500 http_ctx->task = task;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009501
9502 /* In the execution wrappers linked with a stream, the
9503 * Lua context can be not initialized. This behavior
9504 * permits to save performances because a systematic
9505 * Lua initialization cause 5% performances loss.
9506 */
Thierry Fournierc7492592020-11-28 23:57:24 +01009507 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 +01009508 SEND_ERR(strm->be, "Lua applet http '%s': can't initialize Lua context.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009509 ctx->rule->arg.hlua_rule->fcn->name);
Christopher Fauletc9929382022-05-12 11:52:27 +02009510 return -1;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009511 }
9512
9513 /* Set timeout according with the applet configuration. */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02009514 hlua->max_time = ctx->applet->timeout;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009515
9516 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009517 if (!SET_SAFE_LJMP(hlua)) {
Thierry Fournierfd107a22016-02-19 19:57:23 +01009518 if (lua_type(hlua->T, -1) == LUA_TSTRING)
9519 error = lua_tostring(hlua->T, -1);
9520 else
9521 error = "critical error";
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009522 SEND_ERR(strm->be, "Lua applet http '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009523 ctx->rule->arg.hlua_rule->fcn->name, error);
Christopher Fauletc9929382022-05-12 11:52:27 +02009524 return -1;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009525 }
9526
9527 /* Check stack available size. */
9528 if (!lua_checkstack(hlua->T, 1)) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009529 SEND_ERR(strm->be, "Lua applet http '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009530 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009531 RESET_SAFE_LJMP(hlua);
Christopher Fauletc9929382022-05-12 11:52:27 +02009532 return -1;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009533 }
9534
9535 /* Restore the function in the stack. */
Thierry Fournierc7492592020-11-28 23:57:24 +01009536 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ctx->rule->arg.hlua_rule->fcn->function_ref[hlua->state_id]);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009537
9538 /* Create and and push object stream in the stack. */
9539 if (!hlua_applet_http_new(hlua->T, ctx)) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009540 SEND_ERR(strm->be, "Lua applet http '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009541 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009542 RESET_SAFE_LJMP(hlua);
Christopher Fauletc9929382022-05-12 11:52:27 +02009543 return -1;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009544 }
9545 hlua->nargs = 1;
9546
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009547 /* push keywords in the stack. */
9548 for (arg = ctx->rule->arg.hlua_rule->args; arg && *arg; arg++) {
9549 if (!lua_checkstack(hlua->T, 1)) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009550 SEND_ERR(strm->be, "Lua applet http '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009551 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009552 RESET_SAFE_LJMP(hlua);
Christopher Fauletc9929382022-05-12 11:52:27 +02009553 return -1;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009554 }
9555 lua_pushstring(hlua->T, *arg);
9556 hlua->nargs++;
9557 }
9558
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009559 RESET_SAFE_LJMP(hlua);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009560
9561 /* Wakeup the applet when data is ready for read. */
Willy Tarreau90e8b452022-05-25 18:21:43 +02009562 applet_need_more_data(ctx);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009563
Christopher Fauletc9929382022-05-12 11:52:27 +02009564 return 0;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009565}
9566
Willy Tarreau60409db2019-08-21 14:14:50 +02009567void hlua_applet_http_fct(struct appctx *ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009568{
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009569 struct hlua_http_ctx *http_ctx = ctx->svcctx;
Willy Tarreauc12b3212022-05-27 11:08:15 +02009570 struct stconn *sc = appctx_sc(ctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02009571 struct stream *strm = __sc_strm(sc);
9572 struct channel *req = sc_oc(sc);
9573 struct channel *res = sc_ic(sc);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009574 struct act_rule *rule = ctx->rule;
9575 struct proxy *px = strm->be;
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009576 struct hlua *hlua = http_ctx->hlua;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009577 struct htx *req_htx, *res_htx;
9578
9579 res_htx = htx_from_buf(&res->buf);
9580
9581 /* If the stream is disconnect or closed, ldo nothing. */
Willy Tarreau3e7be362022-05-27 10:35:27 +02009582 if (unlikely(sc->state == SC_ST_DIS || sc->state == SC_ST_CLO))
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009583 goto out;
9584
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05009585 /* Check if the input buffer is available. */
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009586 if (!b_size(&res->buf)) {
Willy Tarreau3e7be362022-05-27 10:35:27 +02009587 sc_need_room(sc);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009588 goto out;
9589 }
9590 /* check that the output is not closed */
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01009591 if (res->flags & (CF_SHUTW|CF_SHUTW_NOW|CF_SHUTR))
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009592 http_ctx->flags |= APPLET_DONE;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009593
9594 /* Set the currently running flag. */
9595 if (!HLUA_IS_RUNNING(hlua) &&
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009596 !(http_ctx->flags & APPLET_DONE)) {
Christopher Fauletbd878d22021-04-28 10:50:21 +02009597 if (!co_data(req)) {
Willy Tarreau90e8b452022-05-25 18:21:43 +02009598 applet_need_more_data(ctx);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009599 goto out;
9600 }
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009601 }
9602
9603 /* Executes The applet if it is not done. */
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009604 if (!(http_ctx->flags & APPLET_DONE)) {
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009605
9606 /* Execute the function. */
9607 switch (hlua_ctx_resume(hlua, 1)) {
9608 /* finished. */
9609 case HLUA_E_OK:
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009610 http_ctx->flags |= APPLET_DONE;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009611 break;
9612
9613 /* yield. */
9614 case HLUA_E_AGAIN:
9615 if (hlua->wake_time != TICK_ETERNITY)
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009616 task_schedule(http_ctx->task, hlua->wake_time);
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01009617 goto out;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009618
9619 /* finished with error. */
9620 case HLUA_E_ERRMSG:
9621 /* Display log. */
9622 SEND_ERR(px, "Lua applet http '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009623 rule->arg.hlua_rule->fcn->name, lua_tostring(hlua->T, -1));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009624 lua_pop(hlua->T, 1);
9625 goto error;
9626
9627 case HLUA_E_ETMOUT:
9628 SEND_ERR(px, "Lua applet http '%s': execution timeout.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009629 rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009630 goto error;
9631
9632 case HLUA_E_NOMEM:
9633 SEND_ERR(px, "Lua applet http '%s': out of memory error.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009634 rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009635 goto error;
9636
9637 case HLUA_E_YIELD: /* unexpected */
9638 SEND_ERR(px, "Lua applet http '%s': yield not allowed.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009639 rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009640 goto error;
9641
9642 case HLUA_E_ERR:
9643 /* Display log. */
9644 SEND_ERR(px, "Lua applet http '%s' return an unknown error.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009645 rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009646 goto error;
9647
9648 default:
9649 goto error;
9650 }
9651 }
9652
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009653 if (http_ctx->flags & APPLET_DONE) {
9654 if (http_ctx->flags & APPLET_RSP_SENT)
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01009655 goto done;
9656
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009657 if (!(http_ctx->flags & APPLET_HDR_SENT))
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009658 goto error;
9659
Christopher Fauletf89af9c2022-04-07 10:07:18 +02009660 /* no more data are expected. If the response buffer is empty
9661 * for a chunked message, be sure to add something (EOT block in
9662 * this case) to have something to send. It is important to be
9663 * sure the EOM flags will be handled by the endpoint.
9664 */
9665 if (htx_is_empty(res_htx) && (strm->txn->rsp.flags & (HTTP_MSGF_XFER_LEN|HTTP_MSGF_CNT_LEN)) == HTTP_MSGF_XFER_LEN) {
9666 if (!htx_add_endof(res_htx, HTX_BLK_EOT)) {
Willy Tarreau3e7be362022-05-27 10:35:27 +02009667 sc_need_room(sc);
Christopher Fauletf89af9c2022-04-07 10:07:18 +02009668 goto out;
9669 }
9670 channel_add_input(res, 1);
9671 }
9672
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01009673 res_htx->flags |= HTX_FL_EOM;
Christopher Fauletd8d27082022-03-07 15:50:54 +01009674 res->flags |= CF_EOI;
Willy Tarreaud869e132022-05-17 18:05:31 +02009675 se_fl_set(ctx->sedesc, SE_FL_EOI);
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009676 strm->txn->status = http_ctx->status;
9677 http_ctx->flags |= APPLET_RSP_SENT;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009678 }
9679
9680 done:
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009681 if (http_ctx->flags & APPLET_DONE) {
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01009682 if (!(res->flags & CF_SHUTR)) {
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009683 res->flags |= CF_READ_NULL;
Willy Tarreau3e7be362022-05-27 10:35:27 +02009684 sc_shutr(sc);
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01009685 }
9686
9687 /* eat the whole request */
9688 if (co_data(req)) {
9689 req_htx = htx_from_buf(&req->buf);
9690 co_htx_skip(req, req_htx, co_data(req));
9691 htx_to_buf(req_htx, &req->buf);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009692 }
9693 }
9694
9695 out:
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009696 htx_to_buf(res_htx, &res->buf);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009697 return;
9698
9699 error:
9700
9701 /* If we are in HTTP mode, and we are not send any
9702 * data, return a 500 server error in best effort:
9703 * if there is no room available in the buffer,
9704 * just close the connection.
9705 */
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009706 if (!(http_ctx->flags & APPLET_HDR_SENT)) {
Christopher Fauletf7346382019-07-17 22:02:08 +02009707 struct buffer *err = &http_err_chunks[HTTP_ERR_500];
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009708
9709 channel_erase(res);
9710 res->buf.data = b_data(err);
9711 memcpy(res->buf.area, b_head(err), b_data(err));
9712 res_htx = htx_from_buf(&res->buf);
Christopher Fauletf6cce3f2019-02-27 21:20:09 +01009713 channel_add_input(res, res_htx->data);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009714 }
9715 if (!(strm->flags & SF_ERR_MASK))
9716 strm->flags |= SF_ERR_RESOURCE;
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009717 http_ctx->flags |= APPLET_DONE;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009718 goto done;
9719}
9720
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009721static void hlua_applet_http_release(struct appctx *ctx)
9722{
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009723 struct hlua_http_ctx *http_ctx = ctx->svcctx;
9724
9725 task_destroy(http_ctx->task);
9726 http_ctx->task = NULL;
9727 hlua_ctx_destroy(http_ctx->hlua);
9728 http_ctx->hlua = NULL;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009729}
9730
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009731/* global {tcp|http}-request parser. Return ACT_RET_PRS_OK in
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05009732 * success case, else return ACT_RET_PRS_ERR.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02009733 *
9734 * This function can fail with an abort() due to an Lua critical error.
9735 * We are in the configuration parsing process of HAProxy, this abort() is
9736 * tolerated.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009737 */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009738static enum act_parse_ret action_register_lua(const char **args, int *cur_arg, struct proxy *px,
9739 struct act_rule *rule, char **err)
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009740{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02009741 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009742 int i;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009743
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009744 /* Memory for the rule. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02009745 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009746 if (!rule->arg.hlua_rule) {
9747 memprintf(err, "out of memory error");
Christopher Faulet528526f2021-04-12 14:37:32 +02009748 goto error;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009749 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009750
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009751 /* Memory for arguments. */
Tim Duesterhuse52b6e52020-09-12 20:26:43 +02009752 rule->arg.hlua_rule->args = calloc(fcn->nargs + 1,
9753 sizeof(*rule->arg.hlua_rule->args));
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009754 if (!rule->arg.hlua_rule->args) {
9755 memprintf(err, "out of memory error");
Christopher Faulet528526f2021-04-12 14:37:32 +02009756 goto error;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009757 }
9758
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009759 /* Reference the Lua function and store the reference. */
Thierry Fournierad5345f2020-11-29 02:05:57 +01009760 rule->arg.hlua_rule->fcn = fcn;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009761
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009762 /* Expect some arguments */
9763 for (i = 0; i < fcn->nargs; i++) {
Thierry FOURNIER1725c2e2019-01-06 19:38:49 +01009764 if (*args[*cur_arg] == '\0') {
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009765 memprintf(err, "expect %d arguments", fcn->nargs);
Christopher Faulet528526f2021-04-12 14:37:32 +02009766 goto error;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009767 }
Thierry FOURNIER1725c2e2019-01-06 19:38:49 +01009768 rule->arg.hlua_rule->args[i] = strdup(args[*cur_arg]);
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009769 if (!rule->arg.hlua_rule->args[i]) {
9770 memprintf(err, "out of memory error");
Christopher Faulet528526f2021-04-12 14:37:32 +02009771 goto error;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009772 }
9773 (*cur_arg)++;
9774 }
9775 rule->arg.hlua_rule->args[i] = NULL;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009776
Thierry FOURNIER42148732015-09-02 17:17:33 +02009777 rule->action = ACT_CUSTOM;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009778 rule->action_ptr = hlua_action;
Thierry FOURNIERafa80492015-08-19 09:04:15 +02009779 return ACT_RET_PRS_OK;
Christopher Faulet528526f2021-04-12 14:37:32 +02009780
9781 error:
9782 if (rule->arg.hlua_rule) {
9783 if (rule->arg.hlua_rule->args) {
9784 for (i = 0; i < fcn->nargs; i++)
9785 ha_free(&rule->arg.hlua_rule->args[i]);
9786 ha_free(&rule->arg.hlua_rule->args);
9787 }
9788 ha_free(&rule->arg.hlua_rule);
9789 }
9790 return ACT_RET_PRS_ERR;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009791}
9792
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009793static enum act_parse_ret action_register_service_http(const char **args, int *cur_arg, struct proxy *px,
9794 struct act_rule *rule, char **err)
9795{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02009796 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009797
Thierry FOURNIER718e2a72015-12-20 20:13:14 +01009798 /* HTTP applets are forbidden in tcp-request rules.
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05009799 * HTTP applet request requires everything initialized by
Thierry FOURNIER718e2a72015-12-20 20:13:14 +01009800 * "http_process_request" (analyzer flag AN_REQ_HTTP_INNER).
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05009801 * The applet will be immediately initialized, but its before
Thierry FOURNIER718e2a72015-12-20 20:13:14 +01009802 * the call of this analyzer.
9803 */
9804 if (rule->from != ACT_F_HTTP_REQ) {
9805 memprintf(err, "HTTP applets are forbidden from 'tcp-request' rulesets");
9806 return ACT_RET_PRS_ERR;
9807 }
9808
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009809 /* Memory for the rule. */
9810 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
9811 if (!rule->arg.hlua_rule) {
9812 memprintf(err, "out of memory error");
9813 return ACT_RET_PRS_ERR;
9814 }
9815
9816 /* Reference the Lua function and store the reference. */
Thierry Fournierad5345f2020-11-29 02:05:57 +01009817 rule->arg.hlua_rule->fcn = fcn;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009818
9819 /* TODO: later accept arguments. */
9820 rule->arg.hlua_rule->args = NULL;
9821
9822 /* Add applet pointer in the rule. */
9823 rule->applet.obj_type = OBJ_TYPE_APPLET;
9824 rule->applet.name = fcn->name;
9825 rule->applet.init = hlua_applet_http_init;
9826 rule->applet.fct = hlua_applet_http_fct;
9827 rule->applet.release = hlua_applet_http_release;
9828 rule->applet.timeout = hlua_timeout_applet;
9829
9830 return ACT_RET_PRS_OK;
9831}
9832
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009833/* This function is an LUA binding used for registering
9834 * "sample-conv" functions. It expects a converter name used
9835 * in the haproxy configuration file, and an LUA function.
9836 */
9837__LJMP static int hlua_register_action(lua_State *L)
9838{
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009839 struct action_kw_list *akl = NULL;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009840 const char *name;
9841 int ref;
9842 int len;
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009843 struct hlua_function *fcn = NULL;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009844 int nargs;
Thierry Fournierf67442e2020-11-28 20:41:07 +01009845 struct buffer *trash;
9846 struct action_kw *akw;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009847
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009848 /* Initialise the number of expected arguments at 0. */
9849 nargs = 0;
9850
9851 if (lua_gettop(L) < 3 || lua_gettop(L) > 4)
9852 WILL_LJMP(luaL_error(L, "'register_action' needs between 3 and 4 arguments"));
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009853
9854 /* First argument : converter name. */
9855 name = MAY_LJMP(luaL_checkstring(L, 1));
9856
9857 /* Second argument : environment. */
9858 if (lua_type(L, 2) != LUA_TTABLE)
9859 WILL_LJMP(luaL_error(L, "register_action: second argument must be a table of strings"));
9860
9861 /* Third argument : lua function. */
9862 ref = MAY_LJMP(hlua_checkfunction(L, 3));
9863
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08009864 /* Fourth argument : number of mandatory arguments expected on the configuration line. */
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009865 if (lua_gettop(L) >= 4)
9866 nargs = MAY_LJMP(luaL_checkinteger(L, 4));
9867
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08009868 /* browse the second argument as an array. */
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009869 lua_pushnil(L);
9870 while (lua_next(L, 2) != 0) {
9871 if (lua_type(L, -1) != LUA_TSTRING)
9872 WILL_LJMP(luaL_error(L, "register_action: second argument must be a table of strings"));
9873
Thierry Fournierf67442e2020-11-28 20:41:07 +01009874 /* Check if action exists */
9875 trash = get_trash_chunk();
9876 chunk_printf(trash, "lua.%s", name);
9877 if (strcmp(lua_tostring(L, -1), "tcp-req") == 0) {
9878 akw = tcp_req_cont_action(trash->area);
9879 } else if (strcmp(lua_tostring(L, -1), "tcp-res") == 0) {
9880 akw = tcp_res_cont_action(trash->area);
9881 } else if (strcmp(lua_tostring(L, -1), "http-req") == 0) {
9882 akw = action_http_req_custom(trash->area);
9883 } else if (strcmp(lua_tostring(L, -1), "http-res") == 0) {
9884 akw = action_http_res_custom(trash->area);
9885 } else {
9886 akw = NULL;
9887 }
9888 if (akw != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +01009889 fcn = akw->private;
9890 if (fcn->function_ref[hlua_state_id] != -1) {
9891 ha_warning("Trying to register action 'lua.%s' more than once. "
9892 "This will become a hard error in version 2.5.\n", name);
9893 }
9894 fcn->function_ref[hlua_state_id] = ref;
9895
9896 /* pop the environment string. */
9897 lua_pop(L, 1);
9898 continue;
Thierry Fournierf67442e2020-11-28 20:41:07 +01009899 }
9900
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009901 /* Check required environment. Only accepted "http" or "tcp". */
9902 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02009903 akl = calloc(1, sizeof(*akl) + sizeof(struct action_kw) * 2);
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009904 if (!akl)
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009905 goto alloc_error;;
Thierry Fournier62a22aa2020-11-28 21:06:35 +01009906 fcn = new_hlua_function();
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009907 if (!fcn)
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009908 goto alloc_error;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009909
9910 /* Fill fcn. */
9911 fcn->name = strdup(name);
9912 if (!fcn->name)
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009913 goto alloc_error;
Thierry Fournierc7492592020-11-28 23:57:24 +01009914 fcn->function_ref[hlua_state_id] = ref;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009915
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -07009916 /* Set the expected number of arguments. */
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009917 fcn->nargs = nargs;
9918
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009919 /* List head */
9920 akl->list.n = akl->list.p = NULL;
9921
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009922 /* action keyword. */
9923 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02009924 akl->kw[0].kw = calloc(1, len);
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009925 if (!akl->kw[0].kw)
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009926 goto alloc_error;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009927
9928 snprintf((char *)akl->kw[0].kw, len, "lua.%s", name);
9929
Amaury Denoyellee4a617c2021-05-06 15:33:09 +02009930 akl->kw[0].flags = 0;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009931 akl->kw[0].private = fcn;
9932 akl->kw[0].parse = action_register_lua;
9933
9934 /* select the action registering point. */
9935 if (strcmp(lua_tostring(L, -1), "tcp-req") == 0)
9936 tcp_req_cont_keywords_register(akl);
9937 else if (strcmp(lua_tostring(L, -1), "tcp-res") == 0)
9938 tcp_res_cont_keywords_register(akl);
9939 else if (strcmp(lua_tostring(L, -1), "http-req") == 0)
9940 http_req_keywords_register(akl);
9941 else if (strcmp(lua_tostring(L, -1), "http-res") == 0)
9942 http_res_keywords_register(akl);
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009943 else {
9944 release_hlua_function(fcn);
9945 if (akl)
9946 ha_free((char **)&(akl->kw[0].kw));
9947 ha_free(&akl);
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01009948 WILL_LJMP(luaL_error(L, "Lua action environment '%s' is unknown. "
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009949 "'tcp-req', 'tcp-res', 'http-req' or 'http-res' "
9950 "are expected.", lua_tostring(L, -1)));
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009951 }
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009952
9953 /* pop the environment string. */
9954 lua_pop(L, 1);
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009955
9956 /* reset for next loop */
9957 akl = NULL;
9958 fcn = NULL;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009959 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009960 return ACT_RET_PRS_OK;
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009961
9962 alloc_error:
9963 release_hlua_function(fcn);
9964 ha_free(&akl);
9965 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
9966 return 0; /* Never reached */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009967}
9968
9969static enum act_parse_ret action_register_service_tcp(const char **args, int *cur_arg, struct proxy *px,
9970 struct act_rule *rule, char **err)
9971{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02009972 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009973
Christopher Faulet280f85b2019-07-15 15:02:04 +02009974 if (px->mode == PR_MODE_HTTP) {
9975 memprintf(err, "Lua TCP services cannot be used on HTTP proxies");
Christopher Fauletafd8f102018-11-08 11:34:21 +01009976 return ACT_RET_PRS_ERR;
9977 }
9978
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009979 /* Memory for the rule. */
9980 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
9981 if (!rule->arg.hlua_rule) {
9982 memprintf(err, "out of memory error");
9983 return ACT_RET_PRS_ERR;
9984 }
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009985
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009986 /* Reference the Lua function and store the reference. */
Thierry Fournierad5345f2020-11-29 02:05:57 +01009987 rule->arg.hlua_rule->fcn = fcn;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009988
9989 /* TODO: later accept arguments. */
9990 rule->arg.hlua_rule->args = NULL;
9991
9992 /* Add applet pointer in the rule. */
9993 rule->applet.obj_type = OBJ_TYPE_APPLET;
9994 rule->applet.name = fcn->name;
9995 rule->applet.init = hlua_applet_tcp_init;
9996 rule->applet.fct = hlua_applet_tcp_fct;
9997 rule->applet.release = hlua_applet_tcp_release;
9998 rule->applet.timeout = hlua_timeout_applet;
9999
10000 return 0;
10001}
10002
10003/* This function is an LUA binding used for registering
10004 * "sample-conv" functions. It expects a converter name used
10005 * in the haproxy configuration file, and an LUA function.
10006 */
10007__LJMP static int hlua_register_service(lua_State *L)
10008{
10009 struct action_kw_list *akl;
10010 const char *name;
10011 const char *env;
10012 int ref;
10013 int len;
Christopher Faulet5c028d72021-04-12 15:11:44 +020010014 struct hlua_function *fcn = NULL;
Thierry Fournierf67442e2020-11-28 20:41:07 +010010015 struct buffer *trash;
10016 struct action_kw *akw;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010017
10018 MAY_LJMP(check_args(L, 3, "register_service"));
10019
10020 /* First argument : converter name. */
10021 name = MAY_LJMP(luaL_checkstring(L, 1));
10022
10023 /* Second argument : environment. */
10024 env = MAY_LJMP(luaL_checkstring(L, 2));
10025
10026 /* Third argument : lua function. */
10027 ref = MAY_LJMP(hlua_checkfunction(L, 3));
10028
Thierry Fournierf67442e2020-11-28 20:41:07 +010010029 /* Check for service already registered */
10030 trash = get_trash_chunk();
10031 chunk_printf(trash, "lua.%s", name);
10032 akw = service_find(trash->area);
10033 if (akw != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +010010034 fcn = akw->private;
10035 if (fcn->function_ref[hlua_state_id] != -1) {
10036 ha_warning("Trying to register service 'lua.%s' more than once. "
10037 "This will become a hard error in version 2.5.\n", name);
10038 }
10039 fcn->function_ref[hlua_state_id] = ref;
10040 return 0;
Thierry Fournierf67442e2020-11-28 20:41:07 +010010041 }
10042
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010043 /* Allocate and fill the sample fetch keyword struct. */
10044 akl = calloc(1, sizeof(*akl) + sizeof(struct action_kw) * 2);
10045 if (!akl)
Christopher Faulet5c028d72021-04-12 15:11:44 +020010046 goto alloc_error;
Thierry Fournier62a22aa2020-11-28 21:06:35 +010010047 fcn = new_hlua_function();
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010048 if (!fcn)
Christopher Faulet5c028d72021-04-12 15:11:44 +020010049 goto alloc_error;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010050
10051 /* Fill fcn. */
10052 len = strlen("<lua.>") + strlen(name) + 1;
10053 fcn->name = calloc(1, len);
10054 if (!fcn->name)
Christopher Faulet5c028d72021-04-12 15:11:44 +020010055 goto alloc_error;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010056 snprintf((char *)fcn->name, len, "<lua.%s>", name);
Thierry Fournierc7492592020-11-28 23:57:24 +010010057 fcn->function_ref[hlua_state_id] = ref;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010058
10059 /* List head */
10060 akl->list.n = akl->list.p = NULL;
10061
10062 /* converter keyword. */
10063 len = strlen("lua.") + strlen(name) + 1;
10064 akl->kw[0].kw = calloc(1, len);
10065 if (!akl->kw[0].kw)
Christopher Faulet5c028d72021-04-12 15:11:44 +020010066 goto alloc_error;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010067
10068 snprintf((char *)akl->kw[0].kw, len, "lua.%s", name);
10069
Thierry FOURNIER / OZON.IO02564fd2016-11-12 11:07:05 +010010070 /* Check required environment. Only accepted "http" or "tcp". */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010071 if (strcmp(env, "tcp") == 0)
10072 akl->kw[0].parse = action_register_service_tcp;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010073 else if (strcmp(env, "http") == 0)
10074 akl->kw[0].parse = action_register_service_http;
Christopher Faulet5c028d72021-04-12 15:11:44 +020010075 else {
10076 release_hlua_function(fcn);
10077 if (akl)
10078 ha_free((char **)&(akl->kw[0].kw));
10079 ha_free(&akl);
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +010010080 WILL_LJMP(luaL_error(L, "Lua service environment '%s' is unknown. "
Eric Salamafe7456f2017-12-21 14:30:07 +010010081 "'tcp' or 'http' are expected.", env));
Christopher Faulet5c028d72021-04-12 15:11:44 +020010082 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010083
Amaury Denoyellee4a617c2021-05-06 15:33:09 +020010084 akl->kw[0].flags = 0;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010085 akl->kw[0].private = fcn;
10086
10087 /* End of array. */
10088 memset(&akl->kw[1], 0, sizeof(*akl->kw));
10089
10090 /* Register this new converter */
10091 service_keywords_register(akl);
10092
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010093 return 0;
Christopher Faulet5c028d72021-04-12 15:11:44 +020010094
10095 alloc_error:
10096 release_hlua_function(fcn);
10097 ha_free(&akl);
10098 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
10099 return 0; /* Never reached */
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010100}
10101
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010102/* This function initialises Lua cli handler. It copies the
10103 * arguments in the Lua stack and create channel IO objects.
10104 */
Aurélien Nephtaliabbf6072018-04-18 13:26:46 +020010105static int hlua_cli_parse_fct(char **args, char *payload, struct appctx *appctx, void *private)
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010106{
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010107 struct hlua_cli_ctx *ctx = applet_reserve_svcctx(appctx, sizeof(*ctx));
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010108 struct hlua *hlua;
10109 struct hlua_function *fcn;
10110 int i;
10111 const char *error;
10112
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010113 fcn = private;
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010114 ctx->fcn = private;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +010010115
Willy Tarreaubafbe012017-11-24 17:34:44 +010010116 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +010010117 if (!hlua) {
10118 SEND_ERR(NULL, "Lua cli '%s': out of memory.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +010010119 return 1;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +010010120 }
10121 HLUA_INIT(hlua);
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010122 ctx->hlua = hlua;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010123
10124 /* Create task used by signal to wakeup applets.
Ilya Shipitsind4259502020-04-08 01:07:56 +050010125 * We use the same wakeup function than the Lua applet_tcp and
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010126 * applet_http. It is absolutely compatible.
10127 */
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010128 ctx->task = task_new_here();
10129 if (!ctx->task) {
Thierry FOURNIERffbf5692016-12-16 11:14:06 +010010130 SEND_ERR(NULL, "Lua cli '%s': out of memory.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +010010131 goto error;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010132 }
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010133 ctx->task->nice = 0;
10134 ctx->task->context = appctx;
10135 ctx->task->process = hlua_applet_wakeup;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010136
10137 /* Initialises the Lua context */
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010138 if (!hlua_ctx_init(hlua, fcn_ref_to_stack_id(fcn), ctx->task, 0)) {
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010139 SEND_ERR(NULL, "Lua cli '%s': can't initialize Lua context.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +010010140 goto error;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010141 }
10142
10143 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010144 if (!SET_SAFE_LJMP(hlua)) {
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010145 if (lua_type(hlua->T, -1) == LUA_TSTRING)
10146 error = lua_tostring(hlua->T, -1);
10147 else
10148 error = "critical error";
10149 SEND_ERR(NULL, "Lua cli '%s': %s.\n", fcn->name, error);
10150 goto error;
10151 }
10152
10153 /* Check stack available size. */
10154 if (!lua_checkstack(hlua->T, 2)) {
10155 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
10156 goto error;
10157 }
10158
10159 /* Restore the function in the stack. */
Thierry Fournierc7492592020-11-28 23:57:24 +010010160 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, fcn->function_ref[hlua->state_id]);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010161
10162 /* Once the arguments parsed, the CLI is like an AppletTCP,
10163 * so push AppletTCP in the stack.
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010164 */
10165 if (!hlua_applet_tcp_new(hlua->T, appctx)) {
10166 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
10167 goto error;
10168 }
10169 hlua->nargs = 1;
10170
10171 /* push keywords in the stack. */
10172 for (i = 0; *args[i]; i++) {
10173 /* Check stack available size. */
10174 if (!lua_checkstack(hlua->T, 1)) {
10175 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
10176 goto error;
10177 }
10178 lua_pushstring(hlua->T, args[i]);
10179 hlua->nargs++;
10180 }
10181
10182 /* We must initialize the execution timeouts. */
10183 hlua->max_time = hlua_timeout_session;
10184
10185 /* At this point the execution is safe. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010186 RESET_SAFE_LJMP(hlua);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010187
10188 /* It's ok */
10189 return 0;
10190
10191 /* It's not ok. */
10192error:
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010193 RESET_SAFE_LJMP(hlua);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010194 hlua_ctx_destroy(hlua);
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010195 ctx->hlua = NULL;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010196 return 1;
10197}
10198
10199static int hlua_cli_io_handler_fct(struct appctx *appctx)
10200{
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010201 struct hlua_cli_ctx *ctx = appctx->svcctx;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010202 struct hlua *hlua;
Willy Tarreau475e4632022-05-27 10:26:46 +020010203 struct stconn *sc;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010204 struct hlua_function *fcn;
10205
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010206 hlua = ctx->hlua;
Willy Tarreauc12b3212022-05-27 11:08:15 +020010207 sc = appctx_sc(appctx);
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010208 fcn = ctx->fcn;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010209
10210 /* If the stream is disconnect or closed, ldo nothing. */
Willy Tarreau475e4632022-05-27 10:26:46 +020010211 if (unlikely(sc->state == SC_ST_DIS || sc->state == SC_ST_CLO))
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010212 return 1;
10213
10214 /* Execute the function. */
10215 switch (hlua_ctx_resume(hlua, 1)) {
10216
10217 /* finished. */
10218 case HLUA_E_OK:
10219 return 1;
10220
10221 /* yield. */
10222 case HLUA_E_AGAIN:
10223 /* We want write. */
10224 if (HLUA_IS_WAKERESWR(hlua))
Willy Tarreau475e4632022-05-27 10:26:46 +020010225 sc_need_room(sc);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010226 /* Set the timeout. */
10227 if (hlua->wake_time != TICK_ETERNITY)
10228 task_schedule(hlua->task, hlua->wake_time);
10229 return 0;
10230
10231 /* finished with error. */
10232 case HLUA_E_ERRMSG:
10233 /* Display log. */
10234 SEND_ERR(NULL, "Lua cli '%s': %s.\n",
10235 fcn->name, lua_tostring(hlua->T, -1));
10236 lua_pop(hlua->T, 1);
10237 return 1;
10238
Thierry Fournierd5b073c2018-05-21 19:42:47 +020010239 case HLUA_E_ETMOUT:
10240 SEND_ERR(NULL, "Lua converter '%s': execution timeout.\n",
10241 fcn->name);
10242 return 1;
10243
10244 case HLUA_E_NOMEM:
10245 SEND_ERR(NULL, "Lua converter '%s': out of memory error.\n",
10246 fcn->name);
10247 return 1;
10248
10249 case HLUA_E_YIELD: /* unexpected */
10250 SEND_ERR(NULL, "Lua converter '%s': yield not allowed.\n",
10251 fcn->name);
10252 return 1;
10253
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010254 case HLUA_E_ERR:
10255 /* Display log. */
10256 SEND_ERR(NULL, "Lua cli '%s' return an unknown error.\n",
10257 fcn->name);
10258 return 1;
10259
10260 default:
10261 return 1;
10262 }
10263
10264 return 1;
10265}
10266
10267static void hlua_cli_io_release_fct(struct appctx *appctx)
10268{
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010269 struct hlua_cli_ctx *ctx = appctx->svcctx;
10270
10271 hlua_ctx_destroy(ctx->hlua);
10272 ctx->hlua = NULL;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010273}
10274
10275/* This function is an LUA binding used for registering
10276 * new keywords in the cli. It expects a list of keywords
10277 * which are the "path". It is limited to 5 keywords. A
10278 * description of the command, a function to be executed
10279 * for the parsing and a function for io handlers.
10280 */
10281__LJMP static int hlua_register_cli(lua_State *L)
10282{
10283 struct cli_kw_list *cli_kws;
10284 const char *message;
10285 int ref_io;
10286 int len;
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010287 struct hlua_function *fcn = NULL;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010288 int index;
10289 int i;
Thierry Fournierf67442e2020-11-28 20:41:07 +010010290 struct buffer *trash;
10291 const char *kw[5];
10292 struct cli_kw *cli_kw;
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010293 const char *errmsg;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010294
10295 MAY_LJMP(check_args(L, 3, "register_cli"));
10296
10297 /* First argument : an array of maximum 5 keywords. */
10298 if (!lua_istable(L, 1))
10299 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table"));
10300
10301 /* Second argument : string with contextual message. */
10302 message = MAY_LJMP(luaL_checkstring(L, 2));
10303
10304 /* Third and fourth argument : lua function. */
10305 ref_io = MAY_LJMP(hlua_checkfunction(L, 3));
10306
Thierry Fournierf67442e2020-11-28 20:41:07 +010010307 /* Check for CLI service already registered */
10308 trash = get_trash_chunk();
10309 index = 0;
10310 lua_pushnil(L);
10311 memset(kw, 0, sizeof(kw));
10312 while (lua_next(L, 1) != 0) {
10313 if (index >= CLI_PREFIX_KW_NB)
10314 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table with a maximum of 5 entries"));
10315 if (lua_type(L, -1) != LUA_TSTRING)
10316 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table filled with strings"));
10317 kw[index] = lua_tostring(L, -1);
10318 if (index == 0)
10319 chunk_printf(trash, "%s", kw[index]);
10320 else
10321 chunk_appendf(trash, " %s", kw[index]);
10322 index++;
10323 lua_pop(L, 1);
10324 }
10325 cli_kw = cli_find_kw_exact((char **)kw);
10326 if (cli_kw != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +010010327 fcn = cli_kw->private;
10328 if (fcn->function_ref[hlua_state_id] != -1) {
10329 ha_warning("Trying to register CLI keyword 'lua.%s' more than once. "
10330 "This will become a hard error in version 2.5.\n", trash->area);
10331 }
10332 fcn->function_ref[hlua_state_id] = ref_io;
10333 return 0;
Thierry Fournierf67442e2020-11-28 20:41:07 +010010334 }
10335
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010336 /* Allocate and fill the sample fetch keyword struct. */
10337 cli_kws = calloc(1, sizeof(*cli_kws) + sizeof(struct cli_kw) * 2);
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010338 if (!cli_kws) {
10339 errmsg = "Lua out of memory error.";
10340 goto error;
10341 }
Thierry Fournier62a22aa2020-11-28 21:06:35 +010010342 fcn = new_hlua_function();
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010343 if (!fcn) {
10344 errmsg = "Lua out of memory error.";
10345 goto error;
10346 }
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010347
10348 /* Fill path. */
10349 index = 0;
10350 lua_pushnil(L);
10351 while(lua_next(L, 1) != 0) {
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010352 if (index >= 5) {
10353 errmsg = "1st argument must be a table with a maximum of 5 entries";
10354 goto error;
10355 }
10356 if (lua_type(L, -1) != LUA_TSTRING) {
10357 errmsg = "1st argument must be a table filled with strings";
10358 goto error;
10359 }
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010360 cli_kws->kw[0].str_kw[index] = strdup(lua_tostring(L, -1));
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010361 if (!cli_kws->kw[0].str_kw[index]) {
10362 errmsg = "Lua out of memory error.";
10363 goto error;
10364 }
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010365 index++;
10366 lua_pop(L, 1);
10367 }
10368
10369 /* Copy help message. */
10370 cli_kws->kw[0].usage = strdup(message);
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010371 if (!cli_kws->kw[0].usage) {
10372 errmsg = "Lua out of memory error.";
10373 goto error;
10374 }
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010375
10376 /* Fill fcn io handler. */
10377 len = strlen("<lua.cli>") + 1;
10378 for (i = 0; i < index; i++)
10379 len += strlen(cli_kws->kw[0].str_kw[i]) + 1;
10380 fcn->name = calloc(1, len);
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010381 if (!fcn->name) {
10382 errmsg = "Lua out of memory error.";
10383 goto error;
10384 }
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010385 strncat((char *)fcn->name, "<lua.cli", len);
10386 for (i = 0; i < index; i++) {
10387 strncat((char *)fcn->name, ".", len);
10388 strncat((char *)fcn->name, cli_kws->kw[0].str_kw[i], len);
10389 }
10390 strncat((char *)fcn->name, ">", len);
Thierry Fournierc7492592020-11-28 23:57:24 +010010391 fcn->function_ref[hlua_state_id] = ref_io;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010392
10393 /* Fill last entries. */
10394 cli_kws->kw[0].private = fcn;
10395 cli_kws->kw[0].parse = hlua_cli_parse_fct;
10396 cli_kws->kw[0].io_handler = hlua_cli_io_handler_fct;
10397 cli_kws->kw[0].io_release = hlua_cli_io_release_fct;
10398
10399 /* Register this new converter */
10400 cli_register_kw(cli_kws);
10401
10402 return 0;
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010403
10404 error:
10405 release_hlua_function(fcn);
10406 if (cli_kws) {
10407 for (i = 0; i < index; i++)
10408 ha_free((char **)&(cli_kws->kw[0].str_kw[i]));
10409 ha_free((char **)&(cli_kws->kw[0].usage));
10410 }
10411 ha_free(&cli_kws);
10412 WILL_LJMP(luaL_error(L, errmsg));
10413 return 0; /* Never reached */
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010414}
10415
Christopher Faulet69c581a2021-05-31 08:54:04 +020010416static int hlua_filter_init_per_thread(struct proxy *px, struct flt_conf *fconf)
10417{
10418 struct hlua_flt_config *conf = fconf->conf;
10419 lua_State *L;
10420 int error, pos, state_id, flt_ref;
10421
10422 state_id = reg_flt_to_stack_id(conf->reg);
10423 L = hlua_states[state_id];
10424 pos = lua_gettop(L);
10425
10426 /* The filter parsing function */
10427 lua_rawgeti(L, LUA_REGISTRYINDEX, conf->reg->fun_ref[state_id]);
10428
10429 /* Push the filter class on the stack and resolve all callbacks */
10430 lua_rawgeti(L, LUA_REGISTRYINDEX, conf->reg->flt_ref[state_id]);
10431
10432 /* Duplicate the filter class so each filter will have its own copy */
10433 lua_newtable(L);
10434 lua_pushnil(L);
10435
10436 while (lua_next(L, pos+2)) {
10437 lua_pushvalue(L, -2);
10438 lua_insert(L, -2);
10439 lua_settable(L, -4);
10440 }
10441 flt_ref = luaL_ref(L, LUA_REGISTRYINDEX);
10442
10443 /* Remove the original lua filter class from the stack */
10444 lua_pop(L, 1);
10445
10446 /* Push the copy on the stack */
10447 lua_rawgeti(L, LUA_REGISTRYINDEX, flt_ref);
10448
10449 /* extra args are pushed in a table */
10450 lua_newtable(L);
10451 for (pos = 0; conf->args[pos]; pos++) {
10452 /* Check stack available size. */
10453 if (!lua_checkstack(L, 1)) {
10454 ha_alert("Lua filter '%s' : Lua error : full stack.", conf->reg->name);
10455 goto error;
10456 }
10457 lua_pushstring(L, conf->args[pos]);
10458 lua_rawseti(L, -2, lua_rawlen(L, -2) + 1);
10459 }
10460
10461 error = lua_pcall(L, 2, LUA_MULTRET, 0);
10462 switch (error) {
10463 case LUA_OK:
10464 /* replace the filter ref */
10465 conf->ref[state_id] = flt_ref;
10466 break;
10467 case LUA_ERRRUN:
10468 ha_alert("Lua filter '%s' : runtime error : %s", conf->reg->name, lua_tostring(L, -1));
10469 goto error;
10470 case LUA_ERRMEM:
10471 ha_alert("Lua filter '%s' : out of memory error", conf->reg->name);
10472 goto error;
10473 case LUA_ERRERR:
10474 ha_alert("Lua filter '%s' : message handler error : %s", conf->reg->name, lua_tostring(L, -1));
10475 goto error;
10476#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM <= 503
10477 case LUA_ERRGCMM:
10478 ha_alert("Lua filter '%s' : garbage collector error : %s", conf->reg->name, lua_tostring(L, -1));
10479 goto error;
10480#endif
10481 default:
Ilya Shipitsinff0f2782021-08-22 22:18:07 +050010482 ha_alert("Lua filter '%s' : unknown error : %s", conf->reg->name, lua_tostring(L, -1));
Christopher Faulet69c581a2021-05-31 08:54:04 +020010483 goto error;
10484 }
10485
10486 lua_settop(L, 0);
10487 return 0;
10488
10489 error:
10490 lua_settop(L, 0);
10491 return -1;
10492}
10493
10494static void hlua_filter_deinit_per_thread(struct proxy *px, struct flt_conf *fconf)
10495{
10496 struct hlua_flt_config *conf = fconf->conf;
10497 lua_State *L;
10498 int state_id;
10499
10500 if (!conf)
10501 return;
10502
10503 state_id = reg_flt_to_stack_id(conf->reg);
10504 L = hlua_states[state_id];
10505 luaL_unref(L, LUA_REGISTRYINDEX, conf->ref[state_id]);
10506}
10507
10508static int hlua_filter_init(struct proxy *px, struct flt_conf *fconf)
10509{
10510 struct hlua_flt_config *conf = fconf->conf;
10511 int state_id = reg_flt_to_stack_id(conf->reg);
10512
10513 /* Rely on per-thread init for global scripts */
10514 if (!state_id)
10515 return hlua_filter_init_per_thread(px, fconf);
10516 return 0;
10517}
10518
10519static void hlua_filter_deinit(struct proxy *px, struct flt_conf *fconf)
10520{
10521
10522 if (fconf->conf) {
10523 struct hlua_flt_config *conf = fconf->conf;
10524 int state_id = reg_flt_to_stack_id(conf->reg);
10525 int pos;
10526
10527 /* Rely on per-thread deinit for global scripts */
10528 if (!state_id)
10529 hlua_filter_deinit_per_thread(px, fconf);
10530
10531 for (pos = 0; conf->args[pos]; pos++)
10532 free(conf->args[pos]);
10533 free(conf->args);
10534 }
10535 ha_free(&fconf->conf);
10536 ha_free((char **)&fconf->id);
10537 ha_free(&fconf->ops);
10538}
10539
10540static int hlua_filter_new(struct stream *s, struct filter *filter)
10541{
10542 struct hlua_flt_config *conf = FLT_CONF(filter);
10543 struct hlua_flt_ctx *flt_ctx = NULL;
10544 int ret = 1;
10545
10546 /* In the execution wrappers linked with a stream, the
10547 * Lua context can be not initialized. This behavior
10548 * permits to save performances because a systematic
10549 * Lua initialization cause 5% performances loss.
10550 */
10551 if (!s->hlua) {
10552 struct hlua *hlua;
10553
10554 hlua = pool_alloc(pool_head_hlua);
10555 if (!hlua) {
10556 SEND_ERR(s->be, "Lua filter '%s': can't initialize Lua context.\n",
10557 conf->reg->name);
10558 ret = 0;
10559 goto end;
10560 }
10561 HLUA_INIT(hlua);
10562 s->hlua = hlua;
10563 if (!hlua_ctx_init(s->hlua, reg_flt_to_stack_id(conf->reg), s->task, 0)) {
10564 SEND_ERR(s->be, "Lua filter '%s': can't initialize Lua context.\n",
10565 conf->reg->name);
10566 ret = 0;
10567 goto end;
10568 }
10569 }
10570
10571 flt_ctx = pool_zalloc(pool_head_hlua_flt_ctx);
10572 if (!flt_ctx) {
10573 SEND_ERR(s->be, "Lua filter '%s': can't initialize filter Lua context.\n",
10574 conf->reg->name);
10575 ret = 0;
10576 goto end;
10577 }
10578 flt_ctx->hlua[0] = pool_alloc(pool_head_hlua);
10579 flt_ctx->hlua[1] = pool_alloc(pool_head_hlua);
10580 if (!flt_ctx->hlua[0] || !flt_ctx->hlua[1]) {
10581 SEND_ERR(s->be, "Lua filter '%s': can't initialize filter Lua context.\n",
10582 conf->reg->name);
10583 ret = 0;
10584 goto end;
10585 }
10586 HLUA_INIT(flt_ctx->hlua[0]);
10587 HLUA_INIT(flt_ctx->hlua[1]);
10588 if (!hlua_ctx_init(flt_ctx->hlua[0], reg_flt_to_stack_id(conf->reg), s->task, 0) ||
10589 !hlua_ctx_init(flt_ctx->hlua[1], reg_flt_to_stack_id(conf->reg), s->task, 0)) {
10590 SEND_ERR(s->be, "Lua filter '%s': can't initialize filter Lua context.\n",
10591 conf->reg->name);
10592 ret = 0;
10593 goto end;
10594 }
10595
10596 if (!HLUA_IS_RUNNING(s->hlua)) {
10597 /* The following Lua calls can fail. */
10598 if (!SET_SAFE_LJMP(s->hlua)) {
10599 const char *error;
10600
10601 if (lua_type(s->hlua->T, -1) == LUA_TSTRING)
10602 error = lua_tostring(s->hlua->T, -1);
10603 else
10604 error = "critical error";
10605 SEND_ERR(s->be, "Lua filter '%s': %s.\n", conf->reg->name, error);
10606 ret = 0;
10607 goto end;
10608 }
10609
10610 /* Check stack size. */
10611 if (!lua_checkstack(s->hlua->T, 1)) {
10612 SEND_ERR(s->be, "Lua filter '%s': full stack.\n", conf->reg->name);
Tim Duesterhus22817382021-09-11 23:17:25 +020010613 RESET_SAFE_LJMP(s->hlua);
Christopher Faulet69c581a2021-05-31 08:54:04 +020010614 ret = 0;
10615 goto end;
10616 }
10617
10618 lua_rawgeti(s->hlua->T, LUA_REGISTRYINDEX, conf->ref[s->hlua->state_id]);
10619 if (lua_getfield(s->hlua->T, -1, "new") != LUA_TFUNCTION) {
10620 SEND_ERR(s->be, "Lua filter '%s': 'new' field is not a function.\n",
10621 conf->reg->name);
10622 RESET_SAFE_LJMP(s->hlua);
10623 ret = 0;
10624 goto end;
10625 }
10626 lua_insert(s->hlua->T, -2);
10627
10628 /* Push the copy on the stack */
10629 s->hlua->nargs = 1;
10630
10631 /* We must initialize the execution timeouts. */
10632 s->hlua->max_time = hlua_timeout_session;
10633
10634 /* At this point the execution is safe. */
10635 RESET_SAFE_LJMP(s->hlua);
10636 }
10637
10638 switch (hlua_ctx_resume(s->hlua, 0)) {
10639 case HLUA_E_OK:
10640 /* Nothing returned or not a table, ignore the filter for current stream */
10641 if (!lua_gettop(s->hlua->T) || !lua_istable(s->hlua->T, 1)) {
10642 ret = 0;
10643 goto end;
10644 }
10645
10646 /* Attached the filter pointer to the ctx */
10647 lua_pushstring(s->hlua->T, "__filter");
10648 lua_pushlightuserdata(s->hlua->T, filter);
10649 lua_settable(s->hlua->T, -3);
10650
10651 /* Save a ref on the filter ctx */
10652 lua_pushvalue(s->hlua->T, 1);
10653 flt_ctx->ref = luaL_ref(s->hlua->T, LUA_REGISTRYINDEX);
10654 filter->ctx = flt_ctx;
10655 break;
10656 case HLUA_E_ERRMSG:
10657 SEND_ERR(s->be, "Lua filter '%s' : %s.\n", conf->reg->name, lua_tostring(s->hlua->T, -1));
10658 ret = -1;
10659 goto end;
10660 case HLUA_E_ETMOUT:
10661 SEND_ERR(s->be, "Lua filter '%s' : 'new' execution timeout.\n", conf->reg->name);
10662 ret = 0;
10663 goto end;
10664 case HLUA_E_NOMEM:
10665 SEND_ERR(s->be, "Lua filter '%s' : out of memory error.\n", conf->reg->name);
10666 ret = 0;
10667 goto end;
10668 case HLUA_E_AGAIN:
10669 case HLUA_E_YIELD:
10670 SEND_ERR(s->be, "Lua filter '%s': yield functions like core.tcp() or core.sleep()"
10671 " are not allowed from 'new' function.\n", conf->reg->name);
10672 ret = 0;
10673 goto end;
10674 case HLUA_E_ERR:
10675 SEND_ERR(s->be, "Lua filter '%s': 'new' returns an unknown error.\n", conf->reg->name);
10676 ret = 0;
10677 goto end;
10678 default:
10679 ret = 0;
10680 goto end;
10681 }
10682
10683 end:
10684 if (s->hlua)
10685 lua_settop(s->hlua->T, 0);
10686 if (ret <= 0) {
10687 if (flt_ctx) {
10688 hlua_ctx_destroy(flt_ctx->hlua[0]);
10689 hlua_ctx_destroy(flt_ctx->hlua[1]);
10690 pool_free(pool_head_hlua_flt_ctx, flt_ctx);
10691 }
10692 }
10693 return ret;
10694}
10695
10696static void hlua_filter_delete(struct stream *s, struct filter *filter)
10697{
10698 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10699
10700 luaL_unref(s->hlua->T, LUA_REGISTRYINDEX, flt_ctx->ref);
10701 hlua_ctx_destroy(flt_ctx->hlua[0]);
10702 hlua_ctx_destroy(flt_ctx->hlua[1]);
10703 pool_free(pool_head_hlua_flt_ctx, flt_ctx);
10704 filter->ctx = NULL;
10705}
10706
Christopher Faulet9f55a502020-02-25 15:21:02 +010010707static int hlua_filter_from_payload(struct filter *filter)
10708{
10709 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10710
10711 return (flt_ctx && !!(flt_ctx->flags & HLUA_FLT_CTX_FL_PAYLOAD));
10712}
10713
Christopher Fauletc404f112020-02-26 15:03:09 +010010714static int hlua_filter_callback(struct stream *s, struct filter *filter, const char *fun,
10715 int dir, unsigned int flags)
10716{
10717 struct hlua *flt_hlua;
10718 struct hlua_flt_config *conf = FLT_CONF(filter);
10719 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10720 unsigned int hflags = HLUA_TXN_FLT_CTX;
10721 int ret = 1;
10722
10723 flt_hlua = flt_ctx->hlua[(dir == SMP_OPT_DIR_REQ ? 0 : 1)];
10724 if (!flt_hlua)
10725 goto end;
10726
10727 if (!HLUA_IS_RUNNING(flt_hlua)) {
10728 int extra_idx = lua_gettop(flt_hlua->T);
10729
10730 /* The following Lua calls can fail. */
10731 if (!SET_SAFE_LJMP(flt_hlua)) {
10732 const char *error;
10733
10734 if (lua_type(flt_hlua->T, -1) == LUA_TSTRING)
10735 error = lua_tostring(flt_hlua->T, -1);
10736 else
10737 error = "critical error";
10738 SEND_ERR(s->be, "Lua filter '%s': %s.\n", conf->reg->name, error);
10739 goto end;
10740 }
10741
10742 /* Check stack size. */
10743 if (!lua_checkstack(flt_hlua->T, 3)) {
10744 SEND_ERR(s->be, "Lua filter '%s': full stack.\n", conf->reg->name);
10745 RESET_SAFE_LJMP(flt_hlua);
10746 goto end;
10747 }
10748
10749 lua_rawgeti(flt_hlua->T, LUA_REGISTRYINDEX, flt_ctx->ref);
10750 if (lua_getfield(flt_hlua->T, -1, fun) != LUA_TFUNCTION) {
10751 RESET_SAFE_LJMP(flt_hlua);
10752 goto end;
10753 }
10754 lua_insert(flt_hlua->T, -2);
10755
10756 if (!hlua_txn_new(flt_hlua->T, s, s->be, dir, hflags)) {
10757 SEND_ERR(s->be, "Lua filter '%s': full stack.\n", conf->reg->name);
10758 RESET_SAFE_LJMP(flt_hlua);
10759 goto end;
10760 }
10761 flt_hlua->nargs = 2;
10762
10763 if (flags & HLUA_FLT_CB_ARG_CHN) {
10764 if (dir == SMP_OPT_DIR_REQ)
10765 lua_getfield(flt_hlua->T, -1, "req");
10766 else
10767 lua_getfield(flt_hlua->T, -1, "res");
10768 if (lua_type(flt_hlua->T, -1) == LUA_TTABLE) {
10769 lua_pushstring(flt_hlua->T, "__filter");
10770 lua_pushlightuserdata(flt_hlua->T, filter);
10771 lua_settable(flt_hlua->T, -3);
10772 }
10773 flt_hlua->nargs++;
10774 }
10775 else if (flags & HLUA_FLT_CB_ARG_HTTP_MSG) {
Christopher Fauleteae8afa2020-02-26 17:15:48 +010010776 if (dir == SMP_OPT_DIR_REQ)
10777 lua_getfield(flt_hlua->T, -1, "http_req");
10778 else
10779 lua_getfield(flt_hlua->T, -1, "http_res");
10780 if (lua_type(flt_hlua->T, -1) == LUA_TTABLE) {
10781 lua_pushstring(flt_hlua->T, "__filter");
10782 lua_pushlightuserdata(flt_hlua->T, filter);
10783 lua_settable(flt_hlua->T, -3);
10784 }
10785 flt_hlua->nargs++;
Christopher Fauletc404f112020-02-26 15:03:09 +010010786 }
10787
10788 /* Check stack size. */
10789 if (!lua_checkstack(flt_hlua->T, 1)) {
10790 SEND_ERR(s->be, "Lua filter '%s': full stack.\n", conf->reg->name);
10791 RESET_SAFE_LJMP(flt_hlua);
10792 goto end;
10793 }
10794
10795 while (extra_idx--) {
10796 lua_pushvalue(flt_hlua->T, 1);
10797 lua_remove(flt_hlua->T, 1);
10798 flt_hlua->nargs++;
10799 }
10800
10801 /* We must initialize the execution timeouts. */
10802 flt_hlua->max_time = hlua_timeout_session;
10803
10804 /* At this point the execution is safe. */
10805 RESET_SAFE_LJMP(flt_hlua);
10806 }
10807
10808 switch (hlua_ctx_resume(flt_hlua, !(flags & HLUA_FLT_CB_FINAL))) {
10809 case HLUA_E_OK:
10810 /* Catch the return value if it required */
10811 if ((flags & HLUA_FLT_CB_RETVAL) && lua_gettop(flt_hlua->T) > 0) {
10812 ret = lua_tointeger(flt_hlua->T, -1);
10813 lua_settop(flt_hlua->T, 0); /* Empty the stack. */
10814 }
10815
10816 /* Set timeout in the required channel. */
10817 if (flt_hlua->wake_time != TICK_ETERNITY) {
10818 if (dir == SMP_OPT_DIR_REQ)
10819 s->req.analyse_exp = flt_hlua->wake_time;
10820 else
10821 s->res.analyse_exp = flt_hlua->wake_time;
10822 }
10823 break;
10824 case HLUA_E_AGAIN:
10825 /* Set timeout in the required channel. */
10826 if (flt_hlua->wake_time != TICK_ETERNITY) {
10827 if (dir == SMP_OPT_DIR_REQ)
10828 s->req.analyse_exp = flt_hlua->wake_time;
10829 else
10830 s->res.analyse_exp = flt_hlua->wake_time;
10831 }
10832 /* Some actions can be wake up when a "write" event
10833 * is detected on a response channel. This is useful
10834 * only for actions targeted on the requests.
10835 */
10836 if (HLUA_IS_WAKERESWR(flt_hlua))
10837 s->res.flags |= CF_WAKE_WRITE;
10838 if (HLUA_IS_WAKEREQWR(flt_hlua))
10839 s->req.flags |= CF_WAKE_WRITE;
10840 ret = 0;
10841 goto end;
10842 case HLUA_E_ERRMSG:
10843 SEND_ERR(s->be, "Lua filter '%s' : %s.\n", conf->reg->name, lua_tostring(flt_hlua->T, -1));
10844 ret = -1;
10845 goto end;
10846 case HLUA_E_ETMOUT:
10847 SEND_ERR(s->be, "Lua filter '%s' : '%s' callback execution timeout.\n", conf->reg->name, fun);
10848 goto end;
10849 case HLUA_E_NOMEM:
10850 SEND_ERR(s->be, "Lua filter '%s' : out of memory error.\n", conf->reg->name);
10851 goto end;
10852 case HLUA_E_YIELD:
10853 SEND_ERR(s->be, "Lua filter '%s': yield functions like core.tcp() or core.sleep()"
10854 " are not allowed from '%s' callback.\n", conf->reg->name, fun);
10855 goto end;
10856 case HLUA_E_ERR:
10857 SEND_ERR(s->be, "Lua filter '%s': '%s' returns an unknown error.\n", conf->reg->name, fun);
10858 goto end;
10859 default:
10860 goto end;
10861 }
10862
10863
10864 end:
10865 return ret;
10866}
10867
10868static int hlua_filter_start_analyze(struct stream *s, struct filter *filter, struct channel *chn)
10869{
10870 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10871
10872 flt_ctx->flags = 0;
10873 return hlua_filter_callback(s, filter, "start_analyze",
10874 (!(chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES),
10875 (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_RETVAL | HLUA_FLT_CB_ARG_CHN));
10876}
10877
10878static int hlua_filter_end_analyze(struct stream *s, struct filter *filter, struct channel *chn)
10879{
10880 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10881
10882 flt_ctx->flags &= ~HLUA_FLT_CTX_FL_PAYLOAD;
10883 return hlua_filter_callback(s, filter, "end_analyze",
10884 (!(chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES),
10885 (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_RETVAL | HLUA_FLT_CB_ARG_CHN));
10886}
10887
Christopher Fauleteae8afa2020-02-26 17:15:48 +010010888static int hlua_filter_http_headers(struct stream *s, struct filter *filter, struct http_msg *msg)
10889{
10890 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10891
10892 flt_ctx->flags &= ~HLUA_FLT_CTX_FL_PAYLOAD;
10893 return hlua_filter_callback(s, filter, "http_headers",
10894 (!(msg->chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES),
10895 (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_RETVAL | HLUA_FLT_CB_ARG_HTTP_MSG));
10896}
10897
10898static int hlua_filter_http_payload(struct stream *s, struct filter *filter, struct http_msg *msg,
10899 unsigned int offset, unsigned int len)
10900{
10901 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10902 struct hlua *flt_hlua;
10903 int dir = (!(msg->chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES);
10904 int idx = (dir == SMP_OPT_DIR_REQ ? 0 : 1);
10905 int ret;
10906
10907 flt_hlua = flt_ctx->hlua[idx];
10908 flt_ctx->cur_off[idx] = offset;
10909 flt_ctx->cur_len[idx] = len;
10910 flt_ctx->flags |= HLUA_FLT_CTX_FL_PAYLOAD;
10911 ret = hlua_filter_callback(s, filter, "http_payload", dir, (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_ARG_HTTP_MSG));
10912 if (ret != -1) {
10913 ret = flt_ctx->cur_len[idx];
10914 if (lua_gettop(flt_hlua->T) > 0) {
10915 ret = lua_tointeger(flt_hlua->T, -1);
10916 if (ret > flt_ctx->cur_len[idx])
10917 ret = flt_ctx->cur_len[idx];
10918 lua_settop(flt_hlua->T, 0); /* Empty the stack. */
10919 }
10920 }
10921 return ret;
10922}
10923
10924static int hlua_filter_http_end(struct stream *s, struct filter *filter, struct http_msg *msg)
10925{
10926 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10927
10928 flt_ctx->flags &= ~HLUA_FLT_CTX_FL_PAYLOAD;
10929 return hlua_filter_callback(s, filter, "http_end",
10930 (!(msg->chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES),
10931 (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_RETVAL | HLUA_FLT_CB_ARG_HTTP_MSG));
10932}
10933
Christopher Fauletc404f112020-02-26 15:03:09 +010010934static int hlua_filter_tcp_payload(struct stream *s, struct filter *filter, struct channel *chn,
10935 unsigned int offset, unsigned int len)
10936{
10937 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10938 struct hlua *flt_hlua;
10939 int dir = (!(chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES);
10940 int idx = (dir == SMP_OPT_DIR_REQ ? 0 : 1);
10941 int ret;
10942
10943 flt_hlua = flt_ctx->hlua[idx];
10944 flt_ctx->cur_off[idx] = offset;
10945 flt_ctx->cur_len[idx] = len;
10946 flt_ctx->flags |= HLUA_FLT_CTX_FL_PAYLOAD;
10947 ret = hlua_filter_callback(s, filter, "tcp_payload", dir, (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_ARG_CHN));
10948 if (ret != -1) {
10949 ret = flt_ctx->cur_len[idx];
10950 if (lua_gettop(flt_hlua->T) > 0) {
10951 ret = lua_tointeger(flt_hlua->T, -1);
10952 if (ret > flt_ctx->cur_len[idx])
10953 ret = flt_ctx->cur_len[idx];
10954 lua_settop(flt_hlua->T, 0); /* Empty the stack. */
10955 }
10956 }
10957 return ret;
10958}
10959
Christopher Faulet69c581a2021-05-31 08:54:04 +020010960static int hlua_filter_parse_fct(char **args, int *cur_arg, struct proxy *px,
10961 struct flt_conf *fconf, char **err, void *private)
10962{
10963 struct hlua_reg_filter *reg_flt = private;
10964 lua_State *L;
10965 struct hlua_flt_config *conf = NULL;
10966 const char *flt_id = NULL;
10967 int state_id, pos, flt_flags = 0;
10968 struct flt_ops *hlua_flt_ops = NULL;
10969
10970 state_id = reg_flt_to_stack_id(reg_flt);
10971 L = hlua_states[state_id];
10972
10973 /* Initialize the filter ops with default callbacks */
10974 hlua_flt_ops = calloc(1, sizeof(*hlua_flt_ops));
Christopher Fauletc86bb872021-08-13 08:33:57 +020010975 if (!hlua_flt_ops)
10976 goto error;
Christopher Faulet69c581a2021-05-31 08:54:04 +020010977 hlua_flt_ops->init = hlua_filter_init;
10978 hlua_flt_ops->deinit = hlua_filter_deinit;
10979 if (state_id) {
10980 /* Set per-thread callback if script is loaded per-thread */
10981 hlua_flt_ops->init_per_thread = hlua_filter_init_per_thread;
10982 hlua_flt_ops->deinit_per_thread = hlua_filter_deinit_per_thread;
10983 }
10984 hlua_flt_ops->attach = hlua_filter_new;
10985 hlua_flt_ops->detach = hlua_filter_delete;
10986
10987 /* Push the filter class on the stack and resolve all callbacks */
10988 lua_rawgeti(L, LUA_REGISTRYINDEX, reg_flt->flt_ref[state_id]);
10989
Christopher Fauletc404f112020-02-26 15:03:09 +010010990 if (lua_getfield(L, -1, "start_analyze") == LUA_TFUNCTION)
10991 hlua_flt_ops->channel_start_analyze = hlua_filter_start_analyze;
10992 lua_pop(L, 1);
10993 if (lua_getfield(L, -1, "end_analyze") == LUA_TFUNCTION)
10994 hlua_flt_ops->channel_end_analyze = hlua_filter_end_analyze;
10995 lua_pop(L, 1);
Christopher Fauleteae8afa2020-02-26 17:15:48 +010010996 if (lua_getfield(L, -1, "http_headers") == LUA_TFUNCTION)
10997 hlua_flt_ops->http_headers = hlua_filter_http_headers;
10998 lua_pop(L, 1);
10999 if (lua_getfield(L, -1, "http_payload") == LUA_TFUNCTION)
11000 hlua_flt_ops->http_payload = hlua_filter_http_payload;
11001 lua_pop(L, 1);
11002 if (lua_getfield(L, -1, "http_end") == LUA_TFUNCTION)
11003 hlua_flt_ops->http_end = hlua_filter_http_end;
11004 lua_pop(L, 1);
Christopher Fauletc404f112020-02-26 15:03:09 +010011005 if (lua_getfield(L, -1, "tcp_payload") == LUA_TFUNCTION)
11006 hlua_flt_ops->tcp_payload = hlua_filter_tcp_payload;
11007 lua_pop(L, 1);
Christopher Faulet69c581a2021-05-31 08:54:04 +020011008
11009 /* Get id and flags of the filter class */
11010 if (lua_getfield(L, -1, "id") == LUA_TSTRING)
11011 flt_id = lua_tostring(L, -1);
11012 lua_pop(L, 1);
11013 if (lua_getfield(L, -1, "flags") == LUA_TNUMBER)
11014 flt_flags = lua_tointeger(L, -1);
11015 lua_pop(L, 1);
11016
11017 /* Create the filter config */
11018 conf = calloc(1, sizeof(*conf));
Christopher Fauletc86bb872021-08-13 08:33:57 +020011019 if (!conf)
Christopher Faulet69c581a2021-05-31 08:54:04 +020011020 goto error;
Christopher Faulet69c581a2021-05-31 08:54:04 +020011021 conf->reg = reg_flt;
11022
11023 /* duplicate args */
11024 for (pos = 0; *args[*cur_arg + 1 + pos]; pos++);
11025 conf->args = calloc(pos + 1, sizeof(*conf->args));
Christopher Fauletc86bb872021-08-13 08:33:57 +020011026 if (!conf->args)
11027 goto error;
11028 for (pos = 0; *args[*cur_arg + 1 + pos]; pos++) {
Christopher Faulet69c581a2021-05-31 08:54:04 +020011029 conf->args[pos] = strdup(args[*cur_arg + 1 + pos]);
Christopher Fauletc86bb872021-08-13 08:33:57 +020011030 if (!conf->args[pos])
11031 goto error;
11032 }
Christopher Faulet69c581a2021-05-31 08:54:04 +020011033 conf->args[pos] = NULL;
11034 *cur_arg += pos + 1;
11035
Christopher Fauletc86bb872021-08-13 08:33:57 +020011036 if (flt_id) {
11037 fconf->id = strdup(flt_id);
11038 if (!fconf->id)
11039 goto error;
11040 }
Christopher Faulet69c581a2021-05-31 08:54:04 +020011041 fconf->flags = flt_flags;
11042 fconf->conf = conf;
11043 fconf->ops = hlua_flt_ops;
11044
11045 lua_settop(L, 0);
11046 return 0;
11047
11048 error:
Christopher Fauletc86bb872021-08-13 08:33:57 +020011049 memprintf(err, "Lua filter '%s' : Lua out of memory error", reg_flt->name);
Christopher Faulet69c581a2021-05-31 08:54:04 +020011050 free(hlua_flt_ops);
Christopher Fauletc86bb872021-08-13 08:33:57 +020011051 if (conf && conf->args) {
11052 for (pos = 0; conf->args[pos]; pos++)
11053 free(conf->args[pos]);
11054 free(conf->args);
11055 }
Christopher Faulet69c581a2021-05-31 08:54:04 +020011056 free(conf);
Christopher Fauletc86bb872021-08-13 08:33:57 +020011057 free((char *)fconf->id);
Christopher Faulet69c581a2021-05-31 08:54:04 +020011058 lua_settop(L, 0);
11059 return -1;
11060}
11061
Christopher Fauletc404f112020-02-26 15:03:09 +010011062__LJMP static int hlua_register_data_filter(lua_State *L)
11063{
11064 struct filter *filter;
11065 struct channel *chn;
11066
11067 MAY_LJMP(check_args(L, 2, "register_data_filter"));
11068 MAY_LJMP(luaL_checktype(L, 1, LUA_TTABLE));
11069 chn = MAY_LJMP(hlua_checkchannel(L, 2));
11070
11071 lua_getfield(L, 1, "__filter");
11072 MAY_LJMP(luaL_checktype(L, -1, LUA_TLIGHTUSERDATA));
11073 filter = lua_touserdata (L, -1);
11074 lua_pop(L, 1);
11075
11076 register_data_filter(chn_strm(chn), chn, filter);
11077 return 1;
11078}
11079
11080__LJMP static int hlua_unregister_data_filter(lua_State *L)
11081{
11082 struct filter *filter;
11083 struct channel *chn;
11084
11085 MAY_LJMP(check_args(L, 2, "unregister_data_filter"));
11086 MAY_LJMP(luaL_checktype(L, 1, LUA_TTABLE));
11087 chn = MAY_LJMP(hlua_checkchannel(L, 2));
11088
11089 lua_getfield(L, 1, "__filter");
11090 MAY_LJMP(luaL_checktype(L, -1, LUA_TLIGHTUSERDATA));
11091 filter = lua_touserdata (L, -1);
11092 lua_pop(L, 1);
11093
11094 unregister_data_filter(chn_strm(chn), chn, filter);
11095 return 1;
11096}
11097
Christopher Faulet69c581a2021-05-31 08:54:04 +020011098/* This function is an LUA binding used for registering a filter. It expects a
Ilya Shipitsinff0f2782021-08-22 22:18:07 +050011099 * filter name used in the haproxy configuration file and a LUA function to
Christopher Faulet69c581a2021-05-31 08:54:04 +020011100 * parse configuration arguments.
11101 */
11102__LJMP static int hlua_register_filter(lua_State *L)
11103{
11104 struct buffer *trash;
11105 struct flt_kw_list *fkl;
11106 struct flt_kw *fkw;
11107 const char *name;
11108 struct hlua_reg_filter *reg_flt= NULL;
11109 int flt_ref, fun_ref;
11110 int len;
11111
11112 MAY_LJMP(check_args(L, 3, "register_filter"));
11113
11114 /* First argument : filter name. */
11115 name = MAY_LJMP(luaL_checkstring(L, 1));
11116
11117 /* Second argument : The filter class */
11118 flt_ref = MAY_LJMP(hlua_checktable(L, 2));
11119
11120 /* Third argument : lua function. */
11121 fun_ref = MAY_LJMP(hlua_checkfunction(L, 3));
11122
11123 trash = get_trash_chunk();
11124 chunk_printf(trash, "lua.%s", name);
11125 fkw = flt_find_kw(trash->area);
11126 if (fkw != NULL) {
11127 reg_flt = fkw->private;
11128 if (reg_flt->flt_ref[hlua_state_id] != -1 || reg_flt->fun_ref[hlua_state_id] != -1) {
11129 ha_warning("Trying to register filter 'lua.%s' more than once. "
11130 "This will become a hard error in version 2.5.\n", name);
11131 }
11132 reg_flt->flt_ref[hlua_state_id] = flt_ref;
11133 reg_flt->fun_ref[hlua_state_id] = fun_ref;
11134 return 0;
11135 }
11136
11137 fkl = calloc(1, sizeof(*fkl) + sizeof(struct flt_kw) * 2);
11138 if (!fkl)
11139 goto alloc_error;
11140 fkl->scope = "HLUA";
11141
11142 reg_flt = new_hlua_reg_filter(name);
11143 if (!reg_flt)
11144 goto alloc_error;
11145
11146 reg_flt->flt_ref[hlua_state_id] = flt_ref;
11147 reg_flt->fun_ref[hlua_state_id] = fun_ref;
11148
11149 /* The filter keyword */
11150 len = strlen("lua.") + strlen(name) + 1;
11151 fkl->kw[0].kw = calloc(1, len);
11152 if (!fkl->kw[0].kw)
11153 goto alloc_error;
11154
11155 snprintf((char *)fkl->kw[0].kw, len, "lua.%s", name);
11156
11157 fkl->kw[0].parse = hlua_filter_parse_fct;
11158 fkl->kw[0].private = reg_flt;
11159 memset(&fkl->kw[1], 0, sizeof(*fkl->kw));
11160
11161 /* Register this new filter */
11162 flt_register_keywords(fkl);
11163
11164 return 0;
11165
11166 alloc_error:
11167 release_hlua_reg_filter(reg_flt);
11168 ha_free(&fkl);
11169 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
11170 return 0; /* Never reached */
11171}
11172
Thierry FOURNIERbd413492015-03-03 16:52:26 +010011173static int hlua_read_timeout(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011174 const struct proxy *defpx, const char *file, int line,
Thierry FOURNIERbd413492015-03-03 16:52:26 +010011175 char **err, unsigned int *timeout)
11176{
11177 const char *error;
11178
11179 error = parse_time_err(args[1], timeout, TIME_UNIT_MS);
Willy Tarreau9faebe32019-06-07 19:00:37 +020011180 if (error == PARSE_TIME_OVER) {
11181 memprintf(err, "timer overflow in argument <%s> to <%s> (maximum value is 2147483647 ms or ~24.8 days)",
11182 args[1], args[0]);
11183 return -1;
11184 }
11185 else if (error == PARSE_TIME_UNDER) {
11186 memprintf(err, "timer underflow in argument <%s> to <%s> (minimum non-null value is 1 ms)",
11187 args[1], args[0]);
11188 return -1;
11189 }
11190 else if (error) {
Thierry FOURNIERbd413492015-03-03 16:52:26 +010011191 memprintf(err, "%s: invalid timeout", args[0]);
11192 return -1;
11193 }
11194 return 0;
11195}
11196
11197static int hlua_session_timeout(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011198 const struct proxy *defpx, const char *file, int line,
Thierry FOURNIERbd413492015-03-03 16:52:26 +010011199 char **err)
11200{
11201 return hlua_read_timeout(args, section_type, curpx, defpx,
11202 file, line, err, &hlua_timeout_session);
11203}
11204
11205static int hlua_task_timeout(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011206 const struct proxy *defpx, const char *file, int line,
Thierry FOURNIERbd413492015-03-03 16:52:26 +010011207 char **err)
11208{
11209 return hlua_read_timeout(args, section_type, curpx, defpx,
11210 file, line, err, &hlua_timeout_task);
11211}
11212
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020011213static int hlua_applet_timeout(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011214 const struct proxy *defpx, const char *file, int line,
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020011215 char **err)
11216{
11217 return hlua_read_timeout(args, section_type, curpx, defpx,
11218 file, line, err, &hlua_timeout_applet);
11219}
11220
Thierry FOURNIERee9f8022015-03-03 17:37:37 +010011221static int hlua_forced_yield(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011222 const struct proxy *defpx, const char *file, int line,
Thierry FOURNIERee9f8022015-03-03 17:37:37 +010011223 char **err)
11224{
11225 char *error;
11226
11227 hlua_nb_instruction = strtoll(args[1], &error, 10);
11228 if (*error != '\0') {
11229 memprintf(err, "%s: invalid number", args[0]);
11230 return -1;
11231 }
11232 return 0;
11233}
11234
Willy Tarreau32f61e22015-03-18 17:54:59 +010011235static int hlua_parse_maxmem(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011236 const struct proxy *defpx, const char *file, int line,
Willy Tarreau32f61e22015-03-18 17:54:59 +010011237 char **err)
11238{
11239 char *error;
11240
11241 if (*(args[1]) == 0) {
Thierry Fournier70e38e92022-09-19 09:01:53 +020011242 memprintf(err, "'%s' expects an integer argument (Lua memory size in MB).", args[0]);
Willy Tarreau32f61e22015-03-18 17:54:59 +010011243 return -1;
11244 }
11245 hlua_global_allocator.limit = strtoll(args[1], &error, 10) * 1024L * 1024L;
11246 if (*error != '\0') {
11247 memprintf(err, "%s: invalid number %s (error at '%c')", args[0], args[1], *error);
11248 return -1;
11249 }
11250 return 0;
11251}
11252
11253
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011254/* This function is called by the main configuration key "lua-load". It loads and
11255 * execute an lua file during the parsing of the HAProxy configuration file. It is
11256 * the main lua entry point.
11257 *
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -080011258 * This function runs with the HAProxy keywords API. It returns -1 if an error
11259 * occurs, otherwise it returns 0.
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011260 *
11261 * In some error case, LUA set an error message in top of the stack. This function
11262 * returns this error message in the HAProxy logs and pop it from the stack.
Thierry FOURNIERbabae282015-09-17 11:36:37 +020011263 *
11264 * This function can fail with an abort() due to an Lua critical error.
11265 * We are in the configuration parsing process of HAProxy, this abort() is
11266 * tolerated.
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011267 */
Thierry Fournierae6b5682022-09-19 09:04:16 +020011268static int hlua_load_state(char **args, lua_State *L, char **err)
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011269{
11270 int error;
Thierry Fournierae6b5682022-09-19 09:04:16 +020011271 int nargs;
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011272
11273 /* Just load and compile the file. */
Thierry Fournierae6b5682022-09-19 09:04:16 +020011274 error = luaL_loadfile(L, args[0]);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011275 if (error) {
Thierry Fournierae6b5682022-09-19 09:04:16 +020011276 memprintf(err, "error in Lua file '%s': %s", args[0], lua_tostring(L, -1));
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011277 lua_pop(L, 1);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011278 return -1;
11279 }
Thierry Fournierae6b5682022-09-19 09:04:16 +020011280
11281 /* Push args in the Lua stack, except the first one which is the filename */
11282 for (nargs = 1; *(args[nargs]) != 0; nargs++) {
Aurelien DARRAGON4d7aefe2022-09-23 10:22:14 +020011283 /* Check stack size. */
11284 if (!lua_checkstack(L, 1)) {
11285 memprintf(err, "Lua runtime error while loading arguments: stack is full.");
11286 return -1;
11287 }
Thierry Fournierae6b5682022-09-19 09:04:16 +020011288 lua_pushstring(L, args[nargs]);
11289 }
11290 nargs--;
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011291
11292 /* If no syntax error where detected, execute the code. */
Thierry Fournierae6b5682022-09-19 09:04:16 +020011293 error = lua_pcall(L, nargs, LUA_MULTRET, 0);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011294 switch (error) {
11295 case LUA_OK:
11296 break;
11297 case LUA_ERRRUN:
Thierry Fournier70e38e92022-09-19 09:01:53 +020011298 memprintf(err, "Lua runtime error: %s", lua_tostring(L, -1));
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011299 lua_pop(L, 1);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011300 return -1;
11301 case LUA_ERRMEM:
Thierry Fournier70e38e92022-09-19 09:01:53 +020011302 memprintf(err, "Lua out of memory error");
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011303 return -1;
11304 case LUA_ERRERR:
Thierry Fournier70e38e92022-09-19 09:01:53 +020011305 memprintf(err, "Lua message handler error: %s", lua_tostring(L, -1));
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011306 lua_pop(L, 1);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011307 return -1;
Christopher Faulet08ed98f2020-07-28 10:33:25 +020011308#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM <= 503
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011309 case LUA_ERRGCMM:
Thierry Fournier70e38e92022-09-19 09:01:53 +020011310 memprintf(err, "Lua garbage collector error: %s", lua_tostring(L, -1));
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011311 lua_pop(L, 1);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011312 return -1;
Christopher Faulet08ed98f2020-07-28 10:33:25 +020011313#endif
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011314 default:
Thierry Fournier70e38e92022-09-19 09:01:53 +020011315 memprintf(err, "Lua unknown error: %s", lua_tostring(L, -1));
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011316 lua_pop(L, 1);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011317 return -1;
11318 }
11319
11320 return 0;
11321}
11322
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011323static int hlua_load(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011324 const struct proxy *defpx, const char *file, int line,
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011325 char **err)
11326{
11327 if (*(args[1]) == 0) {
Thierry Fournier70e38e92022-09-19 09:01:53 +020011328 memprintf(err, "'%s' expects a file name as parameter.", args[0]);
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011329 return -1;
11330 }
11331
Thierry Fournier59f11be2020-11-29 00:37:41 +010011332 /* loading for global state */
Thierry Fournierc7492592020-11-28 23:57:24 +010011333 hlua_state_id = 0;
Willy Tarreau43ab05b2021-09-28 09:43:11 +020011334 ha_set_thread(NULL);
Thierry Fournierae6b5682022-09-19 09:04:16 +020011335 return hlua_load_state(&args[1], hlua_states[0], err);
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011336}
11337
Thierry Fournier59f11be2020-11-29 00:37:41 +010011338static int hlua_load_per_thread(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011339 const struct proxy *defpx, const char *file, int line,
Thierry Fournier59f11be2020-11-29 00:37:41 +010011340 char **err)
11341{
11342 int len;
Thierry Fournierae6b5682022-09-19 09:04:16 +020011343 int i;
Thierry Fournier59f11be2020-11-29 00:37:41 +010011344
11345 if (*(args[1]) == 0) {
Thierry Fournier70e38e92022-09-19 09:01:53 +020011346 memprintf(err, "'%s' expects a file as parameter.", args[0]);
Thierry Fournier59f11be2020-11-29 00:37:41 +010011347 return -1;
11348 }
11349
11350 if (per_thread_load == NULL) {
11351 /* allocate the first entry large enough to store the final NULL */
11352 per_thread_load = calloc(1, sizeof(*per_thread_load));
11353 if (per_thread_load == NULL) {
11354 memprintf(err, "out of memory error");
11355 return -1;
11356 }
11357 }
11358
11359 /* count used entries */
11360 for (len = 0; per_thread_load[len] != NULL; len++)
11361 ;
11362
11363 per_thread_load = realloc(per_thread_load, (len + 2) * sizeof(*per_thread_load));
11364 if (per_thread_load == NULL) {
11365 memprintf(err, "out of memory error");
11366 return -1;
11367 }
Thierry Fournier59f11be2020-11-29 00:37:41 +010011368 per_thread_load[len + 1] = NULL;
11369
Thierry Fournierae6b5682022-09-19 09:04:16 +020011370 /* count args excepting the first, allocate array and copy args */
11371 for (i = 0; *(args[i + 1]) != 0; i++);
Aurelien DARRAGONb12d1692022-09-23 08:48:34 +020011372 per_thread_load[len] = calloc(i + 1, sizeof(*per_thread_load[len]));
Thierry Fournier59f11be2020-11-29 00:37:41 +010011373 if (per_thread_load[len] == NULL) {
11374 memprintf(err, "out of memory error");
11375 return -1;
11376 }
Thierry Fournierae6b5682022-09-19 09:04:16 +020011377 for (i = 1; *(args[i]) != 0; i++) {
11378 per_thread_load[len][i - 1] = strdup(args[i]);
11379 if (per_thread_load[len][i - 1] == NULL) {
11380 memprintf(err, "out of memory error");
11381 return -1;
11382 }
11383 }
11384 per_thread_load[len][i - 1] = strdup("");
11385 if (per_thread_load[len][i - 1] == NULL) {
11386 memprintf(err, "out of memory error");
11387 return -1;
11388 }
Thierry Fournier59f11be2020-11-29 00:37:41 +010011389
11390 /* loading for thread 1 only */
11391 hlua_state_id = 1;
Willy Tarreau43ab05b2021-09-28 09:43:11 +020011392 ha_set_thread(NULL);
Thierry Fournierae6b5682022-09-19 09:04:16 +020011393 return hlua_load_state(per_thread_load[len], hlua_states[1], err);
Thierry Fournier59f11be2020-11-29 00:37:41 +010011394}
11395
Tim Duesterhusc9fc9f22020-01-12 13:55:39 +010011396/* Prepend the given <path> followed by a semicolon to the `package.<type>` variable
11397 * in the given <ctx>.
11398 */
Thierry Fournier3fb9e512020-11-28 10:13:12 +010011399static int hlua_prepend_path(lua_State *L, char *type, char *path)
Tim Duesterhusc9fc9f22020-01-12 13:55:39 +010011400{
Thierry Fournier3fb9e512020-11-28 10:13:12 +010011401 lua_getglobal(L, "package"); /* push package variable */
11402 lua_pushstring(L, path); /* push given path */
11403 lua_pushstring(L, ";"); /* push semicolon */
11404 lua_getfield(L, -3, type); /* push old path */
11405 lua_concat(L, 3); /* concatenate to new path */
11406 lua_setfield(L, -2, type); /* store new path */
11407 lua_pop(L, 1); /* pop package variable */
Tim Duesterhusc9fc9f22020-01-12 13:55:39 +010011408
11409 return 0;
11410}
11411
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010011412static int hlua_config_prepend_path(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011413 const struct proxy *defpx, const char *file, int line,
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010011414 char **err)
11415{
11416 char *path;
11417 char *type = "path";
Tim Duesterhus621e74a2021-01-03 20:04:36 +010011418 struct prepend_path *p = NULL;
Bertrand Jacquin7fbc7702021-11-24 21:16:06 +000011419 size_t i;
Thierry Fournier59f11be2020-11-29 00:37:41 +010011420
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010011421 if (too_many_args(2, args, err, NULL)) {
Tim Duesterhus621e74a2021-01-03 20:04:36 +010011422 goto err;
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010011423 }
11424
11425 if (!(*args[1])) {
11426 memprintf(err, "'%s' expects to receive a <path> as argument", args[0]);
Tim Duesterhus621e74a2021-01-03 20:04:36 +010011427 goto err;
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010011428 }
11429 path = args[1];
11430
11431 if (*args[2]) {
11432 if (strcmp(args[2], "path") != 0 && strcmp(args[2], "cpath") != 0) {
11433 memprintf(err, "'%s' expects <type> to either be 'path' or 'cpath'", args[0]);
Tim Duesterhus621e74a2021-01-03 20:04:36 +010011434 goto err;
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010011435 }
11436 type = args[2];
11437 }
11438
Thierry Fournier59f11be2020-11-29 00:37:41 +010011439 p = calloc(1, sizeof(*p));
11440 if (p == NULL) {
Tim Duesterhusf89d43a2021-01-03 20:04:37 +010011441 memprintf(err, "memory allocation failed");
Tim Duesterhus621e74a2021-01-03 20:04:36 +010011442 goto err;
Thierry Fournier59f11be2020-11-29 00:37:41 +010011443 }
11444 p->path = strdup(path);
11445 if (p->path == NULL) {
Tim Duesterhusf89d43a2021-01-03 20:04:37 +010011446 memprintf(err, "memory allocation failed");
Tim Duesterhus621e74a2021-01-03 20:04:36 +010011447 goto err2;
Thierry Fournier59f11be2020-11-29 00:37:41 +010011448 }
11449 p->type = strdup(type);
11450 if (p->type == NULL) {
Tim Duesterhusf89d43a2021-01-03 20:04:37 +010011451 memprintf(err, "memory allocation failed");
Tim Duesterhus621e74a2021-01-03 20:04:36 +010011452 goto err2;
Thierry Fournier59f11be2020-11-29 00:37:41 +010011453 }
Willy Tarreau2b718102021-04-21 07:32:39 +020011454 LIST_APPEND(&prepend_path_list, &p->l);
Thierry Fournier59f11be2020-11-29 00:37:41 +010011455
Tim Duesterhus9e5e5862021-10-11 18:51:08 +020011456 /* Handle the global state and the per-thread state for the first
11457 * thread. The remaining threads will be initialized based on
11458 * prepend_path_list.
11459 */
Bertrand Jacquin7fbc7702021-11-24 21:16:06 +000011460 for (i = 0; i < 2; i++) {
Tim Duesterhus9e5e5862021-10-11 18:51:08 +020011461 lua_State *L = hlua_states[i];
11462 const char *error;
11463
11464 if (setjmp(safe_ljmp_env) != 0) {
11465 lua_atpanic(L, hlua_panic_safe);
11466 if (lua_type(L, -1) == LUA_TSTRING)
11467 error = lua_tostring(L, -1);
11468 else
11469 error = "critical error";
11470 fprintf(stderr, "lua-prepend-path: %s.\n", error);
11471 exit(1);
11472 } else {
11473 lua_atpanic(L, hlua_panic_ljmp);
11474 }
11475
11476 hlua_prepend_path(L, type, path);
11477
11478 lua_atpanic(L, hlua_panic_safe);
11479 }
11480
Thierry Fournier59f11be2020-11-29 00:37:41 +010011481 return 0;
Tim Duesterhus621e74a2021-01-03 20:04:36 +010011482
11483err2:
11484 free(p->type);
11485 free(p->path);
11486err:
11487 free(p);
11488 return -1;
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010011489}
11490
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011491/* configuration keywords declaration */
11492static struct cfg_kw_list cfg_kws = {{ },{
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010011493 { CFG_GLOBAL, "lua-prepend-path", hlua_config_prepend_path },
Thierry FOURNIERbd413492015-03-03 16:52:26 +010011494 { CFG_GLOBAL, "lua-load", hlua_load },
Thierry Fournier59f11be2020-11-29 00:37:41 +010011495 { CFG_GLOBAL, "lua-load-per-thread", hlua_load_per_thread },
Thierry FOURNIERbd413492015-03-03 16:52:26 +010011496 { CFG_GLOBAL, "tune.lua.session-timeout", hlua_session_timeout },
11497 { CFG_GLOBAL, "tune.lua.task-timeout", hlua_task_timeout },
Thierry FOURNIER56da1012015-10-01 08:42:31 +020011498 { CFG_GLOBAL, "tune.lua.service-timeout", hlua_applet_timeout },
Thierry FOURNIERee9f8022015-03-03 17:37:37 +010011499 { CFG_GLOBAL, "tune.lua.forced-yield", hlua_forced_yield },
Willy Tarreau32f61e22015-03-18 17:54:59 +010011500 { CFG_GLOBAL, "tune.lua.maxmem", hlua_parse_maxmem },
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011501 { 0, NULL, NULL },
11502}};
11503
Willy Tarreau0108d902018-11-25 19:14:37 +010011504INITCALL1(STG_REGISTER, cfg_register_keywords, &cfg_kws);
11505
William Lallemand52139182022-03-30 15:05:42 +020011506#ifdef USE_OPENSSL
Christopher Fauletafd8f102018-11-08 11:34:21 +010011507
William Lallemand30fcca12022-03-30 12:03:12 +020011508/*
11509 * This function replace a ckch_store by another one, and rebuild the ckch_inst and all its dependencies.
11510 * It does the sam as "cli_io_handler_commit_cert" but for lua, the major
11511 * difference is that the yield in lua and for the CLI is not handled the same
11512 * way.
11513 */
11514__LJMP static int hlua_ckch_commit_yield(lua_State *L, int status, lua_KContext ctx)
11515{
11516 struct ckch_inst **lua_ckchi = lua_touserdata(L, -1);
11517 struct ckch_store **lua_ckchs = lua_touserdata(L, -2);
11518 struct ckch_inst *ckchi = *lua_ckchi;
11519 struct ckch_store *old_ckchs = lua_ckchs[0];
11520 struct ckch_store *new_ckchs = lua_ckchs[1];
11521 struct hlua *hlua;
11522 char *err = NULL;
11523 int y = 1;
11524
11525 hlua = hlua_gethlua(L);
11526
11527 /* get the first ckchi to copy */
11528 if (ckchi == NULL)
11529 ckchi = LIST_ELEM(old_ckchs->ckch_inst.n, typeof(ckchi), by_ckchs);
11530
11531 /* walk through the old ckch_inst and creates new ckch_inst using the updated ckchs */
11532 list_for_each_entry_from(ckchi, &old_ckchs->ckch_inst, by_ckchs) {
11533 struct ckch_inst *new_inst;
11534
11535 /* it takes a lot of CPU to creates SSL_CTXs, so we yield every 10 CKCH instances */
11536 if (y % 10 == 0) {
11537
11538 *lua_ckchi = ckchi;
11539
11540 task_wakeup(hlua->task, TASK_WOKEN_MSG);
11541 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_ckch_commit_yield, TICK_ETERNITY, 0));
11542 }
11543
11544 if (ckch_inst_rebuild(new_ckchs, ckchi, &new_inst, &err))
11545 goto error;
11546
11547 /* link the new ckch_inst to the duplicate */
11548 LIST_APPEND(&new_ckchs->ckch_inst, &new_inst->by_ckchs);
11549 y++;
11550 }
11551
11552 /* The generation is finished, we can insert everything */
11553 ckch_store_replace(old_ckchs, new_ckchs);
11554
11555 lua_pop(L, 2); /* pop the lua_ckchs and ckchi */
11556
11557 HA_SPIN_UNLOCK(CKCH_LOCK, &ckch_lock);
11558
11559 return 0;
11560
11561error:
11562 ckch_store_free(new_ckchs);
11563 HA_SPIN_UNLOCK(CKCH_LOCK, &ckch_lock);
11564 WILL_LJMP(luaL_error(L, "%s", err));
11565 free(err);
11566
11567 return 0;
11568}
11569
11570/*
11571 * Replace a ckch_store <filename> in the ckchs_tree with a ckch_store created
11572 * from the table in parameter.
11573 *
11574 * This is equivalent to "set ssl cert" + "commit ssl cert" over the CLI, which
11575 * means it does not need to have a transaction since everything is done in the
11576 * same function.
11577 *
11578 * CertCache.set{filename="", crt="", key="", sctl="", ocsp="", issuer=""}
11579 *
11580 */
11581__LJMP static int hlua_ckch_set(lua_State *L)
11582{
11583 struct hlua *hlua;
11584 struct ckch_inst **lua_ckchi;
11585 struct ckch_store **lua_ckchs;
11586 struct ckch_store *old_ckchs = NULL;
11587 struct ckch_store *new_ckchs = NULL;
11588 int errcode = 0;
11589 char *err = NULL;
11590 struct cert_exts *cert_ext = NULL;
11591 char *filename;
11592 struct cert_key_and_chain *ckch;
11593 int ret;
11594
11595 if (lua_type(L, -1) != LUA_TTABLE)
11596 WILL_LJMP(luaL_error(L, "'CertCache.set' needs a table as argument"));
11597
11598 hlua = hlua_gethlua(L);
11599
11600 /* FIXME: this should not return an error but should come back later */
11601 if (HA_SPIN_TRYLOCK(CKCH_LOCK, &ckch_lock))
11602 WILL_LJMP(luaL_error(L, "CertCache already under lock"));
11603
11604 ret = lua_getfield(L, -1, "filename");
11605 if (ret != LUA_TSTRING) {
Thierry Fournier70e38e92022-09-19 09:01:53 +020011606 memprintf(&err, "%sNo filename specified!", err ? err : "");
William Lallemand30fcca12022-03-30 12:03:12 +020011607 errcode |= ERR_ALERT | ERR_FATAL;
11608 goto end;
11609 }
11610 filename = (char *)lua_tostring(L, -1);
11611
11612
11613 /* look for the filename in the tree */
11614 old_ckchs = ckchs_lookup(filename);
11615 if (!old_ckchs) {
Thierry Fournier70e38e92022-09-19 09:01:53 +020011616 memprintf(&err, "%sCan't replace a certificate which is not referenced by the configuration!", err ? err : "");
William Lallemand30fcca12022-03-30 12:03:12 +020011617 errcode |= ERR_ALERT | ERR_FATAL;
11618 goto end;
11619 }
11620 /* TODO: handle extra_files_noext */
11621
11622 new_ckchs = ckchs_dup(old_ckchs);
11623 if (!new_ckchs) {
Thierry Fournier70e38e92022-09-19 09:01:53 +020011624 memprintf(&err, "%sCannot allocate memory!", err ? err : "");
William Lallemand30fcca12022-03-30 12:03:12 +020011625 errcode |= ERR_ALERT | ERR_FATAL;
11626 goto end;
11627 }
11628
11629 ckch = new_ckchs->ckch;
11630
11631 /* loop on the field in the table, which have the same name as the
11632 * possible extensions of files */
11633 lua_pushnil(L);
11634 while (lua_next(L, 1)) {
11635 int i;
11636 const char *field = lua_tostring(L, -2);
11637 char *payload = (char *)lua_tostring(L, -1);
11638
11639 if (!field || strcmp(field, "filename") == 0) {
11640 lua_pop(L, 1);
11641 continue;
11642 }
11643
11644 for (i = 0; field && cert_exts[i].ext != NULL; i++) {
11645 if (strcmp(field, cert_exts[i].ext) == 0) {
11646 cert_ext = &cert_exts[i];
11647 break;
11648 }
11649 }
11650
11651 /* this is the default type, the field is not supported */
11652 if (cert_ext == NULL) {
Thierry Fournier70e38e92022-09-19 09:01:53 +020011653 memprintf(&err, "%sUnsupported field '%s'", err ? err : "", field);
William Lallemand30fcca12022-03-30 12:03:12 +020011654 errcode |= ERR_ALERT | ERR_FATAL;
11655 goto end;
11656 }
11657
11658 /* appply the change on the duplicate */
William Lallemandd8c195a2022-05-26 11:20:13 +020011659 if (cert_ext->load(filename, payload, ckch, &err) != 0) {
Thierry Fournier70e38e92022-09-19 09:01:53 +020011660 memprintf(&err, "%sCan't load the payload for '%s'", err ? err : "", cert_ext->ext);
William Lallemand30fcca12022-03-30 12:03:12 +020011661 errcode |= ERR_ALERT | ERR_FATAL;
11662 goto end;
11663 }
11664 lua_pop(L, 1);
11665 }
11666
11667 /* store the pointers on the lua stack */
11668 lua_ckchs = lua_newuserdata(L, sizeof(struct ckch_store *) * 2);
11669 lua_ckchs[0] = old_ckchs;
11670 lua_ckchs[1] = new_ckchs;
11671 lua_ckchi = lua_newuserdata(L, sizeof(struct ckch_inst *));
11672 *lua_ckchi = NULL;
11673
11674 task_wakeup(hlua->task, TASK_WOKEN_MSG);
11675 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_ckch_commit_yield, TICK_ETERNITY, 0));
11676
11677end:
11678 HA_SPIN_UNLOCK(CKCH_LOCK, &ckch_lock);
11679
11680 if (errcode & ERR_CODE) {
11681 ckch_store_free(new_ckchs);
11682 WILL_LJMP(luaL_error(L, "%s", err));
11683 }
11684 free(err);
11685
11686 return 0;
11687}
11688
William Lallemand52139182022-03-30 15:05:42 +020011689#else
11690
11691__LJMP static int hlua_ckch_set(lua_State *L)
11692{
11693 WILL_LJMP(luaL_error(L, "'CertCache.set' needs an HAProxy built with OpenSSL"));
11694
11695 return 0;
11696}
11697#endif /* ! USE_OPENSSL */
11698
11699
11700
Thierry FOURNIERbabae282015-09-17 11:36:37 +020011701/* This function can fail with an abort() due to an Lua critical error.
11702 * We are in the initialisation process of HAProxy, this abort() is
11703 * tolerated.
11704 */
Thierry Fournierb8cef172020-11-28 15:37:17 +010011705int hlua_post_init_state(lua_State *L)
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010011706{
11707 struct hlua_init_function *init;
11708 const char *msg;
11709 enum hlua_exec ret;
Thierry Fournierfd107a22016-02-19 19:57:23 +010011710 const char *error;
Thierry Fournier670db242020-11-28 10:49:59 +010011711 const char *kind;
11712 const char *trace;
11713 int return_status = 1;
11714#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM >= 504
11715 int nres;
11716#endif
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010011717
Willy Tarreaucdb53462020-12-02 12:12:00 +010011718 /* disable memory limit checks if limit is not set */
11719 if (!hlua_global_allocator.limit)
11720 hlua_global_allocator.limit = ~hlua_global_allocator.limit;
11721
Ilya Shipitsin856aabc2020-04-16 23:51:34 +050011722 /* Call post initialisation function in safe environment. */
Thierry Fournier3c539322020-11-28 16:05:05 +010011723 if (setjmp(safe_ljmp_env) != 0) {
11724 lua_atpanic(L, hlua_panic_safe);
Thierry Fournierb8cef172020-11-28 15:37:17 +010011725 if (lua_type(L, -1) == LUA_TSTRING)
11726 error = lua_tostring(L, -1);
Thierry Fournier3d4a6752016-02-19 20:53:30 +010011727 else
11728 error = "critical error";
11729 fprintf(stderr, "Lua post-init: %s.\n", error);
11730 exit(1);
Thierry Fournier3c539322020-11-28 16:05:05 +010011731 } else {
11732 lua_atpanic(L, hlua_panic_ljmp);
Thierry Fournier3d4a6752016-02-19 20:53:30 +010011733 }
Frédéric Lécaille54f2bcf2018-08-29 13:46:24 +020011734
Thierry Fournierb8cef172020-11-28 15:37:17 +010011735 hlua_fcn_post_init(L);
Thierry Fournier3d4a6752016-02-19 20:53:30 +010011736
Thierry Fournierc7492592020-11-28 23:57:24 +010011737 list_for_each_entry(init, &hlua_init_functions[hlua_state_id], l) {
Thierry Fournierb8cef172020-11-28 15:37:17 +010011738 lua_rawgeti(L, LUA_REGISTRYINDEX, init->function_ref);
Thierry Fournier670db242020-11-28 10:49:59 +010011739
11740#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM >= 504
Thierry Fournierb8cef172020-11-28 15:37:17 +010011741 ret = lua_resume(L, L, 0, &nres);
Thierry Fournier670db242020-11-28 10:49:59 +010011742#else
Thierry Fournierb8cef172020-11-28 15:37:17 +010011743 ret = lua_resume(L, L, 0);
Thierry Fournier670db242020-11-28 10:49:59 +010011744#endif
11745 kind = NULL;
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010011746 switch (ret) {
Thierry Fournier670db242020-11-28 10:49:59 +010011747
11748 case LUA_OK:
Thierry Fournierb8cef172020-11-28 15:37:17 +010011749 lua_pop(L, -1);
Thierry Fournier13d08b72020-11-28 11:02:58 +010011750 break;
Thierry Fournier670db242020-11-28 10:49:59 +010011751
11752 case LUA_ERRERR:
11753 kind = "message handler error";
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -070011754 /* Fall through */
Thierry Fournier670db242020-11-28 10:49:59 +010011755 case LUA_ERRRUN:
11756 if (!kind)
11757 kind = "runtime error";
Thierry Fournierb8cef172020-11-28 15:37:17 +010011758 msg = lua_tostring(L, -1);
11759 lua_settop(L, 0); /* Empty the stack. */
11760 lua_pop(L, 1);
Christopher Fauletd09cc512021-03-24 14:48:45 +010011761 trace = hlua_traceback(L, ", ");
Thierry Fournier670db242020-11-28 10:49:59 +010011762 if (msg)
11763 ha_alert("Lua init: %s: '%s' from %s\n", kind, msg, trace);
11764 else
11765 ha_alert("Lua init: unknown %s from %s\n", kind, trace);
11766 return_status = 0;
11767 break;
11768
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010011769 default:
Thierry Fournier670db242020-11-28 10:49:59 +010011770 /* Unknown error */
11771 kind = "Unknown error";
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -070011772 /* Fall through */
Thierry Fournier670db242020-11-28 10:49:59 +010011773 case LUA_YIELD:
11774 /* yield is not configured at this step, this state doesn't happen */
11775 if (!kind)
11776 kind = "yield not allowed";
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -070011777 /* Fall through */
Thierry Fournier670db242020-11-28 10:49:59 +010011778 case LUA_ERRMEM:
11779 if (!kind)
11780 kind = "out of memory error";
Thierry Fournierb8cef172020-11-28 15:37:17 +010011781 lua_settop(L, 0);
11782 lua_pop(L, 1);
Christopher Fauletd09cc512021-03-24 14:48:45 +010011783 trace = hlua_traceback(L, ", ");
Thierry Fournier670db242020-11-28 10:49:59 +010011784 ha_alert("Lua init: %s: %s\n", kind, trace);
11785 return_status = 0;
11786 break;
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010011787 }
Thierry Fournier670db242020-11-28 10:49:59 +010011788 if (!return_status)
11789 break;
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010011790 }
Thierry Fournier3c539322020-11-28 16:05:05 +010011791
11792 lua_atpanic(L, hlua_panic_safe);
Thierry Fournier670db242020-11-28 10:49:59 +010011793 return return_status;
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010011794}
11795
Thierry Fournierb8cef172020-11-28 15:37:17 +010011796int hlua_post_init()
11797{
Thierry Fournier59f11be2020-11-29 00:37:41 +010011798 int ret;
11799 int i;
11800 int errors;
11801 char *err = NULL;
11802 struct hlua_function *fcn;
Christopher Faulet69c581a2021-05-31 08:54:04 +020011803 struct hlua_reg_filter *reg_flt;
Thierry Fournier59f11be2020-11-29 00:37:41 +010011804
Willy Tarreaub1310492021-08-30 09:35:18 +020011805#if defined(USE_OPENSSL)
Thierry Fournierb8cef172020-11-28 15:37:17 +010011806 /* Initialize SSL server. */
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010011807 if (socket_ssl->xprt->prepare_srv) {
Thierry Fournierb8cef172020-11-28 15:37:17 +010011808 int saved_used_backed = global.ssl_used_backend;
11809 // don't affect maxconn automatic computation
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010011810 socket_ssl->xprt->prepare_srv(socket_ssl);
Thierry Fournierb8cef172020-11-28 15:37:17 +010011811 global.ssl_used_backend = saved_used_backed;
11812 }
11813#endif
11814
Thierry Fournierc7492592020-11-28 23:57:24 +010011815 /* Perform post init of common thread */
11816 hlua_state_id = 0;
Willy Tarreau43ab05b2021-09-28 09:43:11 +020011817 ha_set_thread(&ha_thread_info[0]);
Thierry Fournier59f11be2020-11-29 00:37:41 +010011818 ret = hlua_post_init_state(hlua_states[hlua_state_id]);
11819 if (ret == 0)
11820 return 0;
11821
11822 /* init remaining lua states and load files */
11823 for (hlua_state_id = 2; hlua_state_id < global.nbthread + 1; hlua_state_id++) {
11824
11825 /* set thread context */
Willy Tarreau43ab05b2021-09-28 09:43:11 +020011826 ha_set_thread(&ha_thread_info[hlua_state_id - 1]);
Thierry Fournier59f11be2020-11-29 00:37:41 +010011827
11828 /* Init lua state */
11829 hlua_states[hlua_state_id] = hlua_init_state(hlua_state_id);
11830
11831 /* Load lua files */
11832 for (i = 0; per_thread_load && per_thread_load[i]; i++) {
11833 ret = hlua_load_state(per_thread_load[i], hlua_states[hlua_state_id], &err);
11834 if (ret != 0) {
11835 ha_alert("Lua init: %s\n", err);
11836 return 0;
11837 }
11838 }
11839 }
11840
11841 /* Reset thread context */
Willy Tarreau43ab05b2021-09-28 09:43:11 +020011842 ha_set_thread(NULL);
Thierry Fournier59f11be2020-11-29 00:37:41 +010011843
11844 /* Execute post init for all states */
11845 for (hlua_state_id = 1; hlua_state_id < global.nbthread + 1; hlua_state_id++) {
11846
11847 /* set thread context */
Willy Tarreau43ab05b2021-09-28 09:43:11 +020011848 ha_set_thread(&ha_thread_info[hlua_state_id - 1]);
Thierry Fournier59f11be2020-11-29 00:37:41 +010011849
11850 /* run post init */
11851 ret = hlua_post_init_state(hlua_states[hlua_state_id]);
11852 if (ret == 0)
11853 return 0;
11854 }
11855
11856 /* Reset thread context */
Willy Tarreau43ab05b2021-09-28 09:43:11 +020011857 ha_set_thread(NULL);
Thierry Fournier59f11be2020-11-29 00:37:41 +010011858
11859 /* control functions registering. Each function must have:
11860 * - only the function_ref[0] set positive and all other to -1
11861 * - only the function_ref[0] set to -1 and all other positive
11862 * This ensure a same reference is not used both in shared
11863 * lua state and thread dedicated lua state. Note: is the case
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +050011864 * reach, the shared state is priority, but the bug will be
Thierry Fournier59f11be2020-11-29 00:37:41 +010011865 * complicated to found for the end user.
11866 */
11867 errors = 0;
11868 list_for_each_entry(fcn, &referenced_functions, l) {
11869 ret = 0;
11870 for (i = 1; i < global.nbthread + 1; i++) {
11871 if (fcn->function_ref[i] == -1)
11872 ret--;
11873 else
11874 ret++;
11875 }
11876 if (abs(ret) != global.nbthread) {
11877 ha_alert("Lua function '%s' is not referenced in all thread. "
11878 "Expect function in all thread or in none thread.\n", fcn->name);
11879 errors++;
11880 continue;
11881 }
11882
11883 if ((fcn->function_ref[0] == -1) == (ret < 0)) {
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +050011884 ha_alert("Lua function '%s' is referenced both ins shared Lua context (through lua-load) "
11885 "and per-thread Lua context (through lua-load-per-thread). these two context "
Thierry Fournier59f11be2020-11-29 00:37:41 +010011886 "exclusive.\n", fcn->name);
11887 errors++;
11888 }
11889 }
11890
Christopher Faulet69c581a2021-05-31 08:54:04 +020011891 /* Do the same with registered filters */
11892 list_for_each_entry(reg_flt, &referenced_filters, l) {
11893 ret = 0;
11894 for (i = 1; i < global.nbthread + 1; i++) {
11895 if (reg_flt->flt_ref[i] == -1)
11896 ret--;
11897 else
11898 ret++;
11899 }
11900 if (abs(ret) != global.nbthread) {
11901 ha_alert("Lua filter '%s' is not referenced in all thread. "
11902 "Expect function in all thread or in none thread.\n", reg_flt->name);
11903 errors++;
11904 continue;
11905 }
11906
11907 if ((reg_flt->flt_ref[0] == -1) == (ret < 0)) {
11908 ha_alert("Lua filter '%s' is referenced both ins shared Lua context (through lua-load) "
11909 "and per-thread Lua context (through lua-load-per-thread). these two context "
11910 "exclusive.\n", fcn->name);
11911 errors++;
11912 }
11913 }
11914
11915
Thierry Fournier59f11be2020-11-29 00:37:41 +010011916 if (errors > 0)
11917 return 0;
11918
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +050011919 /* after this point, this global will no longer be used, so set to
Thierry Fournier59f11be2020-11-29 00:37:41 +010011920 * -1 in order to have probably a segfault if someone use it
11921 */
11922 hlua_state_id = -1;
11923
11924 return 1;
Thierry Fournierb8cef172020-11-28 15:37:17 +010011925}
11926
Willy Tarreau32f61e22015-03-18 17:54:59 +010011927/* The memory allocator used by the Lua stack. <ud> is a pointer to the
11928 * allocator's context. <ptr> is the pointer to alloc/free/realloc. <osize>
11929 * is the previously allocated size or the kind of object in case of a new
Willy Tarreaud36c7fa2020-12-02 12:26:29 +010011930 * allocation. <nsize> is the requested new size. A new allocation is
11931 * indicated by <ptr> being NULL. A free is indicated by <nsize> being
Willy Tarreaucdb53462020-12-02 12:12:00 +010011932 * zero. This one verifies that the limits are respected but is optimized
11933 * for the fast case where limits are not used, hence stats are not updated.
Willy Tarreaua5efdff2021-10-22 16:00:02 +020011934 *
11935 * Warning: while this API ressembles glibc's realloc() a lot, glibc surpasses
11936 * POSIX by making realloc(ptr,0) an effective free(), but others do not do
11937 * that and will simply allocate zero as if it were the result of malloc(0),
11938 * so mapping this onto realloc() will lead to memory leaks on non-glibc
11939 * systems.
Willy Tarreau32f61e22015-03-18 17:54:59 +010011940 */
11941static void *hlua_alloc(void *ud, void *ptr, size_t osize, size_t nsize)
11942{
11943 struct hlua_mem_allocator *zone = ud;
Willy Tarreaucdb53462020-12-02 12:12:00 +010011944 size_t limit, old, new;
11945
11946 /* a limit of ~0 means unlimited and boot complete, so there's no need
11947 * for accounting anymore.
11948 */
Willy Tarreaua5efdff2021-10-22 16:00:02 +020011949 if (likely(~zone->limit == 0)) {
11950 if (!nsize)
11951 ha_free(&ptr);
11952 else
11953 ptr = realloc(ptr, nsize);
11954 return ptr;
11955 }
Willy Tarreau32f61e22015-03-18 17:54:59 +010011956
Willy Tarreaud36c7fa2020-12-02 12:26:29 +010011957 if (!ptr)
11958 osize = 0;
Willy Tarreau32f61e22015-03-18 17:54:59 +010011959
Willy Tarreaucdb53462020-12-02 12:12:00 +010011960 /* enforce strict limits across all threads */
11961 limit = zone->limit;
11962 old = _HA_ATOMIC_LOAD(&zone->allocated);
11963 do {
11964 new = old + nsize - osize;
11965 if (unlikely(nsize && limit && new > limit))
11966 return NULL;
11967 } while (!_HA_ATOMIC_CAS(&zone->allocated, &old, new));
Willy Tarreau32f61e22015-03-18 17:54:59 +010011968
Willy Tarreaua5efdff2021-10-22 16:00:02 +020011969 if (!nsize)
11970 ha_free(&ptr);
11971 else
11972 ptr = realloc(ptr, nsize);
Willy Tarreaucdb53462020-12-02 12:12:00 +010011973
11974 if (unlikely(!ptr && nsize)) // failed
11975 _HA_ATOMIC_SUB(&zone->allocated, nsize - osize);
11976
11977 __ha_barrier_atomic_store();
Willy Tarreau32f61e22015-03-18 17:54:59 +010011978 return ptr;
11979}
11980
Thierry Fournierecb83c22020-11-28 15:49:44 +010011981/* This function can fail with an abort() due to a Lua critical error.
Thierry FOURNIERbabae282015-09-17 11:36:37 +020011982 * We are in the initialisation process of HAProxy, this abort() is
11983 * tolerated.
11984 */
Thierry Fournierecb83c22020-11-28 15:49:44 +010011985lua_State *hlua_init_state(int thread_num)
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +010011986{
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010011987 int i;
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010011988 int idx;
11989 struct sample_fetch *sf;
Thierry FOURNIER594afe72015-03-10 23:58:30 +010011990 struct sample_conv *sc;
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010011991 char *p;
Thierry Fournierfd107a22016-02-19 19:57:23 +010011992 const char *error_msg;
Thierry Fournier4234dbd2020-11-28 13:18:23 +010011993 void **context;
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011994 lua_State *L;
Thierry Fournier59f11be2020-11-29 00:37:41 +010011995 struct prepend_path *pp;
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010011996
Thierry FOURNIER380d0932015-01-23 14:27:52 +010011997 /* Init main lua stack. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011998 L = lua_newstate(hlua_alloc, &hlua_global_allocator);
Thierry FOURNIER380d0932015-01-23 14:27:52 +010011999
Thierry Fournier4234dbd2020-11-28 13:18:23 +010012000 /* Initialise Lua context to NULL */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012001 context = lua_getextraspace(L);
Thierry Fournier4234dbd2020-11-28 13:18:23 +010012002 *context = NULL;
12003
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -080012004 /* From this point, until the end of the initialisation function,
Thierry FOURNIERbabae282015-09-17 11:36:37 +020012005 * the Lua function can fail with an abort. We are in the initialisation
12006 * process of HAProxy, this abort() is tolerated.
12007 */
12008
Thierry Fournier3c539322020-11-28 16:05:05 +010012009 /* Call post initialisation function in safe environment. */
12010 if (setjmp(safe_ljmp_env) != 0) {
12011 lua_atpanic(L, hlua_panic_safe);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012012 if (lua_type(L, -1) == LUA_TSTRING)
12013 error_msg = lua_tostring(L, -1);
Thierry Fournier2f05cc62020-11-28 16:08:02 +010012014 else
12015 error_msg = "critical error";
12016 fprintf(stderr, "Lua init: %s.\n", error_msg);
12017 exit(1);
Thierry Fournier3c539322020-11-28 16:05:05 +010012018 } else {
12019 lua_atpanic(L, hlua_panic_ljmp);
Thierry Fournier2f05cc62020-11-28 16:08:02 +010012020 }
12021
Thierry FOURNIER380d0932015-01-23 14:27:52 +010012022 /* Initialise lua. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012023 luaL_openlibs(L);
Tim Duesterhus541fe1e2020-01-12 13:55:41 +010012024#define HLUA_PREPEND_PATH_TOSTRING1(x) #x
12025#define HLUA_PREPEND_PATH_TOSTRING(x) HLUA_PREPEND_PATH_TOSTRING1(x)
12026#ifdef HLUA_PREPEND_PATH
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012027 hlua_prepend_path(L, "path", HLUA_PREPEND_PATH_TOSTRING(HLUA_PREPEND_PATH));
Tim Duesterhus541fe1e2020-01-12 13:55:41 +010012028#endif
12029#ifdef HLUA_PREPEND_CPATH
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012030 hlua_prepend_path(L, "cpath", HLUA_PREPEND_PATH_TOSTRING(HLUA_PREPEND_CPATH));
Tim Duesterhus541fe1e2020-01-12 13:55:41 +010012031#endif
12032#undef HLUA_PREPEND_PATH_TOSTRING
12033#undef HLUA_PREPEND_PATH_TOSTRING1
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010012034
Thierry Fournier59f11be2020-11-29 00:37:41 +010012035 /* Apply configured prepend path */
12036 list_for_each_entry(pp, &prepend_path_list, l)
12037 hlua_prepend_path(L, pp->type, pp->path);
12038
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010012039 /*
12040 *
12041 * Create "core" object.
12042 *
12043 */
12044
Thierry FOURNIERa2d8c652015-03-11 17:29:39 +010012045 /* This table entry is the object "core" base. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012046 lua_newtable(L);
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010012047
Thierry Fournierecb83c22020-11-28 15:49:44 +010012048 /* set the thread id */
12049 hlua_class_const_int(L, "thread", thread_num);
12050
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010012051 /* Push the loglevel constants. */
Willy Tarreau80f5fae2015-02-27 16:38:20 +010012052 for (i = 0; i < NB_LOG_LEVELS; i++)
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012053 hlua_class_const_int(L, log_levels[i], i);
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010012054
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010012055 /* Register special functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012056 hlua_class_function(L, "register_init", hlua_register_init);
12057 hlua_class_function(L, "register_task", hlua_register_task);
12058 hlua_class_function(L, "register_fetches", hlua_register_fetches);
12059 hlua_class_function(L, "register_converters", hlua_register_converters);
12060 hlua_class_function(L, "register_action", hlua_register_action);
12061 hlua_class_function(L, "register_service", hlua_register_service);
12062 hlua_class_function(L, "register_cli", hlua_register_cli);
Christopher Faulet69c581a2021-05-31 08:54:04 +020012063 hlua_class_function(L, "register_filter", hlua_register_filter);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012064 hlua_class_function(L, "yield", hlua_yield);
12065 hlua_class_function(L, "set_nice", hlua_set_nice);
12066 hlua_class_function(L, "sleep", hlua_sleep);
12067 hlua_class_function(L, "msleep", hlua_msleep);
12068 hlua_class_function(L, "add_acl", hlua_add_acl);
12069 hlua_class_function(L, "del_acl", hlua_del_acl);
12070 hlua_class_function(L, "set_map", hlua_set_map);
12071 hlua_class_function(L, "del_map", hlua_del_map);
12072 hlua_class_function(L, "tcp", hlua_socket_new);
William Lallemand3956c4e2021-09-21 16:25:15 +020012073 hlua_class_function(L, "httpclient", hlua_httpclient_new);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012074 hlua_class_function(L, "log", hlua_log);
12075 hlua_class_function(L, "Debug", hlua_log_debug);
12076 hlua_class_function(L, "Info", hlua_log_info);
12077 hlua_class_function(L, "Warning", hlua_log_warning);
12078 hlua_class_function(L, "Alert", hlua_log_alert);
12079 hlua_class_function(L, "done", hlua_done);
12080 hlua_fcn_reg_core_fcn(L);
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010012081
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012082 lua_setglobal(L, "core");
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010012083
12084 /*
12085 *
Christopher Faulet0f3c8902020-01-31 18:57:12 +010012086 * Create "act" object.
12087 *
12088 */
12089
12090 /* This table entry is the object "act" base. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012091 lua_newtable(L);
Christopher Faulet0f3c8902020-01-31 18:57:12 +010012092
12093 /* push action return constants */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012094 hlua_class_const_int(L, "CONTINUE", ACT_RET_CONT);
12095 hlua_class_const_int(L, "STOP", ACT_RET_STOP);
12096 hlua_class_const_int(L, "YIELD", ACT_RET_YIELD);
12097 hlua_class_const_int(L, "ERROR", ACT_RET_ERR);
12098 hlua_class_const_int(L, "DONE", ACT_RET_DONE);
12099 hlua_class_const_int(L, "DENY", ACT_RET_DENY);
12100 hlua_class_const_int(L, "ABORT", ACT_RET_ABRT);
12101 hlua_class_const_int(L, "INVALID", ACT_RET_INV);
Christopher Faulet0f3c8902020-01-31 18:57:12 +010012102
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012103 hlua_class_function(L, "wake_time", hlua_set_wake_time);
Christopher Faulet2c2c2e32020-01-31 19:07:52 +010012104
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012105 lua_setglobal(L, "act");
Christopher Faulet0f3c8902020-01-31 18:57:12 +010012106
12107 /*
12108 *
Christopher Faulet69c581a2021-05-31 08:54:04 +020012109 * Create "Filter" object.
12110 *
12111 */
12112
12113 /* This table entry is the object "filter" base. */
12114 lua_newtable(L);
12115
12116 /* push flags and constants */
12117 hlua_class_const_int(L, "CONTINUE", 1);
12118 hlua_class_const_int(L, "WAIT", 0);
12119 hlua_class_const_int(L, "ERROR", -1);
12120
12121 hlua_class_const_int(L, "FLT_CFG_FL_HTX", FLT_CFG_FL_HTX);
12122
Christopher Fauletc404f112020-02-26 15:03:09 +010012123 hlua_class_function(L, "wake_time", hlua_set_wake_time);
12124 hlua_class_function(L, "register_data_filter", hlua_register_data_filter);
12125 hlua_class_function(L, "unregister_data_filter", hlua_unregister_data_filter);
12126
Christopher Faulet69c581a2021-05-31 08:54:04 +020012127 lua_setglobal(L, "filter");
12128
12129 /*
12130 *
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012131 * Register class Map
12132 *
12133 */
12134
12135 /* This table entry is the object "Map" base. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012136 lua_newtable(L);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012137
12138 /* register pattern types. */
12139 for (i=0; i<PAT_MATCH_NUM; i++)
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012140 hlua_class_const_int(L, pat_match_names[i], i);
Thierry FOURNIER4dc71972017-01-28 08:33:08 +010012141 for (i=0; i<PAT_MATCH_NUM; i++) {
Willy Tarreau843b7cb2018-07-13 10:54:26 +020012142 snprintf(trash.area, trash.size, "_%s", pat_match_names[i]);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012143 hlua_class_const_int(L, trash.area, i);
Thierry FOURNIER4dc71972017-01-28 08:33:08 +010012144 }
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012145
12146 /* register constructor. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012147 hlua_class_function(L, "new", hlua_map_new);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012148
12149 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012150 lua_newtable(L);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012151
Ilya Shipitsind4259502020-04-08 01:07:56 +050012152 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012153 lua_pushstring(L, "__index");
12154 lua_newtable(L);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012155
12156 /* Register . */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012157 hlua_class_function(L, "lookup", hlua_map_lookup);
12158 hlua_class_function(L, "slookup", hlua_map_slookup);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012159
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012160 lua_rawset(L, -3);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012161
Thierry Fournier45e78d72016-02-19 18:34:46 +010012162 /* Register previous table in the registry with reference and named entry.
12163 * The function hlua_register_metatable() pops the stack, so we
12164 * previously create a copy of the table.
12165 */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012166 lua_pushvalue(L, -1); /* Copy the -1 entry and push it on the stack. */
12167 class_map_ref = hlua_register_metatable(L, CLASS_MAP);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012168
12169 /* Assign the metatable to the mai Map object. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012170 lua_setmetatable(L, -2);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012171
12172 /* Set a name to the table. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012173 lua_setglobal(L, "Map");
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012174
12175 /*
12176 *
William Lallemand30fcca12022-03-30 12:03:12 +020012177 * Register "CertCache" class
12178 *
12179 */
12180
12181 /* Create and fill the metatable. */
12182 lua_newtable(L);
12183 /* Register */
12184 hlua_class_function(L, "set", hlua_ckch_set);
12185 lua_setglobal(L, CLASS_CERTCACHE); /* Create global object called Regex */
12186
12187 /*
12188 *
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010012189 * Register class Channel
12190 *
12191 */
12192
12193 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012194 lua_newtable(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010012195
Ilya Shipitsind4259502020-04-08 01:07:56 +050012196 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012197 lua_pushstring(L, "__index");
12198 lua_newtable(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010012199
12200 /* Register . */
Christopher Faulet6a79fc12021-08-06 16:02:36 +020012201 hlua_class_function(L, "data", hlua_channel_get_data);
12202 hlua_class_function(L, "line", hlua_channel_get_line);
12203 hlua_class_function(L, "set", hlua_channel_set_data);
12204 hlua_class_function(L, "remove", hlua_channel_del_data);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012205 hlua_class_function(L, "append", hlua_channel_append);
Christopher Faulet6a79fc12021-08-06 16:02:36 +020012206 hlua_class_function(L, "prepend", hlua_channel_prepend);
12207 hlua_class_function(L, "insert", hlua_channel_insert_data);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012208 hlua_class_function(L, "send", hlua_channel_send);
12209 hlua_class_function(L, "forward", hlua_channel_forward);
Christopher Faulet6a79fc12021-08-06 16:02:36 +020012210 hlua_class_function(L, "input", hlua_channel_get_in_len);
12211 hlua_class_function(L, "output", hlua_channel_get_out_len);
12212 hlua_class_function(L, "may_recv", hlua_channel_may_recv);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012213 hlua_class_function(L, "is_full", hlua_channel_is_full);
12214 hlua_class_function(L, "is_resp", hlua_channel_is_resp);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010012215
Christopher Faulet6a79fc12021-08-06 16:02:36 +020012216 /* Deprecated API */
12217 hlua_class_function(L, "get", hlua_channel_get);
12218 hlua_class_function(L, "dup", hlua_channel_dup);
12219 hlua_class_function(L, "getline", hlua_channel_getline);
12220 hlua_class_function(L, "get_in_len", hlua_channel_get_in_len);
12221 hlua_class_function(L, "get_out_len", hlua_channel_get_out_len);
12222
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012223 lua_rawset(L, -3);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010012224
12225 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012226 class_channel_ref = hlua_register_metatable(L, CLASS_CHANNEL);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010012227
12228 /*
12229 *
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010012230 * Register class Fetches
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010012231 *
12232 */
12233
12234 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012235 lua_newtable(L);
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010012236
Ilya Shipitsind4259502020-04-08 01:07:56 +050012237 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012238 lua_pushstring(L, "__index");
12239 lua_newtable(L);
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010012240
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010012241 /* Browse existing fetches and create the associated
12242 * object method.
12243 */
12244 sf = NULL;
12245 while ((sf = sample_fetch_getnext(sf, &idx)) != NULL) {
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010012246 /* gL.Tua doesn't support '.' and '-' in the function names, replace it
12247 * by an underscore.
12248 */
Willy Tarreau5ef96562021-08-26 16:48:53 +020012249 strlcpy2(trash.area, sf->kw, trash.size);
Willy Tarreau843b7cb2018-07-13 10:54:26 +020012250 for (p = trash.area; *p; p++)
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010012251 if (*p == '.' || *p == '-' || *p == '+')
12252 *p = '_';
12253
12254 /* Register the function. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012255 lua_pushstring(L, trash.area);
12256 lua_pushlightuserdata(L, sf);
12257 lua_pushcclosure(L, hlua_run_sample_fetch, 1);
12258 lua_rawset(L, -3);
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010012259 }
12260
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012261 lua_rawset(L, -3);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010012262
12263 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012264 class_fetches_ref = hlua_register_metatable(L, CLASS_FETCHES);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010012265
12266 /*
12267 *
Thierry FOURNIER594afe72015-03-10 23:58:30 +010012268 * Register class Converters
12269 *
12270 */
12271
12272 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012273 lua_newtable(L);
Thierry FOURNIER594afe72015-03-10 23:58:30 +010012274
12275 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012276 lua_pushstring(L, "__index");
12277 lua_newtable(L);
Thierry FOURNIER594afe72015-03-10 23:58:30 +010012278
12279 /* Browse existing converters and create the associated
12280 * object method.
12281 */
12282 sc = NULL;
12283 while ((sc = sample_conv_getnext(sc, &idx)) != NULL) {
Thierry FOURNIER594afe72015-03-10 23:58:30 +010012284 /* gL.Tua doesn't support '.' and '-' in the function names, replace it
12285 * by an underscore.
12286 */
Willy Tarreau5ef96562021-08-26 16:48:53 +020012287 strlcpy2(trash.area, sc->kw, trash.size);
Willy Tarreau843b7cb2018-07-13 10:54:26 +020012288 for (p = trash.area; *p; p++)
Thierry FOURNIER594afe72015-03-10 23:58:30 +010012289 if (*p == '.' || *p == '-' || *p == '+')
12290 *p = '_';
12291
12292 /* Register the function. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012293 lua_pushstring(L, trash.area);
12294 lua_pushlightuserdata(L, sc);
12295 lua_pushcclosure(L, hlua_run_sample_conv, 1);
12296 lua_rawset(L, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +010012297 }
12298
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012299 lua_rawset(L, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +010012300
12301 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012302 class_converters_ref = hlua_register_metatable(L, CLASS_CONVERTERS);
Thierry FOURNIER594afe72015-03-10 23:58:30 +010012303
12304 /*
12305 *
Thierry FOURNIER08504f42015-03-16 14:17:08 +010012306 * Register class HTTP
12307 *
12308 */
12309
12310 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012311 lua_newtable(L);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010012312
Ilya Shipitsind4259502020-04-08 01:07:56 +050012313 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012314 lua_pushstring(L, "__index");
12315 lua_newtable(L);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010012316
12317 /* Register Lua functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012318 hlua_class_function(L, "req_get_headers",hlua_http_req_get_headers);
12319 hlua_class_function(L, "req_del_header", hlua_http_req_del_hdr);
12320 hlua_class_function(L, "req_rep_header", hlua_http_req_rep_hdr);
12321 hlua_class_function(L, "req_rep_value", hlua_http_req_rep_val);
12322 hlua_class_function(L, "req_add_header", hlua_http_req_add_hdr);
12323 hlua_class_function(L, "req_set_header", hlua_http_req_set_hdr);
12324 hlua_class_function(L, "req_set_method", hlua_http_req_set_meth);
12325 hlua_class_function(L, "req_set_path", hlua_http_req_set_path);
12326 hlua_class_function(L, "req_set_query", hlua_http_req_set_query);
12327 hlua_class_function(L, "req_set_uri", hlua_http_req_set_uri);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010012328
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012329 hlua_class_function(L, "res_get_headers",hlua_http_res_get_headers);
12330 hlua_class_function(L, "res_del_header", hlua_http_res_del_hdr);
12331 hlua_class_function(L, "res_rep_header", hlua_http_res_rep_hdr);
12332 hlua_class_function(L, "res_rep_value", hlua_http_res_rep_val);
12333 hlua_class_function(L, "res_add_header", hlua_http_res_add_hdr);
12334 hlua_class_function(L, "res_set_header", hlua_http_res_set_hdr);
12335 hlua_class_function(L, "res_set_status", hlua_http_res_set_status);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010012336
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012337 lua_rawset(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010012338
12339 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012340 class_http_ref = hlua_register_metatable(L, CLASS_HTTP);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010012341
Christopher Fauletdf97ac42020-02-26 16:57:19 +010012342 /*
12343 *
12344 * Register class HTTPMessage
12345 *
12346 */
12347
12348 /* Create and fill the metatable. */
12349 lua_newtable(L);
12350
Ilya Shipitsinff0f2782021-08-22 22:18:07 +050012351 /* Create and fill the __index entry. */
Christopher Fauletdf97ac42020-02-26 16:57:19 +010012352 lua_pushstring(L, "__index");
12353 lua_newtable(L);
12354
12355 /* Register Lua functions. */
12356 hlua_class_function(L, "is_resp", hlua_http_msg_is_resp);
12357 hlua_class_function(L, "get_stline", hlua_http_msg_get_stline);
12358 hlua_class_function(L, "get_headers", hlua_http_msg_get_headers);
12359 hlua_class_function(L, "del_header", hlua_http_msg_del_hdr);
12360 hlua_class_function(L, "rep_header", hlua_http_msg_rep_hdr);
12361 hlua_class_function(L, "rep_value", hlua_http_msg_rep_val);
12362 hlua_class_function(L, "add_header", hlua_http_msg_add_hdr);
12363 hlua_class_function(L, "set_header", hlua_http_msg_set_hdr);
12364 hlua_class_function(L, "set_method", hlua_http_msg_set_meth);
12365 hlua_class_function(L, "set_path", hlua_http_msg_set_path);
12366 hlua_class_function(L, "set_query", hlua_http_msg_set_query);
12367 hlua_class_function(L, "set_uri", hlua_http_msg_set_uri);
12368 hlua_class_function(L, "set_status", hlua_http_msg_set_status);
12369 hlua_class_function(L, "is_full", hlua_http_msg_is_full);
12370 hlua_class_function(L, "may_recv", hlua_http_msg_may_recv);
12371 hlua_class_function(L, "eom", hlua_http_msg_is_eom);
12372 hlua_class_function(L, "input", hlua_http_msg_get_in_len);
12373 hlua_class_function(L, "output", hlua_http_msg_get_out_len);
12374
12375 hlua_class_function(L, "body", hlua_http_msg_get_body);
12376 hlua_class_function(L, "set", hlua_http_msg_set_data);
12377 hlua_class_function(L, "remove", hlua_http_msg_del_data);
12378 hlua_class_function(L, "append", hlua_http_msg_append);
12379 hlua_class_function(L, "prepend", hlua_http_msg_prepend);
12380 hlua_class_function(L, "insert", hlua_http_msg_insert_data);
12381 hlua_class_function(L, "set_eom", hlua_http_msg_set_eom);
12382 hlua_class_function(L, "unset_eom", hlua_http_msg_unset_eom);
12383
12384 hlua_class_function(L, "send", hlua_http_msg_send);
12385 hlua_class_function(L, "forward", hlua_http_msg_forward);
12386
12387 lua_rawset(L, -3);
12388
12389 /* Register previous table in the registry with reference and named entry. */
12390 class_http_msg_ref = hlua_register_metatable(L, CLASS_HTTP_MSG);
William Lallemand3956c4e2021-09-21 16:25:15 +020012391
12392 /*
12393 *
12394 * Register class HTTPClient
12395 *
12396 */
12397
12398 /* Create and fill the metatable. */
12399 lua_newtable(L);
12400 lua_pushstring(L, "__index");
12401 lua_newtable(L);
12402 hlua_class_function(L, "get", hlua_httpclient_get);
William Lallemanddc2cc902021-10-26 11:43:26 +020012403 hlua_class_function(L, "head", hlua_httpclient_head);
12404 hlua_class_function(L, "put", hlua_httpclient_put);
12405 hlua_class_function(L, "post", hlua_httpclient_post);
12406 hlua_class_function(L, "delete", hlua_httpclient_delete);
William Lallemand3956c4e2021-09-21 16:25:15 +020012407 lua_settable(L, -3); /* Sets the __index entry. */
William Lallemandf77f1de2021-09-28 19:10:38 +020012408 /* Register the garbage collector entry. */
12409 lua_pushstring(L, "__gc");
12410 lua_pushcclosure(L, hlua_httpclient_gc, 0);
12411 lua_settable(L, -3); /* Push the last 2 entries in the table at index -3 */
12412
William Lallemand3956c4e2021-09-21 16:25:15 +020012413
12414
12415 class_httpclient_ref = hlua_register_metatable(L, CLASS_HTTPCLIENT);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010012416 /*
12417 *
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020012418 * Register class AppletTCP
12419 *
12420 */
12421
12422 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012423 lua_newtable(L);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020012424
Ilya Shipitsind4259502020-04-08 01:07:56 +050012425 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012426 lua_pushstring(L, "__index");
12427 lua_newtable(L);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020012428
12429 /* Register Lua functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012430 hlua_class_function(L, "getline", hlua_applet_tcp_getline);
12431 hlua_class_function(L, "receive", hlua_applet_tcp_recv);
12432 hlua_class_function(L, "send", hlua_applet_tcp_send);
12433 hlua_class_function(L, "set_priv", hlua_applet_tcp_set_priv);
12434 hlua_class_function(L, "get_priv", hlua_applet_tcp_get_priv);
12435 hlua_class_function(L, "set_var", hlua_applet_tcp_set_var);
12436 hlua_class_function(L, "unset_var", hlua_applet_tcp_unset_var);
12437 hlua_class_function(L, "get_var", hlua_applet_tcp_get_var);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020012438
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012439 lua_settable(L, -3);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020012440
12441 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012442 class_applet_tcp_ref = hlua_register_metatable(L, CLASS_APPLET_TCP);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020012443
12444 /*
12445 *
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020012446 * Register class AppletHTTP
12447 *
12448 */
12449
12450 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012451 lua_newtable(L);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020012452
Ilya Shipitsind4259502020-04-08 01:07:56 +050012453 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012454 lua_pushstring(L, "__index");
12455 lua_newtable(L);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020012456
12457 /* Register Lua functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012458 hlua_class_function(L, "set_priv", hlua_applet_http_set_priv);
12459 hlua_class_function(L, "get_priv", hlua_applet_http_get_priv);
12460 hlua_class_function(L, "set_var", hlua_applet_http_set_var);
12461 hlua_class_function(L, "unset_var", hlua_applet_http_unset_var);
12462 hlua_class_function(L, "get_var", hlua_applet_http_get_var);
12463 hlua_class_function(L, "getline", hlua_applet_http_getline);
12464 hlua_class_function(L, "receive", hlua_applet_http_recv);
12465 hlua_class_function(L, "send", hlua_applet_http_send);
12466 hlua_class_function(L, "add_header", hlua_applet_http_addheader);
12467 hlua_class_function(L, "set_status", hlua_applet_http_status);
12468 hlua_class_function(L, "start_response", hlua_applet_http_start_response);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020012469
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012470 lua_settable(L, -3);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020012471
12472 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012473 class_applet_http_ref = hlua_register_metatable(L, CLASS_APPLET_HTTP);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020012474
12475 /*
12476 *
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010012477 * Register class TXN
12478 *
12479 */
12480
12481 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012482 lua_newtable(L);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010012483
Ilya Shipitsind4259502020-04-08 01:07:56 +050012484 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012485 lua_pushstring(L, "__index");
12486 lua_newtable(L);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010012487
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +010012488 /* Register Lua functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012489 hlua_class_function(L, "set_priv", hlua_set_priv);
12490 hlua_class_function(L, "get_priv", hlua_get_priv);
12491 hlua_class_function(L, "set_var", hlua_set_var);
12492 hlua_class_function(L, "unset_var", hlua_unset_var);
12493 hlua_class_function(L, "get_var", hlua_get_var);
12494 hlua_class_function(L, "done", hlua_txn_done);
12495 hlua_class_function(L, "reply", hlua_txn_reply_new);
12496 hlua_class_function(L, "set_loglevel", hlua_txn_set_loglevel);
12497 hlua_class_function(L, "set_tos", hlua_txn_set_tos);
12498 hlua_class_function(L, "set_mark", hlua_txn_set_mark);
12499 hlua_class_function(L, "set_priority_class", hlua_txn_set_priority_class);
12500 hlua_class_function(L, "set_priority_offset", hlua_txn_set_priority_offset);
12501 hlua_class_function(L, "deflog", hlua_txn_deflog);
12502 hlua_class_function(L, "log", hlua_txn_log);
12503 hlua_class_function(L, "Debug", hlua_txn_log_debug);
12504 hlua_class_function(L, "Info", hlua_txn_log_info);
12505 hlua_class_function(L, "Warning", hlua_txn_log_warning);
12506 hlua_class_function(L, "Alert", hlua_txn_log_alert);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +010012507
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012508 lua_rawset(L, -3);
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010012509
12510 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012511 class_txn_ref = hlua_register_metatable(L, CLASS_TXN);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012512
12513 /*
12514 *
Christopher Faulet700d9e82020-01-31 12:21:52 +010012515 * Register class reply
12516 *
12517 */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012518 lua_newtable(L);
12519 lua_pushstring(L, "__index");
12520 lua_newtable(L);
12521 hlua_class_function(L, "set_status", hlua_txn_reply_set_status);
12522 hlua_class_function(L, "add_header", hlua_txn_reply_add_header);
12523 hlua_class_function(L, "del_header", hlua_txn_reply_del_header);
12524 hlua_class_function(L, "set_body", hlua_txn_reply_set_body);
12525 lua_settable(L, -3); /* Sets the __index entry. */
12526 class_txn_reply_ref = luaL_ref(L, LUA_REGISTRYINDEX);
Christopher Faulet700d9e82020-01-31 12:21:52 +010012527
12528
12529 /*
12530 *
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012531 * Register class Socket
12532 *
12533 */
12534
12535 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012536 lua_newtable(L);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012537
Ilya Shipitsind4259502020-04-08 01:07:56 +050012538 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012539 lua_pushstring(L, "__index");
12540 lua_newtable(L);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012541
Baptiste Assmann84bb4932015-03-02 21:40:06 +010012542#ifdef USE_OPENSSL
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012543 hlua_class_function(L, "connect_ssl", hlua_socket_connect_ssl);
Baptiste Assmann84bb4932015-03-02 21:40:06 +010012544#endif
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012545 hlua_class_function(L, "connect", hlua_socket_connect);
12546 hlua_class_function(L, "send", hlua_socket_send);
12547 hlua_class_function(L, "receive", hlua_socket_receive);
12548 hlua_class_function(L, "close", hlua_socket_close);
12549 hlua_class_function(L, "getpeername", hlua_socket_getpeername);
12550 hlua_class_function(L, "getsockname", hlua_socket_getsockname);
12551 hlua_class_function(L, "setoption", hlua_socket_setoption);
12552 hlua_class_function(L, "settimeout", hlua_socket_settimeout);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012553
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012554 lua_rawset(L, -3); /* Push the last 2 entries in the table at index -3 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012555
12556 /* Register the garbage collector entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012557 lua_pushstring(L, "__gc");
12558 lua_pushcclosure(L, hlua_socket_gc, 0);
12559 lua_rawset(L, -3); /* Push the last 2 entries in the table at index -3 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012560
12561 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012562 class_socket_ref = hlua_register_metatable(L, CLASS_SOCKET);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012563
Thierry Fournieraafc7772020-12-04 11:47:47 +010012564 lua_atpanic(L, hlua_panic_safe);
12565
12566 return L;
12567}
12568
12569void hlua_init(void) {
12570 int i;
Amaury Denoyelle239fdbf2021-03-24 10:22:03 +010012571 char *errmsg;
Thierry Fournieraafc7772020-12-04 11:47:47 +010012572#ifdef USE_OPENSSL
12573 struct srv_kw *kw;
12574 int tmp_error;
12575 char *error;
12576 char *args[] = { /* SSL client configuration. */
12577 "ssl",
12578 "verify",
12579 "none",
12580 NULL
12581 };
12582#endif
12583
12584 /* Init post init function list head */
12585 for (i = 0; i < MAX_THREADS + 1; i++)
12586 LIST_INIT(&hlua_init_functions[i]);
12587
12588 /* Init state for common/shared lua parts */
12589 hlua_state_id = 0;
Willy Tarreau43ab05b2021-09-28 09:43:11 +020012590 ha_set_thread(NULL);
Thierry Fournieraafc7772020-12-04 11:47:47 +010012591 hlua_states[0] = hlua_init_state(0);
12592
12593 /* Init state 1 for thread 0. We have at least one thread. */
12594 hlua_state_id = 1;
Willy Tarreau43ab05b2021-09-28 09:43:11 +020012595 ha_set_thread(NULL);
Thierry Fournieraafc7772020-12-04 11:47:47 +010012596 hlua_states[1] = hlua_init_state(1);
12597
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012598 /* Proxy and server configuration initialisation. */
William Lallemand6bb77b92021-07-28 15:48:16 +020012599 socket_proxy = alloc_new_proxy("LUA-SOCKET", PR_CAP_FE|PR_CAP_BE|PR_CAP_INT, &errmsg);
Amaury Denoyelle239fdbf2021-03-24 10:22:03 +010012600 if (!socket_proxy) {
12601 fprintf(stderr, "Lua init: %s\n", errmsg);
12602 exit(1);
12603 }
12604 proxy_preset_defaults(socket_proxy);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012605
12606 /* Init TCP server: unchanged parameters */
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010012607 socket_tcp = new_server(socket_proxy);
12608 if (!socket_tcp) {
12609 fprintf(stderr, "Lua init: failed to allocate tcp server socket\n");
12610 exit(1);
12611 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012612
12613#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012614 /* Init TCP server: unchanged parameters */
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010012615 socket_ssl = new_server(socket_proxy);
12616 if (!socket_ssl) {
12617 fprintf(stderr, "Lua init: failed to allocate ssl server socket\n");
12618 exit(1);
12619 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012620
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010012621 socket_ssl->use_ssl = 1;
12622 socket_ssl->xprt = xprt_get(XPRT_SSL);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012623
Bertrand Jacquin80839ff2021-01-21 19:14:46 +000012624 for (i = 0; args[i] != NULL; i++) {
12625 if ((kw = srv_find_kw(args[i])) != NULL) { /* Maybe it's registered server keyword */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012626 /*
12627 *
12628 * If the keyword is not known, we can search in the registered
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -080012629 * server keywords. This is useful to configure special SSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012630 * features like client certificates and ssl_verify.
12631 *
12632 */
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010012633 tmp_error = kw->parse(args, &i, socket_proxy, socket_ssl, &error);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012634 if (tmp_error != 0) {
12635 fprintf(stderr, "INTERNAL ERROR: %s\n", error);
12636 abort(); /* This must be never arrives because the command line
12637 not editable by the user. */
12638 }
Bertrand Jacquin80839ff2021-01-21 19:14:46 +000012639 i += kw->skip;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012640 }
12641 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012642#endif
Thierry Fournier75933d42016-01-21 09:30:18 +010012643
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +010012644}
Willy Tarreaubb57d942016-12-21 19:04:56 +010012645
Tim Duesterhusd0c0ca22020-07-04 11:53:26 +020012646static void hlua_deinit()
12647{
Willy Tarreau186f3762020-12-04 11:48:12 +010012648 int thr;
Christopher Faulet69c581a2021-05-31 08:54:04 +020012649 struct hlua_reg_filter *reg_flt, *reg_flt_bck;
12650
12651 list_for_each_entry_safe(reg_flt, reg_flt_bck, &referenced_filters, l)
12652 release_hlua_reg_filter(reg_flt);
Willy Tarreau186f3762020-12-04 11:48:12 +010012653
12654 for (thr = 0; thr < MAX_THREADS+1; thr++) {
12655 if (hlua_states[thr])
12656 lua_close(hlua_states[thr]);
12657 }
Willy Tarreau430bf4a2021-03-04 09:45:32 +010012658
Amaury Denoyellebc2ebfa2021-08-25 15:34:53 +020012659 srv_drop(socket_tcp);
Willy Tarreau430bf4a2021-03-04 09:45:32 +010012660
Willy Tarreau0f143af2021-03-05 10:41:48 +010012661#ifdef USE_OPENSSL
Amaury Denoyellebc2ebfa2021-08-25 15:34:53 +020012662 srv_drop(socket_ssl);
Willy Tarreau0f143af2021-03-05 10:41:48 +010012663#endif
Amaury Denoyelle239fdbf2021-03-24 10:22:03 +010012664
12665 free_proxy(socket_proxy);
Tim Duesterhusd0c0ca22020-07-04 11:53:26 +020012666}
12667
12668REGISTER_POST_DEINIT(hlua_deinit);
12669
Willy Tarreau80713382018-11-26 10:19:54 +010012670static void hlua_register_build_options(void)
12671{
Willy Tarreaubb57d942016-12-21 19:04:56 +010012672 char *ptr = NULL;
Willy Tarreau80713382018-11-26 10:19:54 +010012673
Willy Tarreaubb57d942016-12-21 19:04:56 +010012674 memprintf(&ptr, "Built with Lua version : %s", LUA_RELEASE);
12675 hap_register_build_opts(ptr, 1);
12676}
Willy Tarreau80713382018-11-26 10:19:54 +010012677
12678INITCALL0(STG_REGISTER, hlua_register_build_options);