blob: b5465e8b8ee120e4c0d03948899dc94bb1ea3248 [file] [log] [blame]
Thierry Fourniere726b142016-02-11 17:57:57 +01001/*
2 * Lua unsafe core engine
3 *
4 * Copyright 2015-2016 Thierry Fournier <tfournier@arpalert.org>
5 *
6 * This program is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU General Public License
8 * as published by the Free Software Foundation; either version
9 * 2 of the License, or (at your option) any later version.
10 *
11 */
12
Bertrand Jacquinf4c12d42021-01-21 21:14:07 +000013#define _GNU_SOURCE
14
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +010015#include <ctype.h>
Thierry FOURNIERbabae282015-09-17 11:36:37 +020016#include <setjmp.h>
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +010017
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +010018#include <lauxlib.h>
19#include <lua.h>
20#include <lualib.h>
21
Thierry FOURNIER463119c2015-03-10 00:35:36 +010022#if !defined(LUA_VERSION_NUM) || LUA_VERSION_NUM < 503
23#error "Requires Lua 5.3 or later."
Cyril Bontédc0306e2015-03-02 00:08:40 +010024#endif
25
Willy Tarreau8d2b7772020-05-27 10:58:19 +020026#include <import/ebpttree.h>
Thierry FOURNIER380d0932015-01-23 14:27:52 +010027
Willy Tarreaub2551052020-06-09 09:07:15 +020028#include <haproxy/api.h>
29#include <haproxy/applet.h>
Willy Tarreaudfd3de82020-06-04 23:46:14 +020030#include <haproxy/arg.h>
Christopher Fauletd25d9262020-08-06 11:04:46 +020031#include <haproxy/auth.h>
Willy Tarreau6be78492020-06-05 00:00:29 +020032#include <haproxy/cfgparse.h>
Willy Tarreauf1d32c42020-06-04 21:07:02 +020033#include <haproxy/channel.h>
Willy Tarreau83487a82020-06-04 20:19:54 +020034#include <haproxy/cli.h>
Willy Tarreau55542642021-10-08 09:33:24 +020035#include <haproxy/clock.h>
Willy Tarreau7ea393d2020-06-04 18:02:10 +020036#include <haproxy/connection.h>
Christopher Faulet69c581a2021-05-31 08:54:04 +020037#include <haproxy/filters.h>
Willy Tarreau5413a872020-06-02 19:33:08 +020038#include <haproxy/h1.h>
Willy Tarreau86416052020-06-04 09:20:54 +020039#include <haproxy/hlua.h>
Willy Tarreau8c794002020-06-04 10:05:25 +020040#include <haproxy/hlua_fcn.h>
Willy Tarreauc2b1ff02020-06-04 21:21:03 +020041#include <haproxy/http_ana.h>
William Lallemand3956c4e2021-09-21 16:25:15 +020042#include <haproxy/http_client.h>
Willy Tarreau126ba3a2020-06-04 18:26:43 +020043#include <haproxy/http_fetch.h>
Willy Tarreaub2551052020-06-09 09:07:15 +020044#include <haproxy/http_htx.h>
Willy Tarreauc761f842020-06-04 11:40:28 +020045#include <haproxy/http_rules.h>
Willy Tarreau36979d92020-06-05 17:27:29 +020046#include <haproxy/log.h>
Willy Tarreau2cd58092020-06-04 15:10:43 +020047#include <haproxy/map.h>
Willy Tarreau8efbdfb2020-06-04 11:29:21 +020048#include <haproxy/obj_type.h>
Willy Tarreau225a90a2020-06-04 15:06:28 +020049#include <haproxy/pattern.h>
Willy Tarreau469509b2020-06-04 15:13:30 +020050#include <haproxy/payload.h>
Willy Tarreau3d6ee402021-05-08 20:28:07 +020051#include <haproxy/proxy.h>
Willy Tarreaub2551052020-06-09 09:07:15 +020052#include <haproxy/regex.h>
Willy Tarreaue6ce10b2020-06-04 15:33:47 +020053#include <haproxy/sample.h>
Willy Tarreau5edca2f2022-05-27 09:25:10 +020054#include <haproxy/sc_strm.h>
Willy Tarreau198e92a2021-03-05 10:23:32 +010055#include <haproxy/server.h>
Willy Tarreau48d25b32020-06-04 18:58:52 +020056#include <haproxy/session.h>
William Lallemand30fcca12022-03-30 12:03:12 +020057#include <haproxy/ssl_ckch.h>
58#include <haproxy/ssl_sock.h>
Willy Tarreau2eec9b52020-06-04 19:58:55 +020059#include <haproxy/stats-t.h>
Willy Tarreaucb086c62022-05-27 09:47:12 +020060#include <haproxy/stconn.h>
Willy Tarreaudfd3de82020-06-04 23:46:14 +020061#include <haproxy/stream.h>
Willy Tarreaucea0e1b2020-06-04 17:25:40 +020062#include <haproxy/task.h>
Willy Tarreau8b550af2020-06-04 17:42:48 +020063#include <haproxy/tcp_rules.h>
Willy Tarreaub2551052020-06-09 09:07:15 +020064#include <haproxy/thread.h>
Willy Tarreau48fbcae2020-06-03 18:09:46 +020065#include <haproxy/tools.h>
Willy Tarreaua1718922020-06-04 16:25:31 +020066#include <haproxy/vars.h>
Willy Tarreaub2551052020-06-09 09:07:15 +020067#include <haproxy/xref.h>
68
Thierry FOURNIER380d0932015-01-23 14:27:52 +010069
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +010070/* Lua uses longjmp to perform yield or throwing errors. This
71 * macro is used only for identifying the function that can
72 * not return because a longjmp is executed.
73 * __LJMP marks a prototype of hlua file that can use longjmp.
74 * WILL_LJMP() marks an lua function that will use longjmp.
75 * MAY_LJMP() marks an lua function that may use longjmp.
76 */
77#define __LJMP
Willy Tarreau4e7cc332018-10-20 17:45:48 +020078#define WILL_LJMP(func) do { func; my_unreachable(); } while(0)
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +010079#define MAY_LJMP(func) func
80
Thierry FOURNIERbabae282015-09-17 11:36:37 +020081/* This couple of function executes securely some Lua calls outside of
82 * the lua runtime environment. Each Lua call can return a longjmp
83 * if it encounter a memory error.
84 *
85 * Lua documentation extract:
86 *
87 * If an error happens outside any protected environment, Lua calls
88 * a panic function (see lua_atpanic) and then calls abort, thus
89 * exiting the host application. Your panic function can avoid this
90 * exit by never returning (e.g., doing a long jump to your own
91 * recovery point outside Lua).
92 *
93 * The panic function runs as if it were a message handler (see
Willy Tarreau3dfb7da2022-03-02 22:33:39 +010094 * #2.3); in particular, the error message is at the top of the
Thierry FOURNIERbabae282015-09-17 11:36:37 +020095 * stack. However, there is no guarantee about stack space. To push
96 * anything on the stack, the panic function must first check the
Willy Tarreau3dfb7da2022-03-02 22:33:39 +010097 * available space (see #4.2).
Thierry FOURNIERbabae282015-09-17 11:36:37 +020098 *
99 * We must check all the Lua entry point. This includes:
100 * - The include/proto/hlua.h exported functions
101 * - the task wrapper function
102 * - The action wrapper function
103 * - The converters wrapper function
104 * - The sample-fetch wrapper functions
105 *
Ilya Shipitsin46a030c2020-07-05 16:36:08 +0500106 * It is tolerated that the initialisation function returns an abort.
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -0800107 * Before each Lua abort, an error message is written on stderr.
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200108 *
109 * The macro SET_SAFE_LJMP initialise the longjmp. The Macro
110 * RESET_SAFE_LJMP reset the longjmp. These function must be macro
111 * because they must be exists in the program stack when the longjmp
112 * is called.
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +0200113 *
114 * Note that the Lua processing is not really thread safe. It provides
115 * heavy system which consists to add our own lock function in the Lua
116 * code and recompile the library. This system will probably not accepted
117 * by maintainers of various distribs.
118 *
Ilya Shipitsin856aabc2020-04-16 23:51:34 +0500119 * Our main execution point of the Lua is the function lua_resume(). A
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +0200120 * quick looking on the Lua sources displays a lua_lock() a the start
121 * of function and a lua_unlock() at the end of the function. So I
122 * conclude that the Lua thread safe mode just perform a mutex around
123 * all execution. So I prefer to do this in the HAProxy code, it will be
124 * easier for distro maintainers.
125 *
126 * Note that the HAProxy lua functions rounded by the macro SET_SAFE_LJMP
127 * and RESET_SAFE_LJMP manipulates the Lua stack, so it will be careful
128 * to set mutex around these functions.
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200129 */
Willy Tarreau86abe442018-11-25 20:12:18 +0100130__decl_spinlock(hlua_global_lock);
Thierry FOURNIERffbad792017-07-12 11:39:04 +0200131THREAD_LOCAL jmp_buf safe_ljmp_env;
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200132static int hlua_panic_safe(lua_State *L) { return 0; }
Willy Tarreau6a510902021-07-14 19:41:25 +0200133static int hlua_panic_ljmp(lua_State *L) { WILL_LJMP(longjmp(safe_ljmp_env, 1)); return 0; }
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200134
Thierry Fournier62a22aa2020-11-28 21:06:35 +0100135/* This is the chained list of struct hlua_function referenced
136 * for haproxy action, sample-fetches, converters, cli and
137 * applet bindings. It is used for a post-initialisation control.
138 */
139static struct list referenced_functions = LIST_HEAD_INIT(referenced_functions);
140
Thierry Fournierc7492592020-11-28 23:57:24 +0100141/* This variable is used only during initialization to identify the Lua state
142 * currently being initialized. 0 is the common lua state, 1 to n are the Lua
143 * states dedicated to each thread (in this case hlua_state_id==tid+1).
144 */
145static int hlua_state_id;
146
Thierry Fournier59f11be2020-11-29 00:37:41 +0100147/* This is a NULL-terminated list of lua file which are referenced to load per thread */
148static char **per_thread_load = NULL;
149
150lua_State *hlua_init_state(int thread_id);
151
Willy Tarreau1e7bef12021-08-20 15:47:25 +0200152/* This function takes the Lua global lock. Keep this function's visibility
153 * global so that it can appear in stack dumps and performance profiles!
154 */
155void lua_take_global_lock()
156{
157 HA_SPIN_LOCK(LUA_LOCK, &hlua_global_lock);
158}
159
160static inline void lua_drop_global_lock()
161{
162 HA_SPIN_UNLOCK(LUA_LOCK, &hlua_global_lock);
163}
164
Thierry Fournier7cbe5042020-11-28 17:02:21 +0100165#define SET_SAFE_LJMP_L(__L, __HLUA) \
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200166 ({ \
167 int ret; \
Thierry Fournier021d9862020-11-28 23:42:03 +0100168 if ((__HLUA)->state_id == 0) \
Willy Tarreau1e7bef12021-08-20 15:47:25 +0200169 lua_take_global_lock(); \
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200170 if (setjmp(safe_ljmp_env) != 0) { \
171 lua_atpanic(__L, hlua_panic_safe); \
172 ret = 0; \
Thierry Fournier021d9862020-11-28 23:42:03 +0100173 if ((__HLUA)->state_id == 0) \
Willy Tarreau1e7bef12021-08-20 15:47:25 +0200174 lua_drop_global_lock(); \
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200175 } else { \
176 lua_atpanic(__L, hlua_panic_ljmp); \
177 ret = 1; \
178 } \
179 ret; \
180 })
181
182/* If we are the last function catching Lua errors, we
183 * must reset the panic function.
184 */
Thierry Fournier7cbe5042020-11-28 17:02:21 +0100185#define RESET_SAFE_LJMP_L(__L, __HLUA) \
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200186 do { \
187 lua_atpanic(__L, hlua_panic_safe); \
Thierry Fournier021d9862020-11-28 23:42:03 +0100188 if ((__HLUA)->state_id == 0) \
Willy Tarreau1e7bef12021-08-20 15:47:25 +0200189 lua_drop_global_lock(); \
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200190 } while(0)
191
Thierry Fournier7cbe5042020-11-28 17:02:21 +0100192#define SET_SAFE_LJMP(__HLUA) \
193 SET_SAFE_LJMP_L((__HLUA)->T, __HLUA)
194
195#define RESET_SAFE_LJMP(__HLUA) \
196 RESET_SAFE_LJMP_L((__HLUA)->T, __HLUA)
197
198#define SET_SAFE_LJMP_PARENT(__HLUA) \
Thierry Fournier021d9862020-11-28 23:42:03 +0100199 SET_SAFE_LJMP_L(hlua_states[(__HLUA)->state_id], __HLUA)
Thierry Fournier7cbe5042020-11-28 17:02:21 +0100200
201#define RESET_SAFE_LJMP_PARENT(__HLUA) \
Thierry Fournier021d9862020-11-28 23:42:03 +0100202 RESET_SAFE_LJMP_L(hlua_states[(__HLUA)->state_id], __HLUA)
Thierry Fournier7cbe5042020-11-28 17:02:21 +0100203
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +0200204/* Applet status flags */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200205#define APPLET_DONE 0x01 /* applet processing is done. */
Christopher Faulet18c2e8d2019-03-01 12:02:08 +0100206/* unused: 0x02 */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200207#define APPLET_HDR_SENT 0x04 /* Response header sent. */
Christopher Fauleta2097962019-07-15 16:25:33 +0200208/* unused: 0x08, 0x10 */
Thierry FOURNIERd93ea2b2015-12-20 19:14:52 +0100209#define APPLET_HTTP11 0x20 /* Last chunk sent. */
Christopher Faulet56a3d6e2019-02-27 22:06:23 +0100210#define APPLET_RSP_SENT 0x40 /* The response was fully sent */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200211
Thierry Fournierafc63e22020-11-28 17:06:51 +0100212/* The main Lua execution context. The 0 index is the
213 * common state shared by all threads.
214 */
Willy Tarreau186f3762020-12-04 11:48:12 +0100215static lua_State *hlua_states[MAX_THREADS + 1];
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100216
Christopher Fauletc404f112020-02-26 15:03:09 +0100217#define HLUA_FLT_CB_FINAL 0x00000001
218#define HLUA_FLT_CB_RETVAL 0x00000002
219#define HLUA_FLT_CB_ARG_CHN 0x00000004
220#define HLUA_FLT_CB_ARG_HTTP_MSG 0x00000008
221
Christopher Faulet9f55a502020-02-25 15:21:02 +0100222#define HLUA_FLT_CTX_FL_PAYLOAD 0x00000001
223
Christopher Faulet69c581a2021-05-31 08:54:04 +0200224struct hlua_reg_filter {
225 char *name;
226 int flt_ref[MAX_THREADS + 1];
227 int fun_ref[MAX_THREADS + 1];
228 struct list l;
229};
230
231struct hlua_flt_config {
232 struct hlua_reg_filter *reg;
233 int ref[MAX_THREADS + 1];
234 char **args;
235};
236
237struct hlua_flt_ctx {
238 int ref; /* ref to the filter lua object */
239 struct hlua *hlua[2]; /* lua runtime context (0: request, 1: response) */
240 unsigned int cur_off[2]; /* current offset (0: request, 1: response) */
241 unsigned int cur_len[2]; /* current forwardable length (0: request, 1: response) */
242 unsigned int flags; /* HLUA_FLT_CTX_FL_* */
243};
244
Willy Tarreau5321da92022-05-06 11:57:34 +0200245/* appctx context used by the cosockets */
246struct hlua_csk_ctx {
247 int connected;
248 struct xref xref; /* cross reference with the Lua object owner. */
249 struct list wake_on_read;
250 struct list wake_on_write;
251 struct appctx *appctx;
252 int die;
253};
254
Willy Tarreaue23f33b2022-05-06 14:07:13 +0200255/* appctx context used by TCP services */
256struct hlua_tcp_ctx {
257 struct hlua *hlua;
258 int flags;
259 struct task *task;
260};
261
Willy Tarreauaa229cc2022-05-06 14:26:10 +0200262/* appctx context used by HTTP services */
263struct hlua_http_ctx {
264 struct hlua *hlua;
265 int left_bytes; /* The max amount of bytes that we can read. */
266 int flags;
267 int status;
268 const char *reason;
269 struct task *task;
270};
271
Willy Tarreaubcda5f62022-05-03 18:13:39 +0200272/* used by registered CLI keywords */
273struct hlua_cli_ctx {
274 struct hlua *hlua;
275 struct task *task;
276 struct hlua_function *fcn;
277};
278
Christopher Faulet69c581a2021-05-31 08:54:04 +0200279DECLARE_STATIC_POOL(pool_head_hlua_flt_ctx, "hlua_flt_ctx", sizeof(struct hlua_flt_ctx));
280
Christopher Faulet9f55a502020-02-25 15:21:02 +0100281static int hlua_filter_from_payload(struct filter *filter);
282
Christopher Faulet69c581a2021-05-31 08:54:04 +0200283/* This is the chained list of struct hlua_flt referenced
284 * for haproxy filters. It is used for a post-initialisation control.
285 */
286static struct list referenced_filters = LIST_HEAD_INIT(referenced_filters);
287
288
Thierry FOURNIERebed6e92016-12-16 11:54:07 +0100289/* This is the memory pool containing struct lua for applets
290 * (including cli).
291 */
Willy Tarreau8ceae722018-11-26 11:58:30 +0100292DECLARE_STATIC_POOL(pool_head_hlua, "hlua", sizeof(struct hlua));
Thierry FOURNIERebed6e92016-12-16 11:54:07 +0100293
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +0100294/* Used for Socket connection. */
Amaury Denoyelle239fdbf2021-03-24 10:22:03 +0100295static struct proxy *socket_proxy;
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +0100296static struct server *socket_tcp;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +0100297#ifdef USE_OPENSSL
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +0100298static struct server *socket_ssl;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +0100299#endif
300
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +0100301/* List head of the function called at the initialisation time. */
Thierry Fournierc7492592020-11-28 23:57:24 +0100302struct list hlua_init_functions[MAX_THREADS + 1];
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +0100303
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +0100304/* The following variables contains the reference of the different
305 * Lua classes. These references are useful for identify metadata
306 * associated with an object.
307 */
Thierry FOURNIER65f34c62015-02-16 20:11:43 +0100308static int class_txn_ref;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +0100309static int class_socket_ref;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +0100310static int class_channel_ref;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +0100311static int class_fetches_ref;
Thierry FOURNIER594afe72015-03-10 23:58:30 +0100312static int class_converters_ref;
Thierry FOURNIER08504f42015-03-16 14:17:08 +0100313static int class_http_ref;
Christopher Fauletdf97ac42020-02-26 16:57:19 +0100314static int class_http_msg_ref;
William Lallemand3956c4e2021-09-21 16:25:15 +0200315static int class_httpclient_ref;
Thierry FOURNIER3def3932015-04-07 11:27:54 +0200316static int class_map_ref;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +0200317static int class_applet_tcp_ref;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200318static int class_applet_http_ref;
Christopher Faulet700d9e82020-01-31 12:21:52 +0100319static int class_txn_reply_ref;
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +0100320
Thierry FOURNIERbd413492015-03-03 16:52:26 +0100321/* Global Lua execution timeout. By default Lua, execution linked
Willy Tarreau87b09662015-04-03 00:22:06 +0200322 * with stream (actions, sample-fetches and converters) have a
Thierry FOURNIERbd413492015-03-03 16:52:26 +0100323 * short timeout. Lua linked with tasks doesn't have a timeout
324 * because a task may remain alive during all the haproxy execution.
325 */
326static unsigned int hlua_timeout_session = 4000; /* session timeout. */
327static unsigned int hlua_timeout_task = TICK_ETERNITY; /* task timeout. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +0200328static unsigned int hlua_timeout_applet = 4000; /* applet timeout. */
Thierry FOURNIERbd413492015-03-03 16:52:26 +0100329
Thierry FOURNIERee9f8022015-03-03 17:37:37 +0100330/* Interrupts the Lua processing each "hlua_nb_instruction" instructions.
331 * it is used for preventing infinite loops.
332 *
333 * I test the scheer with an infinite loop containing one incrementation
334 * and one test. I run this loop between 10 seconds, I raise a ceil of
335 * 710M loops from one interrupt each 9000 instructions, so I fix the value
336 * to one interrupt each 10 000 instructions.
337 *
338 * configured | Number of
339 * instructions | loops executed
340 * between two | in milions
341 * forced yields |
342 * ---------------+---------------
343 * 10 | 160
344 * 500 | 670
345 * 1000 | 680
346 * 5000 | 700
347 * 7000 | 700
348 * 8000 | 700
349 * 9000 | 710 <- ceil
350 * 10000 | 710
351 * 100000 | 710
352 * 1000000 | 710
353 *
354 */
355static unsigned int hlua_nb_instruction = 10000;
356
Willy Tarreaucdb53462020-12-02 12:12:00 +0100357/* Descriptor for the memory allocation state. The limit is pre-initialised to
358 * 0 until it is replaced by "tune.lua.maxmem" during the config parsing, or it
359 * is replaced with ~0 during post_init after everything was loaded. This way
360 * it is guaranteed that if limit is ~0 the boot is complete and that if it's
361 * zero it's not yet limited and proper accounting is required.
Willy Tarreau32f61e22015-03-18 17:54:59 +0100362 */
363struct hlua_mem_allocator {
364 size_t allocated;
365 size_t limit;
366};
367
Willy Tarreaucdb53462020-12-02 12:12:00 +0100368static struct hlua_mem_allocator hlua_global_allocator THREAD_ALIGNED(64);
Willy Tarreau32f61e22015-03-18 17:54:59 +0100369
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100370/* These functions converts types between HAProxy internal args or
371 * sample and LUA types. Another function permits to check if the
372 * LUA stack contains arguments according with an required ARG_T
373 * format.
374 */
375static int hlua_arg2lua(lua_State *L, const struct arg *arg);
376static int hlua_lua2arg(lua_State *L, int ud, struct arg *arg);
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100377__LJMP static int hlua_lua2arg_check(lua_State *L, int first, struct arg *argp,
David Carlier0c437f42016-04-27 16:21:56 +0100378 uint64_t mask, struct proxy *p);
Willy Tarreau5eadada2015-03-10 17:28:54 +0100379static int hlua_smp2lua(lua_State *L, struct sample *smp);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100380static int hlua_smp2lua_str(lua_State *L, struct sample *smp);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100381static int hlua_lua2smp(lua_State *L, int ud, struct sample *smp);
382
Christopher Faulet9d1332b2020-02-24 16:46:16 +0100383__LJMP static int hlua_http_get_headers(lua_State *L, struct http_msg *msg);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200384
Thierry Fournier59f11be2020-11-29 00:37:41 +0100385struct prepend_path {
386 struct list l;
387 char *type;
388 char *path;
389};
390
391static struct list prepend_path_list = LIST_HEAD_INIT(prepend_path_list);
392
Thierry FOURNIER23bc3752015-09-11 19:15:43 +0200393#define SEND_ERR(__be, __fmt, __args...) \
394 do { \
395 send_log(__be, LOG_ERR, __fmt, ## __args); \
396 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE)) \
Christopher Faulet767a84b2017-11-24 16:50:31 +0100397 ha_alert(__fmt, ## __args); \
Thierry FOURNIER23bc3752015-09-11 19:15:43 +0200398 } while (0)
399
Thierry Fournier62a22aa2020-11-28 21:06:35 +0100400static inline struct hlua_function *new_hlua_function()
401{
402 struct hlua_function *fcn;
Thierry Fournierc7492592020-11-28 23:57:24 +0100403 int i;
Thierry Fournier62a22aa2020-11-28 21:06:35 +0100404
405 fcn = calloc(1, sizeof(*fcn));
406 if (!fcn)
407 return NULL;
Willy Tarreau2b718102021-04-21 07:32:39 +0200408 LIST_APPEND(&referenced_functions, &fcn->l);
Thierry Fournierc7492592020-11-28 23:57:24 +0100409 for (i = 0; i < MAX_THREADS + 1; i++)
410 fcn->function_ref[i] = -1;
Thierry Fournier62a22aa2020-11-28 21:06:35 +0100411 return fcn;
412}
413
Christopher Fauletdda44442021-04-12 14:05:43 +0200414static inline void release_hlua_function(struct hlua_function *fcn)
415{
416 if (!fcn)
417 return;
418 if (fcn->name)
419 ha_free(&fcn->name);
Willy Tarreau2b718102021-04-21 07:32:39 +0200420 LIST_DELETE(&fcn->l);
Christopher Fauletdda44442021-04-12 14:05:43 +0200421 ha_free(&fcn);
422}
423
Thierry Fournierc7492592020-11-28 23:57:24 +0100424/* If the common state is set, the stack id is 0, otherwise it is the tid + 1 */
425static inline int fcn_ref_to_stack_id(struct hlua_function *fcn)
426{
427 if (fcn->function_ref[0] == -1)
428 return tid + 1;
429 return 0;
430}
431
Christopher Faulet69c581a2021-05-31 08:54:04 +0200432/* Create a new registered filter. Only its name is filled */
433static inline struct hlua_reg_filter *new_hlua_reg_filter(const char *name)
434{
435 struct hlua_reg_filter *reg_flt;
436 int i;
437
438 reg_flt = calloc(1, sizeof(*reg_flt));
439 if (!reg_flt)
440 return NULL;
441 reg_flt->name = strdup(name);
442 if (!reg_flt->name) {
443 free(reg_flt);
444 return NULL;
445 }
446 LIST_APPEND(&referenced_filters, &reg_flt->l);
447 for (i = 0; i < MAX_THREADS + 1; i++) {
448 reg_flt->flt_ref[i] = -1;
449 reg_flt->fun_ref[i] = -1;
450 }
451 return reg_flt;
452}
453
454/* Release a registered filter */
455static inline void release_hlua_reg_filter(struct hlua_reg_filter *reg_flt)
456{
457 if (!reg_flt)
458 return;
459 if (reg_flt->name)
460 ha_free(&reg_flt->name);
461 LIST_DELETE(&reg_flt->l);
462 ha_free(&reg_flt);
463}
464
465/* If the common state is set, the stack id is 0, otherwise it is the tid + 1 */
466static inline int reg_flt_to_stack_id(struct hlua_reg_filter *reg_flt)
467{
468 if (reg_flt->fun_ref[0] == -1)
469 return tid + 1;
470 return 0;
471}
472
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100473/* Used to check an Lua function type in the stack. It creates and
474 * returns a reference of the function. This function throws an
475 * error if the rgument is not a "function".
476 */
477__LJMP unsigned int hlua_checkfunction(lua_State *L, int argno)
478{
479 if (!lua_isfunction(L, argno)) {
Thierry FOURNIERfd1e9552018-02-23 18:41:18 +0100480 const char *msg = lua_pushfstring(L, "function expected, got %s", luaL_typename(L, argno));
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100481 WILL_LJMP(luaL_argerror(L, argno, msg));
482 }
483 lua_pushvalue(L, argno);
484 return luaL_ref(L, LUA_REGISTRYINDEX);
485}
486
Christopher Fauletba9e21d2020-02-25 10:20:04 +0100487/* Used to check an Lua table type in the stack. It creates and
488 * returns a reference of the table. This function throws an
489 * error if the rgument is not a "table".
490 */
491__LJMP unsigned int hlua_checktable(lua_State *L, int argno)
492{
493 if (!lua_istable(L, argno)) {
494 const char *msg = lua_pushfstring(L, "table expected, got %s", luaL_typename(L, argno));
495 WILL_LJMP(luaL_argerror(L, argno, msg));
496 }
497 lua_pushvalue(L, argno);
498 return luaL_ref(L, LUA_REGISTRYINDEX);
499}
500
Christopher Fauletd09cc512021-03-24 14:48:45 +0100501__LJMP const char *hlua_traceback(lua_State *L, const char* sep)
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200502{
503 lua_Debug ar;
504 int level = 0;
Willy Tarreau83061a82018-07-13 11:56:34 +0200505 struct buffer *msg = get_trash_chunk();
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200506
507 while (lua_getstack(L, level++, &ar)) {
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200508 /* Fill fields:
509 * 'S': fills in the fields source, short_src, linedefined, lastlinedefined, and what;
510 * 'l': fills in the field currentline;
511 * 'n': fills in the field name and namewhat;
512 * 't': fills in the field istailcall;
513 */
514 lua_getinfo(L, "Slnt", &ar);
515
Willy Tarreau5c143402022-06-19 17:35:53 +0200516 /* skip these empty entries, usually they come from deep C functions */
517 if (ar.currentline < 0 && *ar.what == 'C' && !*ar.namewhat && !ar.name)
518 continue;
519
520 /* Add separator */
521 if (b_data(msg))
522 chunk_appendf(msg, "%s", sep);
523
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200524 /* Append code localisation */
525 if (ar.currentline > 0)
Christopher Fauletd09cc512021-03-24 14:48:45 +0100526 chunk_appendf(msg, "%s:%d: ", ar.short_src, ar.currentline);
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200527 else
Christopher Fauletd09cc512021-03-24 14:48:45 +0100528 chunk_appendf(msg, "%s: ", ar.short_src);
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200529
530 /*
531 * Get function name
532 *
533 * if namewhat is no empty, name is defined.
534 * what contains "Lua" for Lua function, "C" for C function,
535 * or "main" for main code.
536 */
537 if (*ar.namewhat != '\0' && ar.name != NULL) /* is there a name from code? */
Christopher Fauletd09cc512021-03-24 14:48:45 +0100538 chunk_appendf(msg, "in %s '%s'", ar.namewhat, ar.name); /* use it */
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200539
540 else if (*ar.what == 'm') /* "main", the code is not executed in a function */
Christopher Fauletd09cc512021-03-24 14:48:45 +0100541 chunk_appendf(msg, "in main chunk");
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200542
543 else if (*ar.what != 'C') /* for Lua functions, use <file:line> */
Christopher Fauletd09cc512021-03-24 14:48:45 +0100544 chunk_appendf(msg, "in function line %d", ar.linedefined);
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200545
546 else /* nothing left... */
547 chunk_appendf(msg, "?");
548
549
550 /* Display tailed call */
551 if (ar.istailcall)
552 chunk_appendf(msg, " ...");
553 }
554
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200555 return msg->area;
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200556}
557
558
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100559/* This function check the number of arguments available in the
560 * stack. If the number of arguments available is not the same
Ilya Shipitsinc02a23f2020-05-06 00:53:22 +0500561 * then <nb> an error is thrown.
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100562 */
563__LJMP static inline void check_args(lua_State *L, int nb, char *fcn)
564{
565 if (lua_gettop(L) == nb)
566 return;
567 WILL_LJMP(luaL_error(L, "'%s' needs %d arguments", fcn, nb));
568}
569
Mark Lakes22154b42018-01-29 14:38:40 -0800570/* This function pushes an error string prefixed by the file name
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100571 * and the line number where the error is encountered.
572 */
573static int hlua_pusherror(lua_State *L, const char *fmt, ...)
574{
575 va_list argp;
576 va_start(argp, fmt);
577 luaL_where(L, 1);
578 lua_pushvfstring(L, fmt, argp);
579 va_end(argp);
580 lua_concat(L, 2);
581 return 1;
582}
583
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100584/* This functions is used with sample fetch and converters. It
585 * converts the HAProxy configuration argument in a lua stack
586 * values.
587 *
588 * It takes an array of "arg", and each entry of the array is
589 * converted and pushed in the LUA stack.
590 */
591static int hlua_arg2lua(lua_State *L, const struct arg *arg)
592{
593 switch (arg->type) {
594 case ARGT_SINT:
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100595 case ARGT_TIME:
596 case ARGT_SIZE:
Thierry FOURNIERf90838b2015-03-06 13:48:32 +0100597 lua_pushinteger(L, arg->data.sint);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100598 break;
599
600 case ARGT_STR:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200601 lua_pushlstring(L, arg->data.str.area, arg->data.str.data);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100602 break;
603
604 case ARGT_IPV4:
605 case ARGT_IPV6:
606 case ARGT_MSK4:
607 case ARGT_MSK6:
608 case ARGT_FE:
609 case ARGT_BE:
610 case ARGT_TAB:
611 case ARGT_SRV:
612 case ARGT_USR:
613 case ARGT_MAP:
614 default:
615 lua_pushnil(L);
616 break;
617 }
618 return 1;
619}
620
Ilya Shipitsinc02a23f2020-05-06 00:53:22 +0500621/* This function take one entry in an LUA stack at the index "ud",
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100622 * and try to convert it in an HAProxy argument entry. This is useful
Ilya Shipitsind4259502020-04-08 01:07:56 +0500623 * with sample fetch wrappers. The input arguments are given to the
624 * lua wrapper and converted as arg list by the function.
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100625 */
626static int hlua_lua2arg(lua_State *L, int ud, struct arg *arg)
627{
628 switch (lua_type(L, ud)) {
629
630 case LUA_TNUMBER:
631 case LUA_TBOOLEAN:
632 arg->type = ARGT_SINT;
633 arg->data.sint = lua_tointeger(L, ud);
634 break;
635
636 case LUA_TSTRING:
637 arg->type = ARGT_STR;
Tim Duesterhus2e89dec2019-09-29 23:03:08 +0200638 arg->data.str.area = (char *)lua_tolstring(L, ud, &arg->data.str.data);
Tim Duesterhus29d2e8a2019-09-29 23:03:07 +0200639 /* We don't know the actual size of the underlying allocation, so be conservative. */
Christopher Fauletfdea1b62020-08-06 08:29:18 +0200640 arg->data.str.size = arg->data.str.data+1; /* count the terminating null byte */
Tim Duesterhus29d2e8a2019-09-29 23:03:07 +0200641 arg->data.str.head = 0;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100642 break;
643
644 case LUA_TUSERDATA:
645 case LUA_TNIL:
646 case LUA_TTABLE:
647 case LUA_TFUNCTION:
648 case LUA_TTHREAD:
649 case LUA_TLIGHTUSERDATA:
650 arg->type = ARGT_SINT;
Thierry FOURNIERbf65cd42015-07-20 17:45:02 +0200651 arg->data.sint = 0;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100652 break;
653 }
654 return 1;
655}
656
657/* the following functions are used to convert a struct sample
658 * in Lua type. This useful to convert the return of the
Ilya Shipitsind4259502020-04-08 01:07:56 +0500659 * fetches or converters.
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100660 */
Willy Tarreau5eadada2015-03-10 17:28:54 +0100661static int hlua_smp2lua(lua_State *L, struct sample *smp)
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100662{
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200663 switch (smp->data.type) {
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100664 case SMP_T_SINT:
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100665 case SMP_T_BOOL:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200666 lua_pushinteger(L, smp->data.u.sint);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100667 break;
668
669 case SMP_T_BIN:
670 case SMP_T_STR:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200671 lua_pushlstring(L, smp->data.u.str.area, smp->data.u.str.data);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100672 break;
673
674 case SMP_T_METH:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200675 switch (smp->data.u.meth.meth) {
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100676 case HTTP_METH_OPTIONS: lua_pushstring(L, "OPTIONS"); break;
677 case HTTP_METH_GET: lua_pushstring(L, "GET"); break;
678 case HTTP_METH_HEAD: lua_pushstring(L, "HEAD"); break;
679 case HTTP_METH_POST: lua_pushstring(L, "POST"); break;
680 case HTTP_METH_PUT: lua_pushstring(L, "PUT"); break;
681 case HTTP_METH_DELETE: lua_pushstring(L, "DELETE"); break;
682 case HTTP_METH_TRACE: lua_pushstring(L, "TRACE"); break;
683 case HTTP_METH_CONNECT: lua_pushstring(L, "CONNECT"); break;
684 case HTTP_METH_OTHER:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200685 lua_pushlstring(L, smp->data.u.meth.str.area, smp->data.u.meth.str.data);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100686 break;
687 default:
688 lua_pushnil(L);
689 break;
690 }
691 break;
692
693 case SMP_T_IPV4:
694 case SMP_T_IPV6:
695 case SMP_T_ADDR: /* This type is never used to qualify a sample. */
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200696 if (sample_casts[smp->data.type][SMP_T_STR] &&
697 sample_casts[smp->data.type][SMP_T_STR](smp))
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200698 lua_pushlstring(L, smp->data.u.str.area, smp->data.u.str.data);
Willy Tarreau5eadada2015-03-10 17:28:54 +0100699 else
700 lua_pushnil(L);
701 break;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100702 default:
703 lua_pushnil(L);
704 break;
705 }
706 return 1;
707}
708
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100709/* the following functions are used to convert a struct sample
710 * in Lua strings. This is useful to convert the return of the
Ilya Shipitsind4259502020-04-08 01:07:56 +0500711 * fetches or converters.
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100712 */
713static int hlua_smp2lua_str(lua_State *L, struct sample *smp)
714{
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200715 switch (smp->data.type) {
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100716
717 case SMP_T_BIN:
718 case SMP_T_STR:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200719 lua_pushlstring(L, smp->data.u.str.area, smp->data.u.str.data);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100720 break;
721
722 case SMP_T_METH:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200723 switch (smp->data.u.meth.meth) {
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100724 case HTTP_METH_OPTIONS: lua_pushstring(L, "OPTIONS"); break;
725 case HTTP_METH_GET: lua_pushstring(L, "GET"); break;
726 case HTTP_METH_HEAD: lua_pushstring(L, "HEAD"); break;
727 case HTTP_METH_POST: lua_pushstring(L, "POST"); break;
728 case HTTP_METH_PUT: lua_pushstring(L, "PUT"); break;
729 case HTTP_METH_DELETE: lua_pushstring(L, "DELETE"); break;
730 case HTTP_METH_TRACE: lua_pushstring(L, "TRACE"); break;
731 case HTTP_METH_CONNECT: lua_pushstring(L, "CONNECT"); break;
732 case HTTP_METH_OTHER:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200733 lua_pushlstring(L, smp->data.u.meth.str.area, smp->data.u.meth.str.data);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100734 break;
735 default:
736 lua_pushstring(L, "");
737 break;
738 }
739 break;
740
741 case SMP_T_SINT:
742 case SMP_T_BOOL:
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100743 case SMP_T_IPV4:
744 case SMP_T_IPV6:
745 case SMP_T_ADDR: /* This type is never used to qualify a sample. */
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200746 if (sample_casts[smp->data.type][SMP_T_STR] &&
747 sample_casts[smp->data.type][SMP_T_STR](smp))
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200748 lua_pushlstring(L, smp->data.u.str.area, smp->data.u.str.data);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100749 else
750 lua_pushstring(L, "");
751 break;
752 default:
753 lua_pushstring(L, "");
754 break;
755 }
756 return 1;
757}
758
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100759/* the following functions are used to convert an Lua type in a
760 * struct sample. This is useful to provide data from a converter
761 * to the LUA code.
762 */
763static int hlua_lua2smp(lua_State *L, int ud, struct sample *smp)
764{
765 switch (lua_type(L, ud)) {
766
767 case LUA_TNUMBER:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200768 smp->data.type = SMP_T_SINT;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200769 smp->data.u.sint = lua_tointeger(L, ud);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100770 break;
771
772
773 case LUA_TBOOLEAN:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200774 smp->data.type = SMP_T_BOOL;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200775 smp->data.u.sint = lua_toboolean(L, ud);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100776 break;
777
778 case LUA_TSTRING:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200779 smp->data.type = SMP_T_STR;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100780 smp->flags |= SMP_F_CONST;
Tim Duesterhus2e89dec2019-09-29 23:03:08 +0200781 smp->data.u.str.area = (char *)lua_tolstring(L, ud, &smp->data.u.str.data);
Tim Duesterhus29d2e8a2019-09-29 23:03:07 +0200782 /* We don't know the actual size of the underlying allocation, so be conservative. */
Christopher Fauletfdea1b62020-08-06 08:29:18 +0200783 smp->data.u.str.size = smp->data.u.str.data+1; /* count the terminating null byte */
Tim Duesterhus29d2e8a2019-09-29 23:03:07 +0200784 smp->data.u.str.head = 0;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100785 break;
786
787 case LUA_TUSERDATA:
788 case LUA_TNIL:
789 case LUA_TTABLE:
790 case LUA_TFUNCTION:
791 case LUA_TTHREAD:
792 case LUA_TLIGHTUSERDATA:
Thierry FOURNIER93405e12015-08-26 14:19:03 +0200793 case LUA_TNONE:
794 default:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200795 smp->data.type = SMP_T_BOOL;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200796 smp->data.u.sint = 0;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100797 break;
798 }
799 return 1;
800}
801
Ilya Shipitsind4259502020-04-08 01:07:56 +0500802/* This function check the "argp" built by another conversion function
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -0800803 * is in accord with the expected argp defined by the "mask". The function
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100804 * returns true or false. It can be adjust the types if there compatibles.
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100805 *
Ilya Shipitsinc02a23f2020-05-06 00:53:22 +0500806 * This function assumes that the argp argument contains ARGM_NBARGS + 1
Willy Tarreauee0d7272021-07-16 10:26:56 +0200807 * entries and that there is at least one stop at the last position.
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100808 */
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100809__LJMP int hlua_lua2arg_check(lua_State *L, int first, struct arg *argp,
David Carlier0c437f42016-04-27 16:21:56 +0100810 uint64_t mask, struct proxy *p)
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100811{
812 int min_arg;
Willy Tarreauee0d7272021-07-16 10:26:56 +0200813 int idx;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100814 struct proxy *px;
Christopher Fauletd25d9262020-08-06 11:04:46 +0200815 struct userlist *ul;
Christopher Fauletfd2e9062020-08-06 11:10:57 +0200816 struct my_regex *reg;
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200817 const char *msg = NULL;
Christopher Fauletfd2e9062020-08-06 11:10:57 +0200818 char *sname, *pname, *err = NULL;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100819
820 idx = 0;
821 min_arg = ARGM(mask);
822 mask >>= ARGM_BITS;
823
824 while (1) {
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200825 struct buffer tmp = BUF_NULL;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100826
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100827 /* Check for mandatory arguments. */
828 if (argp[idx].type == ARGT_STOP) {
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100829 if (idx < min_arg) {
830
831 /* If miss other argument than the first one, we return an error. */
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200832 if (idx > 0) {
833 msg = "Mandatory argument expected";
834 goto error;
835 }
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100836
837 /* If first argument have a certain type, some default values
838 * may be used. See the function smp_resolve_args().
839 */
840 switch (mask & ARGT_MASK) {
841
842 case ARGT_FE:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200843 if (!(p->cap & PR_CAP_FE)) {
844 msg = "Mandatory argument expected";
845 goto error;
846 }
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100847 argp[idx].data.prx = p;
848 argp[idx].type = ARGT_FE;
849 argp[idx+1].type = ARGT_STOP;
850 break;
851
852 case ARGT_BE:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200853 if (!(p->cap & PR_CAP_BE)) {
854 msg = "Mandatory argument expected";
855 goto error;
856 }
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100857 argp[idx].data.prx = p;
858 argp[idx].type = ARGT_BE;
859 argp[idx+1].type = ARGT_STOP;
860 break;
861
862 case ARGT_TAB:
863 argp[idx].data.prx = p;
864 argp[idx].type = ARGT_TAB;
865 argp[idx+1].type = ARGT_STOP;
866 break;
867
868 default:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200869 msg = "Mandatory argument expected";
870 goto error;
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100871 break;
872 }
873 }
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200874 break;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100875 }
876
Ilya Shipitsin856aabc2020-04-16 23:51:34 +0500877 /* Check for exceed the number of required argument. */
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100878 if ((mask & ARGT_MASK) == ARGT_STOP &&
879 argp[idx].type != ARGT_STOP) {
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200880 msg = "Last argument expected";
881 goto error;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100882 }
883
884 if ((mask & ARGT_MASK) == ARGT_STOP &&
885 argp[idx].type == ARGT_STOP) {
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200886 break;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100887 }
888
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200889 /* Convert some argument types. All string in argp[] are for not
890 * duplicated yet.
891 */
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100892 switch (mask & ARGT_MASK) {
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100893 case ARGT_SINT:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200894 if (argp[idx].type != ARGT_SINT) {
895 msg = "integer expected";
896 goto error;
897 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100898 argp[idx].type = ARGT_SINT;
899 break;
900
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100901 case ARGT_TIME:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200902 if (argp[idx].type != ARGT_SINT) {
903 msg = "integer expected";
904 goto error;
905 }
Thierry FOURNIER29176f32015-07-07 00:41:29 +0200906 argp[idx].type = ARGT_TIME;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100907 break;
908
909 case ARGT_SIZE:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200910 if (argp[idx].type != ARGT_SINT) {
911 msg = "integer expected";
912 goto error;
913 }
Thierry FOURNIER29176f32015-07-07 00:41:29 +0200914 argp[idx].type = ARGT_SIZE;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100915 break;
916
917 case ARGT_FE:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200918 if (argp[idx].type != ARGT_STR) {
919 msg = "string expected";
920 goto error;
921 }
Christopher Fauletfdea1b62020-08-06 08:29:18 +0200922 argp[idx].data.prx = proxy_fe_by_name(argp[idx].data.str.area);
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200923 if (!argp[idx].data.prx) {
924 msg = "frontend doesn't exist";
925 goto error;
926 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100927 argp[idx].type = ARGT_FE;
928 break;
929
930 case ARGT_BE:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200931 if (argp[idx].type != ARGT_STR) {
932 msg = "string expected";
933 goto error;
934 }
Christopher Fauletfdea1b62020-08-06 08:29:18 +0200935 argp[idx].data.prx = proxy_be_by_name(argp[idx].data.str.area);
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200936 if (!argp[idx].data.prx) {
937 msg = "backend doesn't exist";
938 goto error;
939 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100940 argp[idx].type = ARGT_BE;
941 break;
942
943 case ARGT_TAB:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200944 if (argp[idx].type != ARGT_STR) {
945 msg = "string expected";
946 goto error;
947 }
Christopher Fauletfdea1b62020-08-06 08:29:18 +0200948 argp[idx].data.t = stktable_find_by_name(argp[idx].data.str.area);
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200949 if (!argp[idx].data.t) {
950 msg = "table doesn't exist";
951 goto error;
952 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100953 argp[idx].type = ARGT_TAB;
954 break;
955
956 case ARGT_SRV:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200957 if (argp[idx].type != ARGT_STR) {
958 msg = "string expected";
959 goto error;
960 }
Christopher Fauletfdea1b62020-08-06 08:29:18 +0200961 sname = strrchr(argp[idx].data.str.area, '/');
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100962 if (sname) {
963 *sname++ = '\0';
Christopher Fauletfdea1b62020-08-06 08:29:18 +0200964 pname = argp[idx].data.str.area;
Willy Tarreau9e0bb102015-05-26 11:24:42 +0200965 px = proxy_be_by_name(pname);
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200966 if (!px) {
967 msg = "backend doesn't exist";
968 goto error;
969 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100970 }
971 else {
Christopher Fauletfdea1b62020-08-06 08:29:18 +0200972 sname = argp[idx].data.str.area;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100973 px = p;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100974 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100975 argp[idx].data.srv = findserver(px, sname);
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200976 if (!argp[idx].data.srv) {
977 msg = "server doesn't exist";
978 goto error;
979 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100980 argp[idx].type = ARGT_SRV;
981 break;
982
983 case ARGT_IPV4:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200984 if (argp[idx].type != ARGT_STR) {
985 msg = "string expected";
986 goto error;
987 }
988 if (inet_pton(AF_INET, argp[idx].data.str.area, &argp[idx].data.ipv4)) {
989 msg = "invalid IPv4 address";
990 goto error;
991 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100992 argp[idx].type = ARGT_IPV4;
993 break;
994
995 case ARGT_MSK4:
Christopher Faulete663a6e2020-08-07 09:11:22 +0200996 if (argp[idx].type == ARGT_SINT)
997 len2mask4(argp[idx].data.sint, &argp[idx].data.ipv4);
998 else if (argp[idx].type == ARGT_STR) {
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200999 if (!str2mask(argp[idx].data.str.area, &argp[idx].data.ipv4)) {
1000 msg = "invalid IPv4 mask";
1001 goto error;
1002 }
1003 }
1004 else {
1005 msg = "integer or string expected";
1006 goto error;
Christopher Faulete663a6e2020-08-07 09:11:22 +02001007 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001008 argp[idx].type = ARGT_MSK4;
1009 break;
1010
1011 case ARGT_IPV6:
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001012 if (argp[idx].type != ARGT_STR) {
1013 msg = "string expected";
1014 goto error;
1015 }
1016 if (inet_pton(AF_INET6, argp[idx].data.str.area, &argp[idx].data.ipv6)) {
1017 msg = "invalid IPv6 address";
1018 goto error;
1019 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001020 argp[idx].type = ARGT_IPV6;
1021 break;
1022
1023 case ARGT_MSK6:
Christopher Faulete663a6e2020-08-07 09:11:22 +02001024 if (argp[idx].type == ARGT_SINT)
1025 len2mask6(argp[idx].data.sint, &argp[idx].data.ipv6);
1026 else if (argp[idx].type == ARGT_STR) {
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001027 if (!str2mask6(argp[idx].data.str.area, &argp[idx].data.ipv6)) {
1028 msg = "invalid IPv6 mask";
1029 goto error;
1030 }
1031 }
1032 else {
1033 msg = "integer or string expected";
1034 goto error;
Christopher Faulete663a6e2020-08-07 09:11:22 +02001035 }
Tim Duesterhusb814da62018-01-25 16:24:50 +01001036 argp[idx].type = ARGT_MSK6;
1037 break;
1038
Christopher Fauletfd2e9062020-08-06 11:10:57 +02001039 case ARGT_REG:
1040 if (argp[idx].type != ARGT_STR) {
1041 msg = "string expected";
1042 goto error;
1043 }
1044 reg = regex_comp(argp[idx].data.str.area, !(argp[idx].type_flags & ARGF_REG_ICASE), 1, &err);
1045 if (!reg) {
1046 msg = lua_pushfstring(L, "error compiling regex '%s' : '%s'",
1047 argp[idx].data.str.area, err);
1048 free(err);
1049 goto error;
1050 }
1051 argp[idx].type = ARGT_REG;
1052 argp[idx].data.reg = reg;
1053 break;
1054
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001055 case ARGT_USR:
Christopher Fauletd25d9262020-08-06 11:04:46 +02001056 if (argp[idx].type != ARGT_STR) {
1057 msg = "string expected";
1058 goto error;
1059 }
1060 if (p->uri_auth && p->uri_auth->userlist &&
Tim Duesterhuse5ff1412021-01-02 22:31:53 +01001061 strcmp(p->uri_auth->userlist->name, argp[idx].data.str.area) == 0)
Christopher Fauletd25d9262020-08-06 11:04:46 +02001062 ul = p->uri_auth->userlist;
1063 else
1064 ul = auth_find_userlist(argp[idx].data.str.area);
1065
1066 if (!ul) {
1067 msg = lua_pushfstring(L, "unable to find userlist '%s'", argp[idx].data.str.area);
1068 goto error;
1069 }
1070 argp[idx].type = ARGT_USR;
1071 argp[idx].data.usr = ul;
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001072 break;
1073
1074 case ARGT_STR:
1075 if (!chunk_dup(&tmp, &argp[idx].data.str)) {
1076 msg = "unable to duplicate string arg";
1077 goto error;
1078 }
1079 argp[idx].data.str = tmp;
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001080 break;
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001081
Christopher Fauletd25d9262020-08-06 11:04:46 +02001082 case ARGT_MAP:
Christopher Fauletd25d9262020-08-06 11:04:46 +02001083 msg = "type not yet supported";
1084 goto error;
1085 break;
1086
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001087 }
1088
1089 /* Check for type of argument. */
1090 if ((mask & ARGT_MASK) != argp[idx].type) {
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001091 msg = lua_pushfstring(L, "'%s' expected, got '%s'",
1092 arg_type_names[(mask & ARGT_MASK)],
1093 arg_type_names[argp[idx].type & ARGT_MASK]);
1094 goto error;
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001095 }
1096
1097 /* Next argument. */
1098 mask >>= ARGT_BITS;
1099 idx++;
1100 }
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001101 return 0;
1102
1103 error:
Willy Tarreauee0d7272021-07-16 10:26:56 +02001104 free_args(argp);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001105 WILL_LJMP(luaL_argerror(L, first + idx, msg));
1106 return 0; /* Never reached */
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001107}
1108
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001109/*
Ilya Shipitsinc02a23f2020-05-06 00:53:22 +05001110 * The following functions are used to make correspondence between the the
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001111 * executed lua pointer and the "struct hlua *" that contain the context.
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001112 *
1113 * - hlua_gethlua : return the hlua context associated with an lua_State.
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001114 * - hlua_sethlua : create the association between hlua context and lua_state.
1115 */
1116static inline struct hlua *hlua_gethlua(lua_State *L)
1117{
Thierry FOURNIER38c5fd62015-03-10 02:40:29 +01001118 struct hlua **hlua = lua_getextraspace(L);
1119 return *hlua;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001120}
1121static inline void hlua_sethlua(struct hlua *hlua)
1122{
Thierry FOURNIER38c5fd62015-03-10 02:40:29 +01001123 struct hlua **hlua_store = lua_getextraspace(hlua->T);
1124 *hlua_store = hlua;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001125}
1126
Willy Tarreau0b7b6392022-06-19 17:39:33 +02001127/* Will return a non-NULL string indicating the Lua call trace if the caller
1128 * currently is executing from within a Lua function. One line per entry will
1129 * be emitted, and each extra line will be prefixed with <pfx>. If a current
1130 * Lua function is not detected, NULL is returned.
1131 */
1132const char *hlua_show_current_location(const char *pfx)
1133{
1134 lua_State *L;
1135 lua_Debug ar;
1136
1137 /* global or per-thread stack initializing ? */
1138 if (hlua_state_id != -1 && (L = hlua_states[hlua_state_id]) && lua_getstack(L, 0, &ar))
1139 return hlua_traceback(L, pfx);
1140
1141 /* per-thread stack running ? */
1142 if (hlua_states[tid + 1] && (L = hlua_states[tid + 1]) && lua_getstack(L, 0, &ar))
1143 return hlua_traceback(L, pfx);
1144
1145 /* global stack running ? */
1146 if (hlua_states[0] && (L = hlua_states[0]) && lua_getstack(L, 0, &ar))
1147 return hlua_traceback(L, pfx);
1148
1149 return NULL;
1150}
1151
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01001152/* This function is used to send logs. It try to send on screen (stderr)
1153 * and on the default syslog server.
1154 */
1155static inline void hlua_sendlog(struct proxy *px, int level, const char *msg)
1156{
1157 struct tm tm;
1158 char *p;
1159
1160 /* Cleanup the log message. */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001161 p = trash.area;
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01001162 for (; *msg != '\0'; msg++, p++) {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001163 if (p >= trash.area + trash.size - 1) {
Thierry FOURNIERccf00632015-09-16 12:47:03 +02001164 /* Break the message if exceed the buffer size. */
1165 *(p-4) = ' ';
1166 *(p-3) = '.';
1167 *(p-2) = '.';
1168 *(p-1) = '.';
1169 break;
1170 }
Willy Tarreau90807112020-02-25 08:16:33 +01001171 if (isprint((unsigned char)*msg))
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01001172 *p = *msg;
1173 else
1174 *p = '.';
1175 }
1176 *p = '\0';
1177
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001178 send_log(px, level, "%s\n", trash.area);
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01001179 if (!(global.mode & MODE_QUIET) || (global.mode & (MODE_VERBOSE | MODE_STARTING))) {
Christopher Fauletf98d8212020-10-02 18:13:52 +02001180 if (level == LOG_DEBUG && !(global.mode & MODE_DEBUG))
1181 return;
1182
Willy Tarreaua678b432015-08-28 10:14:59 +02001183 get_localtime(date.tv_sec, &tm);
1184 fprintf(stderr, "[%s] %03d/%02d%02d%02d (%d) : %s\n",
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01001185 log_levels[level], tm.tm_yday, tm.tm_hour, tm.tm_min, tm.tm_sec,
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001186 (int)getpid(), trash.area);
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01001187 fflush(stderr);
1188 }
1189}
1190
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001191/* This function just ensure that the yield will be always
1192 * returned with a timeout and permit to set some flags
1193 */
1194__LJMP void hlua_yieldk(lua_State *L, int nresults, int ctx,
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001195 lua_KFunction k, int timeout, unsigned int flags)
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001196{
Thierry Fournier4234dbd2020-11-28 13:18:23 +01001197 struct hlua *hlua;
1198
1199 /* Get hlua struct, or NULL if we execute from main lua state */
1200 hlua = hlua_gethlua(L);
1201 if (!hlua) {
1202 return;
1203 }
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001204
1205 /* Set the wake timeout. If timeout is required, we set
1206 * the expiration time.
1207 */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001208 hlua->wake_time = timeout;
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001209
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01001210 hlua->flags |= flags;
1211
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001212 /* Process the yield. */
Willy Tarreau9635e032018-10-16 17:52:55 +02001213 MAY_LJMP(lua_yieldk(L, nresults, ctx, k));
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001214}
1215
Willy Tarreau87b09662015-04-03 00:22:06 +02001216/* This function initialises the Lua environment stored in the stream.
1217 * It must be called at the start of the stream. This function creates
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001218 * an LUA coroutine. It can not be use to crete the main LUA context.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02001219 *
1220 * This function is particular. it initialises a new Lua thread. If the
1221 * initialisation fails (example: out of memory error), the lua function
1222 * throws an error (longjmp).
1223 *
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +01001224 * In some case (at least one), this function can be called from safe
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001225 * environment, so we must not initialise it. While the support of
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +01001226 * threads appear, the safe environment set a lock to ensure only one
1227 * Lua execution at a time. If we initialize safe environment in another
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001228 * safe environment, we have a dead lock.
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +01001229 *
1230 * set "already_safe" true if the context is initialized form safe
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001231 * Lua function.
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +01001232 *
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001233 * This function manipulates two Lua stacks: the main and the thread. Only
Thierry FOURNIERbabae282015-09-17 11:36:37 +02001234 * the main stack can fail. The thread is not manipulated. This function
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001235 * MUST NOT manipulate the created thread stack state, because it is not
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001236 * protected against errors thrown by the thread stack.
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001237 */
Thierry Fournier021d9862020-11-28 23:42:03 +01001238int hlua_ctx_init(struct hlua *lua, int state_id, struct task *task, int already_safe)
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001239{
1240 lua->Mref = LUA_REFNIL;
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001241 lua->flags = 0;
Willy Tarreauf31af932020-01-14 09:59:38 +01001242 lua->gc_count = 0;
Christopher Fauletbc275a92020-02-26 14:55:16 +01001243 lua->wake_time = TICK_ETERNITY;
Thierry Fournier021d9862020-11-28 23:42:03 +01001244 lua->state_id = state_id;
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01001245 LIST_INIT(&lua->com);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001246 if (!already_safe) {
1247 if (!SET_SAFE_LJMP_PARENT(lua)) {
1248 lua->Tref = LUA_REFNIL;
1249 return 0;
1250 }
1251 }
Thierry Fournier021d9862020-11-28 23:42:03 +01001252 lua->T = lua_newthread(hlua_states[state_id]);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001253 if (!lua->T) {
1254 lua->Tref = LUA_REFNIL;
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +01001255 if (!already_safe)
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001256 RESET_SAFE_LJMP_PARENT(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001257 return 0;
1258 }
1259 hlua_sethlua(lua);
Thierry Fournier021d9862020-11-28 23:42:03 +01001260 lua->Tref = luaL_ref(hlua_states[state_id], LUA_REGISTRYINDEX);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001261 lua->task = task;
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +01001262 if (!already_safe)
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001263 RESET_SAFE_LJMP_PARENT(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001264 return 1;
1265}
1266
Willy Tarreau87b09662015-04-03 00:22:06 +02001267/* Used to destroy the Lua coroutine when the attached stream or task
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001268 * is destroyed. The destroy also the memory context. The struct "lua"
1269 * is not freed.
1270 */
1271void hlua_ctx_destroy(struct hlua *lua)
1272{
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01001273 if (!lua)
Thierry FOURNIERa718b292015-03-04 16:48:34 +01001274 return;
1275
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01001276 if (!lua->T)
1277 goto end;
1278
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01001279 /* Purge all the pending signals. */
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001280 notification_purge(&lua->com);
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01001281
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001282 if (!SET_SAFE_LJMP(lua))
Thierry FOURNIER75d02082017-07-12 13:41:33 +02001283 return;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001284 luaL_unref(lua->T, LUA_REGISTRYINDEX, lua->Mref);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001285 RESET_SAFE_LJMP(lua);
Thierry FOURNIER5a50a852015-09-23 16:59:28 +02001286
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001287 if (!SET_SAFE_LJMP_PARENT(lua))
Thierry FOURNIER75d02082017-07-12 13:41:33 +02001288 return;
Thierry Fournier021d9862020-11-28 23:42:03 +01001289 luaL_unref(hlua_states[lua->state_id], LUA_REGISTRYINDEX, lua->Tref);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001290 RESET_SAFE_LJMP_PARENT(lua);
Thierry FOURNIER5a50a852015-09-23 16:59:28 +02001291 /* Forces a garbage collecting process. If the Lua program is finished
1292 * without error, we run the GC on the thread pointer. Its freed all
1293 * the unused memory.
1294 * If the thread is finnish with an error or is currently yielded,
1295 * it seems that the GC applied on the thread doesn't clean anything,
1296 * so e run the GC on the main thread.
1297 * NOTE: maybe this action locks all the Lua threads untiml the en of
1298 * the garbage collection.
1299 */
Willy Tarreauf31af932020-01-14 09:59:38 +01001300 if (lua->gc_count) {
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001301 if (!SET_SAFE_LJMP_PARENT(lua))
Thierry FOURNIER75d02082017-07-12 13:41:33 +02001302 return;
Thierry Fournier021d9862020-11-28 23:42:03 +01001303 lua_gc(hlua_states[lua->state_id], LUA_GCCOLLECT, 0);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001304 RESET_SAFE_LJMP_PARENT(lua);
Thierry FOURNIER7c39ab42015-09-27 22:53:33 +02001305 }
Thierry FOURNIER5a50a852015-09-23 16:59:28 +02001306
Thierry FOURNIERa7b536b2015-09-21 22:50:24 +02001307 lua->T = NULL;
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01001308
1309end:
Willy Tarreaubafbe012017-11-24 17:34:44 +01001310 pool_free(pool_head_hlua, lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001311}
1312
1313/* This function is used to restore the Lua context when a coroutine
1314 * fails. This function copy the common memory between old coroutine
1315 * and the new coroutine. The old coroutine is destroyed, and its
1316 * replaced by the new coroutine.
1317 * If the flag "keep_msg" is set, the last entry of the old is assumed
1318 * as string error message and it is copied in the new stack.
1319 */
1320static int hlua_ctx_renew(struct hlua *lua, int keep_msg)
1321{
1322 lua_State *T;
1323 int new_ref;
1324
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001325 /* New Lua coroutine. */
Thierry Fournier021d9862020-11-28 23:42:03 +01001326 T = lua_newthread(hlua_states[lua->state_id]);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001327 if (!T)
1328 return 0;
1329
1330 /* Copy last error message. */
1331 if (keep_msg)
1332 lua_xmove(lua->T, T, 1);
1333
1334 /* Copy data between the coroutines. */
1335 lua_rawgeti(lua->T, LUA_REGISTRYINDEX, lua->Mref);
1336 lua_xmove(lua->T, T, 1);
Ilya Shipitsin46a030c2020-07-05 16:36:08 +05001337 new_ref = luaL_ref(T, LUA_REGISTRYINDEX); /* Value popped. */
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001338
1339 /* Destroy old data. */
1340 luaL_unref(lua->T, LUA_REGISTRYINDEX, lua->Mref);
1341
1342 /* The thread is garbage collected by Lua. */
Thierry Fournier021d9862020-11-28 23:42:03 +01001343 luaL_unref(hlua_states[lua->state_id], LUA_REGISTRYINDEX, lua->Tref);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001344
1345 /* Fill the struct with the new coroutine values. */
1346 lua->Mref = new_ref;
1347 lua->T = T;
Thierry Fournier021d9862020-11-28 23:42:03 +01001348 lua->Tref = luaL_ref(hlua_states[lua->state_id], LUA_REGISTRYINDEX);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001349
1350 /* Set context. */
1351 hlua_sethlua(lua);
1352
1353 return 1;
1354}
1355
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001356void hlua_hook(lua_State *L, lua_Debug *ar)
1357{
Thierry Fournier4234dbd2020-11-28 13:18:23 +01001358 struct hlua *hlua;
1359
1360 /* Get hlua struct, or NULL if we execute from main lua state */
1361 hlua = hlua_gethlua(L);
1362 if (!hlua)
1363 return;
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001364
1365 /* Lua cannot yield when its returning from a function,
1366 * so, we can fix the interrupt hook to 1 instruction,
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001367 * expecting that the function is finished.
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001368 */
1369 if (lua_gethookmask(L) & LUA_MASKRET) {
1370 lua_sethook(hlua->T, hlua_hook, LUA_MASKCOUNT, 1);
1371 return;
1372 }
1373
1374 /* restore the interrupt condition. */
1375 lua_sethook(hlua->T, hlua_hook, LUA_MASKCOUNT, hlua_nb_instruction);
1376
1377 /* If we interrupt the Lua processing in yieldable state, we yield.
1378 * If the state is not yieldable, trying yield causes an error.
1379 */
1380 if (lua_isyieldable(L))
Willy Tarreau9635e032018-10-16 17:52:55 +02001381 MAY_LJMP(hlua_yieldk(L, 0, 0, NULL, TICK_ETERNITY, HLUA_CTRLYIELD));
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001382
Thierry FOURNIERa85cfb12015-03-13 14:50:06 +01001383 /* If we cannot yield, update the clock and check the timeout. */
Willy Tarreau55542642021-10-08 09:33:24 +02001384 clock_update_date(0, 1);
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001385 hlua->run_time += now_ms - hlua->start_time;
1386 if (hlua->max_time && hlua->run_time >= hlua->max_time) {
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001387 lua_pushfstring(L, "execution timeout");
1388 WILL_LJMP(lua_error(L));
1389 }
1390
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001391 /* Update the start time. */
1392 hlua->start_time = now_ms;
1393
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001394 /* Try to interrupt the process at the end of the current
1395 * unyieldable function.
1396 */
1397 lua_sethook(hlua->T, hlua_hook, LUA_MASKRET|LUA_MASKCOUNT, hlua_nb_instruction);
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001398}
1399
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001400/* This function start or resumes the Lua stack execution. If the flag
1401 * "yield_allowed" if no set and the LUA stack execution returns a yield
1402 * The function return an error.
1403 *
1404 * The function can returns 4 values:
1405 * - HLUA_E_OK : The execution is terminated without any errors.
1406 * - HLUA_E_AGAIN : The execution must continue at the next associated
1407 * task wakeup.
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001408 * - HLUA_E_ERRMSG : An error has occurred, an error message is set in
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001409 * the top of the stack.
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001410 * - HLUA_E_ERR : An error has occurred without error message.
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001411 *
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001412 * If an error occurred, the stack is renewed and it is ready to run new
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001413 * LUA code.
1414 */
1415static enum hlua_exec hlua_ctx_resume(struct hlua *lua, int yield_allowed)
1416{
Christopher Faulet08ed98f2020-07-28 10:33:25 +02001417#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM >= 504
1418 int nres;
1419#endif
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001420 int ret;
1421 const char *msg;
Thierry FOURNIERfc044c92018-06-07 14:40:48 +02001422 const char *trace;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001423
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001424 /* Initialise run time counter. */
1425 if (!HLUA_IS_RUNNING(lua))
1426 lua->run_time = 0;
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001427
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +02001428 /* Lock the whole Lua execution. This lock must be before the
1429 * label "resume_execution".
1430 */
Thierry Fournier021d9862020-11-28 23:42:03 +01001431 if (lua->state_id == 0)
Willy Tarreau1e7bef12021-08-20 15:47:25 +02001432 lua_take_global_lock();
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +02001433
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001434resume_execution:
1435
1436 /* This hook interrupts the Lua processing each 'hlua_nb_instruction'
1437 * instructions. it is used for preventing infinite loops.
1438 */
1439 lua_sethook(lua->T, hlua_hook, LUA_MASKCOUNT, hlua_nb_instruction);
1440
Thierry FOURNIER1bfc09b2015-03-05 17:10:14 +01001441 /* Remove all flags except the running flags. */
Thierry FOURNIER2f3867f2015-09-28 01:02:01 +02001442 HLUA_SET_RUN(lua);
1443 HLUA_CLR_CTRLYIELD(lua);
1444 HLUA_CLR_WAKERESWR(lua);
1445 HLUA_CLR_WAKEREQWR(lua);
Christopher Faulet1f43a342021-08-04 17:58:21 +02001446 HLUA_CLR_NOYIELD(lua);
1447 if (!yield_allowed)
1448 HLUA_SET_NOYIELD(lua);
Thierry FOURNIER1bfc09b2015-03-05 17:10:14 +01001449
Christopher Fauletbc275a92020-02-26 14:55:16 +01001450 /* Update the start time and reset wake_time. */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001451 lua->start_time = now_ms;
Christopher Fauletbc275a92020-02-26 14:55:16 +01001452 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001453
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001454 /* Call the function. */
Christopher Faulet08ed98f2020-07-28 10:33:25 +02001455#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM >= 504
Thierry Fournier021d9862020-11-28 23:42:03 +01001456 ret = lua_resume(lua->T, hlua_states[lua->state_id], lua->nargs, &nres);
Christopher Faulet08ed98f2020-07-28 10:33:25 +02001457#else
Thierry Fournier021d9862020-11-28 23:42:03 +01001458 ret = lua_resume(lua->T, hlua_states[lua->state_id], lua->nargs);
Christopher Faulet08ed98f2020-07-28 10:33:25 +02001459#endif
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001460 switch (ret) {
1461
1462 case LUA_OK:
1463 ret = HLUA_E_OK;
1464 break;
1465
1466 case LUA_YIELD:
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001467 /* Check if the execution timeout is expired. It it is the case, we
1468 * break the Lua execution.
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001469 */
Willy Tarreau55542642021-10-08 09:33:24 +02001470 clock_update_date(0, 1);
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001471 lua->run_time += now_ms - lua->start_time;
1472 if (lua->max_time && lua->run_time > lua->max_time) {
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001473 lua_settop(lua->T, 0); /* Empty the stack. */
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001474 ret = HLUA_E_ETMOUT;
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001475 break;
1476 }
1477 /* Process the forced yield. if the general yield is not allowed or
1478 * if no task were associated this the current Lua execution
1479 * coroutine, we resume the execution. Else we want to return in the
1480 * scheduler and we want to be waked up again, to continue the
1481 * current Lua execution. So we schedule our own task.
1482 */
1483 if (HLUA_IS_CTRLYIELDING(lua)) {
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001484 if (!yield_allowed || !lua->task)
1485 goto resume_execution;
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001486 task_wakeup(lua->task, TASK_WOKEN_MSG);
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001487 }
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001488 if (!yield_allowed) {
1489 lua_settop(lua->T, 0); /* Empty the stack. */
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001490 ret = HLUA_E_YIELD;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001491 break;
1492 }
1493 ret = HLUA_E_AGAIN;
1494 break;
1495
1496 case LUA_ERRRUN:
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001497
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001498 /* Special exit case. The traditional exit is returned as an error
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001499 * because the errors ares the only one mean to return immediately
1500 * from and lua execution.
1501 */
1502 if (lua->flags & HLUA_EXIT) {
1503 ret = HLUA_E_OK;
Christopher Faulet7716cdf2020-01-29 11:53:30 +01001504 hlua_ctx_renew(lua, 1);
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001505 break;
1506 }
1507
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001508 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001509 if (!lua_checkstack(lua->T, 1)) {
1510 ret = HLUA_E_ERR;
1511 break;
1512 }
1513 msg = lua_tostring(lua->T, -1);
1514 lua_settop(lua->T, 0); /* Empty the stack. */
1515 lua_pop(lua->T, 1);
Christopher Fauletd09cc512021-03-24 14:48:45 +01001516 trace = hlua_traceback(lua->T, ", ");
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001517 if (msg)
Thierry Fournier46278ff2020-11-29 11:48:12 +01001518 lua_pushfstring(lua->T, "[state-id %d] runtime error: %s from %s", lua->state_id, msg, trace);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001519 else
Thierry Fournier46278ff2020-11-29 11:48:12 +01001520 lua_pushfstring(lua->T, "[state-id %d] unknown runtime error from %s", lua->state_id, trace);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001521 ret = HLUA_E_ERRMSG;
1522 break;
1523
1524 case LUA_ERRMEM:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001525 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001526 lua_settop(lua->T, 0); /* Empty the stack. */
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001527 ret = HLUA_E_NOMEM;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001528 break;
1529
1530 case LUA_ERRERR:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001531 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001532 if (!lua_checkstack(lua->T, 1)) {
1533 ret = HLUA_E_ERR;
1534 break;
1535 }
1536 msg = lua_tostring(lua->T, -1);
1537 lua_settop(lua->T, 0); /* Empty the stack. */
1538 lua_pop(lua->T, 1);
1539 if (msg)
Thierry Fournier46278ff2020-11-29 11:48:12 +01001540 lua_pushfstring(lua->T, "[state-id %d] message handler error: %s", lua->state_id, msg);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001541 else
Thierry Fournier46278ff2020-11-29 11:48:12 +01001542 lua_pushfstring(lua->T, "[state-id %d] message handler error", lua->state_id);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001543 ret = HLUA_E_ERRMSG;
1544 break;
1545
1546 default:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001547 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001548 lua_settop(lua->T, 0); /* Empty the stack. */
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001549 ret = HLUA_E_ERR;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001550 break;
1551 }
1552
1553 switch (ret) {
1554 case HLUA_E_AGAIN:
1555 break;
1556
1557 case HLUA_E_ERRMSG:
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001558 notification_purge(&lua->com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001559 hlua_ctx_renew(lua, 1);
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001560 HLUA_CLR_RUN(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001561 break;
1562
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001563 case HLUA_E_ETMOUT:
1564 case HLUA_E_NOMEM:
1565 case HLUA_E_YIELD:
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001566 case HLUA_E_ERR:
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001567 HLUA_CLR_RUN(lua);
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001568 notification_purge(&lua->com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001569 hlua_ctx_renew(lua, 0);
1570 break;
1571
1572 case HLUA_E_OK:
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001573 HLUA_CLR_RUN(lua);
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001574 notification_purge(&lua->com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001575 break;
1576 }
1577
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +02001578 /* This is the main exit point, remove the Lua lock. */
Thierry Fournier021d9862020-11-28 23:42:03 +01001579 if (lua->state_id == 0)
Willy Tarreau1e7bef12021-08-20 15:47:25 +02001580 lua_drop_global_lock();
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +02001581
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001582 return ret;
1583}
1584
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001585/* This function exit the current code. */
1586__LJMP static int hlua_done(lua_State *L)
1587{
Thierry Fournier4234dbd2020-11-28 13:18:23 +01001588 struct hlua *hlua;
1589
1590 /* Get hlua struct, or NULL if we execute from main lua state */
1591 hlua = hlua_gethlua(L);
1592 if (!hlua)
1593 return 0;
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001594
1595 hlua->flags |= HLUA_EXIT;
1596 WILL_LJMP(lua_error(L));
1597
1598 return 0;
1599}
1600
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001601/* This function is an LUA binding. It provides a function
1602 * for deleting ACL from a referenced ACL file.
1603 */
1604__LJMP static int hlua_del_acl(lua_State *L)
1605{
1606 const char *name;
1607 const char *key;
1608 struct pat_ref *ref;
1609
1610 MAY_LJMP(check_args(L, 2, "del_acl"));
1611
1612 name = MAY_LJMP(luaL_checkstring(L, 1));
1613 key = MAY_LJMP(luaL_checkstring(L, 2));
1614
1615 ref = pat_ref_lookup(name);
1616 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001617 WILL_LJMP(luaL_error(L, "'del_acl': unknown acl file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001618
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001619 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001620 pat_ref_delete(ref, key);
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001621 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001622 return 0;
1623}
1624
1625/* This function is an LUA binding. It provides a function
1626 * for deleting map entry from a referenced map file.
1627 */
1628static int hlua_del_map(lua_State *L)
1629{
1630 const char *name;
1631 const char *key;
1632 struct pat_ref *ref;
1633
1634 MAY_LJMP(check_args(L, 2, "del_map"));
1635
1636 name = MAY_LJMP(luaL_checkstring(L, 1));
1637 key = MAY_LJMP(luaL_checkstring(L, 2));
1638
1639 ref = pat_ref_lookup(name);
1640 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001641 WILL_LJMP(luaL_error(L, "'del_map': unknown acl file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001642
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001643 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001644 pat_ref_delete(ref, key);
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001645 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001646 return 0;
1647}
1648
1649/* This function is an LUA binding. It provides a function
1650 * for adding ACL pattern from a referenced ACL file.
1651 */
1652static int hlua_add_acl(lua_State *L)
1653{
1654 const char *name;
1655 const char *key;
1656 struct pat_ref *ref;
1657
1658 MAY_LJMP(check_args(L, 2, "add_acl"));
1659
1660 name = MAY_LJMP(luaL_checkstring(L, 1));
1661 key = MAY_LJMP(luaL_checkstring(L, 2));
1662
1663 ref = pat_ref_lookup(name);
1664 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001665 WILL_LJMP(luaL_error(L, "'add_acl': unknown acl file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001666
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001667 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001668 if (pat_ref_find_elt(ref, key) == NULL)
1669 pat_ref_add(ref, key, NULL, NULL);
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001670 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001671 return 0;
1672}
1673
1674/* This function is an LUA binding. It provides a function
1675 * for setting map pattern and sample from a referenced map
1676 * file.
1677 */
1678static int hlua_set_map(lua_State *L)
1679{
1680 const char *name;
1681 const char *key;
1682 const char *value;
1683 struct pat_ref *ref;
1684
1685 MAY_LJMP(check_args(L, 3, "set_map"));
1686
1687 name = MAY_LJMP(luaL_checkstring(L, 1));
1688 key = MAY_LJMP(luaL_checkstring(L, 2));
1689 value = MAY_LJMP(luaL_checkstring(L, 3));
1690
1691 ref = pat_ref_lookup(name);
1692 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001693 WILL_LJMP(luaL_error(L, "'set_map': unknown map file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001694
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001695 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001696 if (pat_ref_find_elt(ref, key) != NULL)
1697 pat_ref_set(ref, key, value, NULL);
1698 else
1699 pat_ref_add(ref, key, value, NULL);
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001700 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001701 return 0;
1702}
1703
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01001704/* A class is a lot of memory that contain data. This data can be a table,
1705 * an integer or user data. This data is associated with a metatable. This
Ilya Shipitsinc02a23f2020-05-06 00:53:22 +05001706 * metatable have an original version registered in the global context with
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01001707 * the name of the object (_G[<name>] = <metable> ).
1708 *
1709 * A metable is a table that modify the standard behavior of a standard
1710 * access to the associated data. The entries of this new metatable are
1711 * defined as is:
1712 *
1713 * http://lua-users.org/wiki/MetatableEvents
1714 *
1715 * __index
1716 *
1717 * we access an absent field in a table, the result is nil. This is
1718 * true, but it is not the whole truth. Actually, such access triggers
1719 * the interpreter to look for an __index metamethod: If there is no
1720 * such method, as usually happens, then the access results in nil;
1721 * otherwise, the metamethod will provide the result.
1722 *
1723 * Control 'prototype' inheritance. When accessing "myTable[key]" and
1724 * the key does not appear in the table, but the metatable has an __index
1725 * property:
1726 *
1727 * - if the value is a function, the function is called, passing in the
1728 * table and the key; the return value of that function is returned as
1729 * the result.
1730 *
1731 * - if the value is another table, the value of the key in that table is
1732 * asked for and returned (and if it doesn't exist in that table, but that
1733 * table's metatable has an __index property, then it continues on up)
1734 *
1735 * - Use "rawget(myTable,key)" to skip this metamethod.
1736 *
1737 * http://www.lua.org/pil/13.4.1.html
1738 *
1739 * __newindex
1740 *
1741 * Like __index, but control property assignment.
1742 *
1743 * __mode - Control weak references. A string value with one or both
1744 * of the characters 'k' and 'v' which specifies that the the
1745 * keys and/or values in the table are weak references.
1746 *
1747 * __call - Treat a table like a function. When a table is followed by
1748 * parenthesis such as "myTable( 'foo' )" and the metatable has
1749 * a __call key pointing to a function, that function is invoked
1750 * (passing any specified arguments) and the return value is
1751 * returned.
1752 *
1753 * __metatable - Hide the metatable. When "getmetatable( myTable )" is
1754 * called, if the metatable for myTable has a __metatable
1755 * key, the value of that key is returned instead of the
1756 * actual metatable.
1757 *
1758 * __tostring - Control string representation. When the builtin
1759 * "tostring( myTable )" function is called, if the metatable
1760 * for myTable has a __tostring property set to a function,
1761 * that function is invoked (passing myTable to it) and the
1762 * return value is used as the string representation.
1763 *
1764 * __len - Control table length. When the table length is requested using
1765 * the length operator ( '#' ), if the metatable for myTable has
1766 * a __len key pointing to a function, that function is invoked
1767 * (passing myTable to it) and the return value used as the value
1768 * of "#myTable".
1769 *
1770 * __gc - Userdata finalizer code. When userdata is set to be garbage
1771 * collected, if the metatable has a __gc field pointing to a
1772 * function, that function is first invoked, passing the userdata
1773 * to it. The __gc metamethod is not called for tables.
1774 * (See http://lua-users.org/lists/lua-l/2006-11/msg00508.html)
1775 *
1776 * Special metamethods for redefining standard operators:
1777 * http://www.lua.org/pil/13.1.html
1778 *
1779 * __add "+"
1780 * __sub "-"
1781 * __mul "*"
1782 * __div "/"
1783 * __unm "!"
1784 * __pow "^"
1785 * __concat ".."
1786 *
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001787 * Special methods for redefining standard relations
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01001788 * http://www.lua.org/pil/13.2.html
1789 *
1790 * __eq "=="
1791 * __lt "<"
1792 * __le "<="
1793 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001794
1795/*
1796 *
1797 *
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001798 * Class Map
1799 *
1800 *
1801 */
1802
1803/* Returns a struct hlua_map if the stack entry "ud" is
1804 * a class session, otherwise it throws an error.
1805 */
1806__LJMP static struct map_descriptor *hlua_checkmap(lua_State *L, int ud)
1807{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02001808 return MAY_LJMP(hlua_checkudata(L, ud, class_map_ref));
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001809}
1810
1811/* This function is the map constructor. It don't need
1812 * the class Map object. It creates and return a new Map
1813 * object. It must be called only during "body" or "init"
1814 * context because it process some filesystem accesses.
1815 */
1816__LJMP static int hlua_map_new(struct lua_State *L)
1817{
1818 const char *fn;
1819 int match = PAT_MATCH_STR;
1820 struct sample_conv conv;
1821 const char *file = "";
1822 int line = 0;
1823 lua_Debug ar;
1824 char *err = NULL;
1825 struct arg args[2];
1826
1827 if (lua_gettop(L) < 1 || lua_gettop(L) > 2)
1828 WILL_LJMP(luaL_error(L, "'new' needs at least 1 argument."));
1829
1830 fn = MAY_LJMP(luaL_checkstring(L, 1));
1831
1832 if (lua_gettop(L) >= 2) {
1833 match = MAY_LJMP(luaL_checkinteger(L, 2));
1834 if (match < 0 || match >= PAT_MATCH_NUM)
1835 WILL_LJMP(luaL_error(L, "'new' needs a valid match method."));
1836 }
1837
1838 /* Get Lua filename and line number. */
1839 if (lua_getstack(L, 1, &ar)) { /* check function at level */
1840 lua_getinfo(L, "Sl", &ar); /* get info about it */
1841 if (ar.currentline > 0) { /* is there info? */
1842 file = ar.short_src;
1843 line = ar.currentline;
1844 }
1845 }
1846
1847 /* fill fake sample_conv struct. */
1848 conv.kw = ""; /* unused. */
1849 conv.process = NULL; /* unused. */
1850 conv.arg_mask = 0; /* unused. */
1851 conv.val_args = NULL; /* unused. */
1852 conv.out_type = SMP_T_STR;
1853 conv.private = (void *)(long)match;
1854 switch (match) {
1855 case PAT_MATCH_STR: conv.in_type = SMP_T_STR; break;
1856 case PAT_MATCH_BEG: conv.in_type = SMP_T_STR; break;
1857 case PAT_MATCH_SUB: conv.in_type = SMP_T_STR; break;
1858 case PAT_MATCH_DIR: conv.in_type = SMP_T_STR; break;
1859 case PAT_MATCH_DOM: conv.in_type = SMP_T_STR; break;
1860 case PAT_MATCH_END: conv.in_type = SMP_T_STR; break;
1861 case PAT_MATCH_REG: conv.in_type = SMP_T_STR; break;
Thierry FOURNIER07ee64e2015-07-06 23:43:03 +02001862 case PAT_MATCH_INT: conv.in_type = SMP_T_SINT; break;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001863 case PAT_MATCH_IP: conv.in_type = SMP_T_ADDR; break;
1864 default:
1865 WILL_LJMP(luaL_error(L, "'new' doesn't support this match mode."));
1866 }
1867
1868 /* fill fake args. */
1869 args[0].type = ARGT_STR;
Christopher Faulet73292e92020-08-06 08:40:09 +02001870 args[0].data.str.area = strdup(fn);
1871 args[0].data.str.data = strlen(fn);
1872 args[0].data.str.size = args[0].data.str.data+1;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001873 args[1].type = ARGT_STOP;
1874
1875 /* load the map. */
1876 if (!sample_load_map(args, &conv, file, line, &err)) {
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +05001877 /* error case: we can't use luaL_error because we must
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001878 * free the err variable.
1879 */
1880 luaL_where(L, 1);
1881 lua_pushfstring(L, "'new': %s.", err);
1882 lua_concat(L, 2);
1883 free(err);
Christopher Faulet6ad7df42020-08-07 11:45:18 +02001884 chunk_destroy(&args[0].data.str);
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001885 WILL_LJMP(lua_error(L));
1886 }
1887
1888 /* create the lua object. */
1889 lua_newtable(L);
1890 lua_pushlightuserdata(L, args[0].data.map);
1891 lua_rawseti(L, -2, 0);
1892
1893 /* Pop a class Map metatable and affect it to the userdata. */
1894 lua_rawgeti(L, LUA_REGISTRYINDEX, class_map_ref);
1895 lua_setmetatable(L, -2);
1896
1897
1898 return 1;
1899}
1900
1901__LJMP static inline int _hlua_map_lookup(struct lua_State *L, int str)
1902{
1903 struct map_descriptor *desc;
1904 struct pattern *pat;
1905 struct sample smp;
1906
1907 MAY_LJMP(check_args(L, 2, "lookup"));
1908 desc = MAY_LJMP(hlua_checkmap(L, 1));
Thierry FOURNIER07ee64e2015-07-06 23:43:03 +02001909 if (desc->pat.expect_type == SMP_T_SINT) {
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02001910 smp.data.type = SMP_T_SINT;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +02001911 smp.data.u.sint = MAY_LJMP(luaL_checkinteger(L, 2));
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001912 }
1913 else {
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02001914 smp.data.type = SMP_T_STR;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001915 smp.flags = SMP_F_CONST;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001916 smp.data.u.str.area = (char *)MAY_LJMP(luaL_checklstring(L, 2, (size_t *)&smp.data.u.str.data));
Thierry Fournier91dc0c02020-11-10 20:38:20 +01001917 smp.data.u.str.size = smp.data.u.str.data + 1;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001918 }
1919
1920 pat = pattern_exec_match(&desc->pat, &smp, 1);
Thierry FOURNIER503bb092015-08-19 08:35:43 +02001921 if (!pat || !pat->data) {
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001922 if (str)
1923 lua_pushstring(L, "");
1924 else
1925 lua_pushnil(L);
1926 return 1;
1927 }
1928
1929 /* The Lua pattern must return a string, so we can't check the returned type */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001930 lua_pushlstring(L, pat->data->u.str.area, pat->data->u.str.data);
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001931 return 1;
1932}
1933
1934__LJMP static int hlua_map_lookup(struct lua_State *L)
1935{
1936 return _hlua_map_lookup(L, 0);
1937}
1938
1939__LJMP static int hlua_map_slookup(struct lua_State *L)
1940{
1941 return _hlua_map_lookup(L, 1);
1942}
1943
1944/*
1945 *
1946 *
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001947 * Class Socket
1948 *
1949 *
1950 */
1951
1952__LJMP static struct hlua_socket *hlua_checksocket(lua_State *L, int ud)
1953{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02001954 return MAY_LJMP(hlua_checkudata(L, ud, class_socket_ref));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001955}
1956
1957/* This function is the handler called for each I/O on the established
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001958 * connection. It is used for notify space available to send or data
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001959 * received.
1960 */
Willy Tarreau00a37f02015-04-13 12:05:19 +02001961static void hlua_socket_handler(struct appctx *appctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001962{
Willy Tarreau5321da92022-05-06 11:57:34 +02001963 struct hlua_csk_ctx *ctx = appctx->svcctx;
Willy Tarreauc12b3212022-05-27 11:08:15 +02001964 struct stconn *sc = appctx_sc(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001965
Willy Tarreau5321da92022-05-06 11:57:34 +02001966 if (ctx->die) {
Willy Tarreau3e7be362022-05-27 10:35:27 +02001967 sc_shutw(sc);
1968 sc_shutr(sc);
1969 sc_ic(sc)->flags |= CF_READ_NULL;
Willy Tarreau5321da92022-05-06 11:57:34 +02001970 notification_wake(&ctx->wake_on_read);
1971 notification_wake(&ctx->wake_on_write);
Willy Tarreau3e7be362022-05-27 10:35:27 +02001972 stream_shutdown(__sc_strm(sc), SF_ERR_KILLED);
Thierry FOURNIERb13b20a2017-07-16 20:48:54 +02001973 }
1974
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +05001975 /* If we can't write, wakeup the pending write signals. */
Willy Tarreau3e7be362022-05-27 10:35:27 +02001976 if (channel_output_closed(sc_ic(sc)))
Willy Tarreau5321da92022-05-06 11:57:34 +02001977 notification_wake(&ctx->wake_on_write);
Thierry FOURNIER6d695e62015-09-27 19:29:38 +02001978
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +05001979 /* If we can't read, wakeup the pending read signals. */
Willy Tarreau3e7be362022-05-27 10:35:27 +02001980 if (channel_input_closed(sc_oc(sc)))
Willy Tarreau5321da92022-05-06 11:57:34 +02001981 notification_wake(&ctx->wake_on_read);
Thierry FOURNIER6d695e62015-09-27 19:29:38 +02001982
Willy Tarreau5a0b25d2019-07-18 18:01:14 +02001983 /* if the connection is not established, inform the stream that we want
Thierry FOURNIER316e3192015-09-04 18:25:53 +02001984 * to be notified whenever the connection completes.
1985 */
Willy Tarreau3e7be362022-05-27 10:35:27 +02001986 if (sc_opposite(sc)->state < SC_ST_EST) {
Willy Tarreau90e8b452022-05-25 18:21:43 +02001987 applet_need_more_data(appctx);
Willy Tarreaub23edc82022-05-24 16:49:03 +02001988 se_need_remote_conn(appctx->sedesc);
Willy Tarreau4164eb92022-05-25 15:42:03 +02001989 applet_have_more_data(appctx);
Willy Tarreaud4da1962015-04-20 01:31:23 +02001990 return;
Thierry FOURNIER316e3192015-09-04 18:25:53 +02001991 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001992
1993 /* This function is called after the connect. */
Willy Tarreau5321da92022-05-06 11:57:34 +02001994 ctx->connected = 1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001995
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001996 /* Wake the tasks which wants to write if the buffer have available space. */
Willy Tarreau3e7be362022-05-27 10:35:27 +02001997 if (channel_may_recv(sc_ic(sc)))
Willy Tarreau5321da92022-05-06 11:57:34 +02001998 notification_wake(&ctx->wake_on_write);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001999
2000 /* Wake the tasks which wants to read if the buffer contains data. */
Willy Tarreau3e7be362022-05-27 10:35:27 +02002001 if (!channel_is_empty(sc_oc(sc)))
Willy Tarreau5321da92022-05-06 11:57:34 +02002002 notification_wake(&ctx->wake_on_read);
Thierry FOURNIER101b9762018-05-27 01:27:40 +02002003
2004 /* Some data were injected in the buffer, notify the stream
2005 * interface.
2006 */
Willy Tarreau3e7be362022-05-27 10:35:27 +02002007 if (!channel_is_empty(sc_ic(sc)))
2008 sc_update(sc);
Thierry FOURNIER101b9762018-05-27 01:27:40 +02002009
2010 /* If write notifications are registered, we considers we want
Willy Tarreau3367d412018-11-15 10:57:41 +01002011 * to write, so we clear the blocking flag.
Thierry FOURNIER101b9762018-05-27 01:27:40 +02002012 */
Willy Tarreau5321da92022-05-06 11:57:34 +02002013 if (notification_registered(&ctx->wake_on_write))
Willy Tarreau4164eb92022-05-25 15:42:03 +02002014 applet_have_more_data(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002015}
2016
Christopher Faulet5f35a3e2022-05-12 15:31:05 +02002017static int hlua_socket_init(struct appctx *appctx)
2018{
2019 struct hlua_csk_ctx *ctx = appctx->svcctx;
2020 struct stream *s;
2021
2022 if (appctx_finalize_startup(appctx, socket_proxy, &BUF_NULL) == -1)
2023 goto error;
2024
2025 s = appctx_strm(appctx);
2026
Willy Tarreau4596fe22022-05-17 19:07:51 +02002027 /* Configure "right" stream connector. This stconn is used to connect
Christopher Faulet5f35a3e2022-05-12 15:31:05 +02002028 * and retrieve data from the server. The connection is initialized
2029 * with the "struct server".
2030 */
Willy Tarreau74568cf2022-05-27 09:03:30 +02002031 sc_set_state(s->scb, SC_ST_ASS);
Christopher Faulet5f35a3e2022-05-12 15:31:05 +02002032
2033 /* Force destination server. */
2034 s->flags |= SF_DIRECT | SF_ASSIGNED | SF_BE_ASSIGNED;
2035 s->target = &socket_tcp->obj_type;
2036
2037 ctx->appctx = appctx;
2038 return 0;
2039
2040 error:
2041 return -1;
2042}
2043
Willy Tarreau87b09662015-04-03 00:22:06 +02002044/* This function is called when the "struct stream" is destroyed.
2045 * Remove the link from the object to this stream.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002046 * Wake all the pending signals.
2047 */
Willy Tarreau00a37f02015-04-13 12:05:19 +02002048static void hlua_socket_release(struct appctx *appctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002049{
Willy Tarreau5321da92022-05-06 11:57:34 +02002050 struct hlua_csk_ctx *ctx = appctx->svcctx;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002051 struct xref *peer;
2052
Christopher Faulet5f35a3e2022-05-12 15:31:05 +02002053 /* Remove my link in the original objects. */
Willy Tarreau5321da92022-05-06 11:57:34 +02002054 peer = xref_get_peer_and_lock(&ctx->xref);
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002055 if (peer)
Willy Tarreau5321da92022-05-06 11:57:34 +02002056 xref_disconnect(&ctx->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002057
2058 /* Wake all the task waiting for me. */
Willy Tarreau5321da92022-05-06 11:57:34 +02002059 notification_wake(&ctx->wake_on_read);
2060 notification_wake(&ctx->wake_on_write);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002061}
2062
2063/* If the garbage collectio of the object is launch, nobody
Willy Tarreau87b09662015-04-03 00:22:06 +02002064 * uses this object. If the stream does not exists, just quit.
2065 * Send the shutdown signal to the stream. In some cases,
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002066 * pending signal can rest in the read and write lists. destroy
2067 * it.
2068 */
2069__LJMP static int hlua_socket_gc(lua_State *L)
2070{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002071 struct hlua_socket *socket;
Willy Tarreau5321da92022-05-06 11:57:34 +02002072 struct hlua_csk_ctx *ctx;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002073 struct xref *peer;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002074
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002075 MAY_LJMP(check_args(L, 1, "__gc"));
2076
2077 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002078 peer = xref_get_peer_and_lock(&socket->xref);
2079 if (!peer)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002080 return 0;
Willy Tarreau5321da92022-05-06 11:57:34 +02002081
2082 ctx = container_of(peer, struct hlua_csk_ctx, xref);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002083
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002084 /* Set the flag which destroy the session. */
Willy Tarreau5321da92022-05-06 11:57:34 +02002085 ctx->die = 1;
2086 appctx_wakeup(ctx->appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002087
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002088 /* Remove all reference between the Lua stack and the coroutine stream. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002089 xref_disconnect(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002090 return 0;
2091}
2092
2093/* The close function send shutdown signal and break the
Willy Tarreau87b09662015-04-03 00:22:06 +02002094 * links between the stream and the object.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002095 */
sada05ed3302018-05-11 11:48:18 -07002096__LJMP static int hlua_socket_close_helper(lua_State *L)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002097{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002098 struct hlua_socket *socket;
Willy Tarreau5321da92022-05-06 11:57:34 +02002099 struct hlua_csk_ctx *ctx;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002100 struct xref *peer;
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002101 struct hlua *hlua;
2102
2103 /* Get hlua struct, or NULL if we execute from main lua state */
2104 hlua = hlua_gethlua(L);
2105 if (!hlua)
2106 return 0;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002107
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002108 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002109
2110 /* Check if we run on the same thread than the xreator thread.
2111 * We cannot access to the socket if the thread is different.
2112 */
2113 if (socket->tid != tid)
2114 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2115
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002116 peer = xref_get_peer_and_lock(&socket->xref);
2117 if (!peer)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002118 return 0;
Willy Tarreauf31af932020-01-14 09:59:38 +01002119
2120 hlua->gc_count--;
Willy Tarreau5321da92022-05-06 11:57:34 +02002121 ctx = container_of(peer, struct hlua_csk_ctx, xref);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002122
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002123 /* Set the flag which destroy the session. */
Willy Tarreau5321da92022-05-06 11:57:34 +02002124 ctx->die = 1;
2125 appctx_wakeup(ctx->appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002126
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002127 /* Remove all reference between the Lua stack and the coroutine stream. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002128 xref_disconnect(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002129 return 0;
2130}
2131
sada05ed3302018-05-11 11:48:18 -07002132/* The close function calls close_helper.
2133 */
2134__LJMP static int hlua_socket_close(lua_State *L)
2135{
2136 MAY_LJMP(check_args(L, 1, "close"));
2137 return hlua_socket_close_helper(L);
2138}
2139
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002140/* This Lua function assumes that the stack contain three parameters.
2141 * 1 - USERDATA containing a struct socket
2142 * 2 - INTEGER with values of the macro defined below
2143 * If the integer is -1, we must read at most one line.
2144 * If the integer is -2, we ust read all the data until the
2145 * end of the stream.
2146 * If the integer is positive value, we must read a number of
2147 * bytes corresponding to this value.
2148 */
2149#define HLSR_READ_LINE (-1)
2150#define HLSR_READ_ALL (-2)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002151__LJMP static int hlua_socket_receive_yield(struct lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002152{
2153 struct hlua_socket *socket = MAY_LJMP(hlua_checksocket(L, 1));
2154 int wanted = lua_tointeger(L, 2);
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002155 struct hlua *hlua;
Willy Tarreau5321da92022-05-06 11:57:34 +02002156 struct hlua_csk_ctx *csk_ctx;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002157 struct appctx *appctx;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02002158 size_t len;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002159 int nblk;
Willy Tarreau206ba832018-06-14 15:27:31 +02002160 const char *blk1;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02002161 size_t len1;
Willy Tarreau206ba832018-06-14 15:27:31 +02002162 const char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02002163 size_t len2;
Thierry FOURNIER00543922015-03-09 18:35:06 +01002164 int skip_at_end = 0;
Willy Tarreau81389672015-03-10 12:03:52 +01002165 struct channel *oc;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002166 struct stream *s;
2167 struct xref *peer;
Thierry FOURNIER8c126c72018-05-25 16:27:44 +02002168 int missing_bytes;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002169
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002170 /* Get hlua struct, or NULL if we execute from main lua state */
2171 hlua = hlua_gethlua(L);
2172
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002173 /* Check if this lua stack is schedulable. */
2174 if (!hlua || !hlua->task)
2175 WILL_LJMP(luaL_error(L, "The 'receive' function is only allowed in "
2176 "'frontend', 'backend' or 'task'"));
2177
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002178 /* Check if we run on the same thread than the xreator thread.
2179 * We cannot access to the socket if the thread is different.
2180 */
2181 if (socket->tid != tid)
2182 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2183
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002184 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002185 peer = xref_get_peer_and_lock(&socket->xref);
2186 if (!peer)
2187 goto no_peer;
Willy Tarreau5321da92022-05-06 11:57:34 +02002188
2189 csk_ctx = container_of(peer, struct hlua_csk_ctx, xref);
2190 appctx = csk_ctx->appctx;
Willy Tarreau0698c802022-05-11 14:09:57 +02002191 s = appctx_strm(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002192
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002193 oc = &s->res;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002194 if (wanted == HLSR_READ_LINE) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002195 /* Read line. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02002196 nblk = co_getline_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002197 if (nblk < 0) /* Connection close. */
2198 goto connection_closed;
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002199 if (nblk == 0) /* No data available. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002200 goto connection_empty;
Thierry FOURNIER00543922015-03-09 18:35:06 +01002201
2202 /* remove final \r\n. */
2203 if (nblk == 1) {
2204 if (blk1[len1-1] == '\n') {
2205 len1--;
2206 skip_at_end++;
2207 if (blk1[len1-1] == '\r') {
2208 len1--;
2209 skip_at_end++;
2210 }
2211 }
2212 }
2213 else {
2214 if (blk2[len2-1] == '\n') {
2215 len2--;
2216 skip_at_end++;
2217 if (blk2[len2-1] == '\r') {
2218 len2--;
2219 skip_at_end++;
2220 }
2221 }
2222 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002223 }
2224
2225 else if (wanted == HLSR_READ_ALL) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002226 /* Read all the available data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02002227 nblk = co_getblk_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002228 if (nblk < 0) /* Connection close. */
2229 goto connection_closed;
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002230 if (nblk == 0) /* No data available. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002231 goto connection_empty;
2232 }
2233
2234 else {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002235 /* Read a block of data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02002236 nblk = co_getblk_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002237 if (nblk < 0) /* Connection close. */
2238 goto connection_closed;
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002239 if (nblk == 0) /* No data available. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002240 goto connection_empty;
2241
Thierry FOURNIER8c126c72018-05-25 16:27:44 +02002242 missing_bytes = wanted - socket->b.n;
2243 if (len1 > missing_bytes) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002244 nblk = 1;
Thierry FOURNIER8c126c72018-05-25 16:27:44 +02002245 len1 = missing_bytes;
2246 } if (nblk == 2 && len1 + len2 > missing_bytes)
2247 len2 = missing_bytes - len1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002248 }
2249
2250 len = len1;
2251
2252 luaL_addlstring(&socket->b, blk1, len1);
2253 if (nblk == 2) {
2254 len += len2;
2255 luaL_addlstring(&socket->b, blk2, len2);
2256 }
2257
2258 /* Consume data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02002259 co_skip(oc, len + skip_at_end);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002260
2261 /* Don't wait anything. */
Thierry FOURNIER7e4ee472018-05-25 15:03:50 +02002262 appctx_wakeup(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002263
2264 /* If the pattern reclaim to read all the data
2265 * in the connection, got out.
2266 */
2267 if (wanted == HLSR_READ_ALL)
2268 goto connection_empty;
Thierry FOURNIER8c126c72018-05-25 16:27:44 +02002269 else if (wanted >= 0 && socket->b.n < wanted)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002270 goto connection_empty;
2271
2272 /* Return result. */
2273 luaL_pushresult(&socket->b);
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002274 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002275 return 1;
2276
2277connection_closed:
2278
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002279 xref_unlock(&socket->xref, peer);
2280
2281no_peer:
2282
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002283 /* If the buffer containds data. */
2284 if (socket->b.n > 0) {
2285 luaL_pushresult(&socket->b);
2286 return 1;
2287 }
2288 lua_pushnil(L);
2289 lua_pushstring(L, "connection closed.");
2290 return 2;
2291
2292connection_empty:
2293
Willy Tarreau5321da92022-05-06 11:57:34 +02002294 if (!notification_new(&hlua->com, &csk_ctx->wake_on_read, hlua->task)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002295 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002296 WILL_LJMP(luaL_error(L, "out of memory"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002297 }
2298 xref_unlock(&socket->xref, peer);
Willy Tarreau9635e032018-10-16 17:52:55 +02002299 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_receive_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002300 return 0;
2301}
2302
Tim Duesterhusb33754c2018-01-04 19:32:14 +01002303/* This Lua function gets two parameters. The first one can be string
2304 * or a number. If the string is "*l", the user requires one line. If
2305 * the string is "*a", the user requires all the contents of the stream.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002306 * If the value is a number, the user require a number of bytes equal
2307 * to the value. The default value is "*l" (a line).
2308 *
Tim Duesterhusb33754c2018-01-04 19:32:14 +01002309 * This parameter with a variable type is converted in integer. This
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002310 * integer takes this values:
2311 * -1 : read a line
2312 * -2 : read all the stream
Tim Duesterhusb33754c2018-01-04 19:32:14 +01002313 * >0 : amount of bytes.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002314 *
Tim Duesterhusb33754c2018-01-04 19:32:14 +01002315 * The second parameter is optional. It contains a string that must be
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002316 * concatenated with the read data.
2317 */
2318__LJMP static int hlua_socket_receive(struct lua_State *L)
2319{
2320 int wanted = HLSR_READ_LINE;
2321 const char *pattern;
Christopher Fauletc31b2002021-05-03 10:11:13 +02002322 int lastarg, type;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002323 char *error;
2324 size_t len;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002325 struct hlua_socket *socket;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002326
2327 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
2328 WILL_LJMP(luaL_error(L, "The 'receive' function requires between 1 and 3 arguments."));
2329
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002330 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002331
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002332 /* Check if we run on the same thread than the xreator thread.
2333 * We cannot access to the socket if the thread is different.
2334 */
2335 if (socket->tid != tid)
2336 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2337
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002338 /* check for pattern. */
2339 if (lua_gettop(L) >= 2) {
2340 type = lua_type(L, 2);
2341 if (type == LUA_TSTRING) {
2342 pattern = lua_tostring(L, 2);
2343 if (strcmp(pattern, "*a") == 0)
2344 wanted = HLSR_READ_ALL;
2345 else if (strcmp(pattern, "*l") == 0)
2346 wanted = HLSR_READ_LINE;
2347 else {
2348 wanted = strtoll(pattern, &error, 10);
2349 if (*error != '\0')
2350 WILL_LJMP(luaL_error(L, "Unsupported pattern."));
2351 }
2352 }
2353 else if (type == LUA_TNUMBER) {
2354 wanted = lua_tointeger(L, 2);
2355 if (wanted < 0)
2356 WILL_LJMP(luaL_error(L, "Unsupported size."));
2357 }
2358 }
2359
2360 /* Set pattern. */
2361 lua_pushinteger(L, wanted);
Tim Duesterhusc6e377e2018-01-04 19:32:13 +01002362
2363 /* Check if we would replace the top by itself. */
2364 if (lua_gettop(L) != 2)
2365 lua_replace(L, 2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002366
Christopher Fauletc31b2002021-05-03 10:11:13 +02002367 /* Save index of the top of the stack because since buffers are used, it
2368 * may change
2369 */
2370 lastarg = lua_gettop(L);
2371
Tim Duesterhusb33754c2018-01-04 19:32:14 +01002372 /* init buffer, and fill it with prefix. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002373 luaL_buffinit(L, &socket->b);
2374
2375 /* Check prefix. */
Christopher Fauletc31b2002021-05-03 10:11:13 +02002376 if (lastarg >= 3) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002377 if (lua_type(L, 3) != LUA_TSTRING)
2378 WILL_LJMP(luaL_error(L, "Expect a 'string' for the prefix"));
2379 pattern = lua_tolstring(L, 3, &len);
2380 luaL_addlstring(&socket->b, pattern, len);
2381 }
2382
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002383 return __LJMP(hlua_socket_receive_yield(L, 0, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002384}
2385
2386/* Write the Lua input string in the output buffer.
Mark Lakes22154b42018-01-29 14:38:40 -08002387 * This function returns a yield if no space is available.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002388 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002389static int hlua_socket_write_yield(struct lua_State *L,int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002390{
2391 struct hlua_socket *socket;
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002392 struct hlua *hlua;
Willy Tarreau5321da92022-05-06 11:57:34 +02002393 struct hlua_csk_ctx *csk_ctx;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002394 struct appctx *appctx;
2395 size_t buf_len;
2396 const char *buf;
2397 int len;
2398 int send_len;
2399 int sent;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002400 struct xref *peer;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002401 struct stream *s;
Willy Tarreau3e7be362022-05-27 10:35:27 +02002402 struct stconn *sc;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002403
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002404 /* Get hlua struct, or NULL if we execute from main lua state */
2405 hlua = hlua_gethlua(L);
2406
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002407 /* Check if this lua stack is schedulable. */
2408 if (!hlua || !hlua->task)
2409 WILL_LJMP(luaL_error(L, "The 'write' function is only allowed in "
2410 "'frontend', 'backend' or 'task'"));
2411
2412 /* Get object */
2413 socket = MAY_LJMP(hlua_checksocket(L, 1));
2414 buf = MAY_LJMP(luaL_checklstring(L, 2, &buf_len));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002415 sent = MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002416
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002417 /* Check if we run on the same thread than the xreator thread.
2418 * We cannot access to the socket if the thread is different.
2419 */
2420 if (socket->tid != tid)
2421 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2422
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002423 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002424 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002425 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002426 lua_pushinteger(L, -1);
2427 return 1;
2428 }
Willy Tarreau5321da92022-05-06 11:57:34 +02002429
2430 csk_ctx = container_of(peer, struct hlua_csk_ctx, xref);
2431 appctx = csk_ctx->appctx;
Willy Tarreauc12b3212022-05-27 11:08:15 +02002432 sc = appctx_sc(appctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02002433 s = __sc_strm(sc);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002434
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002435 /* Check for connection close. */
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002436 if (channel_output_closed(&s->req)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002437 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002438 lua_pushinteger(L, -1);
2439 return 1;
2440 }
2441
2442 /* Update the input buffer data. */
2443 buf += sent;
2444 send_len = buf_len - sent;
2445
2446 /* All the data are sent. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002447 if (sent >= buf_len) {
2448 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002449 return 1; /* Implicitly return the length sent. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002450 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002451
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002452 /* Check if the buffer is available because HAProxy doesn't allocate
Thierry FOURNIER486d52a2015-03-09 17:51:43 +01002453 * the request buffer if its not required.
2454 */
Willy Tarreauc9fa0482018-07-10 17:43:27 +02002455 if (s->req.buf.size == 0) {
Willy Tarreau3e7be362022-05-27 10:35:27 +02002456 if (!sc_alloc_ibuf(sc, &appctx->buffer_wait))
Christopher Faulet33834b12016-12-19 09:29:06 +01002457 goto hlua_socket_write_yield_return;
Thierry FOURNIER486d52a2015-03-09 17:51:43 +01002458 }
2459
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002460 /* Check for available space. */
Willy Tarreauc9fa0482018-07-10 17:43:27 +02002461 len = b_room(&s->req.buf);
Christopher Faulet33834b12016-12-19 09:29:06 +01002462 if (len <= 0) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002463 goto hlua_socket_write_yield_return;
Christopher Faulet33834b12016-12-19 09:29:06 +01002464 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002465
2466 /* send data */
2467 if (len < send_len)
2468 send_len = len;
Thierry FOURNIER66b89192018-05-27 01:14:47 +02002469 len = ci_putblk(&s->req, buf, send_len);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002470
2471 /* "Not enough space" (-1), "Buffer too little to contain
2472 * the data" (-2) are not expected because the available length
2473 * is tested.
2474 * Other unknown error are also not expected.
2475 */
2476 if (len <= 0) {
Willy Tarreaubc18da12015-03-13 14:00:47 +01002477 if (len == -1)
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002478 s->req.flags |= CF_WAKE_WRITE;
Willy Tarreaubc18da12015-03-13 14:00:47 +01002479
sada05ed3302018-05-11 11:48:18 -07002480 MAY_LJMP(hlua_socket_close_helper(L));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002481 lua_pop(L, 1);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002482 lua_pushinteger(L, -1);
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002483 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002484 return 1;
2485 }
2486
2487 /* update buffers. */
Thierry FOURNIER101b9762018-05-27 01:27:40 +02002488 appctx_wakeup(appctx);
Willy Tarreaude70fa12015-09-26 11:25:05 +02002489
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002490 s->req.rex = TICK_ETERNITY;
2491 s->res.wex = TICK_ETERNITY;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002492
2493 /* Update length sent. */
2494 lua_pop(L, 1);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002495 lua_pushinteger(L, sent + len);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002496
2497 /* All the data buffer is sent ? */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002498 if (sent + len >= buf_len) {
2499 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002500 return 1;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002501 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002502
2503hlua_socket_write_yield_return:
Willy Tarreau5321da92022-05-06 11:57:34 +02002504 if (!notification_new(&hlua->com, &csk_ctx->wake_on_write, hlua->task)) {
Thierry FOURNIERba42fcd2018-05-27 00:59:48 +02002505 xref_unlock(&socket->xref, peer);
2506 WILL_LJMP(luaL_error(L, "out of memory"));
2507 }
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002508 xref_unlock(&socket->xref, peer);
Willy Tarreau9635e032018-10-16 17:52:55 +02002509 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_write_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002510 return 0;
2511}
2512
2513/* This function initiate the send of data. It just check the input
2514 * parameters and push an integer in the Lua stack that contain the
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002515 * amount of data written to the buffer. This is used by the function
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002516 * "hlua_socket_write_yield" that can yield.
2517 *
2518 * The Lua function gets between 3 and 4 parameters. The first one is
2519 * the associated object. The second is a string buffer. The third is
2520 * a facultative integer that represents where is the buffer position
2521 * of the start of the data that can send. The first byte is the
2522 * position "1". The default value is "1". The fourth argument is a
2523 * facultative integer that represents where is the buffer position
2524 * of the end of the data that can send. The default is the last byte.
2525 */
2526static int hlua_socket_send(struct lua_State *L)
2527{
2528 int i;
2529 int j;
2530 const char *buf;
2531 size_t buf_len;
2532
2533 /* Check number of arguments. */
2534 if (lua_gettop(L) < 2 || lua_gettop(L) > 4)
2535 WILL_LJMP(luaL_error(L, "'send' needs between 2 and 4 arguments"));
2536
2537 /* Get the string. */
2538 buf = MAY_LJMP(luaL_checklstring(L, 2, &buf_len));
2539
2540 /* Get and check j. */
2541 if (lua_gettop(L) == 4) {
2542 j = MAY_LJMP(luaL_checkinteger(L, 4));
2543 if (j < 0)
2544 j = buf_len + j + 1;
2545 if (j > buf_len)
2546 j = buf_len + 1;
2547 lua_pop(L, 1);
2548 }
2549 else
2550 j = buf_len;
2551
2552 /* Get and check i. */
2553 if (lua_gettop(L) == 3) {
2554 i = MAY_LJMP(luaL_checkinteger(L, 3));
2555 if (i < 0)
2556 i = buf_len + i + 1;
2557 if (i > buf_len)
2558 i = buf_len + 1;
2559 lua_pop(L, 1);
2560 } else
2561 i = 1;
2562
2563 /* Check bth i and j. */
2564 if (i > j) {
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002565 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002566 return 1;
2567 }
2568 if (i == 0 && j == 0) {
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002569 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002570 return 1;
2571 }
2572 if (i == 0)
2573 i = 1;
2574 if (j == 0)
2575 j = 1;
2576
2577 /* Pop the string. */
2578 lua_pop(L, 1);
2579
2580 /* Update the buffer length. */
2581 buf += i - 1;
2582 buf_len = j - i + 1;
2583 lua_pushlstring(L, buf, buf_len);
2584
2585 /* This unsigned is used to remember the amount of sent data. */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002586 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002587
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002588 return MAY_LJMP(hlua_socket_write_yield(L, 0, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002589}
2590
Willy Tarreau22b0a682015-06-17 19:43:49 +02002591#define SOCKET_INFO_MAX_LEN sizeof("[0000:0000:0000:0000:0000:0000:0000:0000]:12345")
Christopher Faulete6465b32021-10-22 15:36:08 +02002592__LJMP static inline int hlua_socket_info(struct lua_State *L, const struct sockaddr_storage *addr)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002593{
2594 static char buffer[SOCKET_INFO_MAX_LEN];
2595 int ret;
2596 int len;
2597 char *p;
2598
2599 ret = addr_to_str(addr, buffer+1, SOCKET_INFO_MAX_LEN-1);
2600 if (ret <= 0) {
2601 lua_pushnil(L);
2602 return 1;
2603 }
2604
2605 if (ret == AF_UNIX) {
2606 lua_pushstring(L, buffer+1);
2607 return 1;
2608 }
2609 else if (ret == AF_INET6) {
2610 buffer[0] = '[';
2611 len = strlen(buffer);
2612 buffer[len] = ']';
2613 len++;
2614 buffer[len] = ':';
2615 len++;
2616 p = buffer;
2617 }
2618 else if (ret == AF_INET) {
2619 p = buffer + 1;
2620 len = strlen(p);
2621 p[len] = ':';
2622 len++;
2623 }
2624 else {
2625 lua_pushnil(L);
2626 return 1;
2627 }
2628
2629 if (port_to_str(addr, p + len, SOCKET_INFO_MAX_LEN-1 - len) <= 0) {
2630 lua_pushnil(L);
2631 return 1;
2632 }
2633
2634 lua_pushstring(L, p);
2635 return 1;
2636}
2637
2638/* Returns information about the peer of the connection. */
2639__LJMP static int hlua_socket_getpeername(struct lua_State *L)
2640{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002641 struct hlua_socket *socket;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002642 struct xref *peer;
2643 struct appctx *appctx;
Willy Tarreau3e7be362022-05-27 10:35:27 +02002644 struct stconn *sc;
Christopher Faulet16f16af2021-10-27 09:34:56 +02002645 const struct sockaddr_storage *dst;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002646 int ret;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002647
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002648 MAY_LJMP(check_args(L, 1, "getpeername"));
2649
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002650 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002651
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002652 /* Check if we run on the same thread than the xreator thread.
2653 * We cannot access to the socket if the thread is different.
2654 */
2655 if (socket->tid != tid)
2656 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2657
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002658 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002659 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002660 if (!peer) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002661 lua_pushnil(L);
2662 return 1;
2663 }
Willy Tarreau5321da92022-05-06 11:57:34 +02002664
2665 appctx = container_of(peer, struct hlua_csk_ctx, xref)->appctx;
Willy Tarreauc12b3212022-05-27 11:08:15 +02002666 sc = appctx_sc(appctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02002667 dst = sc_dst(sc_opposite(sc));
Christopher Faulet16f16af2021-10-27 09:34:56 +02002668 if (!dst) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002669 xref_unlock(&socket->xref, peer);
Willy Tarreaua71f6422016-11-16 17:00:14 +01002670 lua_pushnil(L);
2671 return 1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002672 }
2673
Christopher Faulet16f16af2021-10-27 09:34:56 +02002674 ret = MAY_LJMP(hlua_socket_info(L, dst));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002675 xref_unlock(&socket->xref, peer);
2676 return ret;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002677}
2678
2679/* Returns information about my connection side. */
2680static int hlua_socket_getsockname(struct lua_State *L)
2681{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002682 struct hlua_socket *socket;
2683 struct connection *conn;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002684 struct appctx *appctx;
2685 struct xref *peer;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002686 struct stream *s;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002687 int ret;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002688
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002689 MAY_LJMP(check_args(L, 1, "getsockname"));
2690
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002691 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002692
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002693 /* Check if we run on the same thread than the xreator thread.
2694 * We cannot access to the socket if the thread is different.
2695 */
2696 if (socket->tid != tid)
2697 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2698
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002699 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002700 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002701 if (!peer) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002702 lua_pushnil(L);
2703 return 1;
2704 }
Willy Tarreau5321da92022-05-06 11:57:34 +02002705
2706 appctx = container_of(peer, struct hlua_csk_ctx, xref)->appctx;
Willy Tarreau0698c802022-05-11 14:09:57 +02002707 s = appctx_strm(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002708
Willy Tarreaufd9417b2022-05-18 16:23:22 +02002709 conn = sc_conn(s->scb);
Willy Tarreau5a0b25d2019-07-18 18:01:14 +02002710 if (!conn || !conn_get_src(conn)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002711 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002712 lua_pushnil(L);
2713 return 1;
2714 }
2715
Willy Tarreau9da9a6f2019-07-17 14:49:44 +02002716 ret = hlua_socket_info(L, conn->src);
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002717 xref_unlock(&socket->xref, peer);
2718 return ret;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002719}
2720
2721/* This struct define the applet. */
Willy Tarreau30576452015-04-13 13:50:30 +02002722static struct applet update_applet = {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002723 .obj_type = OBJ_TYPE_APPLET,
2724 .name = "<LUA_TCP>",
2725 .fct = hlua_socket_handler,
Christopher Faulet5f35a3e2022-05-12 15:31:05 +02002726 .init = hlua_socket_init,
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002727 .release = hlua_socket_release,
2728};
2729
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002730__LJMP static int hlua_socket_connect_yield(struct lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002731{
2732 struct hlua_socket *socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002733 struct hlua *hlua;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002734 struct xref *peer;
Willy Tarreau5321da92022-05-06 11:57:34 +02002735 struct hlua_csk_ctx *csk_ctx;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002736 struct appctx *appctx;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002737 struct stream *s;
2738
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002739 /* Get hlua struct, or NULL if we execute from main lua state */
2740 hlua = hlua_gethlua(L);
2741 if (!hlua)
2742 return 0;
2743
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002744 /* Check if we run on the same thread than the xreator thread.
2745 * We cannot access to the socket if the thread is different.
2746 */
2747 if (socket->tid != tid)
2748 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2749
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002750 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002751 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002752 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002753 lua_pushnil(L);
2754 lua_pushstring(L, "Can't connect");
2755 return 2;
2756 }
Willy Tarreau5321da92022-05-06 11:57:34 +02002757
2758 csk_ctx = container_of(peer, struct hlua_csk_ctx, xref);
2759 appctx = csk_ctx->appctx;
Willy Tarreau0698c802022-05-11 14:09:57 +02002760 s = appctx_strm(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002761
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002762 /* Check if we run on the same thread than the xreator thread.
2763 * We cannot access to the socket if the thread is different.
2764 */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002765 if (socket->tid != tid) {
2766 xref_unlock(&socket->xref, peer);
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002767 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002768 }
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002769
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002770 /* Check for connection close. */
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002771 if (!hlua || channel_output_closed(&s->req)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002772 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002773 lua_pushnil(L);
2774 lua_pushstring(L, "Can't connect");
2775 return 2;
2776 }
2777
Willy Tarreau8e7c6e62022-05-18 17:58:02 +02002778 appctx = __sc_appctx(s->scf);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002779
2780 /* Check for connection established. */
Willy Tarreau5321da92022-05-06 11:57:34 +02002781 if (csk_ctx->connected) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002782 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002783 lua_pushinteger(L, 1);
2784 return 1;
2785 }
2786
Willy Tarreau5321da92022-05-06 11:57:34 +02002787 if (!notification_new(&hlua->com, &csk_ctx->wake_on_write, hlua->task)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002788 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002789 WILL_LJMP(luaL_error(L, "out of memory error"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002790 }
2791 xref_unlock(&socket->xref, peer);
Willy Tarreau9635e032018-10-16 17:52:55 +02002792 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_connect_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002793 return 0;
2794}
2795
2796/* This function fail or initite the connection. */
2797__LJMP static int hlua_socket_connect(struct lua_State *L)
2798{
2799 struct hlua_socket *socket;
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002800 int port = -1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002801 const char *ip;
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002802 struct hlua *hlua;
Willy Tarreau5321da92022-05-06 11:57:34 +02002803 struct hlua_csk_ctx *csk_ctx;
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002804 struct appctx *appctx;
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002805 int low, high;
2806 struct sockaddr_storage *addr;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002807 struct xref *peer;
Willy Tarreau3e7be362022-05-27 10:35:27 +02002808 struct stconn *sc;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002809 struct stream *s;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002810
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002811 if (lua_gettop(L) < 2)
2812 WILL_LJMP(luaL_error(L, "connect: need at least 2 arguments"));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002813
2814 /* Get args. */
2815 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002816
2817 /* Check if we run on the same thread than the xreator thread.
2818 * We cannot access to the socket if the thread is different.
2819 */
2820 if (socket->tid != tid)
2821 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2822
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002823 ip = MAY_LJMP(luaL_checkstring(L, 2));
Tim Duesterhus6edab862018-01-06 19:04:45 +01002824 if (lua_gettop(L) >= 3) {
2825 luaL_Buffer b;
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002826 port = MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002827
Tim Duesterhus6edab862018-01-06 19:04:45 +01002828 /* Force the ip to end with a colon, to support IPv6 addresses
2829 * that are not enclosed within square brackets.
2830 */
2831 if (port > 0) {
2832 luaL_buffinit(L, &b);
2833 luaL_addstring(&b, ip);
2834 luaL_addchar(&b, ':');
2835 luaL_pushresult(&b);
2836 ip = lua_tolstring(L, lua_gettop(L), NULL);
2837 }
2838 }
2839
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002840 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002841 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002842 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002843 lua_pushnil(L);
2844 return 1;
2845 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002846
2847 /* Parse ip address. */
Willy Tarreau5fc93282020-09-16 18:25:03 +02002848 addr = str2sa_range(ip, NULL, &low, &high, NULL, NULL, NULL, NULL, NULL, PA_O_PORT_OK | PA_O_STREAM);
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002849 if (!addr) {
2850 xref_unlock(&socket->xref, peer);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002851 WILL_LJMP(luaL_error(L, "connect: cannot parse destination address '%s'", ip));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002852 }
Willy Tarreau9da9a6f2019-07-17 14:49:44 +02002853
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002854 /* Set port. */
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002855 if (low == 0) {
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02002856 if (addr->ss_family == AF_INET) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002857 if (port == -1) {
2858 xref_unlock(&socket->xref, peer);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002859 WILL_LJMP(luaL_error(L, "connect: port missing"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002860 }
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02002861 ((struct sockaddr_in *)addr)->sin_port = htons(port);
2862 } else if (addr->ss_family == AF_INET6) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002863 if (port == -1) {
2864 xref_unlock(&socket->xref, peer);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002865 WILL_LJMP(luaL_error(L, "connect: port missing"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002866 }
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02002867 ((struct sockaddr_in6 *)addr)->sin6_port = htons(port);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002868 }
2869 }
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02002870
Willy Tarreau5321da92022-05-06 11:57:34 +02002871 csk_ctx = container_of(peer, struct hlua_csk_ctx, xref);
2872 appctx = csk_ctx->appctx;
Willy Tarreauc12b3212022-05-27 11:08:15 +02002873 sc = appctx_sc(appctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02002874 s = __sc_strm(sc);
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02002875
Willy Tarreau3e7be362022-05-27 10:35:27 +02002876 if (!sockaddr_alloc(&sc_opposite(sc)->dst, addr, sizeof(*addr))) {
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02002877 xref_unlock(&socket->xref, peer);
2878 WILL_LJMP(luaL_error(L, "connect: internal error"));
2879 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002880
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002881 /* Get hlua struct, or NULL if we execute from main lua state */
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002882 hlua = hlua_gethlua(L);
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002883 if (!hlua)
2884 return 0;
Willy Tarreaubdc97a82015-08-24 15:42:28 +02002885
2886 /* inform the stream that we want to be notified whenever the
2887 * connection completes.
2888 */
Willy Tarreau90e8b452022-05-25 18:21:43 +02002889 applet_need_more_data(appctx);
Willy Tarreau4164eb92022-05-25 15:42:03 +02002890 applet_have_more_data(appctx);
Thierry FOURNIER8c8fbbe2015-09-26 17:02:35 +02002891 appctx_wakeup(appctx);
Willy Tarreaubdc97a82015-08-24 15:42:28 +02002892
Willy Tarreauf31af932020-01-14 09:59:38 +01002893 hlua->gc_count++;
Thierry FOURNIER7c39ab42015-09-27 22:53:33 +02002894
Willy Tarreau5321da92022-05-06 11:57:34 +02002895 if (!notification_new(&hlua->com, &csk_ctx->wake_on_write, hlua->task)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002896 xref_unlock(&socket->xref, peer);
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002897 WILL_LJMP(luaL_error(L, "out of memory"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002898 }
2899 xref_unlock(&socket->xref, peer);
PiBa-NL706d5ee2018-05-05 23:51:42 +02002900
2901 task_wakeup(s->task, TASK_WOKEN_INIT);
2902 /* Return yield waiting for connection. */
2903
Willy Tarreau9635e032018-10-16 17:52:55 +02002904 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_connect_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002905
2906 return 0;
2907}
2908
Baptiste Assmann84bb4932015-03-02 21:40:06 +01002909#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002910__LJMP static int hlua_socket_connect_ssl(struct lua_State *L)
2911{
2912 struct hlua_socket *socket;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002913 struct xref *peer;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002914 struct stream *s;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002915
2916 MAY_LJMP(check_args(L, 3, "connect_ssl"));
2917 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002918
2919 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002920 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002921 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002922 lua_pushnil(L);
2923 return 1;
2924 }
Willy Tarreau5321da92022-05-06 11:57:34 +02002925
Willy Tarreau0698c802022-05-11 14:09:57 +02002926 s = appctx_strm(container_of(peer, struct hlua_csk_ctx, xref)->appctx);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002927
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +01002928 s->target = &socket_ssl->obj_type;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002929 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002930 return MAY_LJMP(hlua_socket_connect(L));
2931}
Baptiste Assmann84bb4932015-03-02 21:40:06 +01002932#endif
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002933
2934__LJMP static int hlua_socket_setoption(struct lua_State *L)
2935{
2936 return 0;
2937}
2938
2939__LJMP static int hlua_socket_settimeout(struct lua_State *L)
2940{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002941 struct hlua_socket *socket;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002942 int tmout;
Mark Lakes56cc1252018-03-27 09:48:06 +02002943 double dtmout;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002944 struct xref *peer;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002945 struct stream *s;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002946
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002947 MAY_LJMP(check_args(L, 2, "settimeout"));
2948
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002949 socket = MAY_LJMP(hlua_checksocket(L, 1));
Mark Lakes56cc1252018-03-27 09:48:06 +02002950
Cyril Bonté7ee465f2018-08-19 22:08:50 +02002951 /* convert the timeout to millis */
2952 dtmout = MAY_LJMP(luaL_checknumber(L, 2)) * 1000;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002953
Thierry Fournier17a921b2018-03-08 09:59:02 +01002954 /* Check for negative values */
Mark Lakes56cc1252018-03-27 09:48:06 +02002955 if (dtmout < 0)
Thierry Fournier17a921b2018-03-08 09:59:02 +01002956 WILL_LJMP(luaL_error(L, "settimeout: cannot set negatives values"));
2957
Mark Lakes56cc1252018-03-27 09:48:06 +02002958 if (dtmout > INT_MAX) /* overflow check */
Cyril Bonté7ee465f2018-08-19 22:08:50 +02002959 WILL_LJMP(luaL_error(L, "settimeout: cannot set values larger than %d ms", INT_MAX));
Mark Lakes56cc1252018-03-27 09:48:06 +02002960
2961 tmout = MS_TO_TICKS((int)dtmout);
Cyril Bonté7ee465f2018-08-19 22:08:50 +02002962 if (tmout == 0)
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05002963 tmout++; /* very small timeouts are adjusted to a minimum of 1ms */
Mark Lakes56cc1252018-03-27 09:48:06 +02002964
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002965 /* Check if we run on the same thread than the xreator thread.
2966 * We cannot access to the socket if the thread is different.
2967 */
2968 if (socket->tid != tid)
2969 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2970
Mark Lakes56cc1252018-03-27 09:48:06 +02002971 /* check for connection break. If some data were read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002972 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002973 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002974 hlua_pusherror(L, "socket: not yet initialised, you can't set timeouts.");
2975 WILL_LJMP(lua_error(L));
2976 return 0;
2977 }
Willy Tarreau5321da92022-05-06 11:57:34 +02002978
Willy Tarreau0698c802022-05-11 14:09:57 +02002979 s = appctx_strm(container_of(peer, struct hlua_csk_ctx, xref)->appctx);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002980
Cyril Bonté7bb63452018-08-17 23:51:02 +02002981 s->sess->fe->timeout.connect = tmout;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002982 s->req.rto = tmout;
2983 s->req.wto = tmout;
2984 s->res.rto = tmout;
2985 s->res.wto = tmout;
Cyril Bonté7bb63452018-08-17 23:51:02 +02002986 s->req.rex = tick_add_ifset(now_ms, tmout);
2987 s->req.wex = tick_add_ifset(now_ms, tmout);
2988 s->res.rex = tick_add_ifset(now_ms, tmout);
2989 s->res.wex = tick_add_ifset(now_ms, tmout);
2990
2991 s->task->expire = tick_add_ifset(now_ms, tmout);
2992 task_queue(s->task);
2993
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002994 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002995
Thierry Fourniere9636f12018-03-08 09:54:32 +01002996 lua_pushinteger(L, 1);
Tim Duesterhus119a5f12018-01-06 19:16:25 +01002997 return 1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002998}
2999
3000__LJMP static int hlua_socket_new(lua_State *L)
3001{
3002 struct hlua_socket *socket;
Willy Tarreau5321da92022-05-06 11:57:34 +02003003 struct hlua_csk_ctx *ctx;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003004 struct appctx *appctx;
3005
3006 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003007 if (!lua_checkstack(L, 3)) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003008 hlua_pusherror(L, "socket: full stack");
3009 goto out_fail_conf;
3010 }
3011
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003012 /* Create the object: obj[0] = userdata. */
3013 lua_newtable(L);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003014 socket = MAY_LJMP(lua_newuserdata(L, sizeof(*socket)));
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003015 lua_rawseti(L, -2, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003016 memset(socket, 0, sizeof(*socket));
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02003017 socket->tid = tid;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003018
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05003019 /* Check if the various memory pools are initialized. */
Willy Tarreaubafbe012017-11-24 17:34:44 +01003020 if (!pool_head_stream || !pool_head_buffer) {
Thierry FOURNIER4a6170c2015-03-09 17:07:10 +01003021 hlua_pusherror(L, "socket: uninitialized pools.");
3022 goto out_fail_conf;
3023 }
3024
Willy Tarreau87b09662015-04-03 00:22:06 +02003025 /* Pop a class stream metatable and affect it to the userdata. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003026 lua_rawgeti(L, LUA_REGISTRYINDEX, class_socket_ref);
3027 lua_setmetatable(L, -2);
3028
Willy Tarreaud420a972015-04-06 00:39:18 +02003029 /* Create the applet context */
Christopher Faulet6095d572022-05-16 17:09:48 +02003030 appctx = appctx_new_here(&update_applet, NULL);
Willy Tarreau61cf7c82015-04-06 00:48:33 +02003031 if (!appctx) {
3032 hlua_pusherror(L, "socket: out of memory");
Christopher Fauleta9e8b392022-03-23 11:01:09 +01003033 goto out_fail_conf;
Willy Tarreau61cf7c82015-04-06 00:48:33 +02003034 }
Willy Tarreau5321da92022-05-06 11:57:34 +02003035 ctx = applet_reserve_svcctx(appctx, sizeof(*ctx));
3036 ctx->connected = 0;
Willy Tarreau5321da92022-05-06 11:57:34 +02003037 ctx->die = 0;
3038 LIST_INIT(&ctx->wake_on_write);
3039 LIST_INIT(&ctx->wake_on_read);
Willy Tarreaub2bf8332015-04-04 15:58:58 +02003040
Christopher Faulet5f35a3e2022-05-12 15:31:05 +02003041 if (appctx_init(appctx) == -1) {
3042 hlua_pusherror(L, "socket: fail to init applet.");
Christopher Faulet13a35e52021-12-20 15:34:16 +01003043 goto out_fail_appctx;
3044 }
3045
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003046 /* Initialise cross reference between stream and Lua socket object. */
Willy Tarreau5321da92022-05-06 11:57:34 +02003047 xref_create(&socket->xref, &ctx->xref);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003048 return 1;
3049
Christopher Faulet13a35e52021-12-20 15:34:16 +01003050 out_fail_appctx:
Christopher Faulet5f35a3e2022-05-12 15:31:05 +02003051 appctx_free_on_early_error(appctx);
Willy Tarreaud420a972015-04-06 00:39:18 +02003052 out_fail_conf:
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003053 WILL_LJMP(lua_error(L));
3054 return 0;
3055}
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01003056
3057/*
3058 *
3059 *
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003060 * Class Channel
3061 *
3062 *
3063 */
3064
3065/* Returns the struct hlua_channel join to the class channel in the
3066 * stack entry "ud" or throws an argument error.
3067 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01003068__LJMP static struct channel *hlua_checkchannel(lua_State *L, int ud)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003069{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003070 return MAY_LJMP(hlua_checkudata(L, ud, class_channel_ref));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003071}
3072
Willy Tarreau47860ed2015-03-10 14:07:50 +01003073/* Pushes the channel onto the top of the stack. If the stask does not have a
3074 * free slots, the function fails and returns 0;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003075 */
Willy Tarreau2a71af42015-03-10 13:51:50 +01003076static int hlua_channel_new(lua_State *L, struct channel *channel)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003077{
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003078 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003079 if (!lua_checkstack(L, 3))
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003080 return 0;
3081
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003082 lua_newtable(L);
Willy Tarreau47860ed2015-03-10 14:07:50 +01003083 lua_pushlightuserdata(L, channel);
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003084 lua_rawseti(L, -2, 0);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003085
3086 /* Pop a class sesison metatable and affect it to the userdata. */
3087 lua_rawgeti(L, LUA_REGISTRYINDEX, class_channel_ref);
3088 lua_setmetatable(L, -2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003089 return 1;
3090}
3091
Christopher Faulet9f55a502020-02-25 15:21:02 +01003092/* Helper function returning a filter attached to a channel at the position <ud>
3093 * in the stack, filling the current offset and length of the filter. If no
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05003094 * filter is attached, NULL is returned and <offset> and <len> are not
Christopher Faulet9f55a502020-02-25 15:21:02 +01003095 * initialized.
3096 */
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003097static struct filter *hlua_channel_filter(lua_State *L, int ud, struct channel *chn, size_t *offset, size_t *len)
Christopher Faulet9f55a502020-02-25 15:21:02 +01003098{
3099 struct filter *filter = NULL;
3100
3101 if (lua_getfield(L, ud, "__filter") == LUA_TLIGHTUSERDATA) {
3102 struct hlua_flt_ctx *flt_ctx;
3103
3104 filter = lua_touserdata (L, -1);
3105 flt_ctx = filter->ctx;
3106 if (hlua_filter_from_payload(filter)) {
3107 *offset = flt_ctx->cur_off[CHN_IDX(chn)];
3108 *len = flt_ctx->cur_len[CHN_IDX(chn)];
3109 }
3110 }
3111
3112 lua_pop(L, 1);
3113 return filter;
3114}
3115
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003116/* Copies <len> bytes of data present in the channel's buffer, starting at the
3117* offset <offset>, and put it in a LUA string variable. It is the caller
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003118* responsibility to ensure <len> and <offset> are valid. It always return the
3119* length of the built string. <len> may be 0, in this case, an empty string is
3120* created and 0 is returned.
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003121*/
3122static inline int _hlua_channel_dup(struct channel *chn, lua_State *L, size_t offset, size_t len)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003123{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003124 size_t block1, block2;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003125 luaL_Buffer b;
3126
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003127 block1 = len;
3128 if (block1 > b_contig_data(&chn->buf, b_peek_ofs(&chn->buf, offset)))
3129 block1 = b_contig_data(&chn->buf, b_peek_ofs(&chn->buf, offset));
3130 block2 = len - block1;
3131
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003132 luaL_buffinit(L, &b);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003133 luaL_addlstring(&b, b_peek(&chn->buf, offset), block1);
3134 if (block2)
3135 luaL_addlstring(&b, b_orig(&chn->buf), block2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003136 luaL_pushresult(&b);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003137 return len;
3138}
3139
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003140/* Inserts the string <str> to the channel's buffer at the offset <offset>. This
3141 * function returns -1 if data cannot be copied. Otherwise, it returns the
3142 * number of bytes copied.
3143 */
3144static int _hlua_channel_insert(struct channel *chn, lua_State *L, struct ist str, size_t offset)
3145{
3146 int ret = 0;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003147
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003148 /* Nothing to do, just return */
3149 if (unlikely(istlen(str) == 0))
3150 goto end;
3151
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003152 if (istlen(str) > c_room(chn)) {
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003153 ret = -1;
3154 goto end;
3155 }
3156 ret = b_insert_blk(&chn->buf, offset, istptr(str), istlen(str));
3157
3158 end:
3159 return ret;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003160}
3161
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003162/* Removes <len> bytes of data at the absolute position <offset>.
3163 */
3164static void _hlua_channel_delete(struct channel *chn, size_t offset, size_t len)
3165{
3166 size_t end = offset + len;
3167
3168 if (b_peek(&chn->buf, end) != b_tail(&chn->buf))
3169 b_move(&chn->buf, b_peek_ofs(&chn->buf, end),
3170 b_data(&chn->buf) - end, -len);
3171 b_sub(&chn->buf, len);
3172}
3173
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003174/* Copies input data in the channel's buffer. It is possible to set a specific
3175 * offset (0 by default) and a length (all remaining input data starting for the
3176 * offset by default). If there is not enough input data and more data can be
3177 * received, this function yields.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003178 *
3179 * From an action, All input data are considered. For a filter, the offset and
3180 * the length of input data to consider are retrieved from the filter context.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003181 */
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003182__LJMP static int hlua_channel_get_data_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003183{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003184 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003185 struct filter *filter;
3186 size_t input, output;
3187 int offset, len;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003188
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003189 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003190
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003191 output = co_data(chn);
3192 input = ci_data(chn);
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003193
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003194 filter = hlua_channel_filter(L, 1, chn, &output, &input);
3195 if (filter && !hlua_filter_from_payload(filter))
3196 WILL_LJMP(lua_error(L));
3197
3198 offset = output;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003199 if (lua_gettop(L) > 1) {
3200 offset = MAY_LJMP(luaL_checkinteger(L, 2));
3201 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02003202 offset = MAX(0, (int)input + offset);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003203 offset += output;
3204 if (offset < output || offset > input + output) {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003205 lua_pushfstring(L, "offset out of range.");
3206 WILL_LJMP(lua_error(L));
3207 }
3208 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003209 len = output + input - offset;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003210 if (lua_gettop(L) == 3) {
3211 len = MAY_LJMP(luaL_checkinteger(L, 3));
3212 if (!len)
3213 goto dup;
3214 if (len == -1)
3215 len = global.tune.bufsize;
3216 if (len < 0) {
3217 lua_pushfstring(L, "length out of range.");
3218 WILL_LJMP(lua_error(L));
3219 }
3220 }
3221
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003222 if (offset + len > output + input) {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003223 if (!HLUA_CANT_YIELD(hlua_gethlua(L)) && !channel_input_closed(chn) && channel_may_recv(chn)) {
3224 /* Yield waiting for more data, as requested */
3225 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_get_data_yield, TICK_ETERNITY, 0));
3226 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003227 len = output + input - offset;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003228 }
3229
3230 dup:
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003231 _hlua_channel_dup(chn, L, offset, len);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003232 return 1;
3233}
3234
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003235/* Copies the first line (including the trailing LF) of input data in the
3236 * channel's buffer. It is possible to set a specific offset (0 by default) and
3237 * a length (all remaining input data starting for the offset by default). If
3238 * there is not enough input data and more data can be received, the function
3239 * yields. If a length is explicitly specified, no more data are
3240 * copied. Otherwise, if no LF is found and more data can be received, this
3241 * function yields.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003242 *
3243 * From an action, All input data are considered. For a filter, the offset and
3244 * the length of input data to consider are retrieved from the filter context.
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003245 */
3246__LJMP static int hlua_channel_get_line_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003247{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003248 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003249 struct filter *filter;
3250 size_t l, input, output;
3251 int offset, len;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003252
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003253 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003254 output = co_data(chn);
3255 input = ci_data(chn);
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003256
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003257 filter = hlua_channel_filter(L, 1, chn, &output, &input);
3258 if (filter && !hlua_filter_from_payload(filter))
3259 WILL_LJMP(lua_error(L));
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003260
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003261 offset = output;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003262 if (lua_gettop(L) > 1) {
3263 offset = MAY_LJMP(luaL_checkinteger(L, 2));
3264 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02003265 offset = MAX(0, (int)input + offset);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003266 offset += output;
3267 if (offset < output || offset > input + output) {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003268 lua_pushfstring(L, "offset out of range.");
3269 WILL_LJMP(lua_error(L));
3270 }
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003271 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003272
3273 len = output + input - offset;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003274 if (lua_gettop(L) == 3) {
3275 len = MAY_LJMP(luaL_checkinteger(L, 3));
3276 if (!len)
3277 goto dup;
3278 if (len == -1)
3279 len = global.tune.bufsize;
3280 if (len < 0) {
3281 lua_pushfstring(L, "length out of range.");
3282 WILL_LJMP(lua_error(L));
3283 }
3284 }
3285
3286 for (l = 0; l < len; l++) {
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003287 if (l + offset >= output + input)
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003288 break;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003289 if (*(b_peek(&chn->buf, offset + l)) == '\n') {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003290 len = l+1;
3291 goto dup;
3292 }
3293 }
3294
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003295 if (offset + len > output + input) {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003296 if (!HLUA_CANT_YIELD(hlua_gethlua(L)) && !channel_input_closed(chn) && channel_may_recv(chn)) {
3297 /* Yield waiting for more data */
3298 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_get_line_yield, TICK_ETERNITY, 0));
3299 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003300 len = output + input - offset;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003301 }
3302
3303 dup:
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003304 _hlua_channel_dup(chn, L, offset, len);
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003305 return 1;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003306}
3307
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003308/* [ DEPRECATED ]
3309 *
3310 * Duplicate all input data foud in the channel's buffer. The data are not
3311 * removed from the buffer. This function relies on _hlua_channel_dup().
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003312 *
3313 * From an action, All input data are considered. For a filter, the offset and
3314 * the length of input data to consider are retrieved from the filter context.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003315 */
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003316__LJMP static int hlua_channel_dup(lua_State *L)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003317{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003318 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003319 struct filter *filter;
3320 size_t offset, len;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003321
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003322 MAY_LJMP(check_args(L, 1, "dup"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003323 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003324 if (IS_HTX_STRM(chn_strm(chn))) {
3325 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3326 WILL_LJMP(lua_error(L));
3327 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003328
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003329 offset = co_data(chn);
3330 len = ci_data(chn);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003331
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003332 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3333 if (filter && !hlua_filter_from_payload(filter))
3334 WILL_LJMP(lua_error(L));
3335
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003336 if (!ci_data(chn) && channel_input_closed(chn)) {
3337 lua_pushnil(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003338 return 1;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003339 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003340
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003341 _hlua_channel_dup(chn, L, offset, len);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003342 return 1;
3343}
3344
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003345/* [ DEPRECATED ]
3346 *
3347 * Get all input data foud in the channel's buffer. The data are removed from
3348 * the buffer after the copy. This function relies on _hlua_channel_dup() and
3349 * _hlua_channel_delete().
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003350 *
3351 * From an action, All input data are considered. For a filter, the offset and
3352 * the length of input data to consider are retrieved from the filter context.
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003353 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003354__LJMP static int hlua_channel_get(lua_State *L)
3355{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003356 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003357 struct filter *filter;
3358 size_t offset, len;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003359 int ret;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003360
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003361 MAY_LJMP(check_args(L, 1, "get"));
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003362 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3363 if (IS_HTX_STRM(chn_strm(chn))) {
3364 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3365 WILL_LJMP(lua_error(L));
3366 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003367
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003368 offset = co_data(chn);
3369 len = ci_data(chn);
3370
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003371 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3372 if (filter && !hlua_filter_from_payload(filter))
3373 WILL_LJMP(lua_error(L));
3374
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003375 if (!ci_data(chn) && channel_input_closed(chn)) {
3376 lua_pushnil(L);
3377 return 1;
3378 }
3379
3380 ret = _hlua_channel_dup(chn, L, offset, len);
3381 _hlua_channel_delete(chn, offset, ret);
3382 return 1;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003383}
3384
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003385/* This functions consumes and returns one line. If the channel is closed,
3386 * and the last data does not contains a final '\n', the data are returned
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003387 * without the final '\n'. When no more data are available, it returns nil
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003388 * value.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003389 *
3390 * From an action, All input data are considered. For a filter, the offset and
3391 * the length of input data to consider are retrieved from the filter context.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003392 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003393__LJMP static int hlua_channel_getline_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003394{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003395 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003396 struct filter *filter;
3397 size_t l, offset, len;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003398 int ret;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003399
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003400 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003401
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003402 offset = co_data(chn);
3403 len = ci_data(chn);
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003404
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003405 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3406 if (filter && !hlua_filter_from_payload(filter))
3407 WILL_LJMP(lua_error(L));
3408
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003409 if (!ci_data(chn) && channel_input_closed(chn)) {
3410 lua_pushnil(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003411 return 1;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003412 }
3413
3414 for (l = 0; l < len; l++) {
3415 if (*(b_peek(&chn->buf, offset+l)) == '\n') {
3416 len = l+1;
3417 goto dup;
3418 }
3419 }
3420
3421 if (!HLUA_CANT_YIELD(hlua_gethlua(L)) && !channel_input_closed(chn) && channel_may_recv(chn)) {
3422 /* Yield waiting for more data */
3423 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_getline_yield, TICK_ETERNITY, 0));
3424 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003425
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003426 dup:
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003427 ret = _hlua_channel_dup(chn, L, offset, len);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003428 _hlua_channel_delete(chn, offset, ret);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003429 return 1;
3430}
3431
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003432/* [ DEPRECATED ]
3433 *
3434 * Check arguments for the function "hlua_channel_getline_yield".
3435 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003436__LJMP static int hlua_channel_getline(lua_State *L)
3437{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003438 struct channel *chn;
3439
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003440 MAY_LJMP(check_args(L, 1, "getline"));
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003441 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3442 if (IS_HTX_STRM(chn_strm(chn))) {
3443 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3444 WILL_LJMP(lua_error(L));
3445 }
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003446 return MAY_LJMP(hlua_channel_getline_yield(L, 0, 0));
3447}
3448
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003449/* Retrieves a given amount of input data at the given offset. By default all
3450 * available input data are returned. The offset may be negactive to start from
3451 * the end of input data. The length may be -1 to set it to the maximum buffer
3452 * size.
3453 */
3454__LJMP static int hlua_channel_get_data(lua_State *L)
3455{
3456 struct channel *chn;
3457
3458 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
3459 WILL_LJMP(luaL_error(L, "'data' expects at most 2 arguments"));
3460 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3461 if (IS_HTX_STRM(chn_strm(chn))) {
3462 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3463 WILL_LJMP(lua_error(L));
3464 }
3465 return MAY_LJMP(hlua_channel_get_data_yield(L, 0, 0));
3466}
3467
3468/* Retrieves a given amount of input data at the given offset. By default all
3469 * available input data are returned. The offset may be negactive to start from
3470 * the end of input data. The length may be -1 to set it to the maximum buffer
3471 * size.
3472 */
3473__LJMP static int hlua_channel_get_line(lua_State *L)
3474{
3475 struct channel *chn;
3476
3477 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
3478 WILL_LJMP(luaL_error(L, "'line' expects at most 2 arguments"));
3479 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3480 if (IS_HTX_STRM(chn_strm(chn))) {
3481 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3482 WILL_LJMP(lua_error(L));
3483 }
3484 return MAY_LJMP(hlua_channel_get_line_yield(L, 0, 0));
3485}
3486
3487/* Appends a string into the input side of channel. It returns the length of the
3488 * written string, or -1 if the channel is closed or if the buffer size is too
3489 * little for the data. 0 may be returned if nothing is copied. This function
3490 * does not yield.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003491 *
3492 * For a filter, the context is updated on success.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003493 */
Christopher Faulet23976d92021-08-06 09:59:49 +02003494__LJMP static int hlua_channel_append(lua_State *L)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003495{
Christopher Faulet23976d92021-08-06 09:59:49 +02003496 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003497 struct filter *filter;
Christopher Faulet23976d92021-08-06 09:59:49 +02003498 const char *str;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003499 size_t sz, offset, len;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003500 int ret;
Christopher Faulet23976d92021-08-06 09:59:49 +02003501
3502 MAY_LJMP(check_args(L, 2, "append"));
3503 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003504 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
Christopher Faulet1bb6afa2021-03-08 17:57:53 +01003505 if (IS_HTX_STRM(chn_strm(chn))) {
Thierry Fournier77016da2020-08-15 14:35:51 +02003506 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
Christopher Faulet3f829a42018-12-13 21:56:45 +01003507 WILL_LJMP(lua_error(L));
Thierry Fournier77016da2020-08-15 14:35:51 +02003508 }
Christopher Faulet3f829a42018-12-13 21:56:45 +01003509
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003510 offset = co_data(chn);
3511 len = ci_data(chn);
3512
3513 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3514 if (filter && !hlua_filter_from_payload(filter))
3515 WILL_LJMP(lua_error(L));
3516
3517 ret = _hlua_channel_insert(chn, L, ist2(str, sz), offset);
3518 if (ret > 0 && filter) {
3519 struct hlua_flt_ctx *flt_ctx = filter->ctx;
3520
3521 flt_update_offsets(filter, chn, ret);
3522 flt_ctx->cur_len[CHN_IDX(chn)] += ret;
3523 }
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003524 lua_pushinteger(L, ret);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003525 return 1;
3526}
3527
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003528/* Prepends a string into the input side of channel. It returns the length of the
3529 * written string, or -1 if the channel is closed or if the buffer size is too
3530 * little for the data. 0 may be returned if nothing is copied. This function
3531 * does not yield.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003532 *
3533 * For a filter, the context is updated on success.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003534 */
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003535__LJMP static int hlua_channel_prepend(lua_State *L)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003536{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003537 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003538 struct filter *filter;
Christopher Faulet23976d92021-08-06 09:59:49 +02003539 const char *str;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003540 size_t sz, offset, len;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003541 int ret;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003542
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003543 MAY_LJMP(check_args(L, 2, "prepend"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003544 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003545 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
3546 if (IS_HTX_STRM(chn_strm(chn))) {
3547 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3548 WILL_LJMP(lua_error(L));
3549 }
3550
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003551 offset = co_data(chn);
3552 len = ci_data(chn);
3553
3554 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3555 if (filter && !hlua_filter_from_payload(filter))
3556 WILL_LJMP(lua_error(L));
3557
3558 ret = _hlua_channel_insert(chn, L, ist2(str, sz), offset);
3559 if (ret > 0 && filter) {
3560 struct hlua_flt_ctx *flt_ctx = filter->ctx;
3561
3562 flt_update_offsets(filter, chn, ret);
3563 flt_ctx->cur_len[CHN_IDX(chn)] += ret;
3564 }
3565
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003566 lua_pushinteger(L, ret);
3567 return 1;
3568}
3569
3570/* Inserts a given amount of input data at the given offset by a string
3571 * content. By default the string is appended at the end of input data. It
3572 * returns the length of the written string, or -1 if the channel is closed or
3573 * if the buffer size is too little for the data.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003574 *
3575 * For a filter, the context is updated on success.
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003576 */
3577__LJMP static int hlua_channel_insert_data(lua_State *L)
3578{
3579 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003580 struct filter *filter;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003581 const char *str;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003582 size_t sz, input, output;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003583 int ret, offset;
3584
3585 if (lua_gettop(L) < 2 || lua_gettop(L) > 3)
3586 WILL_LJMP(luaL_error(L, "'insert' expects at least 1 argument and at most 2 arguments"));
3587 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3588 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003589
3590 output = co_data(chn);
3591 input = ci_data(chn);
3592
3593 filter = hlua_channel_filter(L, 1, chn, &output, &input);
3594 if (filter && !hlua_filter_from_payload(filter))
3595 WILL_LJMP(lua_error(L));
3596
3597 offset = input + output;
3598 if (lua_gettop(L) > 2) {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003599 offset = MAY_LJMP(luaL_checkinteger(L, 3));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003600 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02003601 offset = MAX(0, (int)input + offset);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003602 offset += output;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003603 if (offset < output || offset > output + input) {
3604 lua_pushfstring(L, "offset out of range.");
3605 WILL_LJMP(lua_error(L));
3606 }
3607 }
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003608 if (IS_HTX_STRM(chn_strm(chn))) {
3609 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3610 WILL_LJMP(lua_error(L));
3611 }
3612
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003613 ret = _hlua_channel_insert(chn, L, ist2(str, sz), offset);
3614 if (ret > 0 && filter) {
3615 struct hlua_flt_ctx *flt_ctx = filter->ctx;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003616
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003617 flt_update_offsets(filter, chn, ret);
3618 flt_ctx->cur_len[CHN_IDX(chn)] += ret;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003619 }
3620
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003621 lua_pushinteger(L, ret);
3622 return 1;
3623}
3624/* Replaces a given amount of input data at the given offset by a string
3625 * content. By default all remaining data are removed (offset = 0 and len =
3626 * -1). It returns the length of the written string, or -1 if the channel is
3627 * closed or if the buffer size is too little for the data.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003628 *
3629 * For a filter, the context is updated on success.
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003630 */
3631__LJMP static int hlua_channel_set_data(lua_State *L)
3632{
3633 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003634 struct filter *filter;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003635 const char *str;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003636 size_t sz, input, output;
3637 int ret, offset, len;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003638
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003639 if (lua_gettop(L) < 2 || lua_gettop(L) > 4)
3640 WILL_LJMP(luaL_error(L, "'set' expects at least 1 argument and at most 3 arguments"));
3641 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3642 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003643
Christopher Faulet1bb6afa2021-03-08 17:57:53 +01003644 if (IS_HTX_STRM(chn_strm(chn))) {
Thierry Fournier77016da2020-08-15 14:35:51 +02003645 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
Christopher Faulet3f829a42018-12-13 21:56:45 +01003646 WILL_LJMP(lua_error(L));
Thierry Fournier77016da2020-08-15 14:35:51 +02003647 }
Christopher Faulet3f829a42018-12-13 21:56:45 +01003648
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003649 output = co_data(chn);
3650 input = ci_data(chn);
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003651
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003652 filter = hlua_channel_filter(L, 1, chn, &output, &input);
3653 if (filter && !hlua_filter_from_payload(filter))
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003654 WILL_LJMP(lua_error(L));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003655
3656 offset = output;
3657 if (lua_gettop(L) > 2) {
3658 offset = MAY_LJMP(luaL_checkinteger(L, 3));
3659 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02003660 offset = MAX(0, (int)input + offset);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003661 offset += output;
3662 if (offset < output || offset > input + output) {
3663 lua_pushfstring(L, "offset out of range.");
3664 WILL_LJMP(lua_error(L));
3665 }
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003666 }
3667
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003668 len = output + input - offset;
3669 if (lua_gettop(L) == 4) {
3670 len = MAY_LJMP(luaL_checkinteger(L, 4));
3671 if (!len)
3672 goto set;
3673 if (len == -1)
3674 len = output + input - offset;
3675 if (len < 0 || offset + len > output + input) {
3676 lua_pushfstring(L, "length out of range.");
3677 WILL_LJMP(lua_error(L));
3678 }
3679 }
3680
3681 set:
Christopher Faulet23976d92021-08-06 09:59:49 +02003682 /* Be sure we can copied the string once input data will be removed. */
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003683 if (sz > c_room(chn) + len)
Christopher Faulet23976d92021-08-06 09:59:49 +02003684 lua_pushinteger(L, -1);
3685 else {
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003686 _hlua_channel_delete(chn, offset, len);
3687 ret = _hlua_channel_insert(chn, L, ist2(str, sz), offset);
3688 if (filter) {
3689 struct hlua_flt_ctx *flt_ctx = filter->ctx;
3690
3691 len -= (ret > 0 ? ret : 0);
3692 flt_update_offsets(filter, chn, -len);
3693 flt_ctx->cur_len[CHN_IDX(chn)] -= len;
3694 }
3695
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003696 lua_pushinteger(L, ret);
Christopher Faulet23976d92021-08-06 09:59:49 +02003697 }
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003698 return 1;
3699}
3700
3701/* Removes a given amount of input data at the given offset. By default all
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003702 * input data are removed (offset = 0 and len = -1). It returns the amount of
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003703 * the removed data.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003704 *
3705 * For a filter, the context is updated on success.
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003706 */
3707__LJMP static int hlua_channel_del_data(lua_State *L)
3708{
3709 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003710 struct filter *filter;
3711 size_t input, output;
3712 int offset, len;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003713
3714 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
3715 WILL_LJMP(luaL_error(L, "'remove' expects at most 2 arguments"));
3716 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003717
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003718 if (IS_HTX_STRM(chn_strm(chn))) {
3719 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3720 WILL_LJMP(lua_error(L));
3721 }
3722
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003723 output = co_data(chn);
3724 input = ci_data(chn);
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003725
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003726 filter = hlua_channel_filter(L, 1, chn, &output, &input);
3727 if (filter && !hlua_filter_from_payload(filter))
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003728 WILL_LJMP(lua_error(L));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003729
3730 offset = output;
Boyang Lie0c54352022-05-10 17:47:23 +00003731 if (lua_gettop(L) > 1) {
3732 offset = MAY_LJMP(luaL_checkinteger(L, 2));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003733 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02003734 offset = MAX(0, (int)input + offset);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003735 offset += output;
3736 if (offset < output || offset > input + output) {
3737 lua_pushfstring(L, "offset out of range.");
3738 WILL_LJMP(lua_error(L));
3739 }
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003740 }
3741
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003742 len = output + input - offset;
Boyang Lie0c54352022-05-10 17:47:23 +00003743 if (lua_gettop(L) == 3) {
3744 len = MAY_LJMP(luaL_checkinteger(L, 3));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003745 if (!len)
3746 goto end;
3747 if (len == -1)
3748 len = output + input - offset;
3749 if (len < 0 || offset + len > output + input) {
3750 lua_pushfstring(L, "length out of range.");
3751 WILL_LJMP(lua_error(L));
3752 }
3753 }
3754
3755 _hlua_channel_delete(chn, offset, len);
3756 if (filter) {
3757 struct hlua_flt_ctx *flt_ctx = filter->ctx;
3758
3759 flt_update_offsets(filter, chn, -len);
3760 flt_ctx->cur_len[CHN_IDX(chn)] -= len;
3761 }
3762
3763 end:
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003764 lua_pushinteger(L, len);
Christopher Faulet23976d92021-08-06 09:59:49 +02003765 return 1;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003766}
3767
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003768/* Append data in the output side of the buffer. This data is immediately
3769 * sent. The function returns the amount of data written. If the buffer
3770 * cannot contain the data, the function yields. The function returns -1
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003771 * if the channel is closed.
3772 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003773__LJMP static int hlua_channel_send_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003774{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003775 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003776 struct filter *filter;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003777 const char *str;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003778 size_t offset, len, sz;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003779 int l, ret;
Thierry Fournier4234dbd2020-11-28 13:18:23 +01003780 struct hlua *hlua;
3781
3782 /* Get hlua struct, or NULL if we execute from main lua state */
3783 hlua = hlua_gethlua(L);
3784 if (!hlua) {
3785 lua_pushnil(L);
3786 return 1;
3787 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003788
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003789 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3790 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
3791 l = MAY_LJMP(luaL_checkinteger(L, 3));
Christopher Faulet3f829a42018-12-13 21:56:45 +01003792
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003793 offset = co_data(chn);
3794 len = ci_data(chn);
3795
3796 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3797 if (filter && !hlua_filter_from_payload(filter))
3798 WILL_LJMP(lua_error(L));
3799
3800
Willy Tarreau47860ed2015-03-10 14:07:50 +01003801 if (unlikely(channel_output_closed(chn))) {
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003802 lua_pushinteger(L, -1);
3803 return 1;
3804 }
3805
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003806 len = c_room(chn);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003807 if (len > sz -l) {
3808 if (filter) {
3809 lua_pushinteger(L, -1);
3810 return 1;
3811 }
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003812 len = sz - l;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003813 }
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01003814
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003815 ret = _hlua_channel_insert(chn, L, ist2(str, len), offset);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003816 if (ret == -1) {
3817 lua_pop(L, 1);
3818 lua_pushinteger(L, -1);
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01003819 return 1;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003820 }
3821 if (ret) {
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003822 if (filter) {
3823 struct hlua_flt_ctx *flt_ctx = filter->ctx;
3824
3825
3826 flt_update_offsets(filter, chn, ret);
3827 FLT_OFF(filter, chn) += ret;
3828 flt_ctx->cur_off[CHN_IDX(chn)] += ret;
3829 }
3830 else
3831 c_adv(chn, ret);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003832
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003833 l += ret;
3834 lua_pop(L, 1);
3835 lua_pushinteger(L, l);
3836 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003837
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003838 if (l < sz) {
3839 /* Yield only if the channel's output is not empty.
3840 * Otherwise it means we cannot add more data. */
3841 if (co_data(chn) == 0 || HLUA_CANT_YIELD(hlua_gethlua(L)))
Christopher Faulet2e60aa42021-08-05 11:58:37 +02003842 return 1;
3843
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003844 /* If we are waiting for space in the response buffer, we
3845 * must set the flag WAKERESWR. This flag required the task
3846 * wake up if any activity is detected on the response buffer.
3847 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01003848 if (chn->flags & CF_ISRESP)
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003849 HLUA_SET_WAKERESWR(hlua);
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01003850 else
3851 HLUA_SET_WAKEREQWR(hlua);
Willy Tarreau9635e032018-10-16 17:52:55 +02003852 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003853 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003854
3855 return 1;
3856}
3857
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05003858/* Just a wrapper of "_hlua_channel_send". This wrapper permits
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003859 * yield the LUA process, and resume it without checking the
3860 * input arguments.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003861 *
3862 * This function cannot be called from a filter.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003863 */
3864__LJMP static int hlua_channel_send(lua_State *L)
3865{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003866 struct channel *chn;
3867
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003868 MAY_LJMP(check_args(L, 2, "send"));
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003869 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3870 if (IS_HTX_STRM(chn_strm(chn))) {
3871 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3872 WILL_LJMP(lua_error(L));
3873 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003874 lua_pushinteger(L, 0);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003875 return MAY_LJMP(hlua_channel_send_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003876}
3877
3878/* This function forward and amount of butes. The data pass from
3879 * the input side of the buffer to the output side, and can be
3880 * forwarded. This function never fails.
3881 *
3882 * The Lua function takes an amount of bytes to be forwarded in
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05003883 * input. It returns the number of bytes forwarded.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003884 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003885__LJMP static int hlua_channel_forward_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003886{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003887 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003888 struct filter *filter;
3889 size_t offset, len, fwd;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003890 int l, max;
Thierry Fournier4234dbd2020-11-28 13:18:23 +01003891 struct hlua *hlua;
3892
3893 /* Get hlua struct, or NULL if we execute from main lua state */
3894 hlua = hlua_gethlua(L);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003895 if (!hlua) {
3896 lua_pushnil(L);
Thierry Fournier4234dbd2020-11-28 13:18:23 +01003897 return 1;
Thierry Fournier77016da2020-08-15 14:35:51 +02003898 }
Christopher Faulet3f829a42018-12-13 21:56:45 +01003899
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003900 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003901 fwd = MAY_LJMP(luaL_checkinteger(L, 2));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003902 l = MAY_LJMP(luaL_checkinteger(L, -1));
3903
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003904 offset = co_data(chn);
3905 len = ci_data(chn);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003906
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003907 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3908 if (filter && !hlua_filter_from_payload(filter))
3909 WILL_LJMP(lua_error(L));
3910
3911 max = fwd - l;
3912 if (max > len)
3913 max = len;
3914
3915 if (filter) {
3916 struct hlua_flt_ctx *flt_ctx = filter->ctx;
3917
3918 FLT_OFF(filter, chn) += max;
3919 flt_ctx->cur_off[CHN_IDX(chn)] += max;
3920 flt_ctx->cur_len[CHN_IDX(chn)] -= max;
3921 }
3922 else
3923 channel_forward(chn, max);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003924
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003925 l += max;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003926 lua_pop(L, 1);
3927 lua_pushinteger(L, l);
3928
3929 /* Check if it miss bytes to forward. */
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003930 if (l < fwd) {
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003931 /* The the input channel or the output channel are closed, we
3932 * must return the amount of data forwarded.
3933 */
Christopher Faulet2e60aa42021-08-05 11:58:37 +02003934 if (channel_input_closed(chn) || channel_output_closed(chn) || HLUA_CANT_YIELD(hlua_gethlua(L)))
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003935 return 1;
3936
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003937 /* If we are waiting for space data in the response buffer, we
3938 * must set the flag WAKERESWR. This flag required the task
3939 * wake up if any activity is detected on the response buffer.
3940 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01003941 if (chn->flags & CF_ISRESP)
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003942 HLUA_SET_WAKERESWR(hlua);
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01003943 else
3944 HLUA_SET_WAKEREQWR(hlua);
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003945
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003946 /* Otherwise, we can yield waiting for new data in the inpout side. */
Willy Tarreau9635e032018-10-16 17:52:55 +02003947 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_forward_yield, TICK_ETERNITY, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003948 }
3949
3950 return 1;
3951}
3952
3953/* Just check the input and prepare the stack for the previous
3954 * function "hlua_channel_forward_yield"
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003955 *
3956 * This function cannot be called from a filter.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003957 */
3958__LJMP static int hlua_channel_forward(lua_State *L)
3959{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003960 struct channel *chn;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003961
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003962 MAY_LJMP(check_args(L, 2, "forward"));
3963 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3964 if (IS_HTX_STRM(chn_strm(chn))) {
3965 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3966 WILL_LJMP(lua_error(L));
3967 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003968 lua_pushinteger(L, 0);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003969 return MAY_LJMP(hlua_channel_forward_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003970}
3971
3972/* Just returns the number of bytes available in the input
3973 * side of the buffer. This function never fails.
3974 */
3975__LJMP static int hlua_channel_get_in_len(lua_State *L)
3976{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003977 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003978 struct filter *filter;
3979 size_t output, input;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003980
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003981 MAY_LJMP(check_args(L, 1, "input"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003982 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003983
3984 output = co_data(chn);
3985 input = ci_data(chn);
3986 filter = hlua_channel_filter(L, 1, chn, &output, &input);
3987 if (filter || !IS_HTX_STRM(chn_strm(chn)))
3988 lua_pushinteger(L, input);
3989 else {
Christopher Fauleta3ceac12018-12-14 13:39:09 +01003990 struct htx *htx = htxbuf(&chn->buf);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003991
Christopher Fauleta3ceac12018-12-14 13:39:09 +01003992 lua_pushinteger(L, htx->data - co_data(chn));
3993 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003994 return 1;
3995}
3996
Thierry FOURNIER / OZON.IO65192f32016-11-07 15:28:40 +01003997/* Returns true if the channel is full. */
3998__LJMP static int hlua_channel_is_full(lua_State *L)
3999{
4000 struct channel *chn;
Thierry FOURNIER / OZON.IO65192f32016-11-07 15:28:40 +01004001
4002 MAY_LJMP(check_args(L, 1, "is_full"));
4003 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Faulet0ec740e2020-02-26 11:59:19 +01004004 /* ignore the reserve, we are not on a producer side (ie in an
4005 * applet).
4006 */
4007 lua_pushboolean(L, channel_full(chn, 0));
Thierry FOURNIER / OZON.IO65192f32016-11-07 15:28:40 +01004008 return 1;
4009}
4010
Christopher Faulet6a79fc12021-08-06 16:02:36 +02004011/* Returns true if the channel may still receive data. */
4012__LJMP static int hlua_channel_may_recv(lua_State *L)
4013{
4014 struct channel *chn;
4015
4016 MAY_LJMP(check_args(L, 1, "may_recv"));
4017 chn = MAY_LJMP(hlua_checkchannel(L, 1));
4018 lua_pushboolean(L, (!channel_input_closed(chn) && channel_may_recv(chn)));
4019 return 1;
4020}
4021
Christopher Faulet2ac9ba22020-02-25 10:15:50 +01004022/* Returns true if the channel is the response channel. */
4023__LJMP static int hlua_channel_is_resp(lua_State *L)
4024{
4025 struct channel *chn;
4026
4027 MAY_LJMP(check_args(L, 1, "is_resp"));
4028 chn = MAY_LJMP(hlua_checkchannel(L, 1));
4029
4030 lua_pushboolean(L, !!(chn->flags & CF_ISRESP));
4031 return 1;
4032}
4033
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004034/* Just returns the number of bytes available in the output
4035 * side of the buffer. This function never fails.
4036 */
4037__LJMP static int hlua_channel_get_out_len(lua_State *L)
4038{
Willy Tarreau47860ed2015-03-10 14:07:50 +01004039 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004040 size_t output, input;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004041
Christopher Faulet6a79fc12021-08-06 16:02:36 +02004042 MAY_LJMP(check_args(L, 1, "output"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004043 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004044
4045 output = co_data(chn);
4046 input = ci_data(chn);
4047 hlua_channel_filter(L, 1, chn, &output, &input);
4048
4049 lua_pushinteger(L, output);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004050 return 1;
4051}
4052
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004053/*
4054 *
4055 *
4056 * Class Fetches
4057 *
4058 *
4059 */
4060
4061/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02004062 * a class stream, otherwise it throws an error.
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004063 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004064__LJMP static struct hlua_smp *hlua_checkfetches(lua_State *L, int ud)
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004065{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004066 return MAY_LJMP(hlua_checkudata(L, ud, class_fetches_ref));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004067}
4068
4069/* This function creates and push in the stack a fetch object according
4070 * with a current TXN.
4071 */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004072static int hlua_fetches_new(lua_State *L, struct hlua_txn *txn, unsigned int flags)
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004073{
Willy Tarreau7073c472015-04-06 11:15:40 +02004074 struct hlua_smp *hsmp;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004075
4076 /* Check stack size. */
4077 if (!lua_checkstack(L, 3))
4078 return 0;
4079
4080 /* Create the object: obj[0] = userdata.
4081 * Note that the base of the Fetches object is the
4082 * transaction object.
4083 */
4084 lua_newtable(L);
Willy Tarreau7073c472015-04-06 11:15:40 +02004085 hsmp = lua_newuserdata(L, sizeof(*hsmp));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004086 lua_rawseti(L, -2, 0);
4087
Willy Tarreau7073c472015-04-06 11:15:40 +02004088 hsmp->s = txn->s;
4089 hsmp->p = txn->p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01004090 hsmp->dir = txn->dir;
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004091 hsmp->flags = flags;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004092
4093 /* Pop a class sesison metatable and affect it to the userdata. */
4094 lua_rawgeti(L, LUA_REGISTRYINDEX, class_fetches_ref);
4095 lua_setmetatable(L, -2);
4096
4097 return 1;
4098}
4099
4100/* This function is an LUA binding. It is called with each sample-fetch.
4101 * It uses closure argument to store the associated sample-fetch. It
4102 * returns only one argument or throws an error. An error is thrown
4103 * only if an error is encountered during the argument parsing. If
4104 * the "sample-fetch" function fails, nil is returned.
4105 */
4106__LJMP static int hlua_run_sample_fetch(lua_State *L)
4107{
Willy Tarreaub2ccb562015-04-06 11:11:15 +02004108 struct hlua_smp *hsmp;
Willy Tarreau2ec22742015-03-10 14:27:20 +01004109 struct sample_fetch *f;
Frédéric Lécaillef874a832018-06-15 13:56:04 +02004110 struct arg args[ARGM_NBARGS + 1] = {{0}};
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004111 int i;
4112 struct sample smp;
4113
4114 /* Get closure arguments. */
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004115 f = lua_touserdata(L, lua_upvalueindex(1));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004116
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004117 /* Get traditional arguments. */
Willy Tarreaub2ccb562015-04-06 11:11:15 +02004118 hsmp = MAY_LJMP(hlua_checkfetches(L, 1));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004119
Thierry FOURNIERca988662015-12-20 18:43:03 +01004120 /* Check execution authorization. */
4121 if (f->use & SMP_USE_HTTP_ANY &&
4122 !(hsmp->flags & HLUA_F_MAY_USE_HTTP)) {
4123 lua_pushfstring(L, "the sample-fetch '%s' needs an HTTP parser which "
4124 "is not available in Lua services", f->kw);
4125 WILL_LJMP(lua_error(L));
4126 }
4127
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004128 /* Get extra arguments. */
4129 for (i = 0; i < lua_gettop(L) - 1; i++) {
4130 if (i >= ARGM_NBARGS)
4131 break;
4132 hlua_lua2arg(L, i + 2, &args[i]);
4133 }
4134 args[i].type = ARGT_STOP;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004135 args[i].data.str.area = NULL;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004136
4137 /* Check arguments. */
Willy Tarreaub2ccb562015-04-06 11:11:15 +02004138 MAY_LJMP(hlua_lua2arg_check(L, 2, args, f->arg_mask, hsmp->p));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004139
4140 /* Run the special args checker. */
Willy Tarreau2ec22742015-03-10 14:27:20 +01004141 if (f->val_args && !f->val_args(args, NULL)) {
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004142 lua_pushfstring(L, "error in arguments");
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004143 goto error;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004144 }
4145
4146 /* Initialise the sample. */
4147 memset(&smp, 0, sizeof(smp));
4148
4149 /* Run the sample fetch process. */
Willy Tarreau1777ea62016-03-10 16:15:46 +01004150 smp_set_owner(&smp, hsmp->p, hsmp->s->sess, hsmp->s, hsmp->dir & SMP_OPT_DIR);
Thierry FOURNIER0786d052015-05-11 15:42:45 +02004151 if (!f->process(args, &smp, f->kw, f->private)) {
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004152 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004153 lua_pushstring(L, "");
4154 else
4155 lua_pushnil(L);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004156 goto end;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004157 }
4158
4159 /* Convert the returned sample in lua value. */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004160 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004161 hlua_smp2lua_str(L, &smp);
4162 else
4163 hlua_smp2lua(L, &smp);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004164
4165 end:
Willy Tarreauee0d7272021-07-16 10:26:56 +02004166 free_args(args);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004167 return 1;
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004168
4169 error:
Willy Tarreauee0d7272021-07-16 10:26:56 +02004170 free_args(args);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004171 WILL_LJMP(lua_error(L));
4172 return 0; /* Never reached */
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004173}
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004174
4175/*
4176 *
4177 *
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004178 * Class Converters
4179 *
4180 *
4181 */
4182
4183/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02004184 * a class stream, otherwise it throws an error.
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004185 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004186__LJMP static struct hlua_smp *hlua_checkconverters(lua_State *L, int ud)
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004187{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004188 return MAY_LJMP(hlua_checkudata(L, ud, class_converters_ref));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004189}
4190
4191/* This function creates and push in the stack a Converters object
4192 * according with a current TXN.
4193 */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004194static int hlua_converters_new(lua_State *L, struct hlua_txn *txn, unsigned int flags)
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004195{
Willy Tarreau7073c472015-04-06 11:15:40 +02004196 struct hlua_smp *hsmp;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004197
4198 /* Check stack size. */
4199 if (!lua_checkstack(L, 3))
4200 return 0;
4201
4202 /* Create the object: obj[0] = userdata.
4203 * Note that the base of the Converters object is the
4204 * same than the TXN object.
4205 */
4206 lua_newtable(L);
Willy Tarreau7073c472015-04-06 11:15:40 +02004207 hsmp = lua_newuserdata(L, sizeof(*hsmp));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004208 lua_rawseti(L, -2, 0);
4209
Willy Tarreau7073c472015-04-06 11:15:40 +02004210 hsmp->s = txn->s;
4211 hsmp->p = txn->p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01004212 hsmp->dir = txn->dir;
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004213 hsmp->flags = flags;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004214
Willy Tarreau87b09662015-04-03 00:22:06 +02004215 /* Pop a class stream metatable and affect it to the table. */
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004216 lua_rawgeti(L, LUA_REGISTRYINDEX, class_converters_ref);
4217 lua_setmetatable(L, -2);
4218
4219 return 1;
4220}
4221
4222/* This function is an LUA binding. It is called with each converter.
4223 * It uses closure argument to store the associated converter. It
4224 * returns only one argument or throws an error. An error is thrown
4225 * only if an error is encountered during the argument parsing. If
4226 * the converter function function fails, nil is returned.
4227 */
4228__LJMP static int hlua_run_sample_conv(lua_State *L)
4229{
Willy Tarreauda5f1082015-04-06 11:17:13 +02004230 struct hlua_smp *hsmp;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004231 struct sample_conv *conv;
Frédéric Lécaillef874a832018-06-15 13:56:04 +02004232 struct arg args[ARGM_NBARGS + 1] = {{0}};
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004233 int i;
4234 struct sample smp;
4235
4236 /* Get closure arguments. */
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004237 conv = lua_touserdata(L, lua_upvalueindex(1));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004238
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004239 /* Get traditional arguments. */
Willy Tarreauda5f1082015-04-06 11:17:13 +02004240 hsmp = MAY_LJMP(hlua_checkconverters(L, 1));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004241
4242 /* Get extra arguments. */
4243 for (i = 0; i < lua_gettop(L) - 2; i++) {
4244 if (i >= ARGM_NBARGS)
4245 break;
4246 hlua_lua2arg(L, i + 3, &args[i]);
4247 }
4248 args[i].type = ARGT_STOP;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004249 args[i].data.str.area = NULL;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004250
4251 /* Check arguments. */
Willy Tarreauda5f1082015-04-06 11:17:13 +02004252 MAY_LJMP(hlua_lua2arg_check(L, 3, args, conv->arg_mask, hsmp->p));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004253
4254 /* Run the special args checker. */
4255 if (conv->val_args && !conv->val_args(args, conv, "", 0, NULL)) {
4256 hlua_pusherror(L, "error in arguments");
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004257 goto error;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004258 }
4259
4260 /* Initialise the sample. */
Amaury Denoyellebc0af6a2020-10-29 17:21:20 +01004261 memset(&smp, 0, sizeof(smp));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004262 if (!hlua_lua2smp(L, 2, &smp)) {
4263 hlua_pusherror(L, "error in the input argument");
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004264 goto error;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004265 }
4266
Willy Tarreau1777ea62016-03-10 16:15:46 +01004267 smp_set_owner(&smp, hsmp->p, hsmp->s->sess, hsmp->s, hsmp->dir & SMP_OPT_DIR);
4268
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004269 /* Apply expected cast. */
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02004270 if (!sample_casts[smp.data.type][conv->in_type]) {
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004271 hlua_pusherror(L, "invalid input argument: cannot cast '%s' to '%s'",
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02004272 smp_to_type[smp.data.type], smp_to_type[conv->in_type]);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004273 goto error;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004274 }
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02004275 if (sample_casts[smp.data.type][conv->in_type] != c_none &&
4276 !sample_casts[smp.data.type][conv->in_type](&smp)) {
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004277 hlua_pusherror(L, "error during the input argument casting");
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004278 goto error;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004279 }
4280
4281 /* Run the sample conversion process. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02004282 if (!conv->process(args, &smp, conv->private)) {
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004283 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004284 lua_pushstring(L, "");
4285 else
Willy Tarreaua678b432015-08-28 10:14:59 +02004286 lua_pushnil(L);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004287 goto end;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004288 }
4289
4290 /* Convert the returned sample in lua value. */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004291 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004292 hlua_smp2lua_str(L, &smp);
4293 else
4294 hlua_smp2lua(L, &smp);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004295 end:
Willy Tarreauee0d7272021-07-16 10:26:56 +02004296 free_args(args);
Willy Tarreaua678b432015-08-28 10:14:59 +02004297 return 1;
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004298
4299 error:
Willy Tarreauee0d7272021-07-16 10:26:56 +02004300 free_args(args);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004301 WILL_LJMP(lua_error(L));
4302 return 0; /* Never reached */
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004303}
4304
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004305/*
4306 *
4307 *
4308 * Class AppletTCP
4309 *
4310 *
4311 */
4312
4313/* Returns a struct hlua_txn if the stack entry "ud" is
4314 * a class stream, otherwise it throws an error.
4315 */
4316__LJMP static struct hlua_appctx *hlua_checkapplet_tcp(lua_State *L, int ud)
4317{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004318 return MAY_LJMP(hlua_checkudata(L, ud, class_applet_tcp_ref));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004319}
4320
4321/* This function creates and push in the stack an Applet object
4322 * according with a current TXN.
4323 */
4324static int hlua_applet_tcp_new(lua_State *L, struct appctx *ctx)
4325{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004326 struct hlua_appctx *luactx;
Willy Tarreau0698c802022-05-11 14:09:57 +02004327 struct stream *s = appctx_strm(ctx);
Christopher Faulet2da02ae2022-02-24 13:45:27 +01004328 struct proxy *p;
4329
4330 ALREADY_CHECKED(s);
4331 p = s->be;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004332
4333 /* Check stack size. */
4334 if (!lua_checkstack(L, 3))
4335 return 0;
4336
4337 /* Create the object: obj[0] = userdata.
4338 * Note that the base of the Converters object is the
4339 * same than the TXN object.
4340 */
4341 lua_newtable(L);
Willy Tarreau7e702d12021-04-28 17:59:21 +02004342 luactx = lua_newuserdata(L, sizeof(*luactx));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004343 lua_rawseti(L, -2, 0);
Willy Tarreau7e702d12021-04-28 17:59:21 +02004344 luactx->appctx = ctx;
4345 luactx->htxn.s = s;
4346 luactx->htxn.p = p;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004347
4348 /* Create the "f" field that contains a list of fetches. */
4349 lua_pushstring(L, "f");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004350 if (!hlua_fetches_new(L, &luactx->htxn, 0))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004351 return 0;
4352 lua_settable(L, -3);
4353
4354 /* Create the "sf" field that contains a list of stringsafe fetches. */
4355 lua_pushstring(L, "sf");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004356 if (!hlua_fetches_new(L, &luactx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004357 return 0;
4358 lua_settable(L, -3);
4359
4360 /* Create the "c" field that contains a list of converters. */
4361 lua_pushstring(L, "c");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004362 if (!hlua_converters_new(L, &luactx->htxn, 0))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004363 return 0;
4364 lua_settable(L, -3);
4365
4366 /* Create the "sc" field that contains a list of stringsafe converters. */
4367 lua_pushstring(L, "sc");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004368 if (!hlua_converters_new(L, &luactx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004369 return 0;
4370 lua_settable(L, -3);
4371
4372 /* Pop a class stream metatable and affect it to the table. */
4373 lua_rawgeti(L, LUA_REGISTRYINDEX, class_applet_tcp_ref);
4374 lua_setmetatable(L, -2);
4375
4376 return 1;
4377}
4378
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004379__LJMP static int hlua_applet_tcp_set_var(lua_State *L)
4380{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004381 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004382 struct stream *s;
4383 const char *name;
4384 size_t len;
4385 struct sample smp;
4386
Tim Duesterhus4e172c92020-05-19 13:49:42 +02004387 if (lua_gettop(L) < 3 || lua_gettop(L) > 4)
4388 WILL_LJMP(luaL_error(L, "'set_var' needs between 3 and 4 arguments"));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004389
4390 /* It is useles to retrieve the stream, but this function
4391 * runs only in a stream context.
4392 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004393 luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004394 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02004395 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004396
4397 /* Converts the third argument in a sample. */
Amaury Denoyellebc0af6a2020-10-29 17:21:20 +01004398 memset(&smp, 0, sizeof(smp));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004399 hlua_lua2smp(L, 3, &smp);
4400
4401 /* Store the sample in a variable. */
4402 smp_set_owner(&smp, s->be, s->sess, s, 0);
Tim Duesterhus4e172c92020-05-19 13:49:42 +02004403
4404 if (lua_gettop(L) == 4 && lua_toboolean(L, 4))
4405 lua_pushboolean(L, vars_set_by_name_ifexist(name, len, &smp) != 0);
4406 else
4407 lua_pushboolean(L, vars_set_by_name(name, len, &smp) != 0);
4408
Tim Duesterhus84ebc132020-05-19 13:49:41 +02004409 return 1;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004410}
4411
4412__LJMP static int hlua_applet_tcp_unset_var(lua_State *L)
4413{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004414 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004415 struct stream *s;
4416 const char *name;
4417 size_t len;
4418 struct sample smp;
4419
4420 MAY_LJMP(check_args(L, 2, "unset_var"));
4421
4422 /* It is useles to retrieve the stream, but this function
4423 * runs only in a stream context.
4424 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004425 luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004426 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02004427 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004428
4429 /* Unset the variable. */
4430 smp_set_owner(&smp, s->be, s->sess, s, 0);
Tim Duesterhus84ebc132020-05-19 13:49:41 +02004431 lua_pushboolean(L, vars_unset_by_name_ifexist(name, len, &smp) != 0);
4432 return 1;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004433}
4434
4435__LJMP static int hlua_applet_tcp_get_var(lua_State *L)
4436{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004437 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004438 struct stream *s;
4439 const char *name;
4440 size_t len;
4441 struct sample smp;
4442
4443 MAY_LJMP(check_args(L, 2, "get_var"));
4444
4445 /* It is useles to retrieve the stream, but this function
4446 * runs only in a stream context.
4447 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004448 luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004449 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02004450 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004451
4452 smp_set_owner(&smp, s->be, s->sess, s, 0);
Willy Tarreaue352b9d2021-09-03 11:52:38 +02004453 if (!vars_get_by_name(name, len, &smp, NULL)) {
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004454 lua_pushnil(L);
4455 return 1;
4456 }
4457
4458 return hlua_smp2lua(L, &smp);
4459}
4460
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004461__LJMP static int hlua_applet_tcp_set_priv(lua_State *L)
4462{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004463 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
4464 struct stream *s = luactx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01004465 struct hlua *hlua;
4466
4467 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01004468 if (!s->hlua)
4469 return 0;
4470 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004471
4472 MAY_LJMP(check_args(L, 2, "set_priv"));
4473
4474 /* Remove previous value. */
Thierry FOURNIERe068b602017-04-26 13:27:05 +02004475 luaL_unref(L, LUA_REGISTRYINDEX, hlua->Mref);
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004476
4477 /* Get and store new value. */
4478 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
4479 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
4480
4481 return 0;
4482}
4483
4484__LJMP static int hlua_applet_tcp_get_priv(lua_State *L)
4485{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004486 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
4487 struct stream *s = luactx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01004488 struct hlua *hlua;
4489
4490 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01004491 if (!s->hlua) {
4492 lua_pushnil(L);
4493 return 1;
4494 }
4495 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004496
4497 /* Push configuration index in the stack. */
4498 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
4499
4500 return 1;
4501}
4502
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004503/* If expected data not yet available, it returns a yield. This function
4504 * consumes the data in the buffer. It returns a string containing the
4505 * data. This string can be empty.
4506 */
4507__LJMP static int hlua_applet_tcp_getline_yield(lua_State *L, int status, lua_KContext ctx)
4508{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004509 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Willy Tarreauc12b3212022-05-27 11:08:15 +02004510 struct stconn *sc = appctx_sc(luactx->appctx);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004511 int ret;
Willy Tarreau206ba832018-06-14 15:27:31 +02004512 const char *blk1;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004513 size_t len1;
Willy Tarreau206ba832018-06-14 15:27:31 +02004514 const char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004515 size_t len2;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004516
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004517 /* Read the maximum amount of data available. */
Willy Tarreau3e7be362022-05-27 10:35:27 +02004518 ret = co_getline_nc(sc_oc(sc), &blk1, &len1, &blk2, &len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004519
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004520 /* Data not yet available. return yield. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004521 if (ret == 0) {
Willy Tarreau90e8b452022-05-25 18:21:43 +02004522 applet_need_more_data(luactx->appctx);
Willy Tarreau9635e032018-10-16 17:52:55 +02004523 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_getline_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004524 }
4525
4526 /* End of data: commit the total strings and return. */
4527 if (ret < 0) {
Willy Tarreau7e702d12021-04-28 17:59:21 +02004528 luaL_pushresult(&luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004529 return 1;
4530 }
4531
4532 /* Ensure that the block 2 length is usable. */
4533 if (ret == 1)
4534 len2 = 0;
4535
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -07004536 /* don't check the max length read and don't check. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004537 luaL_addlstring(&luactx->b, blk1, len1);
4538 luaL_addlstring(&luactx->b, blk2, len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004539
4540 /* Consume input channel output buffer data. */
Willy Tarreau3e7be362022-05-27 10:35:27 +02004541 co_skip(sc_oc(sc), len1 + len2);
Willy Tarreau7e702d12021-04-28 17:59:21 +02004542 luaL_pushresult(&luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004543 return 1;
4544}
4545
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004546/* Check arguments for the function "hlua_channel_get_yield". */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004547__LJMP static int hlua_applet_tcp_getline(lua_State *L)
4548{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004549 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004550
4551 /* Initialise the string catenation. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004552 luaL_buffinit(L, &luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004553
4554 return MAY_LJMP(hlua_applet_tcp_getline_yield(L, 0, 0));
4555}
4556
4557/* If expected data not yet available, it returns a yield. This function
4558 * consumes the data in the buffer. It returns a string containing the
4559 * data. This string can be empty.
4560 */
4561__LJMP static int hlua_applet_tcp_recv_yield(lua_State *L, int status, lua_KContext ctx)
4562{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004563 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Willy Tarreauc12b3212022-05-27 11:08:15 +02004564 struct stconn *sc = appctx_sc(luactx->appctx);
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004565 size_t len = MAY_LJMP(luaL_checkinteger(L, 2));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004566 int ret;
Willy Tarreau206ba832018-06-14 15:27:31 +02004567 const char *blk1;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004568 size_t len1;
Willy Tarreau206ba832018-06-14 15:27:31 +02004569 const char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004570 size_t len2;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004571
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004572 /* Read the maximum amount of data available. */
Willy Tarreau3e7be362022-05-27 10:35:27 +02004573 ret = co_getblk_nc(sc_oc(sc), &blk1, &len1, &blk2, &len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004574
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004575 /* Data not yet available. return yield. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004576 if (ret == 0) {
Willy Tarreau90e8b452022-05-25 18:21:43 +02004577 applet_need_more_data(luactx->appctx);
Willy Tarreau9635e032018-10-16 17:52:55 +02004578 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004579 }
4580
4581 /* End of data: commit the total strings and return. */
4582 if (ret < 0) {
Willy Tarreau7e702d12021-04-28 17:59:21 +02004583 luaL_pushresult(&luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004584 return 1;
4585 }
4586
4587 /* Ensure that the block 2 length is usable. */
4588 if (ret == 1)
4589 len2 = 0;
4590
4591 if (len == -1) {
4592
4593 /* If len == -1, catenate all the data avalaile and
4594 * yield because we want to get all the data until
4595 * the end of data stream.
4596 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004597 luaL_addlstring(&luactx->b, blk1, len1);
4598 luaL_addlstring(&luactx->b, blk2, len2);
Willy Tarreau3e7be362022-05-27 10:35:27 +02004599 co_skip(sc_oc(sc), len1 + len2);
Willy Tarreau90e8b452022-05-25 18:21:43 +02004600 applet_need_more_data(luactx->appctx);
Willy Tarreau9635e032018-10-16 17:52:55 +02004601 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004602
4603 } else {
4604
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05004605 /* Copy the first block caping to the length required. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004606 if (len1 > len)
4607 len1 = len;
Willy Tarreau7e702d12021-04-28 17:59:21 +02004608 luaL_addlstring(&luactx->b, blk1, len1);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004609 len -= len1;
4610
4611 /* Copy the second block. */
4612 if (len2 > len)
4613 len2 = len;
Willy Tarreau7e702d12021-04-28 17:59:21 +02004614 luaL_addlstring(&luactx->b, blk2, len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004615 len -= len2;
4616
4617 /* Consume input channel output buffer data. */
Willy Tarreau3e7be362022-05-27 10:35:27 +02004618 co_skip(sc_oc(sc), len1 + len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004619
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004620 /* If there is no other data available, yield waiting for new data. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004621 if (len > 0) {
4622 lua_pushinteger(L, len);
4623 lua_replace(L, 2);
Willy Tarreau90e8b452022-05-25 18:21:43 +02004624 applet_need_more_data(luactx->appctx);
Willy Tarreau9635e032018-10-16 17:52:55 +02004625 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004626 }
4627
4628 /* return the result. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004629 luaL_pushresult(&luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004630 return 1;
4631 }
4632
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004633 /* we never execute this */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004634 hlua_pusherror(L, "Lua: internal error");
4635 WILL_LJMP(lua_error(L));
4636 return 0;
4637}
4638
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004639/* Check arguments for the function "hlua_channel_get_yield". */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004640__LJMP static int hlua_applet_tcp_recv(lua_State *L)
4641{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004642 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004643 int len = -1;
4644
4645 if (lua_gettop(L) > 2)
4646 WILL_LJMP(luaL_error(L, "The 'recv' function requires between 1 and 2 arguments."));
4647 if (lua_gettop(L) >= 2) {
4648 len = MAY_LJMP(luaL_checkinteger(L, 2));
4649 lua_pop(L, 1);
4650 }
4651
4652 /* Confirm or set the required length */
4653 lua_pushinteger(L, len);
4654
4655 /* Initialise the string catenation. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004656 luaL_buffinit(L, &luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004657
4658 return MAY_LJMP(hlua_applet_tcp_recv_yield(L, 0, 0));
4659}
4660
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004661/* Append data in the output side of the buffer. This data is immediately
4662 * sent. The function returns the amount of data written. If the buffer
4663 * cannot contain the data, the function yields. The function returns -1
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004664 * if the channel is closed.
4665 */
4666__LJMP static int hlua_applet_tcp_send_yield(lua_State *L, int status, lua_KContext ctx)
4667{
4668 size_t len;
Willy Tarreau7e702d12021-04-28 17:59:21 +02004669 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004670 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
4671 int l = MAY_LJMP(luaL_checkinteger(L, 3));
Willy Tarreauc12b3212022-05-27 11:08:15 +02004672 struct stconn *sc = appctx_sc(luactx->appctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02004673 struct channel *chn = sc_ic(sc);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004674 int max;
4675
4676 /* Get the max amount of data which can write as input in the channel. */
4677 max = channel_recv_max(chn);
4678 if (max > (len - l))
4679 max = len - l;
4680
4681 /* Copy data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02004682 ci_putblk(chn, str + l, max);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004683
4684 /* update counters. */
4685 l += max;
4686 lua_pop(L, 1);
4687 lua_pushinteger(L, l);
4688
4689 /* If some data is not send, declares the situation to the
4690 * applet, and returns a yield.
4691 */
4692 if (l < len) {
Willy Tarreau3e7be362022-05-27 10:35:27 +02004693 sc_need_room(sc);
Willy Tarreau9635e032018-10-16 17:52:55 +02004694 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004695 }
4696
4697 return 1;
4698}
4699
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05004700/* Just a wrapper of "hlua_applet_tcp_send_yield". This wrapper permits
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004701 * yield the LUA process, and resume it without checking the
4702 * input arguments.
4703 */
4704__LJMP static int hlua_applet_tcp_send(lua_State *L)
4705{
4706 MAY_LJMP(check_args(L, 2, "send"));
4707 lua_pushinteger(L, 0);
4708
4709 return MAY_LJMP(hlua_applet_tcp_send_yield(L, 0, 0));
4710}
4711
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004712/*
4713 *
4714 *
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004715 * Class AppletHTTP
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004716 *
4717 *
4718 */
4719
4720/* Returns a struct hlua_txn if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02004721 * a class stream, otherwise it throws an error.
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004722 */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004723__LJMP static struct hlua_appctx *hlua_checkapplet_http(lua_State *L, int ud)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004724{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004725 return MAY_LJMP(hlua_checkudata(L, ud, class_applet_http_ref));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004726}
4727
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004728/* This function creates and push in the stack an Applet object
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004729 * according with a current TXN.
Willy Tarreauaa229cc2022-05-06 14:26:10 +02004730 * It relies on the caller to have already reserved the room in ctx->svcctx
4731 * for the local storage of hlua_http_ctx.
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004732 */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004733static int hlua_applet_http_new(lua_State *L, struct appctx *ctx)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004734{
Willy Tarreauaa229cc2022-05-06 14:26:10 +02004735 struct hlua_http_ctx *http_ctx = ctx->svcctx;
Willy Tarreau7e702d12021-04-28 17:59:21 +02004736 struct hlua_appctx *luactx;
Thierry FOURNIER841475e2015-12-11 17:10:09 +01004737 struct hlua_txn htxn;
Willy Tarreau0698c802022-05-11 14:09:57 +02004738 struct stream *s = appctx_strm(ctx);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004739 struct proxy *px = s->be;
Christopher Fauleta2097962019-07-15 16:25:33 +02004740 struct htx *htx;
4741 struct htx_blk *blk;
4742 struct htx_sl *sl;
4743 struct ist path;
4744 unsigned long long len = 0;
4745 int32_t pos;
Amaury Denoyellec453f952021-07-06 11:40:12 +02004746 struct http_uri_parser parser;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004747
4748 /* Check stack size. */
4749 if (!lua_checkstack(L, 3))
4750 return 0;
4751
4752 /* Create the object: obj[0] = userdata.
4753 * Note that the base of the Converters object is the
4754 * same than the TXN object.
4755 */
4756 lua_newtable(L);
Willy Tarreau7e702d12021-04-28 17:59:21 +02004757 luactx = lua_newuserdata(L, sizeof(*luactx));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004758 lua_rawseti(L, -2, 0);
Willy Tarreau7e702d12021-04-28 17:59:21 +02004759 luactx->appctx = ctx;
Willy Tarreauaa229cc2022-05-06 14:26:10 +02004760 http_ctx->status = 200; /* Default status code returned. */
4761 http_ctx->reason = NULL; /* Use default reason based on status */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004762 luactx->htxn.s = s;
4763 luactx->htxn.p = px;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004764
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004765 /* Create the "f" field that contains a list of fetches. */
4766 lua_pushstring(L, "f");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004767 if (!hlua_fetches_new(L, &luactx->htxn, 0))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004768 return 0;
4769 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004770
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004771 /* Create the "sf" field that contains a list of stringsafe fetches. */
4772 lua_pushstring(L, "sf");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004773 if (!hlua_fetches_new(L, &luactx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004774 return 0;
4775 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004776
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004777 /* Create the "c" field that contains a list of converters. */
4778 lua_pushstring(L, "c");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004779 if (!hlua_converters_new(L, &luactx->htxn, 0))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004780 return 0;
4781 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004782
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004783 /* Create the "sc" field that contains a list of stringsafe converters. */
4784 lua_pushstring(L, "sc");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004785 if (!hlua_converters_new(L, &luactx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004786 return 0;
4787 lua_settable(L, -3);
Willy Tarreaueee5b512015-04-03 23:46:31 +02004788
Christopher Fauleta2097962019-07-15 16:25:33 +02004789 htx = htxbuf(&s->req.buf);
4790 blk = htx_get_first_blk(htx);
Christopher Fauletea009732019-11-18 15:50:25 +01004791 BUG_ON(!blk || htx_get_blk_type(blk) != HTX_BLK_REQ_SL);
Christopher Fauleta2097962019-07-15 16:25:33 +02004792 sl = htx_get_blk_ptr(htx, blk);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004793
Christopher Fauleta2097962019-07-15 16:25:33 +02004794 /* Stores the request method. */
4795 lua_pushstring(L, "method");
4796 lua_pushlstring(L, HTX_SL_REQ_MPTR(sl), HTX_SL_REQ_MLEN(sl));
4797 lua_settable(L, -3);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004798
Christopher Fauleta2097962019-07-15 16:25:33 +02004799 /* Stores the http version. */
4800 lua_pushstring(L, "version");
4801 lua_pushlstring(L, HTX_SL_REQ_VPTR(sl), HTX_SL_REQ_VLEN(sl));
4802 lua_settable(L, -3);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004803
Christopher Fauleta2097962019-07-15 16:25:33 +02004804 /* creates an array of headers. hlua_http_get_headers() crates and push
4805 * the array on the top of the stack.
4806 */
4807 lua_pushstring(L, "headers");
4808 htxn.s = s;
4809 htxn.p = px;
4810 htxn.dir = SMP_OPT_DIR_REQ;
Christopher Faulet9d1332b2020-02-24 16:46:16 +01004811 if (!hlua_http_get_headers(L, &htxn.s->txn->req))
Christopher Fauleta2097962019-07-15 16:25:33 +02004812 return 0;
4813 lua_settable(L, -3);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004814
Amaury Denoyellec453f952021-07-06 11:40:12 +02004815 parser = http_uri_parser_init(htx_sl_req_uri(sl));
4816 path = http_parse_path(&parser);
Tim Duesterhused526372020-03-05 17:56:33 +01004817 if (isttest(path)) {
Christopher Fauleta2097962019-07-15 16:25:33 +02004818 char *p, *q, *end;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004819
Christopher Fauleta2097962019-07-15 16:25:33 +02004820 p = path.ptr;
Tim Duesterhus4c8f75f2021-11-06 15:14:44 +01004821 end = istend(path);
Christopher Fauleta2097962019-07-15 16:25:33 +02004822 q = p;
4823 while (q < end && *q != '?')
4824 q++;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004825
Thierry FOURNIER7d388632017-02-22 02:06:16 +01004826 /* Stores the request path. */
Christopher Fauleta2097962019-07-15 16:25:33 +02004827 lua_pushstring(L, "path");
4828 lua_pushlstring(L, p, q - p);
Thierry FOURNIER7d388632017-02-22 02:06:16 +01004829 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01004830
Christopher Fauleta2097962019-07-15 16:25:33 +02004831 /* Stores the query string. */
4832 lua_pushstring(L, "qs");
4833 if (*q == '?')
4834 q++;
4835 lua_pushlstring(L, q, end - q);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004836 lua_settable(L, -3);
Christopher Fauleta2097962019-07-15 16:25:33 +02004837 }
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004838
Christopher Fauleta2097962019-07-15 16:25:33 +02004839 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
4840 struct htx_blk *blk = htx_get_blk(htx, pos);
4841 enum htx_blk_type type = htx_get_blk_type(blk);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004842
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01004843 if (type == HTX_BLK_TLR || type == HTX_BLK_EOT)
Christopher Fauleta2097962019-07-15 16:25:33 +02004844 break;
4845 if (type == HTX_BLK_DATA)
4846 len += htx_get_blksz(blk);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004847 }
Christopher Fauleta2097962019-07-15 16:25:33 +02004848 if (htx->extra != ULLONG_MAX)
4849 len += htx->extra;
4850
4851 /* Stores the request path. */
4852 lua_pushstring(L, "length");
4853 lua_pushinteger(L, len);
4854 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01004855
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004856 /* Create an empty array of HTTP request headers. */
4857 lua_pushstring(L, "response");
4858 lua_newtable(L);
4859 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01004860
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004861 /* Pop a class stream metatable and affect it to the table. */
4862 lua_rawgeti(L, LUA_REGISTRYINDEX, class_applet_http_ref);
4863 lua_setmetatable(L, -2);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004864
4865 return 1;
4866}
4867
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004868__LJMP static int hlua_applet_http_set_var(lua_State *L)
4869{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004870 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004871 struct stream *s;
4872 const char *name;
4873 size_t len;
4874 struct sample smp;
4875
Tim Duesterhus4e172c92020-05-19 13:49:42 +02004876 if (lua_gettop(L) < 3 || lua_gettop(L) > 4)
4877 WILL_LJMP(luaL_error(L, "'set_var' needs between 3 and 4 arguments"));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004878
4879 /* It is useles to retrieve the stream, but this function
4880 * runs only in a stream context.
4881 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004882 luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004883 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02004884 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004885
4886 /* Converts the third argument in a sample. */
Amaury Denoyellebc0af6a2020-10-29 17:21:20 +01004887 memset(&smp, 0, sizeof(smp));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004888 hlua_lua2smp(L, 3, &smp);
4889
4890 /* Store the sample in a variable. */
4891 smp_set_owner(&smp, s->be, s->sess, s, 0);
Tim Duesterhus4e172c92020-05-19 13:49:42 +02004892
4893 if (lua_gettop(L) == 4 && lua_toboolean(L, 4))
4894 lua_pushboolean(L, vars_set_by_name_ifexist(name, len, &smp) != 0);
4895 else
4896 lua_pushboolean(L, vars_set_by_name(name, len, &smp) != 0);
4897
Tim Duesterhus84ebc132020-05-19 13:49:41 +02004898 return 1;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004899}
4900
4901__LJMP static int hlua_applet_http_unset_var(lua_State *L)
4902{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004903 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004904 struct stream *s;
4905 const char *name;
4906 size_t len;
4907 struct sample smp;
4908
4909 MAY_LJMP(check_args(L, 2, "unset_var"));
4910
4911 /* It is useles to retrieve the stream, but this function
4912 * runs only in a stream context.
4913 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004914 luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004915 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02004916 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004917
4918 /* Unset the variable. */
4919 smp_set_owner(&smp, s->be, s->sess, s, 0);
Tim Duesterhus84ebc132020-05-19 13:49:41 +02004920 lua_pushboolean(L, vars_unset_by_name_ifexist(name, len, &smp) != 0);
4921 return 1;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004922}
4923
4924__LJMP static int hlua_applet_http_get_var(lua_State *L)
4925{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004926 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004927 struct stream *s;
4928 const char *name;
4929 size_t len;
4930 struct sample smp;
4931
4932 MAY_LJMP(check_args(L, 2, "get_var"));
4933
4934 /* It is useles to retrieve the stream, but this function
4935 * runs only in a stream context.
4936 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004937 luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004938 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02004939 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004940
4941 smp_set_owner(&smp, s->be, s->sess, s, 0);
Willy Tarreaue352b9d2021-09-03 11:52:38 +02004942 if (!vars_get_by_name(name, len, &smp, NULL)) {
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004943 lua_pushnil(L);
4944 return 1;
4945 }
4946
4947 return hlua_smp2lua(L, &smp);
4948}
4949
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004950__LJMP static int hlua_applet_http_set_priv(lua_State *L)
4951{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004952 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4953 struct stream *s = luactx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01004954 struct hlua *hlua;
4955
4956 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01004957 if (!s->hlua)
4958 return 0;
4959 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004960
4961 MAY_LJMP(check_args(L, 2, "set_priv"));
4962
4963 /* Remove previous value. */
Thierry FOURNIERe068b602017-04-26 13:27:05 +02004964 luaL_unref(L, LUA_REGISTRYINDEX, hlua->Mref);
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004965
4966 /* Get and store new value. */
4967 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
4968 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
4969
4970 return 0;
4971}
4972
4973__LJMP static int hlua_applet_http_get_priv(lua_State *L)
4974{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004975 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4976 struct stream *s = luactx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01004977 struct hlua *hlua;
4978
4979 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01004980 if (!s->hlua) {
4981 lua_pushnil(L);
4982 return 1;
4983 }
4984 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004985
4986 /* Push configuration index in the stack. */
4987 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
4988
4989 return 1;
4990}
4991
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004992/* If expected data not yet available, it returns a yield. This function
4993 * consumes the data in the buffer. It returns a string containing the
4994 * data. This string can be empty.
4995 */
Christopher Fauleta2097962019-07-15 16:25:33 +02004996__LJMP static int hlua_applet_http_getline_yield(lua_State *L, int status, lua_KContext ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004997{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004998 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Willy Tarreauc12b3212022-05-27 11:08:15 +02004999 struct stconn *sc = appctx_sc(luactx->appctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02005000 struct channel *req = sc_oc(sc);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005001 struct htx *htx;
5002 struct htx_blk *blk;
5003 size_t count;
5004 int stop = 0;
5005
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005006 htx = htx_from_buf(&req->buf);
5007 count = co_data(req);
Christopher Fauleta3f15502019-05-13 15:27:23 +02005008 blk = htx_get_first_blk(htx);
Christopher Fauletcc26b132018-12-18 21:20:57 +01005009
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005010 while (count && !stop && blk) {
5011 enum htx_blk_type type = htx_get_blk_type(blk);
5012 uint32_t sz = htx_get_blksz(blk);
5013 struct ist v;
5014 uint32_t vlen;
5015 char *nl;
5016
5017 vlen = sz;
5018 if (vlen > count) {
5019 if (type != HTX_BLK_DATA)
5020 break;
5021 vlen = count;
5022 }
5023
5024 switch (type) {
5025 case HTX_BLK_UNUSED:
5026 break;
5027
5028 case HTX_BLK_DATA:
5029 v = htx_get_blk_value(htx, blk);
5030 v.len = vlen;
5031 nl = istchr(v, '\n');
5032 if (nl != NULL) {
5033 stop = 1;
5034 vlen = nl - v.ptr + 1;
5035 }
Willy Tarreau7e702d12021-04-28 17:59:21 +02005036 luaL_addlstring(&luactx->b, v.ptr, vlen);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005037 break;
5038
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005039 case HTX_BLK_TLR:
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01005040 case HTX_BLK_EOT:
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005041 stop = 1;
5042 break;
5043
5044 default:
5045 break;
5046 }
5047
Willy Tarreau84240042022-02-28 16:51:23 +01005048 c_rew(req, vlen);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005049 count -= vlen;
5050 if (sz == vlen)
5051 blk = htx_remove_blk(htx, blk);
5052 else {
5053 htx_cut_data_blk(htx, blk, vlen);
5054 break;
5055 }
5056 }
5057
Christopher Fauleteccb31c2021-04-02 14:24:56 +02005058 /* The message was fully consumed and no more data are expected
5059 * (EOM flag set).
5060 */
5061 if (htx_is_empty(htx) && (htx->flags & HTX_FL_EOM))
5062 stop = 1;
5063
Christopher Faulet0ae79d02019-02-27 21:36:59 +01005064 htx_to_buf(htx, &req->buf);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005065 if (!stop) {
Willy Tarreau90e8b452022-05-25 18:21:43 +02005066 applet_need_more_data(luactx->appctx);
Christopher Fauleta2097962019-07-15 16:25:33 +02005067 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_getline_yield, TICK_ETERNITY, 0));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005068 }
5069
5070 /* return the result. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005071 luaL_pushresult(&luactx->b);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005072 return 1;
5073}
5074
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005075
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08005076/* Check arguments for the function "hlua_channel_get_yield". */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005077__LJMP static int hlua_applet_http_getline(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005078{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005079 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005080
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005081 /* Initialise the string catenation. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005082 luaL_buffinit(L, &luactx->b);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005083
Christopher Fauleta2097962019-07-15 16:25:33 +02005084 return MAY_LJMP(hlua_applet_http_getline_yield(L, 0, 0));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005085}
5086
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005087/* If expected data not yet available, it returns a yield. This function
5088 * consumes the data in the buffer. It returns a string containing the
5089 * data. This string can be empty.
5090 */
Christopher Fauleta2097962019-07-15 16:25:33 +02005091__LJMP static int hlua_applet_http_recv_yield(lua_State *L, int status, lua_KContext ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005092{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005093 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Willy Tarreauc12b3212022-05-27 11:08:15 +02005094 struct stconn *sc = appctx_sc(luactx->appctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02005095 struct channel *req = sc_oc(sc);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005096 struct htx *htx;
5097 struct htx_blk *blk;
5098 size_t count;
5099 int len;
5100
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005101 htx = htx_from_buf(&req->buf);
5102 len = MAY_LJMP(luaL_checkinteger(L, 2));
5103 count = co_data(req);
Christopher Faulet29f17582019-05-23 11:03:26 +02005104 blk = htx_get_head_blk(htx);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005105 while (count && len && blk) {
5106 enum htx_blk_type type = htx_get_blk_type(blk);
5107 uint32_t sz = htx_get_blksz(blk);
5108 struct ist v;
5109 uint32_t vlen;
5110
5111 vlen = sz;
5112 if (len > 0 && vlen > len)
5113 vlen = len;
5114 if (vlen > count) {
5115 if (type != HTX_BLK_DATA)
5116 break;
5117 vlen = count;
5118 }
5119
5120 switch (type) {
5121 case HTX_BLK_UNUSED:
5122 break;
5123
5124 case HTX_BLK_DATA:
5125 v = htx_get_blk_value(htx, blk);
Willy Tarreau7e702d12021-04-28 17:59:21 +02005126 luaL_addlstring(&luactx->b, v.ptr, vlen);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005127 break;
5128
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005129 case HTX_BLK_TLR:
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01005130 case HTX_BLK_EOT:
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005131 len = 0;
5132 break;
5133
5134 default:
5135 break;
5136 }
5137
Willy Tarreau84240042022-02-28 16:51:23 +01005138 c_rew(req, vlen);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005139 count -= vlen;
5140 if (len > 0)
5141 len -= vlen;
5142 if (sz == vlen)
5143 blk = htx_remove_blk(htx, blk);
5144 else {
5145 htx_cut_data_blk(htx, blk, vlen);
5146 break;
5147 }
5148 }
5149
Christopher Fauleteccb31c2021-04-02 14:24:56 +02005150 /* The message was fully consumed and no more data are expected
5151 * (EOM flag set).
5152 */
5153 if (htx_is_empty(htx) && (htx->flags & HTX_FL_EOM))
5154 len = 0;
5155
Christopher Faulet0ae79d02019-02-27 21:36:59 +01005156 htx_to_buf(htx, &req->buf);
5157
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005158 /* If we are no other data available, yield waiting for new data. */
5159 if (len) {
5160 if (len > 0) {
5161 lua_pushinteger(L, len);
5162 lua_replace(L, 2);
5163 }
Willy Tarreau90e8b452022-05-25 18:21:43 +02005164 applet_need_more_data(luactx->appctx);
Willy Tarreau9635e032018-10-16 17:52:55 +02005165 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005166 }
5167
5168 /* return the result. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005169 luaL_pushresult(&luactx->b);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005170 return 1;
5171}
5172
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08005173/* Check arguments for the function "hlua_channel_get_yield". */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005174__LJMP static int hlua_applet_http_recv(lua_State *L)
5175{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005176 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005177 int len = -1;
5178
5179 /* Check arguments. */
5180 if (lua_gettop(L) > 2)
5181 WILL_LJMP(luaL_error(L, "The 'recv' function requires between 1 and 2 arguments."));
5182 if (lua_gettop(L) >= 2) {
5183 len = MAY_LJMP(luaL_checkinteger(L, 2));
5184 lua_pop(L, 1);
5185 }
5186
Christopher Fauleta2097962019-07-15 16:25:33 +02005187 lua_pushinteger(L, len);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005188
Christopher Fauleta2097962019-07-15 16:25:33 +02005189 /* Initialise the string catenation. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005190 luaL_buffinit(L, &luactx->b);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005191
Christopher Fauleta2097962019-07-15 16:25:33 +02005192 return MAY_LJMP(hlua_applet_http_recv_yield(L, 0, 0));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005193}
5194
5195/* Append data in the output side of the buffer. This data is immediately
5196 * sent. The function returns the amount of data written. If the buffer
5197 * cannot contain the data, the function yields. The function returns -1
5198 * if the channel is closed.
5199 */
Christopher Fauleta2097962019-07-15 16:25:33 +02005200__LJMP static int hlua_applet_http_send_yield(lua_State *L, int status, lua_KContext ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005201{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005202 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Willy Tarreauc12b3212022-05-27 11:08:15 +02005203 struct stconn *sc = appctx_sc(luactx->appctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02005204 struct channel *res = sc_ic(sc);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005205 struct htx *htx = htx_from_buf(&res->buf);
5206 const char *data;
5207 size_t len;
5208 int l = MAY_LJMP(luaL_checkinteger(L, 3));
5209 int max;
5210
Christopher Faulet9060fc02019-07-03 11:39:30 +02005211 max = htx_get_max_blksz(htx, channel_htx_recv_max(res, htx));
Christopher Faulet4b0e9b22019-01-09 12:16:58 +01005212 if (!max)
5213 goto snd_yield;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005214
5215 data = MAY_LJMP(luaL_checklstring(L, 2, &len));
5216
5217 /* Get the max amount of data which can write as input in the channel. */
5218 if (max > (len - l))
5219 max = len - l;
5220
5221 /* Copy data. */
Willy Tarreau0a7ef022019-05-28 10:30:11 +02005222 max = htx_add_data(htx, ist2(data + l, max));
Christopher Fauletf6cce3f2019-02-27 21:20:09 +01005223 channel_add_input(res, max);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005224
5225 /* update counters. */
5226 l += max;
5227 lua_pop(L, 1);
5228 lua_pushinteger(L, l);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005229
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005230 /* If some data is not send, declares the situation to the
5231 * applet, and returns a yield.
5232 */
5233 if (l < len) {
Christopher Faulet4b0e9b22019-01-09 12:16:58 +01005234 snd_yield:
Christopher Faulet0ae79d02019-02-27 21:36:59 +01005235 htx_to_buf(htx, &res->buf);
Willy Tarreau3e7be362022-05-27 10:35:27 +02005236 sc_need_room(sc);
Willy Tarreau9635e032018-10-16 17:52:55 +02005237 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005238 }
5239
Christopher Fauleta2097962019-07-15 16:25:33 +02005240 htx_to_buf(htx, &res->buf);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005241 return 1;
5242}
5243
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05005244/* Just a wrapper of "hlua_applet_send_yield". This wrapper permits
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005245 * yield the LUA process, and resume it without checking the
5246 * input arguments.
5247 */
5248__LJMP static int hlua_applet_http_send(lua_State *L)
5249{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005250 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005251 struct hlua_http_ctx *http_ctx = luactx->appctx->svcctx;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005252
5253 /* We want to send some data. Headers must be sent. */
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005254 if (!(http_ctx->flags & APPLET_HDR_SENT)) {
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005255 hlua_pusherror(L, "Lua: 'send' you must call start_response() before sending data.");
5256 WILL_LJMP(lua_error(L));
5257 }
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005258
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05005259 /* This integer is used for followinf the amount of data sent. */
Christopher Fauleta2097962019-07-15 16:25:33 +02005260 lua_pushinteger(L, 0);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005261
Christopher Fauleta2097962019-07-15 16:25:33 +02005262 return MAY_LJMP(hlua_applet_http_send_yield(L, 0, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005263}
5264
5265__LJMP static int hlua_applet_http_addheader(lua_State *L)
5266{
5267 const char *name;
5268 int ret;
5269
5270 MAY_LJMP(hlua_checkapplet_http(L, 1));
5271 name = MAY_LJMP(luaL_checkstring(L, 2));
5272 MAY_LJMP(luaL_checkstring(L, 3));
5273
5274 /* Push in the stack the "response" entry. */
5275 ret = lua_getfield(L, 1, "response");
5276 if (ret != LUA_TTABLE) {
5277 hlua_pusherror(L, "Lua: 'add_header' internal error: AppletHTTP['response'] "
5278 "is expected as an array. %s found", lua_typename(L, ret));
5279 WILL_LJMP(lua_error(L));
5280 }
5281
5282 /* check if the header is already registered if it is not
5283 * the case, register it.
5284 */
5285 ret = lua_getfield(L, -1, name);
5286 if (ret == LUA_TNIL) {
5287
5288 /* Entry not found. */
5289 lua_pop(L, 1); /* remove the nil. The "response" table is the top of the stack. */
5290
5291 /* Insert the new header name in the array in the top of the stack.
5292 * It left the new array in the top of the stack.
5293 */
5294 lua_newtable(L);
5295 lua_pushvalue(L, 2);
5296 lua_pushvalue(L, -2);
5297 lua_settable(L, -4);
5298
5299 } else if (ret != LUA_TTABLE) {
5300
5301 /* corruption error. */
5302 hlua_pusherror(L, "Lua: 'add_header' internal error: AppletHTTP['response']['%s'] "
5303 "is expected as an array. %s found", name, lua_typename(L, ret));
5304 WILL_LJMP(lua_error(L));
5305 }
5306
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -07005307 /* Now the top of thestack is an array of values. We push
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005308 * the header value as new entry.
5309 */
5310 lua_pushvalue(L, 3);
5311 ret = lua_rawlen(L, -2);
5312 lua_rawseti(L, -2, ret + 1);
5313 lua_pushboolean(L, 1);
5314 return 1;
5315}
5316
5317__LJMP static int hlua_applet_http_status(lua_State *L)
5318{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005319 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005320 int status = MAY_LJMP(luaL_checkinteger(L, 2));
Robin H. Johnson52f5db22017-01-01 13:10:52 -08005321 const char *reason = MAY_LJMP(luaL_optlstring(L, 3, NULL, NULL));
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005322 struct hlua_http_ctx *http_ctx = luactx->appctx->svcctx;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005323
5324 if (status < 100 || status > 599) {
5325 lua_pushboolean(L, 0);
5326 return 1;
5327 }
5328
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005329 http_ctx->status = status;
5330 http_ctx->reason = reason;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005331 lua_pushboolean(L, 1);
5332 return 1;
5333}
5334
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005335
Christopher Fauleta2097962019-07-15 16:25:33 +02005336__LJMP static int hlua_applet_http_send_response(lua_State *L)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005337{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005338 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005339 struct hlua_http_ctx *http_ctx = luactx->appctx->svcctx;
Willy Tarreauc12b3212022-05-27 11:08:15 +02005340 struct stconn *sc = appctx_sc(luactx->appctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02005341 struct channel *res = sc_ic(sc);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005342 struct htx *htx;
5343 struct htx_sl *sl;
5344 struct h1m h1m;
5345 const char *status, *reason;
5346 const char *name, *value;
5347 size_t nlen, vlen;
5348 unsigned int flags;
5349
5350 /* Send the message at once. */
5351 htx = htx_from_buf(&res->buf);
5352 h1m_init_res(&h1m);
5353
5354 /* Use the same http version than the request. */
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005355 status = ultoa_r(http_ctx->status, trash.area, trash.size);
5356 reason = http_ctx->reason;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005357 if (reason == NULL)
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005358 reason = http_get_reason(http_ctx->status);
5359 if (http_ctx->flags & APPLET_HTTP11) {
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005360 flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11);
5361 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.1"), ist(status), ist(reason));
5362 }
5363 else {
5364 flags = HTX_SL_F_IS_RESP;
5365 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.0"), ist(status), ist(reason));
5366 }
5367 if (!sl) {
5368 hlua_pusherror(L, "Lua applet http '%s': Failed to create response.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005369 luactx->appctx->rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005370 WILL_LJMP(lua_error(L));
5371 }
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005372 sl->info.res.status = http_ctx->status;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005373
5374 /* Get the array associated to the field "response" in the object AppletHTTP. */
5375 lua_pushvalue(L, 0);
5376 if (lua_getfield(L, 1, "response") != LUA_TTABLE) {
5377 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response'] missing.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005378 luactx->appctx->rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005379 WILL_LJMP(lua_error(L));
5380 }
5381
5382 /* Browse the list of headers. */
5383 lua_pushnil(L);
5384 while(lua_next(L, -2) != 0) {
5385 /* We expect a string as -2. */
5386 if (lua_type(L, -2) != LUA_TSTRING) {
5387 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response'][] element must be a string. got %s.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005388 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005389 lua_typename(L, lua_type(L, -2)));
5390 WILL_LJMP(lua_error(L));
5391 }
5392 name = lua_tolstring(L, -2, &nlen);
5393
5394 /* We expect an array as -1. */
5395 if (lua_type(L, -1) != LUA_TTABLE) {
5396 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response']['%s'] element must be an table. got %s.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005397 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005398 name,
5399 lua_typename(L, lua_type(L, -1)));
5400 WILL_LJMP(lua_error(L));
5401 }
5402
5403 /* Browse the table who is on the top of the stack. */
5404 lua_pushnil(L);
5405 while(lua_next(L, -2) != 0) {
5406 int id;
5407
5408 /* We expect a number as -2. */
5409 if (lua_type(L, -2) != LUA_TNUMBER) {
5410 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response']['%s'][] element must be a number. got %s.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005411 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005412 name,
5413 lua_typename(L, lua_type(L, -2)));
5414 WILL_LJMP(lua_error(L));
5415 }
5416 id = lua_tointeger(L, -2);
5417
5418 /* We expect a string as -2. */
5419 if (lua_type(L, -1) != LUA_TSTRING) {
5420 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response']['%s'][%d] element must be a string. got %s.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005421 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005422 name, id,
5423 lua_typename(L, lua_type(L, -1)));
5424 WILL_LJMP(lua_error(L));
5425 }
5426 value = lua_tolstring(L, -1, &vlen);
5427
5428 /* Simple Protocol checks. */
Christopher Faulet545fbba2021-09-28 09:36:25 +02005429 if (isteqi(ist2(name, nlen), ist("transfer-encoding"))) {
5430 int ret;
5431
5432 ret = h1_parse_xfer_enc_header(&h1m, ist2(value, vlen));
5433 if (ret < 0) {
5434 hlua_pusherror(L, "Lua applet http '%s': Invalid '%s' header.\n",
5435 luactx->appctx->rule->arg.hlua_rule->fcn->name,
5436 name);
5437 WILL_LJMP(lua_error(L));
5438 }
5439 else if (ret == 0)
5440 goto next; /* Skip it */
5441 }
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005442 else if (isteqi(ist2(name, nlen), ist("content-length"))) {
5443 struct ist v = ist2(value, vlen);
5444 int ret;
5445
5446 ret = h1_parse_cont_len_header(&h1m, &v);
5447 if (ret < 0) {
5448 hlua_pusherror(L, "Lua applet http '%s': Invalid '%s' header.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005449 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005450 name);
5451 WILL_LJMP(lua_error(L));
5452 }
5453 else if (ret == 0)
5454 goto next; /* Skip it */
5455 }
5456
5457 /* Add a new header */
5458 if (!htx_add_header(htx, ist2(name, nlen), ist2(value, vlen))) {
5459 hlua_pusherror(L, "Lua applet http '%s': Failed to add header '%s' in the response.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005460 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005461 name);
5462 WILL_LJMP(lua_error(L));
5463 }
5464 next:
5465 /* Remove the array from the stack, and get next element with a remaining string. */
5466 lua_pop(L, 1);
5467 }
5468
5469 /* Remove the array from the stack, and get next element with a remaining string. */
5470 lua_pop(L, 1);
5471 }
5472
5473 if (h1m.flags & H1_MF_CHNK)
5474 h1m.flags &= ~H1_MF_CLEN;
5475 if (h1m.flags & (H1_MF_CLEN|H1_MF_CHNK))
5476 h1m.flags |= H1_MF_XFER_LEN;
5477
5478 /* Uset HTX start-line flags */
5479 if (h1m.flags & H1_MF_XFER_ENC)
5480 flags |= HTX_SL_F_XFER_ENC;
5481 if (h1m.flags & H1_MF_XFER_LEN) {
5482 flags |= HTX_SL_F_XFER_LEN;
5483 if (h1m.flags & H1_MF_CHNK)
5484 flags |= HTX_SL_F_CHNK;
5485 else if (h1m.flags & H1_MF_CLEN)
5486 flags |= HTX_SL_F_CLEN;
5487 if (h1m.body_len == 0)
5488 flags |= HTX_SL_F_BODYLESS;
5489 }
5490 sl->flags |= flags;
5491
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -07005492 /* If we don't have a content-length set, and the HTTP version is 1.1
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005493 * and the status code implies the presence of a message body, we must
5494 * announce a transfer encoding chunked. This is required by haproxy
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05005495 * for the keepalive compliance. If the applet announces a transfer-encoding
5496 * chunked itself, don't do anything.
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005497 */
5498 if ((flags & (HTX_SL_F_VER_11|HTX_SL_F_XFER_LEN)) == HTX_SL_F_VER_11 &&
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005499 http_ctx->status >= 200 && http_ctx->status != 204 && http_ctx->status != 304) {
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005500 /* Add a new header */
5501 sl->flags |= (HTX_SL_F_XFER_ENC|H1_MF_CHNK|H1_MF_XFER_LEN);
5502 if (!htx_add_header(htx, ist("transfer-encoding"), ist("chunked"))) {
5503 hlua_pusherror(L, "Lua applet http '%s': Failed to add header 'transfer-encoding' in the response.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005504 luactx->appctx->rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005505 WILL_LJMP(lua_error(L));
5506 }
5507 }
5508
5509 /* Finalize headers. */
5510 if (!htx_add_endof(htx, HTX_BLK_EOH)) {
5511 hlua_pusherror(L, "Lua applet http '%s': Failed create the response.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005512 luactx->appctx->rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005513 WILL_LJMP(lua_error(L));
5514 }
5515
5516 if (htx_used_space(htx) > b_size(&res->buf) - global.tune.maxrewrite) {
5517 b_reset(&res->buf);
5518 hlua_pusherror(L, "Lua: 'start_response': response header block too big");
5519 WILL_LJMP(lua_error(L));
5520 }
5521
5522 htx_to_buf(htx, &res->buf);
Christopher Fauletf6cce3f2019-02-27 21:20:09 +01005523 channel_add_input(res, htx->data);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005524
5525 /* Headers sent, set the flag. */
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005526 http_ctx->flags |= APPLET_HDR_SENT;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005527 return 0;
5528
5529}
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005530/* We will build the status line and the headers of the HTTP response.
5531 * We will try send at once if its not possible, we give back the hand
5532 * waiting for more room.
5533 */
Christopher Fauleta2097962019-07-15 16:25:33 +02005534__LJMP static int hlua_applet_http_start_response_yield(lua_State *L, int status, lua_KContext ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005535{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005536 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Willy Tarreauc12b3212022-05-27 11:08:15 +02005537 struct stconn *sc = appctx_sc(luactx->appctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02005538 struct channel *res = sc_ic(sc);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005539
5540 if (co_data(res)) {
Willy Tarreau3e7be362022-05-27 10:35:27 +02005541 sc_need_room(sc);
Christopher Fauleta2097962019-07-15 16:25:33 +02005542 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_start_response_yield, TICK_ETERNITY, 0));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005543 }
Christopher Fauleta2097962019-07-15 16:25:33 +02005544 return MAY_LJMP(hlua_applet_http_send_response(L));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005545}
5546
5547
Christopher Fauleta2097962019-07-15 16:25:33 +02005548__LJMP static int hlua_applet_http_start_response(lua_State *L)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005549{
Christopher Fauleta2097962019-07-15 16:25:33 +02005550 return MAY_LJMP(hlua_applet_http_start_response_yield(L, 0, 0));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005551}
5552
Christopher Fauleta2097962019-07-15 16:25:33 +02005553/*
5554 *
5555 *
5556 * Class HTTP
5557 *
5558 *
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005559 */
Christopher Fauleta2097962019-07-15 16:25:33 +02005560
5561/* Returns a struct hlua_txn if the stack entry "ud" is
5562 * a class stream, otherwise it throws an error.
5563 */
5564__LJMP static struct hlua_txn *hlua_checkhttp(lua_State *L, int ud)
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005565{
Christopher Fauleta2097962019-07-15 16:25:33 +02005566 return MAY_LJMP(hlua_checkudata(L, ud, class_http_ref));
5567}
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005568
Christopher Fauleta2097962019-07-15 16:25:33 +02005569/* This function creates and push in the stack a HTTP object
5570 * according with a current TXN.
5571 */
5572static int hlua_http_new(lua_State *L, struct hlua_txn *txn)
5573{
5574 struct hlua_txn *htxn;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005575
Christopher Fauleta2097962019-07-15 16:25:33 +02005576 /* Check stack size. */
5577 if (!lua_checkstack(L, 3))
5578 return 0;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005579
Christopher Fauleta2097962019-07-15 16:25:33 +02005580 /* Create the object: obj[0] = userdata.
5581 * Note that the base of the Converters object is the
5582 * same than the TXN object.
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005583 */
Christopher Fauleta2097962019-07-15 16:25:33 +02005584 lua_newtable(L);
5585 htxn = lua_newuserdata(L, sizeof(*htxn));
5586 lua_rawseti(L, -2, 0);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005587
5588 htxn->s = txn->s;
5589 htxn->p = txn->p;
Christopher Faulet256b69a2019-05-23 11:14:21 +02005590 htxn->dir = txn->dir;
5591 htxn->flags = txn->flags;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005592
5593 /* Pop a class stream metatable and affect it to the table. */
5594 lua_rawgeti(L, LUA_REGISTRYINDEX, class_http_ref);
5595 lua_setmetatable(L, -2);
5596
5597 return 1;
5598}
5599
Christopher Fauletdf97ac42020-02-26 16:57:19 +01005600/* This function creates and returns an array containing the status-line
5601 * elements. This function does not fails.
5602 */
5603__LJMP static int hlua_http_get_stline(lua_State *L, struct htx_sl *sl)
5604{
5605 /* Create the table. */
5606 lua_newtable(L);
5607
5608 if (sl->flags & HTX_SL_F_IS_RESP) {
5609 lua_pushstring(L, "version");
5610 lua_pushlstring(L, HTX_SL_RES_VPTR(sl), HTX_SL_RES_VLEN(sl));
5611 lua_settable(L, -3);
5612 lua_pushstring(L, "code");
5613 lua_pushlstring(L, HTX_SL_RES_CPTR(sl), HTX_SL_RES_CLEN(sl));
5614 lua_settable(L, -3);
5615 lua_pushstring(L, "reason");
5616 lua_pushlstring(L, HTX_SL_RES_RPTR(sl), HTX_SL_RES_RLEN(sl));
5617 lua_settable(L, -3);
5618 }
5619 else {
5620 lua_pushstring(L, "method");
5621 lua_pushlstring(L, HTX_SL_REQ_MPTR(sl), HTX_SL_REQ_MLEN(sl));
5622 lua_settable(L, -3);
5623 lua_pushstring(L, "uri");
5624 lua_pushlstring(L, HTX_SL_REQ_UPTR(sl), HTX_SL_REQ_ULEN(sl));
5625 lua_settable(L, -3);
5626 lua_pushstring(L, "version");
5627 lua_pushlstring(L, HTX_SL_REQ_VPTR(sl), HTX_SL_REQ_VLEN(sl));
5628 lua_settable(L, -3);
5629 }
5630 return 1;
5631}
5632
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005633/* This function creates ans returns an array of HTTP headers.
5634 * This function does not fails. It is used as wrapper with the
5635 * 2 following functions.
5636 */
Christopher Faulet9d1332b2020-02-24 16:46:16 +01005637__LJMP static int hlua_http_get_headers(lua_State *L, struct http_msg *msg)
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005638{
Christopher Fauleta2097962019-07-15 16:25:33 +02005639 struct htx *htx;
5640 int32_t pos;
5641
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005642 /* Create the table. */
5643 lua_newtable(L);
5644
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005645
Christopher Fauleta2097962019-07-15 16:25:33 +02005646 htx = htxbuf(&msg->chn->buf);
5647 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
5648 struct htx_blk *blk = htx_get_blk(htx, pos);
5649 enum htx_blk_type type = htx_get_blk_type(blk);
5650 struct ist n, v;
5651 int len;
Christopher Faulet724a12c2018-12-13 22:12:15 +01005652
Christopher Fauleta2097962019-07-15 16:25:33 +02005653 if (type == HTX_BLK_HDR) {
5654 n = htx_get_blk_name(htx,blk);
5655 v = htx_get_blk_value(htx, blk);
Christopher Faulet724a12c2018-12-13 22:12:15 +01005656 }
Christopher Fauleta2097962019-07-15 16:25:33 +02005657 else if (type == HTX_BLK_EOH)
5658 break;
5659 else
5660 continue;
Christopher Faulet724a12c2018-12-13 22:12:15 +01005661
Christopher Fauleta2097962019-07-15 16:25:33 +02005662 /* Check for existing entry:
5663 * assume that the table is on the top of the stack, and
5664 * push the key in the stack, the function lua_gettable()
5665 * perform the lookup.
5666 */
5667 lua_pushlstring(L, n.ptr, n.len);
5668 lua_gettable(L, -2);
Christopher Faulet724a12c2018-12-13 22:12:15 +01005669
Christopher Fauleta2097962019-07-15 16:25:33 +02005670 switch (lua_type(L, -1)) {
5671 case LUA_TNIL:
5672 /* Table not found, create it. */
5673 lua_pop(L, 1); /* remove the nil value. */
5674 lua_pushlstring(L, n.ptr, n.len); /* push the header name as key. */
5675 lua_newtable(L); /* create and push empty table. */
5676 lua_pushlstring(L, v.ptr, v.len); /* push header value. */
5677 lua_rawseti(L, -2, 0); /* index header value (pop it). */
5678 lua_rawset(L, -3); /* index new table with header name (pop the values). */
Christopher Faulet724a12c2018-12-13 22:12:15 +01005679 break;
Christopher Faulet724a12c2018-12-13 22:12:15 +01005680
Christopher Fauleta2097962019-07-15 16:25:33 +02005681 case LUA_TTABLE:
5682 /* Entry found: push the value in the table. */
5683 len = lua_rawlen(L, -1);
5684 lua_pushlstring(L, v.ptr, v.len); /* push header value. */
5685 lua_rawseti(L, -2, len+1); /* index header value (pop it). */
5686 lua_pop(L, 1); /* remove the table (it is stored in the main table). */
5687 break;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005688
Christopher Fauleta2097962019-07-15 16:25:33 +02005689 default:
5690 /* Other cases are errors. */
5691 hlua_pusherror(L, "internal error during the parsing of headers.");
5692 WILL_LJMP(lua_error(L));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005693 }
5694 }
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005695 return 1;
5696}
5697
5698__LJMP static int hlua_http_req_get_headers(lua_State *L)
5699{
5700 struct hlua_txn *htxn;
5701
5702 MAY_LJMP(check_args(L, 1, "req_get_headers"));
5703 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5704
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005705 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005706 WILL_LJMP(lua_error(L));
5707
Christopher Faulet9d1332b2020-02-24 16:46:16 +01005708 return hlua_http_get_headers(L, &htxn->s->txn->req);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005709}
5710
5711__LJMP static int hlua_http_res_get_headers(lua_State *L)
5712{
5713 struct hlua_txn *htxn;
5714
5715 MAY_LJMP(check_args(L, 1, "res_get_headers"));
5716 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5717
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005718 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005719 WILL_LJMP(lua_error(L));
5720
Christopher Faulet9d1332b2020-02-24 16:46:16 +01005721 return hlua_http_get_headers(L, &htxn->s->txn->rsp);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005722}
5723
5724/* This function replace full header, or just a value in
5725 * the request or in the response. It is a wrapper fir the
5726 * 4 following functions.
5727 */
Christopher Fauletd1914aa2020-02-24 16:52:46 +01005728__LJMP static inline int hlua_http_rep_hdr(lua_State *L, struct http_msg *msg, int full)
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005729{
5730 size_t name_len;
5731 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
5732 const char *reg = MAY_LJMP(luaL_checkstring(L, 3));
5733 const char *value = MAY_LJMP(luaL_checkstring(L, 4));
Christopher Fauleta2097962019-07-15 16:25:33 +02005734 struct htx *htx;
Dragan Dosen26743032019-04-30 15:54:36 +02005735 struct my_regex *re;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005736
Dragan Dosen26743032019-04-30 15:54:36 +02005737 if (!(re = regex_comp(reg, 1, 1, NULL)))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005738 WILL_LJMP(luaL_argerror(L, 3, "invalid regex"));
5739
Christopher Fauleta2097962019-07-15 16:25:33 +02005740 htx = htxbuf(&msg->chn->buf);
Christopher Fauletd1914aa2020-02-24 16:52:46 +01005741 http_replace_hdrs(chn_strm(msg->chn), htx, ist2(name, name_len), value, re, full);
Dragan Dosen26743032019-04-30 15:54:36 +02005742 regex_free(re);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005743 return 0;
5744}
5745
5746__LJMP static int hlua_http_req_rep_hdr(lua_State *L)
5747{
5748 struct hlua_txn *htxn;
5749
5750 MAY_LJMP(check_args(L, 4, "req_rep_hdr"));
5751 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5752
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005753 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005754 WILL_LJMP(lua_error(L));
5755
Christopher Fauletd1914aa2020-02-24 16:52:46 +01005756 return MAY_LJMP(hlua_http_rep_hdr(L, &htxn->s->txn->req, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005757}
5758
5759__LJMP static int hlua_http_res_rep_hdr(lua_State *L)
5760{
5761 struct hlua_txn *htxn;
5762
5763 MAY_LJMP(check_args(L, 4, "res_rep_hdr"));
5764 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5765
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005766 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005767 WILL_LJMP(lua_error(L));
5768
Christopher Fauletd1914aa2020-02-24 16:52:46 +01005769 return MAY_LJMP(hlua_http_rep_hdr(L, &htxn->s->txn->rsp, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005770}
5771
5772__LJMP static int hlua_http_req_rep_val(lua_State *L)
5773{
5774 struct hlua_txn *htxn;
5775
5776 MAY_LJMP(check_args(L, 4, "req_rep_hdr"));
5777 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5778
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005779 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005780 WILL_LJMP(lua_error(L));
5781
Christopher Fauletd1914aa2020-02-24 16:52:46 +01005782 return MAY_LJMP(hlua_http_rep_hdr(L, &htxn->s->txn->req, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005783}
5784
5785__LJMP static int hlua_http_res_rep_val(lua_State *L)
5786{
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005787 struct hlua_txn *htxn;
5788
5789 MAY_LJMP(check_args(L, 4, "res_rep_val"));
5790 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5791
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005792 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005793 WILL_LJMP(lua_error(L));
5794
Christopher Fauletd1914aa2020-02-24 16:52:46 +01005795 return MAY_LJMP(hlua_http_rep_hdr(L, &htxn->s->txn->rsp, 0));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005796}
5797
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08005798/* This function deletes all the occurrences of an header.
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005799 * It is a wrapper for the 2 following functions.
5800 */
Christopher Fauletd31c7b32020-02-25 09:37:57 +01005801__LJMP static inline int hlua_http_del_hdr(lua_State *L, struct http_msg *msg)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005802{
5803 size_t len;
5804 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Christopher Fauleta2097962019-07-15 16:25:33 +02005805 struct htx *htx = htxbuf(&msg->chn->buf);
5806 struct http_hdr_ctx ctx;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005807
Christopher Fauleta2097962019-07-15 16:25:33 +02005808 ctx.blk = NULL;
5809 while (http_find_header(htx, ist2(name, len), &ctx, 1))
5810 http_remove_header(htx, &ctx);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005811 return 0;
5812}
5813
5814__LJMP static int hlua_http_req_del_hdr(lua_State *L)
5815{
5816 struct hlua_txn *htxn;
5817
5818 MAY_LJMP(check_args(L, 2, "req_del_hdr"));
5819 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5820
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005821 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005822 WILL_LJMP(lua_error(L));
5823
Christopher Fauletd31c7b32020-02-25 09:37:57 +01005824 return hlua_http_del_hdr(L, &htxn->s->txn->req);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005825}
5826
5827__LJMP static int hlua_http_res_del_hdr(lua_State *L)
5828{
5829 struct hlua_txn *htxn;
5830
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005831 MAY_LJMP(check_args(L, 2, "res_del_hdr"));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005832 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5833
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005834 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005835 WILL_LJMP(lua_error(L));
5836
Christopher Fauletd31c7b32020-02-25 09:37:57 +01005837 return hlua_http_del_hdr(L, &htxn->s->txn->rsp);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005838}
5839
5840/* This function adds an header. It is a wrapper used by
5841 * the 2 following functions.
5842 */
Christopher Fauletd31c7b32020-02-25 09:37:57 +01005843__LJMP static inline int hlua_http_add_hdr(lua_State *L, struct http_msg *msg)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005844{
5845 size_t name_len;
5846 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
5847 size_t value_len;
5848 const char *value = MAY_LJMP(luaL_checklstring(L, 3, &value_len));
Christopher Fauleta2097962019-07-15 16:25:33 +02005849 struct htx *htx = htxbuf(&msg->chn->buf);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005850
Christopher Fauleta2097962019-07-15 16:25:33 +02005851 lua_pushboolean(L, http_add_header(htx, ist2(name, name_len),
5852 ist2(value, value_len)));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005853 return 0;
5854}
5855
Christopher Fauletdf97ac42020-02-26 16:57:19 +01005856__LJMP static int hlua_http_req_add_hdr(lua_State *L)
5857{
5858 struct hlua_txn *htxn;
5859
5860 MAY_LJMP(check_args(L, 3, "req_add_hdr"));
5861 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5862
5863 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
5864 WILL_LJMP(lua_error(L));
5865
5866 return hlua_http_add_hdr(L, &htxn->s->txn->req);
5867}
5868
5869__LJMP static int hlua_http_res_add_hdr(lua_State *L)
5870{
5871 struct hlua_txn *htxn;
5872
5873 MAY_LJMP(check_args(L, 3, "res_add_hdr"));
5874 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5875
5876 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
5877 WILL_LJMP(lua_error(L));
5878
5879 return hlua_http_add_hdr(L, &htxn->s->txn->rsp);
5880}
5881
5882static int hlua_http_req_set_hdr(lua_State *L)
5883{
5884 struct hlua_txn *htxn;
5885
5886 MAY_LJMP(check_args(L, 3, "req_set_hdr"));
5887 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5888
5889 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
5890 WILL_LJMP(lua_error(L));
5891
5892 hlua_http_del_hdr(L, &htxn->s->txn->req);
5893 return hlua_http_add_hdr(L, &htxn->s->txn->req);
5894}
5895
5896static int hlua_http_res_set_hdr(lua_State *L)
5897{
5898 struct hlua_txn *htxn;
5899
5900 MAY_LJMP(check_args(L, 3, "res_set_hdr"));
5901 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5902
5903 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
5904 WILL_LJMP(lua_error(L));
5905
5906 hlua_http_del_hdr(L, &htxn->s->txn->rsp);
5907 return hlua_http_add_hdr(L, &htxn->s->txn->rsp);
5908}
5909
5910/* This function set the method. */
5911static int hlua_http_req_set_meth(lua_State *L)
5912{
5913 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5914 size_t name_len;
5915 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
5916
5917 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
5918 WILL_LJMP(lua_error(L));
5919
5920 lua_pushboolean(L, http_req_replace_stline(0, name, name_len, htxn->p, htxn->s) != -1);
5921 return 1;
5922}
5923
5924/* This function set the method. */
5925static int hlua_http_req_set_path(lua_State *L)
5926{
5927 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5928 size_t name_len;
5929 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
5930
5931 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
5932 WILL_LJMP(lua_error(L));
5933
5934 lua_pushboolean(L, http_req_replace_stline(1, name, name_len, htxn->p, htxn->s) != -1);
5935 return 1;
5936}
5937
5938/* This function set the query-string. */
5939static int hlua_http_req_set_query(lua_State *L)
5940{
5941 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5942 size_t name_len;
5943 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
5944
5945 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
5946 WILL_LJMP(lua_error(L));
5947
5948 /* Check length. */
5949 if (name_len > trash.size - 1) {
5950 lua_pushboolean(L, 0);
5951 return 1;
5952 }
5953
5954 /* Add the mark question as prefix. */
5955 chunk_reset(&trash);
5956 trash.area[trash.data++] = '?';
5957 memcpy(trash.area + trash.data, name, name_len);
5958 trash.data += name_len;
5959
5960 lua_pushboolean(L,
5961 http_req_replace_stline(2, trash.area, trash.data, htxn->p, htxn->s) != -1);
5962 return 1;
5963}
5964
5965/* This function set the uri. */
5966static int hlua_http_req_set_uri(lua_State *L)
5967{
5968 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5969 size_t name_len;
5970 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
5971
5972 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
5973 WILL_LJMP(lua_error(L));
5974
5975 lua_pushboolean(L, http_req_replace_stline(3, name, name_len, htxn->p, htxn->s) != -1);
5976 return 1;
5977}
5978
5979/* This function set the response code & optionally reason. */
5980static int hlua_http_res_set_status(lua_State *L)
5981{
5982 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5983 unsigned int code = MAY_LJMP(luaL_checkinteger(L, 2));
5984 const char *str = MAY_LJMP(luaL_optlstring(L, 3, NULL, NULL));
5985 const struct ist reason = ist2(str, (str ? strlen(str) : 0));
5986
5987 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
5988 WILL_LJMP(lua_error(L));
5989
5990 http_res_set_status(code, reason, htxn->s);
5991 return 0;
5992}
5993
5994/*
5995 *
5996 *
5997 * Class HTTPMessage
5998 *
5999 *
6000 */
6001
6002/* Returns a struct http_msg if the stack entry "ud" is a class HTTPMessage,
6003 * otherwise it throws an error.
6004 */
6005__LJMP static struct http_msg *hlua_checkhttpmsg(lua_State *L, int ud)
6006{
6007 return MAY_LJMP(hlua_checkudata(L, ud, class_http_msg_ref));
6008}
6009
6010/* Creates and pushes on the stack a HTTP object according with a current TXN.
6011 */
Christopher Faulet78c35472020-02-26 17:14:08 +01006012static int hlua_http_msg_new(lua_State *L, struct http_msg *msg)
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006013{
6014 /* Check stack size. */
6015 if (!lua_checkstack(L, 3))
6016 return 0;
6017
6018 lua_newtable(L);
6019 lua_pushlightuserdata(L, msg);
6020 lua_rawseti(L, -2, 0);
6021
6022 /* Create the "channel" field that contains the request channel object. */
6023 lua_pushstring(L, "channel");
6024 if (!hlua_channel_new(L, msg->chn))
6025 return 0;
6026 lua_rawset(L, -3);
6027
6028 /* Pop a class stream metatable and affect it to the table. */
6029 lua_rawgeti(L, LUA_REGISTRYINDEX, class_http_msg_ref);
6030 lua_setmetatable(L, -2);
6031
6032 return 1;
6033}
6034
6035/* Helper function returning a filter attached to the HTTP message at the
6036 * position <ud> in the stack, filling the current offset and length of the
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006037 * filter. If no filter is attached, NULL is returned and <offset> and <len> are
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006038 * filled with output and input length respectively.
6039 */
6040static struct filter *hlua_http_msg_filter(lua_State *L, int ud, struct http_msg *msg, size_t *offset, size_t *len)
6041{
6042 struct channel *chn = msg->chn;
6043 struct htx *htx = htxbuf(&chn->buf);
6044 struct filter *filter = NULL;
6045
6046 *offset = co_data(msg->chn);
6047 *len = htx->data - co_data(msg->chn);
6048
6049 if (lua_getfield(L, ud, "__filter") == LUA_TLIGHTUSERDATA) {
6050 filter = lua_touserdata (L, -1);
6051 if (msg->msg_state >= HTTP_MSG_DATA) {
6052 struct hlua_flt_ctx *flt_ctx = filter->ctx;
6053
6054 *offset = flt_ctx->cur_off[CHN_IDX(chn)];
6055 *len = flt_ctx->cur_len[CHN_IDX(chn)];
6056 }
6057 }
6058
6059 lua_pop(L, 1);
6060 return filter;
6061}
6062
6063/* Returns true if the channel attached to the HTTP message is the response
6064 * channel.
6065 */
6066__LJMP static int hlua_http_msg_is_resp(lua_State *L)
6067{
6068 struct http_msg *msg;
6069
6070 MAY_LJMP(check_args(L, 1, "is_resp"));
6071 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6072
6073 lua_pushboolean(L, !!(msg->chn->flags & CF_ISRESP));
6074 return 1;
6075}
6076
6077/* Returns an array containing the elements status-line of the HTTP message. It relies
6078 * on hlua_http_get_stline().
6079 */
6080__LJMP static int hlua_http_msg_get_stline(lua_State *L)
6081{
6082 struct http_msg *msg;
6083 struct htx *htx;
6084 struct htx_sl *sl;
6085
6086 MAY_LJMP(check_args(L, 1, "get_stline"));
6087 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6088
6089 if (msg->msg_state > HTTP_MSG_BODY)
6090 WILL_LJMP(lua_error(L));
6091
6092 htx = htxbuf(&msg->chn->buf);
6093 sl = http_get_stline(htx);
6094 if (!sl)
6095 return 0;
6096 return hlua_http_get_stline(L, sl);
6097}
6098
6099/* Returns an array containing all headers of the HTTP message. it relies on
6100 * hlua_http_get_headers().
6101 */
6102__LJMP static int hlua_http_msg_get_headers(lua_State *L)
6103{
6104 struct http_msg *msg;
6105
6106 MAY_LJMP(check_args(L, 1, "get_headers"));
6107 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6108
6109 if (msg->msg_state > HTTP_MSG_BODY)
6110 WILL_LJMP(lua_error(L));
6111
6112 return hlua_http_get_headers(L, msg);
6113}
6114
6115/* Deletes all occurrences of an header in the HTTP message matching on its
6116 * name. It relies on hlua_http_del_hdr().
6117 */
6118__LJMP static int hlua_http_msg_del_hdr(lua_State *L)
6119{
6120 struct http_msg *msg;
6121
6122 MAY_LJMP(check_args(L, 2, "del_header"));
6123 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6124
6125 if (msg->msg_state > HTTP_MSG_BODY)
6126 WILL_LJMP(lua_error(L));
6127
6128 return hlua_http_del_hdr(L, msg);
6129}
6130
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006131/* Matches the full value line of all occurrences of an header in the HTTP
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006132 * message given its name against a regex and replaces it if it matches. It
6133 * relies on hlua_http_rep_hdr().
6134 */
6135__LJMP static int hlua_http_msg_rep_hdr(lua_State *L)
6136{
6137 struct http_msg *msg;
6138
6139 MAY_LJMP(check_args(L, 4, "rep_header"));
6140 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6141
6142 if (msg->msg_state > HTTP_MSG_BODY)
6143 WILL_LJMP(lua_error(L));
6144
6145 return hlua_http_rep_hdr(L, msg, 1);
6146}
6147
Ilya Shipitsinbd6b4be2021-10-15 16:18:21 +05006148/* Matches all comma-separated values of all occurrences of an header in the HTTP
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006149 * message given its name against a regex and replaces it if it matches. It
6150 * relies on hlua_http_rep_hdr().
6151 */
6152__LJMP static int hlua_http_msg_rep_val(lua_State *L)
6153{
6154 struct http_msg *msg;
6155
6156 MAY_LJMP(check_args(L, 4, "rep_value"));
6157 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6158
6159 if (msg->msg_state > HTTP_MSG_BODY)
6160 WILL_LJMP(lua_error(L));
6161
6162 return hlua_http_rep_hdr(L, msg, 0);
6163}
6164
6165/* Add an header in the HTTP message. It relies on hlua_http_add_hdr() */
6166__LJMP static int hlua_http_msg_add_hdr(lua_State *L)
6167{
6168 struct http_msg *msg;
6169
6170 MAY_LJMP(check_args(L, 3, "add_header"));
6171 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6172
6173 if (msg->msg_state > HTTP_MSG_BODY)
6174 WILL_LJMP(lua_error(L));
6175
6176 return hlua_http_add_hdr(L, msg);
6177}
6178
6179/* Add an header in the HTTP message removing existing headers with the same
6180 * name. It relies on hlua_http_del_hdr() and hlua_http_add_hdr().
6181 */
6182__LJMP static int hlua_http_msg_set_hdr(lua_State *L)
6183{
6184 struct http_msg *msg;
6185
6186 MAY_LJMP(check_args(L, 3, "set_header"));
6187 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6188
6189 if (msg->msg_state > HTTP_MSG_BODY)
6190 WILL_LJMP(lua_error(L));
6191
6192 hlua_http_del_hdr(L, msg);
6193 return hlua_http_add_hdr(L, msg);
6194}
6195
6196/* Rewrites the request method. It relies on http_req_replace_stline(). */
6197__LJMP static int hlua_http_msg_set_meth(lua_State *L)
6198{
6199 struct stream *s;
6200 struct http_msg *msg;
6201 const char *name;
6202 size_t name_len;
6203
6204 MAY_LJMP(check_args(L, 2, "set_method"));
6205 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6206 name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
6207
6208 if ((msg->chn->flags & CF_ISRESP) || msg->msg_state > HTTP_MSG_BODY)
6209 WILL_LJMP(lua_error(L));
6210
6211 s = chn_strm(msg->chn);
6212 lua_pushboolean(L, http_req_replace_stline(0, name, name_len, s->be, s) != -1);
6213 return 1;
6214}
6215
6216/* Rewrites the request path. It relies on http_req_replace_stline(). */
6217__LJMP static int hlua_http_msg_set_path(lua_State *L)
6218{
6219 struct stream *s;
6220 struct http_msg *msg;
6221 const char *name;
6222 size_t name_len;
6223
6224 MAY_LJMP(check_args(L, 2, "set_path"));
6225 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6226 name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
6227
6228 if ((msg->chn->flags & CF_ISRESP) || msg->msg_state > HTTP_MSG_BODY)
6229 WILL_LJMP(lua_error(L));
6230
6231 s = chn_strm(msg->chn);
6232 lua_pushboolean(L, http_req_replace_stline(1, name, name_len, s->be, s) != -1);
6233 return 1;
6234}
6235
6236/* Rewrites the request query-string. It relies on http_req_replace_stline(). */
6237__LJMP static int hlua_http_msg_set_query(lua_State *L)
6238{
6239 struct stream *s;
6240 struct http_msg *msg;
6241 const char *name;
6242 size_t name_len;
6243
6244 MAY_LJMP(check_args(L, 2, "set_query"));
6245 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6246 name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
6247
6248 if ((msg->chn->flags & CF_ISRESP) || msg->msg_state > HTTP_MSG_BODY)
6249 WILL_LJMP(lua_error(L));
6250
6251 /* Check length. */
6252 if (name_len > trash.size - 1) {
6253 lua_pushboolean(L, 0);
6254 return 1;
6255 }
6256
6257 /* Add the mark question as prefix. */
6258 chunk_reset(&trash);
6259 trash.area[trash.data++] = '?';
6260 memcpy(trash.area + trash.data, name, name_len);
6261 trash.data += name_len;
6262
6263 s = chn_strm(msg->chn);
6264 lua_pushboolean(L, http_req_replace_stline(2, trash.area, trash.data, s->be, s) != -1);
6265 return 1;
6266}
6267
6268/* Rewrites the request URI. It relies on http_req_replace_stline(). */
6269__LJMP static int hlua_http_msg_set_uri(lua_State *L)
6270{
6271 struct stream *s;
6272 struct http_msg *msg;
6273 const char *name;
6274 size_t name_len;
6275
6276 MAY_LJMP(check_args(L, 2, "set_uri"));
6277 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6278 name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
6279
6280 if ((msg->chn->flags & CF_ISRESP) || msg->msg_state > HTTP_MSG_BODY)
6281 WILL_LJMP(lua_error(L));
6282
6283 s = chn_strm(msg->chn);
6284 lua_pushboolean(L, http_req_replace_stline(3, name, name_len, s->be, s) != -1);
6285 return 1;
6286}
6287
6288/* Rewrites the response status code. It relies on http_res_set_status(). */
6289__LJMP static int hlua_http_msg_set_status(lua_State *L)
6290{
6291 struct http_msg *msg;
6292 unsigned int code;
6293 const char *reason;
6294 size_t reason_len;
6295
6296 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6297 code = MAY_LJMP(luaL_checkinteger(L, 2));
6298 reason = MAY_LJMP(luaL_optlstring(L, 3, NULL, &reason_len));
6299
6300 if (!(msg->chn->flags & CF_ISRESP) || msg->msg_state > HTTP_MSG_BODY)
6301 WILL_LJMP(lua_error(L));
6302
6303 lua_pushboolean(L, http_res_set_status(code, ist2(reason, reason_len), chn_strm(msg->chn)) != -1);
6304 return 1;
6305}
6306
6307/* Returns true if the HTTP message is full. */
6308__LJMP static int hlua_http_msg_is_full(lua_State *L)
6309{
6310 struct http_msg *msg;
6311
6312 MAY_LJMP(check_args(L, 1, "is_full"));
6313 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6314 lua_pushboolean(L, channel_full(msg->chn, 0));
6315 return 1;
6316}
6317
6318/* Returns true if the HTTP message may still receive data. */
6319__LJMP static int hlua_http_msg_may_recv(lua_State *L)
6320{
6321 struct http_msg *msg;
6322 struct htx *htx;
6323
6324 MAY_LJMP(check_args(L, 1, "may_recv"));
6325 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6326 htx = htxbuf(&msg->chn->buf);
6327 lua_pushboolean(L, (htx_expect_more(htx) && !channel_input_closed(msg->chn) && channel_may_recv(msg->chn)));
6328 return 1;
6329}
6330
6331/* Returns true if the HTTP message EOM was received */
6332__LJMP static int hlua_http_msg_is_eom(lua_State *L)
6333{
6334 struct http_msg *msg;
6335 struct htx *htx;
6336
6337 MAY_LJMP(check_args(L, 1, "may_recv"));
6338 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6339 htx = htxbuf(&msg->chn->buf);
6340 lua_pushboolean(L, !htx_expect_more(htx));
6341 return 1;
6342}
6343
6344/* Returns the number of bytes available in the input side of the HTTP
6345 * message. This function never fails.
6346 */
6347__LJMP static int hlua_http_msg_get_in_len(lua_State *L)
6348{
6349 struct http_msg *msg;
Christopher Fauleteae8afa2020-02-26 17:15:48 +01006350 size_t output, input;
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006351
6352 MAY_LJMP(check_args(L, 1, "input"));
6353 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
Christopher Fauleteae8afa2020-02-26 17:15:48 +01006354 hlua_http_msg_filter(L, 1, msg, &output, &input);
6355 lua_pushinteger(L, input);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006356 return 1;
6357}
6358
6359/* Returns the number of bytes available in the output side of the HTTP
6360 * message. This function never fails.
6361 */
6362__LJMP static int hlua_http_msg_get_out_len(lua_State *L)
6363{
6364 struct http_msg *msg;
Christopher Fauleteae8afa2020-02-26 17:15:48 +01006365 size_t output, input;
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006366
6367 MAY_LJMP(check_args(L, 1, "output"));
6368 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
Christopher Fauleteae8afa2020-02-26 17:15:48 +01006369 hlua_http_msg_filter(L, 1, msg, &output, &input);
6370 lua_pushinteger(L, output);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006371 return 1;
6372}
6373
6374/* Copies at most <len> bytes of DATA blocks from the HTTP message <msg>
6375 * starting at the offset <offset> and put it in a string LUA variables. It
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006376 * returns the built string length. It stops on the first non-DATA HTX
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006377 * block. This function is called during the payload filtering, so the headers
6378 * are already scheduled for output (from the filter point of view).
6379 */
6380static int _hlua_http_msg_dup(struct http_msg *msg, lua_State *L, size_t offset, size_t len)
6381{
6382 struct htx *htx = htxbuf(&msg->chn->buf);
6383 struct htx_blk *blk;
6384 struct htx_ret htxret;
6385 luaL_Buffer b;
6386 int ret = 0;
6387
6388 luaL_buffinit(L, &b);
6389 htxret = htx_find_offset(htx, offset);
6390 for (blk = htxret.blk, offset = htxret.ret; blk && len; blk = htx_get_next_blk(htx, blk)) {
6391 enum htx_blk_type type = htx_get_blk_type(blk);
6392 struct ist v;
6393
6394 switch (type) {
6395 case HTX_BLK_UNUSED:
6396 break;
6397
6398 case HTX_BLK_DATA:
6399 v = htx_get_blk_value(htx, blk);
Tim Duesterhusb113b5c2021-09-15 13:58:44 +02006400 v = istadv(v, offset);
Tim Duesterhus2471f5c2021-11-08 09:05:01 +01006401 v = isttrim(v, len);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006402
6403 luaL_addlstring(&b, v.ptr, v.len);
6404 ret += v.len;
6405 break;
6406
6407 default:
vishnu0af4bd72021-10-24 06:46:24 +05306408 if (!ret)
6409 goto no_data;
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006410 goto end;
6411 }
6412 offset = 0;
6413 }
6414
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006415end:
vishnu0af4bd72021-10-24 06:46:24 +05306416 if (!ret && (htx->flags & HTX_FL_EOM))
6417 goto no_data;
6418 luaL_pushresult(&b);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006419 return ret;
vishnu0af4bd72021-10-24 06:46:24 +05306420
6421 no_data:
6422 /* Remove the empty string and push nil on the stack */
6423 lua_pop(L, 1);
6424 lua_pushnil(L);
6425 return 0;
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006426}
6427
6428/* Copies the string <str> to the HTTP message <msg> at the offset
6429 * <offset>. This function returns -1 if data cannot be copied. Otherwise, it
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006430 * returns the amount of data written. This function is responsible to update
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006431 * the filter context.
6432 */
6433static int _hlua_http_msg_insert(struct http_msg *msg, struct filter *filter, struct ist str, size_t offset)
6434{
6435 struct htx *htx = htx_from_buf(&msg->chn->buf);
6436 struct htx_ret htxret;
6437 int /*max, */ret = 0;
6438
6439 /* Nothing to do, just return */
6440 if (unlikely(istlen(str) == 0))
6441 goto end;
6442
6443 if (istlen(str) > htx_free_data_space(htx)) {
6444 ret = -1;
6445 goto end;
6446 }
6447
6448 htxret = htx_find_offset(htx, offset);
6449 if (!htxret.blk || htx_get_blk_type(htxret.blk) != HTX_BLK_DATA) {
6450 if (!htx_add_last_data(htx, str))
6451 goto end;
6452 }
6453 else {
6454 struct ist v = htx_get_blk_value(htx, htxret.blk);
6455 v.ptr += htxret.ret;
6456 v.len = 0;
6457 if (!htx_replace_blk_value(htx, htxret.blk, v, str))
6458 goto end;
6459 }
6460 ret = str.len;
6461 if (ret) {
6462 struct hlua_flt_ctx *flt_ctx = filter->ctx;
6463 flt_update_offsets(filter, msg->chn, ret);
6464 flt_ctx->cur_len[CHN_IDX(msg->chn)] += ret;
6465 }
6466
6467 end:
6468 htx_to_buf(htx, &msg->chn->buf);
6469 return ret;
6470}
6471
6472/* Helper function removing at most <len> bytes of DATA blocks at the absolute
6473 * position <offset>. It stops on the first non-DATA HTX block. This function is
6474 * called during the payload filtering, so the headers are already scheduled for
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006475 * output (from the filter point of view). This function is responsible to
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006476 * update the filter context.
6477 */
6478static void _hlua_http_msg_delete(struct http_msg *msg, struct filter *filter, size_t offset, size_t len)
6479{
6480 struct hlua_flt_ctx *flt_ctx = filter->ctx;
6481 struct htx *htx = htx_from_buf(&msg->chn->buf);
6482 struct htx_blk *blk;
6483 struct htx_ret htxret;
6484 size_t ret = 0;
6485
6486 /* Be sure <len> is always the amount of DATA to remove */
6487 if (htx->data == offset+len && htx_get_tail_type(htx) == HTX_BLK_DATA) {
6488 htx_truncate(htx, offset);
6489 ret = len;
6490 goto end;
6491 }
6492
6493 htxret = htx_find_offset(htx, offset);
6494 blk = htxret.blk;
6495 if (htxret.ret) {
6496 struct ist v;
6497
6498 if (htx_get_blk_type(blk) != HTX_BLK_DATA)
6499 goto end;
6500 v = htx_get_blk_value(htx, blk);
6501 v.ptr += htxret.ret;
Tim Duesterhus2471f5c2021-11-08 09:05:01 +01006502 v = isttrim(v, len);
Tim Duesterhusb113b5c2021-09-15 13:58:44 +02006503 blk = htx_replace_blk_value(htx, blk, v, IST_NULL);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006504 len -= v.len;
6505 ret += v.len;
6506 }
6507
6508
6509 while (blk && len) {
6510 enum htx_blk_type type = htx_get_blk_type(blk);
6511 uint32_t sz = htx_get_blksz(blk);
6512
6513 switch (type) {
6514 case HTX_BLK_UNUSED:
6515 break;
6516
6517 case HTX_BLK_DATA:
6518 if (len < sz) {
6519 htx_cut_data_blk(htx, blk, len);
6520 ret += len;
6521 goto end;
6522 }
6523 break;
6524
6525 default:
6526 goto end;
6527 }
6528
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006529 /* Remove all the data block */
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006530 len -= sz;
6531 ret += sz;
6532 blk = htx_remove_blk(htx, blk);
6533 }
6534
6535end:
6536 flt_update_offsets(filter, msg->chn, -ret);
6537 flt_ctx->cur_len[CHN_IDX(msg->chn)] -= ret;
6538 /* WARNING: we don't call htx_to_buf() on purpose, because we don't want
6539 * to loose the EOM flag if the message is empty.
6540 */
6541}
6542
6543/* Copies input data found in an HTTP message. Unlike the channel function used
6544 * to duplicate raw data, this one can only be called inside a filter, from
6545 * http_payload callback. So it cannot yield. An exception is returned if it is
6546 * called from another callback. If nothing was copied, a nil value is pushed on
6547 * the stack.
6548 */
6549__LJMP static int hlua_http_msg_get_body(lua_State *L)
6550{
6551 struct http_msg *msg;
6552 struct filter *filter;
6553 size_t output, input;
6554 int offset, len;
6555
6556 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
6557 WILL_LJMP(luaL_error(L, "'data' expects at most 2 arguments"));
6558 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6559
6560 if (msg->msg_state < HTTP_MSG_DATA)
6561 WILL_LJMP(lua_error(L));
6562
6563 filter = hlua_http_msg_filter(L, 1, msg, &output, &input);
6564 if (!filter || !hlua_filter_from_payload(filter))
6565 WILL_LJMP(lua_error(L));
6566
6567 if (!ci_data(msg->chn) && channel_input_closed(msg->chn)) {
6568 lua_pushnil(L);
6569 return 1;
6570 }
6571
6572 offset = output;
6573 if (lua_gettop(L) > 1) {
6574 offset = MAY_LJMP(luaL_checkinteger(L, 2));
6575 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02006576 offset = MAX(0, (int)input + offset);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006577 offset += output;
6578 if (offset < output || offset > input + output) {
6579 lua_pushfstring(L, "offset out of range.");
6580 WILL_LJMP(lua_error(L));
6581 }
6582 }
6583 len = output + input - offset;
6584 if (lua_gettop(L) == 3) {
6585 len = MAY_LJMP(luaL_checkinteger(L, 3));
6586 if (!len)
6587 goto dup;
6588 if (len == -1)
6589 len = global.tune.bufsize;
6590 if (len < 0) {
6591 lua_pushfstring(L, "length out of range.");
6592 WILL_LJMP(lua_error(L));
6593 }
6594 }
6595
6596 dup:
6597 _hlua_http_msg_dup(msg, L, offset, len);
6598 return 1;
6599}
6600
6601/* Appends a string to the HTTP message, after all existing DATA blocks but
6602 * before the trailers, if any. It returns the amount of data written or -1 if
6603 * nothing was copied. Unlike the channel function used to append data, this one
6604 * can only be called inside a filter, from http_payload callback. So it cannot
6605 * yield. An exception is returned if it is called from another callback.
6606 */
6607__LJMP static int hlua_http_msg_append(lua_State *L)
6608{
6609 struct http_msg *msg;
6610 struct filter *filter;
6611 const char *str;
6612 size_t offset, len, sz;
6613 int ret;
6614
6615 MAY_LJMP(check_args(L, 2, "append"));
6616 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6617
6618 if (msg->msg_state < HTTP_MSG_DATA)
6619 WILL_LJMP(lua_error(L));
6620
6621 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
6622 filter = hlua_http_msg_filter(L, 1, msg, &offset, &len);
6623 if (!filter || !hlua_filter_from_payload(filter))
6624 WILL_LJMP(lua_error(L));
6625
6626 ret = _hlua_http_msg_insert(msg, filter, ist2(str, sz), offset+len);
6627 lua_pushinteger(L, ret);
6628 return 1;
6629}
6630
6631/* Prepends a string to the HTTP message, before all existing DATA blocks. It
6632 * returns the amount of data written or -1 if nothing was copied. Unlike the
6633 * channel function used to prepend data, this one can only be called inside a
6634 * filter, from http_payload callback. So it cannot yield. An exception is
6635 * returned if it is called from another callback.
6636 */
6637__LJMP static int hlua_http_msg_prepend(lua_State *L)
6638{
6639 struct http_msg *msg;
6640 struct filter *filter;
6641 const char *str;
6642 size_t offset, len, sz;
6643 int ret;
6644
6645 MAY_LJMP(check_args(L, 2, "prepend"));
6646 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006647
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006648 if (msg->msg_state < HTTP_MSG_DATA)
6649 WILL_LJMP(lua_error(L));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006650
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006651 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
6652 filter = hlua_http_msg_filter(L, 1, msg, &offset, &len);
6653 if (!filter || !hlua_filter_from_payload(filter))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006654 WILL_LJMP(lua_error(L));
6655
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006656 ret = _hlua_http_msg_insert(msg, filter, ist2(str, sz), offset);
6657 lua_pushinteger(L, ret);
6658 return 1;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006659}
6660
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006661/* Inserts a string to the HTTP message at a given offset. By default the string
6662 * is appended at the end of DATA blocks. It returns the amount of data written
6663 * or -1 if nothing was copied. Unlike the channel function used to insert data,
6664 * this one can only be called inside a filter, from http_payload callback. So
6665 * it cannot yield. An exception is returned if it is called from another
6666 * callback.
6667 */
6668__LJMP static int hlua_http_msg_insert_data(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006669{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006670 struct http_msg *msg;
6671 struct filter *filter;
6672 const char *str;
6673 size_t input, output, sz;
6674 int offset;
6675 int ret;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006676
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006677 if (lua_gettop(L) < 2 || lua_gettop(L) > 3)
6678 WILL_LJMP(luaL_error(L, "'insert' expects at least 1 argument and at most 2 arguments"));
6679 MAY_LJMP(check_args(L, 2, "insert"));
6680 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006681
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006682 if (msg->msg_state < HTTP_MSG_DATA)
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006683 WILL_LJMP(lua_error(L));
6684
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006685 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
6686 filter = hlua_http_msg_filter(L, 1, msg, &input, &output);
6687 if (!filter || !hlua_filter_from_payload(filter))
6688 WILL_LJMP(lua_error(L));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006689
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006690 offset = input + output;
6691 if (lua_gettop(L) > 2) {
6692 offset = MAY_LJMP(luaL_checkinteger(L, 3));
6693 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02006694 offset = MAX(0, (int)input + offset);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006695 offset += output;
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006696 if (offset < output || offset > output + input) {
6697 lua_pushfstring(L, "offset out of range.");
6698 WILL_LJMP(lua_error(L));
6699 }
6700 }
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006701
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006702 ret = _hlua_http_msg_insert(msg, filter, ist2(str, sz), offset);
6703 lua_pushinteger(L, ret);
6704 return 1;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006705}
6706
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006707/* Removes a given amount of data from the HTTP message at a given offset. By
6708 * default all DATA blocks are removed. It returns the amount of data
6709 * removed. Unlike the channel function used to remove data, this one can only
6710 * be called inside a filter, from http_payload callback. So it cannot yield. An
6711 * exception is returned if it is called from another callback.
6712 */
6713__LJMP static int hlua_http_msg_del_data(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006714{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006715 struct http_msg *msg;
6716 struct filter *filter;
6717 size_t input, output;
6718 int offset, len;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006719
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006720 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
Boyang Lie0c54352022-05-10 17:47:23 +00006721 WILL_LJMP(luaL_error(L, "'remove' expects at most 2 arguments"));
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006722 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006723
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006724 if (msg->msg_state < HTTP_MSG_DATA)
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006725 WILL_LJMP(lua_error(L));
6726
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006727 filter = hlua_http_msg_filter(L, 1, msg, &input, &output);
6728 if (!filter || !hlua_filter_from_payload(filter))
6729 WILL_LJMP(lua_error(L));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006730
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006731 offset = input + output;
Boyang Lie0c54352022-05-10 17:47:23 +00006732 if (lua_gettop(L) > 1) {
6733 offset = MAY_LJMP(luaL_checkinteger(L, 2));
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006734 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02006735 offset = MAX(0, (int)input + offset);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006736 offset += output;
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006737 if (offset < output || offset > output + input) {
6738 lua_pushfstring(L, "offset out of range.");
6739 WILL_LJMP(lua_error(L));
6740 }
6741 }
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006742
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006743 len = output + input - offset;
Boyang Lie0c54352022-05-10 17:47:23 +00006744 if (lua_gettop(L) == 3) {
6745 len = MAY_LJMP(luaL_checkinteger(L, 3));
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006746 if (!len)
6747 goto end;
6748 if (len == -1)
6749 len = output + input - offset;
6750 if (len < 0 || offset + len > output + input) {
6751 lua_pushfstring(L, "length out of range.");
6752 WILL_LJMP(lua_error(L));
6753 }
6754 }
6755
6756 _hlua_http_msg_delete(msg, filter, offset, len);
6757
6758 end:
6759 lua_pushinteger(L, len);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006760 return 1;
6761}
6762
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006763/* Replaces a given amount of data at the given offset by a string. By default,
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006764 * all remaining data are removed, accordingly to the filter context. It returns
6765 * the amount of data written or -1 if nothing was copied. Unlike the channel
6766 * function used to replace data, this one can only be called inside a filter,
6767 * from http_payload callback. So it cannot yield. An exception is returned if
6768 * it is called from another callback.
6769 */
6770__LJMP static int hlua_http_msg_set_data(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006771{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006772 struct http_msg *msg;
6773 struct filter *filter;
6774 struct htx *htx;
6775 const char *str;
6776 size_t input, output, sz;
6777 int offset, len;
6778 int ret;
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02006779
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006780 if (lua_gettop(L) < 2 || lua_gettop(L) > 4)
6781 WILL_LJMP(luaL_error(L, "'set' expects at least 1 argument and at most 3 arguments"));
6782 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6783
6784 if (msg->msg_state < HTTP_MSG_DATA)
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006785 WILL_LJMP(lua_error(L));
6786
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006787 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
6788 filter = hlua_http_msg_filter(L, 1, msg, &output, &input);
6789 if (!filter || !hlua_filter_from_payload(filter))
6790 WILL_LJMP(lua_error(L));
6791
6792 offset = output;
6793 if (lua_gettop(L) > 2) {
6794 offset = MAY_LJMP(luaL_checkinteger(L, 3));
6795 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02006796 offset = MAX(0, (int)input + offset);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006797 offset += output;
6798 if (offset < output || offset > input + output) {
6799 lua_pushfstring(L, "offset out of range.");
6800 WILL_LJMP(lua_error(L));
6801 }
6802 }
6803
6804 len = output + input - offset;
6805 if (lua_gettop(L) == 4) {
6806 len = MAY_LJMP(luaL_checkinteger(L, 4));
6807 if (!len)
6808 goto set;
6809 if (len == -1)
6810 len = output + input - offset;
6811 if (len < 0 || offset + len > output + input) {
6812 lua_pushfstring(L, "length out of range.");
6813 WILL_LJMP(lua_error(L));
6814 }
6815 }
6816
6817 set:
6818 /* Be sure we can copied the string once input data will be removed. */
6819 htx = htx_from_buf(&msg->chn->buf);
6820 if (sz > htx_free_data_space(htx) + len)
6821 lua_pushinteger(L, -1);
6822 else {
6823 _hlua_http_msg_delete(msg, filter, offset, len);
6824 ret = _hlua_http_msg_insert(msg, filter, ist2(str, sz), offset);
6825 lua_pushinteger(L, ret);
6826 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006827 return 1;
6828}
6829
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006830/* Prepends data into an HTTP message and forward it, from the filter point of
6831 * view. It returns the amount of data written or -1 if nothing was sent. Unlike
6832 * the channel function used to send data, this one can only be called inside a
6833 * filter, from http_payload callback. So it cannot yield. An exception is
6834 * returned if it is called from another callback.
6835 */
6836__LJMP static int hlua_http_msg_send(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006837{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006838 struct http_msg *msg;
6839 struct filter *filter;
6840 struct htx *htx;
6841 const char *str;
6842 size_t offset, len, sz;
6843 int ret;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006844
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006845 MAY_LJMP(check_args(L, 2, "send"));
6846 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6847
6848 if (msg->msg_state < HTTP_MSG_DATA)
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006849 WILL_LJMP(lua_error(L));
6850
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006851 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
6852 filter = hlua_http_msg_filter(L, 1, msg, &offset, &len);
6853 if (!filter || !hlua_filter_from_payload(filter))
6854 WILL_LJMP(lua_error(L));
6855
6856 /* Return an error if the channel's output is closed */
6857 if (unlikely(channel_output_closed(msg->chn))) {
6858 lua_pushinteger(L, -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006859 return 1;
6860 }
6861
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006862 htx = htx_from_buf(&msg->chn->buf);
6863 if (sz > htx_free_data_space(htx)) {
6864 lua_pushinteger(L, -1);
6865 return 1;
6866 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006867
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006868 ret = _hlua_http_msg_insert(msg, filter, ist2(str, sz), offset);
6869 if (ret > 0) {
6870 struct hlua_flt_ctx *flt_ctx = filter->ctx;
6871
6872 FLT_OFF(filter, msg->chn) += ret;
6873 flt_ctx->cur_len[CHN_IDX(msg->chn)] -= ret;
6874 flt_ctx->cur_off[CHN_IDX(msg->chn)] += ret;
6875 }
6876
6877 lua_pushinteger(L, ret);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006878 return 1;
6879}
6880
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006881/* Forwards a given amount of bytes. It return -1 if the channel's output is
6882 * closed. Otherwise, it returns the number of bytes forwarded. Unlike the
6883 * channel function used to forward data, this one can only be called inside a
6884 * filter, from http_payload callback. So it cannot yield. An exception is
6885 * returned if it is called from another callback. All other functions deal with
6886 * DATA block, this one not.
6887*/
6888__LJMP static int hlua_http_msg_forward(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006889{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006890 struct http_msg *msg;
6891 struct filter *filter;
6892 size_t offset, len;
6893 int fwd, ret = 0;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006894
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006895 MAY_LJMP(check_args(L, 2, "forward"));
6896 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6897
6898 if (msg->msg_state < HTTP_MSG_DATA)
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006899 WILL_LJMP(lua_error(L));
6900
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006901 fwd = MAY_LJMP(luaL_checkinteger(L, 2));
6902 filter = hlua_http_msg_filter(L, 1, msg, &offset, &len);
6903 if (!filter || !hlua_filter_from_payload(filter))
6904 WILL_LJMP(lua_error(L));
6905
6906 /* Nothing to do, just return */
6907 if (!fwd)
6908 goto end;
6909
6910 /* Return an error if the channel's output is closed */
6911 if (unlikely(channel_output_closed(msg->chn))) {
6912 ret = -1;
6913 goto end;
6914 }
6915
6916 ret = fwd;
6917 if (ret > len)
6918 ret = len;
6919
6920 if (ret) {
6921 struct hlua_flt_ctx *flt_ctx = filter->ctx;
6922
6923 FLT_OFF(filter, msg->chn) += ret;
6924 flt_ctx->cur_off[CHN_IDX(msg->chn)] += ret;
6925 flt_ctx->cur_len[CHN_IDX(msg->chn)] -= ret;
6926 }
6927
6928 end:
6929 lua_pushinteger(L, ret);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006930 return 1;
6931}
6932
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006933/* Set EOM flag on the HTX message.
6934 *
6935 * NOTE: Not sure it is a good idea to manipulate this flag but for now I don't
6936 * really know how to do without this feature.
6937 */
6938__LJMP static int hlua_http_msg_set_eom(lua_State *L)
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02006939{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006940 struct http_msg *msg;
6941 struct htx *htx;
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02006942
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006943 MAY_LJMP(check_args(L, 1, "set_eom"));
6944 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6945 htx = htxbuf(&msg->chn->buf);
6946 htx->flags |= HTX_FL_EOM;
6947 return 0;
6948}
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006949
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006950/* Unset EOM flag on the HTX message.
6951 *
6952 * NOTE: Not sure it is a good idea to manipulate this flag but for now I don't
6953 * really know how to do without this feature.
6954 */
6955__LJMP static int hlua_http_msg_unset_eom(lua_State *L)
6956{
6957 struct http_msg *msg;
6958 struct htx *htx;
6959
6960 MAY_LJMP(check_args(L, 1, "set_eom"));
6961 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6962 htx = htxbuf(&msg->chn->buf);
6963 htx->flags &= ~HTX_FL_EOM;
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02006964 return 0;
6965}
6966
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006967/*
6968 *
6969 *
William Lallemand3956c4e2021-09-21 16:25:15 +02006970 * Class HTTPClient
6971 *
6972 *
6973 */
6974__LJMP static struct hlua_httpclient *hlua_checkhttpclient(lua_State *L, int ud)
6975{
6976 return MAY_LJMP(hlua_checkudata(L, ud, class_httpclient_ref));
6977}
6978
William Lallemandf77f1de2021-09-28 19:10:38 +02006979
6980/* stops the httpclient and ask it to kill itself */
6981__LJMP static int hlua_httpclient_gc(lua_State *L)
6982{
6983 struct hlua_httpclient *hlua_hc;
6984
6985 MAY_LJMP(check_args(L, 1, "__gc"));
6986
6987 hlua_hc = MAY_LJMP(hlua_checkhttpclient(L, 1));
6988
6989 httpclient_stop_and_destroy(hlua_hc->hc);
6990
6991 hlua_hc->hc = NULL;
6992
6993
6994 return 0;
6995}
6996
6997
William Lallemand3956c4e2021-09-21 16:25:15 +02006998__LJMP static int hlua_httpclient_new(lua_State *L)
6999{
7000 struct hlua_httpclient *hlua_hc;
7001 struct hlua *hlua;
7002
7003 /* Get hlua struct, or NULL if we execute from main lua state */
7004 hlua = hlua_gethlua(L);
7005 if (!hlua)
7006 return 0;
7007
7008 /* Check stack size. */
7009 if (!lua_checkstack(L, 3)) {
7010 hlua_pusherror(L, "httpclient: full stack");
7011 goto err;
7012 }
7013 /* Create the object: obj[0] = userdata. */
7014 lua_newtable(L);
7015 hlua_hc = MAY_LJMP(lua_newuserdata(L, sizeof(*hlua_hc)));
7016 lua_rawseti(L, -2, 0);
7017 memset(hlua_hc, 0, sizeof(*hlua_hc));
7018
7019 hlua_hc->hc = httpclient_new(hlua, 0, IST_NULL);
7020 if (!hlua_hc->hc)
7021 goto err;
7022
7023 /* Pop a class stream metatable and affect it to the userdata. */
7024 lua_rawgeti(L, LUA_REGISTRYINDEX, class_httpclient_ref);
7025 lua_setmetatable(L, -2);
7026
7027 return 1;
7028
7029 err:
7030 WILL_LJMP(lua_error(L));
7031 return 0;
7032}
7033
7034
7035/*
7036 * Callback of the httpclient, this callback wakes the lua task up, once the
7037 * httpclient receives some data
7038 *
7039 */
7040
William Lallemandbd5739e2021-10-28 15:41:38 +02007041static void hlua_httpclient_cb(struct httpclient *hc)
William Lallemand3956c4e2021-09-21 16:25:15 +02007042{
7043 struct hlua *hlua = hc->caller;
7044
7045 if (!hlua || !hlua->task)
7046 return;
7047
7048 task_wakeup(hlua->task, TASK_WOKEN_MSG);
7049}
7050
7051/*
William Lallemandd7df73a2021-09-23 17:54:00 +02007052 * Fill the lua stack with headers from the httpclient response
7053 * This works the same way as the hlua_http_get_headers() function
7054 */
7055__LJMP static int hlua_httpclient_get_headers(lua_State *L, struct hlua_httpclient *hlua_hc)
7056{
7057 struct http_hdr *hdr;
7058
7059 lua_newtable(L);
7060
William Lallemandef574b22021-10-05 16:19:31 +02007061 for (hdr = hlua_hc->hc->res.hdrs; hdr && isttest(hdr->n); hdr++) {
William Lallemandd7df73a2021-09-23 17:54:00 +02007062 struct ist n, v;
7063 int len;
7064
7065 n = hdr->n;
7066 v = hdr->v;
7067
7068 /* Check for existing entry:
7069 * assume that the table is on the top of the stack, and
7070 * push the key in the stack, the function lua_gettable()
7071 * perform the lookup.
7072 */
7073
7074 lua_pushlstring(L, n.ptr, n.len);
7075 lua_gettable(L, -2);
7076
7077 switch (lua_type(L, -1)) {
7078 case LUA_TNIL:
7079 /* Table not found, create it. */
7080 lua_pop(L, 1); /* remove the nil value. */
7081 lua_pushlstring(L, n.ptr, n.len); /* push the header name as key. */
7082 lua_newtable(L); /* create and push empty table. */
7083 lua_pushlstring(L, v.ptr, v.len); /* push header value. */
7084 lua_rawseti(L, -2, 0); /* index header value (pop it). */
7085 lua_rawset(L, -3); /* index new table with header name (pop the values). */
7086 break;
7087
7088 case LUA_TTABLE:
7089 /* Entry found: push the value in the table. */
7090 len = lua_rawlen(L, -1);
7091 lua_pushlstring(L, v.ptr, v.len); /* push header value. */
7092 lua_rawseti(L, -2, len+1); /* index header value (pop it). */
7093 lua_pop(L, 1); /* remove the table (it is stored in the main table). */
7094 break;
7095
7096 default:
7097 /* Other cases are errors. */
7098 hlua_pusherror(L, "internal error during the parsing of headers.");
7099 WILL_LJMP(lua_error(L));
7100 }
7101 }
7102 return 1;
7103}
7104
7105/*
William Lallemand746e6f32021-10-06 10:57:44 +02007106 * Allocate and return an array of http_hdr ist extracted from the <headers> lua table
7107 *
7108 * Caller must free the result
7109 */
7110struct http_hdr *hlua_httpclient_table_to_hdrs(lua_State *L)
7111{
7112 struct http_hdr hdrs[global.tune.max_http_hdr];
7113 struct http_hdr *result = NULL;
7114 uint32_t hdr_num = 0;
7115
7116 lua_pushnil(L);
7117 while (lua_next(L, -2) != 0) {
7118 struct ist name, value;
7119 const char *n, *v;
7120 size_t nlen, vlen;
7121
7122 if (!lua_isstring(L, -2) || !lua_istable(L, -1)) {
7123 /* Skip element if the key is not a string or if the value is not a table */
7124 goto next_hdr;
7125 }
7126
7127 n = lua_tolstring(L, -2, &nlen);
7128 name = ist2(n, nlen);
7129
7130 /* Loop on header's values */
7131 lua_pushnil(L);
7132 while (lua_next(L, -2)) {
7133 if (!lua_isstring(L, -1)) {
7134 /* Skip the value if it is not a string */
7135 goto next_value;
7136 }
7137
7138 v = lua_tolstring(L, -1, &vlen);
7139 value = ist2(v, vlen);
7140 name = ist2(n, nlen);
7141
7142 hdrs[hdr_num].n = istdup(name);
7143 hdrs[hdr_num].v = istdup(value);
7144
7145 hdr_num++;
7146
7147 next_value:
7148 lua_pop(L, 1);
7149 }
7150
7151 next_hdr:
7152 lua_pop(L, 1);
7153
7154 }
7155
7156 if (hdr_num) {
7157 /* alloc and copy the headers in the httpclient struct */
Tim Duesterhus16cc16d2021-11-06 15:14:45 +01007158 result = calloc((hdr_num + 1), sizeof(*result));
William Lallemand746e6f32021-10-06 10:57:44 +02007159 if (!result)
7160 goto skip_headers;
7161 memcpy(result, hdrs, sizeof(struct http_hdr) * (hdr_num + 1));
7162
7163 result[hdr_num].n = IST_NULL;
7164 result[hdr_num].v = IST_NULL;
7165 }
7166
7167skip_headers:
William Lallemand746e6f32021-10-06 10:57:44 +02007168
7169 return result;
7170}
7171
7172
William Lallemandbd5739e2021-10-28 15:41:38 +02007173/*
7174 * For each yield, checks if there is some data in the httpclient and push them
7175 * in the lua buffer, once the httpclient finished its job, push the result on
7176 * the stack
7177 */
7178__LJMP static int hlua_httpclient_rcv_yield(lua_State *L, int status, lua_KContext ctx)
7179{
7180 struct buffer *tr;
7181 int res;
7182 struct hlua *hlua = hlua_gethlua(L);
7183 struct hlua_httpclient *hlua_hc = hlua_checkhttpclient(L, 1);
7184
7185
7186 tr = get_trash_chunk();
7187
7188 res = httpclient_res_xfer(hlua_hc->hc, tr);
7189 luaL_addlstring(&hlua_hc->b, b_orig(tr), res);
7190
7191 if (!httpclient_data(hlua_hc->hc) && httpclient_ended(hlua_hc->hc)) {
7192
7193 luaL_pushresult(&hlua_hc->b);
7194 lua_settable(L, -3);
7195
7196 lua_pushstring(L, "status");
7197 lua_pushinteger(L, hlua_hc->hc->res.status);
7198 lua_settable(L, -3);
7199
7200
7201 lua_pushstring(L, "reason");
7202 lua_pushlstring(L, hlua_hc->hc->res.reason.ptr, hlua_hc->hc->res.reason.len);
7203 lua_settable(L, -3);
7204
7205 lua_pushstring(L, "headers");
7206 hlua_httpclient_get_headers(L, hlua_hc);
7207 lua_settable(L, -3);
7208
7209 return 1;
7210 }
7211
7212 if (httpclient_data(hlua_hc->hc))
7213 task_wakeup(hlua->task, TASK_WOKEN_MSG);
7214
7215 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_httpclient_rcv_yield, TICK_ETERNITY, 0));
7216
7217 return 0;
7218}
7219
7220/*
7221 * Call this when trying to stream a body during a request
7222 */
7223__LJMP static int hlua_httpclient_snd_yield(lua_State *L, int status, lua_KContext ctx)
7224{
7225 struct hlua *hlua;
7226 struct hlua_httpclient *hlua_hc = hlua_checkhttpclient(L, 1);
7227 const char *body_str = NULL;
7228 int ret;
7229 int end = 0;
7230 size_t buf_len;
7231 size_t to_send = 0;
7232
7233 hlua = hlua_gethlua(L);
7234
7235 if (!hlua || !hlua->task)
7236 WILL_LJMP(luaL_error(L, "The 'get' function is only allowed in "
7237 "'frontend', 'backend' or 'task'"));
7238
7239 ret = lua_getfield(L, -1, "body");
7240 if (ret != LUA_TSTRING)
7241 goto rcv;
7242
7243 body_str = lua_tolstring(L, -1, &buf_len);
7244 lua_pop(L, 1);
7245
Christopher Fauletfc591292022-01-12 14:46:03 +01007246 to_send = buf_len - hlua_hc->sent;
William Lallemandbd5739e2021-10-28 15:41:38 +02007247
7248 if ((hlua_hc->sent + to_send) >= buf_len)
7249 end = 1;
7250
7251 /* the end flag is always set since we are using the whole remaining size */
7252 hlua_hc->sent += httpclient_req_xfer(hlua_hc->hc, ist2(body_str + hlua_hc->sent, to_send), end);
7253
7254 if (buf_len > hlua_hc->sent) {
7255 /* still need to process the buffer */
7256 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_httpclient_snd_yield, TICK_ETERNITY, 0));
7257 } else {
7258 goto rcv;
7259 /* we sent the whole request buffer we can recv */
7260 }
7261 return 0;
7262
7263rcv:
7264
7265 /* we return a "res" object */
7266 lua_newtable(L);
7267
William Lallemandbd5739e2021-10-28 15:41:38 +02007268 lua_pushstring(L, "body");
William Lallemandd1187eb2021-11-02 10:40:06 +01007269 luaL_buffinit(L, &hlua_hc->b);
William Lallemandbd5739e2021-10-28 15:41:38 +02007270
William Lallemand933fe392021-11-04 09:45:58 +01007271 task_wakeup(hlua->task, TASK_WOKEN_MSG);
William Lallemandbd5739e2021-10-28 15:41:38 +02007272 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_httpclient_rcv_yield, TICK_ETERNITY, 0));
7273
7274 return 1;
7275}
William Lallemand746e6f32021-10-06 10:57:44 +02007276
William Lallemand3956c4e2021-09-21 16:25:15 +02007277/*
William Lallemanddc2cc902021-10-26 11:43:26 +02007278 * Send an HTTP request and wait for a response
William Lallemand3956c4e2021-09-21 16:25:15 +02007279 */
7280
William Lallemanddc2cc902021-10-26 11:43:26 +02007281__LJMP static int hlua_httpclient_send(lua_State *L, enum http_meth_t meth)
William Lallemand3956c4e2021-09-21 16:25:15 +02007282{
7283 struct hlua_httpclient *hlua_hc;
William Lallemand746e6f32021-10-06 10:57:44 +02007284 struct http_hdr *hdrs = NULL;
7285 struct http_hdr *hdrs_i = NULL;
William Lallemand3956c4e2021-09-21 16:25:15 +02007286 struct hlua *hlua;
William Lallemand746e6f32021-10-06 10:57:44 +02007287 const char *url_str = NULL;
William Lallemanddec25c32021-10-25 19:48:37 +02007288 const char *body_str = NULL;
William Lallemandbd5739e2021-10-28 15:41:38 +02007289 size_t buf_len;
William Lallemand746e6f32021-10-06 10:57:44 +02007290 int ret;
William Lallemand3956c4e2021-09-21 16:25:15 +02007291
7292 hlua = hlua_gethlua(L);
7293
7294 if (!hlua || !hlua->task)
7295 WILL_LJMP(luaL_error(L, "The 'get' function is only allowed in "
7296 "'frontend', 'backend' or 'task'"));
7297
William Lallemand746e6f32021-10-06 10:57:44 +02007298 if (lua_gettop(L) != 2 || lua_type(L, -1) != LUA_TTABLE)
7299 WILL_LJMP(luaL_error(L, "'get' needs a table as argument"));
7300
William Lallemand4f4f2b72022-02-17 20:00:23 +01007301 hlua_hc = hlua_checkhttpclient(L, 1);
7302
William Lallemand7177a952022-03-03 15:33:12 +01007303 lua_pushnil(L); /* first key */
7304 while (lua_next(L, 2)) {
7305 if (strcmp(lua_tostring(L, -2), "dst") == 0) {
7306 if (httpclient_set_dst(hlua_hc->hc, lua_tostring(L, -1)) < 0)
7307 WILL_LJMP(luaL_error(L, "Can't use the 'dst' argument"));
William Lallemand4f4f2b72022-02-17 20:00:23 +01007308
William Lallemand7177a952022-03-03 15:33:12 +01007309 } else if (strcmp(lua_tostring(L, -2), "url") == 0) {
7310 if (lua_type(L, -1) != LUA_TSTRING)
7311 WILL_LJMP(luaL_error(L, "invalid parameter in 'url', must be a string"));
7312 url_str = lua_tostring(L, -1);
William Lallemand3956c4e2021-09-21 16:25:15 +02007313
William Lallemand7177a952022-03-03 15:33:12 +01007314 } else if (strcmp(lua_tostring(L, -2), "timeout") == 0) {
7315 if (lua_type(L, -1) != LUA_TNUMBER)
7316 WILL_LJMP(luaL_error(L, "invalid parameter in 'timeout', must be a number"));
7317 httpclient_set_timeout(hlua_hc->hc, lua_tointeger(L, -1));
William Lallemandb4a4ef62022-02-23 14:18:16 +01007318
William Lallemand7177a952022-03-03 15:33:12 +01007319 } else if (strcmp(lua_tostring(L, -2), "headers") == 0) {
7320 if (lua_type(L, -1) != LUA_TTABLE)
7321 WILL_LJMP(luaL_error(L, "invalid parameter in 'headers', must be a table"));
7322 hdrs = hlua_httpclient_table_to_hdrs(L);
William Lallemand79416cb2021-09-24 14:51:44 +02007323
William Lallemand7177a952022-03-03 15:33:12 +01007324 } else if (strcmp(lua_tostring(L, -2), "body") == 0) {
7325 if (lua_type(L, -1) != LUA_TSTRING)
7326 WILL_LJMP(luaL_error(L, "invalid parameter in 'body', must be a string"));
7327 body_str = lua_tolstring(L, -1, &buf_len);
William Lallemandbd5739e2021-10-28 15:41:38 +02007328
William Lallemand7177a952022-03-03 15:33:12 +01007329 } else {
7330 WILL_LJMP(luaL_error(L, "'%s' invalid parameter name", lua_tostring(L, -2)));
7331 }
7332 /* removes 'value'; keeps 'key' for next iteration */
7333 lua_pop(L, 1);
7334 }
William Lallemanddec25c32021-10-25 19:48:37 +02007335
William Lallemand746e6f32021-10-06 10:57:44 +02007336 if (!url_str) {
7337 WILL_LJMP(luaL_error(L, "'get' need a 'url' argument"));
7338 return 0;
7339 }
William Lallemand3956c4e2021-09-21 16:25:15 +02007340
William Lallemand10a37362022-03-02 16:18:26 +01007341 hlua_hc->sent = 0;
William Lallemand3956c4e2021-09-21 16:25:15 +02007342
7343 hlua_hc->hc->req.url = istdup(ist(url_str));
William Lallemanddc2cc902021-10-26 11:43:26 +02007344 hlua_hc->hc->req.meth = meth;
William Lallemand3956c4e2021-09-21 16:25:15 +02007345
7346 /* update the httpclient callbacks */
William Lallemandbd5739e2021-10-28 15:41:38 +02007347 hlua_hc->hc->ops.res_stline = hlua_httpclient_cb;
7348 hlua_hc->hc->ops.res_headers = hlua_httpclient_cb;
7349 hlua_hc->hc->ops.res_payload = hlua_httpclient_cb;
William Lallemand8f170c72022-03-15 10:52:07 +01007350 hlua_hc->hc->ops.res_end = hlua_httpclient_cb;
William Lallemand3956c4e2021-09-21 16:25:15 +02007351
William Lallemandbd5739e2021-10-28 15:41:38 +02007352 /* a body is available, it will use the request callback */
7353 if (body_str) {
7354 hlua_hc->hc->ops.req_payload = hlua_httpclient_cb;
7355 }
William Lallemand3956c4e2021-09-21 16:25:15 +02007356
William Lallemandbd5739e2021-10-28 15:41:38 +02007357 ret = httpclient_req_gen(hlua_hc->hc, hlua_hc->hc->req.url, meth, hdrs, IST_NULL);
William Lallemand3956c4e2021-09-21 16:25:15 +02007358
William Lallemand746e6f32021-10-06 10:57:44 +02007359 /* free the temporary headers array */
7360 hdrs_i = hdrs;
7361 while (hdrs_i && isttest(hdrs_i->n)) {
7362 istfree(&hdrs_i->n);
7363 istfree(&hdrs_i->v);
7364 hdrs_i++;
7365 }
7366 ha_free(&hdrs);
7367
7368
William Lallemand6137a9e2021-10-26 15:01:53 +02007369 if (ret != ERR_NONE) {
7370 WILL_LJMP(luaL_error(L, "Can't generate the HTTP request"));
7371 return 0;
7372 }
7373
William Lallemandc2d3db42022-04-26 11:46:13 +02007374 if (!httpclient_start(hlua_hc->hc))
7375 WILL_LJMP(luaL_error(L, "couldn't start the httpclient"));
William Lallemand6137a9e2021-10-26 15:01:53 +02007376
William Lallemandbd5739e2021-10-28 15:41:38 +02007377 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_httpclient_snd_yield, TICK_ETERNITY, 0));
William Lallemand3956c4e2021-09-21 16:25:15 +02007378
William Lallemand3956c4e2021-09-21 16:25:15 +02007379 return 0;
7380}
7381
7382/*
William Lallemanddc2cc902021-10-26 11:43:26 +02007383 * Sends an HTTP HEAD request and wait for a response
7384 *
7385 * httpclient:head(url, headers, payload)
7386 */
7387__LJMP static int hlua_httpclient_head(lua_State *L)
7388{
7389 return hlua_httpclient_send(L, HTTP_METH_HEAD);
7390}
7391
7392/*
7393 * Send an HTTP GET request and wait for a response
7394 *
7395 * httpclient:get(url, headers, payload)
7396 */
7397__LJMP static int hlua_httpclient_get(lua_State *L)
7398{
7399 return hlua_httpclient_send(L, HTTP_METH_GET);
7400
7401}
7402
7403/*
7404 * Sends an HTTP PUT request and wait for a response
7405 *
7406 * httpclient:put(url, headers, payload)
7407 */
7408__LJMP static int hlua_httpclient_put(lua_State *L)
7409{
7410 return hlua_httpclient_send(L, HTTP_METH_PUT);
7411}
7412
7413/*
7414 * Send an HTTP POST request and wait for a response
7415 *
7416 * httpclient:post(url, headers, payload)
7417 */
7418__LJMP static int hlua_httpclient_post(lua_State *L)
7419{
7420 return hlua_httpclient_send(L, HTTP_METH_POST);
7421}
7422
7423
7424/*
7425 * Sends an HTTP DELETE request and wait for a response
7426 *
7427 * httpclient:delete(url, headers, payload)
7428 */
7429__LJMP static int hlua_httpclient_delete(lua_State *L)
7430{
7431 return hlua_httpclient_send(L, HTTP_METH_DELETE);
7432}
7433
7434/*
William Lallemand3956c4e2021-09-21 16:25:15 +02007435 *
7436 *
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007437 * Class TXN
7438 *
7439 *
7440 */
7441
7442/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02007443 * a class stream, otherwise it throws an error.
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007444 */
7445__LJMP static struct hlua_txn *hlua_checktxn(lua_State *L, int ud)
7446{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02007447 return MAY_LJMP(hlua_checkudata(L, ud, class_txn_ref));
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007448}
7449
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007450__LJMP static int hlua_set_var(lua_State *L)
7451{
7452 struct hlua_txn *htxn;
7453 const char *name;
7454 size_t len;
7455 struct sample smp;
7456
Tim Duesterhus4e172c92020-05-19 13:49:42 +02007457 if (lua_gettop(L) < 3 || lua_gettop(L) > 4)
7458 WILL_LJMP(luaL_error(L, "'set_var' needs between 3 and 4 arguments"));
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007459
7460 /* It is useles to retrieve the stream, but this function
7461 * runs only in a stream context.
7462 */
7463 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7464 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
7465
7466 /* Converts the third argument in a sample. */
Amaury Denoyellebc0af6a2020-10-29 17:21:20 +01007467 memset(&smp, 0, sizeof(smp));
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007468 hlua_lua2smp(L, 3, &smp);
7469
7470 /* Store the sample in a variable. */
Willy Tarreau7560dd42016-03-10 16:28:58 +01007471 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
Tim Duesterhus4e172c92020-05-19 13:49:42 +02007472
7473 if (lua_gettop(L) == 4 && lua_toboolean(L, 4))
7474 lua_pushboolean(L, vars_set_by_name_ifexist(name, len, &smp) != 0);
7475 else
7476 lua_pushboolean(L, vars_set_by_name(name, len, &smp) != 0);
7477
Tim Duesterhus84ebc132020-05-19 13:49:41 +02007478 return 1;
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007479}
7480
Christopher Faulet85d79c92016-11-09 16:54:56 +01007481__LJMP static int hlua_unset_var(lua_State *L)
7482{
7483 struct hlua_txn *htxn;
7484 const char *name;
7485 size_t len;
7486 struct sample smp;
7487
7488 MAY_LJMP(check_args(L, 2, "unset_var"));
7489
7490 /* It is useles to retrieve the stream, but this function
7491 * runs only in a stream context.
7492 */
7493 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7494 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
7495
7496 /* Unset the variable. */
7497 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
Tim Duesterhus84ebc132020-05-19 13:49:41 +02007498 lua_pushboolean(L, vars_unset_by_name_ifexist(name, len, &smp) != 0);
7499 return 1;
Christopher Faulet85d79c92016-11-09 16:54:56 +01007500}
7501
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007502__LJMP static int hlua_get_var(lua_State *L)
7503{
7504 struct hlua_txn *htxn;
7505 const char *name;
7506 size_t len;
7507 struct sample smp;
7508
7509 MAY_LJMP(check_args(L, 2, "get_var"));
7510
7511 /* It is useles to retrieve the stream, but this function
7512 * runs only in a stream context.
7513 */
7514 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7515 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
7516
Willy Tarreau7560dd42016-03-10 16:28:58 +01007517 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
Willy Tarreaue352b9d2021-09-03 11:52:38 +02007518 if (!vars_get_by_name(name, len, &smp, NULL)) {
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007519 lua_pushnil(L);
7520 return 1;
7521 }
7522
7523 return hlua_smp2lua(L, &smp);
7524}
7525
Willy Tarreau59551662015-03-10 14:23:13 +01007526__LJMP static int hlua_set_priv(lua_State *L)
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007527{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007528 struct hlua *hlua;
7529
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007530 MAY_LJMP(check_args(L, 2, "set_priv"));
7531
Willy Tarreau87b09662015-04-03 00:22:06 +02007532 /* It is useles to retrieve the stream, but this function
7533 * runs only in a stream context.
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007534 */
7535 MAY_LJMP(hlua_checktxn(L, 1));
Thierry Fournier4234dbd2020-11-28 13:18:23 +01007536
7537 /* Get hlua struct, or NULL if we execute from main lua state */
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007538 hlua = hlua_gethlua(L);
Thierry Fournier4234dbd2020-11-28 13:18:23 +01007539 if (!hlua)
7540 return 0;
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007541
7542 /* Remove previous value. */
Thierry FOURNIERe068b602017-04-26 13:27:05 +02007543 luaL_unref(L, LUA_REGISTRYINDEX, hlua->Mref);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007544
7545 /* Get and store new value. */
7546 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
7547 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
7548
7549 return 0;
7550}
7551
Willy Tarreau59551662015-03-10 14:23:13 +01007552__LJMP static int hlua_get_priv(lua_State *L)
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007553{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007554 struct hlua *hlua;
7555
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007556 MAY_LJMP(check_args(L, 1, "get_priv"));
7557
Willy Tarreau87b09662015-04-03 00:22:06 +02007558 /* It is useles to retrieve the stream, but this function
7559 * runs only in a stream context.
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007560 */
7561 MAY_LJMP(hlua_checktxn(L, 1));
Thierry Fournier4234dbd2020-11-28 13:18:23 +01007562
7563 /* Get hlua struct, or NULL if we execute from main lua state */
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007564 hlua = hlua_gethlua(L);
Thierry Fournier4234dbd2020-11-28 13:18:23 +01007565 if (!hlua) {
7566 lua_pushnil(L);
7567 return 1;
7568 }
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007569
7570 /* Push configuration index in the stack. */
7571 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
7572
7573 return 1;
7574}
7575
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007576/* Create stack entry containing a class TXN. This function
7577 * return 0 if the stack does not contains free slots,
7578 * otherwise it returns 1.
7579 */
Thierry FOURNIERab00df62016-07-14 11:42:37 +02007580static int hlua_txn_new(lua_State *L, struct stream *s, struct proxy *p, int dir, int flags)
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007581{
Willy Tarreaude491382015-04-06 11:04:28 +02007582 struct hlua_txn *htxn;
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007583
7584 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01007585 if (!lua_checkstack(L, 3))
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007586 return 0;
7587
7588 /* NOTE: The allocation never fails. The failure
7589 * throw an error, and the function never returns.
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08007590 * if the throw is not available, the process is aborted.
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007591 */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01007592 /* Create the object: obj[0] = userdata. */
7593 lua_newtable(L);
Willy Tarreaude491382015-04-06 11:04:28 +02007594 htxn = lua_newuserdata(L, sizeof(*htxn));
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01007595 lua_rawseti(L, -2, 0);
7596
Willy Tarreaude491382015-04-06 11:04:28 +02007597 htxn->s = s;
7598 htxn->p = p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01007599 htxn->dir = dir;
Thierry FOURNIERab00df62016-07-14 11:42:37 +02007600 htxn->flags = flags;
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007601
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01007602 /* Create the "f" field that contains a list of fetches. */
7603 lua_pushstring(L, "f");
Thierry FOURNIERca988662015-12-20 18:43:03 +01007604 if (!hlua_fetches_new(L, htxn, HLUA_F_MAY_USE_HTTP))
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01007605 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007606 lua_rawset(L, -3);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01007607
7608 /* Create the "sf" field that contains a list of stringsafe fetches. */
7609 lua_pushstring(L, "sf");
Thierry FOURNIERca988662015-12-20 18:43:03 +01007610 if (!hlua_fetches_new(L, htxn, HLUA_F_MAY_USE_HTTP | HLUA_F_AS_STRING))
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01007611 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007612 lua_rawset(L, -3);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01007613
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007614 /* Create the "c" field that contains a list of converters. */
7615 lua_pushstring(L, "c");
Willy Tarreaude491382015-04-06 11:04:28 +02007616 if (!hlua_converters_new(L, htxn, 0))
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01007617 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007618 lua_rawset(L, -3);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01007619
7620 /* Create the "sc" field that contains a list of stringsafe converters. */
7621 lua_pushstring(L, "sc");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01007622 if (!hlua_converters_new(L, htxn, HLUA_F_AS_STRING))
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007623 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007624 lua_rawset(L, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007625
Thierry FOURNIER397826a2015-03-11 19:39:09 +01007626 /* Create the "req" field that contains the request channel object. */
7627 lua_pushstring(L, "req");
Willy Tarreau2a71af42015-03-10 13:51:50 +01007628 if (!hlua_channel_new(L, &s->req))
Thierry FOURNIER397826a2015-03-11 19:39:09 +01007629 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007630 lua_rawset(L, -3);
Thierry FOURNIER397826a2015-03-11 19:39:09 +01007631
7632 /* Create the "res" field that contains the response channel object. */
7633 lua_pushstring(L, "res");
Willy Tarreau2a71af42015-03-10 13:51:50 +01007634 if (!hlua_channel_new(L, &s->res))
Thierry FOURNIER397826a2015-03-11 19:39:09 +01007635 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007636 lua_rawset(L, -3);
Thierry FOURNIER397826a2015-03-11 19:39:09 +01007637
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007638 /* Creates the HTTP object is the current proxy allows http. */
7639 lua_pushstring(L, "http");
Christopher Faulet1bb6afa2021-03-08 17:57:53 +01007640 if (IS_HTX_STRM(s)) {
Willy Tarreaude491382015-04-06 11:04:28 +02007641 if (!hlua_http_new(L, htxn))
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007642 return 0;
7643 }
7644 else
7645 lua_pushnil(L);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007646 lua_rawset(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007647
Christopher Faulet78c35472020-02-26 17:14:08 +01007648 if ((htxn->flags & HLUA_TXN_CTX_MASK) == HLUA_TXN_FLT_CTX) {
7649 /* HTTPMessage object are created when a lua TXN is created from
7650 * a filter context only
7651 */
7652
7653 /* Creates the HTTP-Request object is the current proxy allows http. */
7654 lua_pushstring(L, "http_req");
7655 if (p->mode == PR_MODE_HTTP) {
7656 if (!hlua_http_msg_new(L, &s->txn->req))
7657 return 0;
7658 }
7659 else
7660 lua_pushnil(L);
7661 lua_rawset(L, -3);
7662
7663 /* Creates the HTTP-Response object is the current proxy allows http. */
7664 lua_pushstring(L, "http_res");
7665 if (p->mode == PR_MODE_HTTP) {
7666 if (!hlua_http_msg_new(L, &s->txn->rsp))
7667 return 0;
7668 }
7669 else
7670 lua_pushnil(L);
7671 lua_rawset(L, -3);
7672 }
7673
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007674 /* Pop a class sesison metatable and affect it to the userdata. */
7675 lua_rawgeti(L, LUA_REGISTRYINDEX, class_txn_ref);
7676 lua_setmetatable(L, -2);
7677
7678 return 1;
7679}
7680
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01007681__LJMP static int hlua_txn_deflog(lua_State *L)
7682{
7683 const char *msg;
7684 struct hlua_txn *htxn;
7685
7686 MAY_LJMP(check_args(L, 2, "deflog"));
7687 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7688 msg = MAY_LJMP(luaL_checkstring(L, 2));
7689
7690 hlua_sendlog(htxn->s->be, htxn->s->logs.level, msg);
7691 return 0;
7692}
7693
7694__LJMP static int hlua_txn_log(lua_State *L)
7695{
7696 int level;
7697 const char *msg;
7698 struct hlua_txn *htxn;
7699
7700 MAY_LJMP(check_args(L, 3, "log"));
7701 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7702 level = MAY_LJMP(luaL_checkinteger(L, 2));
7703 msg = MAY_LJMP(luaL_checkstring(L, 3));
7704
7705 if (level < 0 || level >= NB_LOG_LEVELS)
7706 WILL_LJMP(luaL_argerror(L, 1, "Invalid loglevel."));
7707
7708 hlua_sendlog(htxn->s->be, level, msg);
7709 return 0;
7710}
7711
7712__LJMP static int hlua_txn_log_debug(lua_State *L)
7713{
7714 const char *msg;
7715 struct hlua_txn *htxn;
7716
7717 MAY_LJMP(check_args(L, 2, "Debug"));
7718 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7719 msg = MAY_LJMP(luaL_checkstring(L, 2));
7720 hlua_sendlog(htxn->s->be, LOG_DEBUG, msg);
7721 return 0;
7722}
7723
7724__LJMP static int hlua_txn_log_info(lua_State *L)
7725{
7726 const char *msg;
7727 struct hlua_txn *htxn;
7728
7729 MAY_LJMP(check_args(L, 2, "Info"));
7730 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7731 msg = MAY_LJMP(luaL_checkstring(L, 2));
7732 hlua_sendlog(htxn->s->be, LOG_INFO, msg);
7733 return 0;
7734}
7735
7736__LJMP static int hlua_txn_log_warning(lua_State *L)
7737{
7738 const char *msg;
7739 struct hlua_txn *htxn;
7740
7741 MAY_LJMP(check_args(L, 2, "Warning"));
7742 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7743 msg = MAY_LJMP(luaL_checkstring(L, 2));
7744 hlua_sendlog(htxn->s->be, LOG_WARNING, msg);
7745 return 0;
7746}
7747
7748__LJMP static int hlua_txn_log_alert(lua_State *L)
7749{
7750 const char *msg;
7751 struct hlua_txn *htxn;
7752
7753 MAY_LJMP(check_args(L, 2, "Alert"));
7754 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7755 msg = MAY_LJMP(luaL_checkstring(L, 2));
7756 hlua_sendlog(htxn->s->be, LOG_ALERT, msg);
7757 return 0;
7758}
7759
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01007760__LJMP static int hlua_txn_set_loglevel(lua_State *L)
7761{
7762 struct hlua_txn *htxn;
7763 int ll;
7764
7765 MAY_LJMP(check_args(L, 2, "set_loglevel"));
7766 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7767 ll = MAY_LJMP(luaL_checkinteger(L, 2));
7768
7769 if (ll < 0 || ll > 7)
7770 WILL_LJMP(luaL_argerror(L, 2, "Bad log level. It must be between 0 and 7"));
7771
7772 htxn->s->logs.level = ll;
7773 return 0;
7774}
7775
7776__LJMP static int hlua_txn_set_tos(lua_State *L)
7777{
7778 struct hlua_txn *htxn;
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01007779 int tos;
7780
7781 MAY_LJMP(check_args(L, 2, "set_tos"));
7782 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7783 tos = MAY_LJMP(luaL_checkinteger(L, 2));
7784
Willy Tarreau1a18b542018-12-11 16:37:42 +01007785 conn_set_tos(objt_conn(htxn->s->sess->origin), tos);
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01007786 return 0;
7787}
7788
7789__LJMP static int hlua_txn_set_mark(lua_State *L)
7790{
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01007791 struct hlua_txn *htxn;
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01007792 int mark;
7793
7794 MAY_LJMP(check_args(L, 2, "set_mark"));
7795 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7796 mark = MAY_LJMP(luaL_checkinteger(L, 2));
7797
Lukas Tribus579e3e32019-08-11 18:03:45 +02007798 conn_set_mark(objt_conn(htxn->s->sess->origin), mark);
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01007799 return 0;
7800}
7801
Patrick Hemmer268a7072018-05-11 12:52:31 -04007802__LJMP static int hlua_txn_set_priority_class(lua_State *L)
7803{
7804 struct hlua_txn *htxn;
7805
7806 MAY_LJMP(check_args(L, 2, "set_priority_class"));
7807 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7808 htxn->s->priority_class = queue_limit_class(MAY_LJMP(luaL_checkinteger(L, 2)));
7809 return 0;
7810}
7811
7812__LJMP static int hlua_txn_set_priority_offset(lua_State *L)
7813{
7814 struct hlua_txn *htxn;
7815
7816 MAY_LJMP(check_args(L, 2, "set_priority_offset"));
7817 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7818 htxn->s->priority_offset = queue_limit_offset(MAY_LJMP(luaL_checkinteger(L, 2)));
7819 return 0;
7820}
7821
Christopher Faulet700d9e82020-01-31 12:21:52 +01007822/* Forward the Reply object to the client. This function converts the reply in
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05007823 * HTX an push it to into the response channel. It is response to forward the
Christopher Faulet700d9e82020-01-31 12:21:52 +01007824 * message and terminate the transaction. It returns 1 on success and 0 on
7825 * error. The Reply must be on top of the stack.
7826 */
7827__LJMP static int hlua_txn_forward_reply(lua_State *L, struct stream *s)
7828{
7829 struct htx *htx;
7830 struct htx_sl *sl;
7831 struct h1m h1m;
7832 const char *status, *reason, *body;
7833 size_t status_len, reason_len, body_len;
7834 int ret, code, flags;
7835
7836 code = 200;
7837 status = "200";
7838 status_len = 3;
7839 ret = lua_getfield(L, -1, "status");
7840 if (ret == LUA_TNUMBER) {
7841 code = lua_tointeger(L, -1);
7842 status = lua_tolstring(L, -1, &status_len);
7843 }
7844 lua_pop(L, 1);
7845
7846 reason = http_get_reason(code);
7847 reason_len = strlen(reason);
7848 ret = lua_getfield(L, -1, "reason");
7849 if (ret == LUA_TSTRING)
7850 reason = lua_tolstring(L, -1, &reason_len);
7851 lua_pop(L, 1);
7852
7853 body = NULL;
7854 body_len = 0;
7855 ret = lua_getfield(L, -1, "body");
7856 if (ret == LUA_TSTRING)
7857 body = lua_tolstring(L, -1, &body_len);
7858 lua_pop(L, 1);
7859
7860 /* Prepare the response before inserting the headers */
7861 h1m_init_res(&h1m);
7862 htx = htx_from_buf(&s->res.buf);
7863 channel_htx_truncate(&s->res, htx);
7864 if (s->txn->req.flags & HTTP_MSGF_VER_11) {
7865 flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11);
7866 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.1"),
7867 ist2(status, status_len), ist2(reason, reason_len));
7868 }
7869 else {
7870 flags = HTX_SL_F_IS_RESP;
7871 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.0"),
7872 ist2(status, status_len), ist2(reason, reason_len));
7873 }
7874 if (!sl)
7875 goto fail;
7876 sl->info.res.status = code;
7877
7878 /* Push in the stack the "headers" entry. */
7879 ret = lua_getfield(L, -1, "headers");
7880 if (ret != LUA_TTABLE)
7881 goto skip_headers;
7882
7883 lua_pushnil(L);
7884 while (lua_next(L, -2) != 0) {
7885 struct ist name, value;
7886 const char *n, *v;
7887 size_t nlen, vlen;
7888
7889 if (!lua_isstring(L, -2) || !lua_istable(L, -1)) {
7890 /* Skip element if the key is not a string or if the value is not a table */
7891 goto next_hdr;
7892 }
7893
7894 n = lua_tolstring(L, -2, &nlen);
7895 name = ist2(n, nlen);
7896 if (isteqi(name, ist("content-length"))) {
7897 /* Always skip content-length header. It will be added
7898 * later with the correct len
7899 */
7900 goto next_hdr;
7901 }
7902
7903 /* Loop on header's values */
7904 lua_pushnil(L);
7905 while (lua_next(L, -2)) {
7906 if (!lua_isstring(L, -1)) {
7907 /* Skip the value if it is not a string */
7908 goto next_value;
7909 }
7910
7911 v = lua_tolstring(L, -1, &vlen);
7912 value = ist2(v, vlen);
7913
7914 if (isteqi(name, ist("transfer-encoding")))
7915 h1_parse_xfer_enc_header(&h1m, value);
7916 if (!htx_add_header(htx, ist2(n, nlen), ist2(v, vlen)))
7917 goto fail;
7918
7919 next_value:
7920 lua_pop(L, 1);
7921 }
7922
7923 next_hdr:
7924 lua_pop(L, 1);
7925 }
7926 skip_headers:
7927 lua_pop(L, 1);
7928
7929 /* Update h1m flags: CLEN is set if CHNK is not present */
7930 if (!(h1m.flags & H1_MF_CHNK)) {
7931 const char *clen = ultoa(body_len);
7932
7933 h1m.flags |= H1_MF_CLEN;
7934 if (!htx_add_header(htx, ist("content-length"), ist(clen)))
7935 goto fail;
7936 }
7937 if (h1m.flags & (H1_MF_CLEN|H1_MF_CHNK))
7938 h1m.flags |= H1_MF_XFER_LEN;
7939
7940 /* Update HTX start-line flags */
7941 if (h1m.flags & H1_MF_XFER_ENC)
7942 flags |= HTX_SL_F_XFER_ENC;
7943 if (h1m.flags & H1_MF_XFER_LEN) {
7944 flags |= HTX_SL_F_XFER_LEN;
7945 if (h1m.flags & H1_MF_CHNK)
7946 flags |= HTX_SL_F_CHNK;
7947 else if (h1m.flags & H1_MF_CLEN)
7948 flags |= HTX_SL_F_CLEN;
7949 if (h1m.body_len == 0)
7950 flags |= HTX_SL_F_BODYLESS;
7951 }
7952 sl->flags |= flags;
7953
7954
7955 if (!htx_add_endof(htx, HTX_BLK_EOH) ||
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01007956 (body_len && !htx_add_data_atonce(htx, ist2(body, body_len))))
Christopher Faulet700d9e82020-01-31 12:21:52 +01007957 goto fail;
7958
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01007959 htx->flags |= HTX_FL_EOM;
7960
Christopher Faulet700d9e82020-01-31 12:21:52 +01007961 /* Now, forward the response and terminate the transaction */
7962 s->txn->status = code;
7963 htx_to_buf(htx, &s->res.buf);
7964 if (!http_forward_proxy_resp(s, 1))
7965 goto fail;
7966
7967 return 1;
7968
7969 fail:
7970 channel_htx_truncate(&s->res, htx);
7971 return 0;
7972}
7973
7974/* Terminate a transaction if called from a lua action. For TCP streams,
7975 * processing is just aborted. Nothing is returned to the client and all
7976 * arguments are ignored. For HTTP streams, if a reply is passed as argument, it
7977 * is forwarded to the client before terminating the transaction. On success,
7978 * the function exits with ACT_RET_DONE code. If an error occurred, it exits
7979 * with ACT_RET_ERR code. If this function is not called from a lua action, it
7980 * just exits without any processing.
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01007981 */
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02007982__LJMP static int hlua_txn_done(lua_State *L)
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01007983{
Willy Tarreaub2ccb562015-04-06 11:11:15 +02007984 struct hlua_txn *htxn;
Christopher Faulet700d9e82020-01-31 12:21:52 +01007985 struct stream *s;
7986 int finst;
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01007987
Willy Tarreaub2ccb562015-04-06 11:11:15 +02007988 htxn = MAY_LJMP(hlua_checktxn(L, 1));
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01007989
Christopher Faulet700d9e82020-01-31 12:21:52 +01007990 /* If the flags NOTERM is set, we cannot terminate the session, so we
7991 * just end the execution of the current lua code. */
7992 if (htxn->flags & HLUA_TXN_NOTERM)
Thierry FOURNIERab00df62016-07-14 11:42:37 +02007993 WILL_LJMP(hlua_done(L));
Thierry FOURNIERab00df62016-07-14 11:42:37 +02007994
Christopher Faulet700d9e82020-01-31 12:21:52 +01007995 s = htxn->s;
Christopher Fauletd8f0e072020-02-25 09:45:51 +01007996 if (!IS_HTX_STRM(htxn->s)) {
Christopher Faulet700d9e82020-01-31 12:21:52 +01007997 struct channel *req = &s->req;
7998 struct channel *res = &s->res;
Willy Tarreau81389672015-03-10 12:03:52 +01007999
Christopher Faulet700d9e82020-01-31 12:21:52 +01008000 channel_auto_read(req);
8001 channel_abort(req);
8002 channel_auto_close(req);
8003 channel_erase(req);
8004
8005 res->wex = tick_add_ifset(now_ms, res->wto);
8006 channel_auto_read(res);
8007 channel_auto_close(res);
8008 channel_shutr_now(res);
8009
8010 finst = ((htxn->dir == SMP_OPT_DIR_REQ) ? SF_FINST_R : SF_FINST_D);
8011 goto done;
Christopher Fauletfe6a71b2019-07-26 16:40:24 +02008012 }
Thierry FOURNIER10ec2142015-08-24 17:23:45 +02008013
Christopher Faulet700d9e82020-01-31 12:21:52 +01008014 if (lua_gettop(L) == 1 || !lua_istable(L, 2)) {
8015 /* No reply or invalid reply */
8016 s->txn->status = 0;
8017 http_reply_and_close(s, 0, NULL);
8018 }
8019 else {
8020 /* Remove extra args to have the reply on top of the stack */
8021 if (lua_gettop(L) > 2)
8022 lua_pop(L, lua_gettop(L) - 2);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01008023
Christopher Faulet700d9e82020-01-31 12:21:52 +01008024 if (!hlua_txn_forward_reply(L, s)) {
8025 if (!(s->flags & SF_ERR_MASK))
8026 s->flags |= SF_ERR_PRXCOND;
8027 lua_pushinteger(L, ACT_RET_ERR);
8028 WILL_LJMP(hlua_done(L));
8029 return 0; /* Never reached */
8030 }
Christopher Faulet4d0e2632019-07-16 10:52:40 +02008031 }
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02008032
Christopher Faulet700d9e82020-01-31 12:21:52 +01008033 finst = ((htxn->dir == SMP_OPT_DIR_REQ) ? SF_FINST_R : SF_FINST_H);
8034 if (htxn->dir == SMP_OPT_DIR_REQ) {
8035 /* let's log the request time */
8036 s->logs.tv_request = now;
8037 if (s->sess->fe == s->be) /* report it if the request was intercepted by the frontend */
Willy Tarreau4781b152021-04-06 13:53:36 +02008038 _HA_ATOMIC_INC(&s->sess->fe->fe_counters.intercepted_req);
Christopher Faulet700d9e82020-01-31 12:21:52 +01008039 }
Christopher Fauletfe6a71b2019-07-26 16:40:24 +02008040
Christopher Faulet700d9e82020-01-31 12:21:52 +01008041 done:
8042 if (!(s->flags & SF_ERR_MASK))
8043 s->flags |= SF_ERR_LOCAL;
8044 if (!(s->flags & SF_FINST_MASK))
8045 s->flags |= finst;
Christopher Fauletfe6a71b2019-07-26 16:40:24 +02008046
Christopher Faulete48d1dc2021-08-13 14:11:17 +02008047 if ((htxn->flags & HLUA_TXN_CTX_MASK) == HLUA_TXN_FLT_CTX)
8048 lua_pushinteger(L, -1);
8049 else
8050 lua_pushinteger(L, ACT_RET_ABRT);
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02008051 WILL_LJMP(hlua_done(L));
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01008052 return 0;
8053}
8054
Christopher Faulet700d9e82020-01-31 12:21:52 +01008055/*
8056 *
8057 *
8058 * Class REPLY
8059 *
8060 *
8061 */
8062
8063/* Pushes the TXN reply onto the top of the stack. If the stask does not have a
8064 * free slots, the function fails and returns 0;
8065 */
8066static int hlua_txn_reply_new(lua_State *L)
8067{
8068 struct hlua_txn *htxn;
8069 const char *reason, *body = NULL;
8070 int ret, status;
8071
8072 htxn = MAY_LJMP(hlua_checktxn(L, 1));
Christopher Fauletd8f0e072020-02-25 09:45:51 +01008073 if (!IS_HTX_STRM(htxn->s)) {
Christopher Faulet700d9e82020-01-31 12:21:52 +01008074 hlua_pusherror(L, "txn object is not an HTTP transaction.");
8075 WILL_LJMP(lua_error(L));
8076 }
8077
8078 /* Default value */
8079 status = 200;
8080 reason = http_get_reason(status);
8081
8082 if (lua_istable(L, 2)) {
8083 /* load status and reason from the table argument at index 2 */
8084 ret = lua_getfield(L, 2, "status");
8085 if (ret == LUA_TNIL)
8086 goto reason;
8087 else if (ret != LUA_TNUMBER) {
8088 /* invalid status: ignore the reason */
8089 goto body;
8090 }
8091 status = lua_tointeger(L, -1);
8092
8093 reason:
8094 lua_pop(L, 1); /* restore the stack: remove status */
8095 ret = lua_getfield(L, 2, "reason");
8096 if (ret == LUA_TSTRING)
8097 reason = lua_tostring(L, -1);
8098
8099 body:
8100 lua_pop(L, 1); /* restore the stack: remove invalid status or reason */
8101 ret = lua_getfield(L, 2, "body");
8102 if (ret == LUA_TSTRING)
8103 body = lua_tostring(L, -1);
8104 lua_pop(L, 1); /* restore the stack: remove body */
8105 }
8106
8107 /* Create the Reply table */
8108 lua_newtable(L);
8109
8110 /* Add status element */
8111 lua_pushstring(L, "status");
8112 lua_pushinteger(L, status);
8113 lua_settable(L, -3);
8114
8115 /* Add reason element */
8116 reason = http_get_reason(status);
8117 lua_pushstring(L, "reason");
8118 lua_pushstring(L, reason);
8119 lua_settable(L, -3);
8120
8121 /* Add body element, nil if undefined */
8122 lua_pushstring(L, "body");
8123 if (body)
8124 lua_pushstring(L, body);
8125 else
8126 lua_pushnil(L);
8127 lua_settable(L, -3);
8128
8129 /* Add headers element */
8130 lua_pushstring(L, "headers");
8131 lua_newtable(L);
8132
8133 /* stack: [ txn, <Arg:table>, <Reply:table>, "headers", <headers:table> ] */
8134 if (lua_istable(L, 2)) {
8135 /* load headers from the table argument at index 2. If it is a table, copy it. */
8136 ret = lua_getfield(L, 2, "headers");
8137 if (ret == LUA_TTABLE) {
8138 /* stack: [ ... <headers:table>, <table> ] */
8139 lua_pushnil(L);
8140 while (lua_next(L, -2) != 0) {
8141 /* stack: [ ... <headers:table>, <table>, k, v] */
8142 if (!lua_isstring(L, -1) && !lua_istable(L, -1)) {
8143 /* invalid value type, skip it */
8144 lua_pop(L, 1);
8145 continue;
8146 }
8147
8148
8149 /* Duplicate the key and swap it with the value. */
8150 lua_pushvalue(L, -2);
8151 lua_insert(L, -2);
8152 /* stack: [ ... <headers:table>, <table>, k, k, v ] */
8153
8154 lua_newtable(L);
8155 lua_insert(L, -2);
8156 /* stack: [ ... <headers:table>, <table>, k, k, <inner:table>, v ] */
8157
8158 if (lua_isstring(L, -1)) {
8159 /* push the value in the inner table */
8160 lua_rawseti(L, -2, 1);
8161 }
8162 else { /* table */
8163 lua_pushnil(L);
8164 while (lua_next(L, -2) != 0) {
8165 /* stack: [ ... <headers:table>, <table>, k, k, <inner:table>, <v:table>, k2, v2 ] */
8166 if (!lua_isstring(L, -1)) {
8167 /* invalid value type, skip it*/
8168 lua_pop(L, 1);
8169 continue;
8170 }
8171 /* push the value in the inner table */
8172 lua_rawseti(L, -4, lua_rawlen(L, -4) + 1);
8173 /* stack: [ ... <headers:table>, <table>, k, k, <inner:table>, <v:table>, k2 ] */
8174 }
8175 lua_pop(L, 1);
8176 /* stack: [ ... <headers:table>, <table>, k, k, <inner:table> ] */
8177 }
8178
8179 /* push (k,v) on the stack in the headers table:
8180 * stack: [ ... <headers:table>, <table>, k, k, v ]
8181 */
8182 lua_settable(L, -5);
8183 /* stack: [ ... <headers:table>, <table>, k ] */
8184 }
8185 }
8186 lua_pop(L, 1);
8187 }
8188 /* stack: [ txn, <Arg:table>, <Reply:table>, "headers", <headers:table> ] */
8189 lua_settable(L, -3);
8190 /* stack: [ txn, <Arg:table>, <Reply:table> ] */
8191
8192 /* Pop a class sesison metatable and affect it to the userdata. */
8193 lua_rawgeti(L, LUA_REGISTRYINDEX, class_txn_reply_ref);
8194 lua_setmetatable(L, -2);
8195 return 1;
8196}
8197
8198/* Set the reply status code, and optionally the reason. If no reason is
8199 * provided, the default one corresponding to the status code is used.
8200 */
8201__LJMP static int hlua_txn_reply_set_status(lua_State *L)
8202{
8203 int status = MAY_LJMP(luaL_checkinteger(L, 2));
8204 const char *reason = MAY_LJMP(luaL_optlstring(L, 3, NULL, NULL));
8205
8206 /* First argument (self) must be a table */
8207 luaL_checktype(L, 1, LUA_TTABLE);
8208
8209 if (status < 100 || status > 599) {
8210 lua_pushboolean(L, 0);
8211 return 1;
8212 }
8213 if (!reason)
8214 reason = http_get_reason(status);
8215
8216 lua_pushinteger(L, status);
8217 lua_setfield(L, 1, "status");
8218
8219 lua_pushstring(L, reason);
8220 lua_setfield(L, 1, "reason");
8221
8222 lua_pushboolean(L, 1);
8223 return 1;
8224}
8225
8226/* Add a header into the reply object. Each header name is associated to an
8227 * array of values in the "headers" table. If the header name is not found, a
8228 * new entry is created.
8229 */
8230__LJMP static int hlua_txn_reply_add_header(lua_State *L)
8231{
8232 const char *name = MAY_LJMP(luaL_checkstring(L, 2));
8233 const char *value = MAY_LJMP(luaL_checkstring(L, 3));
8234 int ret;
8235
8236 /* First argument (self) must be a table */
8237 luaL_checktype(L, 1, LUA_TTABLE);
8238
8239 /* Push in the stack the "headers" entry. */
8240 ret = lua_getfield(L, 1, "headers");
8241 if (ret != LUA_TTABLE) {
8242 hlua_pusherror(L, "Reply['headers'] is expected to a an array. %s found", lua_typename(L, ret));
8243 WILL_LJMP(lua_error(L));
8244 }
8245
8246 /* check if the header is already registered. If not, register it. */
8247 ret = lua_getfield(L, -1, name);
8248 if (ret == LUA_TNIL) {
8249 /* Entry not found. */
8250 lua_pop(L, 1); /* remove the nil. The "headers" table is the top of the stack. */
8251
8252 /* Insert the new header name in the array in the top of the stack.
8253 * It left the new array in the top of the stack.
8254 */
8255 lua_newtable(L);
8256 lua_pushstring(L, name);
8257 lua_pushvalue(L, -2);
8258 lua_settable(L, -4);
8259 }
8260 else if (ret != LUA_TTABLE) {
8261 hlua_pusherror(L, "Reply['headers']['%s'] is expected to be an array. %s found", name, lua_typename(L, ret));
8262 WILL_LJMP(lua_error(L));
8263 }
8264
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -07008265 /* Now the top of thestack is an array of values. We push
Christopher Faulet700d9e82020-01-31 12:21:52 +01008266 * the header value as new entry.
8267 */
8268 lua_pushstring(L, value);
8269 ret = lua_rawlen(L, -2);
8270 lua_rawseti(L, -2, ret + 1);
8271
8272 lua_pushboolean(L, 1);
8273 return 1;
8274}
8275
8276/* Remove all occurrences of a given header name. */
8277__LJMP static int hlua_txn_reply_del_header(lua_State *L)
8278{
8279 const char *name = MAY_LJMP(luaL_checkstring(L, 2));
8280 int ret;
8281
8282 /* First argument (self) must be a table */
8283 luaL_checktype(L, 1, LUA_TTABLE);
8284
8285 /* Push in the stack the "headers" entry. */
8286 ret = lua_getfield(L, 1, "headers");
8287 if (ret != LUA_TTABLE) {
8288 hlua_pusherror(L, "Reply['headers'] is expected to be an array. %s found", lua_typename(L, ret));
8289 WILL_LJMP(lua_error(L));
8290 }
8291
8292 lua_pushstring(L, name);
8293 lua_pushnil(L);
8294 lua_settable(L, -3);
8295
8296 lua_pushboolean(L, 1);
8297 return 1;
8298}
8299
8300/* Set the reply's body. Overwrite any existing entry. */
8301__LJMP static int hlua_txn_reply_set_body(lua_State *L)
8302{
8303 const char *payload = MAY_LJMP(luaL_checkstring(L, 2));
8304
8305 /* First argument (self) must be a table */
8306 luaL_checktype(L, 1, LUA_TTABLE);
8307
8308 lua_pushstring(L, payload);
8309 lua_setfield(L, 1, "body");
8310
8311 lua_pushboolean(L, 1);
8312 return 1;
8313}
8314
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01008315__LJMP static int hlua_log(lua_State *L)
8316{
8317 int level;
8318 const char *msg;
8319
8320 MAY_LJMP(check_args(L, 2, "log"));
8321 level = MAY_LJMP(luaL_checkinteger(L, 1));
8322 msg = MAY_LJMP(luaL_checkstring(L, 2));
8323
8324 if (level < 0 || level >= NB_LOG_LEVELS)
8325 WILL_LJMP(luaL_argerror(L, 1, "Invalid loglevel."));
8326
8327 hlua_sendlog(NULL, level, msg);
8328 return 0;
8329}
8330
8331__LJMP static int hlua_log_debug(lua_State *L)
8332{
8333 const char *msg;
8334
8335 MAY_LJMP(check_args(L, 1, "debug"));
8336 msg = MAY_LJMP(luaL_checkstring(L, 1));
8337 hlua_sendlog(NULL, LOG_DEBUG, msg);
8338 return 0;
8339}
8340
8341__LJMP static int hlua_log_info(lua_State *L)
8342{
8343 const char *msg;
8344
8345 MAY_LJMP(check_args(L, 1, "info"));
8346 msg = MAY_LJMP(luaL_checkstring(L, 1));
8347 hlua_sendlog(NULL, LOG_INFO, msg);
8348 return 0;
8349}
8350
8351__LJMP static int hlua_log_warning(lua_State *L)
8352{
8353 const char *msg;
8354
8355 MAY_LJMP(check_args(L, 1, "warning"));
8356 msg = MAY_LJMP(luaL_checkstring(L, 1));
8357 hlua_sendlog(NULL, LOG_WARNING, msg);
8358 return 0;
8359}
8360
8361__LJMP static int hlua_log_alert(lua_State *L)
8362{
8363 const char *msg;
8364
8365 MAY_LJMP(check_args(L, 1, "alert"));
8366 msg = MAY_LJMP(luaL_checkstring(L, 1));
8367 hlua_sendlog(NULL, LOG_ALERT, msg);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01008368 return 0;
8369}
8370
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01008371__LJMP static int hlua_sleep_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008372{
8373 int wakeup_ms = lua_tointeger(L, -1);
Willy Tarreau12c02702021-09-30 16:12:31 +02008374 if (!tick_is_expired(wakeup_ms, now_ms))
Willy Tarreau9635e032018-10-16 17:52:55 +02008375 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008376 return 0;
8377}
8378
8379__LJMP static int hlua_sleep(lua_State *L)
8380{
8381 unsigned int delay;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008382 unsigned int wakeup_ms;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008383
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008384 MAY_LJMP(check_args(L, 1, "sleep"));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008385
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01008386 delay = MAY_LJMP(luaL_checkinteger(L, 1)) * 1000;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008387 wakeup_ms = tick_add(now_ms, delay);
8388 lua_pushinteger(L, wakeup_ms);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008389
Willy Tarreau9635e032018-10-16 17:52:55 +02008390 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008391 return 0;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008392}
8393
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008394__LJMP static int hlua_msleep(lua_State *L)
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008395{
8396 unsigned int delay;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008397 unsigned int wakeup_ms;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008398
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008399 MAY_LJMP(check_args(L, 1, "msleep"));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008400
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01008401 delay = MAY_LJMP(luaL_checkinteger(L, 1));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008402 wakeup_ms = tick_add(now_ms, delay);
8403 lua_pushinteger(L, wakeup_ms);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008404
Willy Tarreau9635e032018-10-16 17:52:55 +02008405 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008406 return 0;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008407}
8408
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01008409/* This functionis an LUA binding. it permits to give back
8410 * the hand at the HAProxy scheduler. It is used when the
8411 * LUA processing consumes a lot of time.
8412 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01008413__LJMP static int hlua_yield_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008414{
8415 return 0;
8416}
8417
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01008418__LJMP static int hlua_yield(lua_State *L)
8419{
Willy Tarreau9635e032018-10-16 17:52:55 +02008420 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_yield_yield, TICK_ETERNITY, HLUA_CTRLYIELD));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008421 return 0;
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01008422}
8423
Thierry FOURNIER37196f42015-02-16 19:34:56 +01008424/* This function change the nice of the currently executed
8425 * task. It is used set low or high priority at the current
8426 * task.
8427 */
Willy Tarreau59551662015-03-10 14:23:13 +01008428__LJMP static int hlua_set_nice(lua_State *L)
Thierry FOURNIER37196f42015-02-16 19:34:56 +01008429{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01008430 struct hlua *hlua;
8431 int nice;
Thierry FOURNIER37196f42015-02-16 19:34:56 +01008432
Willy Tarreau80f5fae2015-02-27 16:38:20 +01008433 MAY_LJMP(check_args(L, 1, "set_nice"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01008434 nice = MAY_LJMP(luaL_checkinteger(L, 1));
Thierry FOURNIER37196f42015-02-16 19:34:56 +01008435
Thierry Fournier4234dbd2020-11-28 13:18:23 +01008436 /* Get hlua struct, or NULL if we execute from main lua state */
8437 hlua = hlua_gethlua(L);
8438
8439 /* If the task is not set, I'm in a start mode. */
Thierry FOURNIER37196f42015-02-16 19:34:56 +01008440 if (!hlua || !hlua->task)
8441 return 0;
8442
8443 if (nice < -1024)
8444 nice = -1024;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01008445 else if (nice > 1024)
Thierry FOURNIER37196f42015-02-16 19:34:56 +01008446 nice = 1024;
8447
8448 hlua->task->nice = nice;
8449 return 0;
8450}
8451
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08008452/* This function is used as a callback of a task. It is called by the
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008453 * HAProxy task subsystem when the task is awaked. The LUA runtime can
8454 * return an E_AGAIN signal, the emmiter of this signal must set a
8455 * signal to wake the task.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008456 *
8457 * Task wrapper are longjmp safe because the only one Lua code
8458 * executed is the safe hlua_ctx_resume();
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008459 */
Willy Tarreau144f84a2021-03-02 16:09:26 +01008460struct task *hlua_process_task(struct task *task, void *context, unsigned int state)
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008461{
Olivier Houchard9f6af332018-05-25 14:04:04 +02008462 struct hlua *hlua = context;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008463 enum hlua_exec status;
8464
Willy Tarreau6ef52f42022-06-15 14:19:48 +02008465 if (task->tid < 0)
8466 task->tid = tid;
8467
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008468 /* If it is the first call to the task, we must initialize the
8469 * execution timeouts.
8470 */
8471 if (!HLUA_IS_RUNNING(hlua))
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02008472 hlua->max_time = hlua_timeout_task;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008473
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008474 /* Execute the Lua code. */
8475 status = hlua_ctx_resume(hlua, 1);
8476
8477 switch (status) {
8478 /* finished or yield */
8479 case HLUA_E_OK:
8480 hlua_ctx_destroy(hlua);
Olivier Houchard3f795f72019-04-17 22:51:06 +02008481 task_destroy(task);
Tim Duesterhuscd235c62018-04-24 13:56:01 +02008482 task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008483 break;
8484
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01008485 case HLUA_E_AGAIN: /* co process or timeout wake me later. */
Thierry FOURNIERcb146882017-12-10 17:10:57 +01008486 notification_gc(&hlua->com);
PiBa-NLfe971b32018-05-02 22:27:14 +02008487 task->expire = hlua->wake_time;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008488 break;
8489
8490 /* finished with error. */
8491 case HLUA_E_ERRMSG:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008492 SEND_ERR(NULL, "Lua task: %s.\n", lua_tostring(hlua->T, -1));
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008493 hlua_ctx_destroy(hlua);
Olivier Houchard3f795f72019-04-17 22:51:06 +02008494 task_destroy(task);
Emeric Brun253e53e2017-10-17 18:58:40 +02008495 task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008496 break;
8497
8498 case HLUA_E_ERR:
8499 default:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008500 SEND_ERR(NULL, "Lua task: unknown error.\n");
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008501 hlua_ctx_destroy(hlua);
Olivier Houchard3f795f72019-04-17 22:51:06 +02008502 task_destroy(task);
Emeric Brun253e53e2017-10-17 18:58:40 +02008503 task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008504 break;
8505 }
Emeric Brun253e53e2017-10-17 18:58:40 +02008506 return task;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008507}
8508
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008509/* This function is an LUA binding that register LUA function to be
8510 * executed after the HAProxy configuration parsing and before the
8511 * HAProxy scheduler starts. This function expect only one LUA
8512 * argument that is a function. This function returns nothing, but
8513 * throws if an error is encountered.
8514 */
8515__LJMP static int hlua_register_init(lua_State *L)
8516{
8517 struct hlua_init_function *init;
8518 int ref;
8519
8520 MAY_LJMP(check_args(L, 1, "register_init"));
8521
8522 ref = MAY_LJMP(hlua_checkfunction(L, 1));
8523
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02008524 init = calloc(1, sizeof(*init));
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008525 if (!init)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01008526 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008527
8528 init->function_ref = ref;
Willy Tarreau2b718102021-04-21 07:32:39 +02008529 LIST_APPEND(&hlua_init_functions[hlua_state_id], &init->l);
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008530 return 0;
8531}
8532
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008533/* This functio is an LUA binding. It permits to register a task
8534 * executed in parallel of the main HAroxy activity. The task is
8535 * created and it is set in the HAProxy scheduler. It can be called
8536 * from the "init" section, "post init" or during the runtime.
8537 *
8538 * Lua prototype:
8539 *
8540 * <none> core.register_task(<function>)
8541 */
8542static int hlua_register_task(lua_State *L)
8543{
Christopher Faulet5294ec02021-04-12 12:24:47 +02008544 struct hlua *hlua = NULL;
8545 struct task *task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008546 int ref;
Thierry Fournier021d9862020-11-28 23:42:03 +01008547 int state_id;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008548
8549 MAY_LJMP(check_args(L, 1, "register_task"));
8550
8551 ref = MAY_LJMP(hlua_checkfunction(L, 1));
8552
Thierry Fournier75fc0292020-11-28 13:18:56 +01008553 /* Get the reference state. If the reference is NULL, L is the master
8554 * state, otherwise hlua->T is.
8555 */
8556 hlua = hlua_gethlua(L);
8557 if (hlua)
Thierry Fournier021d9862020-11-28 23:42:03 +01008558 /* we are in runtime processing */
8559 state_id = hlua->state_id;
Thierry Fournier75fc0292020-11-28 13:18:56 +01008560 else
Thierry Fournier021d9862020-11-28 23:42:03 +01008561 /* we are in initialization mode */
Thierry Fournierc7492592020-11-28 23:57:24 +01008562 state_id = hlua_state_id;
Thierry Fournier75fc0292020-11-28 13:18:56 +01008563
Willy Tarreaubafbe012017-11-24 17:34:44 +01008564 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008565 if (!hlua)
Christopher Faulet5294ec02021-04-12 12:24:47 +02008566 goto alloc_error;
Christopher Faulet1e8433f2021-03-24 15:03:01 +01008567 HLUA_INIT(hlua);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008568
Thierry Fournier59f11be2020-11-29 00:37:41 +01008569 /* We are in the common lua state, execute the task anywhere,
8570 * otherwise, inherit the current thread identifier
8571 */
8572 if (state_id == 0)
Willy Tarreaubeeabf52021-10-01 18:23:30 +02008573 task = task_new_anywhere();
Thierry Fournier59f11be2020-11-29 00:37:41 +01008574 else
Willy Tarreaubeeabf52021-10-01 18:23:30 +02008575 task = task_new_here();
Willy Tarreaue09101e2018-10-16 17:37:12 +02008576 if (!task)
Christopher Faulet5294ec02021-04-12 12:24:47 +02008577 goto alloc_error;
Willy Tarreaue09101e2018-10-16 17:37:12 +02008578
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008579 task->context = hlua;
8580 task->process = hlua_process_task;
8581
Thierry Fournier021d9862020-11-28 23:42:03 +01008582 if (!hlua_ctx_init(hlua, state_id, task, 1))
Christopher Faulet5294ec02021-04-12 12:24:47 +02008583 goto alloc_error;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008584
8585 /* Restore the function in the stack. */
8586 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ref);
8587 hlua->nargs = 0;
8588
8589 /* Schedule task. */
Willy Tarreaue3957f82021-09-30 16:17:37 +02008590 task_wakeup(task, TASK_WOKEN_INIT);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008591
8592 return 0;
Christopher Faulet5294ec02021-04-12 12:24:47 +02008593
8594 alloc_error:
8595 task_destroy(task);
8596 hlua_ctx_destroy(hlua);
8597 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
8598 return 0; /* Never reached */
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008599}
8600
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008601/* Wrapper called by HAProxy to execute an LUA converter. This wrapper
8602 * doesn't allow "yield" functions because the HAProxy engine cannot
8603 * resume converters.
8604 */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02008605static int hlua_sample_conv_wrapper(const struct arg *arg_p, struct sample *smp, void *private)
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008606{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02008607 struct hlua_function *fcn = private;
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02008608 struct stream *stream = smp->strm;
Thierry Fournierfd107a22016-02-19 19:57:23 +01008609 const char *error;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008610
Willy Tarreaube508f12016-03-10 11:47:01 +01008611 if (!stream)
8612 return 0;
8613
Willy Tarreau87b09662015-04-03 00:22:06 +02008614 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01008615 * Lua context can be not initialized. This behavior
8616 * permits to save performances because a systematic
8617 * Lua initialization cause 5% performances loss.
8618 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008619 if (!stream->hlua) {
Christopher Faulet1e8433f2021-03-24 15:03:01 +01008620 struct hlua *hlua;
8621
8622 hlua = pool_alloc(pool_head_hlua);
8623 if (!hlua) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008624 SEND_ERR(stream->be, "Lua converter '%s': can't initialize Lua context.\n", fcn->name);
8625 return 0;
8626 }
Christopher Faulet1e8433f2021-03-24 15:03:01 +01008627 HLUA_INIT(hlua);
8628 stream->hlua = hlua;
Thierry Fournierc7492592020-11-28 23:57:24 +01008629 if (!hlua_ctx_init(stream->hlua, fcn_ref_to_stack_id(fcn), stream->task, 0)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008630 SEND_ERR(stream->be, "Lua converter '%s': can't initialize Lua context.\n", fcn->name);
8631 return 0;
8632 }
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01008633 }
8634
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008635 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008636 if (!HLUA_IS_RUNNING(stream->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008637
8638 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008639 if (!SET_SAFE_LJMP(stream->hlua)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008640 if (lua_type(stream->hlua->T, -1) == LUA_TSTRING)
8641 error = lua_tostring(stream->hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +01008642 else
8643 error = "critical error";
8644 SEND_ERR(stream->be, "Lua converter '%s': %s.\n", fcn->name, error);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008645 return 0;
8646 }
8647
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008648 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008649 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008650 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008651 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008652 return 0;
8653 }
8654
8655 /* Restore the function in the stack. */
Thierry Fournierc7492592020-11-28 23:57:24 +01008656 lua_rawgeti(stream->hlua->T, LUA_REGISTRYINDEX, fcn->function_ref[stream->hlua->state_id]);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008657
8658 /* convert input sample and pust-it in the stack. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008659 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008660 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008661 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008662 return 0;
8663 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008664 hlua_smp2lua(stream->hlua->T, smp);
8665 stream->hlua->nargs = 1;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008666
8667 /* push keywords in the stack. */
8668 if (arg_p) {
8669 for (; arg_p->type != ARGT_STOP; arg_p++) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008670 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008671 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008672 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008673 return 0;
8674 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008675 hlua_arg2lua(stream->hlua->T, arg_p);
8676 stream->hlua->nargs++;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008677 }
8678 }
8679
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008680 /* We must initialize the execution timeouts. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008681 stream->hlua->max_time = hlua_timeout_session;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008682
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008683 /* At this point the execution is safe. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008684 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008685 }
8686
8687 /* Execute the function. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008688 switch (hlua_ctx_resume(stream->hlua, 0)) {
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008689 /* finished. */
8690 case HLUA_E_OK:
Thierry FOURNIERfd80df12017-05-12 16:32:20 +02008691 /* If the stack is empty, the function fails. */
8692 if (lua_gettop(stream->hlua->T) <= 0)
8693 return 0;
8694
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008695 /* Convert the returned value in sample. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008696 hlua_lua2smp(stream->hlua->T, -1, smp);
8697 lua_pop(stream->hlua->T, 1);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008698 return 1;
8699
8700 /* yield. */
8701 case HLUA_E_AGAIN:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008702 SEND_ERR(stream->be, "Lua converter '%s': cannot use yielded functions.\n", fcn->name);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008703 return 0;
8704
8705 /* finished with error. */
8706 case HLUA_E_ERRMSG:
8707 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008708 SEND_ERR(stream->be, "Lua converter '%s': %s.\n",
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008709 fcn->name, lua_tostring(stream->hlua->T, -1));
8710 lua_pop(stream->hlua->T, 1);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008711 return 0;
8712
Thierry Fournierd5b073c2018-05-21 19:42:47 +02008713 case HLUA_E_ETMOUT:
8714 SEND_ERR(stream->be, "Lua converter '%s': execution timeout.\n", fcn->name);
8715 return 0;
8716
8717 case HLUA_E_NOMEM:
8718 SEND_ERR(stream->be, "Lua converter '%s': out of memory error.\n", fcn->name);
8719 return 0;
8720
8721 case HLUA_E_YIELD:
8722 SEND_ERR(stream->be, "Lua converter '%s': yield functions like core.tcp() or core.sleep() are not allowed.\n", fcn->name);
8723 return 0;
8724
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008725 case HLUA_E_ERR:
8726 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008727 SEND_ERR(stream->be, "Lua converter '%s' returns an unknown error.\n", fcn->name);
Tim Duesterhus588b3142020-05-29 14:35:51 +02008728 /* fall through */
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008729
8730 default:
8731 return 0;
8732 }
8733}
8734
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008735/* Wrapper called by HAProxy to execute a sample-fetch. this wrapper
8736 * doesn't allow "yield" functions because the HAProxy engine cannot
Willy Tarreaube508f12016-03-10 11:47:01 +01008737 * resume sample-fetches. This function will be called by the sample
8738 * fetch engine to call lua-based fetch operations.
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008739 */
Thierry FOURNIER0786d052015-05-11 15:42:45 +02008740static int hlua_sample_fetch_wrapper(const struct arg *arg_p, struct sample *smp,
8741 const char *kw, void *private)
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008742{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02008743 struct hlua_function *fcn = private;
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02008744 struct stream *stream = smp->strm;
Thierry Fournierfd107a22016-02-19 19:57:23 +01008745 const char *error;
Christopher Faulet8c9e6bb2021-08-06 16:29:41 +02008746 unsigned int hflags = HLUA_TXN_NOTERM | HLUA_TXN_SMP_CTX;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008747
Willy Tarreaube508f12016-03-10 11:47:01 +01008748 if (!stream)
8749 return 0;
Christopher Fauletafd8f102018-11-08 11:34:21 +01008750
Willy Tarreau87b09662015-04-03 00:22:06 +02008751 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01008752 * Lua context can be not initialized. This behavior
8753 * permits to save performances because a systematic
8754 * Lua initialization cause 5% performances loss.
8755 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008756 if (!stream->hlua) {
Christopher Faulet1e8433f2021-03-24 15:03:01 +01008757 struct hlua *hlua;
8758
8759 hlua = pool_alloc(pool_head_hlua);
8760 if (!hlua) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008761 SEND_ERR(stream->be, "Lua sample-fetch '%s': can't initialize Lua context.\n", fcn->name);
8762 return 0;
8763 }
Christopher Faulet1e8433f2021-03-24 15:03:01 +01008764 hlua->T = NULL;
8765 stream->hlua = hlua;
Thierry Fournierc7492592020-11-28 23:57:24 +01008766 if (!hlua_ctx_init(stream->hlua, fcn_ref_to_stack_id(fcn), stream->task, 0)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008767 SEND_ERR(stream->be, "Lua sample-fetch '%s': can't initialize Lua context.\n", fcn->name);
8768 return 0;
8769 }
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01008770 }
8771
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008772 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008773 if (!HLUA_IS_RUNNING(stream->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008774
8775 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008776 if (!SET_SAFE_LJMP(stream->hlua)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008777 if (lua_type(stream->hlua->T, -1) == LUA_TSTRING)
8778 error = lua_tostring(stream->hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +01008779 else
8780 error = "critical error";
8781 SEND_ERR(smp->px, "Lua sample-fetch '%s': %s.\n", fcn->name, error);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008782 return 0;
8783 }
8784
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008785 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008786 if (!lua_checkstack(stream->hlua->T, 2)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008787 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008788 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008789 return 0;
8790 }
8791
8792 /* Restore the function in the stack. */
Thierry Fournierc7492592020-11-28 23:57:24 +01008793 lua_rawgeti(stream->hlua->T, LUA_REGISTRYINDEX, fcn->function_ref[stream->hlua->state_id]);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008794
8795 /* push arguments in the stack. */
Christopher Fauletbfab2dd2019-07-26 15:09:53 +02008796 if (!hlua_txn_new(stream->hlua->T, stream, smp->px, smp->opt & SMP_OPT_DIR, hflags)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008797 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008798 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008799 return 0;
8800 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008801 stream->hlua->nargs = 1;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008802
8803 /* push keywords in the stack. */
8804 for (; arg_p && arg_p->type != ARGT_STOP; arg_p++) {
8805 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008806 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008807 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008808 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008809 return 0;
8810 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008811 hlua_arg2lua(stream->hlua->T, arg_p);
8812 stream->hlua->nargs++;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008813 }
8814
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008815 /* We must initialize the execution timeouts. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008816 stream->hlua->max_time = hlua_timeout_session;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008817
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008818 /* At this point the execution is safe. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008819 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008820 }
8821
8822 /* Execute the function. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008823 switch (hlua_ctx_resume(stream->hlua, 0)) {
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008824 /* finished. */
8825 case HLUA_E_OK:
Thierry FOURNIERfd80df12017-05-12 16:32:20 +02008826 /* If the stack is empty, the function fails. */
8827 if (lua_gettop(stream->hlua->T) <= 0)
8828 return 0;
8829
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008830 /* Convert the returned value in sample. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008831 hlua_lua2smp(stream->hlua->T, -1, smp);
8832 lua_pop(stream->hlua->T, 1);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008833
8834 /* Set the end of execution flag. */
8835 smp->flags &= ~SMP_F_MAY_CHANGE;
8836 return 1;
8837
8838 /* yield. */
8839 case HLUA_E_AGAIN:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008840 SEND_ERR(smp->px, "Lua sample-fetch '%s': cannot use yielded functions.\n", fcn->name);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008841 return 0;
8842
8843 /* finished with error. */
8844 case HLUA_E_ERRMSG:
8845 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008846 SEND_ERR(smp->px, "Lua sample-fetch '%s': %s.\n",
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008847 fcn->name, lua_tostring(stream->hlua->T, -1));
8848 lua_pop(stream->hlua->T, 1);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008849 return 0;
8850
Thierry Fournierd5b073c2018-05-21 19:42:47 +02008851 case HLUA_E_ETMOUT:
Thierry Fournierd5b073c2018-05-21 19:42:47 +02008852 SEND_ERR(smp->px, "Lua sample-fetch '%s': execution timeout.\n", fcn->name);
8853 return 0;
8854
8855 case HLUA_E_NOMEM:
Thierry Fournierd5b073c2018-05-21 19:42:47 +02008856 SEND_ERR(smp->px, "Lua sample-fetch '%s': out of memory error.\n", fcn->name);
8857 return 0;
8858
8859 case HLUA_E_YIELD:
Thierry Fournierd5b073c2018-05-21 19:42:47 +02008860 SEND_ERR(smp->px, "Lua sample-fetch '%s': yield not allowed.\n", fcn->name);
8861 return 0;
8862
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008863 case HLUA_E_ERR:
8864 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008865 SEND_ERR(smp->px, "Lua sample-fetch '%s' returns an unknown error.\n", fcn->name);
Tim Duesterhus588b3142020-05-29 14:35:51 +02008866 /* fall through */
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008867
8868 default:
8869 return 0;
8870 }
8871}
8872
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008873/* This function is an LUA binding used for registering
8874 * "sample-conv" functions. It expects a converter name used
8875 * in the haproxy configuration file, and an LUA function.
8876 */
8877__LJMP static int hlua_register_converters(lua_State *L)
8878{
8879 struct sample_conv_kw_list *sck;
8880 const char *name;
8881 int ref;
8882 int len;
Christopher Fauletaa224302021-04-12 14:08:21 +02008883 struct hlua_function *fcn = NULL;
Thierry Fournierf67442e2020-11-28 20:41:07 +01008884 struct sample_conv *sc;
8885 struct buffer *trash;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008886
8887 MAY_LJMP(check_args(L, 2, "register_converters"));
8888
8889 /* First argument : converter name. */
8890 name = MAY_LJMP(luaL_checkstring(L, 1));
8891
8892 /* Second argument : lua function. */
8893 ref = MAY_LJMP(hlua_checkfunction(L, 2));
8894
Thierry Fournierf67442e2020-11-28 20:41:07 +01008895 /* Check if the converter is already registered */
8896 trash = get_trash_chunk();
8897 chunk_printf(trash, "lua.%s", name);
8898 sc = find_sample_conv(trash->area, trash->data);
8899 if (sc != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +01008900 fcn = sc->private;
8901 if (fcn->function_ref[hlua_state_id] != -1) {
8902 ha_warning("Trying to register converter 'lua.%s' more than once. "
8903 "This will become a hard error in version 2.5.\n", name);
8904 }
8905 fcn->function_ref[hlua_state_id] = ref;
8906 return 0;
Thierry Fournierf67442e2020-11-28 20:41:07 +01008907 }
8908
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008909 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02008910 sck = calloc(1, sizeof(*sck) + sizeof(struct sample_conv) * 2);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008911 if (!sck)
Christopher Fauletaa224302021-04-12 14:08:21 +02008912 goto alloc_error;
Thierry Fournier62a22aa2020-11-28 21:06:35 +01008913 fcn = new_hlua_function();
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008914 if (!fcn)
Christopher Fauletaa224302021-04-12 14:08:21 +02008915 goto alloc_error;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008916
8917 /* Fill fcn. */
8918 fcn->name = strdup(name);
8919 if (!fcn->name)
Christopher Fauletaa224302021-04-12 14:08:21 +02008920 goto alloc_error;
Thierry Fournierc7492592020-11-28 23:57:24 +01008921 fcn->function_ref[hlua_state_id] = ref;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008922
8923 /* List head */
8924 sck->list.n = sck->list.p = NULL;
8925
8926 /* converter keyword. */
8927 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02008928 sck->kw[0].kw = calloc(1, len);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008929 if (!sck->kw[0].kw)
Christopher Fauletaa224302021-04-12 14:08:21 +02008930 goto alloc_error;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008931
8932 snprintf((char *)sck->kw[0].kw, len, "lua.%s", name);
8933 sck->kw[0].process = hlua_sample_conv_wrapper;
David Carlier0c437f42016-04-27 16:21:56 +01008934 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 +01008935 sck->kw[0].val_args = NULL;
8936 sck->kw[0].in_type = SMP_T_STR;
8937 sck->kw[0].out_type = SMP_T_STR;
8938 sck->kw[0].private = fcn;
8939
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008940 /* Register this new converter */
8941 sample_register_convs(sck);
8942
8943 return 0;
Christopher Fauletaa224302021-04-12 14:08:21 +02008944
8945 alloc_error:
8946 release_hlua_function(fcn);
8947 ha_free(&sck);
8948 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
8949 return 0; /* Never reached */
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008950}
8951
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08008952/* This function is an LUA binding used for registering
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008953 * "sample-fetch" functions. It expects a converter name used
8954 * in the haproxy configuration file, and an LUA function.
8955 */
8956__LJMP static int hlua_register_fetches(lua_State *L)
8957{
8958 const char *name;
8959 int ref;
8960 int len;
8961 struct sample_fetch_kw_list *sfk;
Christopher Faulet2567f182021-04-12 14:11:50 +02008962 struct hlua_function *fcn = NULL;
Thierry Fournierf67442e2020-11-28 20:41:07 +01008963 struct sample_fetch *sf;
8964 struct buffer *trash;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008965
8966 MAY_LJMP(check_args(L, 2, "register_fetches"));
8967
8968 /* First argument : sample-fetch name. */
8969 name = MAY_LJMP(luaL_checkstring(L, 1));
8970
8971 /* Second argument : lua function. */
8972 ref = MAY_LJMP(hlua_checkfunction(L, 2));
8973
Thierry Fournierf67442e2020-11-28 20:41:07 +01008974 /* Check if the sample-fetch is already registered */
8975 trash = get_trash_chunk();
8976 chunk_printf(trash, "lua.%s", name);
8977 sf = find_sample_fetch(trash->area, trash->data);
8978 if (sf != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +01008979 fcn = sf->private;
8980 if (fcn->function_ref[hlua_state_id] != -1) {
8981 ha_warning("Trying to register sample-fetch 'lua.%s' more than once. "
8982 "This will become a hard error in version 2.5.\n", name);
8983 }
8984 fcn->function_ref[hlua_state_id] = ref;
8985 return 0;
Thierry Fournierf67442e2020-11-28 20:41:07 +01008986 }
8987
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008988 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02008989 sfk = calloc(1, sizeof(*sfk) + sizeof(struct sample_fetch) * 2);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008990 if (!sfk)
Christopher Faulet2567f182021-04-12 14:11:50 +02008991 goto alloc_error;
Thierry Fournier62a22aa2020-11-28 21:06:35 +01008992 fcn = new_hlua_function();
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008993 if (!fcn)
Christopher Faulet2567f182021-04-12 14:11:50 +02008994 goto alloc_error;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008995
8996 /* Fill fcn. */
8997 fcn->name = strdup(name);
8998 if (!fcn->name)
Christopher Faulet2567f182021-04-12 14:11:50 +02008999 goto alloc_error;
Thierry Fournierc7492592020-11-28 23:57:24 +01009000 fcn->function_ref[hlua_state_id] = ref;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009001
9002 /* List head */
9003 sfk->list.n = sfk->list.p = NULL;
9004
9005 /* sample-fetch keyword. */
9006 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02009007 sfk->kw[0].kw = calloc(1, len);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009008 if (!sfk->kw[0].kw)
Christopher Faulet2567f182021-04-12 14:11:50 +02009009 goto alloc_error;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009010
9011 snprintf((char *)sfk->kw[0].kw, len, "lua.%s", name);
9012 sfk->kw[0].process = hlua_sample_fetch_wrapper;
David Carlier0c437f42016-04-27 16:21:56 +01009013 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 +01009014 sfk->kw[0].val_args = NULL;
9015 sfk->kw[0].out_type = SMP_T_STR;
9016 sfk->kw[0].use = SMP_USE_HTTP_ANY;
9017 sfk->kw[0].val = 0;
9018 sfk->kw[0].private = fcn;
9019
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009020 /* Register this new fetch. */
9021 sample_register_fetches(sfk);
9022
9023 return 0;
Christopher Faulet2567f182021-04-12 14:11:50 +02009024
9025 alloc_error:
9026 release_hlua_function(fcn);
9027 ha_free(&sfk);
9028 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
9029 return 0; /* Never reached */
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009030}
9031
Christopher Faulet501465d2020-02-26 14:54:16 +01009032/* This function is a lua binding to set the wake_time.
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01009033 */
Christopher Faulet501465d2020-02-26 14:54:16 +01009034__LJMP static int hlua_set_wake_time(lua_State *L)
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01009035{
Thierry Fournier4234dbd2020-11-28 13:18:23 +01009036 struct hlua *hlua;
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01009037 unsigned int delay;
9038 unsigned int wakeup_ms;
9039
Thierry Fournier4234dbd2020-11-28 13:18:23 +01009040 /* Get hlua struct, or NULL if we execute from main lua state */
9041 hlua = hlua_gethlua(L);
9042 if (!hlua) {
9043 return 0;
9044 }
9045
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01009046 MAY_LJMP(check_args(L, 1, "wake_time"));
9047
9048 delay = MAY_LJMP(luaL_checkinteger(L, 1));
9049 wakeup_ms = tick_add(now_ms, delay);
9050 hlua->wake_time = wakeup_ms;
9051 return 0;
9052}
9053
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009054/* This function is a wrapper to execute each LUA function declared as an action
9055 * wrapper during the initialisation period. This function may return any
9056 * ACT_RET_* value. On error ACT_RET_CONT is returned and the action is
9057 * ignored. If the lua action yields, ACT_RET_YIELD is returned. On success, the
9058 * return value is the first element on the stack.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009059 */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009060static enum act_return hlua_action(struct act_rule *rule, struct proxy *px,
Willy Tarreau658b85b2015-09-27 10:00:49 +02009061 struct session *sess, struct stream *s, int flags)
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009062{
9063 char **arg;
Christopher Faulet8c9e6bb2021-08-06 16:29:41 +02009064 unsigned int hflags = HLUA_TXN_ACT_CTX;
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009065 int dir, act_ret = ACT_RET_CONT;
Thierry Fournierfd107a22016-02-19 19:57:23 +01009066 const char *error;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009067
9068 switch (rule->from) {
Christopher Fauletd8f0e072020-02-25 09:45:51 +01009069 case ACT_F_TCP_REQ_CNT: dir = SMP_OPT_DIR_REQ; break;
9070 case ACT_F_TCP_RES_CNT: dir = SMP_OPT_DIR_RES; break;
9071 case ACT_F_HTTP_REQ: dir = SMP_OPT_DIR_REQ; break;
9072 case ACT_F_HTTP_RES: dir = SMP_OPT_DIR_RES; break;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009073 default:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009074 SEND_ERR(px, "Lua: internal error while execute action.\n");
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009075 goto end;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009076 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009077
Willy Tarreau87b09662015-04-03 00:22:06 +02009078 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01009079 * Lua context can be not initialized. This behavior
9080 * permits to save performances because a systematic
9081 * Lua initialization cause 5% performances loss.
9082 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009083 if (!s->hlua) {
Christopher Faulet1e8433f2021-03-24 15:03:01 +01009084 struct hlua *hlua;
9085
9086 hlua = pool_alloc(pool_head_hlua);
9087 if (!hlua) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009088 SEND_ERR(px, "Lua action '%s': can't initialize Lua context.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009089 rule->arg.hlua_rule->fcn->name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009090 goto end;
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009091 }
Christopher Faulet1e8433f2021-03-24 15:03:01 +01009092 HLUA_INIT(hlua);
9093 s->hlua = hlua;
Thierry Fournierc7492592020-11-28 23:57:24 +01009094 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 +01009095 SEND_ERR(px, "Lua action '%s': can't initialize Lua context.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009096 rule->arg.hlua_rule->fcn->name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009097 goto end;
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009098 }
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01009099 }
9100
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009101 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009102 if (!HLUA_IS_RUNNING(s->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02009103
9104 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009105 if (!SET_SAFE_LJMP(s->hlua)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009106 if (lua_type(s->hlua->T, -1) == LUA_TSTRING)
9107 error = lua_tostring(s->hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +01009108 else
9109 error = "critical error";
9110 SEND_ERR(px, "Lua function '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009111 rule->arg.hlua_rule->fcn->name, error);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009112 goto end;
Thierry FOURNIERbabae282015-09-17 11:36:37 +02009113 }
9114
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009115 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009116 if (!lua_checkstack(s->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009117 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009118 rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009119 RESET_SAFE_LJMP(s->hlua);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009120 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009121 }
9122
9123 /* Restore the function in the stack. */
Thierry Fournierc7492592020-11-28 23:57:24 +01009124 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 +01009125
Willy Tarreau87b09662015-04-03 00:22:06 +02009126 /* Create and and push object stream in the stack. */
Christopher Fauletbfab2dd2019-07-26 15:09:53 +02009127 if (!hlua_txn_new(s->hlua->T, s, px, dir, hflags)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009128 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009129 rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009130 RESET_SAFE_LJMP(s->hlua);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009131 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009132 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009133 s->hlua->nargs = 1;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009134
9135 /* push keywords in the stack. */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009136 for (arg = rule->arg.hlua_rule->args; arg && *arg; arg++) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009137 if (!lua_checkstack(s->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009138 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009139 rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009140 RESET_SAFE_LJMP(s->hlua);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009141 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009142 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009143 lua_pushstring(s->hlua->T, *arg);
9144 s->hlua->nargs++;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009145 }
9146
Thierry FOURNIERbabae282015-09-17 11:36:37 +02009147 /* Now the execution is safe. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009148 RESET_SAFE_LJMP(s->hlua);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02009149
Thierry FOURNIERbd413492015-03-03 16:52:26 +01009150 /* We must initialize the execution timeouts. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009151 s->hlua->max_time = hlua_timeout_session;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009152 }
9153
9154 /* Execute the function. */
Christopher Faulet105ba6c2019-12-18 14:41:51 +01009155 switch (hlua_ctx_resume(s->hlua, !(flags & ACT_OPT_FINAL))) {
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009156 /* finished. */
9157 case HLUA_E_OK:
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009158 /* Catch the return value */
9159 if (lua_gettop(s->hlua->T) > 0)
9160 act_ret = lua_tointeger(s->hlua->T, -1);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009161
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01009162 /* Set timeout in the required channel. */
Christopher Faulet498c4832020-07-28 11:59:58 +02009163 if (act_ret == ACT_RET_YIELD) {
9164 if (flags & ACT_OPT_FINAL)
9165 goto err_yield;
9166
Christopher Faulet8f587ea2020-07-28 12:01:55 +02009167 if (dir == SMP_OPT_DIR_REQ)
9168 s->req.analyse_exp = tick_first((tick_is_expired(s->req.analyse_exp, now_ms) ? 0 : s->req.analyse_exp),
9169 s->hlua->wake_time);
9170 else
9171 s->res.analyse_exp = tick_first((tick_is_expired(s->res.analyse_exp, now_ms) ? 0 : s->res.analyse_exp),
9172 s->hlua->wake_time);
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01009173 }
9174 goto end;
9175
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009176 /* yield. */
9177 case HLUA_E_AGAIN:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01009178 /* Set timeout in the required channel. */
Christopher Faulet8f587ea2020-07-28 12:01:55 +02009179 if (dir == SMP_OPT_DIR_REQ)
9180 s->req.analyse_exp = tick_first((tick_is_expired(s->req.analyse_exp, now_ms) ? 0 : s->req.analyse_exp),
9181 s->hlua->wake_time);
9182 else
9183 s->res.analyse_exp = tick_first((tick_is_expired(s->res.analyse_exp, now_ms) ? 0 : s->res.analyse_exp),
9184 s->hlua->wake_time);
9185
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009186 /* Some actions can be wake up when a "write" event
9187 * is detected on a response channel. This is useful
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08009188 * only for actions targeted on the requests.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009189 */
Christopher Faulet51fa3582019-07-26 14:54:52 +02009190 if (HLUA_IS_WAKERESWR(s->hlua))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01009191 s->res.flags |= CF_WAKE_WRITE;
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009192 if (HLUA_IS_WAKEREQWR(s->hlua))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01009193 s->req.flags |= CF_WAKE_WRITE;
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009194 act_ret = ACT_RET_YIELD;
9195 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009196
9197 /* finished with error. */
9198 case HLUA_E_ERRMSG:
9199 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009200 SEND_ERR(px, "Lua function '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009201 rule->arg.hlua_rule->fcn->name, lua_tostring(s->hlua->T, -1));
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009202 lua_pop(s->hlua->T, 1);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009203 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009204
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009205 case HLUA_E_ETMOUT:
Thierry Fournierad5345f2020-11-29 02:05:57 +01009206 SEND_ERR(px, "Lua function '%s': execution timeout.\n", rule->arg.hlua_rule->fcn->name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009207 goto end;
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009208
9209 case HLUA_E_NOMEM:
Thierry Fournierad5345f2020-11-29 02:05:57 +01009210 SEND_ERR(px, "Lua function '%s': out of memory error.\n", rule->arg.hlua_rule->fcn->name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009211 goto end;
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009212
9213 case HLUA_E_YIELD:
Christopher Faulet498c4832020-07-28 11:59:58 +02009214 err_yield:
9215 act_ret = ACT_RET_CONT;
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009216 SEND_ERR(px, "Lua function '%s': aborting Lua processing on expired timeout.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009217 rule->arg.hlua_rule->fcn->name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009218 goto end;
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009219
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009220 case HLUA_E_ERR:
9221 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009222 SEND_ERR(px, "Lua function '%s' return an unknown error.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009223 rule->arg.hlua_rule->fcn->name);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009224
9225 default:
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009226 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009227 }
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009228
9229 end:
Christopher Faulet2361fd92020-07-30 10:40:58 +02009230 if (act_ret != ACT_RET_YIELD && s->hlua)
Christopher Faulet8f587ea2020-07-28 12:01:55 +02009231 s->hlua->wake_time = TICK_ETERNITY;
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009232 return act_ret;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009233}
9234
Willy Tarreau144f84a2021-03-02 16:09:26 +01009235struct task *hlua_applet_wakeup(struct task *t, void *context, unsigned int state)
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009236{
Olivier Houchard9f6af332018-05-25 14:04:04 +02009237 struct appctx *ctx = context;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009238
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009239 appctx_wakeup(ctx);
Willy Tarreaud9587412017-08-23 16:07:33 +02009240 t->expire = TICK_ETERNITY;
Willy Tarreaud1aa41f2017-07-21 16:41:56 +02009241 return t;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009242}
9243
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009244static int hlua_applet_tcp_init(struct appctx *ctx)
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009245{
Willy Tarreaue23f33b2022-05-06 14:07:13 +02009246 struct hlua_tcp_ctx *tcp_ctx = applet_reserve_svcctx(ctx, sizeof(*tcp_ctx));
Willy Tarreauc12b3212022-05-27 11:08:15 +02009247 struct stconn *sc = appctx_sc(ctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02009248 struct stream *strm = __sc_strm(sc);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009249 struct hlua *hlua;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009250 struct task *task;
9251 char **arg;
Thierry Fournierfd107a22016-02-19 19:57:23 +01009252 const char *error;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009253
Willy Tarreaubafbe012017-11-24 17:34:44 +01009254 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009255 if (!hlua) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009256 SEND_ERR(strm->be, "Lua applet tcp '%s': out of memory.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009257 ctx->rule->arg.hlua_rule->fcn->name);
Christopher Fauletc9929382022-05-12 11:52:27 +02009258 return -1;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009259 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009260 HLUA_INIT(hlua);
Willy Tarreaue23f33b2022-05-06 14:07:13 +02009261 tcp_ctx->hlua = hlua;
9262 tcp_ctx->flags = 0;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009263
9264 /* Create task used by signal to wakeup applets. */
Willy Tarreaubeeabf52021-10-01 18:23:30 +02009265 task = task_new_here();
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009266 if (!task) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009267 SEND_ERR(strm->be, "Lua applet tcp '%s': out of memory.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009268 ctx->rule->arg.hlua_rule->fcn->name);
Christopher Fauletc9929382022-05-12 11:52:27 +02009269 return -1;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009270 }
9271 task->nice = 0;
9272 task->context = ctx;
9273 task->process = hlua_applet_wakeup;
Willy Tarreaue23f33b2022-05-06 14:07:13 +02009274 tcp_ctx->task = task;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009275
9276 /* In the execution wrappers linked with a stream, the
9277 * Lua context can be not initialized. This behavior
9278 * permits to save performances because a systematic
9279 * Lua initialization cause 5% performances loss.
9280 */
Thierry Fournierc7492592020-11-28 23:57:24 +01009281 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 +01009282 SEND_ERR(strm->be, "Lua applet tcp '%s': can't initialize Lua context.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009283 ctx->rule->arg.hlua_rule->fcn->name);
Christopher Fauletc9929382022-05-12 11:52:27 +02009284 return -1;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009285 }
9286
9287 /* Set timeout according with the applet configuration. */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02009288 hlua->max_time = ctx->applet->timeout;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009289
9290 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009291 if (!SET_SAFE_LJMP(hlua)) {
Thierry Fournierfd107a22016-02-19 19:57:23 +01009292 if (lua_type(hlua->T, -1) == LUA_TSTRING)
9293 error = lua_tostring(hlua->T, -1);
9294 else
9295 error = "critical error";
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009296 SEND_ERR(strm->be, "Lua applet tcp '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009297 ctx->rule->arg.hlua_rule->fcn->name, error);
Christopher Fauletc9929382022-05-12 11:52:27 +02009298 return -1;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009299 }
9300
9301 /* Check stack available size. */
9302 if (!lua_checkstack(hlua->T, 1)) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009303 SEND_ERR(strm->be, "Lua applet tcp '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009304 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009305 RESET_SAFE_LJMP(hlua);
Christopher Fauletc9929382022-05-12 11:52:27 +02009306 return -1;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009307 }
9308
9309 /* Restore the function in the stack. */
Thierry Fournierc7492592020-11-28 23:57:24 +01009310 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ctx->rule->arg.hlua_rule->fcn->function_ref[hlua->state_id]);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009311
9312 /* Create and and push object stream in the stack. */
9313 if (!hlua_applet_tcp_new(hlua->T, ctx)) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009314 SEND_ERR(strm->be, "Lua applet tcp '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009315 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009316 RESET_SAFE_LJMP(hlua);
Christopher Fauletc9929382022-05-12 11:52:27 +02009317 return -1;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009318 }
9319 hlua->nargs = 1;
9320
9321 /* push keywords in the stack. */
9322 for (arg = ctx->rule->arg.hlua_rule->args; arg && *arg; arg++) {
9323 if (!lua_checkstack(hlua->T, 1)) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009324 SEND_ERR(strm->be, "Lua applet tcp '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009325 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009326 RESET_SAFE_LJMP(hlua);
Christopher Fauletc9929382022-05-12 11:52:27 +02009327 return -1;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009328 }
9329 lua_pushstring(hlua->T, *arg);
9330 hlua->nargs++;
9331 }
9332
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009333 RESET_SAFE_LJMP(hlua);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009334
9335 /* Wakeup the applet ASAP. */
Willy Tarreau90e8b452022-05-25 18:21:43 +02009336 applet_need_more_data(ctx);
Willy Tarreau4164eb92022-05-25 15:42:03 +02009337 applet_have_more_data(ctx);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009338
Christopher Fauletc9929382022-05-12 11:52:27 +02009339 return 0;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009340}
9341
Willy Tarreau60409db2019-08-21 14:14:50 +02009342void hlua_applet_tcp_fct(struct appctx *ctx)
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009343{
Willy Tarreaue23f33b2022-05-06 14:07:13 +02009344 struct hlua_tcp_ctx *tcp_ctx = ctx->svcctx;
Willy Tarreauc12b3212022-05-27 11:08:15 +02009345 struct stconn *sc = appctx_sc(ctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02009346 struct stream *strm = __sc_strm(sc);
9347 struct channel *res = sc_ic(sc);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009348 struct act_rule *rule = ctx->rule;
9349 struct proxy *px = strm->be;
Willy Tarreaue23f33b2022-05-06 14:07:13 +02009350 struct hlua *hlua = tcp_ctx->hlua;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009351
9352 /* The applet execution is already done. */
Willy Tarreaue23f33b2022-05-06 14:07:13 +02009353 if (tcp_ctx->flags & APPLET_DONE) {
Olivier Houchard594c8c52018-08-28 14:41:31 +02009354 /* eat the whole request */
Willy Tarreau3e7be362022-05-27 10:35:27 +02009355 co_skip(sc_oc(sc), co_data(sc_oc(sc)));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009356 return;
Olivier Houchard594c8c52018-08-28 14:41:31 +02009357 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009358
9359 /* If the stream is disconnect or closed, ldo nothing. */
Willy Tarreau3e7be362022-05-27 10:35:27 +02009360 if (unlikely(sc->state == SC_ST_DIS || sc->state == SC_ST_CLO))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009361 return;
9362
9363 /* Execute the function. */
9364 switch (hlua_ctx_resume(hlua, 1)) {
9365 /* finished. */
9366 case HLUA_E_OK:
Willy Tarreaue23f33b2022-05-06 14:07:13 +02009367 tcp_ctx->flags |= APPLET_DONE;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009368
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009369 /* eat the whole request */
Willy Tarreau3e7be362022-05-27 10:35:27 +02009370 co_skip(sc_oc(sc), co_data(sc_oc(sc)));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009371 res->flags |= CF_READ_NULL;
Willy Tarreau3e7be362022-05-27 10:35:27 +02009372 sc_shutr(sc);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009373 return;
9374
9375 /* yield. */
9376 case HLUA_E_AGAIN:
Thierry Fournier0164f202016-02-20 17:47:43 +01009377 if (hlua->wake_time != TICK_ETERNITY)
Willy Tarreaue23f33b2022-05-06 14:07:13 +02009378 task_schedule(tcp_ctx->task, hlua->wake_time);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009379 return;
9380
9381 /* finished with error. */
9382 case HLUA_E_ERRMSG:
9383 /* Display log. */
9384 SEND_ERR(px, "Lua applet tcp '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009385 rule->arg.hlua_rule->fcn->name, lua_tostring(hlua->T, -1));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009386 lua_pop(hlua->T, 1);
9387 goto error;
9388
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009389 case HLUA_E_ETMOUT:
9390 SEND_ERR(px, "Lua applet tcp '%s': execution timeout.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009391 rule->arg.hlua_rule->fcn->name);
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009392 goto error;
9393
9394 case HLUA_E_NOMEM:
9395 SEND_ERR(px, "Lua applet tcp '%s': out of memory error.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009396 rule->arg.hlua_rule->fcn->name);
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009397 goto error;
9398
9399 case HLUA_E_YIELD: /* unexpected */
9400 SEND_ERR(px, "Lua applet tcp '%s': yield not allowed.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009401 rule->arg.hlua_rule->fcn->name);
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009402 goto error;
9403
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009404 case HLUA_E_ERR:
9405 /* Display log. */
9406 SEND_ERR(px, "Lua applet tcp '%s' return an unknown error.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009407 rule->arg.hlua_rule->fcn->name);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009408 goto error;
9409
9410 default:
9411 goto error;
9412 }
9413
9414error:
9415
9416 /* For all other cases, just close the stream. */
Willy Tarreau3e7be362022-05-27 10:35:27 +02009417 sc_shutw(sc);
9418 sc_shutr(sc);
Willy Tarreaue23f33b2022-05-06 14:07:13 +02009419 tcp_ctx->flags |= APPLET_DONE;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009420}
9421
9422static void hlua_applet_tcp_release(struct appctx *ctx)
9423{
Willy Tarreaue23f33b2022-05-06 14:07:13 +02009424 struct hlua_tcp_ctx *tcp_ctx = ctx->svcctx;
9425
9426 task_destroy(tcp_ctx->task);
9427 tcp_ctx->task = NULL;
9428 hlua_ctx_destroy(tcp_ctx->hlua);
9429 tcp_ctx->hlua = NULL;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009430}
9431
Christopher Fauletc9929382022-05-12 11:52:27 +02009432/* The function returns 0 if the initialisation is complete or -1 if
9433 * an errors occurs. It also reserves the appctx for an hlua_http_ctx.
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009434 */
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009435static int hlua_applet_http_init(struct appctx *ctx)
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009436{
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009437 struct hlua_http_ctx *http_ctx = applet_reserve_svcctx(ctx, sizeof(*http_ctx));
Willy Tarreauc12b3212022-05-27 11:08:15 +02009438 struct stconn *sc = appctx_sc(ctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02009439 struct stream *strm = __sc_strm(sc);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009440 struct http_txn *txn;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009441 struct hlua *hlua;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009442 char **arg;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009443 struct task *task;
Thierry Fournierfd107a22016-02-19 19:57:23 +01009444 const char *error;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009445
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009446 txn = strm->txn;
Willy Tarreaubafbe012017-11-24 17:34:44 +01009447 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009448 if (!hlua) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009449 SEND_ERR(strm->be, "Lua applet http '%s': out of memory.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009450 ctx->rule->arg.hlua_rule->fcn->name);
Christopher Fauletc9929382022-05-12 11:52:27 +02009451 return -1;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009452 }
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009453 HLUA_INIT(hlua);
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009454 http_ctx->hlua = hlua;
9455 http_ctx->left_bytes = -1;
9456 http_ctx->flags = 0;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009457
Thierry FOURNIERd93ea2b2015-12-20 19:14:52 +01009458 if (txn->req.flags & HTTP_MSGF_VER_11)
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009459 http_ctx->flags |= APPLET_HTTP11;
Thierry FOURNIERd93ea2b2015-12-20 19:14:52 +01009460
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009461 /* Create task used by signal to wakeup applets. */
Willy Tarreaubeeabf52021-10-01 18:23:30 +02009462 task = task_new_here();
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009463 if (!task) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009464 SEND_ERR(strm->be, "Lua applet http '%s': out of memory.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009465 ctx->rule->arg.hlua_rule->fcn->name);
Christopher Fauletc9929382022-05-12 11:52:27 +02009466 return -1;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009467 }
9468 task->nice = 0;
9469 task->context = ctx;
9470 task->process = hlua_applet_wakeup;
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009471 http_ctx->task = task;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009472
9473 /* In the execution wrappers linked with a stream, the
9474 * Lua context can be not initialized. This behavior
9475 * permits to save performances because a systematic
9476 * Lua initialization cause 5% performances loss.
9477 */
Thierry Fournierc7492592020-11-28 23:57:24 +01009478 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 +01009479 SEND_ERR(strm->be, "Lua applet http '%s': can't initialize Lua context.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009480 ctx->rule->arg.hlua_rule->fcn->name);
Christopher Fauletc9929382022-05-12 11:52:27 +02009481 return -1;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009482 }
9483
9484 /* Set timeout according with the applet configuration. */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02009485 hlua->max_time = ctx->applet->timeout;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009486
9487 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009488 if (!SET_SAFE_LJMP(hlua)) {
Thierry Fournierfd107a22016-02-19 19:57:23 +01009489 if (lua_type(hlua->T, -1) == LUA_TSTRING)
9490 error = lua_tostring(hlua->T, -1);
9491 else
9492 error = "critical error";
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009493 SEND_ERR(strm->be, "Lua applet http '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009494 ctx->rule->arg.hlua_rule->fcn->name, error);
Christopher Fauletc9929382022-05-12 11:52:27 +02009495 return -1;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009496 }
9497
9498 /* Check stack available size. */
9499 if (!lua_checkstack(hlua->T, 1)) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009500 SEND_ERR(strm->be, "Lua applet http '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009501 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009502 RESET_SAFE_LJMP(hlua);
Christopher Fauletc9929382022-05-12 11:52:27 +02009503 return -1;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009504 }
9505
9506 /* Restore the function in the stack. */
Thierry Fournierc7492592020-11-28 23:57:24 +01009507 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ctx->rule->arg.hlua_rule->fcn->function_ref[hlua->state_id]);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009508
9509 /* Create and and push object stream in the stack. */
9510 if (!hlua_applet_http_new(hlua->T, ctx)) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009511 SEND_ERR(strm->be, "Lua applet http '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009512 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009513 RESET_SAFE_LJMP(hlua);
Christopher Fauletc9929382022-05-12 11:52:27 +02009514 return -1;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009515 }
9516 hlua->nargs = 1;
9517
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009518 /* push keywords in the stack. */
9519 for (arg = ctx->rule->arg.hlua_rule->args; arg && *arg; arg++) {
9520 if (!lua_checkstack(hlua->T, 1)) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009521 SEND_ERR(strm->be, "Lua applet http '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009522 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009523 RESET_SAFE_LJMP(hlua);
Christopher Fauletc9929382022-05-12 11:52:27 +02009524 return -1;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009525 }
9526 lua_pushstring(hlua->T, *arg);
9527 hlua->nargs++;
9528 }
9529
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009530 RESET_SAFE_LJMP(hlua);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009531
9532 /* Wakeup the applet when data is ready for read. */
Willy Tarreau90e8b452022-05-25 18:21:43 +02009533 applet_need_more_data(ctx);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009534
Christopher Fauletc9929382022-05-12 11:52:27 +02009535 return 0;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009536}
9537
Willy Tarreau60409db2019-08-21 14:14:50 +02009538void hlua_applet_http_fct(struct appctx *ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009539{
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009540 struct hlua_http_ctx *http_ctx = ctx->svcctx;
Willy Tarreauc12b3212022-05-27 11:08:15 +02009541 struct stconn *sc = appctx_sc(ctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02009542 struct stream *strm = __sc_strm(sc);
9543 struct channel *req = sc_oc(sc);
9544 struct channel *res = sc_ic(sc);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009545 struct act_rule *rule = ctx->rule;
9546 struct proxy *px = strm->be;
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009547 struct hlua *hlua = http_ctx->hlua;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009548 struct htx *req_htx, *res_htx;
9549
9550 res_htx = htx_from_buf(&res->buf);
9551
9552 /* If the stream is disconnect or closed, ldo nothing. */
Willy Tarreau3e7be362022-05-27 10:35:27 +02009553 if (unlikely(sc->state == SC_ST_DIS || sc->state == SC_ST_CLO))
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009554 goto out;
9555
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05009556 /* Check if the input buffer is available. */
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009557 if (!b_size(&res->buf)) {
Willy Tarreau3e7be362022-05-27 10:35:27 +02009558 sc_need_room(sc);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009559 goto out;
9560 }
9561 /* check that the output is not closed */
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01009562 if (res->flags & (CF_SHUTW|CF_SHUTW_NOW|CF_SHUTR))
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009563 http_ctx->flags |= APPLET_DONE;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009564
9565 /* Set the currently running flag. */
9566 if (!HLUA_IS_RUNNING(hlua) &&
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009567 !(http_ctx->flags & APPLET_DONE)) {
Christopher Fauletbd878d22021-04-28 10:50:21 +02009568 if (!co_data(req)) {
Willy Tarreau90e8b452022-05-25 18:21:43 +02009569 applet_need_more_data(ctx);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009570 goto out;
9571 }
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009572 }
9573
9574 /* Executes The applet if it is not done. */
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009575 if (!(http_ctx->flags & APPLET_DONE)) {
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009576
9577 /* Execute the function. */
9578 switch (hlua_ctx_resume(hlua, 1)) {
9579 /* finished. */
9580 case HLUA_E_OK:
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009581 http_ctx->flags |= APPLET_DONE;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009582 break;
9583
9584 /* yield. */
9585 case HLUA_E_AGAIN:
9586 if (hlua->wake_time != TICK_ETERNITY)
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009587 task_schedule(http_ctx->task, hlua->wake_time);
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01009588 goto out;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009589
9590 /* finished with error. */
9591 case HLUA_E_ERRMSG:
9592 /* Display log. */
9593 SEND_ERR(px, "Lua applet http '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009594 rule->arg.hlua_rule->fcn->name, lua_tostring(hlua->T, -1));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009595 lua_pop(hlua->T, 1);
9596 goto error;
9597
9598 case HLUA_E_ETMOUT:
9599 SEND_ERR(px, "Lua applet http '%s': execution timeout.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009600 rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009601 goto error;
9602
9603 case HLUA_E_NOMEM:
9604 SEND_ERR(px, "Lua applet http '%s': out of memory error.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009605 rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009606 goto error;
9607
9608 case HLUA_E_YIELD: /* unexpected */
9609 SEND_ERR(px, "Lua applet http '%s': yield not allowed.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009610 rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009611 goto error;
9612
9613 case HLUA_E_ERR:
9614 /* Display log. */
9615 SEND_ERR(px, "Lua applet http '%s' return an unknown error.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009616 rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009617 goto error;
9618
9619 default:
9620 goto error;
9621 }
9622 }
9623
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009624 if (http_ctx->flags & APPLET_DONE) {
9625 if (http_ctx->flags & APPLET_RSP_SENT)
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01009626 goto done;
9627
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009628 if (!(http_ctx->flags & APPLET_HDR_SENT))
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009629 goto error;
9630
Christopher Fauletf89af9c2022-04-07 10:07:18 +02009631 /* no more data are expected. If the response buffer is empty
9632 * for a chunked message, be sure to add something (EOT block in
9633 * this case) to have something to send. It is important to be
9634 * sure the EOM flags will be handled by the endpoint.
9635 */
9636 if (htx_is_empty(res_htx) && (strm->txn->rsp.flags & (HTTP_MSGF_XFER_LEN|HTTP_MSGF_CNT_LEN)) == HTTP_MSGF_XFER_LEN) {
9637 if (!htx_add_endof(res_htx, HTX_BLK_EOT)) {
Willy Tarreau3e7be362022-05-27 10:35:27 +02009638 sc_need_room(sc);
Christopher Fauletf89af9c2022-04-07 10:07:18 +02009639 goto out;
9640 }
9641 channel_add_input(res, 1);
9642 }
9643
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01009644 res_htx->flags |= HTX_FL_EOM;
Christopher Fauletd8d27082022-03-07 15:50:54 +01009645 res->flags |= CF_EOI;
Willy Tarreaud869e132022-05-17 18:05:31 +02009646 se_fl_set(ctx->sedesc, SE_FL_EOI);
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009647 strm->txn->status = http_ctx->status;
9648 http_ctx->flags |= APPLET_RSP_SENT;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009649 }
9650
9651 done:
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009652 if (http_ctx->flags & APPLET_DONE) {
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01009653 if (!(res->flags & CF_SHUTR)) {
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009654 res->flags |= CF_READ_NULL;
Willy Tarreau3e7be362022-05-27 10:35:27 +02009655 sc_shutr(sc);
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01009656 }
9657
9658 /* eat the whole request */
9659 if (co_data(req)) {
9660 req_htx = htx_from_buf(&req->buf);
9661 co_htx_skip(req, req_htx, co_data(req));
9662 htx_to_buf(req_htx, &req->buf);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009663 }
9664 }
9665
9666 out:
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009667 htx_to_buf(res_htx, &res->buf);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009668 return;
9669
9670 error:
9671
9672 /* If we are in HTTP mode, and we are not send any
9673 * data, return a 500 server error in best effort:
9674 * if there is no room available in the buffer,
9675 * just close the connection.
9676 */
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009677 if (!(http_ctx->flags & APPLET_HDR_SENT)) {
Christopher Fauletf7346382019-07-17 22:02:08 +02009678 struct buffer *err = &http_err_chunks[HTTP_ERR_500];
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009679
9680 channel_erase(res);
9681 res->buf.data = b_data(err);
9682 memcpy(res->buf.area, b_head(err), b_data(err));
9683 res_htx = htx_from_buf(&res->buf);
Christopher Fauletf6cce3f2019-02-27 21:20:09 +01009684 channel_add_input(res, res_htx->data);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009685 }
9686 if (!(strm->flags & SF_ERR_MASK))
9687 strm->flags |= SF_ERR_RESOURCE;
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009688 http_ctx->flags |= APPLET_DONE;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009689 goto done;
9690}
9691
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009692static void hlua_applet_http_release(struct appctx *ctx)
9693{
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009694 struct hlua_http_ctx *http_ctx = ctx->svcctx;
9695
9696 task_destroy(http_ctx->task);
9697 http_ctx->task = NULL;
9698 hlua_ctx_destroy(http_ctx->hlua);
9699 http_ctx->hlua = NULL;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009700}
9701
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009702/* global {tcp|http}-request parser. Return ACT_RET_PRS_OK in
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05009703 * success case, else return ACT_RET_PRS_ERR.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02009704 *
9705 * This function can fail with an abort() due to an Lua critical error.
9706 * We are in the configuration parsing process of HAProxy, this abort() is
9707 * tolerated.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009708 */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009709static enum act_parse_ret action_register_lua(const char **args, int *cur_arg, struct proxy *px,
9710 struct act_rule *rule, char **err)
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009711{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02009712 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009713 int i;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009714
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009715 /* Memory for the rule. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02009716 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009717 if (!rule->arg.hlua_rule) {
9718 memprintf(err, "out of memory error");
Christopher Faulet528526f2021-04-12 14:37:32 +02009719 goto error;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009720 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009721
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009722 /* Memory for arguments. */
Tim Duesterhuse52b6e52020-09-12 20:26:43 +02009723 rule->arg.hlua_rule->args = calloc(fcn->nargs + 1,
9724 sizeof(*rule->arg.hlua_rule->args));
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009725 if (!rule->arg.hlua_rule->args) {
9726 memprintf(err, "out of memory error");
Christopher Faulet528526f2021-04-12 14:37:32 +02009727 goto error;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009728 }
9729
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009730 /* Reference the Lua function and store the reference. */
Thierry Fournierad5345f2020-11-29 02:05:57 +01009731 rule->arg.hlua_rule->fcn = fcn;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009732
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009733 /* Expect some arguments */
9734 for (i = 0; i < fcn->nargs; i++) {
Thierry FOURNIER1725c2e2019-01-06 19:38:49 +01009735 if (*args[*cur_arg] == '\0') {
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009736 memprintf(err, "expect %d arguments", fcn->nargs);
Christopher Faulet528526f2021-04-12 14:37:32 +02009737 goto error;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009738 }
Thierry FOURNIER1725c2e2019-01-06 19:38:49 +01009739 rule->arg.hlua_rule->args[i] = strdup(args[*cur_arg]);
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009740 if (!rule->arg.hlua_rule->args[i]) {
9741 memprintf(err, "out of memory error");
Christopher Faulet528526f2021-04-12 14:37:32 +02009742 goto error;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009743 }
9744 (*cur_arg)++;
9745 }
9746 rule->arg.hlua_rule->args[i] = NULL;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009747
Thierry FOURNIER42148732015-09-02 17:17:33 +02009748 rule->action = ACT_CUSTOM;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009749 rule->action_ptr = hlua_action;
Thierry FOURNIERafa80492015-08-19 09:04:15 +02009750 return ACT_RET_PRS_OK;
Christopher Faulet528526f2021-04-12 14:37:32 +02009751
9752 error:
9753 if (rule->arg.hlua_rule) {
9754 if (rule->arg.hlua_rule->args) {
9755 for (i = 0; i < fcn->nargs; i++)
9756 ha_free(&rule->arg.hlua_rule->args[i]);
9757 ha_free(&rule->arg.hlua_rule->args);
9758 }
9759 ha_free(&rule->arg.hlua_rule);
9760 }
9761 return ACT_RET_PRS_ERR;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009762}
9763
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009764static enum act_parse_ret action_register_service_http(const char **args, int *cur_arg, struct proxy *px,
9765 struct act_rule *rule, char **err)
9766{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02009767 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009768
Thierry FOURNIER718e2a72015-12-20 20:13:14 +01009769 /* HTTP applets are forbidden in tcp-request rules.
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05009770 * HTTP applet request requires everything initialized by
Thierry FOURNIER718e2a72015-12-20 20:13:14 +01009771 * "http_process_request" (analyzer flag AN_REQ_HTTP_INNER).
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05009772 * The applet will be immediately initialized, but its before
Thierry FOURNIER718e2a72015-12-20 20:13:14 +01009773 * the call of this analyzer.
9774 */
9775 if (rule->from != ACT_F_HTTP_REQ) {
9776 memprintf(err, "HTTP applets are forbidden from 'tcp-request' rulesets");
9777 return ACT_RET_PRS_ERR;
9778 }
9779
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009780 /* Memory for the rule. */
9781 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
9782 if (!rule->arg.hlua_rule) {
9783 memprintf(err, "out of memory error");
9784 return ACT_RET_PRS_ERR;
9785 }
9786
9787 /* Reference the Lua function and store the reference. */
Thierry Fournierad5345f2020-11-29 02:05:57 +01009788 rule->arg.hlua_rule->fcn = fcn;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009789
9790 /* TODO: later accept arguments. */
9791 rule->arg.hlua_rule->args = NULL;
9792
9793 /* Add applet pointer in the rule. */
9794 rule->applet.obj_type = OBJ_TYPE_APPLET;
9795 rule->applet.name = fcn->name;
9796 rule->applet.init = hlua_applet_http_init;
9797 rule->applet.fct = hlua_applet_http_fct;
9798 rule->applet.release = hlua_applet_http_release;
9799 rule->applet.timeout = hlua_timeout_applet;
9800
9801 return ACT_RET_PRS_OK;
9802}
9803
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009804/* This function is an LUA binding used for registering
9805 * "sample-conv" functions. It expects a converter name used
9806 * in the haproxy configuration file, and an LUA function.
9807 */
9808__LJMP static int hlua_register_action(lua_State *L)
9809{
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009810 struct action_kw_list *akl = NULL;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009811 const char *name;
9812 int ref;
9813 int len;
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009814 struct hlua_function *fcn = NULL;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009815 int nargs;
Thierry Fournierf67442e2020-11-28 20:41:07 +01009816 struct buffer *trash;
9817 struct action_kw *akw;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009818
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009819 /* Initialise the number of expected arguments at 0. */
9820 nargs = 0;
9821
9822 if (lua_gettop(L) < 3 || lua_gettop(L) > 4)
9823 WILL_LJMP(luaL_error(L, "'register_action' needs between 3 and 4 arguments"));
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009824
9825 /* First argument : converter name. */
9826 name = MAY_LJMP(luaL_checkstring(L, 1));
9827
9828 /* Second argument : environment. */
9829 if (lua_type(L, 2) != LUA_TTABLE)
9830 WILL_LJMP(luaL_error(L, "register_action: second argument must be a table of strings"));
9831
9832 /* Third argument : lua function. */
9833 ref = MAY_LJMP(hlua_checkfunction(L, 3));
9834
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08009835 /* Fourth argument : number of mandatory arguments expected on the configuration line. */
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009836 if (lua_gettop(L) >= 4)
9837 nargs = MAY_LJMP(luaL_checkinteger(L, 4));
9838
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08009839 /* browse the second argument as an array. */
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009840 lua_pushnil(L);
9841 while (lua_next(L, 2) != 0) {
9842 if (lua_type(L, -1) != LUA_TSTRING)
9843 WILL_LJMP(luaL_error(L, "register_action: second argument must be a table of strings"));
9844
Thierry Fournierf67442e2020-11-28 20:41:07 +01009845 /* Check if action exists */
9846 trash = get_trash_chunk();
9847 chunk_printf(trash, "lua.%s", name);
9848 if (strcmp(lua_tostring(L, -1), "tcp-req") == 0) {
9849 akw = tcp_req_cont_action(trash->area);
9850 } else if (strcmp(lua_tostring(L, -1), "tcp-res") == 0) {
9851 akw = tcp_res_cont_action(trash->area);
9852 } else if (strcmp(lua_tostring(L, -1), "http-req") == 0) {
9853 akw = action_http_req_custom(trash->area);
9854 } else if (strcmp(lua_tostring(L, -1), "http-res") == 0) {
9855 akw = action_http_res_custom(trash->area);
9856 } else {
9857 akw = NULL;
9858 }
9859 if (akw != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +01009860 fcn = akw->private;
9861 if (fcn->function_ref[hlua_state_id] != -1) {
9862 ha_warning("Trying to register action 'lua.%s' more than once. "
9863 "This will become a hard error in version 2.5.\n", name);
9864 }
9865 fcn->function_ref[hlua_state_id] = ref;
9866
9867 /* pop the environment string. */
9868 lua_pop(L, 1);
9869 continue;
Thierry Fournierf67442e2020-11-28 20:41:07 +01009870 }
9871
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009872 /* Check required environment. Only accepted "http" or "tcp". */
9873 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02009874 akl = calloc(1, sizeof(*akl) + sizeof(struct action_kw) * 2);
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009875 if (!akl)
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009876 goto alloc_error;;
Thierry Fournier62a22aa2020-11-28 21:06:35 +01009877 fcn = new_hlua_function();
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009878 if (!fcn)
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009879 goto alloc_error;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009880
9881 /* Fill fcn. */
9882 fcn->name = strdup(name);
9883 if (!fcn->name)
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009884 goto alloc_error;
Thierry Fournierc7492592020-11-28 23:57:24 +01009885 fcn->function_ref[hlua_state_id] = ref;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009886
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -07009887 /* Set the expected number of arguments. */
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009888 fcn->nargs = nargs;
9889
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009890 /* List head */
9891 akl->list.n = akl->list.p = NULL;
9892
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009893 /* action keyword. */
9894 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02009895 akl->kw[0].kw = calloc(1, len);
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009896 if (!akl->kw[0].kw)
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009897 goto alloc_error;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009898
9899 snprintf((char *)akl->kw[0].kw, len, "lua.%s", name);
9900
Amaury Denoyellee4a617c2021-05-06 15:33:09 +02009901 akl->kw[0].flags = 0;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009902 akl->kw[0].private = fcn;
9903 akl->kw[0].parse = action_register_lua;
9904
9905 /* select the action registering point. */
9906 if (strcmp(lua_tostring(L, -1), "tcp-req") == 0)
9907 tcp_req_cont_keywords_register(akl);
9908 else if (strcmp(lua_tostring(L, -1), "tcp-res") == 0)
9909 tcp_res_cont_keywords_register(akl);
9910 else if (strcmp(lua_tostring(L, -1), "http-req") == 0)
9911 http_req_keywords_register(akl);
9912 else if (strcmp(lua_tostring(L, -1), "http-res") == 0)
9913 http_res_keywords_register(akl);
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009914 else {
9915 release_hlua_function(fcn);
9916 if (akl)
9917 ha_free((char **)&(akl->kw[0].kw));
9918 ha_free(&akl);
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01009919 WILL_LJMP(luaL_error(L, "Lua action environment '%s' is unknown. "
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009920 "'tcp-req', 'tcp-res', 'http-req' or 'http-res' "
9921 "are expected.", lua_tostring(L, -1)));
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009922 }
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009923
9924 /* pop the environment string. */
9925 lua_pop(L, 1);
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009926
9927 /* reset for next loop */
9928 akl = NULL;
9929 fcn = NULL;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009930 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009931 return ACT_RET_PRS_OK;
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009932
9933 alloc_error:
9934 release_hlua_function(fcn);
9935 ha_free(&akl);
9936 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
9937 return 0; /* Never reached */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009938}
9939
9940static enum act_parse_ret action_register_service_tcp(const char **args, int *cur_arg, struct proxy *px,
9941 struct act_rule *rule, char **err)
9942{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02009943 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009944
Christopher Faulet280f85b2019-07-15 15:02:04 +02009945 if (px->mode == PR_MODE_HTTP) {
9946 memprintf(err, "Lua TCP services cannot be used on HTTP proxies");
Christopher Fauletafd8f102018-11-08 11:34:21 +01009947 return ACT_RET_PRS_ERR;
9948 }
9949
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009950 /* Memory for the rule. */
9951 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
9952 if (!rule->arg.hlua_rule) {
9953 memprintf(err, "out of memory error");
9954 return ACT_RET_PRS_ERR;
9955 }
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009956
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009957 /* Reference the Lua function and store the reference. */
Thierry Fournierad5345f2020-11-29 02:05:57 +01009958 rule->arg.hlua_rule->fcn = fcn;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009959
9960 /* TODO: later accept arguments. */
9961 rule->arg.hlua_rule->args = NULL;
9962
9963 /* Add applet pointer in the rule. */
9964 rule->applet.obj_type = OBJ_TYPE_APPLET;
9965 rule->applet.name = fcn->name;
9966 rule->applet.init = hlua_applet_tcp_init;
9967 rule->applet.fct = hlua_applet_tcp_fct;
9968 rule->applet.release = hlua_applet_tcp_release;
9969 rule->applet.timeout = hlua_timeout_applet;
9970
9971 return 0;
9972}
9973
9974/* This function is an LUA binding used for registering
9975 * "sample-conv" functions. It expects a converter name used
9976 * in the haproxy configuration file, and an LUA function.
9977 */
9978__LJMP static int hlua_register_service(lua_State *L)
9979{
9980 struct action_kw_list *akl;
9981 const char *name;
9982 const char *env;
9983 int ref;
9984 int len;
Christopher Faulet5c028d72021-04-12 15:11:44 +02009985 struct hlua_function *fcn = NULL;
Thierry Fournierf67442e2020-11-28 20:41:07 +01009986 struct buffer *trash;
9987 struct action_kw *akw;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009988
9989 MAY_LJMP(check_args(L, 3, "register_service"));
9990
9991 /* First argument : converter name. */
9992 name = MAY_LJMP(luaL_checkstring(L, 1));
9993
9994 /* Second argument : environment. */
9995 env = MAY_LJMP(luaL_checkstring(L, 2));
9996
9997 /* Third argument : lua function. */
9998 ref = MAY_LJMP(hlua_checkfunction(L, 3));
9999
Thierry Fournierf67442e2020-11-28 20:41:07 +010010000 /* Check for service already registered */
10001 trash = get_trash_chunk();
10002 chunk_printf(trash, "lua.%s", name);
10003 akw = service_find(trash->area);
10004 if (akw != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +010010005 fcn = akw->private;
10006 if (fcn->function_ref[hlua_state_id] != -1) {
10007 ha_warning("Trying to register service 'lua.%s' more than once. "
10008 "This will become a hard error in version 2.5.\n", name);
10009 }
10010 fcn->function_ref[hlua_state_id] = ref;
10011 return 0;
Thierry Fournierf67442e2020-11-28 20:41:07 +010010012 }
10013
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010014 /* Allocate and fill the sample fetch keyword struct. */
10015 akl = calloc(1, sizeof(*akl) + sizeof(struct action_kw) * 2);
10016 if (!akl)
Christopher Faulet5c028d72021-04-12 15:11:44 +020010017 goto alloc_error;
Thierry Fournier62a22aa2020-11-28 21:06:35 +010010018 fcn = new_hlua_function();
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010019 if (!fcn)
Christopher Faulet5c028d72021-04-12 15:11:44 +020010020 goto alloc_error;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010021
10022 /* Fill fcn. */
10023 len = strlen("<lua.>") + strlen(name) + 1;
10024 fcn->name = calloc(1, len);
10025 if (!fcn->name)
Christopher Faulet5c028d72021-04-12 15:11:44 +020010026 goto alloc_error;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010027 snprintf((char *)fcn->name, len, "<lua.%s>", name);
Thierry Fournierc7492592020-11-28 23:57:24 +010010028 fcn->function_ref[hlua_state_id] = ref;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010029
10030 /* List head */
10031 akl->list.n = akl->list.p = NULL;
10032
10033 /* converter keyword. */
10034 len = strlen("lua.") + strlen(name) + 1;
10035 akl->kw[0].kw = calloc(1, len);
10036 if (!akl->kw[0].kw)
Christopher Faulet5c028d72021-04-12 15:11:44 +020010037 goto alloc_error;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010038
10039 snprintf((char *)akl->kw[0].kw, len, "lua.%s", name);
10040
Thierry FOURNIER / OZON.IO02564fd2016-11-12 11:07:05 +010010041 /* Check required environment. Only accepted "http" or "tcp". */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010042 if (strcmp(env, "tcp") == 0)
10043 akl->kw[0].parse = action_register_service_tcp;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010044 else if (strcmp(env, "http") == 0)
10045 akl->kw[0].parse = action_register_service_http;
Christopher Faulet5c028d72021-04-12 15:11:44 +020010046 else {
10047 release_hlua_function(fcn);
10048 if (akl)
10049 ha_free((char **)&(akl->kw[0].kw));
10050 ha_free(&akl);
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +010010051 WILL_LJMP(luaL_error(L, "Lua service environment '%s' is unknown. "
Eric Salamafe7456f2017-12-21 14:30:07 +010010052 "'tcp' or 'http' are expected.", env));
Christopher Faulet5c028d72021-04-12 15:11:44 +020010053 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010054
Amaury Denoyellee4a617c2021-05-06 15:33:09 +020010055 akl->kw[0].flags = 0;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010056 akl->kw[0].private = fcn;
10057
10058 /* End of array. */
10059 memset(&akl->kw[1], 0, sizeof(*akl->kw));
10060
10061 /* Register this new converter */
10062 service_keywords_register(akl);
10063
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010064 return 0;
Christopher Faulet5c028d72021-04-12 15:11:44 +020010065
10066 alloc_error:
10067 release_hlua_function(fcn);
10068 ha_free(&akl);
10069 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
10070 return 0; /* Never reached */
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010071}
10072
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010073/* This function initialises Lua cli handler. It copies the
10074 * arguments in the Lua stack and create channel IO objects.
10075 */
Aurélien Nephtaliabbf6072018-04-18 13:26:46 +020010076static int hlua_cli_parse_fct(char **args, char *payload, struct appctx *appctx, void *private)
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010077{
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010078 struct hlua_cli_ctx *ctx = applet_reserve_svcctx(appctx, sizeof(*ctx));
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010079 struct hlua *hlua;
10080 struct hlua_function *fcn;
10081 int i;
10082 const char *error;
10083
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010084 fcn = private;
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010085 ctx->fcn = private;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +010010086
Willy Tarreaubafbe012017-11-24 17:34:44 +010010087 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +010010088 if (!hlua) {
10089 SEND_ERR(NULL, "Lua cli '%s': out of memory.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +010010090 return 1;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +010010091 }
10092 HLUA_INIT(hlua);
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010093 ctx->hlua = hlua;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010094
10095 /* Create task used by signal to wakeup applets.
Ilya Shipitsind4259502020-04-08 01:07:56 +050010096 * We use the same wakeup function than the Lua applet_tcp and
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010097 * applet_http. It is absolutely compatible.
10098 */
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010099 ctx->task = task_new_here();
10100 if (!ctx->task) {
Thierry FOURNIERffbf5692016-12-16 11:14:06 +010010101 SEND_ERR(NULL, "Lua cli '%s': out of memory.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +010010102 goto error;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010103 }
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010104 ctx->task->nice = 0;
10105 ctx->task->context = appctx;
10106 ctx->task->process = hlua_applet_wakeup;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010107
10108 /* Initialises the Lua context */
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010109 if (!hlua_ctx_init(hlua, fcn_ref_to_stack_id(fcn), ctx->task, 0)) {
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010110 SEND_ERR(NULL, "Lua cli '%s': can't initialize Lua context.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +010010111 goto error;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010112 }
10113
10114 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010115 if (!SET_SAFE_LJMP(hlua)) {
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010116 if (lua_type(hlua->T, -1) == LUA_TSTRING)
10117 error = lua_tostring(hlua->T, -1);
10118 else
10119 error = "critical error";
10120 SEND_ERR(NULL, "Lua cli '%s': %s.\n", fcn->name, error);
10121 goto error;
10122 }
10123
10124 /* Check stack available size. */
10125 if (!lua_checkstack(hlua->T, 2)) {
10126 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
10127 goto error;
10128 }
10129
10130 /* Restore the function in the stack. */
Thierry Fournierc7492592020-11-28 23:57:24 +010010131 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, fcn->function_ref[hlua->state_id]);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010132
10133 /* Once the arguments parsed, the CLI is like an AppletTCP,
10134 * so push AppletTCP in the stack.
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010135 */
10136 if (!hlua_applet_tcp_new(hlua->T, appctx)) {
10137 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
10138 goto error;
10139 }
10140 hlua->nargs = 1;
10141
10142 /* push keywords in the stack. */
10143 for (i = 0; *args[i]; i++) {
10144 /* Check stack available size. */
10145 if (!lua_checkstack(hlua->T, 1)) {
10146 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
10147 goto error;
10148 }
10149 lua_pushstring(hlua->T, args[i]);
10150 hlua->nargs++;
10151 }
10152
10153 /* We must initialize the execution timeouts. */
10154 hlua->max_time = hlua_timeout_session;
10155
10156 /* At this point the execution is safe. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010157 RESET_SAFE_LJMP(hlua);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010158
10159 /* It's ok */
10160 return 0;
10161
10162 /* It's not ok. */
10163error:
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010164 RESET_SAFE_LJMP(hlua);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010165 hlua_ctx_destroy(hlua);
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010166 ctx->hlua = NULL;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010167 return 1;
10168}
10169
10170static int hlua_cli_io_handler_fct(struct appctx *appctx)
10171{
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010172 struct hlua_cli_ctx *ctx = appctx->svcctx;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010173 struct hlua *hlua;
Willy Tarreau475e4632022-05-27 10:26:46 +020010174 struct stconn *sc;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010175 struct hlua_function *fcn;
10176
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010177 hlua = ctx->hlua;
Willy Tarreauc12b3212022-05-27 11:08:15 +020010178 sc = appctx_sc(appctx);
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010179 fcn = ctx->fcn;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010180
10181 /* If the stream is disconnect or closed, ldo nothing. */
Willy Tarreau475e4632022-05-27 10:26:46 +020010182 if (unlikely(sc->state == SC_ST_DIS || sc->state == SC_ST_CLO))
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010183 return 1;
10184
10185 /* Execute the function. */
10186 switch (hlua_ctx_resume(hlua, 1)) {
10187
10188 /* finished. */
10189 case HLUA_E_OK:
10190 return 1;
10191
10192 /* yield. */
10193 case HLUA_E_AGAIN:
10194 /* We want write. */
10195 if (HLUA_IS_WAKERESWR(hlua))
Willy Tarreau475e4632022-05-27 10:26:46 +020010196 sc_need_room(sc);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010197 /* Set the timeout. */
10198 if (hlua->wake_time != TICK_ETERNITY)
10199 task_schedule(hlua->task, hlua->wake_time);
10200 return 0;
10201
10202 /* finished with error. */
10203 case HLUA_E_ERRMSG:
10204 /* Display log. */
10205 SEND_ERR(NULL, "Lua cli '%s': %s.\n",
10206 fcn->name, lua_tostring(hlua->T, -1));
10207 lua_pop(hlua->T, 1);
10208 return 1;
10209
Thierry Fournierd5b073c2018-05-21 19:42:47 +020010210 case HLUA_E_ETMOUT:
10211 SEND_ERR(NULL, "Lua converter '%s': execution timeout.\n",
10212 fcn->name);
10213 return 1;
10214
10215 case HLUA_E_NOMEM:
10216 SEND_ERR(NULL, "Lua converter '%s': out of memory error.\n",
10217 fcn->name);
10218 return 1;
10219
10220 case HLUA_E_YIELD: /* unexpected */
10221 SEND_ERR(NULL, "Lua converter '%s': yield not allowed.\n",
10222 fcn->name);
10223 return 1;
10224
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010225 case HLUA_E_ERR:
10226 /* Display log. */
10227 SEND_ERR(NULL, "Lua cli '%s' return an unknown error.\n",
10228 fcn->name);
10229 return 1;
10230
10231 default:
10232 return 1;
10233 }
10234
10235 return 1;
10236}
10237
10238static void hlua_cli_io_release_fct(struct appctx *appctx)
10239{
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010240 struct hlua_cli_ctx *ctx = appctx->svcctx;
10241
10242 hlua_ctx_destroy(ctx->hlua);
10243 ctx->hlua = NULL;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010244}
10245
10246/* This function is an LUA binding used for registering
10247 * new keywords in the cli. It expects a list of keywords
10248 * which are the "path". It is limited to 5 keywords. A
10249 * description of the command, a function to be executed
10250 * for the parsing and a function for io handlers.
10251 */
10252__LJMP static int hlua_register_cli(lua_State *L)
10253{
10254 struct cli_kw_list *cli_kws;
10255 const char *message;
10256 int ref_io;
10257 int len;
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010258 struct hlua_function *fcn = NULL;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010259 int index;
10260 int i;
Thierry Fournierf67442e2020-11-28 20:41:07 +010010261 struct buffer *trash;
10262 const char *kw[5];
10263 struct cli_kw *cli_kw;
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010264 const char *errmsg;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010265
10266 MAY_LJMP(check_args(L, 3, "register_cli"));
10267
10268 /* First argument : an array of maximum 5 keywords. */
10269 if (!lua_istable(L, 1))
10270 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table"));
10271
10272 /* Second argument : string with contextual message. */
10273 message = MAY_LJMP(luaL_checkstring(L, 2));
10274
10275 /* Third and fourth argument : lua function. */
10276 ref_io = MAY_LJMP(hlua_checkfunction(L, 3));
10277
Thierry Fournierf67442e2020-11-28 20:41:07 +010010278 /* Check for CLI service already registered */
10279 trash = get_trash_chunk();
10280 index = 0;
10281 lua_pushnil(L);
10282 memset(kw, 0, sizeof(kw));
10283 while (lua_next(L, 1) != 0) {
10284 if (index >= CLI_PREFIX_KW_NB)
10285 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table with a maximum of 5 entries"));
10286 if (lua_type(L, -1) != LUA_TSTRING)
10287 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table filled with strings"));
10288 kw[index] = lua_tostring(L, -1);
10289 if (index == 0)
10290 chunk_printf(trash, "%s", kw[index]);
10291 else
10292 chunk_appendf(trash, " %s", kw[index]);
10293 index++;
10294 lua_pop(L, 1);
10295 }
10296 cli_kw = cli_find_kw_exact((char **)kw);
10297 if (cli_kw != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +010010298 fcn = cli_kw->private;
10299 if (fcn->function_ref[hlua_state_id] != -1) {
10300 ha_warning("Trying to register CLI keyword 'lua.%s' more than once. "
10301 "This will become a hard error in version 2.5.\n", trash->area);
10302 }
10303 fcn->function_ref[hlua_state_id] = ref_io;
10304 return 0;
Thierry Fournierf67442e2020-11-28 20:41:07 +010010305 }
10306
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010307 /* Allocate and fill the sample fetch keyword struct. */
10308 cli_kws = calloc(1, sizeof(*cli_kws) + sizeof(struct cli_kw) * 2);
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010309 if (!cli_kws) {
10310 errmsg = "Lua out of memory error.";
10311 goto error;
10312 }
Thierry Fournier62a22aa2020-11-28 21:06:35 +010010313 fcn = new_hlua_function();
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010314 if (!fcn) {
10315 errmsg = "Lua out of memory error.";
10316 goto error;
10317 }
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010318
10319 /* Fill path. */
10320 index = 0;
10321 lua_pushnil(L);
10322 while(lua_next(L, 1) != 0) {
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010323 if (index >= 5) {
10324 errmsg = "1st argument must be a table with a maximum of 5 entries";
10325 goto error;
10326 }
10327 if (lua_type(L, -1) != LUA_TSTRING) {
10328 errmsg = "1st argument must be a table filled with strings";
10329 goto error;
10330 }
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010331 cli_kws->kw[0].str_kw[index] = strdup(lua_tostring(L, -1));
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010332 if (!cli_kws->kw[0].str_kw[index]) {
10333 errmsg = "Lua out of memory error.";
10334 goto error;
10335 }
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010336 index++;
10337 lua_pop(L, 1);
10338 }
10339
10340 /* Copy help message. */
10341 cli_kws->kw[0].usage = strdup(message);
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010342 if (!cli_kws->kw[0].usage) {
10343 errmsg = "Lua out of memory error.";
10344 goto error;
10345 }
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010346
10347 /* Fill fcn io handler. */
10348 len = strlen("<lua.cli>") + 1;
10349 for (i = 0; i < index; i++)
10350 len += strlen(cli_kws->kw[0].str_kw[i]) + 1;
10351 fcn->name = calloc(1, len);
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010352 if (!fcn->name) {
10353 errmsg = "Lua out of memory error.";
10354 goto error;
10355 }
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010356 strncat((char *)fcn->name, "<lua.cli", len);
10357 for (i = 0; i < index; i++) {
10358 strncat((char *)fcn->name, ".", len);
10359 strncat((char *)fcn->name, cli_kws->kw[0].str_kw[i], len);
10360 }
10361 strncat((char *)fcn->name, ">", len);
Thierry Fournierc7492592020-11-28 23:57:24 +010010362 fcn->function_ref[hlua_state_id] = ref_io;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010363
10364 /* Fill last entries. */
10365 cli_kws->kw[0].private = fcn;
10366 cli_kws->kw[0].parse = hlua_cli_parse_fct;
10367 cli_kws->kw[0].io_handler = hlua_cli_io_handler_fct;
10368 cli_kws->kw[0].io_release = hlua_cli_io_release_fct;
10369
10370 /* Register this new converter */
10371 cli_register_kw(cli_kws);
10372
10373 return 0;
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010374
10375 error:
10376 release_hlua_function(fcn);
10377 if (cli_kws) {
10378 for (i = 0; i < index; i++)
10379 ha_free((char **)&(cli_kws->kw[0].str_kw[i]));
10380 ha_free((char **)&(cli_kws->kw[0].usage));
10381 }
10382 ha_free(&cli_kws);
10383 WILL_LJMP(luaL_error(L, errmsg));
10384 return 0; /* Never reached */
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010385}
10386
Christopher Faulet69c581a2021-05-31 08:54:04 +020010387static int hlua_filter_init_per_thread(struct proxy *px, struct flt_conf *fconf)
10388{
10389 struct hlua_flt_config *conf = fconf->conf;
10390 lua_State *L;
10391 int error, pos, state_id, flt_ref;
10392
10393 state_id = reg_flt_to_stack_id(conf->reg);
10394 L = hlua_states[state_id];
10395 pos = lua_gettop(L);
10396
10397 /* The filter parsing function */
10398 lua_rawgeti(L, LUA_REGISTRYINDEX, conf->reg->fun_ref[state_id]);
10399
10400 /* Push the filter class on the stack and resolve all callbacks */
10401 lua_rawgeti(L, LUA_REGISTRYINDEX, conf->reg->flt_ref[state_id]);
10402
10403 /* Duplicate the filter class so each filter will have its own copy */
10404 lua_newtable(L);
10405 lua_pushnil(L);
10406
10407 while (lua_next(L, pos+2)) {
10408 lua_pushvalue(L, -2);
10409 lua_insert(L, -2);
10410 lua_settable(L, -4);
10411 }
10412 flt_ref = luaL_ref(L, LUA_REGISTRYINDEX);
10413
10414 /* Remove the original lua filter class from the stack */
10415 lua_pop(L, 1);
10416
10417 /* Push the copy on the stack */
10418 lua_rawgeti(L, LUA_REGISTRYINDEX, flt_ref);
10419
10420 /* extra args are pushed in a table */
10421 lua_newtable(L);
10422 for (pos = 0; conf->args[pos]; pos++) {
10423 /* Check stack available size. */
10424 if (!lua_checkstack(L, 1)) {
10425 ha_alert("Lua filter '%s' : Lua error : full stack.", conf->reg->name);
10426 goto error;
10427 }
10428 lua_pushstring(L, conf->args[pos]);
10429 lua_rawseti(L, -2, lua_rawlen(L, -2) + 1);
10430 }
10431
10432 error = lua_pcall(L, 2, LUA_MULTRET, 0);
10433 switch (error) {
10434 case LUA_OK:
10435 /* replace the filter ref */
10436 conf->ref[state_id] = flt_ref;
10437 break;
10438 case LUA_ERRRUN:
10439 ha_alert("Lua filter '%s' : runtime error : %s", conf->reg->name, lua_tostring(L, -1));
10440 goto error;
10441 case LUA_ERRMEM:
10442 ha_alert("Lua filter '%s' : out of memory error", conf->reg->name);
10443 goto error;
10444 case LUA_ERRERR:
10445 ha_alert("Lua filter '%s' : message handler error : %s", conf->reg->name, lua_tostring(L, -1));
10446 goto error;
10447#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM <= 503
10448 case LUA_ERRGCMM:
10449 ha_alert("Lua filter '%s' : garbage collector error : %s", conf->reg->name, lua_tostring(L, -1));
10450 goto error;
10451#endif
10452 default:
Ilya Shipitsinff0f2782021-08-22 22:18:07 +050010453 ha_alert("Lua filter '%s' : unknown error : %s", conf->reg->name, lua_tostring(L, -1));
Christopher Faulet69c581a2021-05-31 08:54:04 +020010454 goto error;
10455 }
10456
10457 lua_settop(L, 0);
10458 return 0;
10459
10460 error:
10461 lua_settop(L, 0);
10462 return -1;
10463}
10464
10465static void hlua_filter_deinit_per_thread(struct proxy *px, struct flt_conf *fconf)
10466{
10467 struct hlua_flt_config *conf = fconf->conf;
10468 lua_State *L;
10469 int state_id;
10470
10471 if (!conf)
10472 return;
10473
10474 state_id = reg_flt_to_stack_id(conf->reg);
10475 L = hlua_states[state_id];
10476 luaL_unref(L, LUA_REGISTRYINDEX, conf->ref[state_id]);
10477}
10478
10479static int hlua_filter_init(struct proxy *px, struct flt_conf *fconf)
10480{
10481 struct hlua_flt_config *conf = fconf->conf;
10482 int state_id = reg_flt_to_stack_id(conf->reg);
10483
10484 /* Rely on per-thread init for global scripts */
10485 if (!state_id)
10486 return hlua_filter_init_per_thread(px, fconf);
10487 return 0;
10488}
10489
10490static void hlua_filter_deinit(struct proxy *px, struct flt_conf *fconf)
10491{
10492
10493 if (fconf->conf) {
10494 struct hlua_flt_config *conf = fconf->conf;
10495 int state_id = reg_flt_to_stack_id(conf->reg);
10496 int pos;
10497
10498 /* Rely on per-thread deinit for global scripts */
10499 if (!state_id)
10500 hlua_filter_deinit_per_thread(px, fconf);
10501
10502 for (pos = 0; conf->args[pos]; pos++)
10503 free(conf->args[pos]);
10504 free(conf->args);
10505 }
10506 ha_free(&fconf->conf);
10507 ha_free((char **)&fconf->id);
10508 ha_free(&fconf->ops);
10509}
10510
10511static int hlua_filter_new(struct stream *s, struct filter *filter)
10512{
10513 struct hlua_flt_config *conf = FLT_CONF(filter);
10514 struct hlua_flt_ctx *flt_ctx = NULL;
10515 int ret = 1;
10516
10517 /* In the execution wrappers linked with a stream, the
10518 * Lua context can be not initialized. This behavior
10519 * permits to save performances because a systematic
10520 * Lua initialization cause 5% performances loss.
10521 */
10522 if (!s->hlua) {
10523 struct hlua *hlua;
10524
10525 hlua = pool_alloc(pool_head_hlua);
10526 if (!hlua) {
10527 SEND_ERR(s->be, "Lua filter '%s': can't initialize Lua context.\n",
10528 conf->reg->name);
10529 ret = 0;
10530 goto end;
10531 }
10532 HLUA_INIT(hlua);
10533 s->hlua = hlua;
10534 if (!hlua_ctx_init(s->hlua, reg_flt_to_stack_id(conf->reg), s->task, 0)) {
10535 SEND_ERR(s->be, "Lua filter '%s': can't initialize Lua context.\n",
10536 conf->reg->name);
10537 ret = 0;
10538 goto end;
10539 }
10540 }
10541
10542 flt_ctx = pool_zalloc(pool_head_hlua_flt_ctx);
10543 if (!flt_ctx) {
10544 SEND_ERR(s->be, "Lua filter '%s': can't initialize filter Lua context.\n",
10545 conf->reg->name);
10546 ret = 0;
10547 goto end;
10548 }
10549 flt_ctx->hlua[0] = pool_alloc(pool_head_hlua);
10550 flt_ctx->hlua[1] = pool_alloc(pool_head_hlua);
10551 if (!flt_ctx->hlua[0] || !flt_ctx->hlua[1]) {
10552 SEND_ERR(s->be, "Lua filter '%s': can't initialize filter Lua context.\n",
10553 conf->reg->name);
10554 ret = 0;
10555 goto end;
10556 }
10557 HLUA_INIT(flt_ctx->hlua[0]);
10558 HLUA_INIT(flt_ctx->hlua[1]);
10559 if (!hlua_ctx_init(flt_ctx->hlua[0], reg_flt_to_stack_id(conf->reg), s->task, 0) ||
10560 !hlua_ctx_init(flt_ctx->hlua[1], reg_flt_to_stack_id(conf->reg), s->task, 0)) {
10561 SEND_ERR(s->be, "Lua filter '%s': can't initialize filter Lua context.\n",
10562 conf->reg->name);
10563 ret = 0;
10564 goto end;
10565 }
10566
10567 if (!HLUA_IS_RUNNING(s->hlua)) {
10568 /* The following Lua calls can fail. */
10569 if (!SET_SAFE_LJMP(s->hlua)) {
10570 const char *error;
10571
10572 if (lua_type(s->hlua->T, -1) == LUA_TSTRING)
10573 error = lua_tostring(s->hlua->T, -1);
10574 else
10575 error = "critical error";
10576 SEND_ERR(s->be, "Lua filter '%s': %s.\n", conf->reg->name, error);
10577 ret = 0;
10578 goto end;
10579 }
10580
10581 /* Check stack size. */
10582 if (!lua_checkstack(s->hlua->T, 1)) {
10583 SEND_ERR(s->be, "Lua filter '%s': full stack.\n", conf->reg->name);
Tim Duesterhus22817382021-09-11 23:17:25 +020010584 RESET_SAFE_LJMP(s->hlua);
Christopher Faulet69c581a2021-05-31 08:54:04 +020010585 ret = 0;
10586 goto end;
10587 }
10588
10589 lua_rawgeti(s->hlua->T, LUA_REGISTRYINDEX, conf->ref[s->hlua->state_id]);
10590 if (lua_getfield(s->hlua->T, -1, "new") != LUA_TFUNCTION) {
10591 SEND_ERR(s->be, "Lua filter '%s': 'new' field is not a function.\n",
10592 conf->reg->name);
10593 RESET_SAFE_LJMP(s->hlua);
10594 ret = 0;
10595 goto end;
10596 }
10597 lua_insert(s->hlua->T, -2);
10598
10599 /* Push the copy on the stack */
10600 s->hlua->nargs = 1;
10601
10602 /* We must initialize the execution timeouts. */
10603 s->hlua->max_time = hlua_timeout_session;
10604
10605 /* At this point the execution is safe. */
10606 RESET_SAFE_LJMP(s->hlua);
10607 }
10608
10609 switch (hlua_ctx_resume(s->hlua, 0)) {
10610 case HLUA_E_OK:
10611 /* Nothing returned or not a table, ignore the filter for current stream */
10612 if (!lua_gettop(s->hlua->T) || !lua_istable(s->hlua->T, 1)) {
10613 ret = 0;
10614 goto end;
10615 }
10616
10617 /* Attached the filter pointer to the ctx */
10618 lua_pushstring(s->hlua->T, "__filter");
10619 lua_pushlightuserdata(s->hlua->T, filter);
10620 lua_settable(s->hlua->T, -3);
10621
10622 /* Save a ref on the filter ctx */
10623 lua_pushvalue(s->hlua->T, 1);
10624 flt_ctx->ref = luaL_ref(s->hlua->T, LUA_REGISTRYINDEX);
10625 filter->ctx = flt_ctx;
10626 break;
10627 case HLUA_E_ERRMSG:
10628 SEND_ERR(s->be, "Lua filter '%s' : %s.\n", conf->reg->name, lua_tostring(s->hlua->T, -1));
10629 ret = -1;
10630 goto end;
10631 case HLUA_E_ETMOUT:
10632 SEND_ERR(s->be, "Lua filter '%s' : 'new' execution timeout.\n", conf->reg->name);
10633 ret = 0;
10634 goto end;
10635 case HLUA_E_NOMEM:
10636 SEND_ERR(s->be, "Lua filter '%s' : out of memory error.\n", conf->reg->name);
10637 ret = 0;
10638 goto end;
10639 case HLUA_E_AGAIN:
10640 case HLUA_E_YIELD:
10641 SEND_ERR(s->be, "Lua filter '%s': yield functions like core.tcp() or core.sleep()"
10642 " are not allowed from 'new' function.\n", conf->reg->name);
10643 ret = 0;
10644 goto end;
10645 case HLUA_E_ERR:
10646 SEND_ERR(s->be, "Lua filter '%s': 'new' returns an unknown error.\n", conf->reg->name);
10647 ret = 0;
10648 goto end;
10649 default:
10650 ret = 0;
10651 goto end;
10652 }
10653
10654 end:
10655 if (s->hlua)
10656 lua_settop(s->hlua->T, 0);
10657 if (ret <= 0) {
10658 if (flt_ctx) {
10659 hlua_ctx_destroy(flt_ctx->hlua[0]);
10660 hlua_ctx_destroy(flt_ctx->hlua[1]);
10661 pool_free(pool_head_hlua_flt_ctx, flt_ctx);
10662 }
10663 }
10664 return ret;
10665}
10666
10667static void hlua_filter_delete(struct stream *s, struct filter *filter)
10668{
10669 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10670
10671 luaL_unref(s->hlua->T, LUA_REGISTRYINDEX, flt_ctx->ref);
10672 hlua_ctx_destroy(flt_ctx->hlua[0]);
10673 hlua_ctx_destroy(flt_ctx->hlua[1]);
10674 pool_free(pool_head_hlua_flt_ctx, flt_ctx);
10675 filter->ctx = NULL;
10676}
10677
Christopher Faulet9f55a502020-02-25 15:21:02 +010010678static int hlua_filter_from_payload(struct filter *filter)
10679{
10680 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10681
10682 return (flt_ctx && !!(flt_ctx->flags & HLUA_FLT_CTX_FL_PAYLOAD));
10683}
10684
Christopher Fauletc404f112020-02-26 15:03:09 +010010685static int hlua_filter_callback(struct stream *s, struct filter *filter, const char *fun,
10686 int dir, unsigned int flags)
10687{
10688 struct hlua *flt_hlua;
10689 struct hlua_flt_config *conf = FLT_CONF(filter);
10690 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10691 unsigned int hflags = HLUA_TXN_FLT_CTX;
10692 int ret = 1;
10693
10694 flt_hlua = flt_ctx->hlua[(dir == SMP_OPT_DIR_REQ ? 0 : 1)];
10695 if (!flt_hlua)
10696 goto end;
10697
10698 if (!HLUA_IS_RUNNING(flt_hlua)) {
10699 int extra_idx = lua_gettop(flt_hlua->T);
10700
10701 /* The following Lua calls can fail. */
10702 if (!SET_SAFE_LJMP(flt_hlua)) {
10703 const char *error;
10704
10705 if (lua_type(flt_hlua->T, -1) == LUA_TSTRING)
10706 error = lua_tostring(flt_hlua->T, -1);
10707 else
10708 error = "critical error";
10709 SEND_ERR(s->be, "Lua filter '%s': %s.\n", conf->reg->name, error);
10710 goto end;
10711 }
10712
10713 /* Check stack size. */
10714 if (!lua_checkstack(flt_hlua->T, 3)) {
10715 SEND_ERR(s->be, "Lua filter '%s': full stack.\n", conf->reg->name);
10716 RESET_SAFE_LJMP(flt_hlua);
10717 goto end;
10718 }
10719
10720 lua_rawgeti(flt_hlua->T, LUA_REGISTRYINDEX, flt_ctx->ref);
10721 if (lua_getfield(flt_hlua->T, -1, fun) != LUA_TFUNCTION) {
10722 RESET_SAFE_LJMP(flt_hlua);
10723 goto end;
10724 }
10725 lua_insert(flt_hlua->T, -2);
10726
10727 if (!hlua_txn_new(flt_hlua->T, s, s->be, dir, hflags)) {
10728 SEND_ERR(s->be, "Lua filter '%s': full stack.\n", conf->reg->name);
10729 RESET_SAFE_LJMP(flt_hlua);
10730 goto end;
10731 }
10732 flt_hlua->nargs = 2;
10733
10734 if (flags & HLUA_FLT_CB_ARG_CHN) {
10735 if (dir == SMP_OPT_DIR_REQ)
10736 lua_getfield(flt_hlua->T, -1, "req");
10737 else
10738 lua_getfield(flt_hlua->T, -1, "res");
10739 if (lua_type(flt_hlua->T, -1) == LUA_TTABLE) {
10740 lua_pushstring(flt_hlua->T, "__filter");
10741 lua_pushlightuserdata(flt_hlua->T, filter);
10742 lua_settable(flt_hlua->T, -3);
10743 }
10744 flt_hlua->nargs++;
10745 }
10746 else if (flags & HLUA_FLT_CB_ARG_HTTP_MSG) {
Christopher Fauleteae8afa2020-02-26 17:15:48 +010010747 if (dir == SMP_OPT_DIR_REQ)
10748 lua_getfield(flt_hlua->T, -1, "http_req");
10749 else
10750 lua_getfield(flt_hlua->T, -1, "http_res");
10751 if (lua_type(flt_hlua->T, -1) == LUA_TTABLE) {
10752 lua_pushstring(flt_hlua->T, "__filter");
10753 lua_pushlightuserdata(flt_hlua->T, filter);
10754 lua_settable(flt_hlua->T, -3);
10755 }
10756 flt_hlua->nargs++;
Christopher Fauletc404f112020-02-26 15:03:09 +010010757 }
10758
10759 /* Check stack size. */
10760 if (!lua_checkstack(flt_hlua->T, 1)) {
10761 SEND_ERR(s->be, "Lua filter '%s': full stack.\n", conf->reg->name);
10762 RESET_SAFE_LJMP(flt_hlua);
10763 goto end;
10764 }
10765
10766 while (extra_idx--) {
10767 lua_pushvalue(flt_hlua->T, 1);
10768 lua_remove(flt_hlua->T, 1);
10769 flt_hlua->nargs++;
10770 }
10771
10772 /* We must initialize the execution timeouts. */
10773 flt_hlua->max_time = hlua_timeout_session;
10774
10775 /* At this point the execution is safe. */
10776 RESET_SAFE_LJMP(flt_hlua);
10777 }
10778
10779 switch (hlua_ctx_resume(flt_hlua, !(flags & HLUA_FLT_CB_FINAL))) {
10780 case HLUA_E_OK:
10781 /* Catch the return value if it required */
10782 if ((flags & HLUA_FLT_CB_RETVAL) && lua_gettop(flt_hlua->T) > 0) {
10783 ret = lua_tointeger(flt_hlua->T, -1);
10784 lua_settop(flt_hlua->T, 0); /* Empty the stack. */
10785 }
10786
10787 /* Set timeout in the required channel. */
10788 if (flt_hlua->wake_time != TICK_ETERNITY) {
10789 if (dir == SMP_OPT_DIR_REQ)
10790 s->req.analyse_exp = flt_hlua->wake_time;
10791 else
10792 s->res.analyse_exp = flt_hlua->wake_time;
10793 }
10794 break;
10795 case HLUA_E_AGAIN:
10796 /* Set timeout in the required channel. */
10797 if (flt_hlua->wake_time != TICK_ETERNITY) {
10798 if (dir == SMP_OPT_DIR_REQ)
10799 s->req.analyse_exp = flt_hlua->wake_time;
10800 else
10801 s->res.analyse_exp = flt_hlua->wake_time;
10802 }
10803 /* Some actions can be wake up when a "write" event
10804 * is detected on a response channel. This is useful
10805 * only for actions targeted on the requests.
10806 */
10807 if (HLUA_IS_WAKERESWR(flt_hlua))
10808 s->res.flags |= CF_WAKE_WRITE;
10809 if (HLUA_IS_WAKEREQWR(flt_hlua))
10810 s->req.flags |= CF_WAKE_WRITE;
10811 ret = 0;
10812 goto end;
10813 case HLUA_E_ERRMSG:
10814 SEND_ERR(s->be, "Lua filter '%s' : %s.\n", conf->reg->name, lua_tostring(flt_hlua->T, -1));
10815 ret = -1;
10816 goto end;
10817 case HLUA_E_ETMOUT:
10818 SEND_ERR(s->be, "Lua filter '%s' : '%s' callback execution timeout.\n", conf->reg->name, fun);
10819 goto end;
10820 case HLUA_E_NOMEM:
10821 SEND_ERR(s->be, "Lua filter '%s' : out of memory error.\n", conf->reg->name);
10822 goto end;
10823 case HLUA_E_YIELD:
10824 SEND_ERR(s->be, "Lua filter '%s': yield functions like core.tcp() or core.sleep()"
10825 " are not allowed from '%s' callback.\n", conf->reg->name, fun);
10826 goto end;
10827 case HLUA_E_ERR:
10828 SEND_ERR(s->be, "Lua filter '%s': '%s' returns an unknown error.\n", conf->reg->name, fun);
10829 goto end;
10830 default:
10831 goto end;
10832 }
10833
10834
10835 end:
10836 return ret;
10837}
10838
10839static int hlua_filter_start_analyze(struct stream *s, struct filter *filter, struct channel *chn)
10840{
10841 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10842
10843 flt_ctx->flags = 0;
10844 return hlua_filter_callback(s, filter, "start_analyze",
10845 (!(chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES),
10846 (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_RETVAL | HLUA_FLT_CB_ARG_CHN));
10847}
10848
10849static int hlua_filter_end_analyze(struct stream *s, struct filter *filter, struct channel *chn)
10850{
10851 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10852
10853 flt_ctx->flags &= ~HLUA_FLT_CTX_FL_PAYLOAD;
10854 return hlua_filter_callback(s, filter, "end_analyze",
10855 (!(chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES),
10856 (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_RETVAL | HLUA_FLT_CB_ARG_CHN));
10857}
10858
Christopher Fauleteae8afa2020-02-26 17:15:48 +010010859static int hlua_filter_http_headers(struct stream *s, struct filter *filter, struct http_msg *msg)
10860{
10861 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10862
10863 flt_ctx->flags &= ~HLUA_FLT_CTX_FL_PAYLOAD;
10864 return hlua_filter_callback(s, filter, "http_headers",
10865 (!(msg->chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES),
10866 (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_RETVAL | HLUA_FLT_CB_ARG_HTTP_MSG));
10867}
10868
10869static int hlua_filter_http_payload(struct stream *s, struct filter *filter, struct http_msg *msg,
10870 unsigned int offset, unsigned int len)
10871{
10872 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10873 struct hlua *flt_hlua;
10874 int dir = (!(msg->chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES);
10875 int idx = (dir == SMP_OPT_DIR_REQ ? 0 : 1);
10876 int ret;
10877
10878 flt_hlua = flt_ctx->hlua[idx];
10879 flt_ctx->cur_off[idx] = offset;
10880 flt_ctx->cur_len[idx] = len;
10881 flt_ctx->flags |= HLUA_FLT_CTX_FL_PAYLOAD;
10882 ret = hlua_filter_callback(s, filter, "http_payload", dir, (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_ARG_HTTP_MSG));
10883 if (ret != -1) {
10884 ret = flt_ctx->cur_len[idx];
10885 if (lua_gettop(flt_hlua->T) > 0) {
10886 ret = lua_tointeger(flt_hlua->T, -1);
10887 if (ret > flt_ctx->cur_len[idx])
10888 ret = flt_ctx->cur_len[idx];
10889 lua_settop(flt_hlua->T, 0); /* Empty the stack. */
10890 }
10891 }
10892 return ret;
10893}
10894
10895static int hlua_filter_http_end(struct stream *s, struct filter *filter, struct http_msg *msg)
10896{
10897 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10898
10899 flt_ctx->flags &= ~HLUA_FLT_CTX_FL_PAYLOAD;
10900 return hlua_filter_callback(s, filter, "http_end",
10901 (!(msg->chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES),
10902 (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_RETVAL | HLUA_FLT_CB_ARG_HTTP_MSG));
10903}
10904
Christopher Fauletc404f112020-02-26 15:03:09 +010010905static int hlua_filter_tcp_payload(struct stream *s, struct filter *filter, struct channel *chn,
10906 unsigned int offset, unsigned int len)
10907{
10908 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10909 struct hlua *flt_hlua;
10910 int dir = (!(chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES);
10911 int idx = (dir == SMP_OPT_DIR_REQ ? 0 : 1);
10912 int ret;
10913
10914 flt_hlua = flt_ctx->hlua[idx];
10915 flt_ctx->cur_off[idx] = offset;
10916 flt_ctx->cur_len[idx] = len;
10917 flt_ctx->flags |= HLUA_FLT_CTX_FL_PAYLOAD;
10918 ret = hlua_filter_callback(s, filter, "tcp_payload", dir, (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_ARG_CHN));
10919 if (ret != -1) {
10920 ret = flt_ctx->cur_len[idx];
10921 if (lua_gettop(flt_hlua->T) > 0) {
10922 ret = lua_tointeger(flt_hlua->T, -1);
10923 if (ret > flt_ctx->cur_len[idx])
10924 ret = flt_ctx->cur_len[idx];
10925 lua_settop(flt_hlua->T, 0); /* Empty the stack. */
10926 }
10927 }
10928 return ret;
10929}
10930
Christopher Faulet69c581a2021-05-31 08:54:04 +020010931static int hlua_filter_parse_fct(char **args, int *cur_arg, struct proxy *px,
10932 struct flt_conf *fconf, char **err, void *private)
10933{
10934 struct hlua_reg_filter *reg_flt = private;
10935 lua_State *L;
10936 struct hlua_flt_config *conf = NULL;
10937 const char *flt_id = NULL;
10938 int state_id, pos, flt_flags = 0;
10939 struct flt_ops *hlua_flt_ops = NULL;
10940
10941 state_id = reg_flt_to_stack_id(reg_flt);
10942 L = hlua_states[state_id];
10943
10944 /* Initialize the filter ops with default callbacks */
10945 hlua_flt_ops = calloc(1, sizeof(*hlua_flt_ops));
Christopher Fauletc86bb872021-08-13 08:33:57 +020010946 if (!hlua_flt_ops)
10947 goto error;
Christopher Faulet69c581a2021-05-31 08:54:04 +020010948 hlua_flt_ops->init = hlua_filter_init;
10949 hlua_flt_ops->deinit = hlua_filter_deinit;
10950 if (state_id) {
10951 /* Set per-thread callback if script is loaded per-thread */
10952 hlua_flt_ops->init_per_thread = hlua_filter_init_per_thread;
10953 hlua_flt_ops->deinit_per_thread = hlua_filter_deinit_per_thread;
10954 }
10955 hlua_flt_ops->attach = hlua_filter_new;
10956 hlua_flt_ops->detach = hlua_filter_delete;
10957
10958 /* Push the filter class on the stack and resolve all callbacks */
10959 lua_rawgeti(L, LUA_REGISTRYINDEX, reg_flt->flt_ref[state_id]);
10960
Christopher Fauletc404f112020-02-26 15:03:09 +010010961 if (lua_getfield(L, -1, "start_analyze") == LUA_TFUNCTION)
10962 hlua_flt_ops->channel_start_analyze = hlua_filter_start_analyze;
10963 lua_pop(L, 1);
10964 if (lua_getfield(L, -1, "end_analyze") == LUA_TFUNCTION)
10965 hlua_flt_ops->channel_end_analyze = hlua_filter_end_analyze;
10966 lua_pop(L, 1);
Christopher Fauleteae8afa2020-02-26 17:15:48 +010010967 if (lua_getfield(L, -1, "http_headers") == LUA_TFUNCTION)
10968 hlua_flt_ops->http_headers = hlua_filter_http_headers;
10969 lua_pop(L, 1);
10970 if (lua_getfield(L, -1, "http_payload") == LUA_TFUNCTION)
10971 hlua_flt_ops->http_payload = hlua_filter_http_payload;
10972 lua_pop(L, 1);
10973 if (lua_getfield(L, -1, "http_end") == LUA_TFUNCTION)
10974 hlua_flt_ops->http_end = hlua_filter_http_end;
10975 lua_pop(L, 1);
Christopher Fauletc404f112020-02-26 15:03:09 +010010976 if (lua_getfield(L, -1, "tcp_payload") == LUA_TFUNCTION)
10977 hlua_flt_ops->tcp_payload = hlua_filter_tcp_payload;
10978 lua_pop(L, 1);
Christopher Faulet69c581a2021-05-31 08:54:04 +020010979
10980 /* Get id and flags of the filter class */
10981 if (lua_getfield(L, -1, "id") == LUA_TSTRING)
10982 flt_id = lua_tostring(L, -1);
10983 lua_pop(L, 1);
10984 if (lua_getfield(L, -1, "flags") == LUA_TNUMBER)
10985 flt_flags = lua_tointeger(L, -1);
10986 lua_pop(L, 1);
10987
10988 /* Create the filter config */
10989 conf = calloc(1, sizeof(*conf));
Christopher Fauletc86bb872021-08-13 08:33:57 +020010990 if (!conf)
Christopher Faulet69c581a2021-05-31 08:54:04 +020010991 goto error;
Christopher Faulet69c581a2021-05-31 08:54:04 +020010992 conf->reg = reg_flt;
10993
10994 /* duplicate args */
10995 for (pos = 0; *args[*cur_arg + 1 + pos]; pos++);
10996 conf->args = calloc(pos + 1, sizeof(*conf->args));
Christopher Fauletc86bb872021-08-13 08:33:57 +020010997 if (!conf->args)
10998 goto error;
10999 for (pos = 0; *args[*cur_arg + 1 + pos]; pos++) {
Christopher Faulet69c581a2021-05-31 08:54:04 +020011000 conf->args[pos] = strdup(args[*cur_arg + 1 + pos]);
Christopher Fauletc86bb872021-08-13 08:33:57 +020011001 if (!conf->args[pos])
11002 goto error;
11003 }
Christopher Faulet69c581a2021-05-31 08:54:04 +020011004 conf->args[pos] = NULL;
11005 *cur_arg += pos + 1;
11006
Christopher Fauletc86bb872021-08-13 08:33:57 +020011007 if (flt_id) {
11008 fconf->id = strdup(flt_id);
11009 if (!fconf->id)
11010 goto error;
11011 }
Christopher Faulet69c581a2021-05-31 08:54:04 +020011012 fconf->flags = flt_flags;
11013 fconf->conf = conf;
11014 fconf->ops = hlua_flt_ops;
11015
11016 lua_settop(L, 0);
11017 return 0;
11018
11019 error:
Christopher Fauletc86bb872021-08-13 08:33:57 +020011020 memprintf(err, "Lua filter '%s' : Lua out of memory error", reg_flt->name);
Christopher Faulet69c581a2021-05-31 08:54:04 +020011021 free(hlua_flt_ops);
Christopher Fauletc86bb872021-08-13 08:33:57 +020011022 if (conf && conf->args) {
11023 for (pos = 0; conf->args[pos]; pos++)
11024 free(conf->args[pos]);
11025 free(conf->args);
11026 }
Christopher Faulet69c581a2021-05-31 08:54:04 +020011027 free(conf);
Christopher Fauletc86bb872021-08-13 08:33:57 +020011028 free((char *)fconf->id);
Christopher Faulet69c581a2021-05-31 08:54:04 +020011029 lua_settop(L, 0);
11030 return -1;
11031}
11032
Christopher Fauletc404f112020-02-26 15:03:09 +010011033__LJMP static int hlua_register_data_filter(lua_State *L)
11034{
11035 struct filter *filter;
11036 struct channel *chn;
11037
11038 MAY_LJMP(check_args(L, 2, "register_data_filter"));
11039 MAY_LJMP(luaL_checktype(L, 1, LUA_TTABLE));
11040 chn = MAY_LJMP(hlua_checkchannel(L, 2));
11041
11042 lua_getfield(L, 1, "__filter");
11043 MAY_LJMP(luaL_checktype(L, -1, LUA_TLIGHTUSERDATA));
11044 filter = lua_touserdata (L, -1);
11045 lua_pop(L, 1);
11046
11047 register_data_filter(chn_strm(chn), chn, filter);
11048 return 1;
11049}
11050
11051__LJMP static int hlua_unregister_data_filter(lua_State *L)
11052{
11053 struct filter *filter;
11054 struct channel *chn;
11055
11056 MAY_LJMP(check_args(L, 2, "unregister_data_filter"));
11057 MAY_LJMP(luaL_checktype(L, 1, LUA_TTABLE));
11058 chn = MAY_LJMP(hlua_checkchannel(L, 2));
11059
11060 lua_getfield(L, 1, "__filter");
11061 MAY_LJMP(luaL_checktype(L, -1, LUA_TLIGHTUSERDATA));
11062 filter = lua_touserdata (L, -1);
11063 lua_pop(L, 1);
11064
11065 unregister_data_filter(chn_strm(chn), chn, filter);
11066 return 1;
11067}
11068
Christopher Faulet69c581a2021-05-31 08:54:04 +020011069/* This function is an LUA binding used for registering a filter. It expects a
Ilya Shipitsinff0f2782021-08-22 22:18:07 +050011070 * filter name used in the haproxy configuration file and a LUA function to
Christopher Faulet69c581a2021-05-31 08:54:04 +020011071 * parse configuration arguments.
11072 */
11073__LJMP static int hlua_register_filter(lua_State *L)
11074{
11075 struct buffer *trash;
11076 struct flt_kw_list *fkl;
11077 struct flt_kw *fkw;
11078 const char *name;
11079 struct hlua_reg_filter *reg_flt= NULL;
11080 int flt_ref, fun_ref;
11081 int len;
11082
11083 MAY_LJMP(check_args(L, 3, "register_filter"));
11084
11085 /* First argument : filter name. */
11086 name = MAY_LJMP(luaL_checkstring(L, 1));
11087
11088 /* Second argument : The filter class */
11089 flt_ref = MAY_LJMP(hlua_checktable(L, 2));
11090
11091 /* Third argument : lua function. */
11092 fun_ref = MAY_LJMP(hlua_checkfunction(L, 3));
11093
11094 trash = get_trash_chunk();
11095 chunk_printf(trash, "lua.%s", name);
11096 fkw = flt_find_kw(trash->area);
11097 if (fkw != NULL) {
11098 reg_flt = fkw->private;
11099 if (reg_flt->flt_ref[hlua_state_id] != -1 || reg_flt->fun_ref[hlua_state_id] != -1) {
11100 ha_warning("Trying to register filter 'lua.%s' more than once. "
11101 "This will become a hard error in version 2.5.\n", name);
11102 }
11103 reg_flt->flt_ref[hlua_state_id] = flt_ref;
11104 reg_flt->fun_ref[hlua_state_id] = fun_ref;
11105 return 0;
11106 }
11107
11108 fkl = calloc(1, sizeof(*fkl) + sizeof(struct flt_kw) * 2);
11109 if (!fkl)
11110 goto alloc_error;
11111 fkl->scope = "HLUA";
11112
11113 reg_flt = new_hlua_reg_filter(name);
11114 if (!reg_flt)
11115 goto alloc_error;
11116
11117 reg_flt->flt_ref[hlua_state_id] = flt_ref;
11118 reg_flt->fun_ref[hlua_state_id] = fun_ref;
11119
11120 /* The filter keyword */
11121 len = strlen("lua.") + strlen(name) + 1;
11122 fkl->kw[0].kw = calloc(1, len);
11123 if (!fkl->kw[0].kw)
11124 goto alloc_error;
11125
11126 snprintf((char *)fkl->kw[0].kw, len, "lua.%s", name);
11127
11128 fkl->kw[0].parse = hlua_filter_parse_fct;
11129 fkl->kw[0].private = reg_flt;
11130 memset(&fkl->kw[1], 0, sizeof(*fkl->kw));
11131
11132 /* Register this new filter */
11133 flt_register_keywords(fkl);
11134
11135 return 0;
11136
11137 alloc_error:
11138 release_hlua_reg_filter(reg_flt);
11139 ha_free(&fkl);
11140 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
11141 return 0; /* Never reached */
11142}
11143
Thierry FOURNIERbd413492015-03-03 16:52:26 +010011144static int hlua_read_timeout(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011145 const struct proxy *defpx, const char *file, int line,
Thierry FOURNIERbd413492015-03-03 16:52:26 +010011146 char **err, unsigned int *timeout)
11147{
11148 const char *error;
11149
11150 error = parse_time_err(args[1], timeout, TIME_UNIT_MS);
Willy Tarreau9faebe32019-06-07 19:00:37 +020011151 if (error == PARSE_TIME_OVER) {
11152 memprintf(err, "timer overflow in argument <%s> to <%s> (maximum value is 2147483647 ms or ~24.8 days)",
11153 args[1], args[0]);
11154 return -1;
11155 }
11156 else if (error == PARSE_TIME_UNDER) {
11157 memprintf(err, "timer underflow in argument <%s> to <%s> (minimum non-null value is 1 ms)",
11158 args[1], args[0]);
11159 return -1;
11160 }
11161 else if (error) {
Thierry FOURNIERbd413492015-03-03 16:52:26 +010011162 memprintf(err, "%s: invalid timeout", args[0]);
11163 return -1;
11164 }
11165 return 0;
11166}
11167
11168static int hlua_session_timeout(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011169 const struct proxy *defpx, const char *file, int line,
Thierry FOURNIERbd413492015-03-03 16:52:26 +010011170 char **err)
11171{
11172 return hlua_read_timeout(args, section_type, curpx, defpx,
11173 file, line, err, &hlua_timeout_session);
11174}
11175
11176static int hlua_task_timeout(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011177 const struct proxy *defpx, const char *file, int line,
Thierry FOURNIERbd413492015-03-03 16:52:26 +010011178 char **err)
11179{
11180 return hlua_read_timeout(args, section_type, curpx, defpx,
11181 file, line, err, &hlua_timeout_task);
11182}
11183
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020011184static int hlua_applet_timeout(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011185 const struct proxy *defpx, const char *file, int line,
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020011186 char **err)
11187{
11188 return hlua_read_timeout(args, section_type, curpx, defpx,
11189 file, line, err, &hlua_timeout_applet);
11190}
11191
Thierry FOURNIERee9f8022015-03-03 17:37:37 +010011192static int hlua_forced_yield(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011193 const struct proxy *defpx, const char *file, int line,
Thierry FOURNIERee9f8022015-03-03 17:37:37 +010011194 char **err)
11195{
11196 char *error;
11197
11198 hlua_nb_instruction = strtoll(args[1], &error, 10);
11199 if (*error != '\0') {
11200 memprintf(err, "%s: invalid number", args[0]);
11201 return -1;
11202 }
11203 return 0;
11204}
11205
Willy Tarreau32f61e22015-03-18 17:54:59 +010011206static int hlua_parse_maxmem(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011207 const struct proxy *defpx, const char *file, int line,
Willy Tarreau32f61e22015-03-18 17:54:59 +010011208 char **err)
11209{
11210 char *error;
11211
11212 if (*(args[1]) == 0) {
11213 memprintf(err, "'%s' expects an integer argument (Lua memory size in MB).\n", args[0]);
11214 return -1;
11215 }
11216 hlua_global_allocator.limit = strtoll(args[1], &error, 10) * 1024L * 1024L;
11217 if (*error != '\0') {
11218 memprintf(err, "%s: invalid number %s (error at '%c')", args[0], args[1], *error);
11219 return -1;
11220 }
11221 return 0;
11222}
11223
11224
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011225/* This function is called by the main configuration key "lua-load". It loads and
11226 * execute an lua file during the parsing of the HAProxy configuration file. It is
11227 * the main lua entry point.
11228 *
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -080011229 * This function runs with the HAProxy keywords API. It returns -1 if an error
11230 * occurs, otherwise it returns 0.
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011231 *
11232 * In some error case, LUA set an error message in top of the stack. This function
11233 * returns this error message in the HAProxy logs and pop it from the stack.
Thierry FOURNIERbabae282015-09-17 11:36:37 +020011234 *
11235 * This function can fail with an abort() due to an Lua critical error.
11236 * We are in the configuration parsing process of HAProxy, this abort() is
11237 * tolerated.
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011238 */
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011239static int hlua_load_state(char *filename, lua_State *L, char **err)
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011240{
11241 int error;
11242
11243 /* Just load and compile the file. */
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011244 error = luaL_loadfile(L, filename);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011245 if (error) {
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011246 memprintf(err, "error in Lua file '%s': %s", filename, lua_tostring(L, -1));
11247 lua_pop(L, 1);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011248 return -1;
11249 }
11250
11251 /* If no syntax error where detected, execute the code. */
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011252 error = lua_pcall(L, 0, LUA_MULTRET, 0);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011253 switch (error) {
11254 case LUA_OK:
11255 break;
11256 case LUA_ERRRUN:
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011257 memprintf(err, "Lua runtime error: %s\n", lua_tostring(L, -1));
11258 lua_pop(L, 1);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011259 return -1;
11260 case LUA_ERRMEM:
Thierry Fournierde6145f2020-11-29 00:55:53 +010011261 memprintf(err, "Lua out of memory error\n");
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011262 return -1;
11263 case LUA_ERRERR:
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011264 memprintf(err, "Lua message handler error: %s\n", lua_tostring(L, -1));
11265 lua_pop(L, 1);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011266 return -1;
Christopher Faulet08ed98f2020-07-28 10:33:25 +020011267#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM <= 503
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011268 case LUA_ERRGCMM:
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011269 memprintf(err, "Lua garbage collector error: %s\n", lua_tostring(L, -1));
11270 lua_pop(L, 1);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011271 return -1;
Christopher Faulet08ed98f2020-07-28 10:33:25 +020011272#endif
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011273 default:
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011274 memprintf(err, "Lua unknown error: %s\n", lua_tostring(L, -1));
11275 lua_pop(L, 1);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011276 return -1;
11277 }
11278
11279 return 0;
11280}
11281
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011282static int hlua_load(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011283 const struct proxy *defpx, const char *file, int line,
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011284 char **err)
11285{
11286 if (*(args[1]) == 0) {
11287 memprintf(err, "'%s' expects a file name as parameter.\n", args[0]);
11288 return -1;
11289 }
11290
Thierry Fournier59f11be2020-11-29 00:37:41 +010011291 /* loading for global state */
Thierry Fournierc7492592020-11-28 23:57:24 +010011292 hlua_state_id = 0;
Willy Tarreau43ab05b2021-09-28 09:43:11 +020011293 ha_set_thread(NULL);
Thierry Fournierafc63e22020-11-28 17:06:51 +010011294 return hlua_load_state(args[1], hlua_states[0], err);
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011295}
11296
Thierry Fournier59f11be2020-11-29 00:37:41 +010011297static int hlua_load_per_thread(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011298 const struct proxy *defpx, const char *file, int line,
Thierry Fournier59f11be2020-11-29 00:37:41 +010011299 char **err)
11300{
11301 int len;
11302
11303 if (*(args[1]) == 0) {
11304 memprintf(err, "'%s' expects a file as parameter.\n", args[0]);
11305 return -1;
11306 }
11307
11308 if (per_thread_load == NULL) {
11309 /* allocate the first entry large enough to store the final NULL */
11310 per_thread_load = calloc(1, sizeof(*per_thread_load));
11311 if (per_thread_load == NULL) {
11312 memprintf(err, "out of memory error");
11313 return -1;
11314 }
11315 }
11316
11317 /* count used entries */
11318 for (len = 0; per_thread_load[len] != NULL; len++)
11319 ;
11320
11321 per_thread_load = realloc(per_thread_load, (len + 2) * sizeof(*per_thread_load));
11322 if (per_thread_load == NULL) {
11323 memprintf(err, "out of memory error");
11324 return -1;
11325 }
11326
11327 per_thread_load[len] = strdup(args[1]);
11328 per_thread_load[len + 1] = NULL;
11329
11330 if (per_thread_load[len] == NULL) {
11331 memprintf(err, "out of memory error");
11332 return -1;
11333 }
11334
11335 /* loading for thread 1 only */
11336 hlua_state_id = 1;
Willy Tarreau43ab05b2021-09-28 09:43:11 +020011337 ha_set_thread(NULL);
Thierry Fournier59f11be2020-11-29 00:37:41 +010011338 return hlua_load_state(args[1], hlua_states[1], err);
11339}
11340
Tim Duesterhusc9fc9f22020-01-12 13:55:39 +010011341/* Prepend the given <path> followed by a semicolon to the `package.<type>` variable
11342 * in the given <ctx>.
11343 */
Thierry Fournier3fb9e512020-11-28 10:13:12 +010011344static int hlua_prepend_path(lua_State *L, char *type, char *path)
Tim Duesterhusc9fc9f22020-01-12 13:55:39 +010011345{
Thierry Fournier3fb9e512020-11-28 10:13:12 +010011346 lua_getglobal(L, "package"); /* push package variable */
11347 lua_pushstring(L, path); /* push given path */
11348 lua_pushstring(L, ";"); /* push semicolon */
11349 lua_getfield(L, -3, type); /* push old path */
11350 lua_concat(L, 3); /* concatenate to new path */
11351 lua_setfield(L, -2, type); /* store new path */
11352 lua_pop(L, 1); /* pop package variable */
Tim Duesterhusc9fc9f22020-01-12 13:55:39 +010011353
11354 return 0;
11355}
11356
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010011357static int hlua_config_prepend_path(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011358 const struct proxy *defpx, const char *file, int line,
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010011359 char **err)
11360{
11361 char *path;
11362 char *type = "path";
Tim Duesterhus621e74a2021-01-03 20:04:36 +010011363 struct prepend_path *p = NULL;
Bertrand Jacquin7fbc7702021-11-24 21:16:06 +000011364 size_t i;
Thierry Fournier59f11be2020-11-29 00:37:41 +010011365
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010011366 if (too_many_args(2, args, err, NULL)) {
Tim Duesterhus621e74a2021-01-03 20:04:36 +010011367 goto err;
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010011368 }
11369
11370 if (!(*args[1])) {
11371 memprintf(err, "'%s' expects to receive a <path> as argument", args[0]);
Tim Duesterhus621e74a2021-01-03 20:04:36 +010011372 goto err;
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010011373 }
11374 path = args[1];
11375
11376 if (*args[2]) {
11377 if (strcmp(args[2], "path") != 0 && strcmp(args[2], "cpath") != 0) {
11378 memprintf(err, "'%s' expects <type> to either be 'path' or 'cpath'", args[0]);
Tim Duesterhus621e74a2021-01-03 20:04:36 +010011379 goto err;
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010011380 }
11381 type = args[2];
11382 }
11383
Thierry Fournier59f11be2020-11-29 00:37:41 +010011384 p = calloc(1, sizeof(*p));
11385 if (p == NULL) {
Tim Duesterhusf89d43a2021-01-03 20:04:37 +010011386 memprintf(err, "memory allocation failed");
Tim Duesterhus621e74a2021-01-03 20:04:36 +010011387 goto err;
Thierry Fournier59f11be2020-11-29 00:37:41 +010011388 }
11389 p->path = strdup(path);
11390 if (p->path == NULL) {
Tim Duesterhusf89d43a2021-01-03 20:04:37 +010011391 memprintf(err, "memory allocation failed");
Tim Duesterhus621e74a2021-01-03 20:04:36 +010011392 goto err2;
Thierry Fournier59f11be2020-11-29 00:37:41 +010011393 }
11394 p->type = strdup(type);
11395 if (p->type == NULL) {
Tim Duesterhusf89d43a2021-01-03 20:04:37 +010011396 memprintf(err, "memory allocation failed");
Tim Duesterhus621e74a2021-01-03 20:04:36 +010011397 goto err2;
Thierry Fournier59f11be2020-11-29 00:37:41 +010011398 }
Willy Tarreau2b718102021-04-21 07:32:39 +020011399 LIST_APPEND(&prepend_path_list, &p->l);
Thierry Fournier59f11be2020-11-29 00:37:41 +010011400
Tim Duesterhus9e5e5862021-10-11 18:51:08 +020011401 /* Handle the global state and the per-thread state for the first
11402 * thread. The remaining threads will be initialized based on
11403 * prepend_path_list.
11404 */
Bertrand Jacquin7fbc7702021-11-24 21:16:06 +000011405 for (i = 0; i < 2; i++) {
Tim Duesterhus9e5e5862021-10-11 18:51:08 +020011406 lua_State *L = hlua_states[i];
11407 const char *error;
11408
11409 if (setjmp(safe_ljmp_env) != 0) {
11410 lua_atpanic(L, hlua_panic_safe);
11411 if (lua_type(L, -1) == LUA_TSTRING)
11412 error = lua_tostring(L, -1);
11413 else
11414 error = "critical error";
11415 fprintf(stderr, "lua-prepend-path: %s.\n", error);
11416 exit(1);
11417 } else {
11418 lua_atpanic(L, hlua_panic_ljmp);
11419 }
11420
11421 hlua_prepend_path(L, type, path);
11422
11423 lua_atpanic(L, hlua_panic_safe);
11424 }
11425
Thierry Fournier59f11be2020-11-29 00:37:41 +010011426 return 0;
Tim Duesterhus621e74a2021-01-03 20:04:36 +010011427
11428err2:
11429 free(p->type);
11430 free(p->path);
11431err:
11432 free(p);
11433 return -1;
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010011434}
11435
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011436/* configuration keywords declaration */
11437static struct cfg_kw_list cfg_kws = {{ },{
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010011438 { CFG_GLOBAL, "lua-prepend-path", hlua_config_prepend_path },
Thierry FOURNIERbd413492015-03-03 16:52:26 +010011439 { CFG_GLOBAL, "lua-load", hlua_load },
Thierry Fournier59f11be2020-11-29 00:37:41 +010011440 { CFG_GLOBAL, "lua-load-per-thread", hlua_load_per_thread },
Thierry FOURNIERbd413492015-03-03 16:52:26 +010011441 { CFG_GLOBAL, "tune.lua.session-timeout", hlua_session_timeout },
11442 { CFG_GLOBAL, "tune.lua.task-timeout", hlua_task_timeout },
Thierry FOURNIER56da1012015-10-01 08:42:31 +020011443 { CFG_GLOBAL, "tune.lua.service-timeout", hlua_applet_timeout },
Thierry FOURNIERee9f8022015-03-03 17:37:37 +010011444 { CFG_GLOBAL, "tune.lua.forced-yield", hlua_forced_yield },
Willy Tarreau32f61e22015-03-18 17:54:59 +010011445 { CFG_GLOBAL, "tune.lua.maxmem", hlua_parse_maxmem },
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011446 { 0, NULL, NULL },
11447}};
11448
Willy Tarreau0108d902018-11-25 19:14:37 +010011449INITCALL1(STG_REGISTER, cfg_register_keywords, &cfg_kws);
11450
William Lallemand52139182022-03-30 15:05:42 +020011451#ifdef USE_OPENSSL
Christopher Fauletafd8f102018-11-08 11:34:21 +010011452
William Lallemand30fcca12022-03-30 12:03:12 +020011453/*
11454 * This function replace a ckch_store by another one, and rebuild the ckch_inst and all its dependencies.
11455 * It does the sam as "cli_io_handler_commit_cert" but for lua, the major
11456 * difference is that the yield in lua and for the CLI is not handled the same
11457 * way.
11458 */
11459__LJMP static int hlua_ckch_commit_yield(lua_State *L, int status, lua_KContext ctx)
11460{
11461 struct ckch_inst **lua_ckchi = lua_touserdata(L, -1);
11462 struct ckch_store **lua_ckchs = lua_touserdata(L, -2);
11463 struct ckch_inst *ckchi = *lua_ckchi;
11464 struct ckch_store *old_ckchs = lua_ckchs[0];
11465 struct ckch_store *new_ckchs = lua_ckchs[1];
11466 struct hlua *hlua;
11467 char *err = NULL;
11468 int y = 1;
11469
11470 hlua = hlua_gethlua(L);
11471
11472 /* get the first ckchi to copy */
11473 if (ckchi == NULL)
11474 ckchi = LIST_ELEM(old_ckchs->ckch_inst.n, typeof(ckchi), by_ckchs);
11475
11476 /* walk through the old ckch_inst and creates new ckch_inst using the updated ckchs */
11477 list_for_each_entry_from(ckchi, &old_ckchs->ckch_inst, by_ckchs) {
11478 struct ckch_inst *new_inst;
11479
11480 /* it takes a lot of CPU to creates SSL_CTXs, so we yield every 10 CKCH instances */
11481 if (y % 10 == 0) {
11482
11483 *lua_ckchi = ckchi;
11484
11485 task_wakeup(hlua->task, TASK_WOKEN_MSG);
11486 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_ckch_commit_yield, TICK_ETERNITY, 0));
11487 }
11488
11489 if (ckch_inst_rebuild(new_ckchs, ckchi, &new_inst, &err))
11490 goto error;
11491
11492 /* link the new ckch_inst to the duplicate */
11493 LIST_APPEND(&new_ckchs->ckch_inst, &new_inst->by_ckchs);
11494 y++;
11495 }
11496
11497 /* The generation is finished, we can insert everything */
11498 ckch_store_replace(old_ckchs, new_ckchs);
11499
11500 lua_pop(L, 2); /* pop the lua_ckchs and ckchi */
11501
11502 HA_SPIN_UNLOCK(CKCH_LOCK, &ckch_lock);
11503
11504 return 0;
11505
11506error:
11507 ckch_store_free(new_ckchs);
11508 HA_SPIN_UNLOCK(CKCH_LOCK, &ckch_lock);
11509 WILL_LJMP(luaL_error(L, "%s", err));
11510 free(err);
11511
11512 return 0;
11513}
11514
11515/*
11516 * Replace a ckch_store <filename> in the ckchs_tree with a ckch_store created
11517 * from the table in parameter.
11518 *
11519 * This is equivalent to "set ssl cert" + "commit ssl cert" over the CLI, which
11520 * means it does not need to have a transaction since everything is done in the
11521 * same function.
11522 *
11523 * CertCache.set{filename="", crt="", key="", sctl="", ocsp="", issuer=""}
11524 *
11525 */
11526__LJMP static int hlua_ckch_set(lua_State *L)
11527{
11528 struct hlua *hlua;
11529 struct ckch_inst **lua_ckchi;
11530 struct ckch_store **lua_ckchs;
11531 struct ckch_store *old_ckchs = NULL;
11532 struct ckch_store *new_ckchs = NULL;
11533 int errcode = 0;
11534 char *err = NULL;
11535 struct cert_exts *cert_ext = NULL;
11536 char *filename;
11537 struct cert_key_and_chain *ckch;
11538 int ret;
11539
11540 if (lua_type(L, -1) != LUA_TTABLE)
11541 WILL_LJMP(luaL_error(L, "'CertCache.set' needs a table as argument"));
11542
11543 hlua = hlua_gethlua(L);
11544
11545 /* FIXME: this should not return an error but should come back later */
11546 if (HA_SPIN_TRYLOCK(CKCH_LOCK, &ckch_lock))
11547 WILL_LJMP(luaL_error(L, "CertCache already under lock"));
11548
11549 ret = lua_getfield(L, -1, "filename");
11550 if (ret != LUA_TSTRING) {
11551 memprintf(&err, "%sNo filename specified!\n", err ? err : "");
11552 errcode |= ERR_ALERT | ERR_FATAL;
11553 goto end;
11554 }
11555 filename = (char *)lua_tostring(L, -1);
11556
11557
11558 /* look for the filename in the tree */
11559 old_ckchs = ckchs_lookup(filename);
11560 if (!old_ckchs) {
11561 memprintf(&err, "%sCan't replace a certificate which is not referenced by the configuration!\n", err ? err : "");
11562 errcode |= ERR_ALERT | ERR_FATAL;
11563 goto end;
11564 }
11565 /* TODO: handle extra_files_noext */
11566
11567 new_ckchs = ckchs_dup(old_ckchs);
11568 if (!new_ckchs) {
11569 memprintf(&err, "%sCannot allocate memory!\n", err ? err : "");
11570 errcode |= ERR_ALERT | ERR_FATAL;
11571 goto end;
11572 }
11573
11574 ckch = new_ckchs->ckch;
11575
11576 /* loop on the field in the table, which have the same name as the
11577 * possible extensions of files */
11578 lua_pushnil(L);
11579 while (lua_next(L, 1)) {
11580 int i;
11581 const char *field = lua_tostring(L, -2);
11582 char *payload = (char *)lua_tostring(L, -1);
11583
11584 if (!field || strcmp(field, "filename") == 0) {
11585 lua_pop(L, 1);
11586 continue;
11587 }
11588
11589 for (i = 0; field && cert_exts[i].ext != NULL; i++) {
11590 if (strcmp(field, cert_exts[i].ext) == 0) {
11591 cert_ext = &cert_exts[i];
11592 break;
11593 }
11594 }
11595
11596 /* this is the default type, the field is not supported */
11597 if (cert_ext == NULL) {
11598 memprintf(&err, "%sUnsupported field '%s'\n", err ? err : "", field);
11599 errcode |= ERR_ALERT | ERR_FATAL;
11600 goto end;
11601 }
11602
11603 /* appply the change on the duplicate */
William Lallemandd8c195a2022-05-26 11:20:13 +020011604 if (cert_ext->load(filename, payload, ckch, &err) != 0) {
11605 memprintf(&err, "%sCan't load the payload for '%s'\n", err ? err : "", cert_ext->ext);
William Lallemand30fcca12022-03-30 12:03:12 +020011606 errcode |= ERR_ALERT | ERR_FATAL;
11607 goto end;
11608 }
11609 lua_pop(L, 1);
11610 }
11611
11612 /* store the pointers on the lua stack */
11613 lua_ckchs = lua_newuserdata(L, sizeof(struct ckch_store *) * 2);
11614 lua_ckchs[0] = old_ckchs;
11615 lua_ckchs[1] = new_ckchs;
11616 lua_ckchi = lua_newuserdata(L, sizeof(struct ckch_inst *));
11617 *lua_ckchi = NULL;
11618
11619 task_wakeup(hlua->task, TASK_WOKEN_MSG);
11620 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_ckch_commit_yield, TICK_ETERNITY, 0));
11621
11622end:
11623 HA_SPIN_UNLOCK(CKCH_LOCK, &ckch_lock);
11624
11625 if (errcode & ERR_CODE) {
11626 ckch_store_free(new_ckchs);
11627 WILL_LJMP(luaL_error(L, "%s", err));
11628 }
11629 free(err);
11630
11631 return 0;
11632}
11633
William Lallemand52139182022-03-30 15:05:42 +020011634#else
11635
11636__LJMP static int hlua_ckch_set(lua_State *L)
11637{
11638 WILL_LJMP(luaL_error(L, "'CertCache.set' needs an HAProxy built with OpenSSL"));
11639
11640 return 0;
11641}
11642#endif /* ! USE_OPENSSL */
11643
11644
11645
Thierry FOURNIERbabae282015-09-17 11:36:37 +020011646/* This function can fail with an abort() due to an Lua critical error.
11647 * We are in the initialisation process of HAProxy, this abort() is
11648 * tolerated.
11649 */
Thierry Fournierb8cef172020-11-28 15:37:17 +010011650int hlua_post_init_state(lua_State *L)
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010011651{
11652 struct hlua_init_function *init;
11653 const char *msg;
11654 enum hlua_exec ret;
Thierry Fournierfd107a22016-02-19 19:57:23 +010011655 const char *error;
Thierry Fournier670db242020-11-28 10:49:59 +010011656 const char *kind;
11657 const char *trace;
11658 int return_status = 1;
11659#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM >= 504
11660 int nres;
11661#endif
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010011662
Willy Tarreaucdb53462020-12-02 12:12:00 +010011663 /* disable memory limit checks if limit is not set */
11664 if (!hlua_global_allocator.limit)
11665 hlua_global_allocator.limit = ~hlua_global_allocator.limit;
11666
Ilya Shipitsin856aabc2020-04-16 23:51:34 +050011667 /* Call post initialisation function in safe environment. */
Thierry Fournier3c539322020-11-28 16:05:05 +010011668 if (setjmp(safe_ljmp_env) != 0) {
11669 lua_atpanic(L, hlua_panic_safe);
Thierry Fournierb8cef172020-11-28 15:37:17 +010011670 if (lua_type(L, -1) == LUA_TSTRING)
11671 error = lua_tostring(L, -1);
Thierry Fournier3d4a6752016-02-19 20:53:30 +010011672 else
11673 error = "critical error";
11674 fprintf(stderr, "Lua post-init: %s.\n", error);
11675 exit(1);
Thierry Fournier3c539322020-11-28 16:05:05 +010011676 } else {
11677 lua_atpanic(L, hlua_panic_ljmp);
Thierry Fournier3d4a6752016-02-19 20:53:30 +010011678 }
Frédéric Lécaille54f2bcf2018-08-29 13:46:24 +020011679
Thierry Fournierb8cef172020-11-28 15:37:17 +010011680 hlua_fcn_post_init(L);
Thierry Fournier3d4a6752016-02-19 20:53:30 +010011681
Thierry Fournierc7492592020-11-28 23:57:24 +010011682 list_for_each_entry(init, &hlua_init_functions[hlua_state_id], l) {
Thierry Fournierb8cef172020-11-28 15:37:17 +010011683 lua_rawgeti(L, LUA_REGISTRYINDEX, init->function_ref);
Thierry Fournier670db242020-11-28 10:49:59 +010011684
11685#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM >= 504
Thierry Fournierb8cef172020-11-28 15:37:17 +010011686 ret = lua_resume(L, L, 0, &nres);
Thierry Fournier670db242020-11-28 10:49:59 +010011687#else
Thierry Fournierb8cef172020-11-28 15:37:17 +010011688 ret = lua_resume(L, L, 0);
Thierry Fournier670db242020-11-28 10:49:59 +010011689#endif
11690 kind = NULL;
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010011691 switch (ret) {
Thierry Fournier670db242020-11-28 10:49:59 +010011692
11693 case LUA_OK:
Thierry Fournierb8cef172020-11-28 15:37:17 +010011694 lua_pop(L, -1);
Thierry Fournier13d08b72020-11-28 11:02:58 +010011695 break;
Thierry Fournier670db242020-11-28 10:49:59 +010011696
11697 case LUA_ERRERR:
11698 kind = "message handler error";
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -070011699 /* Fall through */
Thierry Fournier670db242020-11-28 10:49:59 +010011700 case LUA_ERRRUN:
11701 if (!kind)
11702 kind = "runtime error";
Thierry Fournierb8cef172020-11-28 15:37:17 +010011703 msg = lua_tostring(L, -1);
11704 lua_settop(L, 0); /* Empty the stack. */
11705 lua_pop(L, 1);
Christopher Fauletd09cc512021-03-24 14:48:45 +010011706 trace = hlua_traceback(L, ", ");
Thierry Fournier670db242020-11-28 10:49:59 +010011707 if (msg)
11708 ha_alert("Lua init: %s: '%s' from %s\n", kind, msg, trace);
11709 else
11710 ha_alert("Lua init: unknown %s from %s\n", kind, trace);
11711 return_status = 0;
11712 break;
11713
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010011714 default:
Thierry Fournier670db242020-11-28 10:49:59 +010011715 /* Unknown error */
11716 kind = "Unknown error";
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -070011717 /* Fall through */
Thierry Fournier670db242020-11-28 10:49:59 +010011718 case LUA_YIELD:
11719 /* yield is not configured at this step, this state doesn't happen */
11720 if (!kind)
11721 kind = "yield not allowed";
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -070011722 /* Fall through */
Thierry Fournier670db242020-11-28 10:49:59 +010011723 case LUA_ERRMEM:
11724 if (!kind)
11725 kind = "out of memory error";
Thierry Fournierb8cef172020-11-28 15:37:17 +010011726 lua_settop(L, 0);
11727 lua_pop(L, 1);
Christopher Fauletd09cc512021-03-24 14:48:45 +010011728 trace = hlua_traceback(L, ", ");
Thierry Fournier670db242020-11-28 10:49:59 +010011729 ha_alert("Lua init: %s: %s\n", kind, trace);
11730 return_status = 0;
11731 break;
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010011732 }
Thierry Fournier670db242020-11-28 10:49:59 +010011733 if (!return_status)
11734 break;
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010011735 }
Thierry Fournier3c539322020-11-28 16:05:05 +010011736
11737 lua_atpanic(L, hlua_panic_safe);
Thierry Fournier670db242020-11-28 10:49:59 +010011738 return return_status;
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010011739}
11740
Thierry Fournierb8cef172020-11-28 15:37:17 +010011741int hlua_post_init()
11742{
Thierry Fournier59f11be2020-11-29 00:37:41 +010011743 int ret;
11744 int i;
11745 int errors;
11746 char *err = NULL;
11747 struct hlua_function *fcn;
Christopher Faulet69c581a2021-05-31 08:54:04 +020011748 struct hlua_reg_filter *reg_flt;
Thierry Fournier59f11be2020-11-29 00:37:41 +010011749
Willy Tarreaub1310492021-08-30 09:35:18 +020011750#if defined(USE_OPENSSL)
Thierry Fournierb8cef172020-11-28 15:37:17 +010011751 /* Initialize SSL server. */
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010011752 if (socket_ssl->xprt->prepare_srv) {
Thierry Fournierb8cef172020-11-28 15:37:17 +010011753 int saved_used_backed = global.ssl_used_backend;
11754 // don't affect maxconn automatic computation
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010011755 socket_ssl->xprt->prepare_srv(socket_ssl);
Thierry Fournierb8cef172020-11-28 15:37:17 +010011756 global.ssl_used_backend = saved_used_backed;
11757 }
11758#endif
11759
Thierry Fournierc7492592020-11-28 23:57:24 +010011760 /* Perform post init of common thread */
11761 hlua_state_id = 0;
Willy Tarreau43ab05b2021-09-28 09:43:11 +020011762 ha_set_thread(&ha_thread_info[0]);
Thierry Fournier59f11be2020-11-29 00:37:41 +010011763 ret = hlua_post_init_state(hlua_states[hlua_state_id]);
11764 if (ret == 0)
11765 return 0;
11766
11767 /* init remaining lua states and load files */
11768 for (hlua_state_id = 2; hlua_state_id < global.nbthread + 1; hlua_state_id++) {
11769
11770 /* set thread context */
Willy Tarreau43ab05b2021-09-28 09:43:11 +020011771 ha_set_thread(&ha_thread_info[hlua_state_id - 1]);
Thierry Fournier59f11be2020-11-29 00:37:41 +010011772
11773 /* Init lua state */
11774 hlua_states[hlua_state_id] = hlua_init_state(hlua_state_id);
11775
11776 /* Load lua files */
11777 for (i = 0; per_thread_load && per_thread_load[i]; i++) {
11778 ret = hlua_load_state(per_thread_load[i], hlua_states[hlua_state_id], &err);
11779 if (ret != 0) {
11780 ha_alert("Lua init: %s\n", err);
11781 return 0;
11782 }
11783 }
11784 }
11785
11786 /* Reset thread context */
Willy Tarreau43ab05b2021-09-28 09:43:11 +020011787 ha_set_thread(NULL);
Thierry Fournier59f11be2020-11-29 00:37:41 +010011788
11789 /* Execute post init for all states */
11790 for (hlua_state_id = 1; hlua_state_id < global.nbthread + 1; hlua_state_id++) {
11791
11792 /* set thread context */
Willy Tarreau43ab05b2021-09-28 09:43:11 +020011793 ha_set_thread(&ha_thread_info[hlua_state_id - 1]);
Thierry Fournier59f11be2020-11-29 00:37:41 +010011794
11795 /* run post init */
11796 ret = hlua_post_init_state(hlua_states[hlua_state_id]);
11797 if (ret == 0)
11798 return 0;
11799 }
11800
11801 /* Reset thread context */
Willy Tarreau43ab05b2021-09-28 09:43:11 +020011802 ha_set_thread(NULL);
Thierry Fournier59f11be2020-11-29 00:37:41 +010011803
11804 /* control functions registering. Each function must have:
11805 * - only the function_ref[0] set positive and all other to -1
11806 * - only the function_ref[0] set to -1 and all other positive
11807 * This ensure a same reference is not used both in shared
11808 * lua state and thread dedicated lua state. Note: is the case
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +050011809 * reach, the shared state is priority, but the bug will be
Thierry Fournier59f11be2020-11-29 00:37:41 +010011810 * complicated to found for the end user.
11811 */
11812 errors = 0;
11813 list_for_each_entry(fcn, &referenced_functions, l) {
11814 ret = 0;
11815 for (i = 1; i < global.nbthread + 1; i++) {
11816 if (fcn->function_ref[i] == -1)
11817 ret--;
11818 else
11819 ret++;
11820 }
11821 if (abs(ret) != global.nbthread) {
11822 ha_alert("Lua function '%s' is not referenced in all thread. "
11823 "Expect function in all thread or in none thread.\n", fcn->name);
11824 errors++;
11825 continue;
11826 }
11827
11828 if ((fcn->function_ref[0] == -1) == (ret < 0)) {
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +050011829 ha_alert("Lua function '%s' is referenced both ins shared Lua context (through lua-load) "
11830 "and per-thread Lua context (through lua-load-per-thread). these two context "
Thierry Fournier59f11be2020-11-29 00:37:41 +010011831 "exclusive.\n", fcn->name);
11832 errors++;
11833 }
11834 }
11835
Christopher Faulet69c581a2021-05-31 08:54:04 +020011836 /* Do the same with registered filters */
11837 list_for_each_entry(reg_flt, &referenced_filters, l) {
11838 ret = 0;
11839 for (i = 1; i < global.nbthread + 1; i++) {
11840 if (reg_flt->flt_ref[i] == -1)
11841 ret--;
11842 else
11843 ret++;
11844 }
11845 if (abs(ret) != global.nbthread) {
11846 ha_alert("Lua filter '%s' is not referenced in all thread. "
11847 "Expect function in all thread or in none thread.\n", reg_flt->name);
11848 errors++;
11849 continue;
11850 }
11851
11852 if ((reg_flt->flt_ref[0] == -1) == (ret < 0)) {
11853 ha_alert("Lua filter '%s' is referenced both ins shared Lua context (through lua-load) "
11854 "and per-thread Lua context (through lua-load-per-thread). these two context "
11855 "exclusive.\n", fcn->name);
11856 errors++;
11857 }
11858 }
11859
11860
Thierry Fournier59f11be2020-11-29 00:37:41 +010011861 if (errors > 0)
11862 return 0;
11863
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +050011864 /* after this point, this global will no longer be used, so set to
Thierry Fournier59f11be2020-11-29 00:37:41 +010011865 * -1 in order to have probably a segfault if someone use it
11866 */
11867 hlua_state_id = -1;
11868
11869 return 1;
Thierry Fournierb8cef172020-11-28 15:37:17 +010011870}
11871
Willy Tarreau32f61e22015-03-18 17:54:59 +010011872/* The memory allocator used by the Lua stack. <ud> is a pointer to the
11873 * allocator's context. <ptr> is the pointer to alloc/free/realloc. <osize>
11874 * is the previously allocated size or the kind of object in case of a new
Willy Tarreaud36c7fa2020-12-02 12:26:29 +010011875 * allocation. <nsize> is the requested new size. A new allocation is
11876 * indicated by <ptr> being NULL. A free is indicated by <nsize> being
Willy Tarreaucdb53462020-12-02 12:12:00 +010011877 * zero. This one verifies that the limits are respected but is optimized
11878 * for the fast case where limits are not used, hence stats are not updated.
Willy Tarreaua5efdff2021-10-22 16:00:02 +020011879 *
11880 * Warning: while this API ressembles glibc's realloc() a lot, glibc surpasses
11881 * POSIX by making realloc(ptr,0) an effective free(), but others do not do
11882 * that and will simply allocate zero as if it were the result of malloc(0),
11883 * so mapping this onto realloc() will lead to memory leaks on non-glibc
11884 * systems.
Willy Tarreau32f61e22015-03-18 17:54:59 +010011885 */
11886static void *hlua_alloc(void *ud, void *ptr, size_t osize, size_t nsize)
11887{
11888 struct hlua_mem_allocator *zone = ud;
Willy Tarreaucdb53462020-12-02 12:12:00 +010011889 size_t limit, old, new;
11890
11891 /* a limit of ~0 means unlimited and boot complete, so there's no need
11892 * for accounting anymore.
11893 */
Willy Tarreaua5efdff2021-10-22 16:00:02 +020011894 if (likely(~zone->limit == 0)) {
11895 if (!nsize)
11896 ha_free(&ptr);
11897 else
11898 ptr = realloc(ptr, nsize);
11899 return ptr;
11900 }
Willy Tarreau32f61e22015-03-18 17:54:59 +010011901
Willy Tarreaud36c7fa2020-12-02 12:26:29 +010011902 if (!ptr)
11903 osize = 0;
Willy Tarreau32f61e22015-03-18 17:54:59 +010011904
Willy Tarreaucdb53462020-12-02 12:12:00 +010011905 /* enforce strict limits across all threads */
11906 limit = zone->limit;
11907 old = _HA_ATOMIC_LOAD(&zone->allocated);
11908 do {
11909 new = old + nsize - osize;
11910 if (unlikely(nsize && limit && new > limit))
11911 return NULL;
11912 } while (!_HA_ATOMIC_CAS(&zone->allocated, &old, new));
Willy Tarreau32f61e22015-03-18 17:54:59 +010011913
Willy Tarreaua5efdff2021-10-22 16:00:02 +020011914 if (!nsize)
11915 ha_free(&ptr);
11916 else
11917 ptr = realloc(ptr, nsize);
Willy Tarreaucdb53462020-12-02 12:12:00 +010011918
11919 if (unlikely(!ptr && nsize)) // failed
11920 _HA_ATOMIC_SUB(&zone->allocated, nsize - osize);
11921
11922 __ha_barrier_atomic_store();
Willy Tarreau32f61e22015-03-18 17:54:59 +010011923 return ptr;
11924}
11925
Thierry Fournierecb83c22020-11-28 15:49:44 +010011926/* This function can fail with an abort() due to a Lua critical error.
Thierry FOURNIERbabae282015-09-17 11:36:37 +020011927 * We are in the initialisation process of HAProxy, this abort() is
11928 * tolerated.
11929 */
Thierry Fournierecb83c22020-11-28 15:49:44 +010011930lua_State *hlua_init_state(int thread_num)
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +010011931{
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010011932 int i;
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010011933 int idx;
11934 struct sample_fetch *sf;
Thierry FOURNIER594afe72015-03-10 23:58:30 +010011935 struct sample_conv *sc;
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010011936 char *p;
Thierry Fournierfd107a22016-02-19 19:57:23 +010011937 const char *error_msg;
Thierry Fournier4234dbd2020-11-28 13:18:23 +010011938 void **context;
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011939 lua_State *L;
Thierry Fournier59f11be2020-11-29 00:37:41 +010011940 struct prepend_path *pp;
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010011941
Thierry FOURNIER380d0932015-01-23 14:27:52 +010011942 /* Init main lua stack. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011943 L = lua_newstate(hlua_alloc, &hlua_global_allocator);
Thierry FOURNIER380d0932015-01-23 14:27:52 +010011944
Thierry Fournier4234dbd2020-11-28 13:18:23 +010011945 /* Initialise Lua context to NULL */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011946 context = lua_getextraspace(L);
Thierry Fournier4234dbd2020-11-28 13:18:23 +010011947 *context = NULL;
11948
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -080011949 /* From this point, until the end of the initialisation function,
Thierry FOURNIERbabae282015-09-17 11:36:37 +020011950 * the Lua function can fail with an abort. We are in the initialisation
11951 * process of HAProxy, this abort() is tolerated.
11952 */
11953
Thierry Fournier3c539322020-11-28 16:05:05 +010011954 /* Call post initialisation function in safe environment. */
11955 if (setjmp(safe_ljmp_env) != 0) {
11956 lua_atpanic(L, hlua_panic_safe);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011957 if (lua_type(L, -1) == LUA_TSTRING)
11958 error_msg = lua_tostring(L, -1);
Thierry Fournier2f05cc62020-11-28 16:08:02 +010011959 else
11960 error_msg = "critical error";
11961 fprintf(stderr, "Lua init: %s.\n", error_msg);
11962 exit(1);
Thierry Fournier3c539322020-11-28 16:05:05 +010011963 } else {
11964 lua_atpanic(L, hlua_panic_ljmp);
Thierry Fournier2f05cc62020-11-28 16:08:02 +010011965 }
11966
Thierry FOURNIER380d0932015-01-23 14:27:52 +010011967 /* Initialise lua. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011968 luaL_openlibs(L);
Tim Duesterhus541fe1e2020-01-12 13:55:41 +010011969#define HLUA_PREPEND_PATH_TOSTRING1(x) #x
11970#define HLUA_PREPEND_PATH_TOSTRING(x) HLUA_PREPEND_PATH_TOSTRING1(x)
11971#ifdef HLUA_PREPEND_PATH
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011972 hlua_prepend_path(L, "path", HLUA_PREPEND_PATH_TOSTRING(HLUA_PREPEND_PATH));
Tim Duesterhus541fe1e2020-01-12 13:55:41 +010011973#endif
11974#ifdef HLUA_PREPEND_CPATH
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011975 hlua_prepend_path(L, "cpath", HLUA_PREPEND_PATH_TOSTRING(HLUA_PREPEND_CPATH));
Tim Duesterhus541fe1e2020-01-12 13:55:41 +010011976#endif
11977#undef HLUA_PREPEND_PATH_TOSTRING
11978#undef HLUA_PREPEND_PATH_TOSTRING1
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010011979
Thierry Fournier59f11be2020-11-29 00:37:41 +010011980 /* Apply configured prepend path */
11981 list_for_each_entry(pp, &prepend_path_list, l)
11982 hlua_prepend_path(L, pp->type, pp->path);
11983
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010011984 /*
11985 *
11986 * Create "core" object.
11987 *
11988 */
11989
Thierry FOURNIERa2d8c652015-03-11 17:29:39 +010011990 /* This table entry is the object "core" base. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011991 lua_newtable(L);
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010011992
Thierry Fournierecb83c22020-11-28 15:49:44 +010011993 /* set the thread id */
11994 hlua_class_const_int(L, "thread", thread_num);
11995
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010011996 /* Push the loglevel constants. */
Willy Tarreau80f5fae2015-02-27 16:38:20 +010011997 for (i = 0; i < NB_LOG_LEVELS; i++)
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011998 hlua_class_const_int(L, log_levels[i], i);
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010011999
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010012000 /* Register special functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012001 hlua_class_function(L, "register_init", hlua_register_init);
12002 hlua_class_function(L, "register_task", hlua_register_task);
12003 hlua_class_function(L, "register_fetches", hlua_register_fetches);
12004 hlua_class_function(L, "register_converters", hlua_register_converters);
12005 hlua_class_function(L, "register_action", hlua_register_action);
12006 hlua_class_function(L, "register_service", hlua_register_service);
12007 hlua_class_function(L, "register_cli", hlua_register_cli);
Christopher Faulet69c581a2021-05-31 08:54:04 +020012008 hlua_class_function(L, "register_filter", hlua_register_filter);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012009 hlua_class_function(L, "yield", hlua_yield);
12010 hlua_class_function(L, "set_nice", hlua_set_nice);
12011 hlua_class_function(L, "sleep", hlua_sleep);
12012 hlua_class_function(L, "msleep", hlua_msleep);
12013 hlua_class_function(L, "add_acl", hlua_add_acl);
12014 hlua_class_function(L, "del_acl", hlua_del_acl);
12015 hlua_class_function(L, "set_map", hlua_set_map);
12016 hlua_class_function(L, "del_map", hlua_del_map);
12017 hlua_class_function(L, "tcp", hlua_socket_new);
William Lallemand3956c4e2021-09-21 16:25:15 +020012018 hlua_class_function(L, "httpclient", hlua_httpclient_new);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012019 hlua_class_function(L, "log", hlua_log);
12020 hlua_class_function(L, "Debug", hlua_log_debug);
12021 hlua_class_function(L, "Info", hlua_log_info);
12022 hlua_class_function(L, "Warning", hlua_log_warning);
12023 hlua_class_function(L, "Alert", hlua_log_alert);
12024 hlua_class_function(L, "done", hlua_done);
12025 hlua_fcn_reg_core_fcn(L);
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010012026
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012027 lua_setglobal(L, "core");
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010012028
12029 /*
12030 *
Christopher Faulet0f3c8902020-01-31 18:57:12 +010012031 * Create "act" object.
12032 *
12033 */
12034
12035 /* This table entry is the object "act" base. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012036 lua_newtable(L);
Christopher Faulet0f3c8902020-01-31 18:57:12 +010012037
12038 /* push action return constants */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012039 hlua_class_const_int(L, "CONTINUE", ACT_RET_CONT);
12040 hlua_class_const_int(L, "STOP", ACT_RET_STOP);
12041 hlua_class_const_int(L, "YIELD", ACT_RET_YIELD);
12042 hlua_class_const_int(L, "ERROR", ACT_RET_ERR);
12043 hlua_class_const_int(L, "DONE", ACT_RET_DONE);
12044 hlua_class_const_int(L, "DENY", ACT_RET_DENY);
12045 hlua_class_const_int(L, "ABORT", ACT_RET_ABRT);
12046 hlua_class_const_int(L, "INVALID", ACT_RET_INV);
Christopher Faulet0f3c8902020-01-31 18:57:12 +010012047
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012048 hlua_class_function(L, "wake_time", hlua_set_wake_time);
Christopher Faulet2c2c2e32020-01-31 19:07:52 +010012049
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012050 lua_setglobal(L, "act");
Christopher Faulet0f3c8902020-01-31 18:57:12 +010012051
12052 /*
12053 *
Christopher Faulet69c581a2021-05-31 08:54:04 +020012054 * Create "Filter" object.
12055 *
12056 */
12057
12058 /* This table entry is the object "filter" base. */
12059 lua_newtable(L);
12060
12061 /* push flags and constants */
12062 hlua_class_const_int(L, "CONTINUE", 1);
12063 hlua_class_const_int(L, "WAIT", 0);
12064 hlua_class_const_int(L, "ERROR", -1);
12065
12066 hlua_class_const_int(L, "FLT_CFG_FL_HTX", FLT_CFG_FL_HTX);
12067
Christopher Fauletc404f112020-02-26 15:03:09 +010012068 hlua_class_function(L, "wake_time", hlua_set_wake_time);
12069 hlua_class_function(L, "register_data_filter", hlua_register_data_filter);
12070 hlua_class_function(L, "unregister_data_filter", hlua_unregister_data_filter);
12071
Christopher Faulet69c581a2021-05-31 08:54:04 +020012072 lua_setglobal(L, "filter");
12073
12074 /*
12075 *
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012076 * Register class Map
12077 *
12078 */
12079
12080 /* This table entry is the object "Map" base. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012081 lua_newtable(L);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012082
12083 /* register pattern types. */
12084 for (i=0; i<PAT_MATCH_NUM; i++)
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012085 hlua_class_const_int(L, pat_match_names[i], i);
Thierry FOURNIER4dc71972017-01-28 08:33:08 +010012086 for (i=0; i<PAT_MATCH_NUM; i++) {
Willy Tarreau843b7cb2018-07-13 10:54:26 +020012087 snprintf(trash.area, trash.size, "_%s", pat_match_names[i]);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012088 hlua_class_const_int(L, trash.area, i);
Thierry FOURNIER4dc71972017-01-28 08:33:08 +010012089 }
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012090
12091 /* register constructor. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012092 hlua_class_function(L, "new", hlua_map_new);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012093
12094 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012095 lua_newtable(L);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012096
Ilya Shipitsind4259502020-04-08 01:07:56 +050012097 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012098 lua_pushstring(L, "__index");
12099 lua_newtable(L);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012100
12101 /* Register . */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012102 hlua_class_function(L, "lookup", hlua_map_lookup);
12103 hlua_class_function(L, "slookup", hlua_map_slookup);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012104
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012105 lua_rawset(L, -3);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012106
Thierry Fournier45e78d72016-02-19 18:34:46 +010012107 /* Register previous table in the registry with reference and named entry.
12108 * The function hlua_register_metatable() pops the stack, so we
12109 * previously create a copy of the table.
12110 */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012111 lua_pushvalue(L, -1); /* Copy the -1 entry and push it on the stack. */
12112 class_map_ref = hlua_register_metatable(L, CLASS_MAP);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012113
12114 /* Assign the metatable to the mai Map object. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012115 lua_setmetatable(L, -2);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012116
12117 /* Set a name to the table. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012118 lua_setglobal(L, "Map");
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012119
12120 /*
12121 *
William Lallemand30fcca12022-03-30 12:03:12 +020012122 * Register "CertCache" class
12123 *
12124 */
12125
12126 /* Create and fill the metatable. */
12127 lua_newtable(L);
12128 /* Register */
12129 hlua_class_function(L, "set", hlua_ckch_set);
12130 lua_setglobal(L, CLASS_CERTCACHE); /* Create global object called Regex */
12131
12132 /*
12133 *
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010012134 * Register class Channel
12135 *
12136 */
12137
12138 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012139 lua_newtable(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010012140
Ilya Shipitsind4259502020-04-08 01:07:56 +050012141 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012142 lua_pushstring(L, "__index");
12143 lua_newtable(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010012144
12145 /* Register . */
Christopher Faulet6a79fc12021-08-06 16:02:36 +020012146 hlua_class_function(L, "data", hlua_channel_get_data);
12147 hlua_class_function(L, "line", hlua_channel_get_line);
12148 hlua_class_function(L, "set", hlua_channel_set_data);
12149 hlua_class_function(L, "remove", hlua_channel_del_data);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012150 hlua_class_function(L, "append", hlua_channel_append);
Christopher Faulet6a79fc12021-08-06 16:02:36 +020012151 hlua_class_function(L, "prepend", hlua_channel_prepend);
12152 hlua_class_function(L, "insert", hlua_channel_insert_data);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012153 hlua_class_function(L, "send", hlua_channel_send);
12154 hlua_class_function(L, "forward", hlua_channel_forward);
Christopher Faulet6a79fc12021-08-06 16:02:36 +020012155 hlua_class_function(L, "input", hlua_channel_get_in_len);
12156 hlua_class_function(L, "output", hlua_channel_get_out_len);
12157 hlua_class_function(L, "may_recv", hlua_channel_may_recv);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012158 hlua_class_function(L, "is_full", hlua_channel_is_full);
12159 hlua_class_function(L, "is_resp", hlua_channel_is_resp);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010012160
Christopher Faulet6a79fc12021-08-06 16:02:36 +020012161 /* Deprecated API */
12162 hlua_class_function(L, "get", hlua_channel_get);
12163 hlua_class_function(L, "dup", hlua_channel_dup);
12164 hlua_class_function(L, "getline", hlua_channel_getline);
12165 hlua_class_function(L, "get_in_len", hlua_channel_get_in_len);
12166 hlua_class_function(L, "get_out_len", hlua_channel_get_out_len);
12167
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012168 lua_rawset(L, -3);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010012169
12170 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012171 class_channel_ref = hlua_register_metatable(L, CLASS_CHANNEL);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010012172
12173 /*
12174 *
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010012175 * Register class Fetches
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010012176 *
12177 */
12178
12179 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012180 lua_newtable(L);
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010012181
Ilya Shipitsind4259502020-04-08 01:07:56 +050012182 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012183 lua_pushstring(L, "__index");
12184 lua_newtable(L);
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010012185
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010012186 /* Browse existing fetches and create the associated
12187 * object method.
12188 */
12189 sf = NULL;
12190 while ((sf = sample_fetch_getnext(sf, &idx)) != NULL) {
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010012191 /* gL.Tua doesn't support '.' and '-' in the function names, replace it
12192 * by an underscore.
12193 */
Willy Tarreau5ef96562021-08-26 16:48:53 +020012194 strlcpy2(trash.area, sf->kw, trash.size);
Willy Tarreau843b7cb2018-07-13 10:54:26 +020012195 for (p = trash.area; *p; p++)
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010012196 if (*p == '.' || *p == '-' || *p == '+')
12197 *p = '_';
12198
12199 /* Register the function. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012200 lua_pushstring(L, trash.area);
12201 lua_pushlightuserdata(L, sf);
12202 lua_pushcclosure(L, hlua_run_sample_fetch, 1);
12203 lua_rawset(L, -3);
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010012204 }
12205
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012206 lua_rawset(L, -3);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010012207
12208 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012209 class_fetches_ref = hlua_register_metatable(L, CLASS_FETCHES);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010012210
12211 /*
12212 *
Thierry FOURNIER594afe72015-03-10 23:58:30 +010012213 * Register class Converters
12214 *
12215 */
12216
12217 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012218 lua_newtable(L);
Thierry FOURNIER594afe72015-03-10 23:58:30 +010012219
12220 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012221 lua_pushstring(L, "__index");
12222 lua_newtable(L);
Thierry FOURNIER594afe72015-03-10 23:58:30 +010012223
12224 /* Browse existing converters and create the associated
12225 * object method.
12226 */
12227 sc = NULL;
12228 while ((sc = sample_conv_getnext(sc, &idx)) != NULL) {
Thierry FOURNIER594afe72015-03-10 23:58:30 +010012229 /* gL.Tua doesn't support '.' and '-' in the function names, replace it
12230 * by an underscore.
12231 */
Willy Tarreau5ef96562021-08-26 16:48:53 +020012232 strlcpy2(trash.area, sc->kw, trash.size);
Willy Tarreau843b7cb2018-07-13 10:54:26 +020012233 for (p = trash.area; *p; p++)
Thierry FOURNIER594afe72015-03-10 23:58:30 +010012234 if (*p == '.' || *p == '-' || *p == '+')
12235 *p = '_';
12236
12237 /* Register the function. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012238 lua_pushstring(L, trash.area);
12239 lua_pushlightuserdata(L, sc);
12240 lua_pushcclosure(L, hlua_run_sample_conv, 1);
12241 lua_rawset(L, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +010012242 }
12243
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012244 lua_rawset(L, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +010012245
12246 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012247 class_converters_ref = hlua_register_metatable(L, CLASS_CONVERTERS);
Thierry FOURNIER594afe72015-03-10 23:58:30 +010012248
12249 /*
12250 *
Thierry FOURNIER08504f42015-03-16 14:17:08 +010012251 * Register class HTTP
12252 *
12253 */
12254
12255 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012256 lua_newtable(L);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010012257
Ilya Shipitsind4259502020-04-08 01:07:56 +050012258 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012259 lua_pushstring(L, "__index");
12260 lua_newtable(L);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010012261
12262 /* Register Lua functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012263 hlua_class_function(L, "req_get_headers",hlua_http_req_get_headers);
12264 hlua_class_function(L, "req_del_header", hlua_http_req_del_hdr);
12265 hlua_class_function(L, "req_rep_header", hlua_http_req_rep_hdr);
12266 hlua_class_function(L, "req_rep_value", hlua_http_req_rep_val);
12267 hlua_class_function(L, "req_add_header", hlua_http_req_add_hdr);
12268 hlua_class_function(L, "req_set_header", hlua_http_req_set_hdr);
12269 hlua_class_function(L, "req_set_method", hlua_http_req_set_meth);
12270 hlua_class_function(L, "req_set_path", hlua_http_req_set_path);
12271 hlua_class_function(L, "req_set_query", hlua_http_req_set_query);
12272 hlua_class_function(L, "req_set_uri", hlua_http_req_set_uri);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010012273
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012274 hlua_class_function(L, "res_get_headers",hlua_http_res_get_headers);
12275 hlua_class_function(L, "res_del_header", hlua_http_res_del_hdr);
12276 hlua_class_function(L, "res_rep_header", hlua_http_res_rep_hdr);
12277 hlua_class_function(L, "res_rep_value", hlua_http_res_rep_val);
12278 hlua_class_function(L, "res_add_header", hlua_http_res_add_hdr);
12279 hlua_class_function(L, "res_set_header", hlua_http_res_set_hdr);
12280 hlua_class_function(L, "res_set_status", hlua_http_res_set_status);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010012281
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012282 lua_rawset(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010012283
12284 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012285 class_http_ref = hlua_register_metatable(L, CLASS_HTTP);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010012286
Christopher Fauletdf97ac42020-02-26 16:57:19 +010012287 /*
12288 *
12289 * Register class HTTPMessage
12290 *
12291 */
12292
12293 /* Create and fill the metatable. */
12294 lua_newtable(L);
12295
Ilya Shipitsinff0f2782021-08-22 22:18:07 +050012296 /* Create and fill the __index entry. */
Christopher Fauletdf97ac42020-02-26 16:57:19 +010012297 lua_pushstring(L, "__index");
12298 lua_newtable(L);
12299
12300 /* Register Lua functions. */
12301 hlua_class_function(L, "is_resp", hlua_http_msg_is_resp);
12302 hlua_class_function(L, "get_stline", hlua_http_msg_get_stline);
12303 hlua_class_function(L, "get_headers", hlua_http_msg_get_headers);
12304 hlua_class_function(L, "del_header", hlua_http_msg_del_hdr);
12305 hlua_class_function(L, "rep_header", hlua_http_msg_rep_hdr);
12306 hlua_class_function(L, "rep_value", hlua_http_msg_rep_val);
12307 hlua_class_function(L, "add_header", hlua_http_msg_add_hdr);
12308 hlua_class_function(L, "set_header", hlua_http_msg_set_hdr);
12309 hlua_class_function(L, "set_method", hlua_http_msg_set_meth);
12310 hlua_class_function(L, "set_path", hlua_http_msg_set_path);
12311 hlua_class_function(L, "set_query", hlua_http_msg_set_query);
12312 hlua_class_function(L, "set_uri", hlua_http_msg_set_uri);
12313 hlua_class_function(L, "set_status", hlua_http_msg_set_status);
12314 hlua_class_function(L, "is_full", hlua_http_msg_is_full);
12315 hlua_class_function(L, "may_recv", hlua_http_msg_may_recv);
12316 hlua_class_function(L, "eom", hlua_http_msg_is_eom);
12317 hlua_class_function(L, "input", hlua_http_msg_get_in_len);
12318 hlua_class_function(L, "output", hlua_http_msg_get_out_len);
12319
12320 hlua_class_function(L, "body", hlua_http_msg_get_body);
12321 hlua_class_function(L, "set", hlua_http_msg_set_data);
12322 hlua_class_function(L, "remove", hlua_http_msg_del_data);
12323 hlua_class_function(L, "append", hlua_http_msg_append);
12324 hlua_class_function(L, "prepend", hlua_http_msg_prepend);
12325 hlua_class_function(L, "insert", hlua_http_msg_insert_data);
12326 hlua_class_function(L, "set_eom", hlua_http_msg_set_eom);
12327 hlua_class_function(L, "unset_eom", hlua_http_msg_unset_eom);
12328
12329 hlua_class_function(L, "send", hlua_http_msg_send);
12330 hlua_class_function(L, "forward", hlua_http_msg_forward);
12331
12332 lua_rawset(L, -3);
12333
12334 /* Register previous table in the registry with reference and named entry. */
12335 class_http_msg_ref = hlua_register_metatable(L, CLASS_HTTP_MSG);
William Lallemand3956c4e2021-09-21 16:25:15 +020012336
12337 /*
12338 *
12339 * Register class HTTPClient
12340 *
12341 */
12342
12343 /* Create and fill the metatable. */
12344 lua_newtable(L);
12345 lua_pushstring(L, "__index");
12346 lua_newtable(L);
12347 hlua_class_function(L, "get", hlua_httpclient_get);
William Lallemanddc2cc902021-10-26 11:43:26 +020012348 hlua_class_function(L, "head", hlua_httpclient_head);
12349 hlua_class_function(L, "put", hlua_httpclient_put);
12350 hlua_class_function(L, "post", hlua_httpclient_post);
12351 hlua_class_function(L, "delete", hlua_httpclient_delete);
William Lallemand3956c4e2021-09-21 16:25:15 +020012352 lua_settable(L, -3); /* Sets the __index entry. */
William Lallemandf77f1de2021-09-28 19:10:38 +020012353 /* Register the garbage collector entry. */
12354 lua_pushstring(L, "__gc");
12355 lua_pushcclosure(L, hlua_httpclient_gc, 0);
12356 lua_settable(L, -3); /* Push the last 2 entries in the table at index -3 */
12357
William Lallemand3956c4e2021-09-21 16:25:15 +020012358
12359
12360 class_httpclient_ref = hlua_register_metatable(L, CLASS_HTTPCLIENT);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010012361 /*
12362 *
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020012363 * Register class AppletTCP
12364 *
12365 */
12366
12367 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012368 lua_newtable(L);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020012369
Ilya Shipitsind4259502020-04-08 01:07:56 +050012370 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012371 lua_pushstring(L, "__index");
12372 lua_newtable(L);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020012373
12374 /* Register Lua functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012375 hlua_class_function(L, "getline", hlua_applet_tcp_getline);
12376 hlua_class_function(L, "receive", hlua_applet_tcp_recv);
12377 hlua_class_function(L, "send", hlua_applet_tcp_send);
12378 hlua_class_function(L, "set_priv", hlua_applet_tcp_set_priv);
12379 hlua_class_function(L, "get_priv", hlua_applet_tcp_get_priv);
12380 hlua_class_function(L, "set_var", hlua_applet_tcp_set_var);
12381 hlua_class_function(L, "unset_var", hlua_applet_tcp_unset_var);
12382 hlua_class_function(L, "get_var", hlua_applet_tcp_get_var);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020012383
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012384 lua_settable(L, -3);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020012385
12386 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012387 class_applet_tcp_ref = hlua_register_metatable(L, CLASS_APPLET_TCP);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020012388
12389 /*
12390 *
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020012391 * Register class AppletHTTP
12392 *
12393 */
12394
12395 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012396 lua_newtable(L);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020012397
Ilya Shipitsind4259502020-04-08 01:07:56 +050012398 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012399 lua_pushstring(L, "__index");
12400 lua_newtable(L);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020012401
12402 /* Register Lua functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012403 hlua_class_function(L, "set_priv", hlua_applet_http_set_priv);
12404 hlua_class_function(L, "get_priv", hlua_applet_http_get_priv);
12405 hlua_class_function(L, "set_var", hlua_applet_http_set_var);
12406 hlua_class_function(L, "unset_var", hlua_applet_http_unset_var);
12407 hlua_class_function(L, "get_var", hlua_applet_http_get_var);
12408 hlua_class_function(L, "getline", hlua_applet_http_getline);
12409 hlua_class_function(L, "receive", hlua_applet_http_recv);
12410 hlua_class_function(L, "send", hlua_applet_http_send);
12411 hlua_class_function(L, "add_header", hlua_applet_http_addheader);
12412 hlua_class_function(L, "set_status", hlua_applet_http_status);
12413 hlua_class_function(L, "start_response", hlua_applet_http_start_response);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020012414
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012415 lua_settable(L, -3);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020012416
12417 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012418 class_applet_http_ref = hlua_register_metatable(L, CLASS_APPLET_HTTP);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020012419
12420 /*
12421 *
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010012422 * Register class TXN
12423 *
12424 */
12425
12426 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012427 lua_newtable(L);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010012428
Ilya Shipitsind4259502020-04-08 01:07:56 +050012429 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012430 lua_pushstring(L, "__index");
12431 lua_newtable(L);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010012432
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +010012433 /* Register Lua functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012434 hlua_class_function(L, "set_priv", hlua_set_priv);
12435 hlua_class_function(L, "get_priv", hlua_get_priv);
12436 hlua_class_function(L, "set_var", hlua_set_var);
12437 hlua_class_function(L, "unset_var", hlua_unset_var);
12438 hlua_class_function(L, "get_var", hlua_get_var);
12439 hlua_class_function(L, "done", hlua_txn_done);
12440 hlua_class_function(L, "reply", hlua_txn_reply_new);
12441 hlua_class_function(L, "set_loglevel", hlua_txn_set_loglevel);
12442 hlua_class_function(L, "set_tos", hlua_txn_set_tos);
12443 hlua_class_function(L, "set_mark", hlua_txn_set_mark);
12444 hlua_class_function(L, "set_priority_class", hlua_txn_set_priority_class);
12445 hlua_class_function(L, "set_priority_offset", hlua_txn_set_priority_offset);
12446 hlua_class_function(L, "deflog", hlua_txn_deflog);
12447 hlua_class_function(L, "log", hlua_txn_log);
12448 hlua_class_function(L, "Debug", hlua_txn_log_debug);
12449 hlua_class_function(L, "Info", hlua_txn_log_info);
12450 hlua_class_function(L, "Warning", hlua_txn_log_warning);
12451 hlua_class_function(L, "Alert", hlua_txn_log_alert);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +010012452
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012453 lua_rawset(L, -3);
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010012454
12455 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012456 class_txn_ref = hlua_register_metatable(L, CLASS_TXN);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012457
12458 /*
12459 *
Christopher Faulet700d9e82020-01-31 12:21:52 +010012460 * Register class reply
12461 *
12462 */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012463 lua_newtable(L);
12464 lua_pushstring(L, "__index");
12465 lua_newtable(L);
12466 hlua_class_function(L, "set_status", hlua_txn_reply_set_status);
12467 hlua_class_function(L, "add_header", hlua_txn_reply_add_header);
12468 hlua_class_function(L, "del_header", hlua_txn_reply_del_header);
12469 hlua_class_function(L, "set_body", hlua_txn_reply_set_body);
12470 lua_settable(L, -3); /* Sets the __index entry. */
12471 class_txn_reply_ref = luaL_ref(L, LUA_REGISTRYINDEX);
Christopher Faulet700d9e82020-01-31 12:21:52 +010012472
12473
12474 /*
12475 *
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012476 * Register class Socket
12477 *
12478 */
12479
12480 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012481 lua_newtable(L);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012482
Ilya Shipitsind4259502020-04-08 01:07:56 +050012483 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012484 lua_pushstring(L, "__index");
12485 lua_newtable(L);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012486
Baptiste Assmann84bb4932015-03-02 21:40:06 +010012487#ifdef USE_OPENSSL
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012488 hlua_class_function(L, "connect_ssl", hlua_socket_connect_ssl);
Baptiste Assmann84bb4932015-03-02 21:40:06 +010012489#endif
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012490 hlua_class_function(L, "connect", hlua_socket_connect);
12491 hlua_class_function(L, "send", hlua_socket_send);
12492 hlua_class_function(L, "receive", hlua_socket_receive);
12493 hlua_class_function(L, "close", hlua_socket_close);
12494 hlua_class_function(L, "getpeername", hlua_socket_getpeername);
12495 hlua_class_function(L, "getsockname", hlua_socket_getsockname);
12496 hlua_class_function(L, "setoption", hlua_socket_setoption);
12497 hlua_class_function(L, "settimeout", hlua_socket_settimeout);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012498
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012499 lua_rawset(L, -3); /* Push the last 2 entries in the table at index -3 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012500
12501 /* Register the garbage collector entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012502 lua_pushstring(L, "__gc");
12503 lua_pushcclosure(L, hlua_socket_gc, 0);
12504 lua_rawset(L, -3); /* Push the last 2 entries in the table at index -3 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012505
12506 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012507 class_socket_ref = hlua_register_metatable(L, CLASS_SOCKET);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012508
Thierry Fournieraafc7772020-12-04 11:47:47 +010012509 lua_atpanic(L, hlua_panic_safe);
12510
12511 return L;
12512}
12513
12514void hlua_init(void) {
12515 int i;
Amaury Denoyelle239fdbf2021-03-24 10:22:03 +010012516 char *errmsg;
Thierry Fournieraafc7772020-12-04 11:47:47 +010012517#ifdef USE_OPENSSL
12518 struct srv_kw *kw;
12519 int tmp_error;
12520 char *error;
12521 char *args[] = { /* SSL client configuration. */
12522 "ssl",
12523 "verify",
12524 "none",
12525 NULL
12526 };
12527#endif
12528
12529 /* Init post init function list head */
12530 for (i = 0; i < MAX_THREADS + 1; i++)
12531 LIST_INIT(&hlua_init_functions[i]);
12532
12533 /* Init state for common/shared lua parts */
12534 hlua_state_id = 0;
Willy Tarreau43ab05b2021-09-28 09:43:11 +020012535 ha_set_thread(NULL);
Thierry Fournieraafc7772020-12-04 11:47:47 +010012536 hlua_states[0] = hlua_init_state(0);
12537
12538 /* Init state 1 for thread 0. We have at least one thread. */
12539 hlua_state_id = 1;
Willy Tarreau43ab05b2021-09-28 09:43:11 +020012540 ha_set_thread(NULL);
Thierry Fournieraafc7772020-12-04 11:47:47 +010012541 hlua_states[1] = hlua_init_state(1);
12542
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012543 /* Proxy and server configuration initialisation. */
William Lallemand6bb77b92021-07-28 15:48:16 +020012544 socket_proxy = alloc_new_proxy("LUA-SOCKET", PR_CAP_FE|PR_CAP_BE|PR_CAP_INT, &errmsg);
Amaury Denoyelle239fdbf2021-03-24 10:22:03 +010012545 if (!socket_proxy) {
12546 fprintf(stderr, "Lua init: %s\n", errmsg);
12547 exit(1);
12548 }
12549 proxy_preset_defaults(socket_proxy);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012550
12551 /* Init TCP server: unchanged parameters */
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010012552 socket_tcp = new_server(socket_proxy);
12553 if (!socket_tcp) {
12554 fprintf(stderr, "Lua init: failed to allocate tcp server socket\n");
12555 exit(1);
12556 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012557
12558#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012559 /* Init TCP server: unchanged parameters */
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010012560 socket_ssl = new_server(socket_proxy);
12561 if (!socket_ssl) {
12562 fprintf(stderr, "Lua init: failed to allocate ssl server socket\n");
12563 exit(1);
12564 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012565
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010012566 socket_ssl->use_ssl = 1;
12567 socket_ssl->xprt = xprt_get(XPRT_SSL);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012568
Bertrand Jacquin80839ff2021-01-21 19:14:46 +000012569 for (i = 0; args[i] != NULL; i++) {
12570 if ((kw = srv_find_kw(args[i])) != NULL) { /* Maybe it's registered server keyword */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012571 /*
12572 *
12573 * If the keyword is not known, we can search in the registered
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -080012574 * server keywords. This is useful to configure special SSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012575 * features like client certificates and ssl_verify.
12576 *
12577 */
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010012578 tmp_error = kw->parse(args, &i, socket_proxy, socket_ssl, &error);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012579 if (tmp_error != 0) {
12580 fprintf(stderr, "INTERNAL ERROR: %s\n", error);
12581 abort(); /* This must be never arrives because the command line
12582 not editable by the user. */
12583 }
Bertrand Jacquin80839ff2021-01-21 19:14:46 +000012584 i += kw->skip;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012585 }
12586 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012587#endif
Thierry Fournier75933d42016-01-21 09:30:18 +010012588
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +010012589}
Willy Tarreaubb57d942016-12-21 19:04:56 +010012590
Tim Duesterhusd0c0ca22020-07-04 11:53:26 +020012591static void hlua_deinit()
12592{
Willy Tarreau186f3762020-12-04 11:48:12 +010012593 int thr;
Christopher Faulet69c581a2021-05-31 08:54:04 +020012594 struct hlua_reg_filter *reg_flt, *reg_flt_bck;
12595
12596 list_for_each_entry_safe(reg_flt, reg_flt_bck, &referenced_filters, l)
12597 release_hlua_reg_filter(reg_flt);
Willy Tarreau186f3762020-12-04 11:48:12 +010012598
12599 for (thr = 0; thr < MAX_THREADS+1; thr++) {
12600 if (hlua_states[thr])
12601 lua_close(hlua_states[thr]);
12602 }
Willy Tarreau430bf4a2021-03-04 09:45:32 +010012603
Amaury Denoyellebc2ebfa2021-08-25 15:34:53 +020012604 srv_drop(socket_tcp);
Willy Tarreau430bf4a2021-03-04 09:45:32 +010012605
Willy Tarreau0f143af2021-03-05 10:41:48 +010012606#ifdef USE_OPENSSL
Amaury Denoyellebc2ebfa2021-08-25 15:34:53 +020012607 srv_drop(socket_ssl);
Willy Tarreau0f143af2021-03-05 10:41:48 +010012608#endif
Amaury Denoyelle239fdbf2021-03-24 10:22:03 +010012609
12610 free_proxy(socket_proxy);
Tim Duesterhusd0c0ca22020-07-04 11:53:26 +020012611}
12612
12613REGISTER_POST_DEINIT(hlua_deinit);
12614
Willy Tarreau80713382018-11-26 10:19:54 +010012615static void hlua_register_build_options(void)
12616{
Willy Tarreaubb57d942016-12-21 19:04:56 +010012617 char *ptr = NULL;
Willy Tarreau80713382018-11-26 10:19:54 +010012618
Willy Tarreaubb57d942016-12-21 19:04:56 +010012619 memprintf(&ptr, "Built with Lua version : %s", LUA_RELEASE);
12620 hap_register_build_opts(ptr, 1);
12621}
Willy Tarreau80713382018-11-26 10:19:54 +010012622
12623INITCALL0(STG_REGISTER, hlua_register_build_options);