blob: 05f3a905331d6f3960d173d487d534ce67e2c24b [file] [log] [blame]
Thierry Fourniere726b142016-02-11 17:57:57 +01001/*
2 * Lua unsafe core engine
3 *
4 * Copyright 2015-2016 Thierry Fournier <tfournier@arpalert.org>
5 *
6 * This program is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU General Public License
8 * as published by the Free Software Foundation; either version
9 * 2 of the License, or (at your option) any later version.
10 *
11 */
12
Bertrand Jacquinf4c12d42021-01-21 21:14:07 +000013#define _GNU_SOURCE
14
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +010015#include <ctype.h>
Thierry FOURNIERbabae282015-09-17 11:36:37 +020016#include <setjmp.h>
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +010017
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +010018#include <lauxlib.h>
19#include <lua.h>
20#include <lualib.h>
21
Thierry FOURNIER463119c2015-03-10 00:35:36 +010022#if !defined(LUA_VERSION_NUM) || LUA_VERSION_NUM < 503
23#error "Requires Lua 5.3 or later."
Cyril Bontédc0306e2015-03-02 00:08:40 +010024#endif
25
Willy Tarreau8d2b7772020-05-27 10:58:19 +020026#include <import/ebpttree.h>
Thierry FOURNIER380d0932015-01-23 14:27:52 +010027
Willy Tarreaub2551052020-06-09 09:07:15 +020028#include <haproxy/api.h>
29#include <haproxy/applet.h>
Willy Tarreaudfd3de82020-06-04 23:46:14 +020030#include <haproxy/arg.h>
Christopher Fauletd25d9262020-08-06 11:04:46 +020031#include <haproxy/auth.h>
Willy Tarreau6be78492020-06-05 00:00:29 +020032#include <haproxy/cfgparse.h>
Willy Tarreauf1d32c42020-06-04 21:07:02 +020033#include <haproxy/channel.h>
Willy Tarreau83487a82020-06-04 20:19:54 +020034#include <haproxy/cli.h>
Willy Tarreau55542642021-10-08 09:33:24 +020035#include <haproxy/clock.h>
Willy Tarreau7ea393d2020-06-04 18:02:10 +020036#include <haproxy/connection.h>
Christopher Faulet908628c2022-03-25 16:43:49 +010037#include <haproxy/conn_stream.h>
38#include <haproxy/cs_utils.h>
Christopher Faulet69c581a2021-05-31 08:54:04 +020039#include <haproxy/filters.h>
Willy Tarreau5413a872020-06-02 19:33:08 +020040#include <haproxy/h1.h>
Willy Tarreau86416052020-06-04 09:20:54 +020041#include <haproxy/hlua.h>
Willy Tarreau8c794002020-06-04 10:05:25 +020042#include <haproxy/hlua_fcn.h>
Willy Tarreauc2b1ff02020-06-04 21:21:03 +020043#include <haproxy/http_ana.h>
William Lallemand3956c4e2021-09-21 16:25:15 +020044#include <haproxy/http_client.h>
Willy Tarreau126ba3a2020-06-04 18:26:43 +020045#include <haproxy/http_fetch.h>
Willy Tarreaub2551052020-06-09 09:07:15 +020046#include <haproxy/http_htx.h>
Willy Tarreauc761f842020-06-04 11:40:28 +020047#include <haproxy/http_rules.h>
Willy Tarreau36979d92020-06-05 17:27:29 +020048#include <haproxy/log.h>
Willy Tarreau2cd58092020-06-04 15:10:43 +020049#include <haproxy/map.h>
Willy Tarreau8efbdfb2020-06-04 11:29:21 +020050#include <haproxy/obj_type.h>
Willy Tarreau225a90a2020-06-04 15:06:28 +020051#include <haproxy/pattern.h>
Willy Tarreau469509b2020-06-04 15:13:30 +020052#include <haproxy/payload.h>
Willy Tarreau3d6ee402021-05-08 20:28:07 +020053#include <haproxy/proxy.h>
Willy Tarreaub2551052020-06-09 09:07:15 +020054#include <haproxy/regex.h>
Willy Tarreaue6ce10b2020-06-04 15:33:47 +020055#include <haproxy/sample.h>
Willy Tarreau198e92a2021-03-05 10:23:32 +010056#include <haproxy/server.h>
Willy Tarreau48d25b32020-06-04 18:58:52 +020057#include <haproxy/session.h>
William Lallemand30fcca12022-03-30 12:03:12 +020058#include <haproxy/ssl_ckch.h>
59#include <haproxy/ssl_sock.h>
Willy Tarreau2eec9b52020-06-04 19:58:55 +020060#include <haproxy/stats-t.h>
Willy Tarreaudfd3de82020-06-04 23:46:14 +020061#include <haproxy/stream.h>
Willy Tarreaucea0e1b2020-06-04 17:25:40 +020062#include <haproxy/task.h>
Willy Tarreau8b550af2020-06-04 17:42:48 +020063#include <haproxy/tcp_rules.h>
Willy Tarreaub2551052020-06-09 09:07:15 +020064#include <haproxy/thread.h>
Willy Tarreau48fbcae2020-06-03 18:09:46 +020065#include <haproxy/tools.h>
Willy Tarreaua1718922020-06-04 16:25:31 +020066#include <haproxy/vars.h>
Willy Tarreaub2551052020-06-09 09:07:15 +020067#include <haproxy/xref.h>
68
Thierry FOURNIER380d0932015-01-23 14:27:52 +010069
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +010070/* Lua uses longjmp to perform yield or throwing errors. This
71 * macro is used only for identifying the function that can
72 * not return because a longjmp is executed.
73 * __LJMP marks a prototype of hlua file that can use longjmp.
74 * WILL_LJMP() marks an lua function that will use longjmp.
75 * MAY_LJMP() marks an lua function that may use longjmp.
76 */
77#define __LJMP
Willy Tarreau4e7cc332018-10-20 17:45:48 +020078#define WILL_LJMP(func) do { func; my_unreachable(); } while(0)
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +010079#define MAY_LJMP(func) func
80
Thierry FOURNIERbabae282015-09-17 11:36:37 +020081/* This couple of function executes securely some Lua calls outside of
82 * the lua runtime environment. Each Lua call can return a longjmp
83 * if it encounter a memory error.
84 *
85 * Lua documentation extract:
86 *
87 * If an error happens outside any protected environment, Lua calls
88 * a panic function (see lua_atpanic) and then calls abort, thus
89 * exiting the host application. Your panic function can avoid this
90 * exit by never returning (e.g., doing a long jump to your own
91 * recovery point outside Lua).
92 *
93 * The panic function runs as if it were a message handler (see
Willy Tarreau3dfb7da2022-03-02 22:33:39 +010094 * #2.3); in particular, the error message is at the top of the
Thierry FOURNIERbabae282015-09-17 11:36:37 +020095 * stack. However, there is no guarantee about stack space. To push
96 * anything on the stack, the panic function must first check the
Willy Tarreau3dfb7da2022-03-02 22:33:39 +010097 * available space (see #4.2).
Thierry FOURNIERbabae282015-09-17 11:36:37 +020098 *
99 * We must check all the Lua entry point. This includes:
100 * - The include/proto/hlua.h exported functions
101 * - the task wrapper function
102 * - The action wrapper function
103 * - The converters wrapper function
104 * - The sample-fetch wrapper functions
105 *
Ilya Shipitsin46a030c2020-07-05 16:36:08 +0500106 * It is tolerated that the initialisation function returns an abort.
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -0800107 * Before each Lua abort, an error message is written on stderr.
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200108 *
109 * The macro SET_SAFE_LJMP initialise the longjmp. The Macro
110 * RESET_SAFE_LJMP reset the longjmp. These function must be macro
111 * because they must be exists in the program stack when the longjmp
112 * is called.
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +0200113 *
114 * Note that the Lua processing is not really thread safe. It provides
115 * heavy system which consists to add our own lock function in the Lua
116 * code and recompile the library. This system will probably not accepted
117 * by maintainers of various distribs.
118 *
Ilya Shipitsin856aabc2020-04-16 23:51:34 +0500119 * Our main execution point of the Lua is the function lua_resume(). A
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +0200120 * quick looking on the Lua sources displays a lua_lock() a the start
121 * of function and a lua_unlock() at the end of the function. So I
122 * conclude that the Lua thread safe mode just perform a mutex around
123 * all execution. So I prefer to do this in the HAProxy code, it will be
124 * easier for distro maintainers.
125 *
126 * Note that the HAProxy lua functions rounded by the macro SET_SAFE_LJMP
127 * and RESET_SAFE_LJMP manipulates the Lua stack, so it will be careful
128 * to set mutex around these functions.
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200129 */
Willy Tarreau86abe442018-11-25 20:12:18 +0100130__decl_spinlock(hlua_global_lock);
Thierry FOURNIERffbad792017-07-12 11:39:04 +0200131THREAD_LOCAL jmp_buf safe_ljmp_env;
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200132static int hlua_panic_safe(lua_State *L) { return 0; }
Willy Tarreau6a510902021-07-14 19:41:25 +0200133static int hlua_panic_ljmp(lua_State *L) { WILL_LJMP(longjmp(safe_ljmp_env, 1)); return 0; }
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200134
Thierry Fournier62a22aa2020-11-28 21:06:35 +0100135/* This is the chained list of struct hlua_function referenced
136 * for haproxy action, sample-fetches, converters, cli and
137 * applet bindings. It is used for a post-initialisation control.
138 */
139static struct list referenced_functions = LIST_HEAD_INIT(referenced_functions);
140
Thierry Fournierc7492592020-11-28 23:57:24 +0100141/* This variable is used only during initialization to identify the Lua state
142 * currently being initialized. 0 is the common lua state, 1 to n are the Lua
143 * states dedicated to each thread (in this case hlua_state_id==tid+1).
144 */
145static int hlua_state_id;
146
Thierry Fournier59f11be2020-11-29 00:37:41 +0100147/* This is a NULL-terminated list of lua file which are referenced to load per thread */
148static char **per_thread_load = NULL;
149
150lua_State *hlua_init_state(int thread_id);
151
Willy Tarreau1e7bef12021-08-20 15:47:25 +0200152/* This function takes the Lua global lock. Keep this function's visibility
153 * global so that it can appear in stack dumps and performance profiles!
154 */
155void lua_take_global_lock()
156{
157 HA_SPIN_LOCK(LUA_LOCK, &hlua_global_lock);
158}
159
160static inline void lua_drop_global_lock()
161{
162 HA_SPIN_UNLOCK(LUA_LOCK, &hlua_global_lock);
163}
164
Thierry Fournier7cbe5042020-11-28 17:02:21 +0100165#define SET_SAFE_LJMP_L(__L, __HLUA) \
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200166 ({ \
167 int ret; \
Thierry Fournier021d9862020-11-28 23:42:03 +0100168 if ((__HLUA)->state_id == 0) \
Willy Tarreau1e7bef12021-08-20 15:47:25 +0200169 lua_take_global_lock(); \
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200170 if (setjmp(safe_ljmp_env) != 0) { \
171 lua_atpanic(__L, hlua_panic_safe); \
172 ret = 0; \
Thierry Fournier021d9862020-11-28 23:42:03 +0100173 if ((__HLUA)->state_id == 0) \
Willy Tarreau1e7bef12021-08-20 15:47:25 +0200174 lua_drop_global_lock(); \
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200175 } else { \
176 lua_atpanic(__L, hlua_panic_ljmp); \
177 ret = 1; \
178 } \
179 ret; \
180 })
181
182/* If we are the last function catching Lua errors, we
183 * must reset the panic function.
184 */
Thierry Fournier7cbe5042020-11-28 17:02:21 +0100185#define RESET_SAFE_LJMP_L(__L, __HLUA) \
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200186 do { \
187 lua_atpanic(__L, hlua_panic_safe); \
Thierry Fournier021d9862020-11-28 23:42:03 +0100188 if ((__HLUA)->state_id == 0) \
Willy Tarreau1e7bef12021-08-20 15:47:25 +0200189 lua_drop_global_lock(); \
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200190 } while(0)
191
Thierry Fournier7cbe5042020-11-28 17:02:21 +0100192#define SET_SAFE_LJMP(__HLUA) \
193 SET_SAFE_LJMP_L((__HLUA)->T, __HLUA)
194
195#define RESET_SAFE_LJMP(__HLUA) \
196 RESET_SAFE_LJMP_L((__HLUA)->T, __HLUA)
197
198#define SET_SAFE_LJMP_PARENT(__HLUA) \
Thierry Fournier021d9862020-11-28 23:42:03 +0100199 SET_SAFE_LJMP_L(hlua_states[(__HLUA)->state_id], __HLUA)
Thierry Fournier7cbe5042020-11-28 17:02:21 +0100200
201#define RESET_SAFE_LJMP_PARENT(__HLUA) \
Thierry Fournier021d9862020-11-28 23:42:03 +0100202 RESET_SAFE_LJMP_L(hlua_states[(__HLUA)->state_id], __HLUA)
Thierry Fournier7cbe5042020-11-28 17:02:21 +0100203
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +0200204/* Applet status flags */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200205#define APPLET_DONE 0x01 /* applet processing is done. */
Christopher Faulet18c2e8d2019-03-01 12:02:08 +0100206/* unused: 0x02 */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200207#define APPLET_HDR_SENT 0x04 /* Response header sent. */
Christopher Fauleta2097962019-07-15 16:25:33 +0200208/* unused: 0x08, 0x10 */
Thierry FOURNIERd93ea2b2015-12-20 19:14:52 +0100209#define APPLET_HTTP11 0x20 /* Last chunk sent. */
Christopher Faulet56a3d6e2019-02-27 22:06:23 +0100210#define APPLET_RSP_SENT 0x40 /* The response was fully sent */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200211
Thierry Fournierafc63e22020-11-28 17:06:51 +0100212/* The main Lua execution context. The 0 index is the
213 * common state shared by all threads.
214 */
Willy Tarreau186f3762020-12-04 11:48:12 +0100215static lua_State *hlua_states[MAX_THREADS + 1];
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100216
Christopher Fauletc404f112020-02-26 15:03:09 +0100217#define HLUA_FLT_CB_FINAL 0x00000001
218#define HLUA_FLT_CB_RETVAL 0x00000002
219#define HLUA_FLT_CB_ARG_CHN 0x00000004
220#define HLUA_FLT_CB_ARG_HTTP_MSG 0x00000008
221
Christopher Faulet9f55a502020-02-25 15:21:02 +0100222#define HLUA_FLT_CTX_FL_PAYLOAD 0x00000001
223
Christopher Faulet69c581a2021-05-31 08:54:04 +0200224struct hlua_reg_filter {
225 char *name;
226 int flt_ref[MAX_THREADS + 1];
227 int fun_ref[MAX_THREADS + 1];
228 struct list l;
229};
230
231struct hlua_flt_config {
232 struct hlua_reg_filter *reg;
233 int ref[MAX_THREADS + 1];
234 char **args;
235};
236
237struct hlua_flt_ctx {
238 int ref; /* ref to the filter lua object */
239 struct hlua *hlua[2]; /* lua runtime context (0: request, 1: response) */
240 unsigned int cur_off[2]; /* current offset (0: request, 1: response) */
241 unsigned int cur_len[2]; /* current forwardable length (0: request, 1: response) */
242 unsigned int flags; /* HLUA_FLT_CTX_FL_* */
243};
244
Willy Tarreau5321da92022-05-06 11:57:34 +0200245/* appctx context used by the cosockets */
246struct hlua_csk_ctx {
247 int connected;
248 struct xref xref; /* cross reference with the Lua object owner. */
249 struct list wake_on_read;
250 struct list wake_on_write;
251 struct appctx *appctx;
252 int die;
253};
254
Willy Tarreaue23f33b2022-05-06 14:07:13 +0200255/* appctx context used by TCP services */
256struct hlua_tcp_ctx {
257 struct hlua *hlua;
258 int flags;
259 struct task *task;
260};
261
Willy Tarreauaa229cc2022-05-06 14:26:10 +0200262/* appctx context used by HTTP services */
263struct hlua_http_ctx {
264 struct hlua *hlua;
265 int left_bytes; /* The max amount of bytes that we can read. */
266 int flags;
267 int status;
268 const char *reason;
269 struct task *task;
270};
271
Willy Tarreaubcda5f62022-05-03 18:13:39 +0200272/* used by registered CLI keywords */
273struct hlua_cli_ctx {
274 struct hlua *hlua;
275 struct task *task;
276 struct hlua_function *fcn;
277};
278
Christopher Faulet69c581a2021-05-31 08:54:04 +0200279DECLARE_STATIC_POOL(pool_head_hlua_flt_ctx, "hlua_flt_ctx", sizeof(struct hlua_flt_ctx));
280
Christopher Faulet9f55a502020-02-25 15:21:02 +0100281static int hlua_filter_from_payload(struct filter *filter);
282
Christopher Faulet69c581a2021-05-31 08:54:04 +0200283/* This is the chained list of struct hlua_flt referenced
284 * for haproxy filters. It is used for a post-initialisation control.
285 */
286static struct list referenced_filters = LIST_HEAD_INIT(referenced_filters);
287
288
Thierry FOURNIERebed6e92016-12-16 11:54:07 +0100289/* This is the memory pool containing struct lua for applets
290 * (including cli).
291 */
Willy Tarreau8ceae722018-11-26 11:58:30 +0100292DECLARE_STATIC_POOL(pool_head_hlua, "hlua", sizeof(struct hlua));
Thierry FOURNIERebed6e92016-12-16 11:54:07 +0100293
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +0100294/* Used for Socket connection. */
Amaury Denoyelle239fdbf2021-03-24 10:22:03 +0100295static struct proxy *socket_proxy;
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +0100296static struct server *socket_tcp;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +0100297#ifdef USE_OPENSSL
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +0100298static struct server *socket_ssl;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +0100299#endif
300
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +0100301/* List head of the function called at the initialisation time. */
Thierry Fournierc7492592020-11-28 23:57:24 +0100302struct list hlua_init_functions[MAX_THREADS + 1];
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +0100303
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +0100304/* The following variables contains the reference of the different
305 * Lua classes. These references are useful for identify metadata
306 * associated with an object.
307 */
Thierry FOURNIER65f34c62015-02-16 20:11:43 +0100308static int class_txn_ref;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +0100309static int class_socket_ref;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +0100310static int class_channel_ref;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +0100311static int class_fetches_ref;
Thierry FOURNIER594afe72015-03-10 23:58:30 +0100312static int class_converters_ref;
Thierry FOURNIER08504f42015-03-16 14:17:08 +0100313static int class_http_ref;
Christopher Fauletdf97ac42020-02-26 16:57:19 +0100314static int class_http_msg_ref;
William Lallemand3956c4e2021-09-21 16:25:15 +0200315static int class_httpclient_ref;
Thierry FOURNIER3def3932015-04-07 11:27:54 +0200316static int class_map_ref;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +0200317static int class_applet_tcp_ref;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200318static int class_applet_http_ref;
Christopher Faulet700d9e82020-01-31 12:21:52 +0100319static int class_txn_reply_ref;
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +0100320
Thierry FOURNIERbd413492015-03-03 16:52:26 +0100321/* Global Lua execution timeout. By default Lua, execution linked
Willy Tarreau87b09662015-04-03 00:22:06 +0200322 * with stream (actions, sample-fetches and converters) have a
Thierry FOURNIERbd413492015-03-03 16:52:26 +0100323 * short timeout. Lua linked with tasks doesn't have a timeout
324 * because a task may remain alive during all the haproxy execution.
325 */
326static unsigned int hlua_timeout_session = 4000; /* session timeout. */
327static unsigned int hlua_timeout_task = TICK_ETERNITY; /* task timeout. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +0200328static unsigned int hlua_timeout_applet = 4000; /* applet timeout. */
Thierry FOURNIERbd413492015-03-03 16:52:26 +0100329
Thierry FOURNIERee9f8022015-03-03 17:37:37 +0100330/* Interrupts the Lua processing each "hlua_nb_instruction" instructions.
331 * it is used for preventing infinite loops.
332 *
333 * I test the scheer with an infinite loop containing one incrementation
334 * and one test. I run this loop between 10 seconds, I raise a ceil of
335 * 710M loops from one interrupt each 9000 instructions, so I fix the value
336 * to one interrupt each 10 000 instructions.
337 *
338 * configured | Number of
339 * instructions | loops executed
340 * between two | in milions
341 * forced yields |
342 * ---------------+---------------
343 * 10 | 160
344 * 500 | 670
345 * 1000 | 680
346 * 5000 | 700
347 * 7000 | 700
348 * 8000 | 700
349 * 9000 | 710 <- ceil
350 * 10000 | 710
351 * 100000 | 710
352 * 1000000 | 710
353 *
354 */
355static unsigned int hlua_nb_instruction = 10000;
356
Willy Tarreaucdb53462020-12-02 12:12:00 +0100357/* Descriptor for the memory allocation state. The limit is pre-initialised to
358 * 0 until it is replaced by "tune.lua.maxmem" during the config parsing, or it
359 * is replaced with ~0 during post_init after everything was loaded. This way
360 * it is guaranteed that if limit is ~0 the boot is complete and that if it's
361 * zero it's not yet limited and proper accounting is required.
Willy Tarreau32f61e22015-03-18 17:54:59 +0100362 */
363struct hlua_mem_allocator {
364 size_t allocated;
365 size_t limit;
366};
367
Willy Tarreaucdb53462020-12-02 12:12:00 +0100368static struct hlua_mem_allocator hlua_global_allocator THREAD_ALIGNED(64);
Willy Tarreau32f61e22015-03-18 17:54:59 +0100369
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100370/* These functions converts types between HAProxy internal args or
371 * sample and LUA types. Another function permits to check if the
372 * LUA stack contains arguments according with an required ARG_T
373 * format.
374 */
375static int hlua_arg2lua(lua_State *L, const struct arg *arg);
376static int hlua_lua2arg(lua_State *L, int ud, struct arg *arg);
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100377__LJMP static int hlua_lua2arg_check(lua_State *L, int first, struct arg *argp,
David Carlier0c437f42016-04-27 16:21:56 +0100378 uint64_t mask, struct proxy *p);
Willy Tarreau5eadada2015-03-10 17:28:54 +0100379static int hlua_smp2lua(lua_State *L, struct sample *smp);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100380static int hlua_smp2lua_str(lua_State *L, struct sample *smp);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100381static int hlua_lua2smp(lua_State *L, int ud, struct sample *smp);
382
Christopher Faulet9d1332b2020-02-24 16:46:16 +0100383__LJMP static int hlua_http_get_headers(lua_State *L, struct http_msg *msg);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200384
Thierry Fournier59f11be2020-11-29 00:37:41 +0100385struct prepend_path {
386 struct list l;
387 char *type;
388 char *path;
389};
390
391static struct list prepend_path_list = LIST_HEAD_INIT(prepend_path_list);
392
Thierry FOURNIER23bc3752015-09-11 19:15:43 +0200393#define SEND_ERR(__be, __fmt, __args...) \
394 do { \
395 send_log(__be, LOG_ERR, __fmt, ## __args); \
396 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE)) \
Christopher Faulet767a84b2017-11-24 16:50:31 +0100397 ha_alert(__fmt, ## __args); \
Thierry FOURNIER23bc3752015-09-11 19:15:43 +0200398 } while (0)
399
Thierry Fournier62a22aa2020-11-28 21:06:35 +0100400static inline struct hlua_function *new_hlua_function()
401{
402 struct hlua_function *fcn;
Thierry Fournierc7492592020-11-28 23:57:24 +0100403 int i;
Thierry Fournier62a22aa2020-11-28 21:06:35 +0100404
405 fcn = calloc(1, sizeof(*fcn));
406 if (!fcn)
407 return NULL;
Willy Tarreau2b718102021-04-21 07:32:39 +0200408 LIST_APPEND(&referenced_functions, &fcn->l);
Thierry Fournierc7492592020-11-28 23:57:24 +0100409 for (i = 0; i < MAX_THREADS + 1; i++)
410 fcn->function_ref[i] = -1;
Thierry Fournier62a22aa2020-11-28 21:06:35 +0100411 return fcn;
412}
413
Christopher Fauletdda44442021-04-12 14:05:43 +0200414static inline void release_hlua_function(struct hlua_function *fcn)
415{
416 if (!fcn)
417 return;
418 if (fcn->name)
419 ha_free(&fcn->name);
Willy Tarreau2b718102021-04-21 07:32:39 +0200420 LIST_DELETE(&fcn->l);
Christopher Fauletdda44442021-04-12 14:05:43 +0200421 ha_free(&fcn);
422}
423
Thierry Fournierc7492592020-11-28 23:57:24 +0100424/* If the common state is set, the stack id is 0, otherwise it is the tid + 1 */
425static inline int fcn_ref_to_stack_id(struct hlua_function *fcn)
426{
427 if (fcn->function_ref[0] == -1)
428 return tid + 1;
429 return 0;
430}
431
Christopher Faulet69c581a2021-05-31 08:54:04 +0200432/* Create a new registered filter. Only its name is filled */
433static inline struct hlua_reg_filter *new_hlua_reg_filter(const char *name)
434{
435 struct hlua_reg_filter *reg_flt;
436 int i;
437
438 reg_flt = calloc(1, sizeof(*reg_flt));
439 if (!reg_flt)
440 return NULL;
441 reg_flt->name = strdup(name);
442 if (!reg_flt->name) {
443 free(reg_flt);
444 return NULL;
445 }
446 LIST_APPEND(&referenced_filters, &reg_flt->l);
447 for (i = 0; i < MAX_THREADS + 1; i++) {
448 reg_flt->flt_ref[i] = -1;
449 reg_flt->fun_ref[i] = -1;
450 }
451 return reg_flt;
452}
453
454/* Release a registered filter */
455static inline void release_hlua_reg_filter(struct hlua_reg_filter *reg_flt)
456{
457 if (!reg_flt)
458 return;
459 if (reg_flt->name)
460 ha_free(&reg_flt->name);
461 LIST_DELETE(&reg_flt->l);
462 ha_free(&reg_flt);
463}
464
465/* If the common state is set, the stack id is 0, otherwise it is the tid + 1 */
466static inline int reg_flt_to_stack_id(struct hlua_reg_filter *reg_flt)
467{
468 if (reg_flt->fun_ref[0] == -1)
469 return tid + 1;
470 return 0;
471}
472
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100473/* Used to check an Lua function type in the stack. It creates and
474 * returns a reference of the function. This function throws an
475 * error if the rgument is not a "function".
476 */
477__LJMP unsigned int hlua_checkfunction(lua_State *L, int argno)
478{
479 if (!lua_isfunction(L, argno)) {
Thierry FOURNIERfd1e9552018-02-23 18:41:18 +0100480 const char *msg = lua_pushfstring(L, "function expected, got %s", luaL_typename(L, argno));
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100481 WILL_LJMP(luaL_argerror(L, argno, msg));
482 }
483 lua_pushvalue(L, argno);
484 return luaL_ref(L, LUA_REGISTRYINDEX);
485}
486
Christopher Fauletba9e21d2020-02-25 10:20:04 +0100487/* Used to check an Lua table type in the stack. It creates and
488 * returns a reference of the table. This function throws an
489 * error if the rgument is not a "table".
490 */
491__LJMP unsigned int hlua_checktable(lua_State *L, int argno)
492{
493 if (!lua_istable(L, argno)) {
494 const char *msg = lua_pushfstring(L, "table expected, got %s", luaL_typename(L, argno));
495 WILL_LJMP(luaL_argerror(L, argno, msg));
496 }
497 lua_pushvalue(L, argno);
498 return luaL_ref(L, LUA_REGISTRYINDEX);
499}
500
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200501/* Return the string that is of the top of the stack. */
502const char *hlua_get_top_error_string(lua_State *L)
503{
504 if (lua_gettop(L) < 1)
505 return "unknown error";
506 if (lua_type(L, -1) != LUA_TSTRING)
507 return "unknown error";
508 return lua_tostring(L, -1);
509}
510
Christopher Fauletd09cc512021-03-24 14:48:45 +0100511__LJMP const char *hlua_traceback(lua_State *L, const char* sep)
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200512{
513 lua_Debug ar;
514 int level = 0;
Willy Tarreau83061a82018-07-13 11:56:34 +0200515 struct buffer *msg = get_trash_chunk();
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200516
517 while (lua_getstack(L, level++, &ar)) {
518
519 /* Add separator */
Christopher Fauletd09cc512021-03-24 14:48:45 +0100520 if (b_data(msg))
521 chunk_appendf(msg, "%s", sep);
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200522
523 /* Fill fields:
524 * 'S': fills in the fields source, short_src, linedefined, lastlinedefined, and what;
525 * 'l': fills in the field currentline;
526 * 'n': fills in the field name and namewhat;
527 * 't': fills in the field istailcall;
528 */
529 lua_getinfo(L, "Slnt", &ar);
530
531 /* Append code localisation */
532 if (ar.currentline > 0)
Christopher Fauletd09cc512021-03-24 14:48:45 +0100533 chunk_appendf(msg, "%s:%d: ", ar.short_src, ar.currentline);
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200534 else
Christopher Fauletd09cc512021-03-24 14:48:45 +0100535 chunk_appendf(msg, "%s: ", ar.short_src);
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200536
537 /*
538 * Get function name
539 *
540 * if namewhat is no empty, name is defined.
541 * what contains "Lua" for Lua function, "C" for C function,
542 * or "main" for main code.
543 */
544 if (*ar.namewhat != '\0' && ar.name != NULL) /* is there a name from code? */
Christopher Fauletd09cc512021-03-24 14:48:45 +0100545 chunk_appendf(msg, "in %s '%s'", ar.namewhat, ar.name); /* use it */
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200546
547 else if (*ar.what == 'm') /* "main", the code is not executed in a function */
Christopher Fauletd09cc512021-03-24 14:48:45 +0100548 chunk_appendf(msg, "in main chunk");
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200549
550 else if (*ar.what != 'C') /* for Lua functions, use <file:line> */
Christopher Fauletd09cc512021-03-24 14:48:45 +0100551 chunk_appendf(msg, "in function line %d", ar.linedefined);
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200552
553 else /* nothing left... */
554 chunk_appendf(msg, "?");
555
556
557 /* Display tailed call */
558 if (ar.istailcall)
559 chunk_appendf(msg, " ...");
560 }
561
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200562 return msg->area;
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200563}
564
565
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100566/* This function check the number of arguments available in the
567 * stack. If the number of arguments available is not the same
Ilya Shipitsinc02a23f2020-05-06 00:53:22 +0500568 * then <nb> an error is thrown.
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100569 */
570__LJMP static inline void check_args(lua_State *L, int nb, char *fcn)
571{
572 if (lua_gettop(L) == nb)
573 return;
574 WILL_LJMP(luaL_error(L, "'%s' needs %d arguments", fcn, nb));
575}
576
Mark Lakes22154b42018-01-29 14:38:40 -0800577/* This function pushes an error string prefixed by the file name
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100578 * and the line number where the error is encountered.
579 */
580static int hlua_pusherror(lua_State *L, const char *fmt, ...)
581{
582 va_list argp;
583 va_start(argp, fmt);
584 luaL_where(L, 1);
585 lua_pushvfstring(L, fmt, argp);
586 va_end(argp);
587 lua_concat(L, 2);
588 return 1;
589}
590
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100591/* This functions is used with sample fetch and converters. It
592 * converts the HAProxy configuration argument in a lua stack
593 * values.
594 *
595 * It takes an array of "arg", and each entry of the array is
596 * converted and pushed in the LUA stack.
597 */
598static int hlua_arg2lua(lua_State *L, const struct arg *arg)
599{
600 switch (arg->type) {
601 case ARGT_SINT:
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100602 case ARGT_TIME:
603 case ARGT_SIZE:
Thierry FOURNIERf90838b2015-03-06 13:48:32 +0100604 lua_pushinteger(L, arg->data.sint);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100605 break;
606
607 case ARGT_STR:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200608 lua_pushlstring(L, arg->data.str.area, arg->data.str.data);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100609 break;
610
611 case ARGT_IPV4:
612 case ARGT_IPV6:
613 case ARGT_MSK4:
614 case ARGT_MSK6:
615 case ARGT_FE:
616 case ARGT_BE:
617 case ARGT_TAB:
618 case ARGT_SRV:
619 case ARGT_USR:
620 case ARGT_MAP:
621 default:
622 lua_pushnil(L);
623 break;
624 }
625 return 1;
626}
627
Ilya Shipitsinc02a23f2020-05-06 00:53:22 +0500628/* This function take one entry in an LUA stack at the index "ud",
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100629 * and try to convert it in an HAProxy argument entry. This is useful
Ilya Shipitsind4259502020-04-08 01:07:56 +0500630 * with sample fetch wrappers. The input arguments are given to the
631 * lua wrapper and converted as arg list by the function.
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100632 */
633static int hlua_lua2arg(lua_State *L, int ud, struct arg *arg)
634{
635 switch (lua_type(L, ud)) {
636
637 case LUA_TNUMBER:
638 case LUA_TBOOLEAN:
639 arg->type = ARGT_SINT;
640 arg->data.sint = lua_tointeger(L, ud);
641 break;
642
643 case LUA_TSTRING:
644 arg->type = ARGT_STR;
Tim Duesterhus2e89dec2019-09-29 23:03:08 +0200645 arg->data.str.area = (char *)lua_tolstring(L, ud, &arg->data.str.data);
Tim Duesterhus29d2e8a2019-09-29 23:03:07 +0200646 /* We don't know the actual size of the underlying allocation, so be conservative. */
Christopher Fauletfdea1b62020-08-06 08:29:18 +0200647 arg->data.str.size = arg->data.str.data+1; /* count the terminating null byte */
Tim Duesterhus29d2e8a2019-09-29 23:03:07 +0200648 arg->data.str.head = 0;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100649 break;
650
651 case LUA_TUSERDATA:
652 case LUA_TNIL:
653 case LUA_TTABLE:
654 case LUA_TFUNCTION:
655 case LUA_TTHREAD:
656 case LUA_TLIGHTUSERDATA:
657 arg->type = ARGT_SINT;
Thierry FOURNIERbf65cd42015-07-20 17:45:02 +0200658 arg->data.sint = 0;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100659 break;
660 }
661 return 1;
662}
663
664/* the following functions are used to convert a struct sample
665 * in Lua type. This useful to convert the return of the
Ilya Shipitsind4259502020-04-08 01:07:56 +0500666 * fetches or converters.
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100667 */
Willy Tarreau5eadada2015-03-10 17:28:54 +0100668static int hlua_smp2lua(lua_State *L, struct sample *smp)
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100669{
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200670 switch (smp->data.type) {
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100671 case SMP_T_SINT:
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100672 case SMP_T_BOOL:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200673 lua_pushinteger(L, smp->data.u.sint);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100674 break;
675
676 case SMP_T_BIN:
677 case SMP_T_STR:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200678 lua_pushlstring(L, smp->data.u.str.area, smp->data.u.str.data);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100679 break;
680
681 case SMP_T_METH:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200682 switch (smp->data.u.meth.meth) {
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100683 case HTTP_METH_OPTIONS: lua_pushstring(L, "OPTIONS"); break;
684 case HTTP_METH_GET: lua_pushstring(L, "GET"); break;
685 case HTTP_METH_HEAD: lua_pushstring(L, "HEAD"); break;
686 case HTTP_METH_POST: lua_pushstring(L, "POST"); break;
687 case HTTP_METH_PUT: lua_pushstring(L, "PUT"); break;
688 case HTTP_METH_DELETE: lua_pushstring(L, "DELETE"); break;
689 case HTTP_METH_TRACE: lua_pushstring(L, "TRACE"); break;
690 case HTTP_METH_CONNECT: lua_pushstring(L, "CONNECT"); break;
691 case HTTP_METH_OTHER:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200692 lua_pushlstring(L, smp->data.u.meth.str.area, smp->data.u.meth.str.data);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100693 break;
694 default:
695 lua_pushnil(L);
696 break;
697 }
698 break;
699
700 case SMP_T_IPV4:
701 case SMP_T_IPV6:
702 case SMP_T_ADDR: /* This type is never used to qualify a sample. */
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200703 if (sample_casts[smp->data.type][SMP_T_STR] &&
704 sample_casts[smp->data.type][SMP_T_STR](smp))
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200705 lua_pushlstring(L, smp->data.u.str.area, smp->data.u.str.data);
Willy Tarreau5eadada2015-03-10 17:28:54 +0100706 else
707 lua_pushnil(L);
708 break;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100709 default:
710 lua_pushnil(L);
711 break;
712 }
713 return 1;
714}
715
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100716/* the following functions are used to convert a struct sample
717 * in Lua strings. This is useful to convert the return of the
Ilya Shipitsind4259502020-04-08 01:07:56 +0500718 * fetches or converters.
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100719 */
720static int hlua_smp2lua_str(lua_State *L, struct sample *smp)
721{
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200722 switch (smp->data.type) {
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100723
724 case SMP_T_BIN:
725 case SMP_T_STR:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200726 lua_pushlstring(L, smp->data.u.str.area, smp->data.u.str.data);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100727 break;
728
729 case SMP_T_METH:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200730 switch (smp->data.u.meth.meth) {
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100731 case HTTP_METH_OPTIONS: lua_pushstring(L, "OPTIONS"); break;
732 case HTTP_METH_GET: lua_pushstring(L, "GET"); break;
733 case HTTP_METH_HEAD: lua_pushstring(L, "HEAD"); break;
734 case HTTP_METH_POST: lua_pushstring(L, "POST"); break;
735 case HTTP_METH_PUT: lua_pushstring(L, "PUT"); break;
736 case HTTP_METH_DELETE: lua_pushstring(L, "DELETE"); break;
737 case HTTP_METH_TRACE: lua_pushstring(L, "TRACE"); break;
738 case HTTP_METH_CONNECT: lua_pushstring(L, "CONNECT"); break;
739 case HTTP_METH_OTHER:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200740 lua_pushlstring(L, smp->data.u.meth.str.area, smp->data.u.meth.str.data);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100741 break;
742 default:
743 lua_pushstring(L, "");
744 break;
745 }
746 break;
747
748 case SMP_T_SINT:
749 case SMP_T_BOOL:
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100750 case SMP_T_IPV4:
751 case SMP_T_IPV6:
752 case SMP_T_ADDR: /* This type is never used to qualify a sample. */
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200753 if (sample_casts[smp->data.type][SMP_T_STR] &&
754 sample_casts[smp->data.type][SMP_T_STR](smp))
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200755 lua_pushlstring(L, smp->data.u.str.area, smp->data.u.str.data);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100756 else
757 lua_pushstring(L, "");
758 break;
759 default:
760 lua_pushstring(L, "");
761 break;
762 }
763 return 1;
764}
765
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100766/* the following functions are used to convert an Lua type in a
767 * struct sample. This is useful to provide data from a converter
768 * to the LUA code.
769 */
770static int hlua_lua2smp(lua_State *L, int ud, struct sample *smp)
771{
772 switch (lua_type(L, ud)) {
773
774 case LUA_TNUMBER:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200775 smp->data.type = SMP_T_SINT;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200776 smp->data.u.sint = lua_tointeger(L, ud);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100777 break;
778
779
780 case LUA_TBOOLEAN:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200781 smp->data.type = SMP_T_BOOL;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200782 smp->data.u.sint = lua_toboolean(L, ud);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100783 break;
784
785 case LUA_TSTRING:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200786 smp->data.type = SMP_T_STR;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100787 smp->flags |= SMP_F_CONST;
Tim Duesterhus2e89dec2019-09-29 23:03:08 +0200788 smp->data.u.str.area = (char *)lua_tolstring(L, ud, &smp->data.u.str.data);
Tim Duesterhus29d2e8a2019-09-29 23:03:07 +0200789 /* We don't know the actual size of the underlying allocation, so be conservative. */
Christopher Fauletfdea1b62020-08-06 08:29:18 +0200790 smp->data.u.str.size = smp->data.u.str.data+1; /* count the terminating null byte */
Tim Duesterhus29d2e8a2019-09-29 23:03:07 +0200791 smp->data.u.str.head = 0;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100792 break;
793
794 case LUA_TUSERDATA:
795 case LUA_TNIL:
796 case LUA_TTABLE:
797 case LUA_TFUNCTION:
798 case LUA_TTHREAD:
799 case LUA_TLIGHTUSERDATA:
Thierry FOURNIER93405e12015-08-26 14:19:03 +0200800 case LUA_TNONE:
801 default:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200802 smp->data.type = SMP_T_BOOL;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200803 smp->data.u.sint = 0;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100804 break;
805 }
806 return 1;
807}
808
Ilya Shipitsind4259502020-04-08 01:07:56 +0500809/* This function check the "argp" built by another conversion function
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -0800810 * is in accord with the expected argp defined by the "mask". The function
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100811 * returns true or false. It can be adjust the types if there compatibles.
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100812 *
Ilya Shipitsinc02a23f2020-05-06 00:53:22 +0500813 * This function assumes that the argp argument contains ARGM_NBARGS + 1
Willy Tarreauee0d7272021-07-16 10:26:56 +0200814 * entries and that there is at least one stop at the last position.
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100815 */
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100816__LJMP int hlua_lua2arg_check(lua_State *L, int first, struct arg *argp,
David Carlier0c437f42016-04-27 16:21:56 +0100817 uint64_t mask, struct proxy *p)
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100818{
819 int min_arg;
Willy Tarreauee0d7272021-07-16 10:26:56 +0200820 int idx;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100821 struct proxy *px;
Christopher Fauletd25d9262020-08-06 11:04:46 +0200822 struct userlist *ul;
Christopher Fauletfd2e9062020-08-06 11:10:57 +0200823 struct my_regex *reg;
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200824 const char *msg = NULL;
Christopher Fauletfd2e9062020-08-06 11:10:57 +0200825 char *sname, *pname, *err = NULL;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100826
827 idx = 0;
828 min_arg = ARGM(mask);
829 mask >>= ARGM_BITS;
830
831 while (1) {
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200832 struct buffer tmp = BUF_NULL;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100833
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100834 /* Check for mandatory arguments. */
835 if (argp[idx].type == ARGT_STOP) {
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100836 if (idx < min_arg) {
837
838 /* If miss other argument than the first one, we return an error. */
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200839 if (idx > 0) {
840 msg = "Mandatory argument expected";
841 goto error;
842 }
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100843
844 /* If first argument have a certain type, some default values
845 * may be used. See the function smp_resolve_args().
846 */
847 switch (mask & ARGT_MASK) {
848
849 case ARGT_FE:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200850 if (!(p->cap & PR_CAP_FE)) {
851 msg = "Mandatory argument expected";
852 goto error;
853 }
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100854 argp[idx].data.prx = p;
855 argp[idx].type = ARGT_FE;
856 argp[idx+1].type = ARGT_STOP;
857 break;
858
859 case ARGT_BE:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200860 if (!(p->cap & PR_CAP_BE)) {
861 msg = "Mandatory argument expected";
862 goto error;
863 }
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100864 argp[idx].data.prx = p;
865 argp[idx].type = ARGT_BE;
866 argp[idx+1].type = ARGT_STOP;
867 break;
868
869 case ARGT_TAB:
870 argp[idx].data.prx = p;
871 argp[idx].type = ARGT_TAB;
872 argp[idx+1].type = ARGT_STOP;
873 break;
874
875 default:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200876 msg = "Mandatory argument expected";
877 goto error;
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100878 break;
879 }
880 }
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200881 break;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100882 }
883
Ilya Shipitsin856aabc2020-04-16 23:51:34 +0500884 /* Check for exceed the number of required argument. */
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100885 if ((mask & ARGT_MASK) == ARGT_STOP &&
886 argp[idx].type != ARGT_STOP) {
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200887 msg = "Last argument expected";
888 goto error;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100889 }
890
891 if ((mask & ARGT_MASK) == ARGT_STOP &&
892 argp[idx].type == ARGT_STOP) {
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200893 break;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100894 }
895
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200896 /* Convert some argument types. All string in argp[] are for not
897 * duplicated yet.
898 */
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100899 switch (mask & ARGT_MASK) {
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100900 case ARGT_SINT:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200901 if (argp[idx].type != ARGT_SINT) {
902 msg = "integer expected";
903 goto error;
904 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100905 argp[idx].type = ARGT_SINT;
906 break;
907
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100908 case ARGT_TIME:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200909 if (argp[idx].type != ARGT_SINT) {
910 msg = "integer expected";
911 goto error;
912 }
Thierry FOURNIER29176f32015-07-07 00:41:29 +0200913 argp[idx].type = ARGT_TIME;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100914 break;
915
916 case ARGT_SIZE:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200917 if (argp[idx].type != ARGT_SINT) {
918 msg = "integer expected";
919 goto error;
920 }
Thierry FOURNIER29176f32015-07-07 00:41:29 +0200921 argp[idx].type = ARGT_SIZE;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100922 break;
923
924 case ARGT_FE:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200925 if (argp[idx].type != ARGT_STR) {
926 msg = "string expected";
927 goto error;
928 }
Christopher Fauletfdea1b62020-08-06 08:29:18 +0200929 argp[idx].data.prx = proxy_fe_by_name(argp[idx].data.str.area);
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200930 if (!argp[idx].data.prx) {
931 msg = "frontend doesn't exist";
932 goto error;
933 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100934 argp[idx].type = ARGT_FE;
935 break;
936
937 case ARGT_BE:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200938 if (argp[idx].type != ARGT_STR) {
939 msg = "string expected";
940 goto error;
941 }
Christopher Fauletfdea1b62020-08-06 08:29:18 +0200942 argp[idx].data.prx = proxy_be_by_name(argp[idx].data.str.area);
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200943 if (!argp[idx].data.prx) {
944 msg = "backend doesn't exist";
945 goto error;
946 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100947 argp[idx].type = ARGT_BE;
948 break;
949
950 case ARGT_TAB:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200951 if (argp[idx].type != ARGT_STR) {
952 msg = "string expected";
953 goto error;
954 }
Christopher Fauletfdea1b62020-08-06 08:29:18 +0200955 argp[idx].data.t = stktable_find_by_name(argp[idx].data.str.area);
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200956 if (!argp[idx].data.t) {
957 msg = "table doesn't exist";
958 goto error;
959 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100960 argp[idx].type = ARGT_TAB;
961 break;
962
963 case ARGT_SRV:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200964 if (argp[idx].type != ARGT_STR) {
965 msg = "string expected";
966 goto error;
967 }
Christopher Fauletfdea1b62020-08-06 08:29:18 +0200968 sname = strrchr(argp[idx].data.str.area, '/');
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100969 if (sname) {
970 *sname++ = '\0';
Christopher Fauletfdea1b62020-08-06 08:29:18 +0200971 pname = argp[idx].data.str.area;
Willy Tarreau9e0bb102015-05-26 11:24:42 +0200972 px = proxy_be_by_name(pname);
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200973 if (!px) {
974 msg = "backend doesn't exist";
975 goto error;
976 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100977 }
978 else {
Christopher Fauletfdea1b62020-08-06 08:29:18 +0200979 sname = argp[idx].data.str.area;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100980 px = p;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100981 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100982 argp[idx].data.srv = findserver(px, sname);
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200983 if (!argp[idx].data.srv) {
984 msg = "server doesn't exist";
985 goto error;
986 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100987 argp[idx].type = ARGT_SRV;
988 break;
989
990 case ARGT_IPV4:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200991 if (argp[idx].type != ARGT_STR) {
992 msg = "string expected";
993 goto error;
994 }
995 if (inet_pton(AF_INET, argp[idx].data.str.area, &argp[idx].data.ipv4)) {
996 msg = "invalid IPv4 address";
997 goto error;
998 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100999 argp[idx].type = ARGT_IPV4;
1000 break;
1001
1002 case ARGT_MSK4:
Christopher Faulete663a6e2020-08-07 09:11:22 +02001003 if (argp[idx].type == ARGT_SINT)
1004 len2mask4(argp[idx].data.sint, &argp[idx].data.ipv4);
1005 else if (argp[idx].type == ARGT_STR) {
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001006 if (!str2mask(argp[idx].data.str.area, &argp[idx].data.ipv4)) {
1007 msg = "invalid IPv4 mask";
1008 goto error;
1009 }
1010 }
1011 else {
1012 msg = "integer or string expected";
1013 goto error;
Christopher Faulete663a6e2020-08-07 09:11:22 +02001014 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001015 argp[idx].type = ARGT_MSK4;
1016 break;
1017
1018 case ARGT_IPV6:
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001019 if (argp[idx].type != ARGT_STR) {
1020 msg = "string expected";
1021 goto error;
1022 }
1023 if (inet_pton(AF_INET6, argp[idx].data.str.area, &argp[idx].data.ipv6)) {
1024 msg = "invalid IPv6 address";
1025 goto error;
1026 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001027 argp[idx].type = ARGT_IPV6;
1028 break;
1029
1030 case ARGT_MSK6:
Christopher Faulete663a6e2020-08-07 09:11:22 +02001031 if (argp[idx].type == ARGT_SINT)
1032 len2mask6(argp[idx].data.sint, &argp[idx].data.ipv6);
1033 else if (argp[idx].type == ARGT_STR) {
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001034 if (!str2mask6(argp[idx].data.str.area, &argp[idx].data.ipv6)) {
1035 msg = "invalid IPv6 mask";
1036 goto error;
1037 }
1038 }
1039 else {
1040 msg = "integer or string expected";
1041 goto error;
Christopher Faulete663a6e2020-08-07 09:11:22 +02001042 }
Tim Duesterhusb814da62018-01-25 16:24:50 +01001043 argp[idx].type = ARGT_MSK6;
1044 break;
1045
Christopher Fauletfd2e9062020-08-06 11:10:57 +02001046 case ARGT_REG:
1047 if (argp[idx].type != ARGT_STR) {
1048 msg = "string expected";
1049 goto error;
1050 }
1051 reg = regex_comp(argp[idx].data.str.area, !(argp[idx].type_flags & ARGF_REG_ICASE), 1, &err);
1052 if (!reg) {
1053 msg = lua_pushfstring(L, "error compiling regex '%s' : '%s'",
1054 argp[idx].data.str.area, err);
1055 free(err);
1056 goto error;
1057 }
1058 argp[idx].type = ARGT_REG;
1059 argp[idx].data.reg = reg;
1060 break;
1061
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001062 case ARGT_USR:
Christopher Fauletd25d9262020-08-06 11:04:46 +02001063 if (argp[idx].type != ARGT_STR) {
1064 msg = "string expected";
1065 goto error;
1066 }
1067 if (p->uri_auth && p->uri_auth->userlist &&
Tim Duesterhuse5ff1412021-01-02 22:31:53 +01001068 strcmp(p->uri_auth->userlist->name, argp[idx].data.str.area) == 0)
Christopher Fauletd25d9262020-08-06 11:04:46 +02001069 ul = p->uri_auth->userlist;
1070 else
1071 ul = auth_find_userlist(argp[idx].data.str.area);
1072
1073 if (!ul) {
1074 msg = lua_pushfstring(L, "unable to find userlist '%s'", argp[idx].data.str.area);
1075 goto error;
1076 }
1077 argp[idx].type = ARGT_USR;
1078 argp[idx].data.usr = ul;
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001079 break;
1080
1081 case ARGT_STR:
1082 if (!chunk_dup(&tmp, &argp[idx].data.str)) {
1083 msg = "unable to duplicate string arg";
1084 goto error;
1085 }
1086 argp[idx].data.str = tmp;
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001087 break;
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001088
Christopher Fauletd25d9262020-08-06 11:04:46 +02001089 case ARGT_MAP:
Christopher Fauletd25d9262020-08-06 11:04:46 +02001090 msg = "type not yet supported";
1091 goto error;
1092 break;
1093
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001094 }
1095
1096 /* Check for type of argument. */
1097 if ((mask & ARGT_MASK) != argp[idx].type) {
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001098 msg = lua_pushfstring(L, "'%s' expected, got '%s'",
1099 arg_type_names[(mask & ARGT_MASK)],
1100 arg_type_names[argp[idx].type & ARGT_MASK]);
1101 goto error;
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001102 }
1103
1104 /* Next argument. */
1105 mask >>= ARGT_BITS;
1106 idx++;
1107 }
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001108 return 0;
1109
1110 error:
Willy Tarreauee0d7272021-07-16 10:26:56 +02001111 free_args(argp);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001112 WILL_LJMP(luaL_argerror(L, first + idx, msg));
1113 return 0; /* Never reached */
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001114}
1115
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001116/*
Ilya Shipitsinc02a23f2020-05-06 00:53:22 +05001117 * The following functions are used to make correspondence between the the
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001118 * executed lua pointer and the "struct hlua *" that contain the context.
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001119 *
1120 * - hlua_gethlua : return the hlua context associated with an lua_State.
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001121 * - hlua_sethlua : create the association between hlua context and lua_state.
1122 */
1123static inline struct hlua *hlua_gethlua(lua_State *L)
1124{
Thierry FOURNIER38c5fd62015-03-10 02:40:29 +01001125 struct hlua **hlua = lua_getextraspace(L);
1126 return *hlua;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001127}
1128static inline void hlua_sethlua(struct hlua *hlua)
1129{
Thierry FOURNIER38c5fd62015-03-10 02:40:29 +01001130 struct hlua **hlua_store = lua_getextraspace(hlua->T);
1131 *hlua_store = hlua;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001132}
1133
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01001134/* This function is used to send logs. It try to send on screen (stderr)
1135 * and on the default syslog server.
1136 */
1137static inline void hlua_sendlog(struct proxy *px, int level, const char *msg)
1138{
1139 struct tm tm;
1140 char *p;
1141
1142 /* Cleanup the log message. */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001143 p = trash.area;
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01001144 for (; *msg != '\0'; msg++, p++) {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001145 if (p >= trash.area + trash.size - 1) {
Thierry FOURNIERccf00632015-09-16 12:47:03 +02001146 /* Break the message if exceed the buffer size. */
1147 *(p-4) = ' ';
1148 *(p-3) = '.';
1149 *(p-2) = '.';
1150 *(p-1) = '.';
1151 break;
1152 }
Willy Tarreau90807112020-02-25 08:16:33 +01001153 if (isprint((unsigned char)*msg))
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01001154 *p = *msg;
1155 else
1156 *p = '.';
1157 }
1158 *p = '\0';
1159
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001160 send_log(px, level, "%s\n", trash.area);
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01001161 if (!(global.mode & MODE_QUIET) || (global.mode & (MODE_VERBOSE | MODE_STARTING))) {
Christopher Fauletf98d8212020-10-02 18:13:52 +02001162 if (level == LOG_DEBUG && !(global.mode & MODE_DEBUG))
1163 return;
1164
Willy Tarreaua678b432015-08-28 10:14:59 +02001165 get_localtime(date.tv_sec, &tm);
1166 fprintf(stderr, "[%s] %03d/%02d%02d%02d (%d) : %s\n",
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01001167 log_levels[level], tm.tm_yday, tm.tm_hour, tm.tm_min, tm.tm_sec,
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001168 (int)getpid(), trash.area);
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01001169 fflush(stderr);
1170 }
1171}
1172
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001173/* This function just ensure that the yield will be always
1174 * returned with a timeout and permit to set some flags
1175 */
1176__LJMP void hlua_yieldk(lua_State *L, int nresults, int ctx,
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001177 lua_KFunction k, int timeout, unsigned int flags)
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001178{
Thierry Fournier4234dbd2020-11-28 13:18:23 +01001179 struct hlua *hlua;
1180
1181 /* Get hlua struct, or NULL if we execute from main lua state */
1182 hlua = hlua_gethlua(L);
1183 if (!hlua) {
1184 return;
1185 }
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001186
1187 /* Set the wake timeout. If timeout is required, we set
1188 * the expiration time.
1189 */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001190 hlua->wake_time = timeout;
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001191
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01001192 hlua->flags |= flags;
1193
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001194 /* Process the yield. */
Willy Tarreau9635e032018-10-16 17:52:55 +02001195 MAY_LJMP(lua_yieldk(L, nresults, ctx, k));
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001196}
1197
Willy Tarreau87b09662015-04-03 00:22:06 +02001198/* This function initialises the Lua environment stored in the stream.
1199 * It must be called at the start of the stream. This function creates
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001200 * an LUA coroutine. It can not be use to crete the main LUA context.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02001201 *
1202 * This function is particular. it initialises a new Lua thread. If the
1203 * initialisation fails (example: out of memory error), the lua function
1204 * throws an error (longjmp).
1205 *
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +01001206 * In some case (at least one), this function can be called from safe
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001207 * environment, so we must not initialise it. While the support of
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +01001208 * threads appear, the safe environment set a lock to ensure only one
1209 * Lua execution at a time. If we initialize safe environment in another
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001210 * safe environment, we have a dead lock.
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +01001211 *
1212 * set "already_safe" true if the context is initialized form safe
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001213 * Lua function.
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +01001214 *
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001215 * This function manipulates two Lua stacks: the main and the thread. Only
Thierry FOURNIERbabae282015-09-17 11:36:37 +02001216 * the main stack can fail. The thread is not manipulated. This function
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001217 * MUST NOT manipulate the created thread stack state, because it is not
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001218 * protected against errors thrown by the thread stack.
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001219 */
Thierry Fournier021d9862020-11-28 23:42:03 +01001220int hlua_ctx_init(struct hlua *lua, int state_id, struct task *task, int already_safe)
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001221{
1222 lua->Mref = LUA_REFNIL;
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001223 lua->flags = 0;
Willy Tarreauf31af932020-01-14 09:59:38 +01001224 lua->gc_count = 0;
Christopher Fauletbc275a92020-02-26 14:55:16 +01001225 lua->wake_time = TICK_ETERNITY;
Thierry Fournier021d9862020-11-28 23:42:03 +01001226 lua->state_id = state_id;
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01001227 LIST_INIT(&lua->com);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001228 if (!already_safe) {
1229 if (!SET_SAFE_LJMP_PARENT(lua)) {
1230 lua->Tref = LUA_REFNIL;
1231 return 0;
1232 }
1233 }
Thierry Fournier021d9862020-11-28 23:42:03 +01001234 lua->T = lua_newthread(hlua_states[state_id]);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001235 if (!lua->T) {
1236 lua->Tref = LUA_REFNIL;
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +01001237 if (!already_safe)
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001238 RESET_SAFE_LJMP_PARENT(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001239 return 0;
1240 }
1241 hlua_sethlua(lua);
Thierry Fournier021d9862020-11-28 23:42:03 +01001242 lua->Tref = luaL_ref(hlua_states[state_id], LUA_REGISTRYINDEX);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001243 lua->task = task;
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +01001244 if (!already_safe)
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001245 RESET_SAFE_LJMP_PARENT(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001246 return 1;
1247}
1248
Willy Tarreau87b09662015-04-03 00:22:06 +02001249/* Used to destroy the Lua coroutine when the attached stream or task
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001250 * is destroyed. The destroy also the memory context. The struct "lua"
1251 * is not freed.
1252 */
1253void hlua_ctx_destroy(struct hlua *lua)
1254{
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01001255 if (!lua)
Thierry FOURNIERa718b292015-03-04 16:48:34 +01001256 return;
1257
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01001258 if (!lua->T)
1259 goto end;
1260
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01001261 /* Purge all the pending signals. */
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001262 notification_purge(&lua->com);
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01001263
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001264 if (!SET_SAFE_LJMP(lua))
Thierry FOURNIER75d02082017-07-12 13:41:33 +02001265 return;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001266 luaL_unref(lua->T, LUA_REGISTRYINDEX, lua->Mref);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001267 RESET_SAFE_LJMP(lua);
Thierry FOURNIER5a50a852015-09-23 16:59:28 +02001268
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001269 if (!SET_SAFE_LJMP_PARENT(lua))
Thierry FOURNIER75d02082017-07-12 13:41:33 +02001270 return;
Thierry Fournier021d9862020-11-28 23:42:03 +01001271 luaL_unref(hlua_states[lua->state_id], LUA_REGISTRYINDEX, lua->Tref);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001272 RESET_SAFE_LJMP_PARENT(lua);
Thierry FOURNIER5a50a852015-09-23 16:59:28 +02001273 /* Forces a garbage collecting process. If the Lua program is finished
1274 * without error, we run the GC on the thread pointer. Its freed all
1275 * the unused memory.
1276 * If the thread is finnish with an error or is currently yielded,
1277 * it seems that the GC applied on the thread doesn't clean anything,
1278 * so e run the GC on the main thread.
1279 * NOTE: maybe this action locks all the Lua threads untiml the en of
1280 * the garbage collection.
1281 */
Willy Tarreauf31af932020-01-14 09:59:38 +01001282 if (lua->gc_count) {
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001283 if (!SET_SAFE_LJMP_PARENT(lua))
Thierry FOURNIER75d02082017-07-12 13:41:33 +02001284 return;
Thierry Fournier021d9862020-11-28 23:42:03 +01001285 lua_gc(hlua_states[lua->state_id], LUA_GCCOLLECT, 0);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001286 RESET_SAFE_LJMP_PARENT(lua);
Thierry FOURNIER7c39ab42015-09-27 22:53:33 +02001287 }
Thierry FOURNIER5a50a852015-09-23 16:59:28 +02001288
Thierry FOURNIERa7b536b2015-09-21 22:50:24 +02001289 lua->T = NULL;
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01001290
1291end:
Willy Tarreaubafbe012017-11-24 17:34:44 +01001292 pool_free(pool_head_hlua, lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001293}
1294
1295/* This function is used to restore the Lua context when a coroutine
1296 * fails. This function copy the common memory between old coroutine
1297 * and the new coroutine. The old coroutine is destroyed, and its
1298 * replaced by the new coroutine.
1299 * If the flag "keep_msg" is set, the last entry of the old is assumed
1300 * as string error message and it is copied in the new stack.
1301 */
1302static int hlua_ctx_renew(struct hlua *lua, int keep_msg)
1303{
1304 lua_State *T;
1305 int new_ref;
1306
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001307 /* New Lua coroutine. */
Thierry Fournier021d9862020-11-28 23:42:03 +01001308 T = lua_newthread(hlua_states[lua->state_id]);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001309 if (!T)
1310 return 0;
1311
1312 /* Copy last error message. */
1313 if (keep_msg)
1314 lua_xmove(lua->T, T, 1);
1315
1316 /* Copy data between the coroutines. */
1317 lua_rawgeti(lua->T, LUA_REGISTRYINDEX, lua->Mref);
1318 lua_xmove(lua->T, T, 1);
Ilya Shipitsin46a030c2020-07-05 16:36:08 +05001319 new_ref = luaL_ref(T, LUA_REGISTRYINDEX); /* Value popped. */
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001320
1321 /* Destroy old data. */
1322 luaL_unref(lua->T, LUA_REGISTRYINDEX, lua->Mref);
1323
1324 /* The thread is garbage collected by Lua. */
Thierry Fournier021d9862020-11-28 23:42:03 +01001325 luaL_unref(hlua_states[lua->state_id], LUA_REGISTRYINDEX, lua->Tref);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001326
1327 /* Fill the struct with the new coroutine values. */
1328 lua->Mref = new_ref;
1329 lua->T = T;
Thierry Fournier021d9862020-11-28 23:42:03 +01001330 lua->Tref = luaL_ref(hlua_states[lua->state_id], LUA_REGISTRYINDEX);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001331
1332 /* Set context. */
1333 hlua_sethlua(lua);
1334
1335 return 1;
1336}
1337
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001338void hlua_hook(lua_State *L, lua_Debug *ar)
1339{
Thierry Fournier4234dbd2020-11-28 13:18:23 +01001340 struct hlua *hlua;
1341
1342 /* Get hlua struct, or NULL if we execute from main lua state */
1343 hlua = hlua_gethlua(L);
1344 if (!hlua)
1345 return;
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001346
1347 /* Lua cannot yield when its returning from a function,
1348 * so, we can fix the interrupt hook to 1 instruction,
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001349 * expecting that the function is finished.
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001350 */
1351 if (lua_gethookmask(L) & LUA_MASKRET) {
1352 lua_sethook(hlua->T, hlua_hook, LUA_MASKCOUNT, 1);
1353 return;
1354 }
1355
1356 /* restore the interrupt condition. */
1357 lua_sethook(hlua->T, hlua_hook, LUA_MASKCOUNT, hlua_nb_instruction);
1358
1359 /* If we interrupt the Lua processing in yieldable state, we yield.
1360 * If the state is not yieldable, trying yield causes an error.
1361 */
1362 if (lua_isyieldable(L))
Willy Tarreau9635e032018-10-16 17:52:55 +02001363 MAY_LJMP(hlua_yieldk(L, 0, 0, NULL, TICK_ETERNITY, HLUA_CTRLYIELD));
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001364
Thierry FOURNIERa85cfb12015-03-13 14:50:06 +01001365 /* If we cannot yield, update the clock and check the timeout. */
Willy Tarreau55542642021-10-08 09:33:24 +02001366 clock_update_date(0, 1);
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001367 hlua->run_time += now_ms - hlua->start_time;
1368 if (hlua->max_time && hlua->run_time >= hlua->max_time) {
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001369 lua_pushfstring(L, "execution timeout");
1370 WILL_LJMP(lua_error(L));
1371 }
1372
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001373 /* Update the start time. */
1374 hlua->start_time = now_ms;
1375
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001376 /* Try to interrupt the process at the end of the current
1377 * unyieldable function.
1378 */
1379 lua_sethook(hlua->T, hlua_hook, LUA_MASKRET|LUA_MASKCOUNT, hlua_nb_instruction);
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001380}
1381
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001382/* This function start or resumes the Lua stack execution. If the flag
1383 * "yield_allowed" if no set and the LUA stack execution returns a yield
1384 * The function return an error.
1385 *
1386 * The function can returns 4 values:
1387 * - HLUA_E_OK : The execution is terminated without any errors.
1388 * - HLUA_E_AGAIN : The execution must continue at the next associated
1389 * task wakeup.
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001390 * - HLUA_E_ERRMSG : An error has occurred, an error message is set in
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001391 * the top of the stack.
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001392 * - HLUA_E_ERR : An error has occurred without error message.
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001393 *
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001394 * If an error occurred, the stack is renewed and it is ready to run new
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001395 * LUA code.
1396 */
1397static enum hlua_exec hlua_ctx_resume(struct hlua *lua, int yield_allowed)
1398{
Christopher Faulet08ed98f2020-07-28 10:33:25 +02001399#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM >= 504
1400 int nres;
1401#endif
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001402 int ret;
1403 const char *msg;
Thierry FOURNIERfc044c92018-06-07 14:40:48 +02001404 const char *trace;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001405
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001406 /* Initialise run time counter. */
1407 if (!HLUA_IS_RUNNING(lua))
1408 lua->run_time = 0;
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001409
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +02001410 /* Lock the whole Lua execution. This lock must be before the
1411 * label "resume_execution".
1412 */
Thierry Fournier021d9862020-11-28 23:42:03 +01001413 if (lua->state_id == 0)
Willy Tarreau1e7bef12021-08-20 15:47:25 +02001414 lua_take_global_lock();
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +02001415
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001416resume_execution:
1417
1418 /* This hook interrupts the Lua processing each 'hlua_nb_instruction'
1419 * instructions. it is used for preventing infinite loops.
1420 */
1421 lua_sethook(lua->T, hlua_hook, LUA_MASKCOUNT, hlua_nb_instruction);
1422
Thierry FOURNIER1bfc09b2015-03-05 17:10:14 +01001423 /* Remove all flags except the running flags. */
Thierry FOURNIER2f3867f2015-09-28 01:02:01 +02001424 HLUA_SET_RUN(lua);
1425 HLUA_CLR_CTRLYIELD(lua);
1426 HLUA_CLR_WAKERESWR(lua);
1427 HLUA_CLR_WAKEREQWR(lua);
Christopher Faulet1f43a342021-08-04 17:58:21 +02001428 HLUA_CLR_NOYIELD(lua);
1429 if (!yield_allowed)
1430 HLUA_SET_NOYIELD(lua);
Thierry FOURNIER1bfc09b2015-03-05 17:10:14 +01001431
Christopher Fauletbc275a92020-02-26 14:55:16 +01001432 /* Update the start time and reset wake_time. */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001433 lua->start_time = now_ms;
Christopher Fauletbc275a92020-02-26 14:55:16 +01001434 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001435
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001436 /* Call the function. */
Christopher Faulet08ed98f2020-07-28 10:33:25 +02001437#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM >= 504
Thierry Fournier021d9862020-11-28 23:42:03 +01001438 ret = lua_resume(lua->T, hlua_states[lua->state_id], lua->nargs, &nres);
Christopher Faulet08ed98f2020-07-28 10:33:25 +02001439#else
Thierry Fournier021d9862020-11-28 23:42:03 +01001440 ret = lua_resume(lua->T, hlua_states[lua->state_id], lua->nargs);
Christopher Faulet08ed98f2020-07-28 10:33:25 +02001441#endif
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001442 switch (ret) {
1443
1444 case LUA_OK:
1445 ret = HLUA_E_OK;
1446 break;
1447
1448 case LUA_YIELD:
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001449 /* Check if the execution timeout is expired. It it is the case, we
1450 * break the Lua execution.
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001451 */
Willy Tarreau55542642021-10-08 09:33:24 +02001452 clock_update_date(0, 1);
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001453 lua->run_time += now_ms - lua->start_time;
1454 if (lua->max_time && lua->run_time > lua->max_time) {
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001455 lua_settop(lua->T, 0); /* Empty the stack. */
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001456 ret = HLUA_E_ETMOUT;
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001457 break;
1458 }
1459 /* Process the forced yield. if the general yield is not allowed or
1460 * if no task were associated this the current Lua execution
1461 * coroutine, we resume the execution. Else we want to return in the
1462 * scheduler and we want to be waked up again, to continue the
1463 * current Lua execution. So we schedule our own task.
1464 */
1465 if (HLUA_IS_CTRLYIELDING(lua)) {
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001466 if (!yield_allowed || !lua->task)
1467 goto resume_execution;
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001468 task_wakeup(lua->task, TASK_WOKEN_MSG);
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001469 }
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001470 if (!yield_allowed) {
1471 lua_settop(lua->T, 0); /* Empty the stack. */
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001472 ret = HLUA_E_YIELD;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001473 break;
1474 }
1475 ret = HLUA_E_AGAIN;
1476 break;
1477
1478 case LUA_ERRRUN:
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001479
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001480 /* Special exit case. The traditional exit is returned as an error
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001481 * because the errors ares the only one mean to return immediately
1482 * from and lua execution.
1483 */
1484 if (lua->flags & HLUA_EXIT) {
1485 ret = HLUA_E_OK;
Christopher Faulet7716cdf2020-01-29 11:53:30 +01001486 hlua_ctx_renew(lua, 1);
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001487 break;
1488 }
1489
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001490 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001491 if (!lua_checkstack(lua->T, 1)) {
1492 ret = HLUA_E_ERR;
1493 break;
1494 }
1495 msg = lua_tostring(lua->T, -1);
1496 lua_settop(lua->T, 0); /* Empty the stack. */
1497 lua_pop(lua->T, 1);
Christopher Fauletd09cc512021-03-24 14:48:45 +01001498 trace = hlua_traceback(lua->T, ", ");
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001499 if (msg)
Thierry Fournier46278ff2020-11-29 11:48:12 +01001500 lua_pushfstring(lua->T, "[state-id %d] runtime error: %s from %s", lua->state_id, msg, trace);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001501 else
Thierry Fournier46278ff2020-11-29 11:48:12 +01001502 lua_pushfstring(lua->T, "[state-id %d] unknown runtime error from %s", lua->state_id, trace);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001503 ret = HLUA_E_ERRMSG;
1504 break;
1505
1506 case LUA_ERRMEM:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001507 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001508 lua_settop(lua->T, 0); /* Empty the stack. */
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001509 ret = HLUA_E_NOMEM;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001510 break;
1511
1512 case LUA_ERRERR:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001513 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001514 if (!lua_checkstack(lua->T, 1)) {
1515 ret = HLUA_E_ERR;
1516 break;
1517 }
1518 msg = lua_tostring(lua->T, -1);
1519 lua_settop(lua->T, 0); /* Empty the stack. */
1520 lua_pop(lua->T, 1);
1521 if (msg)
Thierry Fournier46278ff2020-11-29 11:48:12 +01001522 lua_pushfstring(lua->T, "[state-id %d] message handler error: %s", lua->state_id, msg);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001523 else
Thierry Fournier46278ff2020-11-29 11:48:12 +01001524 lua_pushfstring(lua->T, "[state-id %d] message handler error", lua->state_id);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001525 ret = HLUA_E_ERRMSG;
1526 break;
1527
1528 default:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001529 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001530 lua_settop(lua->T, 0); /* Empty the stack. */
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001531 ret = HLUA_E_ERR;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001532 break;
1533 }
1534
1535 switch (ret) {
1536 case HLUA_E_AGAIN:
1537 break;
1538
1539 case HLUA_E_ERRMSG:
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001540 notification_purge(&lua->com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001541 hlua_ctx_renew(lua, 1);
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001542 HLUA_CLR_RUN(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001543 break;
1544
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001545 case HLUA_E_ETMOUT:
1546 case HLUA_E_NOMEM:
1547 case HLUA_E_YIELD:
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001548 case HLUA_E_ERR:
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001549 HLUA_CLR_RUN(lua);
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001550 notification_purge(&lua->com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001551 hlua_ctx_renew(lua, 0);
1552 break;
1553
1554 case HLUA_E_OK:
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001555 HLUA_CLR_RUN(lua);
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001556 notification_purge(&lua->com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001557 break;
1558 }
1559
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +02001560 /* This is the main exit point, remove the Lua lock. */
Thierry Fournier021d9862020-11-28 23:42:03 +01001561 if (lua->state_id == 0)
Willy Tarreau1e7bef12021-08-20 15:47:25 +02001562 lua_drop_global_lock();
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +02001563
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001564 return ret;
1565}
1566
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001567/* This function exit the current code. */
1568__LJMP static int hlua_done(lua_State *L)
1569{
Thierry Fournier4234dbd2020-11-28 13:18:23 +01001570 struct hlua *hlua;
1571
1572 /* Get hlua struct, or NULL if we execute from main lua state */
1573 hlua = hlua_gethlua(L);
1574 if (!hlua)
1575 return 0;
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001576
1577 hlua->flags |= HLUA_EXIT;
1578 WILL_LJMP(lua_error(L));
1579
1580 return 0;
1581}
1582
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001583/* This function is an LUA binding. It provides a function
1584 * for deleting ACL from a referenced ACL file.
1585 */
1586__LJMP static int hlua_del_acl(lua_State *L)
1587{
1588 const char *name;
1589 const char *key;
1590 struct pat_ref *ref;
1591
1592 MAY_LJMP(check_args(L, 2, "del_acl"));
1593
1594 name = MAY_LJMP(luaL_checkstring(L, 1));
1595 key = MAY_LJMP(luaL_checkstring(L, 2));
1596
1597 ref = pat_ref_lookup(name);
1598 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001599 WILL_LJMP(luaL_error(L, "'del_acl': unknown acl file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001600
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001601 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001602 pat_ref_delete(ref, key);
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001603 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001604 return 0;
1605}
1606
1607/* This function is an LUA binding. It provides a function
1608 * for deleting map entry from a referenced map file.
1609 */
1610static int hlua_del_map(lua_State *L)
1611{
1612 const char *name;
1613 const char *key;
1614 struct pat_ref *ref;
1615
1616 MAY_LJMP(check_args(L, 2, "del_map"));
1617
1618 name = MAY_LJMP(luaL_checkstring(L, 1));
1619 key = MAY_LJMP(luaL_checkstring(L, 2));
1620
1621 ref = pat_ref_lookup(name);
1622 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001623 WILL_LJMP(luaL_error(L, "'del_map': unknown acl file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001624
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001625 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001626 pat_ref_delete(ref, key);
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001627 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001628 return 0;
1629}
1630
1631/* This function is an LUA binding. It provides a function
1632 * for adding ACL pattern from a referenced ACL file.
1633 */
1634static int hlua_add_acl(lua_State *L)
1635{
1636 const char *name;
1637 const char *key;
1638 struct pat_ref *ref;
1639
1640 MAY_LJMP(check_args(L, 2, "add_acl"));
1641
1642 name = MAY_LJMP(luaL_checkstring(L, 1));
1643 key = MAY_LJMP(luaL_checkstring(L, 2));
1644
1645 ref = pat_ref_lookup(name);
1646 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001647 WILL_LJMP(luaL_error(L, "'add_acl': unknown acl file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001648
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001649 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001650 if (pat_ref_find_elt(ref, key) == NULL)
1651 pat_ref_add(ref, key, NULL, NULL);
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001652 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001653 return 0;
1654}
1655
1656/* This function is an LUA binding. It provides a function
1657 * for setting map pattern and sample from a referenced map
1658 * file.
1659 */
1660static int hlua_set_map(lua_State *L)
1661{
1662 const char *name;
1663 const char *key;
1664 const char *value;
1665 struct pat_ref *ref;
1666
1667 MAY_LJMP(check_args(L, 3, "set_map"));
1668
1669 name = MAY_LJMP(luaL_checkstring(L, 1));
1670 key = MAY_LJMP(luaL_checkstring(L, 2));
1671 value = MAY_LJMP(luaL_checkstring(L, 3));
1672
1673 ref = pat_ref_lookup(name);
1674 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001675 WILL_LJMP(luaL_error(L, "'set_map': unknown map file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001676
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001677 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001678 if (pat_ref_find_elt(ref, key) != NULL)
1679 pat_ref_set(ref, key, value, NULL);
1680 else
1681 pat_ref_add(ref, key, value, NULL);
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001682 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001683 return 0;
1684}
1685
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01001686/* A class is a lot of memory that contain data. This data can be a table,
1687 * an integer or user data. This data is associated with a metatable. This
Ilya Shipitsinc02a23f2020-05-06 00:53:22 +05001688 * metatable have an original version registered in the global context with
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01001689 * the name of the object (_G[<name>] = <metable> ).
1690 *
1691 * A metable is a table that modify the standard behavior of a standard
1692 * access to the associated data. The entries of this new metatable are
1693 * defined as is:
1694 *
1695 * http://lua-users.org/wiki/MetatableEvents
1696 *
1697 * __index
1698 *
1699 * we access an absent field in a table, the result is nil. This is
1700 * true, but it is not the whole truth. Actually, such access triggers
1701 * the interpreter to look for an __index metamethod: If there is no
1702 * such method, as usually happens, then the access results in nil;
1703 * otherwise, the metamethod will provide the result.
1704 *
1705 * Control 'prototype' inheritance. When accessing "myTable[key]" and
1706 * the key does not appear in the table, but the metatable has an __index
1707 * property:
1708 *
1709 * - if the value is a function, the function is called, passing in the
1710 * table and the key; the return value of that function is returned as
1711 * the result.
1712 *
1713 * - if the value is another table, the value of the key in that table is
1714 * asked for and returned (and if it doesn't exist in that table, but that
1715 * table's metatable has an __index property, then it continues on up)
1716 *
1717 * - Use "rawget(myTable,key)" to skip this metamethod.
1718 *
1719 * http://www.lua.org/pil/13.4.1.html
1720 *
1721 * __newindex
1722 *
1723 * Like __index, but control property assignment.
1724 *
1725 * __mode - Control weak references. A string value with one or both
1726 * of the characters 'k' and 'v' which specifies that the the
1727 * keys and/or values in the table are weak references.
1728 *
1729 * __call - Treat a table like a function. When a table is followed by
1730 * parenthesis such as "myTable( 'foo' )" and the metatable has
1731 * a __call key pointing to a function, that function is invoked
1732 * (passing any specified arguments) and the return value is
1733 * returned.
1734 *
1735 * __metatable - Hide the metatable. When "getmetatable( myTable )" is
1736 * called, if the metatable for myTable has a __metatable
1737 * key, the value of that key is returned instead of the
1738 * actual metatable.
1739 *
1740 * __tostring - Control string representation. When the builtin
1741 * "tostring( myTable )" function is called, if the metatable
1742 * for myTable has a __tostring property set to a function,
1743 * that function is invoked (passing myTable to it) and the
1744 * return value is used as the string representation.
1745 *
1746 * __len - Control table length. When the table length is requested using
1747 * the length operator ( '#' ), if the metatable for myTable has
1748 * a __len key pointing to a function, that function is invoked
1749 * (passing myTable to it) and the return value used as the value
1750 * of "#myTable".
1751 *
1752 * __gc - Userdata finalizer code. When userdata is set to be garbage
1753 * collected, if the metatable has a __gc field pointing to a
1754 * function, that function is first invoked, passing the userdata
1755 * to it. The __gc metamethod is not called for tables.
1756 * (See http://lua-users.org/lists/lua-l/2006-11/msg00508.html)
1757 *
1758 * Special metamethods for redefining standard operators:
1759 * http://www.lua.org/pil/13.1.html
1760 *
1761 * __add "+"
1762 * __sub "-"
1763 * __mul "*"
1764 * __div "/"
1765 * __unm "!"
1766 * __pow "^"
1767 * __concat ".."
1768 *
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001769 * Special methods for redefining standard relations
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01001770 * http://www.lua.org/pil/13.2.html
1771 *
1772 * __eq "=="
1773 * __lt "<"
1774 * __le "<="
1775 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001776
1777/*
1778 *
1779 *
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001780 * Class Map
1781 *
1782 *
1783 */
1784
1785/* Returns a struct hlua_map if the stack entry "ud" is
1786 * a class session, otherwise it throws an error.
1787 */
1788__LJMP static struct map_descriptor *hlua_checkmap(lua_State *L, int ud)
1789{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02001790 return MAY_LJMP(hlua_checkudata(L, ud, class_map_ref));
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001791}
1792
1793/* This function is the map constructor. It don't need
1794 * the class Map object. It creates and return a new Map
1795 * object. It must be called only during "body" or "init"
1796 * context because it process some filesystem accesses.
1797 */
1798__LJMP static int hlua_map_new(struct lua_State *L)
1799{
1800 const char *fn;
1801 int match = PAT_MATCH_STR;
1802 struct sample_conv conv;
1803 const char *file = "";
1804 int line = 0;
1805 lua_Debug ar;
1806 char *err = NULL;
1807 struct arg args[2];
1808
1809 if (lua_gettop(L) < 1 || lua_gettop(L) > 2)
1810 WILL_LJMP(luaL_error(L, "'new' needs at least 1 argument."));
1811
1812 fn = MAY_LJMP(luaL_checkstring(L, 1));
1813
1814 if (lua_gettop(L) >= 2) {
1815 match = MAY_LJMP(luaL_checkinteger(L, 2));
1816 if (match < 0 || match >= PAT_MATCH_NUM)
1817 WILL_LJMP(luaL_error(L, "'new' needs a valid match method."));
1818 }
1819
1820 /* Get Lua filename and line number. */
1821 if (lua_getstack(L, 1, &ar)) { /* check function at level */
1822 lua_getinfo(L, "Sl", &ar); /* get info about it */
1823 if (ar.currentline > 0) { /* is there info? */
1824 file = ar.short_src;
1825 line = ar.currentline;
1826 }
1827 }
1828
1829 /* fill fake sample_conv struct. */
1830 conv.kw = ""; /* unused. */
1831 conv.process = NULL; /* unused. */
1832 conv.arg_mask = 0; /* unused. */
1833 conv.val_args = NULL; /* unused. */
1834 conv.out_type = SMP_T_STR;
1835 conv.private = (void *)(long)match;
1836 switch (match) {
1837 case PAT_MATCH_STR: conv.in_type = SMP_T_STR; break;
1838 case PAT_MATCH_BEG: conv.in_type = SMP_T_STR; break;
1839 case PAT_MATCH_SUB: conv.in_type = SMP_T_STR; break;
1840 case PAT_MATCH_DIR: conv.in_type = SMP_T_STR; break;
1841 case PAT_MATCH_DOM: conv.in_type = SMP_T_STR; break;
1842 case PAT_MATCH_END: conv.in_type = SMP_T_STR; break;
1843 case PAT_MATCH_REG: conv.in_type = SMP_T_STR; break;
Thierry FOURNIER07ee64e2015-07-06 23:43:03 +02001844 case PAT_MATCH_INT: conv.in_type = SMP_T_SINT; break;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001845 case PAT_MATCH_IP: conv.in_type = SMP_T_ADDR; break;
1846 default:
1847 WILL_LJMP(luaL_error(L, "'new' doesn't support this match mode."));
1848 }
1849
1850 /* fill fake args. */
1851 args[0].type = ARGT_STR;
Christopher Faulet73292e92020-08-06 08:40:09 +02001852 args[0].data.str.area = strdup(fn);
1853 args[0].data.str.data = strlen(fn);
1854 args[0].data.str.size = args[0].data.str.data+1;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001855 args[1].type = ARGT_STOP;
1856
1857 /* load the map. */
1858 if (!sample_load_map(args, &conv, file, line, &err)) {
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +05001859 /* error case: we can't use luaL_error because we must
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001860 * free the err variable.
1861 */
1862 luaL_where(L, 1);
1863 lua_pushfstring(L, "'new': %s.", err);
1864 lua_concat(L, 2);
1865 free(err);
Christopher Faulet6ad7df42020-08-07 11:45:18 +02001866 chunk_destroy(&args[0].data.str);
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001867 WILL_LJMP(lua_error(L));
1868 }
1869
1870 /* create the lua object. */
1871 lua_newtable(L);
1872 lua_pushlightuserdata(L, args[0].data.map);
1873 lua_rawseti(L, -2, 0);
1874
1875 /* Pop a class Map metatable and affect it to the userdata. */
1876 lua_rawgeti(L, LUA_REGISTRYINDEX, class_map_ref);
1877 lua_setmetatable(L, -2);
1878
1879
1880 return 1;
1881}
1882
1883__LJMP static inline int _hlua_map_lookup(struct lua_State *L, int str)
1884{
1885 struct map_descriptor *desc;
1886 struct pattern *pat;
1887 struct sample smp;
1888
1889 MAY_LJMP(check_args(L, 2, "lookup"));
1890 desc = MAY_LJMP(hlua_checkmap(L, 1));
Thierry FOURNIER07ee64e2015-07-06 23:43:03 +02001891 if (desc->pat.expect_type == SMP_T_SINT) {
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02001892 smp.data.type = SMP_T_SINT;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +02001893 smp.data.u.sint = MAY_LJMP(luaL_checkinteger(L, 2));
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001894 }
1895 else {
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02001896 smp.data.type = SMP_T_STR;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001897 smp.flags = SMP_F_CONST;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001898 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 +01001899 smp.data.u.str.size = smp.data.u.str.data + 1;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001900 }
1901
1902 pat = pattern_exec_match(&desc->pat, &smp, 1);
Thierry FOURNIER503bb092015-08-19 08:35:43 +02001903 if (!pat || !pat->data) {
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001904 if (str)
1905 lua_pushstring(L, "");
1906 else
1907 lua_pushnil(L);
1908 return 1;
1909 }
1910
1911 /* The Lua pattern must return a string, so we can't check the returned type */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001912 lua_pushlstring(L, pat->data->u.str.area, pat->data->u.str.data);
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001913 return 1;
1914}
1915
1916__LJMP static int hlua_map_lookup(struct lua_State *L)
1917{
1918 return _hlua_map_lookup(L, 0);
1919}
1920
1921__LJMP static int hlua_map_slookup(struct lua_State *L)
1922{
1923 return _hlua_map_lookup(L, 1);
1924}
1925
1926/*
1927 *
1928 *
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001929 * Class Socket
1930 *
1931 *
1932 */
1933
1934__LJMP static struct hlua_socket *hlua_checksocket(lua_State *L, int ud)
1935{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02001936 return MAY_LJMP(hlua_checkudata(L, ud, class_socket_ref));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001937}
1938
1939/* This function is the handler called for each I/O on the established
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001940 * connection. It is used for notify space available to send or data
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001941 * received.
1942 */
Willy Tarreau00a37f02015-04-13 12:05:19 +02001943static void hlua_socket_handler(struct appctx *appctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001944{
Willy Tarreau5321da92022-05-06 11:57:34 +02001945 struct hlua_csk_ctx *ctx = appctx->svcctx;
Christopher Faulet908628c2022-03-25 16:43:49 +01001946 struct conn_stream *cs = appctx->owner;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001947
Willy Tarreau5321da92022-05-06 11:57:34 +02001948 if (ctx->die) {
Christopher Fauletda098e62022-03-31 17:44:45 +02001949 cs_shutw(cs);
1950 cs_shutr(cs);
Christopher Faulet908628c2022-03-25 16:43:49 +01001951 cs_ic(cs)->flags |= CF_READ_NULL;
Willy Tarreau5321da92022-05-06 11:57:34 +02001952 notification_wake(&ctx->wake_on_read);
1953 notification_wake(&ctx->wake_on_write);
Christopher Faulet908628c2022-03-25 16:43:49 +01001954 stream_shutdown(__cs_strm(cs), SF_ERR_KILLED);
Thierry FOURNIERb13b20a2017-07-16 20:48:54 +02001955 }
1956
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +05001957 /* If we can't write, wakeup the pending write signals. */
Christopher Faulet908628c2022-03-25 16:43:49 +01001958 if (channel_output_closed(cs_ic(cs)))
Willy Tarreau5321da92022-05-06 11:57:34 +02001959 notification_wake(&ctx->wake_on_write);
Thierry FOURNIER6d695e62015-09-27 19:29:38 +02001960
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +05001961 /* If we can't read, wakeup the pending read signals. */
Christopher Faulet908628c2022-03-25 16:43:49 +01001962 if (channel_input_closed(cs_oc(cs)))
Willy Tarreau5321da92022-05-06 11:57:34 +02001963 notification_wake(&ctx->wake_on_read);
Thierry FOURNIER6d695e62015-09-27 19:29:38 +02001964
Willy Tarreau5a0b25d2019-07-18 18:01:14 +02001965 /* if the connection is not established, inform the stream that we want
Thierry FOURNIER316e3192015-09-04 18:25:53 +02001966 * to be notified whenever the connection completes.
1967 */
Christopher Faulet62e75742022-03-31 09:16:34 +02001968 if (cs_opposite(cs)->state < CS_ST_EST) {
Christopher Fauleta0bdec32022-04-04 07:51:21 +02001969 cs_cant_get(cs);
1970 cs_rx_conn_blk(cs);
1971 cs_rx_endp_more(cs);
Willy Tarreaud4da1962015-04-20 01:31:23 +02001972 return;
Thierry FOURNIER316e3192015-09-04 18:25:53 +02001973 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001974
1975 /* This function is called after the connect. */
Willy Tarreau5321da92022-05-06 11:57:34 +02001976 ctx->connected = 1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001977
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001978 /* Wake the tasks which wants to write if the buffer have available space. */
Christopher Faulet908628c2022-03-25 16:43:49 +01001979 if (channel_may_recv(cs_ic(cs)))
Willy Tarreau5321da92022-05-06 11:57:34 +02001980 notification_wake(&ctx->wake_on_write);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001981
1982 /* Wake the tasks which wants to read if the buffer contains data. */
Christopher Faulet908628c2022-03-25 16:43:49 +01001983 if (!channel_is_empty(cs_oc(cs)))
Willy Tarreau5321da92022-05-06 11:57:34 +02001984 notification_wake(&ctx->wake_on_read);
Thierry FOURNIER101b9762018-05-27 01:27:40 +02001985
1986 /* Some data were injected in the buffer, notify the stream
1987 * interface.
1988 */
Christopher Faulet908628c2022-03-25 16:43:49 +01001989 if (!channel_is_empty(cs_ic(cs)))
Christopher Faulet13045f02022-04-01 14:23:38 +02001990 cs_update(cs);
Thierry FOURNIER101b9762018-05-27 01:27:40 +02001991
1992 /* If write notifications are registered, we considers we want
Willy Tarreau3367d412018-11-15 10:57:41 +01001993 * to write, so we clear the blocking flag.
Thierry FOURNIER101b9762018-05-27 01:27:40 +02001994 */
Willy Tarreau5321da92022-05-06 11:57:34 +02001995 if (notification_registered(&ctx->wake_on_write))
Christopher Fauleta0bdec32022-04-04 07:51:21 +02001996 cs_rx_endp_more(cs);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001997}
1998
Willy Tarreau87b09662015-04-03 00:22:06 +02001999/* This function is called when the "struct stream" is destroyed.
2000 * Remove the link from the object to this stream.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002001 * Wake all the pending signals.
2002 */
Willy Tarreau00a37f02015-04-13 12:05:19 +02002003static void hlua_socket_release(struct appctx *appctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002004{
Willy Tarreau5321da92022-05-06 11:57:34 +02002005 struct hlua_csk_ctx *ctx = appctx->svcctx;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002006 struct xref *peer;
2007
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002008 /* Remove my link in the original object. */
Willy Tarreau5321da92022-05-06 11:57:34 +02002009 peer = xref_get_peer_and_lock(&ctx->xref);
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002010 if (peer)
Willy Tarreau5321da92022-05-06 11:57:34 +02002011 xref_disconnect(&ctx->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002012
2013 /* Wake all the task waiting for me. */
Willy Tarreau5321da92022-05-06 11:57:34 +02002014 notification_wake(&ctx->wake_on_read);
2015 notification_wake(&ctx->wake_on_write);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002016}
2017
2018/* If the garbage collectio of the object is launch, nobody
Willy Tarreau87b09662015-04-03 00:22:06 +02002019 * uses this object. If the stream does not exists, just quit.
2020 * Send the shutdown signal to the stream. In some cases,
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002021 * pending signal can rest in the read and write lists. destroy
2022 * it.
2023 */
2024__LJMP static int hlua_socket_gc(lua_State *L)
2025{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002026 struct hlua_socket *socket;
Willy Tarreau5321da92022-05-06 11:57:34 +02002027 struct hlua_csk_ctx *ctx;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002028 struct xref *peer;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002029
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002030 MAY_LJMP(check_args(L, 1, "__gc"));
2031
2032 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002033 peer = xref_get_peer_and_lock(&socket->xref);
2034 if (!peer)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002035 return 0;
Willy Tarreau5321da92022-05-06 11:57:34 +02002036
2037 ctx = container_of(peer, struct hlua_csk_ctx, xref);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002038
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002039 /* Set the flag which destroy the session. */
Willy Tarreau5321da92022-05-06 11:57:34 +02002040 ctx->die = 1;
2041 appctx_wakeup(ctx->appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002042
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002043 /* Remove all reference between the Lua stack and the coroutine stream. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002044 xref_disconnect(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002045 return 0;
2046}
2047
2048/* The close function send shutdown signal and break the
Willy Tarreau87b09662015-04-03 00:22:06 +02002049 * links between the stream and the object.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002050 */
sada05ed3302018-05-11 11:48:18 -07002051__LJMP static int hlua_socket_close_helper(lua_State *L)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002052{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002053 struct hlua_socket *socket;
Willy Tarreau5321da92022-05-06 11:57:34 +02002054 struct hlua_csk_ctx *ctx;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002055 struct xref *peer;
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002056 struct hlua *hlua;
2057
2058 /* Get hlua struct, or NULL if we execute from main lua state */
2059 hlua = hlua_gethlua(L);
2060 if (!hlua)
2061 return 0;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002062
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002063 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002064
2065 /* Check if we run on the same thread than the xreator thread.
2066 * We cannot access to the socket if the thread is different.
2067 */
2068 if (socket->tid != tid)
2069 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2070
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002071 peer = xref_get_peer_and_lock(&socket->xref);
2072 if (!peer)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002073 return 0;
Willy Tarreauf31af932020-01-14 09:59:38 +01002074
2075 hlua->gc_count--;
Willy Tarreau5321da92022-05-06 11:57:34 +02002076 ctx = container_of(peer, struct hlua_csk_ctx, xref);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002077
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002078 /* Set the flag which destroy the session. */
Willy Tarreau5321da92022-05-06 11:57:34 +02002079 ctx->die = 1;
2080 appctx_wakeup(ctx->appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002081
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002082 /* Remove all reference between the Lua stack and the coroutine stream. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002083 xref_disconnect(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002084 return 0;
2085}
2086
sada05ed3302018-05-11 11:48:18 -07002087/* The close function calls close_helper.
2088 */
2089__LJMP static int hlua_socket_close(lua_State *L)
2090{
2091 MAY_LJMP(check_args(L, 1, "close"));
2092 return hlua_socket_close_helper(L);
2093}
2094
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002095/* This Lua function assumes that the stack contain three parameters.
2096 * 1 - USERDATA containing a struct socket
2097 * 2 - INTEGER with values of the macro defined below
2098 * If the integer is -1, we must read at most one line.
2099 * If the integer is -2, we ust read all the data until the
2100 * end of the stream.
2101 * If the integer is positive value, we must read a number of
2102 * bytes corresponding to this value.
2103 */
2104#define HLSR_READ_LINE (-1)
2105#define HLSR_READ_ALL (-2)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002106__LJMP static int hlua_socket_receive_yield(struct lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002107{
2108 struct hlua_socket *socket = MAY_LJMP(hlua_checksocket(L, 1));
2109 int wanted = lua_tointeger(L, 2);
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002110 struct hlua *hlua;
Willy Tarreau5321da92022-05-06 11:57:34 +02002111 struct hlua_csk_ctx *csk_ctx;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002112 struct appctx *appctx;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02002113 size_t len;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002114 int nblk;
Willy Tarreau206ba832018-06-14 15:27:31 +02002115 const char *blk1;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02002116 size_t len1;
Willy Tarreau206ba832018-06-14 15:27:31 +02002117 const char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02002118 size_t len2;
Thierry FOURNIER00543922015-03-09 18:35:06 +01002119 int skip_at_end = 0;
Willy Tarreau81389672015-03-10 12:03:52 +01002120 struct channel *oc;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002121 struct stream *s;
2122 struct xref *peer;
Thierry FOURNIER8c126c72018-05-25 16:27:44 +02002123 int missing_bytes;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002124
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002125 /* Get hlua struct, or NULL if we execute from main lua state */
2126 hlua = hlua_gethlua(L);
2127
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002128 /* Check if this lua stack is schedulable. */
2129 if (!hlua || !hlua->task)
2130 WILL_LJMP(luaL_error(L, "The 'receive' function is only allowed in "
2131 "'frontend', 'backend' or 'task'"));
2132
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002133 /* Check if we run on the same thread than the xreator thread.
2134 * We cannot access to the socket if the thread is different.
2135 */
2136 if (socket->tid != tid)
2137 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2138
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002139 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002140 peer = xref_get_peer_and_lock(&socket->xref);
2141 if (!peer)
2142 goto no_peer;
Willy Tarreau5321da92022-05-06 11:57:34 +02002143
2144 csk_ctx = container_of(peer, struct hlua_csk_ctx, xref);
2145 appctx = csk_ctx->appctx;
Christopher Faulet908628c2022-03-25 16:43:49 +01002146 s = __cs_strm(appctx->owner);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002147
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002148 oc = &s->res;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002149 if (wanted == HLSR_READ_LINE) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002150 /* Read line. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02002151 nblk = co_getline_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002152 if (nblk < 0) /* Connection close. */
2153 goto connection_closed;
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002154 if (nblk == 0) /* No data available. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002155 goto connection_empty;
Thierry FOURNIER00543922015-03-09 18:35:06 +01002156
2157 /* remove final \r\n. */
2158 if (nblk == 1) {
2159 if (blk1[len1-1] == '\n') {
2160 len1--;
2161 skip_at_end++;
2162 if (blk1[len1-1] == '\r') {
2163 len1--;
2164 skip_at_end++;
2165 }
2166 }
2167 }
2168 else {
2169 if (blk2[len2-1] == '\n') {
2170 len2--;
2171 skip_at_end++;
2172 if (blk2[len2-1] == '\r') {
2173 len2--;
2174 skip_at_end++;
2175 }
2176 }
2177 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002178 }
2179
2180 else if (wanted == HLSR_READ_ALL) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002181 /* Read all the available data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02002182 nblk = co_getblk_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002183 if (nblk < 0) /* Connection close. */
2184 goto connection_closed;
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002185 if (nblk == 0) /* No data available. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002186 goto connection_empty;
2187 }
2188
2189 else {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002190 /* Read a block of data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02002191 nblk = co_getblk_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002192 if (nblk < 0) /* Connection close. */
2193 goto connection_closed;
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002194 if (nblk == 0) /* No data available. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002195 goto connection_empty;
2196
Thierry FOURNIER8c126c72018-05-25 16:27:44 +02002197 missing_bytes = wanted - socket->b.n;
2198 if (len1 > missing_bytes) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002199 nblk = 1;
Thierry FOURNIER8c126c72018-05-25 16:27:44 +02002200 len1 = missing_bytes;
2201 } if (nblk == 2 && len1 + len2 > missing_bytes)
2202 len2 = missing_bytes - len1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002203 }
2204
2205 len = len1;
2206
2207 luaL_addlstring(&socket->b, blk1, len1);
2208 if (nblk == 2) {
2209 len += len2;
2210 luaL_addlstring(&socket->b, blk2, len2);
2211 }
2212
2213 /* Consume data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02002214 co_skip(oc, len + skip_at_end);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002215
2216 /* Don't wait anything. */
Thierry FOURNIER7e4ee472018-05-25 15:03:50 +02002217 appctx_wakeup(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002218
2219 /* If the pattern reclaim to read all the data
2220 * in the connection, got out.
2221 */
2222 if (wanted == HLSR_READ_ALL)
2223 goto connection_empty;
Thierry FOURNIER8c126c72018-05-25 16:27:44 +02002224 else if (wanted >= 0 && socket->b.n < wanted)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002225 goto connection_empty;
2226
2227 /* Return result. */
2228 luaL_pushresult(&socket->b);
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002229 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002230 return 1;
2231
2232connection_closed:
2233
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002234 xref_unlock(&socket->xref, peer);
2235
2236no_peer:
2237
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002238 /* If the buffer containds data. */
2239 if (socket->b.n > 0) {
2240 luaL_pushresult(&socket->b);
2241 return 1;
2242 }
2243 lua_pushnil(L);
2244 lua_pushstring(L, "connection closed.");
2245 return 2;
2246
2247connection_empty:
2248
Willy Tarreau5321da92022-05-06 11:57:34 +02002249 if (!notification_new(&hlua->com, &csk_ctx->wake_on_read, hlua->task)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002250 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002251 WILL_LJMP(luaL_error(L, "out of memory"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002252 }
2253 xref_unlock(&socket->xref, peer);
Willy Tarreau9635e032018-10-16 17:52:55 +02002254 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_receive_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002255 return 0;
2256}
2257
Tim Duesterhusb33754c2018-01-04 19:32:14 +01002258/* This Lua function gets two parameters. The first one can be string
2259 * or a number. If the string is "*l", the user requires one line. If
2260 * the string is "*a", the user requires all the contents of the stream.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002261 * If the value is a number, the user require a number of bytes equal
2262 * to the value. The default value is "*l" (a line).
2263 *
Tim Duesterhusb33754c2018-01-04 19:32:14 +01002264 * This parameter with a variable type is converted in integer. This
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002265 * integer takes this values:
2266 * -1 : read a line
2267 * -2 : read all the stream
Tim Duesterhusb33754c2018-01-04 19:32:14 +01002268 * >0 : amount of bytes.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002269 *
Tim Duesterhusb33754c2018-01-04 19:32:14 +01002270 * The second parameter is optional. It contains a string that must be
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002271 * concatenated with the read data.
2272 */
2273__LJMP static int hlua_socket_receive(struct lua_State *L)
2274{
2275 int wanted = HLSR_READ_LINE;
2276 const char *pattern;
Christopher Fauletc31b2002021-05-03 10:11:13 +02002277 int lastarg, type;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002278 char *error;
2279 size_t len;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002280 struct hlua_socket *socket;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002281
2282 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
2283 WILL_LJMP(luaL_error(L, "The 'receive' function requires between 1 and 3 arguments."));
2284
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002285 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002286
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002287 /* Check if we run on the same thread than the xreator thread.
2288 * We cannot access to the socket if the thread is different.
2289 */
2290 if (socket->tid != tid)
2291 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2292
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002293 /* check for pattern. */
2294 if (lua_gettop(L) >= 2) {
2295 type = lua_type(L, 2);
2296 if (type == LUA_TSTRING) {
2297 pattern = lua_tostring(L, 2);
2298 if (strcmp(pattern, "*a") == 0)
2299 wanted = HLSR_READ_ALL;
2300 else if (strcmp(pattern, "*l") == 0)
2301 wanted = HLSR_READ_LINE;
2302 else {
2303 wanted = strtoll(pattern, &error, 10);
2304 if (*error != '\0')
2305 WILL_LJMP(luaL_error(L, "Unsupported pattern."));
2306 }
2307 }
2308 else if (type == LUA_TNUMBER) {
2309 wanted = lua_tointeger(L, 2);
2310 if (wanted < 0)
2311 WILL_LJMP(luaL_error(L, "Unsupported size."));
2312 }
2313 }
2314
2315 /* Set pattern. */
2316 lua_pushinteger(L, wanted);
Tim Duesterhusc6e377e2018-01-04 19:32:13 +01002317
2318 /* Check if we would replace the top by itself. */
2319 if (lua_gettop(L) != 2)
2320 lua_replace(L, 2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002321
Christopher Fauletc31b2002021-05-03 10:11:13 +02002322 /* Save index of the top of the stack because since buffers are used, it
2323 * may change
2324 */
2325 lastarg = lua_gettop(L);
2326
Tim Duesterhusb33754c2018-01-04 19:32:14 +01002327 /* init buffer, and fill it with prefix. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002328 luaL_buffinit(L, &socket->b);
2329
2330 /* Check prefix. */
Christopher Fauletc31b2002021-05-03 10:11:13 +02002331 if (lastarg >= 3) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002332 if (lua_type(L, 3) != LUA_TSTRING)
2333 WILL_LJMP(luaL_error(L, "Expect a 'string' for the prefix"));
2334 pattern = lua_tolstring(L, 3, &len);
2335 luaL_addlstring(&socket->b, pattern, len);
2336 }
2337
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002338 return __LJMP(hlua_socket_receive_yield(L, 0, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002339}
2340
2341/* Write the Lua input string in the output buffer.
Mark Lakes22154b42018-01-29 14:38:40 -08002342 * This function returns a yield if no space is available.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002343 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002344static int hlua_socket_write_yield(struct lua_State *L,int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002345{
2346 struct hlua_socket *socket;
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002347 struct hlua *hlua;
Willy Tarreau5321da92022-05-06 11:57:34 +02002348 struct hlua_csk_ctx *csk_ctx;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002349 struct appctx *appctx;
2350 size_t buf_len;
2351 const char *buf;
2352 int len;
2353 int send_len;
2354 int sent;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002355 struct xref *peer;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002356 struct stream *s;
Christopher Faulet908628c2022-03-25 16:43:49 +01002357 struct conn_stream *cs;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002358
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002359 /* Get hlua struct, or NULL if we execute from main lua state */
2360 hlua = hlua_gethlua(L);
2361
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002362 /* Check if this lua stack is schedulable. */
2363 if (!hlua || !hlua->task)
2364 WILL_LJMP(luaL_error(L, "The 'write' function is only allowed in "
2365 "'frontend', 'backend' or 'task'"));
2366
2367 /* Get object */
2368 socket = MAY_LJMP(hlua_checksocket(L, 1));
2369 buf = MAY_LJMP(luaL_checklstring(L, 2, &buf_len));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002370 sent = MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002371
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002372 /* Check if we run on the same thread than the xreator thread.
2373 * We cannot access to the socket if the thread is different.
2374 */
2375 if (socket->tid != tid)
2376 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2377
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002378 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002379 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002380 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002381 lua_pushinteger(L, -1);
2382 return 1;
2383 }
Willy Tarreau5321da92022-05-06 11:57:34 +02002384
2385 csk_ctx = container_of(peer, struct hlua_csk_ctx, xref);
2386 appctx = csk_ctx->appctx;
Christopher Faulet908628c2022-03-25 16:43:49 +01002387 cs = appctx->owner;
2388 s = __cs_strm(cs);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002389
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002390 /* Check for connection close. */
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002391 if (channel_output_closed(&s->req)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002392 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002393 lua_pushinteger(L, -1);
2394 return 1;
2395 }
2396
2397 /* Update the input buffer data. */
2398 buf += sent;
2399 send_len = buf_len - sent;
2400
2401 /* All the data are sent. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002402 if (sent >= buf_len) {
2403 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002404 return 1; /* Implicitly return the length sent. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002405 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002406
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002407 /* Check if the buffer is available because HAProxy doesn't allocate
Thierry FOURNIER486d52a2015-03-09 17:51:43 +01002408 * the request buffer if its not required.
2409 */
Willy Tarreauc9fa0482018-07-10 17:43:27 +02002410 if (s->req.buf.size == 0) {
Christopher Faulet8f45eec2022-04-01 17:19:36 +02002411 if (!cs_alloc_ibuf(cs, &appctx->buffer_wait))
Christopher Faulet33834b12016-12-19 09:29:06 +01002412 goto hlua_socket_write_yield_return;
Thierry FOURNIER486d52a2015-03-09 17:51:43 +01002413 }
2414
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002415 /* Check for available space. */
Willy Tarreauc9fa0482018-07-10 17:43:27 +02002416 len = b_room(&s->req.buf);
Christopher Faulet33834b12016-12-19 09:29:06 +01002417 if (len <= 0) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002418 goto hlua_socket_write_yield_return;
Christopher Faulet33834b12016-12-19 09:29:06 +01002419 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002420
2421 /* send data */
2422 if (len < send_len)
2423 send_len = len;
Thierry FOURNIER66b89192018-05-27 01:14:47 +02002424 len = ci_putblk(&s->req, buf, send_len);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002425
2426 /* "Not enough space" (-1), "Buffer too little to contain
2427 * the data" (-2) are not expected because the available length
2428 * is tested.
2429 * Other unknown error are also not expected.
2430 */
2431 if (len <= 0) {
Willy Tarreaubc18da12015-03-13 14:00:47 +01002432 if (len == -1)
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002433 s->req.flags |= CF_WAKE_WRITE;
Willy Tarreaubc18da12015-03-13 14:00:47 +01002434
sada05ed3302018-05-11 11:48:18 -07002435 MAY_LJMP(hlua_socket_close_helper(L));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002436 lua_pop(L, 1);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002437 lua_pushinteger(L, -1);
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002438 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002439 return 1;
2440 }
2441
2442 /* update buffers. */
Thierry FOURNIER101b9762018-05-27 01:27:40 +02002443 appctx_wakeup(appctx);
Willy Tarreaude70fa12015-09-26 11:25:05 +02002444
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002445 s->req.rex = TICK_ETERNITY;
2446 s->res.wex = TICK_ETERNITY;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002447
2448 /* Update length sent. */
2449 lua_pop(L, 1);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002450 lua_pushinteger(L, sent + len);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002451
2452 /* All the data buffer is sent ? */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002453 if (sent + len >= buf_len) {
2454 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002455 return 1;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002456 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002457
2458hlua_socket_write_yield_return:
Willy Tarreau5321da92022-05-06 11:57:34 +02002459 if (!notification_new(&hlua->com, &csk_ctx->wake_on_write, hlua->task)) {
Thierry FOURNIERba42fcd2018-05-27 00:59:48 +02002460 xref_unlock(&socket->xref, peer);
2461 WILL_LJMP(luaL_error(L, "out of memory"));
2462 }
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002463 xref_unlock(&socket->xref, peer);
Willy Tarreau9635e032018-10-16 17:52:55 +02002464 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_write_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002465 return 0;
2466}
2467
2468/* This function initiate the send of data. It just check the input
2469 * parameters and push an integer in the Lua stack that contain the
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002470 * amount of data written to the buffer. This is used by the function
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002471 * "hlua_socket_write_yield" that can yield.
2472 *
2473 * The Lua function gets between 3 and 4 parameters. The first one is
2474 * the associated object. The second is a string buffer. The third is
2475 * a facultative integer that represents where is the buffer position
2476 * of the start of the data that can send. The first byte is the
2477 * position "1". The default value is "1". The fourth argument is a
2478 * facultative integer that represents where is the buffer position
2479 * of the end of the data that can send. The default is the last byte.
2480 */
2481static int hlua_socket_send(struct lua_State *L)
2482{
2483 int i;
2484 int j;
2485 const char *buf;
2486 size_t buf_len;
2487
2488 /* Check number of arguments. */
2489 if (lua_gettop(L) < 2 || lua_gettop(L) > 4)
2490 WILL_LJMP(luaL_error(L, "'send' needs between 2 and 4 arguments"));
2491
2492 /* Get the string. */
2493 buf = MAY_LJMP(luaL_checklstring(L, 2, &buf_len));
2494
2495 /* Get and check j. */
2496 if (lua_gettop(L) == 4) {
2497 j = MAY_LJMP(luaL_checkinteger(L, 4));
2498 if (j < 0)
2499 j = buf_len + j + 1;
2500 if (j > buf_len)
2501 j = buf_len + 1;
2502 lua_pop(L, 1);
2503 }
2504 else
2505 j = buf_len;
2506
2507 /* Get and check i. */
2508 if (lua_gettop(L) == 3) {
2509 i = MAY_LJMP(luaL_checkinteger(L, 3));
2510 if (i < 0)
2511 i = buf_len + i + 1;
2512 if (i > buf_len)
2513 i = buf_len + 1;
2514 lua_pop(L, 1);
2515 } else
2516 i = 1;
2517
2518 /* Check bth i and j. */
2519 if (i > j) {
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002520 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002521 return 1;
2522 }
2523 if (i == 0 && j == 0) {
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002524 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002525 return 1;
2526 }
2527 if (i == 0)
2528 i = 1;
2529 if (j == 0)
2530 j = 1;
2531
2532 /* Pop the string. */
2533 lua_pop(L, 1);
2534
2535 /* Update the buffer length. */
2536 buf += i - 1;
2537 buf_len = j - i + 1;
2538 lua_pushlstring(L, buf, buf_len);
2539
2540 /* This unsigned is used to remember the amount of sent data. */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002541 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002542
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002543 return MAY_LJMP(hlua_socket_write_yield(L, 0, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002544}
2545
Willy Tarreau22b0a682015-06-17 19:43:49 +02002546#define SOCKET_INFO_MAX_LEN sizeof("[0000:0000:0000:0000:0000:0000:0000:0000]:12345")
Christopher Faulete6465b32021-10-22 15:36:08 +02002547__LJMP static inline int hlua_socket_info(struct lua_State *L, const struct sockaddr_storage *addr)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002548{
2549 static char buffer[SOCKET_INFO_MAX_LEN];
2550 int ret;
2551 int len;
2552 char *p;
2553
2554 ret = addr_to_str(addr, buffer+1, SOCKET_INFO_MAX_LEN-1);
2555 if (ret <= 0) {
2556 lua_pushnil(L);
2557 return 1;
2558 }
2559
2560 if (ret == AF_UNIX) {
2561 lua_pushstring(L, buffer+1);
2562 return 1;
2563 }
2564 else if (ret == AF_INET6) {
2565 buffer[0] = '[';
2566 len = strlen(buffer);
2567 buffer[len] = ']';
2568 len++;
2569 buffer[len] = ':';
2570 len++;
2571 p = buffer;
2572 }
2573 else if (ret == AF_INET) {
2574 p = buffer + 1;
2575 len = strlen(p);
2576 p[len] = ':';
2577 len++;
2578 }
2579 else {
2580 lua_pushnil(L);
2581 return 1;
2582 }
2583
2584 if (port_to_str(addr, p + len, SOCKET_INFO_MAX_LEN-1 - len) <= 0) {
2585 lua_pushnil(L);
2586 return 1;
2587 }
2588
2589 lua_pushstring(L, p);
2590 return 1;
2591}
2592
2593/* Returns information about the peer of the connection. */
2594__LJMP static int hlua_socket_getpeername(struct lua_State *L)
2595{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002596 struct hlua_socket *socket;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002597 struct xref *peer;
2598 struct appctx *appctx;
Christopher Faulet908628c2022-03-25 16:43:49 +01002599 struct conn_stream *cs;
Christopher Faulet16f16af2021-10-27 09:34:56 +02002600 const struct sockaddr_storage *dst;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002601 int ret;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002602
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002603 MAY_LJMP(check_args(L, 1, "getpeername"));
2604
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002605 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002606
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002607 /* Check if we run on the same thread than the xreator thread.
2608 * We cannot access to the socket if the thread is different.
2609 */
2610 if (socket->tid != tid)
2611 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2612
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002613 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002614 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002615 if (!peer) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002616 lua_pushnil(L);
2617 return 1;
2618 }
Willy Tarreau5321da92022-05-06 11:57:34 +02002619
2620 appctx = container_of(peer, struct hlua_csk_ctx, xref)->appctx;
Christopher Faulet908628c2022-03-25 16:43:49 +01002621 cs = appctx->owner;
Christopher Faulet8da67aa2022-03-29 17:53:09 +02002622 dst = cs_dst(cs_opposite(cs));
Christopher Faulet16f16af2021-10-27 09:34:56 +02002623 if (!dst) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002624 xref_unlock(&socket->xref, peer);
Willy Tarreaua71f6422016-11-16 17:00:14 +01002625 lua_pushnil(L);
2626 return 1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002627 }
2628
Christopher Faulet16f16af2021-10-27 09:34:56 +02002629 ret = MAY_LJMP(hlua_socket_info(L, dst));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002630 xref_unlock(&socket->xref, peer);
2631 return ret;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002632}
2633
2634/* Returns information about my connection side. */
2635static int hlua_socket_getsockname(struct lua_State *L)
2636{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002637 struct hlua_socket *socket;
2638 struct connection *conn;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002639 struct appctx *appctx;
2640 struct xref *peer;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002641 struct stream *s;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002642 int ret;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002643
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002644 MAY_LJMP(check_args(L, 1, "getsockname"));
2645
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002646 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002647
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002648 /* Check if we run on the same thread than the xreator thread.
2649 * We cannot access to the socket if the thread is different.
2650 */
2651 if (socket->tid != tid)
2652 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2653
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002654 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002655 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002656 if (!peer) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002657 lua_pushnil(L);
2658 return 1;
2659 }
Willy Tarreau5321da92022-05-06 11:57:34 +02002660
2661 appctx = container_of(peer, struct hlua_csk_ctx, xref)->appctx;
Christopher Faulet908628c2022-03-25 16:43:49 +01002662 s = __cs_strm(appctx->owner);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002663
Christopher Faulet95a61e82021-12-22 14:22:03 +01002664 conn = cs_conn(s->csb);
Willy Tarreau5a0b25d2019-07-18 18:01:14 +02002665 if (!conn || !conn_get_src(conn)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002666 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002667 lua_pushnil(L);
2668 return 1;
2669 }
2670
Willy Tarreau9da9a6f2019-07-17 14:49:44 +02002671 ret = hlua_socket_info(L, conn->src);
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002672 xref_unlock(&socket->xref, peer);
2673 return ret;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002674}
2675
2676/* This struct define the applet. */
Willy Tarreau30576452015-04-13 13:50:30 +02002677static struct applet update_applet = {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002678 .obj_type = OBJ_TYPE_APPLET,
2679 .name = "<LUA_TCP>",
2680 .fct = hlua_socket_handler,
2681 .release = hlua_socket_release,
2682};
2683
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002684__LJMP static int hlua_socket_connect_yield(struct lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002685{
2686 struct hlua_socket *socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002687 struct hlua *hlua;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002688 struct xref *peer;
Willy Tarreau5321da92022-05-06 11:57:34 +02002689 struct hlua_csk_ctx *csk_ctx;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002690 struct appctx *appctx;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002691 struct stream *s;
2692
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002693 /* Get hlua struct, or NULL if we execute from main lua state */
2694 hlua = hlua_gethlua(L);
2695 if (!hlua)
2696 return 0;
2697
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002698 /* Check if we run on the same thread than the xreator thread.
2699 * We cannot access to the socket if the thread is different.
2700 */
2701 if (socket->tid != tid)
2702 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2703
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002704 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002705 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002706 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002707 lua_pushnil(L);
2708 lua_pushstring(L, "Can't connect");
2709 return 2;
2710 }
Willy Tarreau5321da92022-05-06 11:57:34 +02002711
2712 csk_ctx = container_of(peer, struct hlua_csk_ctx, xref);
2713 appctx = csk_ctx->appctx;
Christopher Faulet908628c2022-03-25 16:43:49 +01002714 s = __cs_strm(appctx->owner);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002715
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002716 /* Check if we run on the same thread than the xreator thread.
2717 * We cannot access to the socket if the thread is different.
2718 */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002719 if (socket->tid != tid) {
2720 xref_unlock(&socket->xref, peer);
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002721 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002722 }
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002723
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002724 /* Check for connection close. */
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002725 if (!hlua || channel_output_closed(&s->req)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002726 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002727 lua_pushnil(L);
2728 lua_pushstring(L, "Can't connect");
2729 return 2;
2730 }
2731
Christopher Faulet693b23b2022-02-28 09:09:05 +01002732 appctx = __cs_appctx(s->csf);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002733
2734 /* Check for connection established. */
Willy Tarreau5321da92022-05-06 11:57:34 +02002735 if (csk_ctx->connected) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002736 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002737 lua_pushinteger(L, 1);
2738 return 1;
2739 }
2740
Willy Tarreau5321da92022-05-06 11:57:34 +02002741 if (!notification_new(&hlua->com, &csk_ctx->wake_on_write, hlua->task)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002742 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002743 WILL_LJMP(luaL_error(L, "out of memory error"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002744 }
2745 xref_unlock(&socket->xref, peer);
Willy Tarreau9635e032018-10-16 17:52:55 +02002746 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_connect_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002747 return 0;
2748}
2749
2750/* This function fail or initite the connection. */
2751__LJMP static int hlua_socket_connect(struct lua_State *L)
2752{
2753 struct hlua_socket *socket;
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002754 int port = -1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002755 const char *ip;
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002756 struct hlua *hlua;
Willy Tarreau5321da92022-05-06 11:57:34 +02002757 struct hlua_csk_ctx *csk_ctx;
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002758 struct appctx *appctx;
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002759 int low, high;
2760 struct sockaddr_storage *addr;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002761 struct xref *peer;
Christopher Faulet908628c2022-03-25 16:43:49 +01002762 struct conn_stream *cs;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002763 struct stream *s;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002764
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002765 if (lua_gettop(L) < 2)
2766 WILL_LJMP(luaL_error(L, "connect: need at least 2 arguments"));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002767
2768 /* Get args. */
2769 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002770
2771 /* Check if we run on the same thread than the xreator thread.
2772 * We cannot access to the socket if the thread is different.
2773 */
2774 if (socket->tid != tid)
2775 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2776
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002777 ip = MAY_LJMP(luaL_checkstring(L, 2));
Tim Duesterhus6edab862018-01-06 19:04:45 +01002778 if (lua_gettop(L) >= 3) {
2779 luaL_Buffer b;
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002780 port = MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002781
Tim Duesterhus6edab862018-01-06 19:04:45 +01002782 /* Force the ip to end with a colon, to support IPv6 addresses
2783 * that are not enclosed within square brackets.
2784 */
2785 if (port > 0) {
2786 luaL_buffinit(L, &b);
2787 luaL_addstring(&b, ip);
2788 luaL_addchar(&b, ':');
2789 luaL_pushresult(&b);
2790 ip = lua_tolstring(L, lua_gettop(L), NULL);
2791 }
2792 }
2793
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002794 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002795 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002796 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002797 lua_pushnil(L);
2798 return 1;
2799 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002800
2801 /* Parse ip address. */
Willy Tarreau5fc93282020-09-16 18:25:03 +02002802 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 +02002803 if (!addr) {
2804 xref_unlock(&socket->xref, peer);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002805 WILL_LJMP(luaL_error(L, "connect: cannot parse destination address '%s'", ip));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002806 }
Willy Tarreau9da9a6f2019-07-17 14:49:44 +02002807
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002808 /* Set port. */
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002809 if (low == 0) {
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02002810 if (addr->ss_family == AF_INET) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002811 if (port == -1) {
2812 xref_unlock(&socket->xref, peer);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002813 WILL_LJMP(luaL_error(L, "connect: port missing"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002814 }
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02002815 ((struct sockaddr_in *)addr)->sin_port = htons(port);
2816 } else if (addr->ss_family == AF_INET6) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002817 if (port == -1) {
2818 xref_unlock(&socket->xref, peer);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002819 WILL_LJMP(luaL_error(L, "connect: port missing"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002820 }
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02002821 ((struct sockaddr_in6 *)addr)->sin6_port = htons(port);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002822 }
2823 }
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02002824
Willy Tarreau5321da92022-05-06 11:57:34 +02002825 csk_ctx = container_of(peer, struct hlua_csk_ctx, xref);
2826 appctx = csk_ctx->appctx;
Christopher Faulet908628c2022-03-25 16:43:49 +01002827 cs = appctx->owner;
2828 s = __cs_strm(cs);
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02002829
Christopher Faulet8da67aa2022-03-29 17:53:09 +02002830 if (!sockaddr_alloc(&cs_opposite(cs)->dst, addr, sizeof(*addr))) {
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02002831 xref_unlock(&socket->xref, peer);
2832 WILL_LJMP(luaL_error(L, "connect: internal error"));
2833 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002834
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002835 /* Get hlua struct, or NULL if we execute from main lua state */
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002836 hlua = hlua_gethlua(L);
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002837 if (!hlua)
2838 return 0;
Willy Tarreaubdc97a82015-08-24 15:42:28 +02002839
2840 /* inform the stream that we want to be notified whenever the
2841 * connection completes.
2842 */
Christopher Fauleta0bdec32022-04-04 07:51:21 +02002843 cs_cant_get(s->csf);
2844 cs_rx_endp_more(s->csf);
Thierry FOURNIER8c8fbbe2015-09-26 17:02:35 +02002845 appctx_wakeup(appctx);
Willy Tarreaubdc97a82015-08-24 15:42:28 +02002846
Willy Tarreauf31af932020-01-14 09:59:38 +01002847 hlua->gc_count++;
Thierry FOURNIER7c39ab42015-09-27 22:53:33 +02002848
Willy Tarreau5321da92022-05-06 11:57:34 +02002849 if (!notification_new(&hlua->com, &csk_ctx->wake_on_write, hlua->task)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002850 xref_unlock(&socket->xref, peer);
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002851 WILL_LJMP(luaL_error(L, "out of memory"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002852 }
2853 xref_unlock(&socket->xref, peer);
PiBa-NL706d5ee2018-05-05 23:51:42 +02002854
2855 task_wakeup(s->task, TASK_WOKEN_INIT);
2856 /* Return yield waiting for connection. */
2857
Willy Tarreau9635e032018-10-16 17:52:55 +02002858 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_connect_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002859
2860 return 0;
2861}
2862
Baptiste Assmann84bb4932015-03-02 21:40:06 +01002863#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002864__LJMP static int hlua_socket_connect_ssl(struct lua_State *L)
2865{
2866 struct hlua_socket *socket;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002867 struct xref *peer;
2868 struct appctx *appctx;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002869 struct stream *s;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002870
2871 MAY_LJMP(check_args(L, 3, "connect_ssl"));
2872 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002873
2874 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002875 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002876 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002877 lua_pushnil(L);
2878 return 1;
2879 }
Willy Tarreau5321da92022-05-06 11:57:34 +02002880
2881 appctx = container_of(peer, struct hlua_csk_ctx, xref)->appctx;
Christopher Faulet908628c2022-03-25 16:43:49 +01002882 s = __cs_strm(appctx->owner);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002883
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +01002884 s->target = &socket_ssl->obj_type;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002885 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002886 return MAY_LJMP(hlua_socket_connect(L));
2887}
Baptiste Assmann84bb4932015-03-02 21:40:06 +01002888#endif
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002889
2890__LJMP static int hlua_socket_setoption(struct lua_State *L)
2891{
2892 return 0;
2893}
2894
2895__LJMP static int hlua_socket_settimeout(struct lua_State *L)
2896{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002897 struct hlua_socket *socket;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002898 int tmout;
Mark Lakes56cc1252018-03-27 09:48:06 +02002899 double dtmout;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002900 struct xref *peer;
2901 struct appctx *appctx;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002902 struct stream *s;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002903
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002904 MAY_LJMP(check_args(L, 2, "settimeout"));
2905
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002906 socket = MAY_LJMP(hlua_checksocket(L, 1));
Mark Lakes56cc1252018-03-27 09:48:06 +02002907
Cyril Bonté7ee465f2018-08-19 22:08:50 +02002908 /* convert the timeout to millis */
2909 dtmout = MAY_LJMP(luaL_checknumber(L, 2)) * 1000;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002910
Thierry Fournier17a921b2018-03-08 09:59:02 +01002911 /* Check for negative values */
Mark Lakes56cc1252018-03-27 09:48:06 +02002912 if (dtmout < 0)
Thierry Fournier17a921b2018-03-08 09:59:02 +01002913 WILL_LJMP(luaL_error(L, "settimeout: cannot set negatives values"));
2914
Mark Lakes56cc1252018-03-27 09:48:06 +02002915 if (dtmout > INT_MAX) /* overflow check */
Cyril Bonté7ee465f2018-08-19 22:08:50 +02002916 WILL_LJMP(luaL_error(L, "settimeout: cannot set values larger than %d ms", INT_MAX));
Mark Lakes56cc1252018-03-27 09:48:06 +02002917
2918 tmout = MS_TO_TICKS((int)dtmout);
Cyril Bonté7ee465f2018-08-19 22:08:50 +02002919 if (tmout == 0)
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05002920 tmout++; /* very small timeouts are adjusted to a minimum of 1ms */
Mark Lakes56cc1252018-03-27 09:48:06 +02002921
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002922 /* Check if we run on the same thread than the xreator thread.
2923 * We cannot access to the socket if the thread is different.
2924 */
2925 if (socket->tid != tid)
2926 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2927
Mark Lakes56cc1252018-03-27 09:48:06 +02002928 /* check for connection break. If some data were read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002929 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002930 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002931 hlua_pusherror(L, "socket: not yet initialised, you can't set timeouts.");
2932 WILL_LJMP(lua_error(L));
2933 return 0;
2934 }
Willy Tarreau5321da92022-05-06 11:57:34 +02002935
2936 appctx = container_of(peer, struct hlua_csk_ctx, xref)->appctx;
Christopher Faulet908628c2022-03-25 16:43:49 +01002937 s = __cs_strm(appctx->owner);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002938
Cyril Bonté7bb63452018-08-17 23:51:02 +02002939 s->sess->fe->timeout.connect = tmout;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002940 s->req.rto = tmout;
2941 s->req.wto = tmout;
2942 s->res.rto = tmout;
2943 s->res.wto = tmout;
Cyril Bonté7bb63452018-08-17 23:51:02 +02002944 s->req.rex = tick_add_ifset(now_ms, tmout);
2945 s->req.wex = tick_add_ifset(now_ms, tmout);
2946 s->res.rex = tick_add_ifset(now_ms, tmout);
2947 s->res.wex = tick_add_ifset(now_ms, tmout);
2948
2949 s->task->expire = tick_add_ifset(now_ms, tmout);
2950 task_queue(s->task);
2951
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002952 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002953
Thierry Fourniere9636f12018-03-08 09:54:32 +01002954 lua_pushinteger(L, 1);
Tim Duesterhus119a5f12018-01-06 19:16:25 +01002955 return 1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002956}
2957
2958__LJMP static int hlua_socket_new(lua_State *L)
2959{
2960 struct hlua_socket *socket;
Willy Tarreau5321da92022-05-06 11:57:34 +02002961 struct hlua_csk_ctx *ctx;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002962 struct appctx *appctx;
Willy Tarreau15b5e142015-04-04 14:38:25 +02002963 struct session *sess;
Christopher Faulet13a35e52021-12-20 15:34:16 +01002964 struct conn_stream *cs;
Christopher Fauleta9e8b392022-03-23 11:01:09 +01002965 struct stream *s;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002966
2967 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002968 if (!lua_checkstack(L, 3)) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002969 hlua_pusherror(L, "socket: full stack");
2970 goto out_fail_conf;
2971 }
2972
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002973 /* Create the object: obj[0] = userdata. */
2974 lua_newtable(L);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002975 socket = MAY_LJMP(lua_newuserdata(L, sizeof(*socket)));
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002976 lua_rawseti(L, -2, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002977 memset(socket, 0, sizeof(*socket));
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002978 socket->tid = tid;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002979
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05002980 /* Check if the various memory pools are initialized. */
Willy Tarreaubafbe012017-11-24 17:34:44 +01002981 if (!pool_head_stream || !pool_head_buffer) {
Thierry FOURNIER4a6170c2015-03-09 17:07:10 +01002982 hlua_pusherror(L, "socket: uninitialized pools.");
2983 goto out_fail_conf;
2984 }
2985
Willy Tarreau87b09662015-04-03 00:22:06 +02002986 /* Pop a class stream metatable and affect it to the userdata. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002987 lua_rawgeti(L, LUA_REGISTRYINDEX, class_socket_ref);
2988 lua_setmetatable(L, -2);
2989
Willy Tarreaud420a972015-04-06 00:39:18 +02002990 /* Create the applet context */
Christopher Faulet9ec2f4d2022-03-23 15:15:29 +01002991 appctx = appctx_new(&update_applet, NULL);
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002992 if (!appctx) {
2993 hlua_pusherror(L, "socket: out of memory");
Christopher Fauleta9e8b392022-03-23 11:01:09 +01002994 goto out_fail_conf;
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002995 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002996
Willy Tarreau5321da92022-05-06 11:57:34 +02002997 ctx = applet_reserve_svcctx(appctx, sizeof(*ctx));
2998 ctx->connected = 0;
2999 ctx->appctx = appctx;
3000 ctx->die = 0;
3001 LIST_INIT(&ctx->wake_on_write);
3002 LIST_INIT(&ctx->wake_on_read);
Willy Tarreaub2bf8332015-04-04 15:58:58 +02003003
Willy Tarreaud420a972015-04-06 00:39:18 +02003004 /* Now create a session, task and stream for this applet */
Amaury Denoyelle239fdbf2021-03-24 10:22:03 +01003005 sess = session_new(socket_proxy, NULL, &appctx->obj_type);
Willy Tarreaud420a972015-04-06 00:39:18 +02003006 if (!sess) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003007 hlua_pusherror(L, "socket: out of memory");
Christopher Faulet13a35e52021-12-20 15:34:16 +01003008 goto out_fail_appctx;
3009 }
3010
Christopher Faulet9ec2f4d2022-03-23 15:15:29 +01003011 cs = cs_new_from_applet(appctx->endp, sess, &BUF_NULL);
Christopher Fauleta9e8b392022-03-23 11:01:09 +01003012 if (!cs) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003013 hlua_pusherror(L, "socket: out of memory");
Christopher Faulet2479e5f2022-01-19 14:50:11 +01003014 goto out_fail_sess;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003015 }
3016
Christopher Fauleta9e8b392022-03-23 11:01:09 +01003017 s = DISGUISE(cs_strm(cs));
Christopher Faulet2479e5f2022-01-19 14:50:11 +01003018
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003019 /* Initialise cross reference between stream and Lua socket object. */
Willy Tarreau5321da92022-05-06 11:57:34 +02003020 xref_create(&socket->xref, &ctx->xref);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003021
Christopher Faulet6b0a0fb2022-04-04 11:29:28 +02003022 /* Configure "right" conn-stream. this "si" is used to connect
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003023 * and retrieve data from the server. The connection is initialized
3024 * with the "struct server".
3025 */
Christopher Faulet62e75742022-03-31 09:16:34 +02003026 cs_set_state(s->csb, CS_ST_ASS);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003027
3028 /* Force destination server. */
Christopher Fauleta9e8b392022-03-23 11:01:09 +01003029 s->flags |= SF_DIRECT | SF_ASSIGNED | SF_BE_ASSIGNED;
3030 s->target = &socket_tcp->obj_type;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003031
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003032 return 1;
3033
Willy Tarreaud420a972015-04-06 00:39:18 +02003034 out_fail_sess:
Christopher Faulet13a35e52021-12-20 15:34:16 +01003035 session_free(sess);
3036 out_fail_appctx:
Willy Tarreaud420a972015-04-06 00:39:18 +02003037 appctx_free(appctx);
3038 out_fail_conf:
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003039 WILL_LJMP(lua_error(L));
3040 return 0;
3041}
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01003042
3043/*
3044 *
3045 *
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003046 * Class Channel
3047 *
3048 *
3049 */
3050
3051/* Returns the struct hlua_channel join to the class channel in the
3052 * stack entry "ud" or throws an argument error.
3053 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01003054__LJMP static struct channel *hlua_checkchannel(lua_State *L, int ud)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003055{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003056 return MAY_LJMP(hlua_checkudata(L, ud, class_channel_ref));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003057}
3058
Willy Tarreau47860ed2015-03-10 14:07:50 +01003059/* Pushes the channel onto the top of the stack. If the stask does not have a
3060 * free slots, the function fails and returns 0;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003061 */
Willy Tarreau2a71af42015-03-10 13:51:50 +01003062static int hlua_channel_new(lua_State *L, struct channel *channel)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003063{
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003064 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003065 if (!lua_checkstack(L, 3))
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003066 return 0;
3067
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003068 lua_newtable(L);
Willy Tarreau47860ed2015-03-10 14:07:50 +01003069 lua_pushlightuserdata(L, channel);
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003070 lua_rawseti(L, -2, 0);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003071
3072 /* Pop a class sesison metatable and affect it to the userdata. */
3073 lua_rawgeti(L, LUA_REGISTRYINDEX, class_channel_ref);
3074 lua_setmetatable(L, -2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003075 return 1;
3076}
3077
Christopher Faulet9f55a502020-02-25 15:21:02 +01003078/* Helper function returning a filter attached to a channel at the position <ud>
3079 * in the stack, filling the current offset and length of the filter. If no
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05003080 * filter is attached, NULL is returned and <offset> and <len> are not
Christopher Faulet9f55a502020-02-25 15:21:02 +01003081 * initialized.
3082 */
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003083static 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 +01003084{
3085 struct filter *filter = NULL;
3086
3087 if (lua_getfield(L, ud, "__filter") == LUA_TLIGHTUSERDATA) {
3088 struct hlua_flt_ctx *flt_ctx;
3089
3090 filter = lua_touserdata (L, -1);
3091 flt_ctx = filter->ctx;
3092 if (hlua_filter_from_payload(filter)) {
3093 *offset = flt_ctx->cur_off[CHN_IDX(chn)];
3094 *len = flt_ctx->cur_len[CHN_IDX(chn)];
3095 }
3096 }
3097
3098 lua_pop(L, 1);
3099 return filter;
3100}
3101
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003102/* Copies <len> bytes of data present in the channel's buffer, starting at the
3103* offset <offset>, and put it in a LUA string variable. It is the caller
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003104* responsibility to ensure <len> and <offset> are valid. It always return the
3105* length of the built string. <len> may be 0, in this case, an empty string is
3106* created and 0 is returned.
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003107*/
3108static inline int _hlua_channel_dup(struct channel *chn, lua_State *L, size_t offset, size_t len)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003109{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003110 size_t block1, block2;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003111 luaL_Buffer b;
3112
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003113 block1 = len;
3114 if (block1 > b_contig_data(&chn->buf, b_peek_ofs(&chn->buf, offset)))
3115 block1 = b_contig_data(&chn->buf, b_peek_ofs(&chn->buf, offset));
3116 block2 = len - block1;
3117
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003118 luaL_buffinit(L, &b);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003119 luaL_addlstring(&b, b_peek(&chn->buf, offset), block1);
3120 if (block2)
3121 luaL_addlstring(&b, b_orig(&chn->buf), block2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003122 luaL_pushresult(&b);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003123 return len;
3124}
3125
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003126/* Inserts the string <str> to the channel's buffer at the offset <offset>. This
3127 * function returns -1 if data cannot be copied. Otherwise, it returns the
3128 * number of bytes copied.
3129 */
3130static int _hlua_channel_insert(struct channel *chn, lua_State *L, struct ist str, size_t offset)
3131{
3132 int ret = 0;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003133
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003134 /* Nothing to do, just return */
3135 if (unlikely(istlen(str) == 0))
3136 goto end;
3137
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003138 if (istlen(str) > c_room(chn)) {
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003139 ret = -1;
3140 goto end;
3141 }
3142 ret = b_insert_blk(&chn->buf, offset, istptr(str), istlen(str));
3143
3144 end:
3145 return ret;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003146}
3147
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003148/* Removes <len> bytes of data at the absolute position <offset>.
3149 */
3150static void _hlua_channel_delete(struct channel *chn, size_t offset, size_t len)
3151{
3152 size_t end = offset + len;
3153
3154 if (b_peek(&chn->buf, end) != b_tail(&chn->buf))
3155 b_move(&chn->buf, b_peek_ofs(&chn->buf, end),
3156 b_data(&chn->buf) - end, -len);
3157 b_sub(&chn->buf, len);
3158}
3159
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003160/* Copies input data in the channel's buffer. It is possible to set a specific
3161 * offset (0 by default) and a length (all remaining input data starting for the
3162 * offset by default). If there is not enough input data and more data can be
3163 * received, this function yields.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003164 *
3165 * From an action, All input data are considered. For a filter, the offset and
3166 * the length of input data to consider are retrieved from the filter context.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003167 */
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003168__LJMP static int hlua_channel_get_data_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003169{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003170 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003171 struct filter *filter;
3172 size_t input, output;
3173 int offset, len;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003174
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003175 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003176
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003177 output = co_data(chn);
3178 input = ci_data(chn);
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003179
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003180 filter = hlua_channel_filter(L, 1, chn, &output, &input);
3181 if (filter && !hlua_filter_from_payload(filter))
3182 WILL_LJMP(lua_error(L));
3183
3184 offset = output;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003185 if (lua_gettop(L) > 1) {
3186 offset = MAY_LJMP(luaL_checkinteger(L, 2));
3187 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02003188 offset = MAX(0, (int)input + offset);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003189 offset += output;
3190 if (offset < output || offset > input + output) {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003191 lua_pushfstring(L, "offset out of range.");
3192 WILL_LJMP(lua_error(L));
3193 }
3194 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003195 len = output + input - offset;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003196 if (lua_gettop(L) == 3) {
3197 len = MAY_LJMP(luaL_checkinteger(L, 3));
3198 if (!len)
3199 goto dup;
3200 if (len == -1)
3201 len = global.tune.bufsize;
3202 if (len < 0) {
3203 lua_pushfstring(L, "length out of range.");
3204 WILL_LJMP(lua_error(L));
3205 }
3206 }
3207
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003208 if (offset + len > output + input) {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003209 if (!HLUA_CANT_YIELD(hlua_gethlua(L)) && !channel_input_closed(chn) && channel_may_recv(chn)) {
3210 /* Yield waiting for more data, as requested */
3211 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_get_data_yield, TICK_ETERNITY, 0));
3212 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003213 len = output + input - offset;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003214 }
3215
3216 dup:
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003217 _hlua_channel_dup(chn, L, offset, len);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003218 return 1;
3219}
3220
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003221/* Copies the first line (including the trailing LF) of input data in the
3222 * channel's buffer. It is possible to set a specific offset (0 by default) and
3223 * a length (all remaining input data starting for the offset by default). If
3224 * there is not enough input data and more data can be received, the function
3225 * yields. If a length is explicitly specified, no more data are
3226 * copied. Otherwise, if no LF is found and more data can be received, this
3227 * function yields.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003228 *
3229 * From an action, All input data are considered. For a filter, the offset and
3230 * the length of input data to consider are retrieved from the filter context.
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003231 */
3232__LJMP static int hlua_channel_get_line_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003233{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003234 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003235 struct filter *filter;
3236 size_t l, input, output;
3237 int offset, len;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003238
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003239 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003240 output = co_data(chn);
3241 input = ci_data(chn);
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003242
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003243 filter = hlua_channel_filter(L, 1, chn, &output, &input);
3244 if (filter && !hlua_filter_from_payload(filter))
3245 WILL_LJMP(lua_error(L));
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003246
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003247 offset = output;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003248 if (lua_gettop(L) > 1) {
3249 offset = MAY_LJMP(luaL_checkinteger(L, 2));
3250 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02003251 offset = MAX(0, (int)input + offset);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003252 offset += output;
3253 if (offset < output || offset > input + output) {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003254 lua_pushfstring(L, "offset out of range.");
3255 WILL_LJMP(lua_error(L));
3256 }
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003257 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003258
3259 len = output + input - offset;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003260 if (lua_gettop(L) == 3) {
3261 len = MAY_LJMP(luaL_checkinteger(L, 3));
3262 if (!len)
3263 goto dup;
3264 if (len == -1)
3265 len = global.tune.bufsize;
3266 if (len < 0) {
3267 lua_pushfstring(L, "length out of range.");
3268 WILL_LJMP(lua_error(L));
3269 }
3270 }
3271
3272 for (l = 0; l < len; l++) {
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003273 if (l + offset >= output + input)
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003274 break;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003275 if (*(b_peek(&chn->buf, offset + l)) == '\n') {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003276 len = l+1;
3277 goto dup;
3278 }
3279 }
3280
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003281 if (offset + len > output + input) {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003282 if (!HLUA_CANT_YIELD(hlua_gethlua(L)) && !channel_input_closed(chn) && channel_may_recv(chn)) {
3283 /* Yield waiting for more data */
3284 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_get_line_yield, TICK_ETERNITY, 0));
3285 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003286 len = output + input - offset;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003287 }
3288
3289 dup:
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003290 _hlua_channel_dup(chn, L, offset, len);
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003291 return 1;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003292}
3293
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003294/* [ DEPRECATED ]
3295 *
3296 * Duplicate all input data foud in the channel's buffer. The data are not
3297 * removed from the buffer. This function relies on _hlua_channel_dup().
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003298 *
3299 * From an action, All input data are considered. For a filter, the offset and
3300 * the length of input data to consider are retrieved from the filter context.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003301 */
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003302__LJMP static int hlua_channel_dup(lua_State *L)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003303{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003304 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003305 struct filter *filter;
3306 size_t offset, len;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003307
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003308 MAY_LJMP(check_args(L, 1, "dup"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003309 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003310 if (IS_HTX_STRM(chn_strm(chn))) {
3311 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3312 WILL_LJMP(lua_error(L));
3313 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003314
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003315 offset = co_data(chn);
3316 len = ci_data(chn);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003317
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003318 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3319 if (filter && !hlua_filter_from_payload(filter))
3320 WILL_LJMP(lua_error(L));
3321
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003322 if (!ci_data(chn) && channel_input_closed(chn)) {
3323 lua_pushnil(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003324 return 1;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003325 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003326
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003327 _hlua_channel_dup(chn, L, offset, len);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003328 return 1;
3329}
3330
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003331/* [ DEPRECATED ]
3332 *
3333 * Get all input data foud in the channel's buffer. The data are removed from
3334 * the buffer after the copy. This function relies on _hlua_channel_dup() and
3335 * _hlua_channel_delete().
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003336 *
3337 * From an action, All input data are considered. For a filter, the offset and
3338 * the length of input data to consider are retrieved from the filter context.
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003339 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003340__LJMP static int hlua_channel_get(lua_State *L)
3341{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003342 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003343 struct filter *filter;
3344 size_t offset, len;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003345 int ret;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003346
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003347 MAY_LJMP(check_args(L, 1, "get"));
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003348 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3349 if (IS_HTX_STRM(chn_strm(chn))) {
3350 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3351 WILL_LJMP(lua_error(L));
3352 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003353
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003354 offset = co_data(chn);
3355 len = ci_data(chn);
3356
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003357 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3358 if (filter && !hlua_filter_from_payload(filter))
3359 WILL_LJMP(lua_error(L));
3360
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003361 if (!ci_data(chn) && channel_input_closed(chn)) {
3362 lua_pushnil(L);
3363 return 1;
3364 }
3365
3366 ret = _hlua_channel_dup(chn, L, offset, len);
3367 _hlua_channel_delete(chn, offset, ret);
3368 return 1;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003369}
3370
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003371/* This functions consumes and returns one line. If the channel is closed,
3372 * and the last data does not contains a final '\n', the data are returned
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003373 * without the final '\n'. When no more data are available, it returns nil
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003374 * value.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003375 *
3376 * From an action, All input data are considered. For a filter, the offset and
3377 * the length of input data to consider are retrieved from the filter context.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003378 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003379__LJMP static int hlua_channel_getline_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003380{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003381 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003382 struct filter *filter;
3383 size_t l, offset, len;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003384 int ret;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003385
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003386 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003387
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003388 offset = co_data(chn);
3389 len = ci_data(chn);
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003390
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003391 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3392 if (filter && !hlua_filter_from_payload(filter))
3393 WILL_LJMP(lua_error(L));
3394
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003395 if (!ci_data(chn) && channel_input_closed(chn)) {
3396 lua_pushnil(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003397 return 1;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003398 }
3399
3400 for (l = 0; l < len; l++) {
3401 if (*(b_peek(&chn->buf, offset+l)) == '\n') {
3402 len = l+1;
3403 goto dup;
3404 }
3405 }
3406
3407 if (!HLUA_CANT_YIELD(hlua_gethlua(L)) && !channel_input_closed(chn) && channel_may_recv(chn)) {
3408 /* Yield waiting for more data */
3409 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_getline_yield, TICK_ETERNITY, 0));
3410 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003411
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003412 dup:
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003413 ret = _hlua_channel_dup(chn, L, offset, len);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003414 _hlua_channel_delete(chn, offset, ret);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003415 return 1;
3416}
3417
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003418/* [ DEPRECATED ]
3419 *
3420 * Check arguments for the function "hlua_channel_getline_yield".
3421 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003422__LJMP static int hlua_channel_getline(lua_State *L)
3423{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003424 struct channel *chn;
3425
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003426 MAY_LJMP(check_args(L, 1, "getline"));
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003427 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3428 if (IS_HTX_STRM(chn_strm(chn))) {
3429 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3430 WILL_LJMP(lua_error(L));
3431 }
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003432 return MAY_LJMP(hlua_channel_getline_yield(L, 0, 0));
3433}
3434
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003435/* Retrieves a given amount of input data at the given offset. By default all
3436 * available input data are returned. The offset may be negactive to start from
3437 * the end of input data. The length may be -1 to set it to the maximum buffer
3438 * size.
3439 */
3440__LJMP static int hlua_channel_get_data(lua_State *L)
3441{
3442 struct channel *chn;
3443
3444 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
3445 WILL_LJMP(luaL_error(L, "'data' expects at most 2 arguments"));
3446 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3447 if (IS_HTX_STRM(chn_strm(chn))) {
3448 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3449 WILL_LJMP(lua_error(L));
3450 }
3451 return MAY_LJMP(hlua_channel_get_data_yield(L, 0, 0));
3452}
3453
3454/* Retrieves a given amount of input data at the given offset. By default all
3455 * available input data are returned. The offset may be negactive to start from
3456 * the end of input data. The length may be -1 to set it to the maximum buffer
3457 * size.
3458 */
3459__LJMP static int hlua_channel_get_line(lua_State *L)
3460{
3461 struct channel *chn;
3462
3463 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
3464 WILL_LJMP(luaL_error(L, "'line' expects at most 2 arguments"));
3465 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3466 if (IS_HTX_STRM(chn_strm(chn))) {
3467 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3468 WILL_LJMP(lua_error(L));
3469 }
3470 return MAY_LJMP(hlua_channel_get_line_yield(L, 0, 0));
3471}
3472
3473/* Appends a string into the input side of channel. It returns the length of the
3474 * written string, or -1 if the channel is closed or if the buffer size is too
3475 * little for the data. 0 may be returned if nothing is copied. This function
3476 * does not yield.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003477 *
3478 * For a filter, the context is updated on success.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003479 */
Christopher Faulet23976d92021-08-06 09:59:49 +02003480__LJMP static int hlua_channel_append(lua_State *L)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003481{
Christopher Faulet23976d92021-08-06 09:59:49 +02003482 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003483 struct filter *filter;
Christopher Faulet23976d92021-08-06 09:59:49 +02003484 const char *str;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003485 size_t sz, offset, len;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003486 int ret;
Christopher Faulet23976d92021-08-06 09:59:49 +02003487
3488 MAY_LJMP(check_args(L, 2, "append"));
3489 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003490 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
Christopher Faulet1bb6afa2021-03-08 17:57:53 +01003491 if (IS_HTX_STRM(chn_strm(chn))) {
Thierry Fournier77016da2020-08-15 14:35:51 +02003492 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
Christopher Faulet3f829a42018-12-13 21:56:45 +01003493 WILL_LJMP(lua_error(L));
Thierry Fournier77016da2020-08-15 14:35:51 +02003494 }
Christopher Faulet3f829a42018-12-13 21:56:45 +01003495
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003496 offset = co_data(chn);
3497 len = ci_data(chn);
3498
3499 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3500 if (filter && !hlua_filter_from_payload(filter))
3501 WILL_LJMP(lua_error(L));
3502
3503 ret = _hlua_channel_insert(chn, L, ist2(str, sz), offset);
3504 if (ret > 0 && filter) {
3505 struct hlua_flt_ctx *flt_ctx = filter->ctx;
3506
3507 flt_update_offsets(filter, chn, ret);
3508 flt_ctx->cur_len[CHN_IDX(chn)] += ret;
3509 }
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003510 lua_pushinteger(L, ret);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003511 return 1;
3512}
3513
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003514/* Prepends a string into the input side of channel. It returns the length of the
3515 * written string, or -1 if the channel is closed or if the buffer size is too
3516 * little for the data. 0 may be returned if nothing is copied. This function
3517 * does not yield.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003518 *
3519 * For a filter, the context is updated on success.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003520 */
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003521__LJMP static int hlua_channel_prepend(lua_State *L)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003522{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003523 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003524 struct filter *filter;
Christopher Faulet23976d92021-08-06 09:59:49 +02003525 const char *str;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003526 size_t sz, offset, len;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003527 int ret;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003528
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003529 MAY_LJMP(check_args(L, 2, "prepend"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003530 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003531 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
3532 if (IS_HTX_STRM(chn_strm(chn))) {
3533 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3534 WILL_LJMP(lua_error(L));
3535 }
3536
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003537 offset = co_data(chn);
3538 len = ci_data(chn);
3539
3540 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3541 if (filter && !hlua_filter_from_payload(filter))
3542 WILL_LJMP(lua_error(L));
3543
3544 ret = _hlua_channel_insert(chn, L, ist2(str, sz), offset);
3545 if (ret > 0 && filter) {
3546 struct hlua_flt_ctx *flt_ctx = filter->ctx;
3547
3548 flt_update_offsets(filter, chn, ret);
3549 flt_ctx->cur_len[CHN_IDX(chn)] += ret;
3550 }
3551
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003552 lua_pushinteger(L, ret);
3553 return 1;
3554}
3555
3556/* Inserts a given amount of input data at the given offset by a string
3557 * content. By default the string is appended at the end of input data. It
3558 * returns the length of the written string, or -1 if the channel is closed or
3559 * if the buffer size is too little for the data.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003560 *
3561 * For a filter, the context is updated on success.
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003562 */
3563__LJMP static int hlua_channel_insert_data(lua_State *L)
3564{
3565 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003566 struct filter *filter;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003567 const char *str;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003568 size_t sz, input, output;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003569 int ret, offset;
3570
3571 if (lua_gettop(L) < 2 || lua_gettop(L) > 3)
3572 WILL_LJMP(luaL_error(L, "'insert' expects at least 1 argument and at most 2 arguments"));
3573 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3574 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003575
3576 output = co_data(chn);
3577 input = ci_data(chn);
3578
3579 filter = hlua_channel_filter(L, 1, chn, &output, &input);
3580 if (filter && !hlua_filter_from_payload(filter))
3581 WILL_LJMP(lua_error(L));
3582
3583 offset = input + output;
3584 if (lua_gettop(L) > 2) {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003585 offset = MAY_LJMP(luaL_checkinteger(L, 3));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003586 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02003587 offset = MAX(0, (int)input + offset);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003588 offset += output;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003589 if (offset < output || offset > output + input) {
3590 lua_pushfstring(L, "offset out of range.");
3591 WILL_LJMP(lua_error(L));
3592 }
3593 }
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003594 if (IS_HTX_STRM(chn_strm(chn))) {
3595 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3596 WILL_LJMP(lua_error(L));
3597 }
3598
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003599 ret = _hlua_channel_insert(chn, L, ist2(str, sz), offset);
3600 if (ret > 0 && filter) {
3601 struct hlua_flt_ctx *flt_ctx = filter->ctx;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003602
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003603 flt_update_offsets(filter, chn, ret);
3604 flt_ctx->cur_len[CHN_IDX(chn)] += ret;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003605 }
3606
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003607 lua_pushinteger(L, ret);
3608 return 1;
3609}
3610/* Replaces a given amount of input data at the given offset by a string
3611 * content. By default all remaining data are removed (offset = 0 and len =
3612 * -1). It returns the length of the written string, or -1 if the channel is
3613 * closed or if the buffer size is too little for the data.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003614 *
3615 * For a filter, the context is updated on success.
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003616 */
3617__LJMP static int hlua_channel_set_data(lua_State *L)
3618{
3619 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003620 struct filter *filter;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003621 const char *str;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003622 size_t sz, input, output;
3623 int ret, offset, len;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003624
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003625 if (lua_gettop(L) < 2 || lua_gettop(L) > 4)
3626 WILL_LJMP(luaL_error(L, "'set' expects at least 1 argument and at most 3 arguments"));
3627 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3628 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003629
Christopher Faulet1bb6afa2021-03-08 17:57:53 +01003630 if (IS_HTX_STRM(chn_strm(chn))) {
Thierry Fournier77016da2020-08-15 14:35:51 +02003631 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
Christopher Faulet3f829a42018-12-13 21:56:45 +01003632 WILL_LJMP(lua_error(L));
Thierry Fournier77016da2020-08-15 14:35:51 +02003633 }
Christopher Faulet3f829a42018-12-13 21:56:45 +01003634
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003635 output = co_data(chn);
3636 input = ci_data(chn);
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003637
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003638 filter = hlua_channel_filter(L, 1, chn, &output, &input);
3639 if (filter && !hlua_filter_from_payload(filter))
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003640 WILL_LJMP(lua_error(L));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003641
3642 offset = output;
3643 if (lua_gettop(L) > 2) {
3644 offset = MAY_LJMP(luaL_checkinteger(L, 3));
3645 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02003646 offset = MAX(0, (int)input + offset);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003647 offset += output;
3648 if (offset < output || offset > input + output) {
3649 lua_pushfstring(L, "offset out of range.");
3650 WILL_LJMP(lua_error(L));
3651 }
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003652 }
3653
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003654 len = output + input - offset;
3655 if (lua_gettop(L) == 4) {
3656 len = MAY_LJMP(luaL_checkinteger(L, 4));
3657 if (!len)
3658 goto set;
3659 if (len == -1)
3660 len = output + input - offset;
3661 if (len < 0 || offset + len > output + input) {
3662 lua_pushfstring(L, "length out of range.");
3663 WILL_LJMP(lua_error(L));
3664 }
3665 }
3666
3667 set:
Christopher Faulet23976d92021-08-06 09:59:49 +02003668 /* Be sure we can copied the string once input data will be removed. */
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003669 if (sz > c_room(chn) + len)
Christopher Faulet23976d92021-08-06 09:59:49 +02003670 lua_pushinteger(L, -1);
3671 else {
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003672 _hlua_channel_delete(chn, offset, len);
3673 ret = _hlua_channel_insert(chn, L, ist2(str, sz), offset);
3674 if (filter) {
3675 struct hlua_flt_ctx *flt_ctx = filter->ctx;
3676
3677 len -= (ret > 0 ? ret : 0);
3678 flt_update_offsets(filter, chn, -len);
3679 flt_ctx->cur_len[CHN_IDX(chn)] -= len;
3680 }
3681
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003682 lua_pushinteger(L, ret);
Christopher Faulet23976d92021-08-06 09:59:49 +02003683 }
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003684 return 1;
3685}
3686
3687/* Removes a given amount of input data at the given offset. By default all
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003688 * input data are removed (offset = 0 and len = -1). It returns the amount of
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003689 * the removed data.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003690 *
3691 * For a filter, the context is updated on success.
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003692 */
3693__LJMP static int hlua_channel_del_data(lua_State *L)
3694{
3695 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003696 struct filter *filter;
3697 size_t input, output;
3698 int offset, len;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003699
3700 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
3701 WILL_LJMP(luaL_error(L, "'remove' expects at most 2 arguments"));
3702 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003703
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003704 if (IS_HTX_STRM(chn_strm(chn))) {
3705 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3706 WILL_LJMP(lua_error(L));
3707 }
3708
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003709 output = co_data(chn);
3710 input = ci_data(chn);
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003711
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003712 filter = hlua_channel_filter(L, 1, chn, &output, &input);
3713 if (filter && !hlua_filter_from_payload(filter))
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003714 WILL_LJMP(lua_error(L));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003715
3716 offset = output;
3717 if (lua_gettop(L) > 2) {
3718 offset = MAY_LJMP(luaL_checkinteger(L, 3));
3719 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02003720 offset = MAX(0, (int)input + offset);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003721 offset += output;
3722 if (offset < output || offset > input + output) {
3723 lua_pushfstring(L, "offset out of range.");
3724 WILL_LJMP(lua_error(L));
3725 }
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003726 }
3727
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003728 len = output + input - offset;
3729 if (lua_gettop(L) == 4) {
3730 len = MAY_LJMP(luaL_checkinteger(L, 4));
3731 if (!len)
3732 goto end;
3733 if (len == -1)
3734 len = output + input - offset;
3735 if (len < 0 || offset + len > output + input) {
3736 lua_pushfstring(L, "length out of range.");
3737 WILL_LJMP(lua_error(L));
3738 }
3739 }
3740
3741 _hlua_channel_delete(chn, offset, len);
3742 if (filter) {
3743 struct hlua_flt_ctx *flt_ctx = filter->ctx;
3744
3745 flt_update_offsets(filter, chn, -len);
3746 flt_ctx->cur_len[CHN_IDX(chn)] -= len;
3747 }
3748
3749 end:
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003750 lua_pushinteger(L, len);
Christopher Faulet23976d92021-08-06 09:59:49 +02003751 return 1;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003752}
3753
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003754/* Append data in the output side of the buffer. This data is immediately
3755 * sent. The function returns the amount of data written. If the buffer
3756 * cannot contain the data, the function yields. The function returns -1
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003757 * if the channel is closed.
3758 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003759__LJMP static int hlua_channel_send_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003760{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003761 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003762 struct filter *filter;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003763 const char *str;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003764 size_t offset, len, sz;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003765 int l, ret;
Thierry Fournier4234dbd2020-11-28 13:18:23 +01003766 struct hlua *hlua;
3767
3768 /* Get hlua struct, or NULL if we execute from main lua state */
3769 hlua = hlua_gethlua(L);
3770 if (!hlua) {
3771 lua_pushnil(L);
3772 return 1;
3773 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003774
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003775 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3776 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
3777 l = MAY_LJMP(luaL_checkinteger(L, 3));
Christopher Faulet3f829a42018-12-13 21:56:45 +01003778
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003779 offset = co_data(chn);
3780 len = ci_data(chn);
3781
3782 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3783 if (filter && !hlua_filter_from_payload(filter))
3784 WILL_LJMP(lua_error(L));
3785
3786
Willy Tarreau47860ed2015-03-10 14:07:50 +01003787 if (unlikely(channel_output_closed(chn))) {
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003788 lua_pushinteger(L, -1);
3789 return 1;
3790 }
3791
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003792 len = c_room(chn);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003793 if (len > sz -l) {
3794 if (filter) {
3795 lua_pushinteger(L, -1);
3796 return 1;
3797 }
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003798 len = sz - l;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003799 }
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01003800
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003801 ret = _hlua_channel_insert(chn, L, ist2(str, len), offset);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003802 if (ret == -1) {
3803 lua_pop(L, 1);
3804 lua_pushinteger(L, -1);
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01003805 return 1;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003806 }
3807 if (ret) {
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003808 if (filter) {
3809 struct hlua_flt_ctx *flt_ctx = filter->ctx;
3810
3811
3812 flt_update_offsets(filter, chn, ret);
3813 FLT_OFF(filter, chn) += ret;
3814 flt_ctx->cur_off[CHN_IDX(chn)] += ret;
3815 }
3816 else
3817 c_adv(chn, ret);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003818
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003819 l += ret;
3820 lua_pop(L, 1);
3821 lua_pushinteger(L, l);
3822 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003823
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003824 if (l < sz) {
3825 /* Yield only if the channel's output is not empty.
3826 * Otherwise it means we cannot add more data. */
3827 if (co_data(chn) == 0 || HLUA_CANT_YIELD(hlua_gethlua(L)))
Christopher Faulet2e60aa42021-08-05 11:58:37 +02003828 return 1;
3829
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003830 /* If we are waiting for space in the response buffer, we
3831 * must set the flag WAKERESWR. This flag required the task
3832 * wake up if any activity is detected on the response buffer.
3833 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01003834 if (chn->flags & CF_ISRESP)
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003835 HLUA_SET_WAKERESWR(hlua);
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01003836 else
3837 HLUA_SET_WAKEREQWR(hlua);
Willy Tarreau9635e032018-10-16 17:52:55 +02003838 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003839 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003840
3841 return 1;
3842}
3843
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05003844/* Just a wrapper of "_hlua_channel_send". This wrapper permits
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003845 * yield the LUA process, and resume it without checking the
3846 * input arguments.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003847 *
3848 * This function cannot be called from a filter.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003849 */
3850__LJMP static int hlua_channel_send(lua_State *L)
3851{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003852 struct channel *chn;
3853
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003854 MAY_LJMP(check_args(L, 2, "send"));
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003855 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3856 if (IS_HTX_STRM(chn_strm(chn))) {
3857 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3858 WILL_LJMP(lua_error(L));
3859 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003860 lua_pushinteger(L, 0);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003861 return MAY_LJMP(hlua_channel_send_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003862}
3863
3864/* This function forward and amount of butes. The data pass from
3865 * the input side of the buffer to the output side, and can be
3866 * forwarded. This function never fails.
3867 *
3868 * The Lua function takes an amount of bytes to be forwarded in
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05003869 * input. It returns the number of bytes forwarded.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003870 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003871__LJMP static int hlua_channel_forward_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003872{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003873 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003874 struct filter *filter;
3875 size_t offset, len, fwd;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003876 int l, max;
Thierry Fournier4234dbd2020-11-28 13:18:23 +01003877 struct hlua *hlua;
3878
3879 /* Get hlua struct, or NULL if we execute from main lua state */
3880 hlua = hlua_gethlua(L);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003881 if (!hlua) {
3882 lua_pushnil(L);
Thierry Fournier4234dbd2020-11-28 13:18:23 +01003883 return 1;
Thierry Fournier77016da2020-08-15 14:35:51 +02003884 }
Christopher Faulet3f829a42018-12-13 21:56:45 +01003885
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003886 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003887 fwd = MAY_LJMP(luaL_checkinteger(L, 2));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003888 l = MAY_LJMP(luaL_checkinteger(L, -1));
3889
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003890 offset = co_data(chn);
3891 len = ci_data(chn);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003892
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003893 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3894 if (filter && !hlua_filter_from_payload(filter))
3895 WILL_LJMP(lua_error(L));
3896
3897 max = fwd - l;
3898 if (max > len)
3899 max = len;
3900
3901 if (filter) {
3902 struct hlua_flt_ctx *flt_ctx = filter->ctx;
3903
3904 FLT_OFF(filter, chn) += max;
3905 flt_ctx->cur_off[CHN_IDX(chn)] += max;
3906 flt_ctx->cur_len[CHN_IDX(chn)] -= max;
3907 }
3908 else
3909 channel_forward(chn, max);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003910
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003911 l += max;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003912 lua_pop(L, 1);
3913 lua_pushinteger(L, l);
3914
3915 /* Check if it miss bytes to forward. */
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003916 if (l < fwd) {
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003917 /* The the input channel or the output channel are closed, we
3918 * must return the amount of data forwarded.
3919 */
Christopher Faulet2e60aa42021-08-05 11:58:37 +02003920 if (channel_input_closed(chn) || channel_output_closed(chn) || HLUA_CANT_YIELD(hlua_gethlua(L)))
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003921 return 1;
3922
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003923 /* If we are waiting for space data in the response buffer, we
3924 * must set the flag WAKERESWR. This flag required the task
3925 * wake up if any activity is detected on the response buffer.
3926 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01003927 if (chn->flags & CF_ISRESP)
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003928 HLUA_SET_WAKERESWR(hlua);
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01003929 else
3930 HLUA_SET_WAKEREQWR(hlua);
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003931
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003932 /* Otherwise, we can yield waiting for new data in the inpout side. */
Willy Tarreau9635e032018-10-16 17:52:55 +02003933 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_forward_yield, TICK_ETERNITY, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003934 }
3935
3936 return 1;
3937}
3938
3939/* Just check the input and prepare the stack for the previous
3940 * function "hlua_channel_forward_yield"
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003941 *
3942 * This function cannot be called from a filter.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003943 */
3944__LJMP static int hlua_channel_forward(lua_State *L)
3945{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003946 struct channel *chn;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003947
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003948 MAY_LJMP(check_args(L, 2, "forward"));
3949 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3950 if (IS_HTX_STRM(chn_strm(chn))) {
3951 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3952 WILL_LJMP(lua_error(L));
3953 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003954 lua_pushinteger(L, 0);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003955 return MAY_LJMP(hlua_channel_forward_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003956}
3957
3958/* Just returns the number of bytes available in the input
3959 * side of the buffer. This function never fails.
3960 */
3961__LJMP static int hlua_channel_get_in_len(lua_State *L)
3962{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003963 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003964 struct filter *filter;
3965 size_t output, input;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003966
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003967 MAY_LJMP(check_args(L, 1, "input"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003968 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003969
3970 output = co_data(chn);
3971 input = ci_data(chn);
3972 filter = hlua_channel_filter(L, 1, chn, &output, &input);
3973 if (filter || !IS_HTX_STRM(chn_strm(chn)))
3974 lua_pushinteger(L, input);
3975 else {
Christopher Fauleta3ceac12018-12-14 13:39:09 +01003976 struct htx *htx = htxbuf(&chn->buf);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003977
Christopher Fauleta3ceac12018-12-14 13:39:09 +01003978 lua_pushinteger(L, htx->data - co_data(chn));
3979 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003980 return 1;
3981}
3982
Thierry FOURNIER / OZON.IO65192f32016-11-07 15:28:40 +01003983/* Returns true if the channel is full. */
3984__LJMP static int hlua_channel_is_full(lua_State *L)
3985{
3986 struct channel *chn;
Thierry FOURNIER / OZON.IO65192f32016-11-07 15:28:40 +01003987
3988 MAY_LJMP(check_args(L, 1, "is_full"));
3989 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Faulet0ec740e2020-02-26 11:59:19 +01003990 /* ignore the reserve, we are not on a producer side (ie in an
3991 * applet).
3992 */
3993 lua_pushboolean(L, channel_full(chn, 0));
Thierry FOURNIER / OZON.IO65192f32016-11-07 15:28:40 +01003994 return 1;
3995}
3996
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003997/* Returns true if the channel may still receive data. */
3998__LJMP static int hlua_channel_may_recv(lua_State *L)
3999{
4000 struct channel *chn;
4001
4002 MAY_LJMP(check_args(L, 1, "may_recv"));
4003 chn = MAY_LJMP(hlua_checkchannel(L, 1));
4004 lua_pushboolean(L, (!channel_input_closed(chn) && channel_may_recv(chn)));
4005 return 1;
4006}
4007
Christopher Faulet2ac9ba22020-02-25 10:15:50 +01004008/* Returns true if the channel is the response channel. */
4009__LJMP static int hlua_channel_is_resp(lua_State *L)
4010{
4011 struct channel *chn;
4012
4013 MAY_LJMP(check_args(L, 1, "is_resp"));
4014 chn = MAY_LJMP(hlua_checkchannel(L, 1));
4015
4016 lua_pushboolean(L, !!(chn->flags & CF_ISRESP));
4017 return 1;
4018}
4019
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004020/* Just returns the number of bytes available in the output
4021 * side of the buffer. This function never fails.
4022 */
4023__LJMP static int hlua_channel_get_out_len(lua_State *L)
4024{
Willy Tarreau47860ed2015-03-10 14:07:50 +01004025 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004026 size_t output, input;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004027
Christopher Faulet6a79fc12021-08-06 16:02:36 +02004028 MAY_LJMP(check_args(L, 1, "output"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004029 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004030
4031 output = co_data(chn);
4032 input = ci_data(chn);
4033 hlua_channel_filter(L, 1, chn, &output, &input);
4034
4035 lua_pushinteger(L, output);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004036 return 1;
4037}
4038
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004039/*
4040 *
4041 *
4042 * Class Fetches
4043 *
4044 *
4045 */
4046
4047/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02004048 * a class stream, otherwise it throws an error.
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004049 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004050__LJMP static struct hlua_smp *hlua_checkfetches(lua_State *L, int ud)
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004051{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004052 return MAY_LJMP(hlua_checkudata(L, ud, class_fetches_ref));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004053}
4054
4055/* This function creates and push in the stack a fetch object according
4056 * with a current TXN.
4057 */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004058static int hlua_fetches_new(lua_State *L, struct hlua_txn *txn, unsigned int flags)
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004059{
Willy Tarreau7073c472015-04-06 11:15:40 +02004060 struct hlua_smp *hsmp;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004061
4062 /* Check stack size. */
4063 if (!lua_checkstack(L, 3))
4064 return 0;
4065
4066 /* Create the object: obj[0] = userdata.
4067 * Note that the base of the Fetches object is the
4068 * transaction object.
4069 */
4070 lua_newtable(L);
Willy Tarreau7073c472015-04-06 11:15:40 +02004071 hsmp = lua_newuserdata(L, sizeof(*hsmp));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004072 lua_rawseti(L, -2, 0);
4073
Willy Tarreau7073c472015-04-06 11:15:40 +02004074 hsmp->s = txn->s;
4075 hsmp->p = txn->p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01004076 hsmp->dir = txn->dir;
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004077 hsmp->flags = flags;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004078
4079 /* Pop a class sesison metatable and affect it to the userdata. */
4080 lua_rawgeti(L, LUA_REGISTRYINDEX, class_fetches_ref);
4081 lua_setmetatable(L, -2);
4082
4083 return 1;
4084}
4085
4086/* This function is an LUA binding. It is called with each sample-fetch.
4087 * It uses closure argument to store the associated sample-fetch. It
4088 * returns only one argument or throws an error. An error is thrown
4089 * only if an error is encountered during the argument parsing. If
4090 * the "sample-fetch" function fails, nil is returned.
4091 */
4092__LJMP static int hlua_run_sample_fetch(lua_State *L)
4093{
Willy Tarreaub2ccb562015-04-06 11:11:15 +02004094 struct hlua_smp *hsmp;
Willy Tarreau2ec22742015-03-10 14:27:20 +01004095 struct sample_fetch *f;
Frédéric Lécaillef874a832018-06-15 13:56:04 +02004096 struct arg args[ARGM_NBARGS + 1] = {{0}};
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004097 int i;
4098 struct sample smp;
4099
4100 /* Get closure arguments. */
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004101 f = lua_touserdata(L, lua_upvalueindex(1));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004102
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004103 /* Get traditional arguments. */
Willy Tarreaub2ccb562015-04-06 11:11:15 +02004104 hsmp = MAY_LJMP(hlua_checkfetches(L, 1));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004105
Thierry FOURNIERca988662015-12-20 18:43:03 +01004106 /* Check execution authorization. */
4107 if (f->use & SMP_USE_HTTP_ANY &&
4108 !(hsmp->flags & HLUA_F_MAY_USE_HTTP)) {
4109 lua_pushfstring(L, "the sample-fetch '%s' needs an HTTP parser which "
4110 "is not available in Lua services", f->kw);
4111 WILL_LJMP(lua_error(L));
4112 }
4113
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004114 /* Get extra arguments. */
4115 for (i = 0; i < lua_gettop(L) - 1; i++) {
4116 if (i >= ARGM_NBARGS)
4117 break;
4118 hlua_lua2arg(L, i + 2, &args[i]);
4119 }
4120 args[i].type = ARGT_STOP;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004121 args[i].data.str.area = NULL;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004122
4123 /* Check arguments. */
Willy Tarreaub2ccb562015-04-06 11:11:15 +02004124 MAY_LJMP(hlua_lua2arg_check(L, 2, args, f->arg_mask, hsmp->p));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004125
4126 /* Run the special args checker. */
Willy Tarreau2ec22742015-03-10 14:27:20 +01004127 if (f->val_args && !f->val_args(args, NULL)) {
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004128 lua_pushfstring(L, "error in arguments");
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004129 goto error;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004130 }
4131
4132 /* Initialise the sample. */
4133 memset(&smp, 0, sizeof(smp));
4134
4135 /* Run the sample fetch process. */
Willy Tarreau1777ea62016-03-10 16:15:46 +01004136 smp_set_owner(&smp, hsmp->p, hsmp->s->sess, hsmp->s, hsmp->dir & SMP_OPT_DIR);
Thierry FOURNIER0786d052015-05-11 15:42:45 +02004137 if (!f->process(args, &smp, f->kw, f->private)) {
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004138 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004139 lua_pushstring(L, "");
4140 else
4141 lua_pushnil(L);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004142 goto end;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004143 }
4144
4145 /* Convert the returned sample in lua value. */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004146 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004147 hlua_smp2lua_str(L, &smp);
4148 else
4149 hlua_smp2lua(L, &smp);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004150
4151 end:
Willy Tarreauee0d7272021-07-16 10:26:56 +02004152 free_args(args);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004153 return 1;
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004154
4155 error:
Willy Tarreauee0d7272021-07-16 10:26:56 +02004156 free_args(args);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004157 WILL_LJMP(lua_error(L));
4158 return 0; /* Never reached */
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004159}
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004160
4161/*
4162 *
4163 *
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004164 * Class Converters
4165 *
4166 *
4167 */
4168
4169/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02004170 * a class stream, otherwise it throws an error.
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004171 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004172__LJMP static struct hlua_smp *hlua_checkconverters(lua_State *L, int ud)
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004173{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004174 return MAY_LJMP(hlua_checkudata(L, ud, class_converters_ref));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004175}
4176
4177/* This function creates and push in the stack a Converters object
4178 * according with a current TXN.
4179 */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004180static int hlua_converters_new(lua_State *L, struct hlua_txn *txn, unsigned int flags)
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004181{
Willy Tarreau7073c472015-04-06 11:15:40 +02004182 struct hlua_smp *hsmp;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004183
4184 /* Check stack size. */
4185 if (!lua_checkstack(L, 3))
4186 return 0;
4187
4188 /* Create the object: obj[0] = userdata.
4189 * Note that the base of the Converters object is the
4190 * same than the TXN object.
4191 */
4192 lua_newtable(L);
Willy Tarreau7073c472015-04-06 11:15:40 +02004193 hsmp = lua_newuserdata(L, sizeof(*hsmp));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004194 lua_rawseti(L, -2, 0);
4195
Willy Tarreau7073c472015-04-06 11:15:40 +02004196 hsmp->s = txn->s;
4197 hsmp->p = txn->p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01004198 hsmp->dir = txn->dir;
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004199 hsmp->flags = flags;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004200
Willy Tarreau87b09662015-04-03 00:22:06 +02004201 /* Pop a class stream metatable and affect it to the table. */
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004202 lua_rawgeti(L, LUA_REGISTRYINDEX, class_converters_ref);
4203 lua_setmetatable(L, -2);
4204
4205 return 1;
4206}
4207
4208/* This function is an LUA binding. It is called with each converter.
4209 * It uses closure argument to store the associated converter. It
4210 * returns only one argument or throws an error. An error is thrown
4211 * only if an error is encountered during the argument parsing. If
4212 * the converter function function fails, nil is returned.
4213 */
4214__LJMP static int hlua_run_sample_conv(lua_State *L)
4215{
Willy Tarreauda5f1082015-04-06 11:17:13 +02004216 struct hlua_smp *hsmp;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004217 struct sample_conv *conv;
Frédéric Lécaillef874a832018-06-15 13:56:04 +02004218 struct arg args[ARGM_NBARGS + 1] = {{0}};
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004219 int i;
4220 struct sample smp;
4221
4222 /* Get closure arguments. */
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004223 conv = lua_touserdata(L, lua_upvalueindex(1));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004224
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004225 /* Get traditional arguments. */
Willy Tarreauda5f1082015-04-06 11:17:13 +02004226 hsmp = MAY_LJMP(hlua_checkconverters(L, 1));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004227
4228 /* Get extra arguments. */
4229 for (i = 0; i < lua_gettop(L) - 2; i++) {
4230 if (i >= ARGM_NBARGS)
4231 break;
4232 hlua_lua2arg(L, i + 3, &args[i]);
4233 }
4234 args[i].type = ARGT_STOP;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004235 args[i].data.str.area = NULL;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004236
4237 /* Check arguments. */
Willy Tarreauda5f1082015-04-06 11:17:13 +02004238 MAY_LJMP(hlua_lua2arg_check(L, 3, args, conv->arg_mask, hsmp->p));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004239
4240 /* Run the special args checker. */
4241 if (conv->val_args && !conv->val_args(args, conv, "", 0, NULL)) {
4242 hlua_pusherror(L, "error in arguments");
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004243 goto error;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004244 }
4245
4246 /* Initialise the sample. */
Amaury Denoyellebc0af6a2020-10-29 17:21:20 +01004247 memset(&smp, 0, sizeof(smp));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004248 if (!hlua_lua2smp(L, 2, &smp)) {
4249 hlua_pusherror(L, "error in the input argument");
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004250 goto error;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004251 }
4252
Willy Tarreau1777ea62016-03-10 16:15:46 +01004253 smp_set_owner(&smp, hsmp->p, hsmp->s->sess, hsmp->s, hsmp->dir & SMP_OPT_DIR);
4254
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004255 /* Apply expected cast. */
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02004256 if (!sample_casts[smp.data.type][conv->in_type]) {
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004257 hlua_pusherror(L, "invalid input argument: cannot cast '%s' to '%s'",
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02004258 smp_to_type[smp.data.type], smp_to_type[conv->in_type]);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004259 goto error;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004260 }
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02004261 if (sample_casts[smp.data.type][conv->in_type] != c_none &&
4262 !sample_casts[smp.data.type][conv->in_type](&smp)) {
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004263 hlua_pusherror(L, "error during the input argument casting");
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004264 goto error;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004265 }
4266
4267 /* Run the sample conversion process. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02004268 if (!conv->process(args, &smp, conv->private)) {
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004269 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004270 lua_pushstring(L, "");
4271 else
Willy Tarreaua678b432015-08-28 10:14:59 +02004272 lua_pushnil(L);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004273 goto end;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004274 }
4275
4276 /* Convert the returned sample in lua value. */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004277 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004278 hlua_smp2lua_str(L, &smp);
4279 else
4280 hlua_smp2lua(L, &smp);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004281 end:
Willy Tarreauee0d7272021-07-16 10:26:56 +02004282 free_args(args);
Willy Tarreaua678b432015-08-28 10:14:59 +02004283 return 1;
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004284
4285 error:
Willy Tarreauee0d7272021-07-16 10:26:56 +02004286 free_args(args);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004287 WILL_LJMP(lua_error(L));
4288 return 0; /* Never reached */
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004289}
4290
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004291/*
4292 *
4293 *
4294 * Class AppletTCP
4295 *
4296 *
4297 */
4298
4299/* Returns a struct hlua_txn if the stack entry "ud" is
4300 * a class stream, otherwise it throws an error.
4301 */
4302__LJMP static struct hlua_appctx *hlua_checkapplet_tcp(lua_State *L, int ud)
4303{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004304 return MAY_LJMP(hlua_checkudata(L, ud, class_applet_tcp_ref));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004305}
4306
4307/* This function creates and push in the stack an Applet object
4308 * according with a current TXN.
4309 */
4310static int hlua_applet_tcp_new(lua_State *L, struct appctx *ctx)
4311{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004312 struct hlua_appctx *luactx;
Christopher Faulet908628c2022-03-25 16:43:49 +01004313 struct stream *s = __cs_strm(ctx->owner);
Christopher Faulet2da02ae2022-02-24 13:45:27 +01004314 struct proxy *p;
4315
4316 ALREADY_CHECKED(s);
4317 p = s->be;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004318
4319 /* Check stack size. */
4320 if (!lua_checkstack(L, 3))
4321 return 0;
4322
4323 /* Create the object: obj[0] = userdata.
4324 * Note that the base of the Converters object is the
4325 * same than the TXN object.
4326 */
4327 lua_newtable(L);
Willy Tarreau7e702d12021-04-28 17:59:21 +02004328 luactx = lua_newuserdata(L, sizeof(*luactx));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004329 lua_rawseti(L, -2, 0);
Willy Tarreau7e702d12021-04-28 17:59:21 +02004330 luactx->appctx = ctx;
4331 luactx->htxn.s = s;
4332 luactx->htxn.p = p;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004333
4334 /* Create the "f" field that contains a list of fetches. */
4335 lua_pushstring(L, "f");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004336 if (!hlua_fetches_new(L, &luactx->htxn, 0))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004337 return 0;
4338 lua_settable(L, -3);
4339
4340 /* Create the "sf" field that contains a list of stringsafe fetches. */
4341 lua_pushstring(L, "sf");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004342 if (!hlua_fetches_new(L, &luactx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004343 return 0;
4344 lua_settable(L, -3);
4345
4346 /* Create the "c" field that contains a list of converters. */
4347 lua_pushstring(L, "c");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004348 if (!hlua_converters_new(L, &luactx->htxn, 0))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004349 return 0;
4350 lua_settable(L, -3);
4351
4352 /* Create the "sc" field that contains a list of stringsafe converters. */
4353 lua_pushstring(L, "sc");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004354 if (!hlua_converters_new(L, &luactx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004355 return 0;
4356 lua_settable(L, -3);
4357
4358 /* Pop a class stream metatable and affect it to the table. */
4359 lua_rawgeti(L, LUA_REGISTRYINDEX, class_applet_tcp_ref);
4360 lua_setmetatable(L, -2);
4361
4362 return 1;
4363}
4364
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004365__LJMP static int hlua_applet_tcp_set_var(lua_State *L)
4366{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004367 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004368 struct stream *s;
4369 const char *name;
4370 size_t len;
4371 struct sample smp;
4372
Tim Duesterhus4e172c92020-05-19 13:49:42 +02004373 if (lua_gettop(L) < 3 || lua_gettop(L) > 4)
4374 WILL_LJMP(luaL_error(L, "'set_var' needs between 3 and 4 arguments"));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004375
4376 /* It is useles to retrieve the stream, but this function
4377 * runs only in a stream context.
4378 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004379 luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004380 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02004381 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004382
4383 /* Converts the third argument in a sample. */
Amaury Denoyellebc0af6a2020-10-29 17:21:20 +01004384 memset(&smp, 0, sizeof(smp));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004385 hlua_lua2smp(L, 3, &smp);
4386
4387 /* Store the sample in a variable. */
4388 smp_set_owner(&smp, s->be, s->sess, s, 0);
Tim Duesterhus4e172c92020-05-19 13:49:42 +02004389
4390 if (lua_gettop(L) == 4 && lua_toboolean(L, 4))
4391 lua_pushboolean(L, vars_set_by_name_ifexist(name, len, &smp) != 0);
4392 else
4393 lua_pushboolean(L, vars_set_by_name(name, len, &smp) != 0);
4394
Tim Duesterhus84ebc132020-05-19 13:49:41 +02004395 return 1;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004396}
4397
4398__LJMP static int hlua_applet_tcp_unset_var(lua_State *L)
4399{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004400 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004401 struct stream *s;
4402 const char *name;
4403 size_t len;
4404 struct sample smp;
4405
4406 MAY_LJMP(check_args(L, 2, "unset_var"));
4407
4408 /* It is useles to retrieve the stream, but this function
4409 * runs only in a stream context.
4410 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004411 luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004412 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02004413 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004414
4415 /* Unset the variable. */
4416 smp_set_owner(&smp, s->be, s->sess, s, 0);
Tim Duesterhus84ebc132020-05-19 13:49:41 +02004417 lua_pushboolean(L, vars_unset_by_name_ifexist(name, len, &smp) != 0);
4418 return 1;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004419}
4420
4421__LJMP static int hlua_applet_tcp_get_var(lua_State *L)
4422{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004423 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004424 struct stream *s;
4425 const char *name;
4426 size_t len;
4427 struct sample smp;
4428
4429 MAY_LJMP(check_args(L, 2, "get_var"));
4430
4431 /* It is useles to retrieve the stream, but this function
4432 * runs only in a stream context.
4433 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004434 luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004435 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02004436 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004437
4438 smp_set_owner(&smp, s->be, s->sess, s, 0);
Willy Tarreaue352b9d2021-09-03 11:52:38 +02004439 if (!vars_get_by_name(name, len, &smp, NULL)) {
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004440 lua_pushnil(L);
4441 return 1;
4442 }
4443
4444 return hlua_smp2lua(L, &smp);
4445}
4446
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004447__LJMP static int hlua_applet_tcp_set_priv(lua_State *L)
4448{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004449 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
4450 struct stream *s = luactx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01004451 struct hlua *hlua;
4452
4453 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01004454 if (!s->hlua)
4455 return 0;
4456 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004457
4458 MAY_LJMP(check_args(L, 2, "set_priv"));
4459
4460 /* Remove previous value. */
Thierry FOURNIERe068b602017-04-26 13:27:05 +02004461 luaL_unref(L, LUA_REGISTRYINDEX, hlua->Mref);
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004462
4463 /* Get and store new value. */
4464 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
4465 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
4466
4467 return 0;
4468}
4469
4470__LJMP static int hlua_applet_tcp_get_priv(lua_State *L)
4471{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004472 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
4473 struct stream *s = luactx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01004474 struct hlua *hlua;
4475
4476 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01004477 if (!s->hlua) {
4478 lua_pushnil(L);
4479 return 1;
4480 }
4481 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004482
4483 /* Push configuration index in the stack. */
4484 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
4485
4486 return 1;
4487}
4488
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004489/* If expected data not yet available, it returns a yield. This function
4490 * consumes the data in the buffer. It returns a string containing the
4491 * data. This string can be empty.
4492 */
4493__LJMP static int hlua_applet_tcp_getline_yield(lua_State *L, int status, lua_KContext ctx)
4494{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004495 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Christopher Faulet908628c2022-03-25 16:43:49 +01004496 struct conn_stream *cs = luactx->appctx->owner;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004497 int ret;
Willy Tarreau206ba832018-06-14 15:27:31 +02004498 const char *blk1;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004499 size_t len1;
Willy Tarreau206ba832018-06-14 15:27:31 +02004500 const char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004501 size_t len2;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004502
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004503 /* Read the maximum amount of data available. */
Christopher Faulet908628c2022-03-25 16:43:49 +01004504 ret = co_getline_nc(cs_oc(cs), &blk1, &len1, &blk2, &len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004505
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004506 /* Data not yet available. return yield. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004507 if (ret == 0) {
Christopher Fauleta0bdec32022-04-04 07:51:21 +02004508 cs_cant_get(cs);
Willy Tarreau9635e032018-10-16 17:52:55 +02004509 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_getline_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004510 }
4511
4512 /* End of data: commit the total strings and return. */
4513 if (ret < 0) {
Willy Tarreau7e702d12021-04-28 17:59:21 +02004514 luaL_pushresult(&luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004515 return 1;
4516 }
4517
4518 /* Ensure that the block 2 length is usable. */
4519 if (ret == 1)
4520 len2 = 0;
4521
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -07004522 /* don't check the max length read and don't check. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004523 luaL_addlstring(&luactx->b, blk1, len1);
4524 luaL_addlstring(&luactx->b, blk2, len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004525
4526 /* Consume input channel output buffer data. */
Christopher Faulet908628c2022-03-25 16:43:49 +01004527 co_skip(cs_oc(cs), len1 + len2);
Willy Tarreau7e702d12021-04-28 17:59:21 +02004528 luaL_pushresult(&luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004529 return 1;
4530}
4531
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004532/* Check arguments for the function "hlua_channel_get_yield". */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004533__LJMP static int hlua_applet_tcp_getline(lua_State *L)
4534{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004535 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004536
4537 /* Initialise the string catenation. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004538 luaL_buffinit(L, &luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004539
4540 return MAY_LJMP(hlua_applet_tcp_getline_yield(L, 0, 0));
4541}
4542
4543/* If expected data not yet available, it returns a yield. This function
4544 * consumes the data in the buffer. It returns a string containing the
4545 * data. This string can be empty.
4546 */
4547__LJMP static int hlua_applet_tcp_recv_yield(lua_State *L, int status, lua_KContext ctx)
4548{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004549 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Christopher Faulet908628c2022-03-25 16:43:49 +01004550 struct conn_stream *cs = luactx->appctx->owner;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004551 size_t len = MAY_LJMP(luaL_checkinteger(L, 2));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004552 int ret;
Willy Tarreau206ba832018-06-14 15:27:31 +02004553 const char *blk1;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004554 size_t len1;
Willy Tarreau206ba832018-06-14 15:27:31 +02004555 const char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004556 size_t len2;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004557
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004558 /* Read the maximum amount of data available. */
Christopher Faulet908628c2022-03-25 16:43:49 +01004559 ret = co_getblk_nc(cs_oc(cs), &blk1, &len1, &blk2, &len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004560
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004561 /* Data not yet available. return yield. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004562 if (ret == 0) {
Christopher Fauleta0bdec32022-04-04 07:51:21 +02004563 cs_cant_get(cs);
Willy Tarreau9635e032018-10-16 17:52:55 +02004564 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004565 }
4566
4567 /* End of data: commit the total strings and return. */
4568 if (ret < 0) {
Willy Tarreau7e702d12021-04-28 17:59:21 +02004569 luaL_pushresult(&luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004570 return 1;
4571 }
4572
4573 /* Ensure that the block 2 length is usable. */
4574 if (ret == 1)
4575 len2 = 0;
4576
4577 if (len == -1) {
4578
4579 /* If len == -1, catenate all the data avalaile and
4580 * yield because we want to get all the data until
4581 * the end of data stream.
4582 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004583 luaL_addlstring(&luactx->b, blk1, len1);
4584 luaL_addlstring(&luactx->b, blk2, len2);
Christopher Faulet908628c2022-03-25 16:43:49 +01004585 co_skip(cs_oc(cs), len1 + len2);
Christopher Fauleta0bdec32022-04-04 07:51:21 +02004586 cs_cant_get(cs);
Willy Tarreau9635e032018-10-16 17:52:55 +02004587 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004588
4589 } else {
4590
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05004591 /* Copy the first block caping to the length required. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004592 if (len1 > len)
4593 len1 = len;
Willy Tarreau7e702d12021-04-28 17:59:21 +02004594 luaL_addlstring(&luactx->b, blk1, len1);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004595 len -= len1;
4596
4597 /* Copy the second block. */
4598 if (len2 > len)
4599 len2 = len;
Willy Tarreau7e702d12021-04-28 17:59:21 +02004600 luaL_addlstring(&luactx->b, blk2, len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004601 len -= len2;
4602
4603 /* Consume input channel output buffer data. */
Christopher Faulet908628c2022-03-25 16:43:49 +01004604 co_skip(cs_oc(cs), len1 + len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004605
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004606 /* If there is no other data available, yield waiting for new data. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004607 if (len > 0) {
4608 lua_pushinteger(L, len);
4609 lua_replace(L, 2);
Christopher Fauleta0bdec32022-04-04 07:51:21 +02004610 cs_cant_get(cs);
Willy Tarreau9635e032018-10-16 17:52:55 +02004611 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004612 }
4613
4614 /* return the result. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004615 luaL_pushresult(&luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004616 return 1;
4617 }
4618
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004619 /* we never execute this */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004620 hlua_pusherror(L, "Lua: internal error");
4621 WILL_LJMP(lua_error(L));
4622 return 0;
4623}
4624
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004625/* Check arguments for the function "hlua_channel_get_yield". */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004626__LJMP static int hlua_applet_tcp_recv(lua_State *L)
4627{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004628 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004629 int len = -1;
4630
4631 if (lua_gettop(L) > 2)
4632 WILL_LJMP(luaL_error(L, "The 'recv' function requires between 1 and 2 arguments."));
4633 if (lua_gettop(L) >= 2) {
4634 len = MAY_LJMP(luaL_checkinteger(L, 2));
4635 lua_pop(L, 1);
4636 }
4637
4638 /* Confirm or set the required length */
4639 lua_pushinteger(L, len);
4640
4641 /* Initialise the string catenation. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004642 luaL_buffinit(L, &luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004643
4644 return MAY_LJMP(hlua_applet_tcp_recv_yield(L, 0, 0));
4645}
4646
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004647/* Append data in the output side of the buffer. This data is immediately
4648 * sent. The function returns the amount of data written. If the buffer
4649 * cannot contain the data, the function yields. The function returns -1
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004650 * if the channel is closed.
4651 */
4652__LJMP static int hlua_applet_tcp_send_yield(lua_State *L, int status, lua_KContext ctx)
4653{
4654 size_t len;
Willy Tarreau7e702d12021-04-28 17:59:21 +02004655 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004656 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
4657 int l = MAY_LJMP(luaL_checkinteger(L, 3));
Christopher Faulet908628c2022-03-25 16:43:49 +01004658 struct conn_stream *cs = luactx->appctx->owner;
4659 struct channel *chn = cs_ic(cs);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004660 int max;
4661
4662 /* Get the max amount of data which can write as input in the channel. */
4663 max = channel_recv_max(chn);
4664 if (max > (len - l))
4665 max = len - l;
4666
4667 /* Copy data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02004668 ci_putblk(chn, str + l, max);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004669
4670 /* update counters. */
4671 l += max;
4672 lua_pop(L, 1);
4673 lua_pushinteger(L, l);
4674
4675 /* If some data is not send, declares the situation to the
4676 * applet, and returns a yield.
4677 */
4678 if (l < len) {
Christopher Fauleta0bdec32022-04-04 07:51:21 +02004679 cs_rx_room_blk(cs);
Willy Tarreau9635e032018-10-16 17:52:55 +02004680 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004681 }
4682
4683 return 1;
4684}
4685
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05004686/* Just a wrapper of "hlua_applet_tcp_send_yield". This wrapper permits
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004687 * yield the LUA process, and resume it without checking the
4688 * input arguments.
4689 */
4690__LJMP static int hlua_applet_tcp_send(lua_State *L)
4691{
4692 MAY_LJMP(check_args(L, 2, "send"));
4693 lua_pushinteger(L, 0);
4694
4695 return MAY_LJMP(hlua_applet_tcp_send_yield(L, 0, 0));
4696}
4697
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004698/*
4699 *
4700 *
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004701 * Class AppletHTTP
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004702 *
4703 *
4704 */
4705
4706/* Returns a struct hlua_txn if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02004707 * a class stream, otherwise it throws an error.
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004708 */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004709__LJMP static struct hlua_appctx *hlua_checkapplet_http(lua_State *L, int ud)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004710{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004711 return MAY_LJMP(hlua_checkudata(L, ud, class_applet_http_ref));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004712}
4713
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004714/* This function creates and push in the stack an Applet object
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004715 * according with a current TXN.
Willy Tarreauaa229cc2022-05-06 14:26:10 +02004716 * It relies on the caller to have already reserved the room in ctx->svcctx
4717 * for the local storage of hlua_http_ctx.
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004718 */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004719static int hlua_applet_http_new(lua_State *L, struct appctx *ctx)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004720{
Willy Tarreauaa229cc2022-05-06 14:26:10 +02004721 struct hlua_http_ctx *http_ctx = ctx->svcctx;
Willy Tarreau7e702d12021-04-28 17:59:21 +02004722 struct hlua_appctx *luactx;
Thierry FOURNIER841475e2015-12-11 17:10:09 +01004723 struct hlua_txn htxn;
Christopher Faulet908628c2022-03-25 16:43:49 +01004724 struct stream *s = __cs_strm(ctx->owner);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004725 struct proxy *px = s->be;
Christopher Fauleta2097962019-07-15 16:25:33 +02004726 struct htx *htx;
4727 struct htx_blk *blk;
4728 struct htx_sl *sl;
4729 struct ist path;
4730 unsigned long long len = 0;
4731 int32_t pos;
Amaury Denoyellec453f952021-07-06 11:40:12 +02004732 struct http_uri_parser parser;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004733
4734 /* Check stack size. */
4735 if (!lua_checkstack(L, 3))
4736 return 0;
4737
4738 /* Create the object: obj[0] = userdata.
4739 * Note that the base of the Converters object is the
4740 * same than the TXN object.
4741 */
4742 lua_newtable(L);
Willy Tarreau7e702d12021-04-28 17:59:21 +02004743 luactx = lua_newuserdata(L, sizeof(*luactx));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004744 lua_rawseti(L, -2, 0);
Willy Tarreau7e702d12021-04-28 17:59:21 +02004745 luactx->appctx = ctx;
Willy Tarreauaa229cc2022-05-06 14:26:10 +02004746 http_ctx->status = 200; /* Default status code returned. */
4747 http_ctx->reason = NULL; /* Use default reason based on status */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004748 luactx->htxn.s = s;
4749 luactx->htxn.p = px;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004750
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004751 /* Create the "f" field that contains a list of fetches. */
4752 lua_pushstring(L, "f");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004753 if (!hlua_fetches_new(L, &luactx->htxn, 0))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004754 return 0;
4755 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004756
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004757 /* Create the "sf" field that contains a list of stringsafe fetches. */
4758 lua_pushstring(L, "sf");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004759 if (!hlua_fetches_new(L, &luactx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004760 return 0;
4761 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004762
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004763 /* Create the "c" field that contains a list of converters. */
4764 lua_pushstring(L, "c");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004765 if (!hlua_converters_new(L, &luactx->htxn, 0))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004766 return 0;
4767 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004768
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004769 /* Create the "sc" field that contains a list of stringsafe converters. */
4770 lua_pushstring(L, "sc");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004771 if (!hlua_converters_new(L, &luactx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004772 return 0;
4773 lua_settable(L, -3);
Willy Tarreaueee5b512015-04-03 23:46:31 +02004774
Christopher Fauleta2097962019-07-15 16:25:33 +02004775 htx = htxbuf(&s->req.buf);
4776 blk = htx_get_first_blk(htx);
Christopher Fauletea009732019-11-18 15:50:25 +01004777 BUG_ON(!blk || htx_get_blk_type(blk) != HTX_BLK_REQ_SL);
Christopher Fauleta2097962019-07-15 16:25:33 +02004778 sl = htx_get_blk_ptr(htx, blk);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004779
Christopher Fauleta2097962019-07-15 16:25:33 +02004780 /* Stores the request method. */
4781 lua_pushstring(L, "method");
4782 lua_pushlstring(L, HTX_SL_REQ_MPTR(sl), HTX_SL_REQ_MLEN(sl));
4783 lua_settable(L, -3);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004784
Christopher Fauleta2097962019-07-15 16:25:33 +02004785 /* Stores the http version. */
4786 lua_pushstring(L, "version");
4787 lua_pushlstring(L, HTX_SL_REQ_VPTR(sl), HTX_SL_REQ_VLEN(sl));
4788 lua_settable(L, -3);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004789
Christopher Fauleta2097962019-07-15 16:25:33 +02004790 /* creates an array of headers. hlua_http_get_headers() crates and push
4791 * the array on the top of the stack.
4792 */
4793 lua_pushstring(L, "headers");
4794 htxn.s = s;
4795 htxn.p = px;
4796 htxn.dir = SMP_OPT_DIR_REQ;
Christopher Faulet9d1332b2020-02-24 16:46:16 +01004797 if (!hlua_http_get_headers(L, &htxn.s->txn->req))
Christopher Fauleta2097962019-07-15 16:25:33 +02004798 return 0;
4799 lua_settable(L, -3);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004800
Amaury Denoyellec453f952021-07-06 11:40:12 +02004801 parser = http_uri_parser_init(htx_sl_req_uri(sl));
4802 path = http_parse_path(&parser);
Tim Duesterhused526372020-03-05 17:56:33 +01004803 if (isttest(path)) {
Christopher Fauleta2097962019-07-15 16:25:33 +02004804 char *p, *q, *end;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004805
Christopher Fauleta2097962019-07-15 16:25:33 +02004806 p = path.ptr;
Tim Duesterhus4c8f75f2021-11-06 15:14:44 +01004807 end = istend(path);
Christopher Fauleta2097962019-07-15 16:25:33 +02004808 q = p;
4809 while (q < end && *q != '?')
4810 q++;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004811
Thierry FOURNIER7d388632017-02-22 02:06:16 +01004812 /* Stores the request path. */
Christopher Fauleta2097962019-07-15 16:25:33 +02004813 lua_pushstring(L, "path");
4814 lua_pushlstring(L, p, q - p);
Thierry FOURNIER7d388632017-02-22 02:06:16 +01004815 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01004816
Christopher Fauleta2097962019-07-15 16:25:33 +02004817 /* Stores the query string. */
4818 lua_pushstring(L, "qs");
4819 if (*q == '?')
4820 q++;
4821 lua_pushlstring(L, q, end - q);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004822 lua_settable(L, -3);
Christopher Fauleta2097962019-07-15 16:25:33 +02004823 }
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004824
Christopher Fauleta2097962019-07-15 16:25:33 +02004825 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
4826 struct htx_blk *blk = htx_get_blk(htx, pos);
4827 enum htx_blk_type type = htx_get_blk_type(blk);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004828
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01004829 if (type == HTX_BLK_TLR || type == HTX_BLK_EOT)
Christopher Fauleta2097962019-07-15 16:25:33 +02004830 break;
4831 if (type == HTX_BLK_DATA)
4832 len += htx_get_blksz(blk);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004833 }
Christopher Fauleta2097962019-07-15 16:25:33 +02004834 if (htx->extra != ULLONG_MAX)
4835 len += htx->extra;
4836
4837 /* Stores the request path. */
4838 lua_pushstring(L, "length");
4839 lua_pushinteger(L, len);
4840 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01004841
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004842 /* Create an empty array of HTTP request headers. */
4843 lua_pushstring(L, "response");
4844 lua_newtable(L);
4845 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01004846
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004847 /* Pop a class stream metatable and affect it to the table. */
4848 lua_rawgeti(L, LUA_REGISTRYINDEX, class_applet_http_ref);
4849 lua_setmetatable(L, -2);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004850
4851 return 1;
4852}
4853
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004854__LJMP static int hlua_applet_http_set_var(lua_State *L)
4855{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004856 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004857 struct stream *s;
4858 const char *name;
4859 size_t len;
4860 struct sample smp;
4861
Tim Duesterhus4e172c92020-05-19 13:49:42 +02004862 if (lua_gettop(L) < 3 || lua_gettop(L) > 4)
4863 WILL_LJMP(luaL_error(L, "'set_var' needs between 3 and 4 arguments"));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004864
4865 /* It is useles to retrieve the stream, but this function
4866 * runs only in a stream context.
4867 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004868 luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004869 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02004870 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004871
4872 /* Converts the third argument in a sample. */
Amaury Denoyellebc0af6a2020-10-29 17:21:20 +01004873 memset(&smp, 0, sizeof(smp));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004874 hlua_lua2smp(L, 3, &smp);
4875
4876 /* Store the sample in a variable. */
4877 smp_set_owner(&smp, s->be, s->sess, s, 0);
Tim Duesterhus4e172c92020-05-19 13:49:42 +02004878
4879 if (lua_gettop(L) == 4 && lua_toboolean(L, 4))
4880 lua_pushboolean(L, vars_set_by_name_ifexist(name, len, &smp) != 0);
4881 else
4882 lua_pushboolean(L, vars_set_by_name(name, len, &smp) != 0);
4883
Tim Duesterhus84ebc132020-05-19 13:49:41 +02004884 return 1;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004885}
4886
4887__LJMP static int hlua_applet_http_unset_var(lua_State *L)
4888{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004889 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004890 struct stream *s;
4891 const char *name;
4892 size_t len;
4893 struct sample smp;
4894
4895 MAY_LJMP(check_args(L, 2, "unset_var"));
4896
4897 /* It is useles to retrieve the stream, but this function
4898 * runs only in a stream context.
4899 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004900 luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004901 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02004902 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004903
4904 /* Unset the variable. */
4905 smp_set_owner(&smp, s->be, s->sess, s, 0);
Tim Duesterhus84ebc132020-05-19 13:49:41 +02004906 lua_pushboolean(L, vars_unset_by_name_ifexist(name, len, &smp) != 0);
4907 return 1;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004908}
4909
4910__LJMP static int hlua_applet_http_get_var(lua_State *L)
4911{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004912 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004913 struct stream *s;
4914 const char *name;
4915 size_t len;
4916 struct sample smp;
4917
4918 MAY_LJMP(check_args(L, 2, "get_var"));
4919
4920 /* It is useles to retrieve the stream, but this function
4921 * runs only in a stream context.
4922 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004923 luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004924 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02004925 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004926
4927 smp_set_owner(&smp, s->be, s->sess, s, 0);
Willy Tarreaue352b9d2021-09-03 11:52:38 +02004928 if (!vars_get_by_name(name, len, &smp, NULL)) {
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004929 lua_pushnil(L);
4930 return 1;
4931 }
4932
4933 return hlua_smp2lua(L, &smp);
4934}
4935
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004936__LJMP static int hlua_applet_http_set_priv(lua_State *L)
4937{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004938 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4939 struct stream *s = luactx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01004940 struct hlua *hlua;
4941
4942 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01004943 if (!s->hlua)
4944 return 0;
4945 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004946
4947 MAY_LJMP(check_args(L, 2, "set_priv"));
4948
4949 /* Remove previous value. */
Thierry FOURNIERe068b602017-04-26 13:27:05 +02004950 luaL_unref(L, LUA_REGISTRYINDEX, hlua->Mref);
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004951
4952 /* Get and store new value. */
4953 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
4954 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
4955
4956 return 0;
4957}
4958
4959__LJMP static int hlua_applet_http_get_priv(lua_State *L)
4960{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004961 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4962 struct stream *s = luactx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01004963 struct hlua *hlua;
4964
4965 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01004966 if (!s->hlua) {
4967 lua_pushnil(L);
4968 return 1;
4969 }
4970 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004971
4972 /* Push configuration index in the stack. */
4973 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
4974
4975 return 1;
4976}
4977
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004978/* If expected data not yet available, it returns a yield. This function
4979 * consumes the data in the buffer. It returns a string containing the
4980 * data. This string can be empty.
4981 */
Christopher Fauleta2097962019-07-15 16:25:33 +02004982__LJMP static int hlua_applet_http_getline_yield(lua_State *L, int status, lua_KContext ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004983{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004984 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Christopher Faulet908628c2022-03-25 16:43:49 +01004985 struct conn_stream *cs = luactx->appctx->owner;
4986 struct channel *req = cs_oc(cs);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004987 struct htx *htx;
4988 struct htx_blk *blk;
4989 size_t count;
4990 int stop = 0;
4991
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004992 htx = htx_from_buf(&req->buf);
4993 count = co_data(req);
Christopher Fauleta3f15502019-05-13 15:27:23 +02004994 blk = htx_get_first_blk(htx);
Christopher Fauletcc26b132018-12-18 21:20:57 +01004995
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004996 while (count && !stop && blk) {
4997 enum htx_blk_type type = htx_get_blk_type(blk);
4998 uint32_t sz = htx_get_blksz(blk);
4999 struct ist v;
5000 uint32_t vlen;
5001 char *nl;
5002
5003 vlen = sz;
5004 if (vlen > count) {
5005 if (type != HTX_BLK_DATA)
5006 break;
5007 vlen = count;
5008 }
5009
5010 switch (type) {
5011 case HTX_BLK_UNUSED:
5012 break;
5013
5014 case HTX_BLK_DATA:
5015 v = htx_get_blk_value(htx, blk);
5016 v.len = vlen;
5017 nl = istchr(v, '\n');
5018 if (nl != NULL) {
5019 stop = 1;
5020 vlen = nl - v.ptr + 1;
5021 }
Willy Tarreau7e702d12021-04-28 17:59:21 +02005022 luaL_addlstring(&luactx->b, v.ptr, vlen);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005023 break;
5024
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005025 case HTX_BLK_TLR:
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01005026 case HTX_BLK_EOT:
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005027 stop = 1;
5028 break;
5029
5030 default:
5031 break;
5032 }
5033
Willy Tarreau84240042022-02-28 16:51:23 +01005034 c_rew(req, vlen);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005035 count -= vlen;
5036 if (sz == vlen)
5037 blk = htx_remove_blk(htx, blk);
5038 else {
5039 htx_cut_data_blk(htx, blk, vlen);
5040 break;
5041 }
5042 }
5043
Christopher Fauleteccb31c2021-04-02 14:24:56 +02005044 /* The message was fully consumed and no more data are expected
5045 * (EOM flag set).
5046 */
5047 if (htx_is_empty(htx) && (htx->flags & HTX_FL_EOM))
5048 stop = 1;
5049
Christopher Faulet0ae79d02019-02-27 21:36:59 +01005050 htx_to_buf(htx, &req->buf);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005051 if (!stop) {
Christopher Fauleta0bdec32022-04-04 07:51:21 +02005052 cs_cant_get(cs);
Christopher Fauleta2097962019-07-15 16:25:33 +02005053 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_getline_yield, TICK_ETERNITY, 0));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005054 }
5055
5056 /* return the result. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005057 luaL_pushresult(&luactx->b);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005058 return 1;
5059}
5060
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005061
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08005062/* Check arguments for the function "hlua_channel_get_yield". */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005063__LJMP static int hlua_applet_http_getline(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005064{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005065 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005066
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005067 /* Initialise the string catenation. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005068 luaL_buffinit(L, &luactx->b);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005069
Christopher Fauleta2097962019-07-15 16:25:33 +02005070 return MAY_LJMP(hlua_applet_http_getline_yield(L, 0, 0));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005071}
5072
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005073/* If expected data not yet available, it returns a yield. This function
5074 * consumes the data in the buffer. It returns a string containing the
5075 * data. This string can be empty.
5076 */
Christopher Fauleta2097962019-07-15 16:25:33 +02005077__LJMP static int hlua_applet_http_recv_yield(lua_State *L, int status, lua_KContext ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005078{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005079 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Christopher Faulet908628c2022-03-25 16:43:49 +01005080 struct conn_stream *cs = luactx->appctx->owner;
5081 struct channel *req = cs_oc(cs);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005082 struct htx *htx;
5083 struct htx_blk *blk;
5084 size_t count;
5085 int len;
5086
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005087 htx = htx_from_buf(&req->buf);
5088 len = MAY_LJMP(luaL_checkinteger(L, 2));
5089 count = co_data(req);
Christopher Faulet29f17582019-05-23 11:03:26 +02005090 blk = htx_get_head_blk(htx);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005091 while (count && len && blk) {
5092 enum htx_blk_type type = htx_get_blk_type(blk);
5093 uint32_t sz = htx_get_blksz(blk);
5094 struct ist v;
5095 uint32_t vlen;
5096
5097 vlen = sz;
5098 if (len > 0 && vlen > len)
5099 vlen = len;
5100 if (vlen > count) {
5101 if (type != HTX_BLK_DATA)
5102 break;
5103 vlen = count;
5104 }
5105
5106 switch (type) {
5107 case HTX_BLK_UNUSED:
5108 break;
5109
5110 case HTX_BLK_DATA:
5111 v = htx_get_blk_value(htx, blk);
Willy Tarreau7e702d12021-04-28 17:59:21 +02005112 luaL_addlstring(&luactx->b, v.ptr, vlen);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005113 break;
5114
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005115 case HTX_BLK_TLR:
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01005116 case HTX_BLK_EOT:
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005117 len = 0;
5118 break;
5119
5120 default:
5121 break;
5122 }
5123
Willy Tarreau84240042022-02-28 16:51:23 +01005124 c_rew(req, vlen);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005125 count -= vlen;
5126 if (len > 0)
5127 len -= vlen;
5128 if (sz == vlen)
5129 blk = htx_remove_blk(htx, blk);
5130 else {
5131 htx_cut_data_blk(htx, blk, vlen);
5132 break;
5133 }
5134 }
5135
Christopher Fauleteccb31c2021-04-02 14:24:56 +02005136 /* The message was fully consumed and no more data are expected
5137 * (EOM flag set).
5138 */
5139 if (htx_is_empty(htx) && (htx->flags & HTX_FL_EOM))
5140 len = 0;
5141
Christopher Faulet0ae79d02019-02-27 21:36:59 +01005142 htx_to_buf(htx, &req->buf);
5143
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005144 /* If we are no other data available, yield waiting for new data. */
5145 if (len) {
5146 if (len > 0) {
5147 lua_pushinteger(L, len);
5148 lua_replace(L, 2);
5149 }
Christopher Fauleta0bdec32022-04-04 07:51:21 +02005150 cs_cant_get(cs);
Willy Tarreau9635e032018-10-16 17:52:55 +02005151 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005152 }
5153
5154 /* return the result. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005155 luaL_pushresult(&luactx->b);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005156 return 1;
5157}
5158
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08005159/* Check arguments for the function "hlua_channel_get_yield". */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005160__LJMP static int hlua_applet_http_recv(lua_State *L)
5161{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005162 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005163 int len = -1;
5164
5165 /* Check arguments. */
5166 if (lua_gettop(L) > 2)
5167 WILL_LJMP(luaL_error(L, "The 'recv' function requires between 1 and 2 arguments."));
5168 if (lua_gettop(L) >= 2) {
5169 len = MAY_LJMP(luaL_checkinteger(L, 2));
5170 lua_pop(L, 1);
5171 }
5172
Christopher Fauleta2097962019-07-15 16:25:33 +02005173 lua_pushinteger(L, len);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005174
Christopher Fauleta2097962019-07-15 16:25:33 +02005175 /* Initialise the string catenation. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005176 luaL_buffinit(L, &luactx->b);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005177
Christopher Fauleta2097962019-07-15 16:25:33 +02005178 return MAY_LJMP(hlua_applet_http_recv_yield(L, 0, 0));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005179}
5180
5181/* Append data in the output side of the buffer. This data is immediately
5182 * sent. The function returns the amount of data written. If the buffer
5183 * cannot contain the data, the function yields. The function returns -1
5184 * if the channel is closed.
5185 */
Christopher Fauleta2097962019-07-15 16:25:33 +02005186__LJMP static int hlua_applet_http_send_yield(lua_State *L, int status, lua_KContext ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005187{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005188 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Christopher Faulet908628c2022-03-25 16:43:49 +01005189 struct conn_stream *cs = luactx->appctx->owner;
5190 struct channel *res = cs_ic(cs);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005191 struct htx *htx = htx_from_buf(&res->buf);
5192 const char *data;
5193 size_t len;
5194 int l = MAY_LJMP(luaL_checkinteger(L, 3));
5195 int max;
5196
Christopher Faulet9060fc02019-07-03 11:39:30 +02005197 max = htx_get_max_blksz(htx, channel_htx_recv_max(res, htx));
Christopher Faulet4b0e9b22019-01-09 12:16:58 +01005198 if (!max)
5199 goto snd_yield;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005200
5201 data = MAY_LJMP(luaL_checklstring(L, 2, &len));
5202
5203 /* Get the max amount of data which can write as input in the channel. */
5204 if (max > (len - l))
5205 max = len - l;
5206
5207 /* Copy data. */
Willy Tarreau0a7ef022019-05-28 10:30:11 +02005208 max = htx_add_data(htx, ist2(data + l, max));
Christopher Fauletf6cce3f2019-02-27 21:20:09 +01005209 channel_add_input(res, max);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005210
5211 /* update counters. */
5212 l += max;
5213 lua_pop(L, 1);
5214 lua_pushinteger(L, l);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005215
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005216 /* If some data is not send, declares the situation to the
5217 * applet, and returns a yield.
5218 */
5219 if (l < len) {
Christopher Faulet4b0e9b22019-01-09 12:16:58 +01005220 snd_yield:
Christopher Faulet0ae79d02019-02-27 21:36:59 +01005221 htx_to_buf(htx, &res->buf);
Christopher Fauleta0bdec32022-04-04 07:51:21 +02005222 cs_rx_room_blk(cs);
Willy Tarreau9635e032018-10-16 17:52:55 +02005223 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005224 }
5225
Christopher Fauleta2097962019-07-15 16:25:33 +02005226 htx_to_buf(htx, &res->buf);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005227 return 1;
5228}
5229
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05005230/* Just a wrapper of "hlua_applet_send_yield". This wrapper permits
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005231 * yield the LUA process, and resume it without checking the
5232 * input arguments.
5233 */
5234__LJMP static int hlua_applet_http_send(lua_State *L)
5235{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005236 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005237 struct hlua_http_ctx *http_ctx = luactx->appctx->svcctx;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005238
5239 /* We want to send some data. Headers must be sent. */
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005240 if (!(http_ctx->flags & APPLET_HDR_SENT)) {
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005241 hlua_pusherror(L, "Lua: 'send' you must call start_response() before sending data.");
5242 WILL_LJMP(lua_error(L));
5243 }
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005244
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05005245 /* This integer is used for followinf the amount of data sent. */
Christopher Fauleta2097962019-07-15 16:25:33 +02005246 lua_pushinteger(L, 0);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005247
Christopher Fauleta2097962019-07-15 16:25:33 +02005248 return MAY_LJMP(hlua_applet_http_send_yield(L, 0, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005249}
5250
5251__LJMP static int hlua_applet_http_addheader(lua_State *L)
5252{
5253 const char *name;
5254 int ret;
5255
5256 MAY_LJMP(hlua_checkapplet_http(L, 1));
5257 name = MAY_LJMP(luaL_checkstring(L, 2));
5258 MAY_LJMP(luaL_checkstring(L, 3));
5259
5260 /* Push in the stack the "response" entry. */
5261 ret = lua_getfield(L, 1, "response");
5262 if (ret != LUA_TTABLE) {
5263 hlua_pusherror(L, "Lua: 'add_header' internal error: AppletHTTP['response'] "
5264 "is expected as an array. %s found", lua_typename(L, ret));
5265 WILL_LJMP(lua_error(L));
5266 }
5267
5268 /* check if the header is already registered if it is not
5269 * the case, register it.
5270 */
5271 ret = lua_getfield(L, -1, name);
5272 if (ret == LUA_TNIL) {
5273
5274 /* Entry not found. */
5275 lua_pop(L, 1); /* remove the nil. The "response" table is the top of the stack. */
5276
5277 /* Insert the new header name in the array in the top of the stack.
5278 * It left the new array in the top of the stack.
5279 */
5280 lua_newtable(L);
5281 lua_pushvalue(L, 2);
5282 lua_pushvalue(L, -2);
5283 lua_settable(L, -4);
5284
5285 } else if (ret != LUA_TTABLE) {
5286
5287 /* corruption error. */
5288 hlua_pusherror(L, "Lua: 'add_header' internal error: AppletHTTP['response']['%s'] "
5289 "is expected as an array. %s found", name, lua_typename(L, ret));
5290 WILL_LJMP(lua_error(L));
5291 }
5292
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -07005293 /* Now the top of thestack is an array of values. We push
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005294 * the header value as new entry.
5295 */
5296 lua_pushvalue(L, 3);
5297 ret = lua_rawlen(L, -2);
5298 lua_rawseti(L, -2, ret + 1);
5299 lua_pushboolean(L, 1);
5300 return 1;
5301}
5302
5303__LJMP static int hlua_applet_http_status(lua_State *L)
5304{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005305 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005306 int status = MAY_LJMP(luaL_checkinteger(L, 2));
Robin H. Johnson52f5db22017-01-01 13:10:52 -08005307 const char *reason = MAY_LJMP(luaL_optlstring(L, 3, NULL, NULL));
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005308 struct hlua_http_ctx *http_ctx = luactx->appctx->svcctx;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005309
5310 if (status < 100 || status > 599) {
5311 lua_pushboolean(L, 0);
5312 return 1;
5313 }
5314
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005315 http_ctx->status = status;
5316 http_ctx->reason = reason;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005317 lua_pushboolean(L, 1);
5318 return 1;
5319}
5320
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005321
Christopher Fauleta2097962019-07-15 16:25:33 +02005322__LJMP static int hlua_applet_http_send_response(lua_State *L)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005323{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005324 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005325 struct hlua_http_ctx *http_ctx = luactx->appctx->svcctx;
Christopher Faulet908628c2022-03-25 16:43:49 +01005326 struct conn_stream *cs = luactx->appctx->owner;
5327 struct channel *res = cs_ic(cs);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005328 struct htx *htx;
5329 struct htx_sl *sl;
5330 struct h1m h1m;
5331 const char *status, *reason;
5332 const char *name, *value;
5333 size_t nlen, vlen;
5334 unsigned int flags;
5335
5336 /* Send the message at once. */
5337 htx = htx_from_buf(&res->buf);
5338 h1m_init_res(&h1m);
5339
5340 /* Use the same http version than the request. */
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005341 status = ultoa_r(http_ctx->status, trash.area, trash.size);
5342 reason = http_ctx->reason;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005343 if (reason == NULL)
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005344 reason = http_get_reason(http_ctx->status);
5345 if (http_ctx->flags & APPLET_HTTP11) {
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005346 flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11);
5347 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.1"), ist(status), ist(reason));
5348 }
5349 else {
5350 flags = HTX_SL_F_IS_RESP;
5351 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.0"), ist(status), ist(reason));
5352 }
5353 if (!sl) {
5354 hlua_pusherror(L, "Lua applet http '%s': Failed to create response.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005355 luactx->appctx->rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005356 WILL_LJMP(lua_error(L));
5357 }
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005358 sl->info.res.status = http_ctx->status;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005359
5360 /* Get the array associated to the field "response" in the object AppletHTTP. */
5361 lua_pushvalue(L, 0);
5362 if (lua_getfield(L, 1, "response") != LUA_TTABLE) {
5363 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response'] missing.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005364 luactx->appctx->rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005365 WILL_LJMP(lua_error(L));
5366 }
5367
5368 /* Browse the list of headers. */
5369 lua_pushnil(L);
5370 while(lua_next(L, -2) != 0) {
5371 /* We expect a string as -2. */
5372 if (lua_type(L, -2) != LUA_TSTRING) {
5373 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response'][] element must be a string. got %s.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005374 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005375 lua_typename(L, lua_type(L, -2)));
5376 WILL_LJMP(lua_error(L));
5377 }
5378 name = lua_tolstring(L, -2, &nlen);
5379
5380 /* We expect an array as -1. */
5381 if (lua_type(L, -1) != LUA_TTABLE) {
5382 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 +02005383 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005384 name,
5385 lua_typename(L, lua_type(L, -1)));
5386 WILL_LJMP(lua_error(L));
5387 }
5388
5389 /* Browse the table who is on the top of the stack. */
5390 lua_pushnil(L);
5391 while(lua_next(L, -2) != 0) {
5392 int id;
5393
5394 /* We expect a number as -2. */
5395 if (lua_type(L, -2) != LUA_TNUMBER) {
5396 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 +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, -2)));
5400 WILL_LJMP(lua_error(L));
5401 }
5402 id = lua_tointeger(L, -2);
5403
5404 /* We expect a string as -2. */
5405 if (lua_type(L, -1) != LUA_TSTRING) {
5406 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 +02005407 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005408 name, id,
5409 lua_typename(L, lua_type(L, -1)));
5410 WILL_LJMP(lua_error(L));
5411 }
5412 value = lua_tolstring(L, -1, &vlen);
5413
5414 /* Simple Protocol checks. */
Christopher Faulet545fbba2021-09-28 09:36:25 +02005415 if (isteqi(ist2(name, nlen), ist("transfer-encoding"))) {
5416 int ret;
5417
5418 ret = h1_parse_xfer_enc_header(&h1m, ist2(value, vlen));
5419 if (ret < 0) {
5420 hlua_pusherror(L, "Lua applet http '%s': Invalid '%s' header.\n",
5421 luactx->appctx->rule->arg.hlua_rule->fcn->name,
5422 name);
5423 WILL_LJMP(lua_error(L));
5424 }
5425 else if (ret == 0)
5426 goto next; /* Skip it */
5427 }
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005428 else if (isteqi(ist2(name, nlen), ist("content-length"))) {
5429 struct ist v = ist2(value, vlen);
5430 int ret;
5431
5432 ret = h1_parse_cont_len_header(&h1m, &v);
5433 if (ret < 0) {
5434 hlua_pusherror(L, "Lua applet http '%s': Invalid '%s' header.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005435 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005436 name);
5437 WILL_LJMP(lua_error(L));
5438 }
5439 else if (ret == 0)
5440 goto next; /* Skip it */
5441 }
5442
5443 /* Add a new header */
5444 if (!htx_add_header(htx, ist2(name, nlen), ist2(value, vlen))) {
5445 hlua_pusherror(L, "Lua applet http '%s': Failed to add header '%s' in the response.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005446 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005447 name);
5448 WILL_LJMP(lua_error(L));
5449 }
5450 next:
5451 /* Remove the array from the stack, and get next element with a remaining string. */
5452 lua_pop(L, 1);
5453 }
5454
5455 /* Remove the array from the stack, and get next element with a remaining string. */
5456 lua_pop(L, 1);
5457 }
5458
5459 if (h1m.flags & H1_MF_CHNK)
5460 h1m.flags &= ~H1_MF_CLEN;
5461 if (h1m.flags & (H1_MF_CLEN|H1_MF_CHNK))
5462 h1m.flags |= H1_MF_XFER_LEN;
5463
5464 /* Uset HTX start-line flags */
5465 if (h1m.flags & H1_MF_XFER_ENC)
5466 flags |= HTX_SL_F_XFER_ENC;
5467 if (h1m.flags & H1_MF_XFER_LEN) {
5468 flags |= HTX_SL_F_XFER_LEN;
5469 if (h1m.flags & H1_MF_CHNK)
5470 flags |= HTX_SL_F_CHNK;
5471 else if (h1m.flags & H1_MF_CLEN)
5472 flags |= HTX_SL_F_CLEN;
5473 if (h1m.body_len == 0)
5474 flags |= HTX_SL_F_BODYLESS;
5475 }
5476 sl->flags |= flags;
5477
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -07005478 /* If we don't have a content-length set, and the HTTP version is 1.1
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005479 * and the status code implies the presence of a message body, we must
5480 * announce a transfer encoding chunked. This is required by haproxy
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05005481 * for the keepalive compliance. If the applet announces a transfer-encoding
5482 * chunked itself, don't do anything.
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005483 */
5484 if ((flags & (HTX_SL_F_VER_11|HTX_SL_F_XFER_LEN)) == HTX_SL_F_VER_11 &&
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005485 http_ctx->status >= 200 && http_ctx->status != 204 && http_ctx->status != 304) {
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005486 /* Add a new header */
5487 sl->flags |= (HTX_SL_F_XFER_ENC|H1_MF_CHNK|H1_MF_XFER_LEN);
5488 if (!htx_add_header(htx, ist("transfer-encoding"), ist("chunked"))) {
5489 hlua_pusherror(L, "Lua applet http '%s': Failed to add header 'transfer-encoding' in the response.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005490 luactx->appctx->rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005491 WILL_LJMP(lua_error(L));
5492 }
5493 }
5494
5495 /* Finalize headers. */
5496 if (!htx_add_endof(htx, HTX_BLK_EOH)) {
5497 hlua_pusherror(L, "Lua applet http '%s': Failed create the response.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005498 luactx->appctx->rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005499 WILL_LJMP(lua_error(L));
5500 }
5501
5502 if (htx_used_space(htx) > b_size(&res->buf) - global.tune.maxrewrite) {
5503 b_reset(&res->buf);
5504 hlua_pusherror(L, "Lua: 'start_response': response header block too big");
5505 WILL_LJMP(lua_error(L));
5506 }
5507
5508 htx_to_buf(htx, &res->buf);
Christopher Fauletf6cce3f2019-02-27 21:20:09 +01005509 channel_add_input(res, htx->data);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005510
5511 /* Headers sent, set the flag. */
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005512 http_ctx->flags |= APPLET_HDR_SENT;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005513 return 0;
5514
5515}
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005516/* We will build the status line and the headers of the HTTP response.
5517 * We will try send at once if its not possible, we give back the hand
5518 * waiting for more room.
5519 */
Christopher Fauleta2097962019-07-15 16:25:33 +02005520__LJMP static int hlua_applet_http_start_response_yield(lua_State *L, int status, lua_KContext ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005521{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005522 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Christopher Faulet908628c2022-03-25 16:43:49 +01005523 struct conn_stream *cs = luactx->appctx->owner;
5524 struct channel *res = cs_ic(cs);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005525
5526 if (co_data(res)) {
Christopher Fauleta0bdec32022-04-04 07:51:21 +02005527 cs_rx_room_blk(cs);
Christopher Fauleta2097962019-07-15 16:25:33 +02005528 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_start_response_yield, TICK_ETERNITY, 0));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005529 }
Christopher Fauleta2097962019-07-15 16:25:33 +02005530 return MAY_LJMP(hlua_applet_http_send_response(L));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005531}
5532
5533
Christopher Fauleta2097962019-07-15 16:25:33 +02005534__LJMP static int hlua_applet_http_start_response(lua_State *L)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005535{
Christopher Fauleta2097962019-07-15 16:25:33 +02005536 return MAY_LJMP(hlua_applet_http_start_response_yield(L, 0, 0));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005537}
5538
Christopher Fauleta2097962019-07-15 16:25:33 +02005539/*
5540 *
5541 *
5542 * Class HTTP
5543 *
5544 *
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005545 */
Christopher Fauleta2097962019-07-15 16:25:33 +02005546
5547/* Returns a struct hlua_txn if the stack entry "ud" is
5548 * a class stream, otherwise it throws an error.
5549 */
5550__LJMP static struct hlua_txn *hlua_checkhttp(lua_State *L, int ud)
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005551{
Christopher Fauleta2097962019-07-15 16:25:33 +02005552 return MAY_LJMP(hlua_checkudata(L, ud, class_http_ref));
5553}
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005554
Christopher Fauleta2097962019-07-15 16:25:33 +02005555/* This function creates and push in the stack a HTTP object
5556 * according with a current TXN.
5557 */
5558static int hlua_http_new(lua_State *L, struct hlua_txn *txn)
5559{
5560 struct hlua_txn *htxn;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005561
Christopher Fauleta2097962019-07-15 16:25:33 +02005562 /* Check stack size. */
5563 if (!lua_checkstack(L, 3))
5564 return 0;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005565
Christopher Fauleta2097962019-07-15 16:25:33 +02005566 /* Create the object: obj[0] = userdata.
5567 * Note that the base of the Converters object is the
5568 * same than the TXN object.
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005569 */
Christopher Fauleta2097962019-07-15 16:25:33 +02005570 lua_newtable(L);
5571 htxn = lua_newuserdata(L, sizeof(*htxn));
5572 lua_rawseti(L, -2, 0);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005573
5574 htxn->s = txn->s;
5575 htxn->p = txn->p;
Christopher Faulet256b69a2019-05-23 11:14:21 +02005576 htxn->dir = txn->dir;
5577 htxn->flags = txn->flags;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005578
5579 /* Pop a class stream metatable and affect it to the table. */
5580 lua_rawgeti(L, LUA_REGISTRYINDEX, class_http_ref);
5581 lua_setmetatable(L, -2);
5582
5583 return 1;
5584}
5585
Christopher Fauletdf97ac42020-02-26 16:57:19 +01005586/* This function creates and returns an array containing the status-line
5587 * elements. This function does not fails.
5588 */
5589__LJMP static int hlua_http_get_stline(lua_State *L, struct htx_sl *sl)
5590{
5591 /* Create the table. */
5592 lua_newtable(L);
5593
5594 if (sl->flags & HTX_SL_F_IS_RESP) {
5595 lua_pushstring(L, "version");
5596 lua_pushlstring(L, HTX_SL_RES_VPTR(sl), HTX_SL_RES_VLEN(sl));
5597 lua_settable(L, -3);
5598 lua_pushstring(L, "code");
5599 lua_pushlstring(L, HTX_SL_RES_CPTR(sl), HTX_SL_RES_CLEN(sl));
5600 lua_settable(L, -3);
5601 lua_pushstring(L, "reason");
5602 lua_pushlstring(L, HTX_SL_RES_RPTR(sl), HTX_SL_RES_RLEN(sl));
5603 lua_settable(L, -3);
5604 }
5605 else {
5606 lua_pushstring(L, "method");
5607 lua_pushlstring(L, HTX_SL_REQ_MPTR(sl), HTX_SL_REQ_MLEN(sl));
5608 lua_settable(L, -3);
5609 lua_pushstring(L, "uri");
5610 lua_pushlstring(L, HTX_SL_REQ_UPTR(sl), HTX_SL_REQ_ULEN(sl));
5611 lua_settable(L, -3);
5612 lua_pushstring(L, "version");
5613 lua_pushlstring(L, HTX_SL_REQ_VPTR(sl), HTX_SL_REQ_VLEN(sl));
5614 lua_settable(L, -3);
5615 }
5616 return 1;
5617}
5618
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005619/* This function creates ans returns an array of HTTP headers.
5620 * This function does not fails. It is used as wrapper with the
5621 * 2 following functions.
5622 */
Christopher Faulet9d1332b2020-02-24 16:46:16 +01005623__LJMP static int hlua_http_get_headers(lua_State *L, struct http_msg *msg)
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005624{
Christopher Fauleta2097962019-07-15 16:25:33 +02005625 struct htx *htx;
5626 int32_t pos;
5627
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005628 /* Create the table. */
5629 lua_newtable(L);
5630
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005631
Christopher Fauleta2097962019-07-15 16:25:33 +02005632 htx = htxbuf(&msg->chn->buf);
5633 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
5634 struct htx_blk *blk = htx_get_blk(htx, pos);
5635 enum htx_blk_type type = htx_get_blk_type(blk);
5636 struct ist n, v;
5637 int len;
Christopher Faulet724a12c2018-12-13 22:12:15 +01005638
Christopher Fauleta2097962019-07-15 16:25:33 +02005639 if (type == HTX_BLK_HDR) {
5640 n = htx_get_blk_name(htx,blk);
5641 v = htx_get_blk_value(htx, blk);
Christopher Faulet724a12c2018-12-13 22:12:15 +01005642 }
Christopher Fauleta2097962019-07-15 16:25:33 +02005643 else if (type == HTX_BLK_EOH)
5644 break;
5645 else
5646 continue;
Christopher Faulet724a12c2018-12-13 22:12:15 +01005647
Christopher Fauleta2097962019-07-15 16:25:33 +02005648 /* Check for existing entry:
5649 * assume that the table is on the top of the stack, and
5650 * push the key in the stack, the function lua_gettable()
5651 * perform the lookup.
5652 */
5653 lua_pushlstring(L, n.ptr, n.len);
5654 lua_gettable(L, -2);
Christopher Faulet724a12c2018-12-13 22:12:15 +01005655
Christopher Fauleta2097962019-07-15 16:25:33 +02005656 switch (lua_type(L, -1)) {
5657 case LUA_TNIL:
5658 /* Table not found, create it. */
5659 lua_pop(L, 1); /* remove the nil value. */
5660 lua_pushlstring(L, n.ptr, n.len); /* push the header name as key. */
5661 lua_newtable(L); /* create and push empty table. */
5662 lua_pushlstring(L, v.ptr, v.len); /* push header value. */
5663 lua_rawseti(L, -2, 0); /* index header value (pop it). */
5664 lua_rawset(L, -3); /* index new table with header name (pop the values). */
Christopher Faulet724a12c2018-12-13 22:12:15 +01005665 break;
Christopher Faulet724a12c2018-12-13 22:12:15 +01005666
Christopher Fauleta2097962019-07-15 16:25:33 +02005667 case LUA_TTABLE:
5668 /* Entry found: push the value in the table. */
5669 len = lua_rawlen(L, -1);
5670 lua_pushlstring(L, v.ptr, v.len); /* push header value. */
5671 lua_rawseti(L, -2, len+1); /* index header value (pop it). */
5672 lua_pop(L, 1); /* remove the table (it is stored in the main table). */
5673 break;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005674
Christopher Fauleta2097962019-07-15 16:25:33 +02005675 default:
5676 /* Other cases are errors. */
5677 hlua_pusherror(L, "internal error during the parsing of headers.");
5678 WILL_LJMP(lua_error(L));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005679 }
5680 }
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005681 return 1;
5682}
5683
5684__LJMP static int hlua_http_req_get_headers(lua_State *L)
5685{
5686 struct hlua_txn *htxn;
5687
5688 MAY_LJMP(check_args(L, 1, "req_get_headers"));
5689 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5690
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005691 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005692 WILL_LJMP(lua_error(L));
5693
Christopher Faulet9d1332b2020-02-24 16:46:16 +01005694 return hlua_http_get_headers(L, &htxn->s->txn->req);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005695}
5696
5697__LJMP static int hlua_http_res_get_headers(lua_State *L)
5698{
5699 struct hlua_txn *htxn;
5700
5701 MAY_LJMP(check_args(L, 1, "res_get_headers"));
5702 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5703
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005704 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005705 WILL_LJMP(lua_error(L));
5706
Christopher Faulet9d1332b2020-02-24 16:46:16 +01005707 return hlua_http_get_headers(L, &htxn->s->txn->rsp);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005708}
5709
5710/* This function replace full header, or just a value in
5711 * the request or in the response. It is a wrapper fir the
5712 * 4 following functions.
5713 */
Christopher Fauletd1914aa2020-02-24 16:52:46 +01005714__LJMP static inline int hlua_http_rep_hdr(lua_State *L, struct http_msg *msg, int full)
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005715{
5716 size_t name_len;
5717 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
5718 const char *reg = MAY_LJMP(luaL_checkstring(L, 3));
5719 const char *value = MAY_LJMP(luaL_checkstring(L, 4));
Christopher Fauleta2097962019-07-15 16:25:33 +02005720 struct htx *htx;
Dragan Dosen26743032019-04-30 15:54:36 +02005721 struct my_regex *re;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005722
Dragan Dosen26743032019-04-30 15:54:36 +02005723 if (!(re = regex_comp(reg, 1, 1, NULL)))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005724 WILL_LJMP(luaL_argerror(L, 3, "invalid regex"));
5725
Christopher Fauleta2097962019-07-15 16:25:33 +02005726 htx = htxbuf(&msg->chn->buf);
Christopher Fauletd1914aa2020-02-24 16:52:46 +01005727 http_replace_hdrs(chn_strm(msg->chn), htx, ist2(name, name_len), value, re, full);
Dragan Dosen26743032019-04-30 15:54:36 +02005728 regex_free(re);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005729 return 0;
5730}
5731
5732__LJMP static int hlua_http_req_rep_hdr(lua_State *L)
5733{
5734 struct hlua_txn *htxn;
5735
5736 MAY_LJMP(check_args(L, 4, "req_rep_hdr"));
5737 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5738
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005739 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005740 WILL_LJMP(lua_error(L));
5741
Christopher Fauletd1914aa2020-02-24 16:52:46 +01005742 return MAY_LJMP(hlua_http_rep_hdr(L, &htxn->s->txn->req, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005743}
5744
5745__LJMP static int hlua_http_res_rep_hdr(lua_State *L)
5746{
5747 struct hlua_txn *htxn;
5748
5749 MAY_LJMP(check_args(L, 4, "res_rep_hdr"));
5750 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5751
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005752 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005753 WILL_LJMP(lua_error(L));
5754
Christopher Fauletd1914aa2020-02-24 16:52:46 +01005755 return MAY_LJMP(hlua_http_rep_hdr(L, &htxn->s->txn->rsp, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005756}
5757
5758__LJMP static int hlua_http_req_rep_val(lua_State *L)
5759{
5760 struct hlua_txn *htxn;
5761
5762 MAY_LJMP(check_args(L, 4, "req_rep_hdr"));
5763 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5764
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005765 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005766 WILL_LJMP(lua_error(L));
5767
Christopher Fauletd1914aa2020-02-24 16:52:46 +01005768 return MAY_LJMP(hlua_http_rep_hdr(L, &htxn->s->txn->req, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005769}
5770
5771__LJMP static int hlua_http_res_rep_val(lua_State *L)
5772{
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005773 struct hlua_txn *htxn;
5774
5775 MAY_LJMP(check_args(L, 4, "res_rep_val"));
5776 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5777
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005778 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005779 WILL_LJMP(lua_error(L));
5780
Christopher Fauletd1914aa2020-02-24 16:52:46 +01005781 return MAY_LJMP(hlua_http_rep_hdr(L, &htxn->s->txn->rsp, 0));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005782}
5783
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08005784/* This function deletes all the occurrences of an header.
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005785 * It is a wrapper for the 2 following functions.
5786 */
Christopher Fauletd31c7b32020-02-25 09:37:57 +01005787__LJMP static inline int hlua_http_del_hdr(lua_State *L, struct http_msg *msg)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005788{
5789 size_t len;
5790 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Christopher Fauleta2097962019-07-15 16:25:33 +02005791 struct htx *htx = htxbuf(&msg->chn->buf);
5792 struct http_hdr_ctx ctx;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005793
Christopher Fauleta2097962019-07-15 16:25:33 +02005794 ctx.blk = NULL;
5795 while (http_find_header(htx, ist2(name, len), &ctx, 1))
5796 http_remove_header(htx, &ctx);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005797 return 0;
5798}
5799
5800__LJMP static int hlua_http_req_del_hdr(lua_State *L)
5801{
5802 struct hlua_txn *htxn;
5803
5804 MAY_LJMP(check_args(L, 2, "req_del_hdr"));
5805 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5806
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005807 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005808 WILL_LJMP(lua_error(L));
5809
Christopher Fauletd31c7b32020-02-25 09:37:57 +01005810 return hlua_http_del_hdr(L, &htxn->s->txn->req);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005811}
5812
5813__LJMP static int hlua_http_res_del_hdr(lua_State *L)
5814{
5815 struct hlua_txn *htxn;
5816
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005817 MAY_LJMP(check_args(L, 2, "res_del_hdr"));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005818 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5819
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005820 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005821 WILL_LJMP(lua_error(L));
5822
Christopher Fauletd31c7b32020-02-25 09:37:57 +01005823 return hlua_http_del_hdr(L, &htxn->s->txn->rsp);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005824}
5825
5826/* This function adds an header. It is a wrapper used by
5827 * the 2 following functions.
5828 */
Christopher Fauletd31c7b32020-02-25 09:37:57 +01005829__LJMP static inline int hlua_http_add_hdr(lua_State *L, struct http_msg *msg)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005830{
5831 size_t name_len;
5832 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
5833 size_t value_len;
5834 const char *value = MAY_LJMP(luaL_checklstring(L, 3, &value_len));
Christopher Fauleta2097962019-07-15 16:25:33 +02005835 struct htx *htx = htxbuf(&msg->chn->buf);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005836
Christopher Fauleta2097962019-07-15 16:25:33 +02005837 lua_pushboolean(L, http_add_header(htx, ist2(name, name_len),
5838 ist2(value, value_len)));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005839 return 0;
5840}
5841
Christopher Fauletdf97ac42020-02-26 16:57:19 +01005842__LJMP static int hlua_http_req_add_hdr(lua_State *L)
5843{
5844 struct hlua_txn *htxn;
5845
5846 MAY_LJMP(check_args(L, 3, "req_add_hdr"));
5847 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5848
5849 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
5850 WILL_LJMP(lua_error(L));
5851
5852 return hlua_http_add_hdr(L, &htxn->s->txn->req);
5853}
5854
5855__LJMP static int hlua_http_res_add_hdr(lua_State *L)
5856{
5857 struct hlua_txn *htxn;
5858
5859 MAY_LJMP(check_args(L, 3, "res_add_hdr"));
5860 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5861
5862 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
5863 WILL_LJMP(lua_error(L));
5864
5865 return hlua_http_add_hdr(L, &htxn->s->txn->rsp);
5866}
5867
5868static int hlua_http_req_set_hdr(lua_State *L)
5869{
5870 struct hlua_txn *htxn;
5871
5872 MAY_LJMP(check_args(L, 3, "req_set_hdr"));
5873 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5874
5875 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
5876 WILL_LJMP(lua_error(L));
5877
5878 hlua_http_del_hdr(L, &htxn->s->txn->req);
5879 return hlua_http_add_hdr(L, &htxn->s->txn->req);
5880}
5881
5882static int hlua_http_res_set_hdr(lua_State *L)
5883{
5884 struct hlua_txn *htxn;
5885
5886 MAY_LJMP(check_args(L, 3, "res_set_hdr"));
5887 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5888
5889 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
5890 WILL_LJMP(lua_error(L));
5891
5892 hlua_http_del_hdr(L, &htxn->s->txn->rsp);
5893 return hlua_http_add_hdr(L, &htxn->s->txn->rsp);
5894}
5895
5896/* This function set the method. */
5897static int hlua_http_req_set_meth(lua_State *L)
5898{
5899 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5900 size_t name_len;
5901 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
5902
5903 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
5904 WILL_LJMP(lua_error(L));
5905
5906 lua_pushboolean(L, http_req_replace_stline(0, name, name_len, htxn->p, htxn->s) != -1);
5907 return 1;
5908}
5909
5910/* This function set the method. */
5911static int hlua_http_req_set_path(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(1, name, name_len, htxn->p, htxn->s) != -1);
5921 return 1;
5922}
5923
5924/* This function set the query-string. */
5925static int hlua_http_req_set_query(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 /* Check length. */
5935 if (name_len > trash.size - 1) {
5936 lua_pushboolean(L, 0);
5937 return 1;
5938 }
5939
5940 /* Add the mark question as prefix. */
5941 chunk_reset(&trash);
5942 trash.area[trash.data++] = '?';
5943 memcpy(trash.area + trash.data, name, name_len);
5944 trash.data += name_len;
5945
5946 lua_pushboolean(L,
5947 http_req_replace_stline(2, trash.area, trash.data, htxn->p, htxn->s) != -1);
5948 return 1;
5949}
5950
5951/* This function set the uri. */
5952static int hlua_http_req_set_uri(lua_State *L)
5953{
5954 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5955 size_t name_len;
5956 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
5957
5958 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
5959 WILL_LJMP(lua_error(L));
5960
5961 lua_pushboolean(L, http_req_replace_stline(3, name, name_len, htxn->p, htxn->s) != -1);
5962 return 1;
5963}
5964
5965/* This function set the response code & optionally reason. */
5966static int hlua_http_res_set_status(lua_State *L)
5967{
5968 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5969 unsigned int code = MAY_LJMP(luaL_checkinteger(L, 2));
5970 const char *str = MAY_LJMP(luaL_optlstring(L, 3, NULL, NULL));
5971 const struct ist reason = ist2(str, (str ? strlen(str) : 0));
5972
5973 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
5974 WILL_LJMP(lua_error(L));
5975
5976 http_res_set_status(code, reason, htxn->s);
5977 return 0;
5978}
5979
5980/*
5981 *
5982 *
5983 * Class HTTPMessage
5984 *
5985 *
5986 */
5987
5988/* Returns a struct http_msg if the stack entry "ud" is a class HTTPMessage,
5989 * otherwise it throws an error.
5990 */
5991__LJMP static struct http_msg *hlua_checkhttpmsg(lua_State *L, int ud)
5992{
5993 return MAY_LJMP(hlua_checkudata(L, ud, class_http_msg_ref));
5994}
5995
5996/* Creates and pushes on the stack a HTTP object according with a current TXN.
5997 */
Christopher Faulet78c35472020-02-26 17:14:08 +01005998static int hlua_http_msg_new(lua_State *L, struct http_msg *msg)
Christopher Fauletdf97ac42020-02-26 16:57:19 +01005999{
6000 /* Check stack size. */
6001 if (!lua_checkstack(L, 3))
6002 return 0;
6003
6004 lua_newtable(L);
6005 lua_pushlightuserdata(L, msg);
6006 lua_rawseti(L, -2, 0);
6007
6008 /* Create the "channel" field that contains the request channel object. */
6009 lua_pushstring(L, "channel");
6010 if (!hlua_channel_new(L, msg->chn))
6011 return 0;
6012 lua_rawset(L, -3);
6013
6014 /* Pop a class stream metatable and affect it to the table. */
6015 lua_rawgeti(L, LUA_REGISTRYINDEX, class_http_msg_ref);
6016 lua_setmetatable(L, -2);
6017
6018 return 1;
6019}
6020
6021/* Helper function returning a filter attached to the HTTP message at the
6022 * position <ud> in the stack, filling the current offset and length of the
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006023 * filter. If no filter is attached, NULL is returned and <offset> and <len> are
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006024 * filled with output and input length respectively.
6025 */
6026static struct filter *hlua_http_msg_filter(lua_State *L, int ud, struct http_msg *msg, size_t *offset, size_t *len)
6027{
6028 struct channel *chn = msg->chn;
6029 struct htx *htx = htxbuf(&chn->buf);
6030 struct filter *filter = NULL;
6031
6032 *offset = co_data(msg->chn);
6033 *len = htx->data - co_data(msg->chn);
6034
6035 if (lua_getfield(L, ud, "__filter") == LUA_TLIGHTUSERDATA) {
6036 filter = lua_touserdata (L, -1);
6037 if (msg->msg_state >= HTTP_MSG_DATA) {
6038 struct hlua_flt_ctx *flt_ctx = filter->ctx;
6039
6040 *offset = flt_ctx->cur_off[CHN_IDX(chn)];
6041 *len = flt_ctx->cur_len[CHN_IDX(chn)];
6042 }
6043 }
6044
6045 lua_pop(L, 1);
6046 return filter;
6047}
6048
6049/* Returns true if the channel attached to the HTTP message is the response
6050 * channel.
6051 */
6052__LJMP static int hlua_http_msg_is_resp(lua_State *L)
6053{
6054 struct http_msg *msg;
6055
6056 MAY_LJMP(check_args(L, 1, "is_resp"));
6057 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6058
6059 lua_pushboolean(L, !!(msg->chn->flags & CF_ISRESP));
6060 return 1;
6061}
6062
6063/* Returns an array containing the elements status-line of the HTTP message. It relies
6064 * on hlua_http_get_stline().
6065 */
6066__LJMP static int hlua_http_msg_get_stline(lua_State *L)
6067{
6068 struct http_msg *msg;
6069 struct htx *htx;
6070 struct htx_sl *sl;
6071
6072 MAY_LJMP(check_args(L, 1, "get_stline"));
6073 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6074
6075 if (msg->msg_state > HTTP_MSG_BODY)
6076 WILL_LJMP(lua_error(L));
6077
6078 htx = htxbuf(&msg->chn->buf);
6079 sl = http_get_stline(htx);
6080 if (!sl)
6081 return 0;
6082 return hlua_http_get_stline(L, sl);
6083}
6084
6085/* Returns an array containing all headers of the HTTP message. it relies on
6086 * hlua_http_get_headers().
6087 */
6088__LJMP static int hlua_http_msg_get_headers(lua_State *L)
6089{
6090 struct http_msg *msg;
6091
6092 MAY_LJMP(check_args(L, 1, "get_headers"));
6093 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6094
6095 if (msg->msg_state > HTTP_MSG_BODY)
6096 WILL_LJMP(lua_error(L));
6097
6098 return hlua_http_get_headers(L, msg);
6099}
6100
6101/* Deletes all occurrences of an header in the HTTP message matching on its
6102 * name. It relies on hlua_http_del_hdr().
6103 */
6104__LJMP static int hlua_http_msg_del_hdr(lua_State *L)
6105{
6106 struct http_msg *msg;
6107
6108 MAY_LJMP(check_args(L, 2, "del_header"));
6109 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6110
6111 if (msg->msg_state > HTTP_MSG_BODY)
6112 WILL_LJMP(lua_error(L));
6113
6114 return hlua_http_del_hdr(L, msg);
6115}
6116
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006117/* Matches the full value line of all occurrences of an header in the HTTP
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006118 * message given its name against a regex and replaces it if it matches. It
6119 * relies on hlua_http_rep_hdr().
6120 */
6121__LJMP static int hlua_http_msg_rep_hdr(lua_State *L)
6122{
6123 struct http_msg *msg;
6124
6125 MAY_LJMP(check_args(L, 4, "rep_header"));
6126 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6127
6128 if (msg->msg_state > HTTP_MSG_BODY)
6129 WILL_LJMP(lua_error(L));
6130
6131 return hlua_http_rep_hdr(L, msg, 1);
6132}
6133
Ilya Shipitsinbd6b4be2021-10-15 16:18:21 +05006134/* Matches all comma-separated values of all occurrences of an header in the HTTP
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006135 * message given its name against a regex and replaces it if it matches. It
6136 * relies on hlua_http_rep_hdr().
6137 */
6138__LJMP static int hlua_http_msg_rep_val(lua_State *L)
6139{
6140 struct http_msg *msg;
6141
6142 MAY_LJMP(check_args(L, 4, "rep_value"));
6143 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6144
6145 if (msg->msg_state > HTTP_MSG_BODY)
6146 WILL_LJMP(lua_error(L));
6147
6148 return hlua_http_rep_hdr(L, msg, 0);
6149}
6150
6151/* Add an header in the HTTP message. It relies on hlua_http_add_hdr() */
6152__LJMP static int hlua_http_msg_add_hdr(lua_State *L)
6153{
6154 struct http_msg *msg;
6155
6156 MAY_LJMP(check_args(L, 3, "add_header"));
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_add_hdr(L, msg);
6163}
6164
6165/* Add an header in the HTTP message removing existing headers with the same
6166 * name. It relies on hlua_http_del_hdr() and hlua_http_add_hdr().
6167 */
6168__LJMP static int hlua_http_msg_set_hdr(lua_State *L)
6169{
6170 struct http_msg *msg;
6171
6172 MAY_LJMP(check_args(L, 3, "set_header"));
6173 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6174
6175 if (msg->msg_state > HTTP_MSG_BODY)
6176 WILL_LJMP(lua_error(L));
6177
6178 hlua_http_del_hdr(L, msg);
6179 return hlua_http_add_hdr(L, msg);
6180}
6181
6182/* Rewrites the request method. It relies on http_req_replace_stline(). */
6183__LJMP static int hlua_http_msg_set_meth(lua_State *L)
6184{
6185 struct stream *s;
6186 struct http_msg *msg;
6187 const char *name;
6188 size_t name_len;
6189
6190 MAY_LJMP(check_args(L, 2, "set_method"));
6191 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6192 name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
6193
6194 if ((msg->chn->flags & CF_ISRESP) || msg->msg_state > HTTP_MSG_BODY)
6195 WILL_LJMP(lua_error(L));
6196
6197 s = chn_strm(msg->chn);
6198 lua_pushboolean(L, http_req_replace_stline(0, name, name_len, s->be, s) != -1);
6199 return 1;
6200}
6201
6202/* Rewrites the request path. It relies on http_req_replace_stline(). */
6203__LJMP static int hlua_http_msg_set_path(lua_State *L)
6204{
6205 struct stream *s;
6206 struct http_msg *msg;
6207 const char *name;
6208 size_t name_len;
6209
6210 MAY_LJMP(check_args(L, 2, "set_path"));
6211 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6212 name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
6213
6214 if ((msg->chn->flags & CF_ISRESP) || msg->msg_state > HTTP_MSG_BODY)
6215 WILL_LJMP(lua_error(L));
6216
6217 s = chn_strm(msg->chn);
6218 lua_pushboolean(L, http_req_replace_stline(1, name, name_len, s->be, s) != -1);
6219 return 1;
6220}
6221
6222/* Rewrites the request query-string. It relies on http_req_replace_stline(). */
6223__LJMP static int hlua_http_msg_set_query(lua_State *L)
6224{
6225 struct stream *s;
6226 struct http_msg *msg;
6227 const char *name;
6228 size_t name_len;
6229
6230 MAY_LJMP(check_args(L, 2, "set_query"));
6231 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6232 name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
6233
6234 if ((msg->chn->flags & CF_ISRESP) || msg->msg_state > HTTP_MSG_BODY)
6235 WILL_LJMP(lua_error(L));
6236
6237 /* Check length. */
6238 if (name_len > trash.size - 1) {
6239 lua_pushboolean(L, 0);
6240 return 1;
6241 }
6242
6243 /* Add the mark question as prefix. */
6244 chunk_reset(&trash);
6245 trash.area[trash.data++] = '?';
6246 memcpy(trash.area + trash.data, name, name_len);
6247 trash.data += name_len;
6248
6249 s = chn_strm(msg->chn);
6250 lua_pushboolean(L, http_req_replace_stline(2, trash.area, trash.data, s->be, s) != -1);
6251 return 1;
6252}
6253
6254/* Rewrites the request URI. It relies on http_req_replace_stline(). */
6255__LJMP static int hlua_http_msg_set_uri(lua_State *L)
6256{
6257 struct stream *s;
6258 struct http_msg *msg;
6259 const char *name;
6260 size_t name_len;
6261
6262 MAY_LJMP(check_args(L, 2, "set_uri"));
6263 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6264 name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
6265
6266 if ((msg->chn->flags & CF_ISRESP) || msg->msg_state > HTTP_MSG_BODY)
6267 WILL_LJMP(lua_error(L));
6268
6269 s = chn_strm(msg->chn);
6270 lua_pushboolean(L, http_req_replace_stline(3, name, name_len, s->be, s) != -1);
6271 return 1;
6272}
6273
6274/* Rewrites the response status code. It relies on http_res_set_status(). */
6275__LJMP static int hlua_http_msg_set_status(lua_State *L)
6276{
6277 struct http_msg *msg;
6278 unsigned int code;
6279 const char *reason;
6280 size_t reason_len;
6281
6282 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6283 code = MAY_LJMP(luaL_checkinteger(L, 2));
6284 reason = MAY_LJMP(luaL_optlstring(L, 3, NULL, &reason_len));
6285
6286 if (!(msg->chn->flags & CF_ISRESP) || msg->msg_state > HTTP_MSG_BODY)
6287 WILL_LJMP(lua_error(L));
6288
6289 lua_pushboolean(L, http_res_set_status(code, ist2(reason, reason_len), chn_strm(msg->chn)) != -1);
6290 return 1;
6291}
6292
6293/* Returns true if the HTTP message is full. */
6294__LJMP static int hlua_http_msg_is_full(lua_State *L)
6295{
6296 struct http_msg *msg;
6297
6298 MAY_LJMP(check_args(L, 1, "is_full"));
6299 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6300 lua_pushboolean(L, channel_full(msg->chn, 0));
6301 return 1;
6302}
6303
6304/* Returns true if the HTTP message may still receive data. */
6305__LJMP static int hlua_http_msg_may_recv(lua_State *L)
6306{
6307 struct http_msg *msg;
6308 struct htx *htx;
6309
6310 MAY_LJMP(check_args(L, 1, "may_recv"));
6311 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6312 htx = htxbuf(&msg->chn->buf);
6313 lua_pushboolean(L, (htx_expect_more(htx) && !channel_input_closed(msg->chn) && channel_may_recv(msg->chn)));
6314 return 1;
6315}
6316
6317/* Returns true if the HTTP message EOM was received */
6318__LJMP static int hlua_http_msg_is_eom(lua_State *L)
6319{
6320 struct http_msg *msg;
6321 struct htx *htx;
6322
6323 MAY_LJMP(check_args(L, 1, "may_recv"));
6324 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6325 htx = htxbuf(&msg->chn->buf);
6326 lua_pushboolean(L, !htx_expect_more(htx));
6327 return 1;
6328}
6329
6330/* Returns the number of bytes available in the input side of the HTTP
6331 * message. This function never fails.
6332 */
6333__LJMP static int hlua_http_msg_get_in_len(lua_State *L)
6334{
6335 struct http_msg *msg;
Christopher Fauleteae8afa2020-02-26 17:15:48 +01006336 size_t output, input;
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006337
6338 MAY_LJMP(check_args(L, 1, "input"));
6339 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
Christopher Fauleteae8afa2020-02-26 17:15:48 +01006340 hlua_http_msg_filter(L, 1, msg, &output, &input);
6341 lua_pushinteger(L, input);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006342 return 1;
6343}
6344
6345/* Returns the number of bytes available in the output side of the HTTP
6346 * message. This function never fails.
6347 */
6348__LJMP static int hlua_http_msg_get_out_len(lua_State *L)
6349{
6350 struct http_msg *msg;
Christopher Fauleteae8afa2020-02-26 17:15:48 +01006351 size_t output, input;
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006352
6353 MAY_LJMP(check_args(L, 1, "output"));
6354 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
Christopher Fauleteae8afa2020-02-26 17:15:48 +01006355 hlua_http_msg_filter(L, 1, msg, &output, &input);
6356 lua_pushinteger(L, output);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006357 return 1;
6358}
6359
6360/* Copies at most <len> bytes of DATA blocks from the HTTP message <msg>
6361 * starting at the offset <offset> and put it in a string LUA variables. It
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006362 * returns the built string length. It stops on the first non-DATA HTX
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006363 * block. This function is called during the payload filtering, so the headers
6364 * are already scheduled for output (from the filter point of view).
6365 */
6366static int _hlua_http_msg_dup(struct http_msg *msg, lua_State *L, size_t offset, size_t len)
6367{
6368 struct htx *htx = htxbuf(&msg->chn->buf);
6369 struct htx_blk *blk;
6370 struct htx_ret htxret;
6371 luaL_Buffer b;
6372 int ret = 0;
6373
6374 luaL_buffinit(L, &b);
6375 htxret = htx_find_offset(htx, offset);
6376 for (blk = htxret.blk, offset = htxret.ret; blk && len; blk = htx_get_next_blk(htx, blk)) {
6377 enum htx_blk_type type = htx_get_blk_type(blk);
6378 struct ist v;
6379
6380 switch (type) {
6381 case HTX_BLK_UNUSED:
6382 break;
6383
6384 case HTX_BLK_DATA:
6385 v = htx_get_blk_value(htx, blk);
Tim Duesterhusb113b5c2021-09-15 13:58:44 +02006386 v = istadv(v, offset);
Tim Duesterhus2471f5c2021-11-08 09:05:01 +01006387 v = isttrim(v, len);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006388
6389 luaL_addlstring(&b, v.ptr, v.len);
6390 ret += v.len;
6391 break;
6392
6393 default:
vishnu0af4bd72021-10-24 06:46:24 +05306394 if (!ret)
6395 goto no_data;
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006396 goto end;
6397 }
6398 offset = 0;
6399 }
6400
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006401end:
vishnu0af4bd72021-10-24 06:46:24 +05306402 if (!ret && (htx->flags & HTX_FL_EOM))
6403 goto no_data;
6404 luaL_pushresult(&b);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006405 return ret;
vishnu0af4bd72021-10-24 06:46:24 +05306406
6407 no_data:
6408 /* Remove the empty string and push nil on the stack */
6409 lua_pop(L, 1);
6410 lua_pushnil(L);
6411 return 0;
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006412}
6413
6414/* Copies the string <str> to the HTTP message <msg> at the offset
6415 * <offset>. This function returns -1 if data cannot be copied. Otherwise, it
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006416 * returns the amount of data written. This function is responsible to update
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006417 * the filter context.
6418 */
6419static int _hlua_http_msg_insert(struct http_msg *msg, struct filter *filter, struct ist str, size_t offset)
6420{
6421 struct htx *htx = htx_from_buf(&msg->chn->buf);
6422 struct htx_ret htxret;
6423 int /*max, */ret = 0;
6424
6425 /* Nothing to do, just return */
6426 if (unlikely(istlen(str) == 0))
6427 goto end;
6428
6429 if (istlen(str) > htx_free_data_space(htx)) {
6430 ret = -1;
6431 goto end;
6432 }
6433
6434 htxret = htx_find_offset(htx, offset);
6435 if (!htxret.blk || htx_get_blk_type(htxret.blk) != HTX_BLK_DATA) {
6436 if (!htx_add_last_data(htx, str))
6437 goto end;
6438 }
6439 else {
6440 struct ist v = htx_get_blk_value(htx, htxret.blk);
6441 v.ptr += htxret.ret;
6442 v.len = 0;
6443 if (!htx_replace_blk_value(htx, htxret.blk, v, str))
6444 goto end;
6445 }
6446 ret = str.len;
6447 if (ret) {
6448 struct hlua_flt_ctx *flt_ctx = filter->ctx;
6449 flt_update_offsets(filter, msg->chn, ret);
6450 flt_ctx->cur_len[CHN_IDX(msg->chn)] += ret;
6451 }
6452
6453 end:
6454 htx_to_buf(htx, &msg->chn->buf);
6455 return ret;
6456}
6457
6458/* Helper function removing at most <len> bytes of DATA blocks at the absolute
6459 * position <offset>. It stops on the first non-DATA HTX block. This function is
6460 * called during the payload filtering, so the headers are already scheduled for
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006461 * output (from the filter point of view). This function is responsible to
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006462 * update the filter context.
6463 */
6464static void _hlua_http_msg_delete(struct http_msg *msg, struct filter *filter, size_t offset, size_t len)
6465{
6466 struct hlua_flt_ctx *flt_ctx = filter->ctx;
6467 struct htx *htx = htx_from_buf(&msg->chn->buf);
6468 struct htx_blk *blk;
6469 struct htx_ret htxret;
6470 size_t ret = 0;
6471
6472 /* Be sure <len> is always the amount of DATA to remove */
6473 if (htx->data == offset+len && htx_get_tail_type(htx) == HTX_BLK_DATA) {
6474 htx_truncate(htx, offset);
6475 ret = len;
6476 goto end;
6477 }
6478
6479 htxret = htx_find_offset(htx, offset);
6480 blk = htxret.blk;
6481 if (htxret.ret) {
6482 struct ist v;
6483
6484 if (htx_get_blk_type(blk) != HTX_BLK_DATA)
6485 goto end;
6486 v = htx_get_blk_value(htx, blk);
6487 v.ptr += htxret.ret;
Tim Duesterhus2471f5c2021-11-08 09:05:01 +01006488 v = isttrim(v, len);
Tim Duesterhusb113b5c2021-09-15 13:58:44 +02006489 blk = htx_replace_blk_value(htx, blk, v, IST_NULL);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006490 len -= v.len;
6491 ret += v.len;
6492 }
6493
6494
6495 while (blk && len) {
6496 enum htx_blk_type type = htx_get_blk_type(blk);
6497 uint32_t sz = htx_get_blksz(blk);
6498
6499 switch (type) {
6500 case HTX_BLK_UNUSED:
6501 break;
6502
6503 case HTX_BLK_DATA:
6504 if (len < sz) {
6505 htx_cut_data_blk(htx, blk, len);
6506 ret += len;
6507 goto end;
6508 }
6509 break;
6510
6511 default:
6512 goto end;
6513 }
6514
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006515 /* Remove all the data block */
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006516 len -= sz;
6517 ret += sz;
6518 blk = htx_remove_blk(htx, blk);
6519 }
6520
6521end:
6522 flt_update_offsets(filter, msg->chn, -ret);
6523 flt_ctx->cur_len[CHN_IDX(msg->chn)] -= ret;
6524 /* WARNING: we don't call htx_to_buf() on purpose, because we don't want
6525 * to loose the EOM flag if the message is empty.
6526 */
6527}
6528
6529/* Copies input data found in an HTTP message. Unlike the channel function used
6530 * to duplicate raw data, this one can only be called inside a filter, from
6531 * http_payload callback. So it cannot yield. An exception is returned if it is
6532 * called from another callback. If nothing was copied, a nil value is pushed on
6533 * the stack.
6534 */
6535__LJMP static int hlua_http_msg_get_body(lua_State *L)
6536{
6537 struct http_msg *msg;
6538 struct filter *filter;
6539 size_t output, input;
6540 int offset, len;
6541
6542 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
6543 WILL_LJMP(luaL_error(L, "'data' expects at most 2 arguments"));
6544 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6545
6546 if (msg->msg_state < HTTP_MSG_DATA)
6547 WILL_LJMP(lua_error(L));
6548
6549 filter = hlua_http_msg_filter(L, 1, msg, &output, &input);
6550 if (!filter || !hlua_filter_from_payload(filter))
6551 WILL_LJMP(lua_error(L));
6552
6553 if (!ci_data(msg->chn) && channel_input_closed(msg->chn)) {
6554 lua_pushnil(L);
6555 return 1;
6556 }
6557
6558 offset = output;
6559 if (lua_gettop(L) > 1) {
6560 offset = MAY_LJMP(luaL_checkinteger(L, 2));
6561 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02006562 offset = MAX(0, (int)input + offset);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006563 offset += output;
6564 if (offset < output || offset > input + output) {
6565 lua_pushfstring(L, "offset out of range.");
6566 WILL_LJMP(lua_error(L));
6567 }
6568 }
6569 len = output + input - offset;
6570 if (lua_gettop(L) == 3) {
6571 len = MAY_LJMP(luaL_checkinteger(L, 3));
6572 if (!len)
6573 goto dup;
6574 if (len == -1)
6575 len = global.tune.bufsize;
6576 if (len < 0) {
6577 lua_pushfstring(L, "length out of range.");
6578 WILL_LJMP(lua_error(L));
6579 }
6580 }
6581
6582 dup:
6583 _hlua_http_msg_dup(msg, L, offset, len);
6584 return 1;
6585}
6586
6587/* Appends a string to the HTTP message, after all existing DATA blocks but
6588 * before the trailers, if any. It returns the amount of data written or -1 if
6589 * nothing was copied. Unlike the channel function used to append data, this one
6590 * can only be called inside a filter, from http_payload callback. So it cannot
6591 * yield. An exception is returned if it is called from another callback.
6592 */
6593__LJMP static int hlua_http_msg_append(lua_State *L)
6594{
6595 struct http_msg *msg;
6596 struct filter *filter;
6597 const char *str;
6598 size_t offset, len, sz;
6599 int ret;
6600
6601 MAY_LJMP(check_args(L, 2, "append"));
6602 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6603
6604 if (msg->msg_state < HTTP_MSG_DATA)
6605 WILL_LJMP(lua_error(L));
6606
6607 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
6608 filter = hlua_http_msg_filter(L, 1, msg, &offset, &len);
6609 if (!filter || !hlua_filter_from_payload(filter))
6610 WILL_LJMP(lua_error(L));
6611
6612 ret = _hlua_http_msg_insert(msg, filter, ist2(str, sz), offset+len);
6613 lua_pushinteger(L, ret);
6614 return 1;
6615}
6616
6617/* Prepends a string to the HTTP message, before all existing DATA blocks. It
6618 * returns the amount of data written or -1 if nothing was copied. Unlike the
6619 * channel function used to prepend data, this one can only be called inside a
6620 * filter, from http_payload callback. So it cannot yield. An exception is
6621 * returned if it is called from another callback.
6622 */
6623__LJMP static int hlua_http_msg_prepend(lua_State *L)
6624{
6625 struct http_msg *msg;
6626 struct filter *filter;
6627 const char *str;
6628 size_t offset, len, sz;
6629 int ret;
6630
6631 MAY_LJMP(check_args(L, 2, "prepend"));
6632 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006633
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006634 if (msg->msg_state < HTTP_MSG_DATA)
6635 WILL_LJMP(lua_error(L));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006636
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006637 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
6638 filter = hlua_http_msg_filter(L, 1, msg, &offset, &len);
6639 if (!filter || !hlua_filter_from_payload(filter))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006640 WILL_LJMP(lua_error(L));
6641
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006642 ret = _hlua_http_msg_insert(msg, filter, ist2(str, sz), offset);
6643 lua_pushinteger(L, ret);
6644 return 1;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006645}
6646
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006647/* Inserts a string to the HTTP message at a given offset. By default the string
6648 * is appended at the end of DATA blocks. It returns the amount of data written
6649 * or -1 if nothing was copied. Unlike the channel function used to insert data,
6650 * this one can only be called inside a filter, from http_payload callback. So
6651 * it cannot yield. An exception is returned if it is called from another
6652 * callback.
6653 */
6654__LJMP static int hlua_http_msg_insert_data(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006655{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006656 struct http_msg *msg;
6657 struct filter *filter;
6658 const char *str;
6659 size_t input, output, sz;
6660 int offset;
6661 int ret;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006662
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006663 if (lua_gettop(L) < 2 || lua_gettop(L) > 3)
6664 WILL_LJMP(luaL_error(L, "'insert' expects at least 1 argument and at most 2 arguments"));
6665 MAY_LJMP(check_args(L, 2, "insert"));
6666 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006667
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006668 if (msg->msg_state < HTTP_MSG_DATA)
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006669 WILL_LJMP(lua_error(L));
6670
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006671 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
6672 filter = hlua_http_msg_filter(L, 1, msg, &input, &output);
6673 if (!filter || !hlua_filter_from_payload(filter))
6674 WILL_LJMP(lua_error(L));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006675
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006676 offset = input + output;
6677 if (lua_gettop(L) > 2) {
6678 offset = MAY_LJMP(luaL_checkinteger(L, 3));
6679 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02006680 offset = MAX(0, (int)input + offset);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006681 offset += output;
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006682 if (offset < output || offset > output + input) {
6683 lua_pushfstring(L, "offset out of range.");
6684 WILL_LJMP(lua_error(L));
6685 }
6686 }
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006687
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006688 ret = _hlua_http_msg_insert(msg, filter, ist2(str, sz), offset);
6689 lua_pushinteger(L, ret);
6690 return 1;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006691}
6692
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006693/* Removes a given amount of data from the HTTP message at a given offset. By
6694 * default all DATA blocks are removed. It returns the amount of data
6695 * removed. Unlike the channel function used to remove data, this one can only
6696 * be called inside a filter, from http_payload callback. So it cannot yield. An
6697 * exception is returned if it is called from another callback.
6698 */
6699__LJMP static int hlua_http_msg_del_data(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006700{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006701 struct http_msg *msg;
6702 struct filter *filter;
6703 size_t input, output;
6704 int offset, len;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006705
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006706 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
6707 WILL_LJMP(luaL_error(L, "'insert' expects at most 2 arguments"));
6708 MAY_LJMP(check_args(L, 2, "insert"));
6709 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006710
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006711 if (msg->msg_state < HTTP_MSG_DATA)
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006712 WILL_LJMP(lua_error(L));
6713
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006714 filter = hlua_http_msg_filter(L, 1, msg, &input, &output);
6715 if (!filter || !hlua_filter_from_payload(filter))
6716 WILL_LJMP(lua_error(L));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006717
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006718 offset = input + output;
6719 if (lua_gettop(L) > 2) {
6720 offset = MAY_LJMP(luaL_checkinteger(L, 3));
6721 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02006722 offset = MAX(0, (int)input + offset);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006723 offset += output;
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006724 if (offset < output || offset > output + input) {
6725 lua_pushfstring(L, "offset out of range.");
6726 WILL_LJMP(lua_error(L));
6727 }
6728 }
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006729
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006730 len = output + input - offset;
6731 if (lua_gettop(L) == 4) {
6732 len = MAY_LJMP(luaL_checkinteger(L, 4));
6733 if (!len)
6734 goto end;
6735 if (len == -1)
6736 len = output + input - offset;
6737 if (len < 0 || offset + len > output + input) {
6738 lua_pushfstring(L, "length out of range.");
6739 WILL_LJMP(lua_error(L));
6740 }
6741 }
6742
6743 _hlua_http_msg_delete(msg, filter, offset, len);
6744
6745 end:
6746 lua_pushinteger(L, len);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006747 return 1;
6748}
6749
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006750/* Replaces a given amount of data at the given offset by a string. By default,
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006751 * all remaining data are removed, accordingly to the filter context. It returns
6752 * the amount of data written or -1 if nothing was copied. Unlike the channel
6753 * function used to replace data, this one can only be called inside a filter,
6754 * from http_payload callback. So it cannot yield. An exception is returned if
6755 * it is called from another callback.
6756 */
6757__LJMP static int hlua_http_msg_set_data(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006758{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006759 struct http_msg *msg;
6760 struct filter *filter;
6761 struct htx *htx;
6762 const char *str;
6763 size_t input, output, sz;
6764 int offset, len;
6765 int ret;
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02006766
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006767 if (lua_gettop(L) < 2 || lua_gettop(L) > 4)
6768 WILL_LJMP(luaL_error(L, "'set' expects at least 1 argument and at most 3 arguments"));
6769 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6770
6771 if (msg->msg_state < HTTP_MSG_DATA)
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006772 WILL_LJMP(lua_error(L));
6773
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006774 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
6775 filter = hlua_http_msg_filter(L, 1, msg, &output, &input);
6776 if (!filter || !hlua_filter_from_payload(filter))
6777 WILL_LJMP(lua_error(L));
6778
6779 offset = output;
6780 if (lua_gettop(L) > 2) {
6781 offset = MAY_LJMP(luaL_checkinteger(L, 3));
6782 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02006783 offset = MAX(0, (int)input + offset);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006784 offset += output;
6785 if (offset < output || offset > input + output) {
6786 lua_pushfstring(L, "offset out of range.");
6787 WILL_LJMP(lua_error(L));
6788 }
6789 }
6790
6791 len = output + input - offset;
6792 if (lua_gettop(L) == 4) {
6793 len = MAY_LJMP(luaL_checkinteger(L, 4));
6794 if (!len)
6795 goto set;
6796 if (len == -1)
6797 len = output + input - offset;
6798 if (len < 0 || offset + len > output + input) {
6799 lua_pushfstring(L, "length out of range.");
6800 WILL_LJMP(lua_error(L));
6801 }
6802 }
6803
6804 set:
6805 /* Be sure we can copied the string once input data will be removed. */
6806 htx = htx_from_buf(&msg->chn->buf);
6807 if (sz > htx_free_data_space(htx) + len)
6808 lua_pushinteger(L, -1);
6809 else {
6810 _hlua_http_msg_delete(msg, filter, offset, len);
6811 ret = _hlua_http_msg_insert(msg, filter, ist2(str, sz), offset);
6812 lua_pushinteger(L, ret);
6813 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006814 return 1;
6815}
6816
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006817/* Prepends data into an HTTP message and forward it, from the filter point of
6818 * view. It returns the amount of data written or -1 if nothing was sent. Unlike
6819 * the channel function used to send data, this one can only be called inside a
6820 * filter, from http_payload callback. So it cannot yield. An exception is
6821 * returned if it is called from another callback.
6822 */
6823__LJMP static int hlua_http_msg_send(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006824{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006825 struct http_msg *msg;
6826 struct filter *filter;
6827 struct htx *htx;
6828 const char *str;
6829 size_t offset, len, sz;
6830 int ret;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006831
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006832 MAY_LJMP(check_args(L, 2, "send"));
6833 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6834
6835 if (msg->msg_state < HTTP_MSG_DATA)
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006836 WILL_LJMP(lua_error(L));
6837
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006838 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
6839 filter = hlua_http_msg_filter(L, 1, msg, &offset, &len);
6840 if (!filter || !hlua_filter_from_payload(filter))
6841 WILL_LJMP(lua_error(L));
6842
6843 /* Return an error if the channel's output is closed */
6844 if (unlikely(channel_output_closed(msg->chn))) {
6845 lua_pushinteger(L, -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006846 return 1;
6847 }
6848
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006849 htx = htx_from_buf(&msg->chn->buf);
6850 if (sz > htx_free_data_space(htx)) {
6851 lua_pushinteger(L, -1);
6852 return 1;
6853 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006854
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006855 ret = _hlua_http_msg_insert(msg, filter, ist2(str, sz), offset);
6856 if (ret > 0) {
6857 struct hlua_flt_ctx *flt_ctx = filter->ctx;
6858
6859 FLT_OFF(filter, msg->chn) += ret;
6860 flt_ctx->cur_len[CHN_IDX(msg->chn)] -= ret;
6861 flt_ctx->cur_off[CHN_IDX(msg->chn)] += ret;
6862 }
6863
6864 lua_pushinteger(L, ret);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006865 return 1;
6866}
6867
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006868/* Forwards a given amount of bytes. It return -1 if the channel's output is
6869 * closed. Otherwise, it returns the number of bytes forwarded. Unlike the
6870 * channel function used to forward data, this one can only be called inside a
6871 * filter, from http_payload callback. So it cannot yield. An exception is
6872 * returned if it is called from another callback. All other functions deal with
6873 * DATA block, this one not.
6874*/
6875__LJMP static int hlua_http_msg_forward(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006876{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006877 struct http_msg *msg;
6878 struct filter *filter;
6879 size_t offset, len;
6880 int fwd, ret = 0;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006881
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006882 MAY_LJMP(check_args(L, 2, "forward"));
6883 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6884
6885 if (msg->msg_state < HTTP_MSG_DATA)
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006886 WILL_LJMP(lua_error(L));
6887
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006888 fwd = MAY_LJMP(luaL_checkinteger(L, 2));
6889 filter = hlua_http_msg_filter(L, 1, msg, &offset, &len);
6890 if (!filter || !hlua_filter_from_payload(filter))
6891 WILL_LJMP(lua_error(L));
6892
6893 /* Nothing to do, just return */
6894 if (!fwd)
6895 goto end;
6896
6897 /* Return an error if the channel's output is closed */
6898 if (unlikely(channel_output_closed(msg->chn))) {
6899 ret = -1;
6900 goto end;
6901 }
6902
6903 ret = fwd;
6904 if (ret > len)
6905 ret = len;
6906
6907 if (ret) {
6908 struct hlua_flt_ctx *flt_ctx = filter->ctx;
6909
6910 FLT_OFF(filter, msg->chn) += ret;
6911 flt_ctx->cur_off[CHN_IDX(msg->chn)] += ret;
6912 flt_ctx->cur_len[CHN_IDX(msg->chn)] -= ret;
6913 }
6914
6915 end:
6916 lua_pushinteger(L, ret);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006917 return 1;
6918}
6919
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006920/* Set EOM flag on the HTX message.
6921 *
6922 * NOTE: Not sure it is a good idea to manipulate this flag but for now I don't
6923 * really know how to do without this feature.
6924 */
6925__LJMP static int hlua_http_msg_set_eom(lua_State *L)
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02006926{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006927 struct http_msg *msg;
6928 struct htx *htx;
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02006929
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006930 MAY_LJMP(check_args(L, 1, "set_eom"));
6931 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6932 htx = htxbuf(&msg->chn->buf);
6933 htx->flags |= HTX_FL_EOM;
6934 return 0;
6935}
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006936
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006937/* Unset EOM flag on the HTX message.
6938 *
6939 * NOTE: Not sure it is a good idea to manipulate this flag but for now I don't
6940 * really know how to do without this feature.
6941 */
6942__LJMP static int hlua_http_msg_unset_eom(lua_State *L)
6943{
6944 struct http_msg *msg;
6945 struct htx *htx;
6946
6947 MAY_LJMP(check_args(L, 1, "set_eom"));
6948 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6949 htx = htxbuf(&msg->chn->buf);
6950 htx->flags &= ~HTX_FL_EOM;
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02006951 return 0;
6952}
6953
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006954/*
6955 *
6956 *
William Lallemand3956c4e2021-09-21 16:25:15 +02006957 * Class HTTPClient
6958 *
6959 *
6960 */
6961__LJMP static struct hlua_httpclient *hlua_checkhttpclient(lua_State *L, int ud)
6962{
6963 return MAY_LJMP(hlua_checkudata(L, ud, class_httpclient_ref));
6964}
6965
William Lallemandf77f1de2021-09-28 19:10:38 +02006966
6967/* stops the httpclient and ask it to kill itself */
6968__LJMP static int hlua_httpclient_gc(lua_State *L)
6969{
6970 struct hlua_httpclient *hlua_hc;
6971
6972 MAY_LJMP(check_args(L, 1, "__gc"));
6973
6974 hlua_hc = MAY_LJMP(hlua_checkhttpclient(L, 1));
6975
6976 httpclient_stop_and_destroy(hlua_hc->hc);
6977
6978 hlua_hc->hc = NULL;
6979
6980
6981 return 0;
6982}
6983
6984
William Lallemand3956c4e2021-09-21 16:25:15 +02006985__LJMP static int hlua_httpclient_new(lua_State *L)
6986{
6987 struct hlua_httpclient *hlua_hc;
6988 struct hlua *hlua;
6989
6990 /* Get hlua struct, or NULL if we execute from main lua state */
6991 hlua = hlua_gethlua(L);
6992 if (!hlua)
6993 return 0;
6994
6995 /* Check stack size. */
6996 if (!lua_checkstack(L, 3)) {
6997 hlua_pusherror(L, "httpclient: full stack");
6998 goto err;
6999 }
7000 /* Create the object: obj[0] = userdata. */
7001 lua_newtable(L);
7002 hlua_hc = MAY_LJMP(lua_newuserdata(L, sizeof(*hlua_hc)));
7003 lua_rawseti(L, -2, 0);
7004 memset(hlua_hc, 0, sizeof(*hlua_hc));
7005
7006 hlua_hc->hc = httpclient_new(hlua, 0, IST_NULL);
7007 if (!hlua_hc->hc)
7008 goto err;
7009
7010 /* Pop a class stream metatable and affect it to the userdata. */
7011 lua_rawgeti(L, LUA_REGISTRYINDEX, class_httpclient_ref);
7012 lua_setmetatable(L, -2);
7013
7014 return 1;
7015
7016 err:
7017 WILL_LJMP(lua_error(L));
7018 return 0;
7019}
7020
7021
7022/*
7023 * Callback of the httpclient, this callback wakes the lua task up, once the
7024 * httpclient receives some data
7025 *
7026 */
7027
William Lallemandbd5739e2021-10-28 15:41:38 +02007028static void hlua_httpclient_cb(struct httpclient *hc)
William Lallemand3956c4e2021-09-21 16:25:15 +02007029{
7030 struct hlua *hlua = hc->caller;
7031
7032 if (!hlua || !hlua->task)
7033 return;
7034
7035 task_wakeup(hlua->task, TASK_WOKEN_MSG);
7036}
7037
7038/*
William Lallemandd7df73a2021-09-23 17:54:00 +02007039 * Fill the lua stack with headers from the httpclient response
7040 * This works the same way as the hlua_http_get_headers() function
7041 */
7042__LJMP static int hlua_httpclient_get_headers(lua_State *L, struct hlua_httpclient *hlua_hc)
7043{
7044 struct http_hdr *hdr;
7045
7046 lua_newtable(L);
7047
William Lallemandef574b22021-10-05 16:19:31 +02007048 for (hdr = hlua_hc->hc->res.hdrs; hdr && isttest(hdr->n); hdr++) {
William Lallemandd7df73a2021-09-23 17:54:00 +02007049 struct ist n, v;
7050 int len;
7051
7052 n = hdr->n;
7053 v = hdr->v;
7054
7055 /* Check for existing entry:
7056 * assume that the table is on the top of the stack, and
7057 * push the key in the stack, the function lua_gettable()
7058 * perform the lookup.
7059 */
7060
7061 lua_pushlstring(L, n.ptr, n.len);
7062 lua_gettable(L, -2);
7063
7064 switch (lua_type(L, -1)) {
7065 case LUA_TNIL:
7066 /* Table not found, create it. */
7067 lua_pop(L, 1); /* remove the nil value. */
7068 lua_pushlstring(L, n.ptr, n.len); /* push the header name as key. */
7069 lua_newtable(L); /* create and push empty table. */
7070 lua_pushlstring(L, v.ptr, v.len); /* push header value. */
7071 lua_rawseti(L, -2, 0); /* index header value (pop it). */
7072 lua_rawset(L, -3); /* index new table with header name (pop the values). */
7073 break;
7074
7075 case LUA_TTABLE:
7076 /* Entry found: push the value in the table. */
7077 len = lua_rawlen(L, -1);
7078 lua_pushlstring(L, v.ptr, v.len); /* push header value. */
7079 lua_rawseti(L, -2, len+1); /* index header value (pop it). */
7080 lua_pop(L, 1); /* remove the table (it is stored in the main table). */
7081 break;
7082
7083 default:
7084 /* Other cases are errors. */
7085 hlua_pusherror(L, "internal error during the parsing of headers.");
7086 WILL_LJMP(lua_error(L));
7087 }
7088 }
7089 return 1;
7090}
7091
7092/*
William Lallemand746e6f32021-10-06 10:57:44 +02007093 * Allocate and return an array of http_hdr ist extracted from the <headers> lua table
7094 *
7095 * Caller must free the result
7096 */
7097struct http_hdr *hlua_httpclient_table_to_hdrs(lua_State *L)
7098{
7099 struct http_hdr hdrs[global.tune.max_http_hdr];
7100 struct http_hdr *result = NULL;
7101 uint32_t hdr_num = 0;
7102
7103 lua_pushnil(L);
7104 while (lua_next(L, -2) != 0) {
7105 struct ist name, value;
7106 const char *n, *v;
7107 size_t nlen, vlen;
7108
7109 if (!lua_isstring(L, -2) || !lua_istable(L, -1)) {
7110 /* Skip element if the key is not a string or if the value is not a table */
7111 goto next_hdr;
7112 }
7113
7114 n = lua_tolstring(L, -2, &nlen);
7115 name = ist2(n, nlen);
7116
7117 /* Loop on header's values */
7118 lua_pushnil(L);
7119 while (lua_next(L, -2)) {
7120 if (!lua_isstring(L, -1)) {
7121 /* Skip the value if it is not a string */
7122 goto next_value;
7123 }
7124
7125 v = lua_tolstring(L, -1, &vlen);
7126 value = ist2(v, vlen);
7127 name = ist2(n, nlen);
7128
7129 hdrs[hdr_num].n = istdup(name);
7130 hdrs[hdr_num].v = istdup(value);
7131
7132 hdr_num++;
7133
7134 next_value:
7135 lua_pop(L, 1);
7136 }
7137
7138 next_hdr:
7139 lua_pop(L, 1);
7140
7141 }
7142
7143 if (hdr_num) {
7144 /* alloc and copy the headers in the httpclient struct */
Tim Duesterhus16cc16d2021-11-06 15:14:45 +01007145 result = calloc((hdr_num + 1), sizeof(*result));
William Lallemand746e6f32021-10-06 10:57:44 +02007146 if (!result)
7147 goto skip_headers;
7148 memcpy(result, hdrs, sizeof(struct http_hdr) * (hdr_num + 1));
7149
7150 result[hdr_num].n = IST_NULL;
7151 result[hdr_num].v = IST_NULL;
7152 }
7153
7154skip_headers:
William Lallemand746e6f32021-10-06 10:57:44 +02007155
7156 return result;
7157}
7158
7159
William Lallemandbd5739e2021-10-28 15:41:38 +02007160/*
7161 * For each yield, checks if there is some data in the httpclient and push them
7162 * in the lua buffer, once the httpclient finished its job, push the result on
7163 * the stack
7164 */
7165__LJMP static int hlua_httpclient_rcv_yield(lua_State *L, int status, lua_KContext ctx)
7166{
7167 struct buffer *tr;
7168 int res;
7169 struct hlua *hlua = hlua_gethlua(L);
7170 struct hlua_httpclient *hlua_hc = hlua_checkhttpclient(L, 1);
7171
7172
7173 tr = get_trash_chunk();
7174
7175 res = httpclient_res_xfer(hlua_hc->hc, tr);
7176 luaL_addlstring(&hlua_hc->b, b_orig(tr), res);
7177
7178 if (!httpclient_data(hlua_hc->hc) && httpclient_ended(hlua_hc->hc)) {
7179
7180 luaL_pushresult(&hlua_hc->b);
7181 lua_settable(L, -3);
7182
7183 lua_pushstring(L, "status");
7184 lua_pushinteger(L, hlua_hc->hc->res.status);
7185 lua_settable(L, -3);
7186
7187
7188 lua_pushstring(L, "reason");
7189 lua_pushlstring(L, hlua_hc->hc->res.reason.ptr, hlua_hc->hc->res.reason.len);
7190 lua_settable(L, -3);
7191
7192 lua_pushstring(L, "headers");
7193 hlua_httpclient_get_headers(L, hlua_hc);
7194 lua_settable(L, -3);
7195
7196 return 1;
7197 }
7198
7199 if (httpclient_data(hlua_hc->hc))
7200 task_wakeup(hlua->task, TASK_WOKEN_MSG);
7201
7202 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_httpclient_rcv_yield, TICK_ETERNITY, 0));
7203
7204 return 0;
7205}
7206
7207/*
7208 * Call this when trying to stream a body during a request
7209 */
7210__LJMP static int hlua_httpclient_snd_yield(lua_State *L, int status, lua_KContext ctx)
7211{
7212 struct hlua *hlua;
7213 struct hlua_httpclient *hlua_hc = hlua_checkhttpclient(L, 1);
7214 const char *body_str = NULL;
7215 int ret;
7216 int end = 0;
7217 size_t buf_len;
7218 size_t to_send = 0;
7219
7220 hlua = hlua_gethlua(L);
7221
7222 if (!hlua || !hlua->task)
7223 WILL_LJMP(luaL_error(L, "The 'get' function is only allowed in "
7224 "'frontend', 'backend' or 'task'"));
7225
7226 ret = lua_getfield(L, -1, "body");
7227 if (ret != LUA_TSTRING)
7228 goto rcv;
7229
7230 body_str = lua_tolstring(L, -1, &buf_len);
7231 lua_pop(L, 1);
7232
Christopher Fauletfc591292022-01-12 14:46:03 +01007233 to_send = buf_len - hlua_hc->sent;
William Lallemandbd5739e2021-10-28 15:41:38 +02007234
7235 if ((hlua_hc->sent + to_send) >= buf_len)
7236 end = 1;
7237
7238 /* the end flag is always set since we are using the whole remaining size */
7239 hlua_hc->sent += httpclient_req_xfer(hlua_hc->hc, ist2(body_str + hlua_hc->sent, to_send), end);
7240
7241 if (buf_len > hlua_hc->sent) {
7242 /* still need to process the buffer */
7243 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_httpclient_snd_yield, TICK_ETERNITY, 0));
7244 } else {
7245 goto rcv;
7246 /* we sent the whole request buffer we can recv */
7247 }
7248 return 0;
7249
7250rcv:
7251
7252 /* we return a "res" object */
7253 lua_newtable(L);
7254
William Lallemandbd5739e2021-10-28 15:41:38 +02007255 lua_pushstring(L, "body");
William Lallemandd1187eb2021-11-02 10:40:06 +01007256 luaL_buffinit(L, &hlua_hc->b);
William Lallemandbd5739e2021-10-28 15:41:38 +02007257
William Lallemand933fe392021-11-04 09:45:58 +01007258 task_wakeup(hlua->task, TASK_WOKEN_MSG);
William Lallemandbd5739e2021-10-28 15:41:38 +02007259 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_httpclient_rcv_yield, TICK_ETERNITY, 0));
7260
7261 return 1;
7262}
William Lallemand746e6f32021-10-06 10:57:44 +02007263
William Lallemand3956c4e2021-09-21 16:25:15 +02007264/*
William Lallemanddc2cc902021-10-26 11:43:26 +02007265 * Send an HTTP request and wait for a response
William Lallemand3956c4e2021-09-21 16:25:15 +02007266 */
7267
William Lallemanddc2cc902021-10-26 11:43:26 +02007268__LJMP static int hlua_httpclient_send(lua_State *L, enum http_meth_t meth)
William Lallemand3956c4e2021-09-21 16:25:15 +02007269{
7270 struct hlua_httpclient *hlua_hc;
William Lallemand746e6f32021-10-06 10:57:44 +02007271 struct http_hdr *hdrs = NULL;
7272 struct http_hdr *hdrs_i = NULL;
William Lallemand3956c4e2021-09-21 16:25:15 +02007273 struct hlua *hlua;
William Lallemand746e6f32021-10-06 10:57:44 +02007274 const char *url_str = NULL;
William Lallemanddec25c32021-10-25 19:48:37 +02007275 const char *body_str = NULL;
William Lallemandbd5739e2021-10-28 15:41:38 +02007276 size_t buf_len;
William Lallemand746e6f32021-10-06 10:57:44 +02007277 int ret;
William Lallemand3956c4e2021-09-21 16:25:15 +02007278
7279 hlua = hlua_gethlua(L);
7280
7281 if (!hlua || !hlua->task)
7282 WILL_LJMP(luaL_error(L, "The 'get' function is only allowed in "
7283 "'frontend', 'backend' or 'task'"));
7284
William Lallemand746e6f32021-10-06 10:57:44 +02007285 if (lua_gettop(L) != 2 || lua_type(L, -1) != LUA_TTABLE)
7286 WILL_LJMP(luaL_error(L, "'get' needs a table as argument"));
7287
William Lallemand4f4f2b72022-02-17 20:00:23 +01007288 hlua_hc = hlua_checkhttpclient(L, 1);
7289
William Lallemand7177a952022-03-03 15:33:12 +01007290 lua_pushnil(L); /* first key */
7291 while (lua_next(L, 2)) {
7292 if (strcmp(lua_tostring(L, -2), "dst") == 0) {
7293 if (httpclient_set_dst(hlua_hc->hc, lua_tostring(L, -1)) < 0)
7294 WILL_LJMP(luaL_error(L, "Can't use the 'dst' argument"));
William Lallemand4f4f2b72022-02-17 20:00:23 +01007295
William Lallemand7177a952022-03-03 15:33:12 +01007296 } else if (strcmp(lua_tostring(L, -2), "url") == 0) {
7297 if (lua_type(L, -1) != LUA_TSTRING)
7298 WILL_LJMP(luaL_error(L, "invalid parameter in 'url', must be a string"));
7299 url_str = lua_tostring(L, -1);
William Lallemand3956c4e2021-09-21 16:25:15 +02007300
William Lallemand7177a952022-03-03 15:33:12 +01007301 } else if (strcmp(lua_tostring(L, -2), "timeout") == 0) {
7302 if (lua_type(L, -1) != LUA_TNUMBER)
7303 WILL_LJMP(luaL_error(L, "invalid parameter in 'timeout', must be a number"));
7304 httpclient_set_timeout(hlua_hc->hc, lua_tointeger(L, -1));
William Lallemandb4a4ef62022-02-23 14:18:16 +01007305
William Lallemand7177a952022-03-03 15:33:12 +01007306 } else if (strcmp(lua_tostring(L, -2), "headers") == 0) {
7307 if (lua_type(L, -1) != LUA_TTABLE)
7308 WILL_LJMP(luaL_error(L, "invalid parameter in 'headers', must be a table"));
7309 hdrs = hlua_httpclient_table_to_hdrs(L);
William Lallemand79416cb2021-09-24 14:51:44 +02007310
William Lallemand7177a952022-03-03 15:33:12 +01007311 } else if (strcmp(lua_tostring(L, -2), "body") == 0) {
7312 if (lua_type(L, -1) != LUA_TSTRING)
7313 WILL_LJMP(luaL_error(L, "invalid parameter in 'body', must be a string"));
7314 body_str = lua_tolstring(L, -1, &buf_len);
William Lallemandbd5739e2021-10-28 15:41:38 +02007315
William Lallemand7177a952022-03-03 15:33:12 +01007316 } else {
7317 WILL_LJMP(luaL_error(L, "'%s' invalid parameter name", lua_tostring(L, -2)));
7318 }
7319 /* removes 'value'; keeps 'key' for next iteration */
7320 lua_pop(L, 1);
7321 }
William Lallemanddec25c32021-10-25 19:48:37 +02007322
William Lallemand746e6f32021-10-06 10:57:44 +02007323 if (!url_str) {
7324 WILL_LJMP(luaL_error(L, "'get' need a 'url' argument"));
7325 return 0;
7326 }
William Lallemand3956c4e2021-09-21 16:25:15 +02007327
William Lallemand10a37362022-03-02 16:18:26 +01007328 hlua_hc->sent = 0;
William Lallemand3956c4e2021-09-21 16:25:15 +02007329
7330 hlua_hc->hc->req.url = istdup(ist(url_str));
William Lallemanddc2cc902021-10-26 11:43:26 +02007331 hlua_hc->hc->req.meth = meth;
William Lallemand3956c4e2021-09-21 16:25:15 +02007332
7333 /* update the httpclient callbacks */
William Lallemandbd5739e2021-10-28 15:41:38 +02007334 hlua_hc->hc->ops.res_stline = hlua_httpclient_cb;
7335 hlua_hc->hc->ops.res_headers = hlua_httpclient_cb;
7336 hlua_hc->hc->ops.res_payload = hlua_httpclient_cb;
William Lallemand8f170c72022-03-15 10:52:07 +01007337 hlua_hc->hc->ops.res_end = hlua_httpclient_cb;
William Lallemand3956c4e2021-09-21 16:25:15 +02007338
William Lallemandbd5739e2021-10-28 15:41:38 +02007339 /* a body is available, it will use the request callback */
7340 if (body_str) {
7341 hlua_hc->hc->ops.req_payload = hlua_httpclient_cb;
7342 }
William Lallemand3956c4e2021-09-21 16:25:15 +02007343
William Lallemandbd5739e2021-10-28 15:41:38 +02007344 ret = httpclient_req_gen(hlua_hc->hc, hlua_hc->hc->req.url, meth, hdrs, IST_NULL);
William Lallemand3956c4e2021-09-21 16:25:15 +02007345
William Lallemand746e6f32021-10-06 10:57:44 +02007346 /* free the temporary headers array */
7347 hdrs_i = hdrs;
7348 while (hdrs_i && isttest(hdrs_i->n)) {
7349 istfree(&hdrs_i->n);
7350 istfree(&hdrs_i->v);
7351 hdrs_i++;
7352 }
7353 ha_free(&hdrs);
7354
7355
William Lallemand6137a9e2021-10-26 15:01:53 +02007356 if (ret != ERR_NONE) {
7357 WILL_LJMP(luaL_error(L, "Can't generate the HTTP request"));
7358 return 0;
7359 }
7360
William Lallemandc2d3db42022-04-26 11:46:13 +02007361 if (!httpclient_start(hlua_hc->hc))
7362 WILL_LJMP(luaL_error(L, "couldn't start the httpclient"));
William Lallemand6137a9e2021-10-26 15:01:53 +02007363
William Lallemandbd5739e2021-10-28 15:41:38 +02007364 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_httpclient_snd_yield, TICK_ETERNITY, 0));
William Lallemand3956c4e2021-09-21 16:25:15 +02007365
William Lallemand3956c4e2021-09-21 16:25:15 +02007366 return 0;
7367}
7368
7369/*
William Lallemanddc2cc902021-10-26 11:43:26 +02007370 * Sends an HTTP HEAD request and wait for a response
7371 *
7372 * httpclient:head(url, headers, payload)
7373 */
7374__LJMP static int hlua_httpclient_head(lua_State *L)
7375{
7376 return hlua_httpclient_send(L, HTTP_METH_HEAD);
7377}
7378
7379/*
7380 * Send an HTTP GET request and wait for a response
7381 *
7382 * httpclient:get(url, headers, payload)
7383 */
7384__LJMP static int hlua_httpclient_get(lua_State *L)
7385{
7386 return hlua_httpclient_send(L, HTTP_METH_GET);
7387
7388}
7389
7390/*
7391 * Sends an HTTP PUT request and wait for a response
7392 *
7393 * httpclient:put(url, headers, payload)
7394 */
7395__LJMP static int hlua_httpclient_put(lua_State *L)
7396{
7397 return hlua_httpclient_send(L, HTTP_METH_PUT);
7398}
7399
7400/*
7401 * Send an HTTP POST request and wait for a response
7402 *
7403 * httpclient:post(url, headers, payload)
7404 */
7405__LJMP static int hlua_httpclient_post(lua_State *L)
7406{
7407 return hlua_httpclient_send(L, HTTP_METH_POST);
7408}
7409
7410
7411/*
7412 * Sends an HTTP DELETE request and wait for a response
7413 *
7414 * httpclient:delete(url, headers, payload)
7415 */
7416__LJMP static int hlua_httpclient_delete(lua_State *L)
7417{
7418 return hlua_httpclient_send(L, HTTP_METH_DELETE);
7419}
7420
7421/*
William Lallemand3956c4e2021-09-21 16:25:15 +02007422 *
7423 *
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007424 * Class TXN
7425 *
7426 *
7427 */
7428
7429/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02007430 * a class stream, otherwise it throws an error.
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007431 */
7432__LJMP static struct hlua_txn *hlua_checktxn(lua_State *L, int ud)
7433{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02007434 return MAY_LJMP(hlua_checkudata(L, ud, class_txn_ref));
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007435}
7436
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007437__LJMP static int hlua_set_var(lua_State *L)
7438{
7439 struct hlua_txn *htxn;
7440 const char *name;
7441 size_t len;
7442 struct sample smp;
7443
Tim Duesterhus4e172c92020-05-19 13:49:42 +02007444 if (lua_gettop(L) < 3 || lua_gettop(L) > 4)
7445 WILL_LJMP(luaL_error(L, "'set_var' needs between 3 and 4 arguments"));
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007446
7447 /* It is useles to retrieve the stream, but this function
7448 * runs only in a stream context.
7449 */
7450 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7451 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
7452
7453 /* Converts the third argument in a sample. */
Amaury Denoyellebc0af6a2020-10-29 17:21:20 +01007454 memset(&smp, 0, sizeof(smp));
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007455 hlua_lua2smp(L, 3, &smp);
7456
7457 /* Store the sample in a variable. */
Willy Tarreau7560dd42016-03-10 16:28:58 +01007458 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
Tim Duesterhus4e172c92020-05-19 13:49:42 +02007459
7460 if (lua_gettop(L) == 4 && lua_toboolean(L, 4))
7461 lua_pushboolean(L, vars_set_by_name_ifexist(name, len, &smp) != 0);
7462 else
7463 lua_pushboolean(L, vars_set_by_name(name, len, &smp) != 0);
7464
Tim Duesterhus84ebc132020-05-19 13:49:41 +02007465 return 1;
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007466}
7467
Christopher Faulet85d79c92016-11-09 16:54:56 +01007468__LJMP static int hlua_unset_var(lua_State *L)
7469{
7470 struct hlua_txn *htxn;
7471 const char *name;
7472 size_t len;
7473 struct sample smp;
7474
7475 MAY_LJMP(check_args(L, 2, "unset_var"));
7476
7477 /* It is useles to retrieve the stream, but this function
7478 * runs only in a stream context.
7479 */
7480 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7481 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
7482
7483 /* Unset the variable. */
7484 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
Tim Duesterhus84ebc132020-05-19 13:49:41 +02007485 lua_pushboolean(L, vars_unset_by_name_ifexist(name, len, &smp) != 0);
7486 return 1;
Christopher Faulet85d79c92016-11-09 16:54:56 +01007487}
7488
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007489__LJMP static int hlua_get_var(lua_State *L)
7490{
7491 struct hlua_txn *htxn;
7492 const char *name;
7493 size_t len;
7494 struct sample smp;
7495
7496 MAY_LJMP(check_args(L, 2, "get_var"));
7497
7498 /* It is useles to retrieve the stream, but this function
7499 * runs only in a stream context.
7500 */
7501 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7502 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
7503
Willy Tarreau7560dd42016-03-10 16:28:58 +01007504 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
Willy Tarreaue352b9d2021-09-03 11:52:38 +02007505 if (!vars_get_by_name(name, len, &smp, NULL)) {
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007506 lua_pushnil(L);
7507 return 1;
7508 }
7509
7510 return hlua_smp2lua(L, &smp);
7511}
7512
Willy Tarreau59551662015-03-10 14:23:13 +01007513__LJMP static int hlua_set_priv(lua_State *L)
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007514{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007515 struct hlua *hlua;
7516
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007517 MAY_LJMP(check_args(L, 2, "set_priv"));
7518
Willy Tarreau87b09662015-04-03 00:22:06 +02007519 /* It is useles to retrieve the stream, but this function
7520 * runs only in a stream context.
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007521 */
7522 MAY_LJMP(hlua_checktxn(L, 1));
Thierry Fournier4234dbd2020-11-28 13:18:23 +01007523
7524 /* Get hlua struct, or NULL if we execute from main lua state */
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007525 hlua = hlua_gethlua(L);
Thierry Fournier4234dbd2020-11-28 13:18:23 +01007526 if (!hlua)
7527 return 0;
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007528
7529 /* Remove previous value. */
Thierry FOURNIERe068b602017-04-26 13:27:05 +02007530 luaL_unref(L, LUA_REGISTRYINDEX, hlua->Mref);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007531
7532 /* Get and store new value. */
7533 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
7534 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
7535
7536 return 0;
7537}
7538
Willy Tarreau59551662015-03-10 14:23:13 +01007539__LJMP static int hlua_get_priv(lua_State *L)
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007540{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007541 struct hlua *hlua;
7542
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007543 MAY_LJMP(check_args(L, 1, "get_priv"));
7544
Willy Tarreau87b09662015-04-03 00:22:06 +02007545 /* It is useles to retrieve the stream, but this function
7546 * runs only in a stream context.
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007547 */
7548 MAY_LJMP(hlua_checktxn(L, 1));
Thierry Fournier4234dbd2020-11-28 13:18:23 +01007549
7550 /* Get hlua struct, or NULL if we execute from main lua state */
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007551 hlua = hlua_gethlua(L);
Thierry Fournier4234dbd2020-11-28 13:18:23 +01007552 if (!hlua) {
7553 lua_pushnil(L);
7554 return 1;
7555 }
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007556
7557 /* Push configuration index in the stack. */
7558 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
7559
7560 return 1;
7561}
7562
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007563/* Create stack entry containing a class TXN. This function
7564 * return 0 if the stack does not contains free slots,
7565 * otherwise it returns 1.
7566 */
Thierry FOURNIERab00df62016-07-14 11:42:37 +02007567static int hlua_txn_new(lua_State *L, struct stream *s, struct proxy *p, int dir, int flags)
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007568{
Willy Tarreaude491382015-04-06 11:04:28 +02007569 struct hlua_txn *htxn;
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007570
7571 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01007572 if (!lua_checkstack(L, 3))
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007573 return 0;
7574
7575 /* NOTE: The allocation never fails. The failure
7576 * throw an error, and the function never returns.
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08007577 * if the throw is not available, the process is aborted.
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007578 */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01007579 /* Create the object: obj[0] = userdata. */
7580 lua_newtable(L);
Willy Tarreaude491382015-04-06 11:04:28 +02007581 htxn = lua_newuserdata(L, sizeof(*htxn));
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01007582 lua_rawseti(L, -2, 0);
7583
Willy Tarreaude491382015-04-06 11:04:28 +02007584 htxn->s = s;
7585 htxn->p = p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01007586 htxn->dir = dir;
Thierry FOURNIERab00df62016-07-14 11:42:37 +02007587 htxn->flags = flags;
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007588
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01007589 /* Create the "f" field that contains a list of fetches. */
7590 lua_pushstring(L, "f");
Thierry FOURNIERca988662015-12-20 18:43:03 +01007591 if (!hlua_fetches_new(L, htxn, HLUA_F_MAY_USE_HTTP))
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01007592 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007593 lua_rawset(L, -3);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01007594
7595 /* Create the "sf" field that contains a list of stringsafe fetches. */
7596 lua_pushstring(L, "sf");
Thierry FOURNIERca988662015-12-20 18:43:03 +01007597 if (!hlua_fetches_new(L, htxn, HLUA_F_MAY_USE_HTTP | HLUA_F_AS_STRING))
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01007598 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007599 lua_rawset(L, -3);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01007600
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007601 /* Create the "c" field that contains a list of converters. */
7602 lua_pushstring(L, "c");
Willy Tarreaude491382015-04-06 11:04:28 +02007603 if (!hlua_converters_new(L, htxn, 0))
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01007604 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007605 lua_rawset(L, -3);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01007606
7607 /* Create the "sc" field that contains a list of stringsafe converters. */
7608 lua_pushstring(L, "sc");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01007609 if (!hlua_converters_new(L, htxn, HLUA_F_AS_STRING))
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007610 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007611 lua_rawset(L, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007612
Thierry FOURNIER397826a2015-03-11 19:39:09 +01007613 /* Create the "req" field that contains the request channel object. */
7614 lua_pushstring(L, "req");
Willy Tarreau2a71af42015-03-10 13:51:50 +01007615 if (!hlua_channel_new(L, &s->req))
Thierry FOURNIER397826a2015-03-11 19:39:09 +01007616 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007617 lua_rawset(L, -3);
Thierry FOURNIER397826a2015-03-11 19:39:09 +01007618
7619 /* Create the "res" field that contains the response channel object. */
7620 lua_pushstring(L, "res");
Willy Tarreau2a71af42015-03-10 13:51:50 +01007621 if (!hlua_channel_new(L, &s->res))
Thierry FOURNIER397826a2015-03-11 19:39:09 +01007622 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007623 lua_rawset(L, -3);
Thierry FOURNIER397826a2015-03-11 19:39:09 +01007624
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007625 /* Creates the HTTP object is the current proxy allows http. */
7626 lua_pushstring(L, "http");
Christopher Faulet1bb6afa2021-03-08 17:57:53 +01007627 if (IS_HTX_STRM(s)) {
Willy Tarreaude491382015-04-06 11:04:28 +02007628 if (!hlua_http_new(L, htxn))
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007629 return 0;
7630 }
7631 else
7632 lua_pushnil(L);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007633 lua_rawset(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007634
Christopher Faulet78c35472020-02-26 17:14:08 +01007635 if ((htxn->flags & HLUA_TXN_CTX_MASK) == HLUA_TXN_FLT_CTX) {
7636 /* HTTPMessage object are created when a lua TXN is created from
7637 * a filter context only
7638 */
7639
7640 /* Creates the HTTP-Request object is the current proxy allows http. */
7641 lua_pushstring(L, "http_req");
7642 if (p->mode == PR_MODE_HTTP) {
7643 if (!hlua_http_msg_new(L, &s->txn->req))
7644 return 0;
7645 }
7646 else
7647 lua_pushnil(L);
7648 lua_rawset(L, -3);
7649
7650 /* Creates the HTTP-Response object is the current proxy allows http. */
7651 lua_pushstring(L, "http_res");
7652 if (p->mode == PR_MODE_HTTP) {
7653 if (!hlua_http_msg_new(L, &s->txn->rsp))
7654 return 0;
7655 }
7656 else
7657 lua_pushnil(L);
7658 lua_rawset(L, -3);
7659 }
7660
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007661 /* Pop a class sesison metatable and affect it to the userdata. */
7662 lua_rawgeti(L, LUA_REGISTRYINDEX, class_txn_ref);
7663 lua_setmetatable(L, -2);
7664
7665 return 1;
7666}
7667
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01007668__LJMP static int hlua_txn_deflog(lua_State *L)
7669{
7670 const char *msg;
7671 struct hlua_txn *htxn;
7672
7673 MAY_LJMP(check_args(L, 2, "deflog"));
7674 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7675 msg = MAY_LJMP(luaL_checkstring(L, 2));
7676
7677 hlua_sendlog(htxn->s->be, htxn->s->logs.level, msg);
7678 return 0;
7679}
7680
7681__LJMP static int hlua_txn_log(lua_State *L)
7682{
7683 int level;
7684 const char *msg;
7685 struct hlua_txn *htxn;
7686
7687 MAY_LJMP(check_args(L, 3, "log"));
7688 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7689 level = MAY_LJMP(luaL_checkinteger(L, 2));
7690 msg = MAY_LJMP(luaL_checkstring(L, 3));
7691
7692 if (level < 0 || level >= NB_LOG_LEVELS)
7693 WILL_LJMP(luaL_argerror(L, 1, "Invalid loglevel."));
7694
7695 hlua_sendlog(htxn->s->be, level, msg);
7696 return 0;
7697}
7698
7699__LJMP static int hlua_txn_log_debug(lua_State *L)
7700{
7701 const char *msg;
7702 struct hlua_txn *htxn;
7703
7704 MAY_LJMP(check_args(L, 2, "Debug"));
7705 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7706 msg = MAY_LJMP(luaL_checkstring(L, 2));
7707 hlua_sendlog(htxn->s->be, LOG_DEBUG, msg);
7708 return 0;
7709}
7710
7711__LJMP static int hlua_txn_log_info(lua_State *L)
7712{
7713 const char *msg;
7714 struct hlua_txn *htxn;
7715
7716 MAY_LJMP(check_args(L, 2, "Info"));
7717 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7718 msg = MAY_LJMP(luaL_checkstring(L, 2));
7719 hlua_sendlog(htxn->s->be, LOG_INFO, msg);
7720 return 0;
7721}
7722
7723__LJMP static int hlua_txn_log_warning(lua_State *L)
7724{
7725 const char *msg;
7726 struct hlua_txn *htxn;
7727
7728 MAY_LJMP(check_args(L, 2, "Warning"));
7729 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7730 msg = MAY_LJMP(luaL_checkstring(L, 2));
7731 hlua_sendlog(htxn->s->be, LOG_WARNING, msg);
7732 return 0;
7733}
7734
7735__LJMP static int hlua_txn_log_alert(lua_State *L)
7736{
7737 const char *msg;
7738 struct hlua_txn *htxn;
7739
7740 MAY_LJMP(check_args(L, 2, "Alert"));
7741 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7742 msg = MAY_LJMP(luaL_checkstring(L, 2));
7743 hlua_sendlog(htxn->s->be, LOG_ALERT, msg);
7744 return 0;
7745}
7746
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01007747__LJMP static int hlua_txn_set_loglevel(lua_State *L)
7748{
7749 struct hlua_txn *htxn;
7750 int ll;
7751
7752 MAY_LJMP(check_args(L, 2, "set_loglevel"));
7753 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7754 ll = MAY_LJMP(luaL_checkinteger(L, 2));
7755
7756 if (ll < 0 || ll > 7)
7757 WILL_LJMP(luaL_argerror(L, 2, "Bad log level. It must be between 0 and 7"));
7758
7759 htxn->s->logs.level = ll;
7760 return 0;
7761}
7762
7763__LJMP static int hlua_txn_set_tos(lua_State *L)
7764{
7765 struct hlua_txn *htxn;
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01007766 int tos;
7767
7768 MAY_LJMP(check_args(L, 2, "set_tos"));
7769 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7770 tos = MAY_LJMP(luaL_checkinteger(L, 2));
7771
Willy Tarreau1a18b542018-12-11 16:37:42 +01007772 conn_set_tos(objt_conn(htxn->s->sess->origin), tos);
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01007773 return 0;
7774}
7775
7776__LJMP static int hlua_txn_set_mark(lua_State *L)
7777{
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01007778 struct hlua_txn *htxn;
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01007779 int mark;
7780
7781 MAY_LJMP(check_args(L, 2, "set_mark"));
7782 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7783 mark = MAY_LJMP(luaL_checkinteger(L, 2));
7784
Lukas Tribus579e3e32019-08-11 18:03:45 +02007785 conn_set_mark(objt_conn(htxn->s->sess->origin), mark);
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01007786 return 0;
7787}
7788
Patrick Hemmer268a7072018-05-11 12:52:31 -04007789__LJMP static int hlua_txn_set_priority_class(lua_State *L)
7790{
7791 struct hlua_txn *htxn;
7792
7793 MAY_LJMP(check_args(L, 2, "set_priority_class"));
7794 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7795 htxn->s->priority_class = queue_limit_class(MAY_LJMP(luaL_checkinteger(L, 2)));
7796 return 0;
7797}
7798
7799__LJMP static int hlua_txn_set_priority_offset(lua_State *L)
7800{
7801 struct hlua_txn *htxn;
7802
7803 MAY_LJMP(check_args(L, 2, "set_priority_offset"));
7804 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7805 htxn->s->priority_offset = queue_limit_offset(MAY_LJMP(luaL_checkinteger(L, 2)));
7806 return 0;
7807}
7808
Christopher Faulet700d9e82020-01-31 12:21:52 +01007809/* Forward the Reply object to the client. This function converts the reply in
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05007810 * HTX an push it to into the response channel. It is response to forward the
Christopher Faulet700d9e82020-01-31 12:21:52 +01007811 * message and terminate the transaction. It returns 1 on success and 0 on
7812 * error. The Reply must be on top of the stack.
7813 */
7814__LJMP static int hlua_txn_forward_reply(lua_State *L, struct stream *s)
7815{
7816 struct htx *htx;
7817 struct htx_sl *sl;
7818 struct h1m h1m;
7819 const char *status, *reason, *body;
7820 size_t status_len, reason_len, body_len;
7821 int ret, code, flags;
7822
7823 code = 200;
7824 status = "200";
7825 status_len = 3;
7826 ret = lua_getfield(L, -1, "status");
7827 if (ret == LUA_TNUMBER) {
7828 code = lua_tointeger(L, -1);
7829 status = lua_tolstring(L, -1, &status_len);
7830 }
7831 lua_pop(L, 1);
7832
7833 reason = http_get_reason(code);
7834 reason_len = strlen(reason);
7835 ret = lua_getfield(L, -1, "reason");
7836 if (ret == LUA_TSTRING)
7837 reason = lua_tolstring(L, -1, &reason_len);
7838 lua_pop(L, 1);
7839
7840 body = NULL;
7841 body_len = 0;
7842 ret = lua_getfield(L, -1, "body");
7843 if (ret == LUA_TSTRING)
7844 body = lua_tolstring(L, -1, &body_len);
7845 lua_pop(L, 1);
7846
7847 /* Prepare the response before inserting the headers */
7848 h1m_init_res(&h1m);
7849 htx = htx_from_buf(&s->res.buf);
7850 channel_htx_truncate(&s->res, htx);
7851 if (s->txn->req.flags & HTTP_MSGF_VER_11) {
7852 flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11);
7853 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.1"),
7854 ist2(status, status_len), ist2(reason, reason_len));
7855 }
7856 else {
7857 flags = HTX_SL_F_IS_RESP;
7858 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.0"),
7859 ist2(status, status_len), ist2(reason, reason_len));
7860 }
7861 if (!sl)
7862 goto fail;
7863 sl->info.res.status = code;
7864
7865 /* Push in the stack the "headers" entry. */
7866 ret = lua_getfield(L, -1, "headers");
7867 if (ret != LUA_TTABLE)
7868 goto skip_headers;
7869
7870 lua_pushnil(L);
7871 while (lua_next(L, -2) != 0) {
7872 struct ist name, value;
7873 const char *n, *v;
7874 size_t nlen, vlen;
7875
7876 if (!lua_isstring(L, -2) || !lua_istable(L, -1)) {
7877 /* Skip element if the key is not a string or if the value is not a table */
7878 goto next_hdr;
7879 }
7880
7881 n = lua_tolstring(L, -2, &nlen);
7882 name = ist2(n, nlen);
7883 if (isteqi(name, ist("content-length"))) {
7884 /* Always skip content-length header. It will be added
7885 * later with the correct len
7886 */
7887 goto next_hdr;
7888 }
7889
7890 /* Loop on header's values */
7891 lua_pushnil(L);
7892 while (lua_next(L, -2)) {
7893 if (!lua_isstring(L, -1)) {
7894 /* Skip the value if it is not a string */
7895 goto next_value;
7896 }
7897
7898 v = lua_tolstring(L, -1, &vlen);
7899 value = ist2(v, vlen);
7900
7901 if (isteqi(name, ist("transfer-encoding")))
7902 h1_parse_xfer_enc_header(&h1m, value);
7903 if (!htx_add_header(htx, ist2(n, nlen), ist2(v, vlen)))
7904 goto fail;
7905
7906 next_value:
7907 lua_pop(L, 1);
7908 }
7909
7910 next_hdr:
7911 lua_pop(L, 1);
7912 }
7913 skip_headers:
7914 lua_pop(L, 1);
7915
7916 /* Update h1m flags: CLEN is set if CHNK is not present */
7917 if (!(h1m.flags & H1_MF_CHNK)) {
7918 const char *clen = ultoa(body_len);
7919
7920 h1m.flags |= H1_MF_CLEN;
7921 if (!htx_add_header(htx, ist("content-length"), ist(clen)))
7922 goto fail;
7923 }
7924 if (h1m.flags & (H1_MF_CLEN|H1_MF_CHNK))
7925 h1m.flags |= H1_MF_XFER_LEN;
7926
7927 /* Update HTX start-line flags */
7928 if (h1m.flags & H1_MF_XFER_ENC)
7929 flags |= HTX_SL_F_XFER_ENC;
7930 if (h1m.flags & H1_MF_XFER_LEN) {
7931 flags |= HTX_SL_F_XFER_LEN;
7932 if (h1m.flags & H1_MF_CHNK)
7933 flags |= HTX_SL_F_CHNK;
7934 else if (h1m.flags & H1_MF_CLEN)
7935 flags |= HTX_SL_F_CLEN;
7936 if (h1m.body_len == 0)
7937 flags |= HTX_SL_F_BODYLESS;
7938 }
7939 sl->flags |= flags;
7940
7941
7942 if (!htx_add_endof(htx, HTX_BLK_EOH) ||
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01007943 (body_len && !htx_add_data_atonce(htx, ist2(body, body_len))))
Christopher Faulet700d9e82020-01-31 12:21:52 +01007944 goto fail;
7945
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01007946 htx->flags |= HTX_FL_EOM;
7947
Christopher Faulet700d9e82020-01-31 12:21:52 +01007948 /* Now, forward the response and terminate the transaction */
7949 s->txn->status = code;
7950 htx_to_buf(htx, &s->res.buf);
7951 if (!http_forward_proxy_resp(s, 1))
7952 goto fail;
7953
7954 return 1;
7955
7956 fail:
7957 channel_htx_truncate(&s->res, htx);
7958 return 0;
7959}
7960
7961/* Terminate a transaction if called from a lua action. For TCP streams,
7962 * processing is just aborted. Nothing is returned to the client and all
7963 * arguments are ignored. For HTTP streams, if a reply is passed as argument, it
7964 * is forwarded to the client before terminating the transaction. On success,
7965 * the function exits with ACT_RET_DONE code. If an error occurred, it exits
7966 * with ACT_RET_ERR code. If this function is not called from a lua action, it
7967 * just exits without any processing.
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01007968 */
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02007969__LJMP static int hlua_txn_done(lua_State *L)
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01007970{
Willy Tarreaub2ccb562015-04-06 11:11:15 +02007971 struct hlua_txn *htxn;
Christopher Faulet700d9e82020-01-31 12:21:52 +01007972 struct stream *s;
7973 int finst;
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01007974
Willy Tarreaub2ccb562015-04-06 11:11:15 +02007975 htxn = MAY_LJMP(hlua_checktxn(L, 1));
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01007976
Christopher Faulet700d9e82020-01-31 12:21:52 +01007977 /* If the flags NOTERM is set, we cannot terminate the session, so we
7978 * just end the execution of the current lua code. */
7979 if (htxn->flags & HLUA_TXN_NOTERM)
Thierry FOURNIERab00df62016-07-14 11:42:37 +02007980 WILL_LJMP(hlua_done(L));
Thierry FOURNIERab00df62016-07-14 11:42:37 +02007981
Christopher Faulet700d9e82020-01-31 12:21:52 +01007982 s = htxn->s;
Christopher Fauletd8f0e072020-02-25 09:45:51 +01007983 if (!IS_HTX_STRM(htxn->s)) {
Christopher Faulet700d9e82020-01-31 12:21:52 +01007984 struct channel *req = &s->req;
7985 struct channel *res = &s->res;
Willy Tarreau81389672015-03-10 12:03:52 +01007986
Christopher Faulet700d9e82020-01-31 12:21:52 +01007987 channel_auto_read(req);
7988 channel_abort(req);
7989 channel_auto_close(req);
7990 channel_erase(req);
7991
7992 res->wex = tick_add_ifset(now_ms, res->wto);
7993 channel_auto_read(res);
7994 channel_auto_close(res);
7995 channel_shutr_now(res);
7996
7997 finst = ((htxn->dir == SMP_OPT_DIR_REQ) ? SF_FINST_R : SF_FINST_D);
7998 goto done;
Christopher Fauletfe6a71b2019-07-26 16:40:24 +02007999 }
Thierry FOURNIER10ec2142015-08-24 17:23:45 +02008000
Christopher Faulet700d9e82020-01-31 12:21:52 +01008001 if (lua_gettop(L) == 1 || !lua_istable(L, 2)) {
8002 /* No reply or invalid reply */
8003 s->txn->status = 0;
8004 http_reply_and_close(s, 0, NULL);
8005 }
8006 else {
8007 /* Remove extra args to have the reply on top of the stack */
8008 if (lua_gettop(L) > 2)
8009 lua_pop(L, lua_gettop(L) - 2);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01008010
Christopher Faulet700d9e82020-01-31 12:21:52 +01008011 if (!hlua_txn_forward_reply(L, s)) {
8012 if (!(s->flags & SF_ERR_MASK))
8013 s->flags |= SF_ERR_PRXCOND;
8014 lua_pushinteger(L, ACT_RET_ERR);
8015 WILL_LJMP(hlua_done(L));
8016 return 0; /* Never reached */
8017 }
Christopher Faulet4d0e2632019-07-16 10:52:40 +02008018 }
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02008019
Christopher Faulet700d9e82020-01-31 12:21:52 +01008020 finst = ((htxn->dir == SMP_OPT_DIR_REQ) ? SF_FINST_R : SF_FINST_H);
8021 if (htxn->dir == SMP_OPT_DIR_REQ) {
8022 /* let's log the request time */
8023 s->logs.tv_request = now;
8024 if (s->sess->fe == s->be) /* report it if the request was intercepted by the frontend */
Willy Tarreau4781b152021-04-06 13:53:36 +02008025 _HA_ATOMIC_INC(&s->sess->fe->fe_counters.intercepted_req);
Christopher Faulet700d9e82020-01-31 12:21:52 +01008026 }
Christopher Fauletfe6a71b2019-07-26 16:40:24 +02008027
Christopher Faulet700d9e82020-01-31 12:21:52 +01008028 done:
8029 if (!(s->flags & SF_ERR_MASK))
8030 s->flags |= SF_ERR_LOCAL;
8031 if (!(s->flags & SF_FINST_MASK))
8032 s->flags |= finst;
Christopher Fauletfe6a71b2019-07-26 16:40:24 +02008033
Christopher Faulete48d1dc2021-08-13 14:11:17 +02008034 if ((htxn->flags & HLUA_TXN_CTX_MASK) == HLUA_TXN_FLT_CTX)
8035 lua_pushinteger(L, -1);
8036 else
8037 lua_pushinteger(L, ACT_RET_ABRT);
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02008038 WILL_LJMP(hlua_done(L));
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01008039 return 0;
8040}
8041
Christopher Faulet700d9e82020-01-31 12:21:52 +01008042/*
8043 *
8044 *
8045 * Class REPLY
8046 *
8047 *
8048 */
8049
8050/* Pushes the TXN reply onto the top of the stack. If the stask does not have a
8051 * free slots, the function fails and returns 0;
8052 */
8053static int hlua_txn_reply_new(lua_State *L)
8054{
8055 struct hlua_txn *htxn;
8056 const char *reason, *body = NULL;
8057 int ret, status;
8058
8059 htxn = MAY_LJMP(hlua_checktxn(L, 1));
Christopher Fauletd8f0e072020-02-25 09:45:51 +01008060 if (!IS_HTX_STRM(htxn->s)) {
Christopher Faulet700d9e82020-01-31 12:21:52 +01008061 hlua_pusherror(L, "txn object is not an HTTP transaction.");
8062 WILL_LJMP(lua_error(L));
8063 }
8064
8065 /* Default value */
8066 status = 200;
8067 reason = http_get_reason(status);
8068
8069 if (lua_istable(L, 2)) {
8070 /* load status and reason from the table argument at index 2 */
8071 ret = lua_getfield(L, 2, "status");
8072 if (ret == LUA_TNIL)
8073 goto reason;
8074 else if (ret != LUA_TNUMBER) {
8075 /* invalid status: ignore the reason */
8076 goto body;
8077 }
8078 status = lua_tointeger(L, -1);
8079
8080 reason:
8081 lua_pop(L, 1); /* restore the stack: remove status */
8082 ret = lua_getfield(L, 2, "reason");
8083 if (ret == LUA_TSTRING)
8084 reason = lua_tostring(L, -1);
8085
8086 body:
8087 lua_pop(L, 1); /* restore the stack: remove invalid status or reason */
8088 ret = lua_getfield(L, 2, "body");
8089 if (ret == LUA_TSTRING)
8090 body = lua_tostring(L, -1);
8091 lua_pop(L, 1); /* restore the stack: remove body */
8092 }
8093
8094 /* Create the Reply table */
8095 lua_newtable(L);
8096
8097 /* Add status element */
8098 lua_pushstring(L, "status");
8099 lua_pushinteger(L, status);
8100 lua_settable(L, -3);
8101
8102 /* Add reason element */
8103 reason = http_get_reason(status);
8104 lua_pushstring(L, "reason");
8105 lua_pushstring(L, reason);
8106 lua_settable(L, -3);
8107
8108 /* Add body element, nil if undefined */
8109 lua_pushstring(L, "body");
8110 if (body)
8111 lua_pushstring(L, body);
8112 else
8113 lua_pushnil(L);
8114 lua_settable(L, -3);
8115
8116 /* Add headers element */
8117 lua_pushstring(L, "headers");
8118 lua_newtable(L);
8119
8120 /* stack: [ txn, <Arg:table>, <Reply:table>, "headers", <headers:table> ] */
8121 if (lua_istable(L, 2)) {
8122 /* load headers from the table argument at index 2. If it is a table, copy it. */
8123 ret = lua_getfield(L, 2, "headers");
8124 if (ret == LUA_TTABLE) {
8125 /* stack: [ ... <headers:table>, <table> ] */
8126 lua_pushnil(L);
8127 while (lua_next(L, -2) != 0) {
8128 /* stack: [ ... <headers:table>, <table>, k, v] */
8129 if (!lua_isstring(L, -1) && !lua_istable(L, -1)) {
8130 /* invalid value type, skip it */
8131 lua_pop(L, 1);
8132 continue;
8133 }
8134
8135
8136 /* Duplicate the key and swap it with the value. */
8137 lua_pushvalue(L, -2);
8138 lua_insert(L, -2);
8139 /* stack: [ ... <headers:table>, <table>, k, k, v ] */
8140
8141 lua_newtable(L);
8142 lua_insert(L, -2);
8143 /* stack: [ ... <headers:table>, <table>, k, k, <inner:table>, v ] */
8144
8145 if (lua_isstring(L, -1)) {
8146 /* push the value in the inner table */
8147 lua_rawseti(L, -2, 1);
8148 }
8149 else { /* table */
8150 lua_pushnil(L);
8151 while (lua_next(L, -2) != 0) {
8152 /* stack: [ ... <headers:table>, <table>, k, k, <inner:table>, <v:table>, k2, v2 ] */
8153 if (!lua_isstring(L, -1)) {
8154 /* invalid value type, skip it*/
8155 lua_pop(L, 1);
8156 continue;
8157 }
8158 /* push the value in the inner table */
8159 lua_rawseti(L, -4, lua_rawlen(L, -4) + 1);
8160 /* stack: [ ... <headers:table>, <table>, k, k, <inner:table>, <v:table>, k2 ] */
8161 }
8162 lua_pop(L, 1);
8163 /* stack: [ ... <headers:table>, <table>, k, k, <inner:table> ] */
8164 }
8165
8166 /* push (k,v) on the stack in the headers table:
8167 * stack: [ ... <headers:table>, <table>, k, k, v ]
8168 */
8169 lua_settable(L, -5);
8170 /* stack: [ ... <headers:table>, <table>, k ] */
8171 }
8172 }
8173 lua_pop(L, 1);
8174 }
8175 /* stack: [ txn, <Arg:table>, <Reply:table>, "headers", <headers:table> ] */
8176 lua_settable(L, -3);
8177 /* stack: [ txn, <Arg:table>, <Reply:table> ] */
8178
8179 /* Pop a class sesison metatable and affect it to the userdata. */
8180 lua_rawgeti(L, LUA_REGISTRYINDEX, class_txn_reply_ref);
8181 lua_setmetatable(L, -2);
8182 return 1;
8183}
8184
8185/* Set the reply status code, and optionally the reason. If no reason is
8186 * provided, the default one corresponding to the status code is used.
8187 */
8188__LJMP static int hlua_txn_reply_set_status(lua_State *L)
8189{
8190 int status = MAY_LJMP(luaL_checkinteger(L, 2));
8191 const char *reason = MAY_LJMP(luaL_optlstring(L, 3, NULL, NULL));
8192
8193 /* First argument (self) must be a table */
8194 luaL_checktype(L, 1, LUA_TTABLE);
8195
8196 if (status < 100 || status > 599) {
8197 lua_pushboolean(L, 0);
8198 return 1;
8199 }
8200 if (!reason)
8201 reason = http_get_reason(status);
8202
8203 lua_pushinteger(L, status);
8204 lua_setfield(L, 1, "status");
8205
8206 lua_pushstring(L, reason);
8207 lua_setfield(L, 1, "reason");
8208
8209 lua_pushboolean(L, 1);
8210 return 1;
8211}
8212
8213/* Add a header into the reply object. Each header name is associated to an
8214 * array of values in the "headers" table. If the header name is not found, a
8215 * new entry is created.
8216 */
8217__LJMP static int hlua_txn_reply_add_header(lua_State *L)
8218{
8219 const char *name = MAY_LJMP(luaL_checkstring(L, 2));
8220 const char *value = MAY_LJMP(luaL_checkstring(L, 3));
8221 int ret;
8222
8223 /* First argument (self) must be a table */
8224 luaL_checktype(L, 1, LUA_TTABLE);
8225
8226 /* Push in the stack the "headers" entry. */
8227 ret = lua_getfield(L, 1, "headers");
8228 if (ret != LUA_TTABLE) {
8229 hlua_pusherror(L, "Reply['headers'] is expected to a an array. %s found", lua_typename(L, ret));
8230 WILL_LJMP(lua_error(L));
8231 }
8232
8233 /* check if the header is already registered. If not, register it. */
8234 ret = lua_getfield(L, -1, name);
8235 if (ret == LUA_TNIL) {
8236 /* Entry not found. */
8237 lua_pop(L, 1); /* remove the nil. The "headers" table is the top of the stack. */
8238
8239 /* Insert the new header name in the array in the top of the stack.
8240 * It left the new array in the top of the stack.
8241 */
8242 lua_newtable(L);
8243 lua_pushstring(L, name);
8244 lua_pushvalue(L, -2);
8245 lua_settable(L, -4);
8246 }
8247 else if (ret != LUA_TTABLE) {
8248 hlua_pusherror(L, "Reply['headers']['%s'] is expected to be an array. %s found", name, lua_typename(L, ret));
8249 WILL_LJMP(lua_error(L));
8250 }
8251
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -07008252 /* Now the top of thestack is an array of values. We push
Christopher Faulet700d9e82020-01-31 12:21:52 +01008253 * the header value as new entry.
8254 */
8255 lua_pushstring(L, value);
8256 ret = lua_rawlen(L, -2);
8257 lua_rawseti(L, -2, ret + 1);
8258
8259 lua_pushboolean(L, 1);
8260 return 1;
8261}
8262
8263/* Remove all occurrences of a given header name. */
8264__LJMP static int hlua_txn_reply_del_header(lua_State *L)
8265{
8266 const char *name = MAY_LJMP(luaL_checkstring(L, 2));
8267 int ret;
8268
8269 /* First argument (self) must be a table */
8270 luaL_checktype(L, 1, LUA_TTABLE);
8271
8272 /* Push in the stack the "headers" entry. */
8273 ret = lua_getfield(L, 1, "headers");
8274 if (ret != LUA_TTABLE) {
8275 hlua_pusherror(L, "Reply['headers'] is expected to be an array. %s found", lua_typename(L, ret));
8276 WILL_LJMP(lua_error(L));
8277 }
8278
8279 lua_pushstring(L, name);
8280 lua_pushnil(L);
8281 lua_settable(L, -3);
8282
8283 lua_pushboolean(L, 1);
8284 return 1;
8285}
8286
8287/* Set the reply's body. Overwrite any existing entry. */
8288__LJMP static int hlua_txn_reply_set_body(lua_State *L)
8289{
8290 const char *payload = MAY_LJMP(luaL_checkstring(L, 2));
8291
8292 /* First argument (self) must be a table */
8293 luaL_checktype(L, 1, LUA_TTABLE);
8294
8295 lua_pushstring(L, payload);
8296 lua_setfield(L, 1, "body");
8297
8298 lua_pushboolean(L, 1);
8299 return 1;
8300}
8301
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01008302__LJMP static int hlua_log(lua_State *L)
8303{
8304 int level;
8305 const char *msg;
8306
8307 MAY_LJMP(check_args(L, 2, "log"));
8308 level = MAY_LJMP(luaL_checkinteger(L, 1));
8309 msg = MAY_LJMP(luaL_checkstring(L, 2));
8310
8311 if (level < 0 || level >= NB_LOG_LEVELS)
8312 WILL_LJMP(luaL_argerror(L, 1, "Invalid loglevel."));
8313
8314 hlua_sendlog(NULL, level, msg);
8315 return 0;
8316}
8317
8318__LJMP static int hlua_log_debug(lua_State *L)
8319{
8320 const char *msg;
8321
8322 MAY_LJMP(check_args(L, 1, "debug"));
8323 msg = MAY_LJMP(luaL_checkstring(L, 1));
8324 hlua_sendlog(NULL, LOG_DEBUG, msg);
8325 return 0;
8326}
8327
8328__LJMP static int hlua_log_info(lua_State *L)
8329{
8330 const char *msg;
8331
8332 MAY_LJMP(check_args(L, 1, "info"));
8333 msg = MAY_LJMP(luaL_checkstring(L, 1));
8334 hlua_sendlog(NULL, LOG_INFO, msg);
8335 return 0;
8336}
8337
8338__LJMP static int hlua_log_warning(lua_State *L)
8339{
8340 const char *msg;
8341
8342 MAY_LJMP(check_args(L, 1, "warning"));
8343 msg = MAY_LJMP(luaL_checkstring(L, 1));
8344 hlua_sendlog(NULL, LOG_WARNING, msg);
8345 return 0;
8346}
8347
8348__LJMP static int hlua_log_alert(lua_State *L)
8349{
8350 const char *msg;
8351
8352 MAY_LJMP(check_args(L, 1, "alert"));
8353 msg = MAY_LJMP(luaL_checkstring(L, 1));
8354 hlua_sendlog(NULL, LOG_ALERT, msg);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01008355 return 0;
8356}
8357
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01008358__LJMP static int hlua_sleep_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008359{
8360 int wakeup_ms = lua_tointeger(L, -1);
Willy Tarreau12c02702021-09-30 16:12:31 +02008361 if (!tick_is_expired(wakeup_ms, now_ms))
Willy Tarreau9635e032018-10-16 17:52:55 +02008362 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008363 return 0;
8364}
8365
8366__LJMP static int hlua_sleep(lua_State *L)
8367{
8368 unsigned int delay;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008369 unsigned int wakeup_ms;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008370
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008371 MAY_LJMP(check_args(L, 1, "sleep"));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008372
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01008373 delay = MAY_LJMP(luaL_checkinteger(L, 1)) * 1000;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008374 wakeup_ms = tick_add(now_ms, delay);
8375 lua_pushinteger(L, wakeup_ms);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008376
Willy Tarreau9635e032018-10-16 17:52:55 +02008377 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008378 return 0;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008379}
8380
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008381__LJMP static int hlua_msleep(lua_State *L)
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008382{
8383 unsigned int delay;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008384 unsigned int wakeup_ms;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008385
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008386 MAY_LJMP(check_args(L, 1, "msleep"));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008387
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01008388 delay = MAY_LJMP(luaL_checkinteger(L, 1));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008389 wakeup_ms = tick_add(now_ms, delay);
8390 lua_pushinteger(L, wakeup_ms);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008391
Willy Tarreau9635e032018-10-16 17:52:55 +02008392 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008393 return 0;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008394}
8395
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01008396/* This functionis an LUA binding. it permits to give back
8397 * the hand at the HAProxy scheduler. It is used when the
8398 * LUA processing consumes a lot of time.
8399 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01008400__LJMP static int hlua_yield_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008401{
8402 return 0;
8403}
8404
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01008405__LJMP static int hlua_yield(lua_State *L)
8406{
Willy Tarreau9635e032018-10-16 17:52:55 +02008407 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_yield_yield, TICK_ETERNITY, HLUA_CTRLYIELD));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008408 return 0;
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01008409}
8410
Thierry FOURNIER37196f42015-02-16 19:34:56 +01008411/* This function change the nice of the currently executed
8412 * task. It is used set low or high priority at the current
8413 * task.
8414 */
Willy Tarreau59551662015-03-10 14:23:13 +01008415__LJMP static int hlua_set_nice(lua_State *L)
Thierry FOURNIER37196f42015-02-16 19:34:56 +01008416{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01008417 struct hlua *hlua;
8418 int nice;
Thierry FOURNIER37196f42015-02-16 19:34:56 +01008419
Willy Tarreau80f5fae2015-02-27 16:38:20 +01008420 MAY_LJMP(check_args(L, 1, "set_nice"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01008421 nice = MAY_LJMP(luaL_checkinteger(L, 1));
Thierry FOURNIER37196f42015-02-16 19:34:56 +01008422
Thierry Fournier4234dbd2020-11-28 13:18:23 +01008423 /* Get hlua struct, or NULL if we execute from main lua state */
8424 hlua = hlua_gethlua(L);
8425
8426 /* If the task is not set, I'm in a start mode. */
Thierry FOURNIER37196f42015-02-16 19:34:56 +01008427 if (!hlua || !hlua->task)
8428 return 0;
8429
8430 if (nice < -1024)
8431 nice = -1024;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01008432 else if (nice > 1024)
Thierry FOURNIER37196f42015-02-16 19:34:56 +01008433 nice = 1024;
8434
8435 hlua->task->nice = nice;
8436 return 0;
8437}
8438
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08008439/* This function is used as a callback of a task. It is called by the
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008440 * HAProxy task subsystem when the task is awaked. The LUA runtime can
8441 * return an E_AGAIN signal, the emmiter of this signal must set a
8442 * signal to wake the task.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008443 *
8444 * Task wrapper are longjmp safe because the only one Lua code
8445 * executed is the safe hlua_ctx_resume();
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008446 */
Willy Tarreau144f84a2021-03-02 16:09:26 +01008447struct task *hlua_process_task(struct task *task, void *context, unsigned int state)
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008448{
Olivier Houchard9f6af332018-05-25 14:04:04 +02008449 struct hlua *hlua = context;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008450 enum hlua_exec status;
8451
Christopher Faulet5bc99722018-04-25 10:34:45 +02008452 if (task->thread_mask == MAX_THREADS_MASK)
8453 task_set_affinity(task, tid_bit);
8454
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008455 /* If it is the first call to the task, we must initialize the
8456 * execution timeouts.
8457 */
8458 if (!HLUA_IS_RUNNING(hlua))
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02008459 hlua->max_time = hlua_timeout_task;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008460
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008461 /* Execute the Lua code. */
8462 status = hlua_ctx_resume(hlua, 1);
8463
8464 switch (status) {
8465 /* finished or yield */
8466 case HLUA_E_OK:
8467 hlua_ctx_destroy(hlua);
Olivier Houchard3f795f72019-04-17 22:51:06 +02008468 task_destroy(task);
Tim Duesterhuscd235c62018-04-24 13:56:01 +02008469 task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008470 break;
8471
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01008472 case HLUA_E_AGAIN: /* co process or timeout wake me later. */
Thierry FOURNIERcb146882017-12-10 17:10:57 +01008473 notification_gc(&hlua->com);
PiBa-NLfe971b32018-05-02 22:27:14 +02008474 task->expire = hlua->wake_time;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008475 break;
8476
8477 /* finished with error. */
8478 case HLUA_E_ERRMSG:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008479 SEND_ERR(NULL, "Lua task: %s.\n", lua_tostring(hlua->T, -1));
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008480 hlua_ctx_destroy(hlua);
Olivier Houchard3f795f72019-04-17 22:51:06 +02008481 task_destroy(task);
Emeric Brun253e53e2017-10-17 18:58:40 +02008482 task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008483 break;
8484
8485 case HLUA_E_ERR:
8486 default:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008487 SEND_ERR(NULL, "Lua task: unknown error.\n");
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008488 hlua_ctx_destroy(hlua);
Olivier Houchard3f795f72019-04-17 22:51:06 +02008489 task_destroy(task);
Emeric Brun253e53e2017-10-17 18:58:40 +02008490 task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008491 break;
8492 }
Emeric Brun253e53e2017-10-17 18:58:40 +02008493 return task;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008494}
8495
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008496/* This function is an LUA binding that register LUA function to be
8497 * executed after the HAProxy configuration parsing and before the
8498 * HAProxy scheduler starts. This function expect only one LUA
8499 * argument that is a function. This function returns nothing, but
8500 * throws if an error is encountered.
8501 */
8502__LJMP static int hlua_register_init(lua_State *L)
8503{
8504 struct hlua_init_function *init;
8505 int ref;
8506
8507 MAY_LJMP(check_args(L, 1, "register_init"));
8508
8509 ref = MAY_LJMP(hlua_checkfunction(L, 1));
8510
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02008511 init = calloc(1, sizeof(*init));
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008512 if (!init)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01008513 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008514
8515 init->function_ref = ref;
Willy Tarreau2b718102021-04-21 07:32:39 +02008516 LIST_APPEND(&hlua_init_functions[hlua_state_id], &init->l);
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008517 return 0;
8518}
8519
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008520/* This functio is an LUA binding. It permits to register a task
8521 * executed in parallel of the main HAroxy activity. The task is
8522 * created and it is set in the HAProxy scheduler. It can be called
8523 * from the "init" section, "post init" or during the runtime.
8524 *
8525 * Lua prototype:
8526 *
8527 * <none> core.register_task(<function>)
8528 */
8529static int hlua_register_task(lua_State *L)
8530{
Christopher Faulet5294ec02021-04-12 12:24:47 +02008531 struct hlua *hlua = NULL;
8532 struct task *task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008533 int ref;
Thierry Fournier021d9862020-11-28 23:42:03 +01008534 int state_id;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008535
8536 MAY_LJMP(check_args(L, 1, "register_task"));
8537
8538 ref = MAY_LJMP(hlua_checkfunction(L, 1));
8539
Thierry Fournier75fc0292020-11-28 13:18:56 +01008540 /* Get the reference state. If the reference is NULL, L is the master
8541 * state, otherwise hlua->T is.
8542 */
8543 hlua = hlua_gethlua(L);
8544 if (hlua)
Thierry Fournier021d9862020-11-28 23:42:03 +01008545 /* we are in runtime processing */
8546 state_id = hlua->state_id;
Thierry Fournier75fc0292020-11-28 13:18:56 +01008547 else
Thierry Fournier021d9862020-11-28 23:42:03 +01008548 /* we are in initialization mode */
Thierry Fournierc7492592020-11-28 23:57:24 +01008549 state_id = hlua_state_id;
Thierry Fournier75fc0292020-11-28 13:18:56 +01008550
Willy Tarreaubafbe012017-11-24 17:34:44 +01008551 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008552 if (!hlua)
Christopher Faulet5294ec02021-04-12 12:24:47 +02008553 goto alloc_error;
Christopher Faulet1e8433f2021-03-24 15:03:01 +01008554 HLUA_INIT(hlua);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008555
Thierry Fournier59f11be2020-11-29 00:37:41 +01008556 /* We are in the common lua state, execute the task anywhere,
8557 * otherwise, inherit the current thread identifier
8558 */
8559 if (state_id == 0)
Willy Tarreaubeeabf52021-10-01 18:23:30 +02008560 task = task_new_anywhere();
Thierry Fournier59f11be2020-11-29 00:37:41 +01008561 else
Willy Tarreaubeeabf52021-10-01 18:23:30 +02008562 task = task_new_here();
Willy Tarreaue09101e2018-10-16 17:37:12 +02008563 if (!task)
Christopher Faulet5294ec02021-04-12 12:24:47 +02008564 goto alloc_error;
Willy Tarreaue09101e2018-10-16 17:37:12 +02008565
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008566 task->context = hlua;
8567 task->process = hlua_process_task;
8568
Thierry Fournier021d9862020-11-28 23:42:03 +01008569 if (!hlua_ctx_init(hlua, state_id, task, 1))
Christopher Faulet5294ec02021-04-12 12:24:47 +02008570 goto alloc_error;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008571
8572 /* Restore the function in the stack. */
8573 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ref);
8574 hlua->nargs = 0;
8575
8576 /* Schedule task. */
Willy Tarreaue3957f82021-09-30 16:17:37 +02008577 task_wakeup(task, TASK_WOKEN_INIT);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008578
8579 return 0;
Christopher Faulet5294ec02021-04-12 12:24:47 +02008580
8581 alloc_error:
8582 task_destroy(task);
8583 hlua_ctx_destroy(hlua);
8584 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
8585 return 0; /* Never reached */
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008586}
8587
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008588/* Wrapper called by HAProxy to execute an LUA converter. This wrapper
8589 * doesn't allow "yield" functions because the HAProxy engine cannot
8590 * resume converters.
8591 */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02008592static int hlua_sample_conv_wrapper(const struct arg *arg_p, struct sample *smp, void *private)
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008593{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02008594 struct hlua_function *fcn = private;
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02008595 struct stream *stream = smp->strm;
Thierry Fournierfd107a22016-02-19 19:57:23 +01008596 const char *error;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008597
Willy Tarreaube508f12016-03-10 11:47:01 +01008598 if (!stream)
8599 return 0;
8600
Willy Tarreau87b09662015-04-03 00:22:06 +02008601 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01008602 * Lua context can be not initialized. This behavior
8603 * permits to save performances because a systematic
8604 * Lua initialization cause 5% performances loss.
8605 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008606 if (!stream->hlua) {
Christopher Faulet1e8433f2021-03-24 15:03:01 +01008607 struct hlua *hlua;
8608
8609 hlua = pool_alloc(pool_head_hlua);
8610 if (!hlua) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008611 SEND_ERR(stream->be, "Lua converter '%s': can't initialize Lua context.\n", fcn->name);
8612 return 0;
8613 }
Christopher Faulet1e8433f2021-03-24 15:03:01 +01008614 HLUA_INIT(hlua);
8615 stream->hlua = hlua;
Thierry Fournierc7492592020-11-28 23:57:24 +01008616 if (!hlua_ctx_init(stream->hlua, fcn_ref_to_stack_id(fcn), stream->task, 0)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008617 SEND_ERR(stream->be, "Lua converter '%s': can't initialize Lua context.\n", fcn->name);
8618 return 0;
8619 }
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01008620 }
8621
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008622 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008623 if (!HLUA_IS_RUNNING(stream->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008624
8625 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008626 if (!SET_SAFE_LJMP(stream->hlua)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008627 if (lua_type(stream->hlua->T, -1) == LUA_TSTRING)
8628 error = lua_tostring(stream->hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +01008629 else
8630 error = "critical error";
8631 SEND_ERR(stream->be, "Lua converter '%s': %s.\n", fcn->name, error);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008632 return 0;
8633 }
8634
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008635 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008636 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008637 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008638 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008639 return 0;
8640 }
8641
8642 /* Restore the function in the stack. */
Thierry Fournierc7492592020-11-28 23:57:24 +01008643 lua_rawgeti(stream->hlua->T, LUA_REGISTRYINDEX, fcn->function_ref[stream->hlua->state_id]);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008644
8645 /* convert input sample and pust-it in the stack. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008646 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008647 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008648 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008649 return 0;
8650 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008651 hlua_smp2lua(stream->hlua->T, smp);
8652 stream->hlua->nargs = 1;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008653
8654 /* push keywords in the stack. */
8655 if (arg_p) {
8656 for (; arg_p->type != ARGT_STOP; arg_p++) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008657 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008658 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008659 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008660 return 0;
8661 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008662 hlua_arg2lua(stream->hlua->T, arg_p);
8663 stream->hlua->nargs++;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008664 }
8665 }
8666
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008667 /* We must initialize the execution timeouts. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008668 stream->hlua->max_time = hlua_timeout_session;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008669
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008670 /* At this point the execution is safe. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008671 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008672 }
8673
8674 /* Execute the function. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008675 switch (hlua_ctx_resume(stream->hlua, 0)) {
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008676 /* finished. */
8677 case HLUA_E_OK:
Thierry FOURNIERfd80df12017-05-12 16:32:20 +02008678 /* If the stack is empty, the function fails. */
8679 if (lua_gettop(stream->hlua->T) <= 0)
8680 return 0;
8681
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008682 /* Convert the returned value in sample. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008683 hlua_lua2smp(stream->hlua->T, -1, smp);
8684 lua_pop(stream->hlua->T, 1);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008685 return 1;
8686
8687 /* yield. */
8688 case HLUA_E_AGAIN:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008689 SEND_ERR(stream->be, "Lua converter '%s': cannot use yielded functions.\n", fcn->name);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008690 return 0;
8691
8692 /* finished with error. */
8693 case HLUA_E_ERRMSG:
8694 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008695 SEND_ERR(stream->be, "Lua converter '%s': %s.\n",
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008696 fcn->name, lua_tostring(stream->hlua->T, -1));
8697 lua_pop(stream->hlua->T, 1);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008698 return 0;
8699
Thierry Fournierd5b073c2018-05-21 19:42:47 +02008700 case HLUA_E_ETMOUT:
8701 SEND_ERR(stream->be, "Lua converter '%s': execution timeout.\n", fcn->name);
8702 return 0;
8703
8704 case HLUA_E_NOMEM:
8705 SEND_ERR(stream->be, "Lua converter '%s': out of memory error.\n", fcn->name);
8706 return 0;
8707
8708 case HLUA_E_YIELD:
8709 SEND_ERR(stream->be, "Lua converter '%s': yield functions like core.tcp() or core.sleep() are not allowed.\n", fcn->name);
8710 return 0;
8711
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008712 case HLUA_E_ERR:
8713 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008714 SEND_ERR(stream->be, "Lua converter '%s' returns an unknown error.\n", fcn->name);
Tim Duesterhus588b3142020-05-29 14:35:51 +02008715 /* fall through */
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008716
8717 default:
8718 return 0;
8719 }
8720}
8721
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008722/* Wrapper called by HAProxy to execute a sample-fetch. this wrapper
8723 * doesn't allow "yield" functions because the HAProxy engine cannot
Willy Tarreaube508f12016-03-10 11:47:01 +01008724 * resume sample-fetches. This function will be called by the sample
8725 * fetch engine to call lua-based fetch operations.
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008726 */
Thierry FOURNIER0786d052015-05-11 15:42:45 +02008727static int hlua_sample_fetch_wrapper(const struct arg *arg_p, struct sample *smp,
8728 const char *kw, void *private)
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008729{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02008730 struct hlua_function *fcn = private;
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02008731 struct stream *stream = smp->strm;
Thierry Fournierfd107a22016-02-19 19:57:23 +01008732 const char *error;
Christopher Faulet8c9e6bb2021-08-06 16:29:41 +02008733 unsigned int hflags = HLUA_TXN_NOTERM | HLUA_TXN_SMP_CTX;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008734
Willy Tarreaube508f12016-03-10 11:47:01 +01008735 if (!stream)
8736 return 0;
Christopher Fauletafd8f102018-11-08 11:34:21 +01008737
Willy Tarreau87b09662015-04-03 00:22:06 +02008738 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01008739 * Lua context can be not initialized. This behavior
8740 * permits to save performances because a systematic
8741 * Lua initialization cause 5% performances loss.
8742 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008743 if (!stream->hlua) {
Christopher Faulet1e8433f2021-03-24 15:03:01 +01008744 struct hlua *hlua;
8745
8746 hlua = pool_alloc(pool_head_hlua);
8747 if (!hlua) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008748 SEND_ERR(stream->be, "Lua sample-fetch '%s': can't initialize Lua context.\n", fcn->name);
8749 return 0;
8750 }
Christopher Faulet1e8433f2021-03-24 15:03:01 +01008751 hlua->T = NULL;
8752 stream->hlua = hlua;
Thierry Fournierc7492592020-11-28 23:57:24 +01008753 if (!hlua_ctx_init(stream->hlua, fcn_ref_to_stack_id(fcn), stream->task, 0)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008754 SEND_ERR(stream->be, "Lua sample-fetch '%s': can't initialize Lua context.\n", fcn->name);
8755 return 0;
8756 }
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01008757 }
8758
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008759 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008760 if (!HLUA_IS_RUNNING(stream->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008761
8762 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008763 if (!SET_SAFE_LJMP(stream->hlua)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008764 if (lua_type(stream->hlua->T, -1) == LUA_TSTRING)
8765 error = lua_tostring(stream->hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +01008766 else
8767 error = "critical error";
8768 SEND_ERR(smp->px, "Lua sample-fetch '%s': %s.\n", fcn->name, error);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008769 return 0;
8770 }
8771
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008772 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008773 if (!lua_checkstack(stream->hlua->T, 2)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008774 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008775 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008776 return 0;
8777 }
8778
8779 /* Restore the function in the stack. */
Thierry Fournierc7492592020-11-28 23:57:24 +01008780 lua_rawgeti(stream->hlua->T, LUA_REGISTRYINDEX, fcn->function_ref[stream->hlua->state_id]);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008781
8782 /* push arguments in the stack. */
Christopher Fauletbfab2dd2019-07-26 15:09:53 +02008783 if (!hlua_txn_new(stream->hlua->T, stream, smp->px, smp->opt & SMP_OPT_DIR, hflags)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008784 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008785 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008786 return 0;
8787 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008788 stream->hlua->nargs = 1;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008789
8790 /* push keywords in the stack. */
8791 for (; arg_p && arg_p->type != ARGT_STOP; arg_p++) {
8792 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008793 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008794 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008795 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008796 return 0;
8797 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008798 hlua_arg2lua(stream->hlua->T, arg_p);
8799 stream->hlua->nargs++;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008800 }
8801
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008802 /* We must initialize the execution timeouts. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008803 stream->hlua->max_time = hlua_timeout_session;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008804
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008805 /* At this point the execution is safe. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008806 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008807 }
8808
8809 /* Execute the function. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008810 switch (hlua_ctx_resume(stream->hlua, 0)) {
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008811 /* finished. */
8812 case HLUA_E_OK:
Thierry FOURNIERfd80df12017-05-12 16:32:20 +02008813 /* If the stack is empty, the function fails. */
8814 if (lua_gettop(stream->hlua->T) <= 0)
8815 return 0;
8816
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008817 /* Convert the returned value in sample. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008818 hlua_lua2smp(stream->hlua->T, -1, smp);
8819 lua_pop(stream->hlua->T, 1);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008820
8821 /* Set the end of execution flag. */
8822 smp->flags &= ~SMP_F_MAY_CHANGE;
8823 return 1;
8824
8825 /* yield. */
8826 case HLUA_E_AGAIN:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008827 SEND_ERR(smp->px, "Lua sample-fetch '%s': cannot use yielded functions.\n", fcn->name);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008828 return 0;
8829
8830 /* finished with error. */
8831 case HLUA_E_ERRMSG:
8832 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008833 SEND_ERR(smp->px, "Lua sample-fetch '%s': %s.\n",
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008834 fcn->name, lua_tostring(stream->hlua->T, -1));
8835 lua_pop(stream->hlua->T, 1);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008836 return 0;
8837
Thierry Fournierd5b073c2018-05-21 19:42:47 +02008838 case HLUA_E_ETMOUT:
Thierry Fournierd5b073c2018-05-21 19:42:47 +02008839 SEND_ERR(smp->px, "Lua sample-fetch '%s': execution timeout.\n", fcn->name);
8840 return 0;
8841
8842 case HLUA_E_NOMEM:
Thierry Fournierd5b073c2018-05-21 19:42:47 +02008843 SEND_ERR(smp->px, "Lua sample-fetch '%s': out of memory error.\n", fcn->name);
8844 return 0;
8845
8846 case HLUA_E_YIELD:
Thierry Fournierd5b073c2018-05-21 19:42:47 +02008847 SEND_ERR(smp->px, "Lua sample-fetch '%s': yield not allowed.\n", fcn->name);
8848 return 0;
8849
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008850 case HLUA_E_ERR:
8851 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008852 SEND_ERR(smp->px, "Lua sample-fetch '%s' returns an unknown error.\n", fcn->name);
Tim Duesterhus588b3142020-05-29 14:35:51 +02008853 /* fall through */
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008854
8855 default:
8856 return 0;
8857 }
8858}
8859
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008860/* This function is an LUA binding used for registering
8861 * "sample-conv" functions. It expects a converter name used
8862 * in the haproxy configuration file, and an LUA function.
8863 */
8864__LJMP static int hlua_register_converters(lua_State *L)
8865{
8866 struct sample_conv_kw_list *sck;
8867 const char *name;
8868 int ref;
8869 int len;
Christopher Fauletaa224302021-04-12 14:08:21 +02008870 struct hlua_function *fcn = NULL;
Thierry Fournierf67442e2020-11-28 20:41:07 +01008871 struct sample_conv *sc;
8872 struct buffer *trash;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008873
8874 MAY_LJMP(check_args(L, 2, "register_converters"));
8875
8876 /* First argument : converter name. */
8877 name = MAY_LJMP(luaL_checkstring(L, 1));
8878
8879 /* Second argument : lua function. */
8880 ref = MAY_LJMP(hlua_checkfunction(L, 2));
8881
Thierry Fournierf67442e2020-11-28 20:41:07 +01008882 /* Check if the converter is already registered */
8883 trash = get_trash_chunk();
8884 chunk_printf(trash, "lua.%s", name);
8885 sc = find_sample_conv(trash->area, trash->data);
8886 if (sc != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +01008887 fcn = sc->private;
8888 if (fcn->function_ref[hlua_state_id] != -1) {
8889 ha_warning("Trying to register converter 'lua.%s' more than once. "
8890 "This will become a hard error in version 2.5.\n", name);
8891 }
8892 fcn->function_ref[hlua_state_id] = ref;
8893 return 0;
Thierry Fournierf67442e2020-11-28 20:41:07 +01008894 }
8895
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008896 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02008897 sck = calloc(1, sizeof(*sck) + sizeof(struct sample_conv) * 2);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008898 if (!sck)
Christopher Fauletaa224302021-04-12 14:08:21 +02008899 goto alloc_error;
Thierry Fournier62a22aa2020-11-28 21:06:35 +01008900 fcn = new_hlua_function();
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008901 if (!fcn)
Christopher Fauletaa224302021-04-12 14:08:21 +02008902 goto alloc_error;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008903
8904 /* Fill fcn. */
8905 fcn->name = strdup(name);
8906 if (!fcn->name)
Christopher Fauletaa224302021-04-12 14:08:21 +02008907 goto alloc_error;
Thierry Fournierc7492592020-11-28 23:57:24 +01008908 fcn->function_ref[hlua_state_id] = ref;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008909
8910 /* List head */
8911 sck->list.n = sck->list.p = NULL;
8912
8913 /* converter keyword. */
8914 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02008915 sck->kw[0].kw = calloc(1, len);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008916 if (!sck->kw[0].kw)
Christopher Fauletaa224302021-04-12 14:08:21 +02008917 goto alloc_error;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008918
8919 snprintf((char *)sck->kw[0].kw, len, "lua.%s", name);
8920 sck->kw[0].process = hlua_sample_conv_wrapper;
David Carlier0c437f42016-04-27 16:21:56 +01008921 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 +01008922 sck->kw[0].val_args = NULL;
8923 sck->kw[0].in_type = SMP_T_STR;
8924 sck->kw[0].out_type = SMP_T_STR;
8925 sck->kw[0].private = fcn;
8926
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008927 /* Register this new converter */
8928 sample_register_convs(sck);
8929
8930 return 0;
Christopher Fauletaa224302021-04-12 14:08:21 +02008931
8932 alloc_error:
8933 release_hlua_function(fcn);
8934 ha_free(&sck);
8935 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
8936 return 0; /* Never reached */
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008937}
8938
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08008939/* This function is an LUA binding used for registering
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008940 * "sample-fetch" functions. It expects a converter name used
8941 * in the haproxy configuration file, and an LUA function.
8942 */
8943__LJMP static int hlua_register_fetches(lua_State *L)
8944{
8945 const char *name;
8946 int ref;
8947 int len;
8948 struct sample_fetch_kw_list *sfk;
Christopher Faulet2567f182021-04-12 14:11:50 +02008949 struct hlua_function *fcn = NULL;
Thierry Fournierf67442e2020-11-28 20:41:07 +01008950 struct sample_fetch *sf;
8951 struct buffer *trash;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008952
8953 MAY_LJMP(check_args(L, 2, "register_fetches"));
8954
8955 /* First argument : sample-fetch name. */
8956 name = MAY_LJMP(luaL_checkstring(L, 1));
8957
8958 /* Second argument : lua function. */
8959 ref = MAY_LJMP(hlua_checkfunction(L, 2));
8960
Thierry Fournierf67442e2020-11-28 20:41:07 +01008961 /* Check if the sample-fetch is already registered */
8962 trash = get_trash_chunk();
8963 chunk_printf(trash, "lua.%s", name);
8964 sf = find_sample_fetch(trash->area, trash->data);
8965 if (sf != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +01008966 fcn = sf->private;
8967 if (fcn->function_ref[hlua_state_id] != -1) {
8968 ha_warning("Trying to register sample-fetch 'lua.%s' more than once. "
8969 "This will become a hard error in version 2.5.\n", name);
8970 }
8971 fcn->function_ref[hlua_state_id] = ref;
8972 return 0;
Thierry Fournierf67442e2020-11-28 20:41:07 +01008973 }
8974
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008975 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02008976 sfk = calloc(1, sizeof(*sfk) + sizeof(struct sample_fetch) * 2);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008977 if (!sfk)
Christopher Faulet2567f182021-04-12 14:11:50 +02008978 goto alloc_error;
Thierry Fournier62a22aa2020-11-28 21:06:35 +01008979 fcn = new_hlua_function();
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008980 if (!fcn)
Christopher Faulet2567f182021-04-12 14:11:50 +02008981 goto alloc_error;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008982
8983 /* Fill fcn. */
8984 fcn->name = strdup(name);
8985 if (!fcn->name)
Christopher Faulet2567f182021-04-12 14:11:50 +02008986 goto alloc_error;
Thierry Fournierc7492592020-11-28 23:57:24 +01008987 fcn->function_ref[hlua_state_id] = ref;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008988
8989 /* List head */
8990 sfk->list.n = sfk->list.p = NULL;
8991
8992 /* sample-fetch keyword. */
8993 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02008994 sfk->kw[0].kw = calloc(1, len);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008995 if (!sfk->kw[0].kw)
Christopher Faulet2567f182021-04-12 14:11:50 +02008996 goto alloc_error;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008997
8998 snprintf((char *)sfk->kw[0].kw, len, "lua.%s", name);
8999 sfk->kw[0].process = hlua_sample_fetch_wrapper;
David Carlier0c437f42016-04-27 16:21:56 +01009000 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 +01009001 sfk->kw[0].val_args = NULL;
9002 sfk->kw[0].out_type = SMP_T_STR;
9003 sfk->kw[0].use = SMP_USE_HTTP_ANY;
9004 sfk->kw[0].val = 0;
9005 sfk->kw[0].private = fcn;
9006
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009007 /* Register this new fetch. */
9008 sample_register_fetches(sfk);
9009
9010 return 0;
Christopher Faulet2567f182021-04-12 14:11:50 +02009011
9012 alloc_error:
9013 release_hlua_function(fcn);
9014 ha_free(&sfk);
9015 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
9016 return 0; /* Never reached */
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009017}
9018
Christopher Faulet501465d2020-02-26 14:54:16 +01009019/* This function is a lua binding to set the wake_time.
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01009020 */
Christopher Faulet501465d2020-02-26 14:54:16 +01009021__LJMP static int hlua_set_wake_time(lua_State *L)
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01009022{
Thierry Fournier4234dbd2020-11-28 13:18:23 +01009023 struct hlua *hlua;
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01009024 unsigned int delay;
9025 unsigned int wakeup_ms;
9026
Thierry Fournier4234dbd2020-11-28 13:18:23 +01009027 /* Get hlua struct, or NULL if we execute from main lua state */
9028 hlua = hlua_gethlua(L);
9029 if (!hlua) {
9030 return 0;
9031 }
9032
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01009033 MAY_LJMP(check_args(L, 1, "wake_time"));
9034
9035 delay = MAY_LJMP(luaL_checkinteger(L, 1));
9036 wakeup_ms = tick_add(now_ms, delay);
9037 hlua->wake_time = wakeup_ms;
9038 return 0;
9039}
9040
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009041/* This function is a wrapper to execute each LUA function declared as an action
9042 * wrapper during the initialisation period. This function may return any
9043 * ACT_RET_* value. On error ACT_RET_CONT is returned and the action is
9044 * ignored. If the lua action yields, ACT_RET_YIELD is returned. On success, the
9045 * return value is the first element on the stack.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009046 */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009047static enum act_return hlua_action(struct act_rule *rule, struct proxy *px,
Willy Tarreau658b85b2015-09-27 10:00:49 +02009048 struct session *sess, struct stream *s, int flags)
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009049{
9050 char **arg;
Christopher Faulet8c9e6bb2021-08-06 16:29:41 +02009051 unsigned int hflags = HLUA_TXN_ACT_CTX;
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009052 int dir, act_ret = ACT_RET_CONT;
Thierry Fournierfd107a22016-02-19 19:57:23 +01009053 const char *error;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009054
9055 switch (rule->from) {
Christopher Fauletd8f0e072020-02-25 09:45:51 +01009056 case ACT_F_TCP_REQ_CNT: dir = SMP_OPT_DIR_REQ; break;
9057 case ACT_F_TCP_RES_CNT: dir = SMP_OPT_DIR_RES; break;
9058 case ACT_F_HTTP_REQ: dir = SMP_OPT_DIR_REQ; break;
9059 case ACT_F_HTTP_RES: dir = SMP_OPT_DIR_RES; break;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009060 default:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009061 SEND_ERR(px, "Lua: internal error while execute action.\n");
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009062 goto end;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009063 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009064
Willy Tarreau87b09662015-04-03 00:22:06 +02009065 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01009066 * Lua context can be not initialized. This behavior
9067 * permits to save performances because a systematic
9068 * Lua initialization cause 5% performances loss.
9069 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009070 if (!s->hlua) {
Christopher Faulet1e8433f2021-03-24 15:03:01 +01009071 struct hlua *hlua;
9072
9073 hlua = pool_alloc(pool_head_hlua);
9074 if (!hlua) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009075 SEND_ERR(px, "Lua action '%s': can't initialize Lua context.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009076 rule->arg.hlua_rule->fcn->name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009077 goto end;
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009078 }
Christopher Faulet1e8433f2021-03-24 15:03:01 +01009079 HLUA_INIT(hlua);
9080 s->hlua = hlua;
Thierry Fournierc7492592020-11-28 23:57:24 +01009081 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 +01009082 SEND_ERR(px, "Lua action '%s': can't initialize Lua context.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009083 rule->arg.hlua_rule->fcn->name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009084 goto end;
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009085 }
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01009086 }
9087
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009088 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009089 if (!HLUA_IS_RUNNING(s->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02009090
9091 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009092 if (!SET_SAFE_LJMP(s->hlua)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009093 if (lua_type(s->hlua->T, -1) == LUA_TSTRING)
9094 error = lua_tostring(s->hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +01009095 else
9096 error = "critical error";
9097 SEND_ERR(px, "Lua function '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009098 rule->arg.hlua_rule->fcn->name, error);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009099 goto end;
Thierry FOURNIERbabae282015-09-17 11:36:37 +02009100 }
9101
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009102 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009103 if (!lua_checkstack(s->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009104 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009105 rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009106 RESET_SAFE_LJMP(s->hlua);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009107 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009108 }
9109
9110 /* Restore the function in the stack. */
Thierry Fournierc7492592020-11-28 23:57:24 +01009111 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 +01009112
Willy Tarreau87b09662015-04-03 00:22:06 +02009113 /* Create and and push object stream in the stack. */
Christopher Fauletbfab2dd2019-07-26 15:09:53 +02009114 if (!hlua_txn_new(s->hlua->T, s, px, dir, hflags)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009115 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009116 rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009117 RESET_SAFE_LJMP(s->hlua);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009118 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009119 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009120 s->hlua->nargs = 1;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009121
9122 /* push keywords in the stack. */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009123 for (arg = rule->arg.hlua_rule->args; arg && *arg; arg++) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009124 if (!lua_checkstack(s->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009125 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009126 rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009127 RESET_SAFE_LJMP(s->hlua);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009128 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009129 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009130 lua_pushstring(s->hlua->T, *arg);
9131 s->hlua->nargs++;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009132 }
9133
Thierry FOURNIERbabae282015-09-17 11:36:37 +02009134 /* Now the execution is safe. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009135 RESET_SAFE_LJMP(s->hlua);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02009136
Thierry FOURNIERbd413492015-03-03 16:52:26 +01009137 /* We must initialize the execution timeouts. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009138 s->hlua->max_time = hlua_timeout_session;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009139 }
9140
9141 /* Execute the function. */
Christopher Faulet105ba6c2019-12-18 14:41:51 +01009142 switch (hlua_ctx_resume(s->hlua, !(flags & ACT_OPT_FINAL))) {
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009143 /* finished. */
9144 case HLUA_E_OK:
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009145 /* Catch the return value */
9146 if (lua_gettop(s->hlua->T) > 0)
9147 act_ret = lua_tointeger(s->hlua->T, -1);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009148
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01009149 /* Set timeout in the required channel. */
Christopher Faulet498c4832020-07-28 11:59:58 +02009150 if (act_ret == ACT_RET_YIELD) {
9151 if (flags & ACT_OPT_FINAL)
9152 goto err_yield;
9153
Christopher Faulet8f587ea2020-07-28 12:01:55 +02009154 if (dir == SMP_OPT_DIR_REQ)
9155 s->req.analyse_exp = tick_first((tick_is_expired(s->req.analyse_exp, now_ms) ? 0 : s->req.analyse_exp),
9156 s->hlua->wake_time);
9157 else
9158 s->res.analyse_exp = tick_first((tick_is_expired(s->res.analyse_exp, now_ms) ? 0 : s->res.analyse_exp),
9159 s->hlua->wake_time);
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01009160 }
9161 goto end;
9162
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009163 /* yield. */
9164 case HLUA_E_AGAIN:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01009165 /* Set timeout in the required channel. */
Christopher Faulet8f587ea2020-07-28 12:01:55 +02009166 if (dir == SMP_OPT_DIR_REQ)
9167 s->req.analyse_exp = tick_first((tick_is_expired(s->req.analyse_exp, now_ms) ? 0 : s->req.analyse_exp),
9168 s->hlua->wake_time);
9169 else
9170 s->res.analyse_exp = tick_first((tick_is_expired(s->res.analyse_exp, now_ms) ? 0 : s->res.analyse_exp),
9171 s->hlua->wake_time);
9172
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009173 /* Some actions can be wake up when a "write" event
9174 * is detected on a response channel. This is useful
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08009175 * only for actions targeted on the requests.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009176 */
Christopher Faulet51fa3582019-07-26 14:54:52 +02009177 if (HLUA_IS_WAKERESWR(s->hlua))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01009178 s->res.flags |= CF_WAKE_WRITE;
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009179 if (HLUA_IS_WAKEREQWR(s->hlua))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01009180 s->req.flags |= CF_WAKE_WRITE;
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009181 act_ret = ACT_RET_YIELD;
9182 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009183
9184 /* finished with error. */
9185 case HLUA_E_ERRMSG:
9186 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009187 SEND_ERR(px, "Lua function '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009188 rule->arg.hlua_rule->fcn->name, lua_tostring(s->hlua->T, -1));
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009189 lua_pop(s->hlua->T, 1);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009190 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009191
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009192 case HLUA_E_ETMOUT:
Thierry Fournierad5345f2020-11-29 02:05:57 +01009193 SEND_ERR(px, "Lua function '%s': execution timeout.\n", rule->arg.hlua_rule->fcn->name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009194 goto end;
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009195
9196 case HLUA_E_NOMEM:
Thierry Fournierad5345f2020-11-29 02:05:57 +01009197 SEND_ERR(px, "Lua function '%s': out of memory error.\n", rule->arg.hlua_rule->fcn->name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009198 goto end;
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009199
9200 case HLUA_E_YIELD:
Christopher Faulet498c4832020-07-28 11:59:58 +02009201 err_yield:
9202 act_ret = ACT_RET_CONT;
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009203 SEND_ERR(px, "Lua function '%s': aborting Lua processing on expired timeout.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009204 rule->arg.hlua_rule->fcn->name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009205 goto end;
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009206
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009207 case HLUA_E_ERR:
9208 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009209 SEND_ERR(px, "Lua function '%s' return an unknown error.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009210 rule->arg.hlua_rule->fcn->name);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009211
9212 default:
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009213 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009214 }
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009215
9216 end:
Christopher Faulet2361fd92020-07-30 10:40:58 +02009217 if (act_ret != ACT_RET_YIELD && s->hlua)
Christopher Faulet8f587ea2020-07-28 12:01:55 +02009218 s->hlua->wake_time = TICK_ETERNITY;
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009219 return act_ret;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009220}
9221
Willy Tarreau144f84a2021-03-02 16:09:26 +01009222struct task *hlua_applet_wakeup(struct task *t, void *context, unsigned int state)
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009223{
Olivier Houchard9f6af332018-05-25 14:04:04 +02009224 struct appctx *ctx = context;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009225
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009226 appctx_wakeup(ctx);
Willy Tarreaud9587412017-08-23 16:07:33 +02009227 t->expire = TICK_ETERNITY;
Willy Tarreaud1aa41f2017-07-21 16:41:56 +02009228 return t;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009229}
9230
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009231static int hlua_applet_tcp_init(struct appctx *ctx)
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009232{
Willy Tarreaue23f33b2022-05-06 14:07:13 +02009233 struct hlua_tcp_ctx *tcp_ctx = applet_reserve_svcctx(ctx, sizeof(*tcp_ctx));
Christopher Faulet908628c2022-03-25 16:43:49 +01009234 struct conn_stream *cs = ctx->owner;
9235 struct stream *strm = __cs_strm(cs);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009236 struct hlua *hlua;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009237 struct task *task;
9238 char **arg;
Thierry Fournierfd107a22016-02-19 19:57:23 +01009239 const char *error;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009240
Willy Tarreaubafbe012017-11-24 17:34:44 +01009241 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009242 if (!hlua) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009243 SEND_ERR(strm->be, "Lua applet tcp '%s': out of memory.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009244 ctx->rule->arg.hlua_rule->fcn->name);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009245 return 0;
9246 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009247 HLUA_INIT(hlua);
Willy Tarreaue23f33b2022-05-06 14:07:13 +02009248 tcp_ctx->hlua = hlua;
9249 tcp_ctx->flags = 0;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009250
9251 /* Create task used by signal to wakeup applets. */
Willy Tarreaubeeabf52021-10-01 18:23:30 +02009252 task = task_new_here();
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009253 if (!task) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009254 SEND_ERR(strm->be, "Lua applet tcp '%s': out of memory.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009255 ctx->rule->arg.hlua_rule->fcn->name);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009256 return 0;
9257 }
9258 task->nice = 0;
9259 task->context = ctx;
9260 task->process = hlua_applet_wakeup;
Willy Tarreaue23f33b2022-05-06 14:07:13 +02009261 tcp_ctx->task = task;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009262
9263 /* In the execution wrappers linked with a stream, the
9264 * Lua context can be not initialized. This behavior
9265 * permits to save performances because a systematic
9266 * Lua initialization cause 5% performances loss.
9267 */
Thierry Fournierc7492592020-11-28 23:57:24 +01009268 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 +01009269 SEND_ERR(strm->be, "Lua applet tcp '%s': can't initialize Lua context.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009270 ctx->rule->arg.hlua_rule->fcn->name);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009271 return 0;
9272 }
9273
9274 /* Set timeout according with the applet configuration. */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02009275 hlua->max_time = ctx->applet->timeout;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009276
9277 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009278 if (!SET_SAFE_LJMP(hlua)) {
Thierry Fournierfd107a22016-02-19 19:57:23 +01009279 if (lua_type(hlua->T, -1) == LUA_TSTRING)
9280 error = lua_tostring(hlua->T, -1);
9281 else
9282 error = "critical error";
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009283 SEND_ERR(strm->be, "Lua applet tcp '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009284 ctx->rule->arg.hlua_rule->fcn->name, error);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009285 return 0;
9286 }
9287
9288 /* Check stack available size. */
9289 if (!lua_checkstack(hlua->T, 1)) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009290 SEND_ERR(strm->be, "Lua applet tcp '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009291 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009292 RESET_SAFE_LJMP(hlua);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009293 return 0;
9294 }
9295
9296 /* Restore the function in the stack. */
Thierry Fournierc7492592020-11-28 23:57:24 +01009297 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ctx->rule->arg.hlua_rule->fcn->function_ref[hlua->state_id]);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009298
9299 /* Create and and push object stream in the stack. */
9300 if (!hlua_applet_tcp_new(hlua->T, ctx)) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009301 SEND_ERR(strm->be, "Lua applet tcp '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009302 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009303 RESET_SAFE_LJMP(hlua);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009304 return 0;
9305 }
9306 hlua->nargs = 1;
9307
9308 /* push keywords in the stack. */
9309 for (arg = ctx->rule->arg.hlua_rule->args; arg && *arg; arg++) {
9310 if (!lua_checkstack(hlua->T, 1)) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009311 SEND_ERR(strm->be, "Lua applet tcp '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009312 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009313 RESET_SAFE_LJMP(hlua);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009314 return 0;
9315 }
9316 lua_pushstring(hlua->T, *arg);
9317 hlua->nargs++;
9318 }
9319
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009320 RESET_SAFE_LJMP(hlua);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009321
9322 /* Wakeup the applet ASAP. */
Christopher Fauleta0bdec32022-04-04 07:51:21 +02009323 cs_cant_get(cs);
9324 cs_rx_endp_more(cs);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009325
9326 return 1;
9327}
9328
Willy Tarreau60409db2019-08-21 14:14:50 +02009329void hlua_applet_tcp_fct(struct appctx *ctx)
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009330{
Willy Tarreaue23f33b2022-05-06 14:07:13 +02009331 struct hlua_tcp_ctx *tcp_ctx = ctx->svcctx;
Christopher Faulet908628c2022-03-25 16:43:49 +01009332 struct conn_stream *cs = ctx->owner;
9333 struct stream *strm = __cs_strm(cs);
9334 struct channel *res = cs_ic(cs);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009335 struct act_rule *rule = ctx->rule;
9336 struct proxy *px = strm->be;
Willy Tarreaue23f33b2022-05-06 14:07:13 +02009337 struct hlua *hlua = tcp_ctx->hlua;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009338
9339 /* The applet execution is already done. */
Willy Tarreaue23f33b2022-05-06 14:07:13 +02009340 if (tcp_ctx->flags & APPLET_DONE) {
Olivier Houchard594c8c52018-08-28 14:41:31 +02009341 /* eat the whole request */
Christopher Faulet908628c2022-03-25 16:43:49 +01009342 co_skip(cs_oc(cs), co_data(cs_oc(cs)));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009343 return;
Olivier Houchard594c8c52018-08-28 14:41:31 +02009344 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009345
9346 /* If the stream is disconnect or closed, ldo nothing. */
Christopher Faulet62e75742022-03-31 09:16:34 +02009347 if (unlikely(cs->state == CS_ST_DIS || cs->state == CS_ST_CLO))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009348 return;
9349
9350 /* Execute the function. */
9351 switch (hlua_ctx_resume(hlua, 1)) {
9352 /* finished. */
9353 case HLUA_E_OK:
Willy Tarreaue23f33b2022-05-06 14:07:13 +02009354 tcp_ctx->flags |= APPLET_DONE;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009355
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009356 /* eat the whole request */
Christopher Faulet908628c2022-03-25 16:43:49 +01009357 co_skip(cs_oc(cs), co_data(cs_oc(cs)));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009358 res->flags |= CF_READ_NULL;
Christopher Fauletda098e62022-03-31 17:44:45 +02009359 cs_shutr(cs);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009360 return;
9361
9362 /* yield. */
9363 case HLUA_E_AGAIN:
Thierry Fournier0164f202016-02-20 17:47:43 +01009364 if (hlua->wake_time != TICK_ETERNITY)
Willy Tarreaue23f33b2022-05-06 14:07:13 +02009365 task_schedule(tcp_ctx->task, hlua->wake_time);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009366 return;
9367
9368 /* finished with error. */
9369 case HLUA_E_ERRMSG:
9370 /* Display log. */
9371 SEND_ERR(px, "Lua applet tcp '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009372 rule->arg.hlua_rule->fcn->name, lua_tostring(hlua->T, -1));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009373 lua_pop(hlua->T, 1);
9374 goto error;
9375
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009376 case HLUA_E_ETMOUT:
9377 SEND_ERR(px, "Lua applet tcp '%s': execution timeout.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009378 rule->arg.hlua_rule->fcn->name);
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009379 goto error;
9380
9381 case HLUA_E_NOMEM:
9382 SEND_ERR(px, "Lua applet tcp '%s': out of memory error.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009383 rule->arg.hlua_rule->fcn->name);
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009384 goto error;
9385
9386 case HLUA_E_YIELD: /* unexpected */
9387 SEND_ERR(px, "Lua applet tcp '%s': yield not allowed.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009388 rule->arg.hlua_rule->fcn->name);
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009389 goto error;
9390
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009391 case HLUA_E_ERR:
9392 /* Display log. */
9393 SEND_ERR(px, "Lua applet tcp '%s' return an unknown error.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009394 rule->arg.hlua_rule->fcn->name);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009395 goto error;
9396
9397 default:
9398 goto error;
9399 }
9400
9401error:
9402
9403 /* For all other cases, just close the stream. */
Christopher Fauletda098e62022-03-31 17:44:45 +02009404 cs_shutw(cs);
9405 cs_shutr(cs);
Willy Tarreaue23f33b2022-05-06 14:07:13 +02009406 tcp_ctx->flags |= APPLET_DONE;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009407}
9408
9409static void hlua_applet_tcp_release(struct appctx *ctx)
9410{
Willy Tarreaue23f33b2022-05-06 14:07:13 +02009411 struct hlua_tcp_ctx *tcp_ctx = ctx->svcctx;
9412
9413 task_destroy(tcp_ctx->task);
9414 tcp_ctx->task = NULL;
9415 hlua_ctx_destroy(tcp_ctx->hlua);
9416 tcp_ctx->hlua = NULL;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009417}
9418
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009419/* The function returns 1 if the initialisation is complete, 0 if
9420 * an errors occurs and -1 if more data are required for initializing
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009421 * the applet. It also reserves the appctx for an hlua_http_ctx.
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009422 */
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009423static int hlua_applet_http_init(struct appctx *ctx)
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009424{
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009425 struct hlua_http_ctx *http_ctx = applet_reserve_svcctx(ctx, sizeof(*http_ctx));
Christopher Faulet908628c2022-03-25 16:43:49 +01009426 struct conn_stream *cs = ctx->owner;
9427 struct stream *strm = __cs_strm(cs);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009428 struct http_txn *txn;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009429 struct hlua *hlua;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009430 char **arg;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009431 struct task *task;
Thierry Fournierfd107a22016-02-19 19:57:23 +01009432 const char *error;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009433
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009434 txn = strm->txn;
Willy Tarreaubafbe012017-11-24 17:34:44 +01009435 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009436 if (!hlua) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009437 SEND_ERR(strm->be, "Lua applet http '%s': out of memory.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009438 ctx->rule->arg.hlua_rule->fcn->name);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009439 return 0;
9440 }
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009441 HLUA_INIT(hlua);
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009442 http_ctx->hlua = hlua;
9443 http_ctx->left_bytes = -1;
9444 http_ctx->flags = 0;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009445
Thierry FOURNIERd93ea2b2015-12-20 19:14:52 +01009446 if (txn->req.flags & HTTP_MSGF_VER_11)
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009447 http_ctx->flags |= APPLET_HTTP11;
Thierry FOURNIERd93ea2b2015-12-20 19:14:52 +01009448
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009449 /* Create task used by signal to wakeup applets. */
Willy Tarreaubeeabf52021-10-01 18:23:30 +02009450 task = task_new_here();
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009451 if (!task) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009452 SEND_ERR(strm->be, "Lua applet http '%s': out of memory.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009453 ctx->rule->arg.hlua_rule->fcn->name);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009454 return 0;
9455 }
9456 task->nice = 0;
9457 task->context = ctx;
9458 task->process = hlua_applet_wakeup;
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009459 http_ctx->task = task;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009460
9461 /* In the execution wrappers linked with a stream, the
9462 * Lua context can be not initialized. This behavior
9463 * permits to save performances because a systematic
9464 * Lua initialization cause 5% performances loss.
9465 */
Thierry Fournierc7492592020-11-28 23:57:24 +01009466 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 +01009467 SEND_ERR(strm->be, "Lua applet http '%s': can't initialize Lua context.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009468 ctx->rule->arg.hlua_rule->fcn->name);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009469 return 0;
9470 }
9471
9472 /* Set timeout according with the applet configuration. */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02009473 hlua->max_time = ctx->applet->timeout;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009474
9475 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009476 if (!SET_SAFE_LJMP(hlua)) {
Thierry Fournierfd107a22016-02-19 19:57:23 +01009477 if (lua_type(hlua->T, -1) == LUA_TSTRING)
9478 error = lua_tostring(hlua->T, -1);
9479 else
9480 error = "critical error";
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009481 SEND_ERR(strm->be, "Lua applet http '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009482 ctx->rule->arg.hlua_rule->fcn->name, error);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009483 return 0;
9484 }
9485
9486 /* Check stack available size. */
9487 if (!lua_checkstack(hlua->T, 1)) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009488 SEND_ERR(strm->be, "Lua applet http '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009489 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009490 RESET_SAFE_LJMP(hlua);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009491 return 0;
9492 }
9493
9494 /* Restore the function in the stack. */
Thierry Fournierc7492592020-11-28 23:57:24 +01009495 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ctx->rule->arg.hlua_rule->fcn->function_ref[hlua->state_id]);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009496
9497 /* Create and and push object stream in the stack. */
9498 if (!hlua_applet_http_new(hlua->T, ctx)) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009499 SEND_ERR(strm->be, "Lua applet http '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009500 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009501 RESET_SAFE_LJMP(hlua);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009502 return 0;
9503 }
9504 hlua->nargs = 1;
9505
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009506 /* push keywords in the stack. */
9507 for (arg = ctx->rule->arg.hlua_rule->args; arg && *arg; arg++) {
9508 if (!lua_checkstack(hlua->T, 1)) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009509 SEND_ERR(strm->be, "Lua applet http '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009510 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009511 RESET_SAFE_LJMP(hlua);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009512 return 0;
9513 }
9514 lua_pushstring(hlua->T, *arg);
9515 hlua->nargs++;
9516 }
9517
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009518 RESET_SAFE_LJMP(hlua);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009519
9520 /* Wakeup the applet when data is ready for read. */
Christopher Fauleta0bdec32022-04-04 07:51:21 +02009521 cs_cant_get(cs);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009522
9523 return 1;
9524}
9525
Willy Tarreau60409db2019-08-21 14:14:50 +02009526void hlua_applet_http_fct(struct appctx *ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009527{
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009528 struct hlua_http_ctx *http_ctx = ctx->svcctx;
Christopher Faulet908628c2022-03-25 16:43:49 +01009529 struct conn_stream *cs = ctx->owner;
9530 struct stream *strm = __cs_strm(cs);
9531 struct channel *req = cs_oc(cs);
9532 struct channel *res = cs_ic(cs);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009533 struct act_rule *rule = ctx->rule;
9534 struct proxy *px = strm->be;
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009535 struct hlua *hlua = http_ctx->hlua;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009536 struct htx *req_htx, *res_htx;
9537
9538 res_htx = htx_from_buf(&res->buf);
9539
9540 /* If the stream is disconnect or closed, ldo nothing. */
Christopher Faulet62e75742022-03-31 09:16:34 +02009541 if (unlikely(cs->state == CS_ST_DIS || cs->state == CS_ST_CLO))
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009542 goto out;
9543
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05009544 /* Check if the input buffer is available. */
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009545 if (!b_size(&res->buf)) {
Christopher Fauleta0bdec32022-04-04 07:51:21 +02009546 cs_rx_room_blk(cs);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009547 goto out;
9548 }
9549 /* check that the output is not closed */
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01009550 if (res->flags & (CF_SHUTW|CF_SHUTW_NOW|CF_SHUTR))
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009551 http_ctx->flags |= APPLET_DONE;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009552
9553 /* Set the currently running flag. */
9554 if (!HLUA_IS_RUNNING(hlua) &&
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009555 !(http_ctx->flags & APPLET_DONE)) {
Christopher Fauletbd878d22021-04-28 10:50:21 +02009556 if (!co_data(req)) {
Christopher Fauleta0bdec32022-04-04 07:51:21 +02009557 cs_cant_get(cs);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009558 goto out;
9559 }
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009560 }
9561
9562 /* Executes The applet if it is not done. */
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009563 if (!(http_ctx->flags & APPLET_DONE)) {
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009564
9565 /* Execute the function. */
9566 switch (hlua_ctx_resume(hlua, 1)) {
9567 /* finished. */
9568 case HLUA_E_OK:
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009569 http_ctx->flags |= APPLET_DONE;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009570 break;
9571
9572 /* yield. */
9573 case HLUA_E_AGAIN:
9574 if (hlua->wake_time != TICK_ETERNITY)
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009575 task_schedule(http_ctx->task, hlua->wake_time);
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01009576 goto out;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009577
9578 /* finished with error. */
9579 case HLUA_E_ERRMSG:
9580 /* Display log. */
9581 SEND_ERR(px, "Lua applet http '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009582 rule->arg.hlua_rule->fcn->name, lua_tostring(hlua->T, -1));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009583 lua_pop(hlua->T, 1);
9584 goto error;
9585
9586 case HLUA_E_ETMOUT:
9587 SEND_ERR(px, "Lua applet http '%s': execution timeout.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009588 rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009589 goto error;
9590
9591 case HLUA_E_NOMEM:
9592 SEND_ERR(px, "Lua applet http '%s': out of memory error.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009593 rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009594 goto error;
9595
9596 case HLUA_E_YIELD: /* unexpected */
9597 SEND_ERR(px, "Lua applet http '%s': yield not allowed.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009598 rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009599 goto error;
9600
9601 case HLUA_E_ERR:
9602 /* Display log. */
9603 SEND_ERR(px, "Lua applet http '%s' return an unknown error.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009604 rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009605 goto error;
9606
9607 default:
9608 goto error;
9609 }
9610 }
9611
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009612 if (http_ctx->flags & APPLET_DONE) {
9613 if (http_ctx->flags & APPLET_RSP_SENT)
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01009614 goto done;
9615
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009616 if (!(http_ctx->flags & APPLET_HDR_SENT))
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009617 goto error;
9618
Christopher Fauletf89af9c2022-04-07 10:07:18 +02009619 /* no more data are expected. If the response buffer is empty
9620 * for a chunked message, be sure to add something (EOT block in
9621 * this case) to have something to send. It is important to be
9622 * sure the EOM flags will be handled by the endpoint.
9623 */
9624 if (htx_is_empty(res_htx) && (strm->txn->rsp.flags & (HTTP_MSGF_XFER_LEN|HTTP_MSGF_CNT_LEN)) == HTTP_MSGF_XFER_LEN) {
9625 if (!htx_add_endof(res_htx, HTX_BLK_EOT)) {
Christopher Fauleta0bdec32022-04-04 07:51:21 +02009626 cs_rx_room_blk(cs);
Christopher Fauletf89af9c2022-04-07 10:07:18 +02009627 goto out;
9628 }
9629 channel_add_input(res, 1);
9630 }
9631
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01009632 res_htx->flags |= HTX_FL_EOM;
Christopher Faulet908628c2022-03-25 16:43:49 +01009633 cs->endp->flags |= CS_EP_EOI;
Christopher Fauletd8d27082022-03-07 15:50:54 +01009634 res->flags |= CF_EOI;
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009635 strm->txn->status = http_ctx->status;
9636 http_ctx->flags |= APPLET_RSP_SENT;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009637 }
9638
9639 done:
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009640 if (http_ctx->flags & APPLET_DONE) {
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01009641 if (!(res->flags & CF_SHUTR)) {
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009642 res->flags |= CF_READ_NULL;
Christopher Fauletda098e62022-03-31 17:44:45 +02009643 cs_shutr(cs);
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01009644 }
9645
9646 /* eat the whole request */
9647 if (co_data(req)) {
9648 req_htx = htx_from_buf(&req->buf);
9649 co_htx_skip(req, req_htx, co_data(req));
9650 htx_to_buf(req_htx, &req->buf);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009651 }
9652 }
9653
9654 out:
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009655 htx_to_buf(res_htx, &res->buf);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009656 return;
9657
9658 error:
9659
9660 /* If we are in HTTP mode, and we are not send any
9661 * data, return a 500 server error in best effort:
9662 * if there is no room available in the buffer,
9663 * just close the connection.
9664 */
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009665 if (!(http_ctx->flags & APPLET_HDR_SENT)) {
Christopher Fauletf7346382019-07-17 22:02:08 +02009666 struct buffer *err = &http_err_chunks[HTTP_ERR_500];
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009667
9668 channel_erase(res);
9669 res->buf.data = b_data(err);
9670 memcpy(res->buf.area, b_head(err), b_data(err));
9671 res_htx = htx_from_buf(&res->buf);
Christopher Fauletf6cce3f2019-02-27 21:20:09 +01009672 channel_add_input(res, res_htx->data);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009673 }
9674 if (!(strm->flags & SF_ERR_MASK))
9675 strm->flags |= SF_ERR_RESOURCE;
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009676 http_ctx->flags |= APPLET_DONE;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009677 goto done;
9678}
9679
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009680static void hlua_applet_http_release(struct appctx *ctx)
9681{
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009682 struct hlua_http_ctx *http_ctx = ctx->svcctx;
9683
9684 task_destroy(http_ctx->task);
9685 http_ctx->task = NULL;
9686 hlua_ctx_destroy(http_ctx->hlua);
9687 http_ctx->hlua = NULL;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009688}
9689
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009690/* global {tcp|http}-request parser. Return ACT_RET_PRS_OK in
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05009691 * success case, else return ACT_RET_PRS_ERR.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02009692 *
9693 * This function can fail with an abort() due to an Lua critical error.
9694 * We are in the configuration parsing process of HAProxy, this abort() is
9695 * tolerated.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009696 */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009697static enum act_parse_ret action_register_lua(const char **args, int *cur_arg, struct proxy *px,
9698 struct act_rule *rule, char **err)
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009699{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02009700 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009701 int i;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009702
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009703 /* Memory for the rule. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02009704 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009705 if (!rule->arg.hlua_rule) {
9706 memprintf(err, "out of memory error");
Christopher Faulet528526f2021-04-12 14:37:32 +02009707 goto error;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009708 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009709
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009710 /* Memory for arguments. */
Tim Duesterhuse52b6e52020-09-12 20:26:43 +02009711 rule->arg.hlua_rule->args = calloc(fcn->nargs + 1,
9712 sizeof(*rule->arg.hlua_rule->args));
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009713 if (!rule->arg.hlua_rule->args) {
9714 memprintf(err, "out of memory error");
Christopher Faulet528526f2021-04-12 14:37:32 +02009715 goto error;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009716 }
9717
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009718 /* Reference the Lua function and store the reference. */
Thierry Fournierad5345f2020-11-29 02:05:57 +01009719 rule->arg.hlua_rule->fcn = fcn;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009720
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009721 /* Expect some arguments */
9722 for (i = 0; i < fcn->nargs; i++) {
Thierry FOURNIER1725c2e2019-01-06 19:38:49 +01009723 if (*args[*cur_arg] == '\0') {
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009724 memprintf(err, "expect %d arguments", fcn->nargs);
Christopher Faulet528526f2021-04-12 14:37:32 +02009725 goto error;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009726 }
Thierry FOURNIER1725c2e2019-01-06 19:38:49 +01009727 rule->arg.hlua_rule->args[i] = strdup(args[*cur_arg]);
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009728 if (!rule->arg.hlua_rule->args[i]) {
9729 memprintf(err, "out of memory error");
Christopher Faulet528526f2021-04-12 14:37:32 +02009730 goto error;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009731 }
9732 (*cur_arg)++;
9733 }
9734 rule->arg.hlua_rule->args[i] = NULL;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009735
Thierry FOURNIER42148732015-09-02 17:17:33 +02009736 rule->action = ACT_CUSTOM;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009737 rule->action_ptr = hlua_action;
Thierry FOURNIERafa80492015-08-19 09:04:15 +02009738 return ACT_RET_PRS_OK;
Christopher Faulet528526f2021-04-12 14:37:32 +02009739
9740 error:
9741 if (rule->arg.hlua_rule) {
9742 if (rule->arg.hlua_rule->args) {
9743 for (i = 0; i < fcn->nargs; i++)
9744 ha_free(&rule->arg.hlua_rule->args[i]);
9745 ha_free(&rule->arg.hlua_rule->args);
9746 }
9747 ha_free(&rule->arg.hlua_rule);
9748 }
9749 return ACT_RET_PRS_ERR;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009750}
9751
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009752static enum act_parse_ret action_register_service_http(const char **args, int *cur_arg, struct proxy *px,
9753 struct act_rule *rule, char **err)
9754{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02009755 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009756
Thierry FOURNIER718e2a72015-12-20 20:13:14 +01009757 /* HTTP applets are forbidden in tcp-request rules.
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05009758 * HTTP applet request requires everything initialized by
Thierry FOURNIER718e2a72015-12-20 20:13:14 +01009759 * "http_process_request" (analyzer flag AN_REQ_HTTP_INNER).
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05009760 * The applet will be immediately initialized, but its before
Thierry FOURNIER718e2a72015-12-20 20:13:14 +01009761 * the call of this analyzer.
9762 */
9763 if (rule->from != ACT_F_HTTP_REQ) {
9764 memprintf(err, "HTTP applets are forbidden from 'tcp-request' rulesets");
9765 return ACT_RET_PRS_ERR;
9766 }
9767
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009768 /* Memory for the rule. */
9769 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
9770 if (!rule->arg.hlua_rule) {
9771 memprintf(err, "out of memory error");
9772 return ACT_RET_PRS_ERR;
9773 }
9774
9775 /* Reference the Lua function and store the reference. */
Thierry Fournierad5345f2020-11-29 02:05:57 +01009776 rule->arg.hlua_rule->fcn = fcn;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009777
9778 /* TODO: later accept arguments. */
9779 rule->arg.hlua_rule->args = NULL;
9780
9781 /* Add applet pointer in the rule. */
9782 rule->applet.obj_type = OBJ_TYPE_APPLET;
9783 rule->applet.name = fcn->name;
9784 rule->applet.init = hlua_applet_http_init;
9785 rule->applet.fct = hlua_applet_http_fct;
9786 rule->applet.release = hlua_applet_http_release;
9787 rule->applet.timeout = hlua_timeout_applet;
9788
9789 return ACT_RET_PRS_OK;
9790}
9791
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009792/* This function is an LUA binding used for registering
9793 * "sample-conv" functions. It expects a converter name used
9794 * in the haproxy configuration file, and an LUA function.
9795 */
9796__LJMP static int hlua_register_action(lua_State *L)
9797{
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009798 struct action_kw_list *akl = NULL;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009799 const char *name;
9800 int ref;
9801 int len;
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009802 struct hlua_function *fcn = NULL;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009803 int nargs;
Thierry Fournierf67442e2020-11-28 20:41:07 +01009804 struct buffer *trash;
9805 struct action_kw *akw;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009806
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009807 /* Initialise the number of expected arguments at 0. */
9808 nargs = 0;
9809
9810 if (lua_gettop(L) < 3 || lua_gettop(L) > 4)
9811 WILL_LJMP(luaL_error(L, "'register_action' needs between 3 and 4 arguments"));
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009812
9813 /* First argument : converter name. */
9814 name = MAY_LJMP(luaL_checkstring(L, 1));
9815
9816 /* Second argument : environment. */
9817 if (lua_type(L, 2) != LUA_TTABLE)
9818 WILL_LJMP(luaL_error(L, "register_action: second argument must be a table of strings"));
9819
9820 /* Third argument : lua function. */
9821 ref = MAY_LJMP(hlua_checkfunction(L, 3));
9822
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08009823 /* Fourth argument : number of mandatory arguments expected on the configuration line. */
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009824 if (lua_gettop(L) >= 4)
9825 nargs = MAY_LJMP(luaL_checkinteger(L, 4));
9826
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08009827 /* browse the second argument as an array. */
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009828 lua_pushnil(L);
9829 while (lua_next(L, 2) != 0) {
9830 if (lua_type(L, -1) != LUA_TSTRING)
9831 WILL_LJMP(luaL_error(L, "register_action: second argument must be a table of strings"));
9832
Thierry Fournierf67442e2020-11-28 20:41:07 +01009833 /* Check if action exists */
9834 trash = get_trash_chunk();
9835 chunk_printf(trash, "lua.%s", name);
9836 if (strcmp(lua_tostring(L, -1), "tcp-req") == 0) {
9837 akw = tcp_req_cont_action(trash->area);
9838 } else if (strcmp(lua_tostring(L, -1), "tcp-res") == 0) {
9839 akw = tcp_res_cont_action(trash->area);
9840 } else if (strcmp(lua_tostring(L, -1), "http-req") == 0) {
9841 akw = action_http_req_custom(trash->area);
9842 } else if (strcmp(lua_tostring(L, -1), "http-res") == 0) {
9843 akw = action_http_res_custom(trash->area);
9844 } else {
9845 akw = NULL;
9846 }
9847 if (akw != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +01009848 fcn = akw->private;
9849 if (fcn->function_ref[hlua_state_id] != -1) {
9850 ha_warning("Trying to register action 'lua.%s' more than once. "
9851 "This will become a hard error in version 2.5.\n", name);
9852 }
9853 fcn->function_ref[hlua_state_id] = ref;
9854
9855 /* pop the environment string. */
9856 lua_pop(L, 1);
9857 continue;
Thierry Fournierf67442e2020-11-28 20:41:07 +01009858 }
9859
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009860 /* Check required environment. Only accepted "http" or "tcp". */
9861 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02009862 akl = calloc(1, sizeof(*akl) + sizeof(struct action_kw) * 2);
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009863 if (!akl)
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009864 goto alloc_error;;
Thierry Fournier62a22aa2020-11-28 21:06:35 +01009865 fcn = new_hlua_function();
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009866 if (!fcn)
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009867 goto alloc_error;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009868
9869 /* Fill fcn. */
9870 fcn->name = strdup(name);
9871 if (!fcn->name)
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009872 goto alloc_error;
Thierry Fournierc7492592020-11-28 23:57:24 +01009873 fcn->function_ref[hlua_state_id] = ref;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009874
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -07009875 /* Set the expected number of arguments. */
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009876 fcn->nargs = nargs;
9877
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009878 /* List head */
9879 akl->list.n = akl->list.p = NULL;
9880
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009881 /* action keyword. */
9882 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02009883 akl->kw[0].kw = calloc(1, len);
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009884 if (!akl->kw[0].kw)
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009885 goto alloc_error;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009886
9887 snprintf((char *)akl->kw[0].kw, len, "lua.%s", name);
9888
Amaury Denoyellee4a617c2021-05-06 15:33:09 +02009889 akl->kw[0].flags = 0;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009890 akl->kw[0].private = fcn;
9891 akl->kw[0].parse = action_register_lua;
9892
9893 /* select the action registering point. */
9894 if (strcmp(lua_tostring(L, -1), "tcp-req") == 0)
9895 tcp_req_cont_keywords_register(akl);
9896 else if (strcmp(lua_tostring(L, -1), "tcp-res") == 0)
9897 tcp_res_cont_keywords_register(akl);
9898 else if (strcmp(lua_tostring(L, -1), "http-req") == 0)
9899 http_req_keywords_register(akl);
9900 else if (strcmp(lua_tostring(L, -1), "http-res") == 0)
9901 http_res_keywords_register(akl);
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009902 else {
9903 release_hlua_function(fcn);
9904 if (akl)
9905 ha_free((char **)&(akl->kw[0].kw));
9906 ha_free(&akl);
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01009907 WILL_LJMP(luaL_error(L, "Lua action environment '%s' is unknown. "
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009908 "'tcp-req', 'tcp-res', 'http-req' or 'http-res' "
9909 "are expected.", lua_tostring(L, -1)));
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009910 }
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009911
9912 /* pop the environment string. */
9913 lua_pop(L, 1);
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009914
9915 /* reset for next loop */
9916 akl = NULL;
9917 fcn = NULL;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009918 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009919 return ACT_RET_PRS_OK;
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009920
9921 alloc_error:
9922 release_hlua_function(fcn);
9923 ha_free(&akl);
9924 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
9925 return 0; /* Never reached */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009926}
9927
9928static enum act_parse_ret action_register_service_tcp(const char **args, int *cur_arg, struct proxy *px,
9929 struct act_rule *rule, char **err)
9930{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02009931 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009932
Christopher Faulet280f85b2019-07-15 15:02:04 +02009933 if (px->mode == PR_MODE_HTTP) {
9934 memprintf(err, "Lua TCP services cannot be used on HTTP proxies");
Christopher Fauletafd8f102018-11-08 11:34:21 +01009935 return ACT_RET_PRS_ERR;
9936 }
9937
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009938 /* Memory for the rule. */
9939 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
9940 if (!rule->arg.hlua_rule) {
9941 memprintf(err, "out of memory error");
9942 return ACT_RET_PRS_ERR;
9943 }
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009944
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009945 /* Reference the Lua function and store the reference. */
Thierry Fournierad5345f2020-11-29 02:05:57 +01009946 rule->arg.hlua_rule->fcn = fcn;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009947
9948 /* TODO: later accept arguments. */
9949 rule->arg.hlua_rule->args = NULL;
9950
9951 /* Add applet pointer in the rule. */
9952 rule->applet.obj_type = OBJ_TYPE_APPLET;
9953 rule->applet.name = fcn->name;
9954 rule->applet.init = hlua_applet_tcp_init;
9955 rule->applet.fct = hlua_applet_tcp_fct;
9956 rule->applet.release = hlua_applet_tcp_release;
9957 rule->applet.timeout = hlua_timeout_applet;
9958
9959 return 0;
9960}
9961
9962/* This function is an LUA binding used for registering
9963 * "sample-conv" functions. It expects a converter name used
9964 * in the haproxy configuration file, and an LUA function.
9965 */
9966__LJMP static int hlua_register_service(lua_State *L)
9967{
9968 struct action_kw_list *akl;
9969 const char *name;
9970 const char *env;
9971 int ref;
9972 int len;
Christopher Faulet5c028d72021-04-12 15:11:44 +02009973 struct hlua_function *fcn = NULL;
Thierry Fournierf67442e2020-11-28 20:41:07 +01009974 struct buffer *trash;
9975 struct action_kw *akw;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009976
9977 MAY_LJMP(check_args(L, 3, "register_service"));
9978
9979 /* First argument : converter name. */
9980 name = MAY_LJMP(luaL_checkstring(L, 1));
9981
9982 /* Second argument : environment. */
9983 env = MAY_LJMP(luaL_checkstring(L, 2));
9984
9985 /* Third argument : lua function. */
9986 ref = MAY_LJMP(hlua_checkfunction(L, 3));
9987
Thierry Fournierf67442e2020-11-28 20:41:07 +01009988 /* Check for service already registered */
9989 trash = get_trash_chunk();
9990 chunk_printf(trash, "lua.%s", name);
9991 akw = service_find(trash->area);
9992 if (akw != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +01009993 fcn = akw->private;
9994 if (fcn->function_ref[hlua_state_id] != -1) {
9995 ha_warning("Trying to register service 'lua.%s' more than once. "
9996 "This will become a hard error in version 2.5.\n", name);
9997 }
9998 fcn->function_ref[hlua_state_id] = ref;
9999 return 0;
Thierry Fournierf67442e2020-11-28 20:41:07 +010010000 }
10001
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010002 /* Allocate and fill the sample fetch keyword struct. */
10003 akl = calloc(1, sizeof(*akl) + sizeof(struct action_kw) * 2);
10004 if (!akl)
Christopher Faulet5c028d72021-04-12 15:11:44 +020010005 goto alloc_error;
Thierry Fournier62a22aa2020-11-28 21:06:35 +010010006 fcn = new_hlua_function();
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010007 if (!fcn)
Christopher Faulet5c028d72021-04-12 15:11:44 +020010008 goto alloc_error;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010009
10010 /* Fill fcn. */
10011 len = strlen("<lua.>") + strlen(name) + 1;
10012 fcn->name = calloc(1, len);
10013 if (!fcn->name)
Christopher Faulet5c028d72021-04-12 15:11:44 +020010014 goto alloc_error;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010015 snprintf((char *)fcn->name, len, "<lua.%s>", name);
Thierry Fournierc7492592020-11-28 23:57:24 +010010016 fcn->function_ref[hlua_state_id] = ref;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010017
10018 /* List head */
10019 akl->list.n = akl->list.p = NULL;
10020
10021 /* converter keyword. */
10022 len = strlen("lua.") + strlen(name) + 1;
10023 akl->kw[0].kw = calloc(1, len);
10024 if (!akl->kw[0].kw)
Christopher Faulet5c028d72021-04-12 15:11:44 +020010025 goto alloc_error;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010026
10027 snprintf((char *)akl->kw[0].kw, len, "lua.%s", name);
10028
Thierry FOURNIER / OZON.IO02564fd2016-11-12 11:07:05 +010010029 /* Check required environment. Only accepted "http" or "tcp". */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010030 if (strcmp(env, "tcp") == 0)
10031 akl->kw[0].parse = action_register_service_tcp;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010032 else if (strcmp(env, "http") == 0)
10033 akl->kw[0].parse = action_register_service_http;
Christopher Faulet5c028d72021-04-12 15:11:44 +020010034 else {
10035 release_hlua_function(fcn);
10036 if (akl)
10037 ha_free((char **)&(akl->kw[0].kw));
10038 ha_free(&akl);
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +010010039 WILL_LJMP(luaL_error(L, "Lua service environment '%s' is unknown. "
Eric Salamafe7456f2017-12-21 14:30:07 +010010040 "'tcp' or 'http' are expected.", env));
Christopher Faulet5c028d72021-04-12 15:11:44 +020010041 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010042
Amaury Denoyellee4a617c2021-05-06 15:33:09 +020010043 akl->kw[0].flags = 0;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010044 akl->kw[0].private = fcn;
10045
10046 /* End of array. */
10047 memset(&akl->kw[1], 0, sizeof(*akl->kw));
10048
10049 /* Register this new converter */
10050 service_keywords_register(akl);
10051
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010052 return 0;
Christopher Faulet5c028d72021-04-12 15:11:44 +020010053
10054 alloc_error:
10055 release_hlua_function(fcn);
10056 ha_free(&akl);
10057 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
10058 return 0; /* Never reached */
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010059}
10060
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010061/* This function initialises Lua cli handler. It copies the
10062 * arguments in the Lua stack and create channel IO objects.
10063 */
Aurélien Nephtaliabbf6072018-04-18 13:26:46 +020010064static int hlua_cli_parse_fct(char **args, char *payload, struct appctx *appctx, void *private)
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010065{
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010066 struct hlua_cli_ctx *ctx = applet_reserve_svcctx(appctx, sizeof(*ctx));
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010067 struct hlua *hlua;
10068 struct hlua_function *fcn;
10069 int i;
10070 const char *error;
10071
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010072 fcn = private;
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010073 ctx->fcn = private;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +010010074
Willy Tarreaubafbe012017-11-24 17:34:44 +010010075 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +010010076 if (!hlua) {
10077 SEND_ERR(NULL, "Lua cli '%s': out of memory.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +010010078 return 1;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +010010079 }
10080 HLUA_INIT(hlua);
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010081 ctx->hlua = hlua;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010082
10083 /* Create task used by signal to wakeup applets.
Ilya Shipitsind4259502020-04-08 01:07:56 +050010084 * We use the same wakeup function than the Lua applet_tcp and
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010085 * applet_http. It is absolutely compatible.
10086 */
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010087 ctx->task = task_new_here();
10088 if (!ctx->task) {
Thierry FOURNIERffbf5692016-12-16 11:14:06 +010010089 SEND_ERR(NULL, "Lua cli '%s': out of memory.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +010010090 goto error;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010091 }
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010092 ctx->task->nice = 0;
10093 ctx->task->context = appctx;
10094 ctx->task->process = hlua_applet_wakeup;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010095
10096 /* Initialises the Lua context */
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010097 if (!hlua_ctx_init(hlua, fcn_ref_to_stack_id(fcn), ctx->task, 0)) {
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010098 SEND_ERR(NULL, "Lua cli '%s': can't initialize Lua context.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +010010099 goto error;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010100 }
10101
10102 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010103 if (!SET_SAFE_LJMP(hlua)) {
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010104 if (lua_type(hlua->T, -1) == LUA_TSTRING)
10105 error = lua_tostring(hlua->T, -1);
10106 else
10107 error = "critical error";
10108 SEND_ERR(NULL, "Lua cli '%s': %s.\n", fcn->name, error);
10109 goto error;
10110 }
10111
10112 /* Check stack available size. */
10113 if (!lua_checkstack(hlua->T, 2)) {
10114 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
10115 goto error;
10116 }
10117
10118 /* Restore the function in the stack. */
Thierry Fournierc7492592020-11-28 23:57:24 +010010119 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, fcn->function_ref[hlua->state_id]);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010120
10121 /* Once the arguments parsed, the CLI is like an AppletTCP,
10122 * so push AppletTCP in the stack.
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010123 */
10124 if (!hlua_applet_tcp_new(hlua->T, appctx)) {
10125 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
10126 goto error;
10127 }
10128 hlua->nargs = 1;
10129
10130 /* push keywords in the stack. */
10131 for (i = 0; *args[i]; i++) {
10132 /* Check stack available size. */
10133 if (!lua_checkstack(hlua->T, 1)) {
10134 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
10135 goto error;
10136 }
10137 lua_pushstring(hlua->T, args[i]);
10138 hlua->nargs++;
10139 }
10140
10141 /* We must initialize the execution timeouts. */
10142 hlua->max_time = hlua_timeout_session;
10143
10144 /* At this point the execution is safe. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010145 RESET_SAFE_LJMP(hlua);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010146
10147 /* It's ok */
10148 return 0;
10149
10150 /* It's not ok. */
10151error:
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010152 RESET_SAFE_LJMP(hlua);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010153 hlua_ctx_destroy(hlua);
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010154 ctx->hlua = NULL;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010155 return 1;
10156}
10157
10158static int hlua_cli_io_handler_fct(struct appctx *appctx)
10159{
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010160 struct hlua_cli_ctx *ctx = appctx->svcctx;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010161 struct hlua *hlua;
Christopher Faulet908628c2022-03-25 16:43:49 +010010162 struct conn_stream *cs;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010163 struct hlua_function *fcn;
10164
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010165 hlua = ctx->hlua;
Christopher Faulet908628c2022-03-25 16:43:49 +010010166 cs = appctx->owner;
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010167 fcn = ctx->fcn;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010168
10169 /* If the stream is disconnect or closed, ldo nothing. */
Christopher Faulet62e75742022-03-31 09:16:34 +020010170 if (unlikely(cs->state == CS_ST_DIS || cs->state == CS_ST_CLO))
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010171 return 1;
10172
10173 /* Execute the function. */
10174 switch (hlua_ctx_resume(hlua, 1)) {
10175
10176 /* finished. */
10177 case HLUA_E_OK:
10178 return 1;
10179
10180 /* yield. */
10181 case HLUA_E_AGAIN:
10182 /* We want write. */
10183 if (HLUA_IS_WAKERESWR(hlua))
Christopher Fauleta0bdec32022-04-04 07:51:21 +020010184 cs_rx_room_blk(cs);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010185 /* Set the timeout. */
10186 if (hlua->wake_time != TICK_ETERNITY)
10187 task_schedule(hlua->task, hlua->wake_time);
10188 return 0;
10189
10190 /* finished with error. */
10191 case HLUA_E_ERRMSG:
10192 /* Display log. */
10193 SEND_ERR(NULL, "Lua cli '%s': %s.\n",
10194 fcn->name, lua_tostring(hlua->T, -1));
10195 lua_pop(hlua->T, 1);
10196 return 1;
10197
Thierry Fournierd5b073c2018-05-21 19:42:47 +020010198 case HLUA_E_ETMOUT:
10199 SEND_ERR(NULL, "Lua converter '%s': execution timeout.\n",
10200 fcn->name);
10201 return 1;
10202
10203 case HLUA_E_NOMEM:
10204 SEND_ERR(NULL, "Lua converter '%s': out of memory error.\n",
10205 fcn->name);
10206 return 1;
10207
10208 case HLUA_E_YIELD: /* unexpected */
10209 SEND_ERR(NULL, "Lua converter '%s': yield not allowed.\n",
10210 fcn->name);
10211 return 1;
10212
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010213 case HLUA_E_ERR:
10214 /* Display log. */
10215 SEND_ERR(NULL, "Lua cli '%s' return an unknown error.\n",
10216 fcn->name);
10217 return 1;
10218
10219 default:
10220 return 1;
10221 }
10222
10223 return 1;
10224}
10225
10226static void hlua_cli_io_release_fct(struct appctx *appctx)
10227{
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010228 struct hlua_cli_ctx *ctx = appctx->svcctx;
10229
10230 hlua_ctx_destroy(ctx->hlua);
10231 ctx->hlua = NULL;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010232}
10233
10234/* This function is an LUA binding used for registering
10235 * new keywords in the cli. It expects a list of keywords
10236 * which are the "path". It is limited to 5 keywords. A
10237 * description of the command, a function to be executed
10238 * for the parsing and a function for io handlers.
10239 */
10240__LJMP static int hlua_register_cli(lua_State *L)
10241{
10242 struct cli_kw_list *cli_kws;
10243 const char *message;
10244 int ref_io;
10245 int len;
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010246 struct hlua_function *fcn = NULL;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010247 int index;
10248 int i;
Thierry Fournierf67442e2020-11-28 20:41:07 +010010249 struct buffer *trash;
10250 const char *kw[5];
10251 struct cli_kw *cli_kw;
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010252 const char *errmsg;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010253
10254 MAY_LJMP(check_args(L, 3, "register_cli"));
10255
10256 /* First argument : an array of maximum 5 keywords. */
10257 if (!lua_istable(L, 1))
10258 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table"));
10259
10260 /* Second argument : string with contextual message. */
10261 message = MAY_LJMP(luaL_checkstring(L, 2));
10262
10263 /* Third and fourth argument : lua function. */
10264 ref_io = MAY_LJMP(hlua_checkfunction(L, 3));
10265
Thierry Fournierf67442e2020-11-28 20:41:07 +010010266 /* Check for CLI service already registered */
10267 trash = get_trash_chunk();
10268 index = 0;
10269 lua_pushnil(L);
10270 memset(kw, 0, sizeof(kw));
10271 while (lua_next(L, 1) != 0) {
10272 if (index >= CLI_PREFIX_KW_NB)
10273 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table with a maximum of 5 entries"));
10274 if (lua_type(L, -1) != LUA_TSTRING)
10275 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table filled with strings"));
10276 kw[index] = lua_tostring(L, -1);
10277 if (index == 0)
10278 chunk_printf(trash, "%s", kw[index]);
10279 else
10280 chunk_appendf(trash, " %s", kw[index]);
10281 index++;
10282 lua_pop(L, 1);
10283 }
10284 cli_kw = cli_find_kw_exact((char **)kw);
10285 if (cli_kw != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +010010286 fcn = cli_kw->private;
10287 if (fcn->function_ref[hlua_state_id] != -1) {
10288 ha_warning("Trying to register CLI keyword 'lua.%s' more than once. "
10289 "This will become a hard error in version 2.5.\n", trash->area);
10290 }
10291 fcn->function_ref[hlua_state_id] = ref_io;
10292 return 0;
Thierry Fournierf67442e2020-11-28 20:41:07 +010010293 }
10294
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010295 /* Allocate and fill the sample fetch keyword struct. */
10296 cli_kws = calloc(1, sizeof(*cli_kws) + sizeof(struct cli_kw) * 2);
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010297 if (!cli_kws) {
10298 errmsg = "Lua out of memory error.";
10299 goto error;
10300 }
Thierry Fournier62a22aa2020-11-28 21:06:35 +010010301 fcn = new_hlua_function();
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010302 if (!fcn) {
10303 errmsg = "Lua out of memory error.";
10304 goto error;
10305 }
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010306
10307 /* Fill path. */
10308 index = 0;
10309 lua_pushnil(L);
10310 while(lua_next(L, 1) != 0) {
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010311 if (index >= 5) {
10312 errmsg = "1st argument must be a table with a maximum of 5 entries";
10313 goto error;
10314 }
10315 if (lua_type(L, -1) != LUA_TSTRING) {
10316 errmsg = "1st argument must be a table filled with strings";
10317 goto error;
10318 }
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010319 cli_kws->kw[0].str_kw[index] = strdup(lua_tostring(L, -1));
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010320 if (!cli_kws->kw[0].str_kw[index]) {
10321 errmsg = "Lua out of memory error.";
10322 goto error;
10323 }
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010324 index++;
10325 lua_pop(L, 1);
10326 }
10327
10328 /* Copy help message. */
10329 cli_kws->kw[0].usage = strdup(message);
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010330 if (!cli_kws->kw[0].usage) {
10331 errmsg = "Lua out of memory error.";
10332 goto error;
10333 }
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010334
10335 /* Fill fcn io handler. */
10336 len = strlen("<lua.cli>") + 1;
10337 for (i = 0; i < index; i++)
10338 len += strlen(cli_kws->kw[0].str_kw[i]) + 1;
10339 fcn->name = calloc(1, len);
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010340 if (!fcn->name) {
10341 errmsg = "Lua out of memory error.";
10342 goto error;
10343 }
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010344 strncat((char *)fcn->name, "<lua.cli", len);
10345 for (i = 0; i < index; i++) {
10346 strncat((char *)fcn->name, ".", len);
10347 strncat((char *)fcn->name, cli_kws->kw[0].str_kw[i], len);
10348 }
10349 strncat((char *)fcn->name, ">", len);
Thierry Fournierc7492592020-11-28 23:57:24 +010010350 fcn->function_ref[hlua_state_id] = ref_io;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010351
10352 /* Fill last entries. */
10353 cli_kws->kw[0].private = fcn;
10354 cli_kws->kw[0].parse = hlua_cli_parse_fct;
10355 cli_kws->kw[0].io_handler = hlua_cli_io_handler_fct;
10356 cli_kws->kw[0].io_release = hlua_cli_io_release_fct;
10357
10358 /* Register this new converter */
10359 cli_register_kw(cli_kws);
10360
10361 return 0;
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010362
10363 error:
10364 release_hlua_function(fcn);
10365 if (cli_kws) {
10366 for (i = 0; i < index; i++)
10367 ha_free((char **)&(cli_kws->kw[0].str_kw[i]));
10368 ha_free((char **)&(cli_kws->kw[0].usage));
10369 }
10370 ha_free(&cli_kws);
10371 WILL_LJMP(luaL_error(L, errmsg));
10372 return 0; /* Never reached */
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010373}
10374
Christopher Faulet69c581a2021-05-31 08:54:04 +020010375static int hlua_filter_init_per_thread(struct proxy *px, struct flt_conf *fconf)
10376{
10377 struct hlua_flt_config *conf = fconf->conf;
10378 lua_State *L;
10379 int error, pos, state_id, flt_ref;
10380
10381 state_id = reg_flt_to_stack_id(conf->reg);
10382 L = hlua_states[state_id];
10383 pos = lua_gettop(L);
10384
10385 /* The filter parsing function */
10386 lua_rawgeti(L, LUA_REGISTRYINDEX, conf->reg->fun_ref[state_id]);
10387
10388 /* Push the filter class on the stack and resolve all callbacks */
10389 lua_rawgeti(L, LUA_REGISTRYINDEX, conf->reg->flt_ref[state_id]);
10390
10391 /* Duplicate the filter class so each filter will have its own copy */
10392 lua_newtable(L);
10393 lua_pushnil(L);
10394
10395 while (lua_next(L, pos+2)) {
10396 lua_pushvalue(L, -2);
10397 lua_insert(L, -2);
10398 lua_settable(L, -4);
10399 }
10400 flt_ref = luaL_ref(L, LUA_REGISTRYINDEX);
10401
10402 /* Remove the original lua filter class from the stack */
10403 lua_pop(L, 1);
10404
10405 /* Push the copy on the stack */
10406 lua_rawgeti(L, LUA_REGISTRYINDEX, flt_ref);
10407
10408 /* extra args are pushed in a table */
10409 lua_newtable(L);
10410 for (pos = 0; conf->args[pos]; pos++) {
10411 /* Check stack available size. */
10412 if (!lua_checkstack(L, 1)) {
10413 ha_alert("Lua filter '%s' : Lua error : full stack.", conf->reg->name);
10414 goto error;
10415 }
10416 lua_pushstring(L, conf->args[pos]);
10417 lua_rawseti(L, -2, lua_rawlen(L, -2) + 1);
10418 }
10419
10420 error = lua_pcall(L, 2, LUA_MULTRET, 0);
10421 switch (error) {
10422 case LUA_OK:
10423 /* replace the filter ref */
10424 conf->ref[state_id] = flt_ref;
10425 break;
10426 case LUA_ERRRUN:
10427 ha_alert("Lua filter '%s' : runtime error : %s", conf->reg->name, lua_tostring(L, -1));
10428 goto error;
10429 case LUA_ERRMEM:
10430 ha_alert("Lua filter '%s' : out of memory error", conf->reg->name);
10431 goto error;
10432 case LUA_ERRERR:
10433 ha_alert("Lua filter '%s' : message handler error : %s", conf->reg->name, lua_tostring(L, -1));
10434 goto error;
10435#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM <= 503
10436 case LUA_ERRGCMM:
10437 ha_alert("Lua filter '%s' : garbage collector error : %s", conf->reg->name, lua_tostring(L, -1));
10438 goto error;
10439#endif
10440 default:
Ilya Shipitsinff0f2782021-08-22 22:18:07 +050010441 ha_alert("Lua filter '%s' : unknown error : %s", conf->reg->name, lua_tostring(L, -1));
Christopher Faulet69c581a2021-05-31 08:54:04 +020010442 goto error;
10443 }
10444
10445 lua_settop(L, 0);
10446 return 0;
10447
10448 error:
10449 lua_settop(L, 0);
10450 return -1;
10451}
10452
10453static void hlua_filter_deinit_per_thread(struct proxy *px, struct flt_conf *fconf)
10454{
10455 struct hlua_flt_config *conf = fconf->conf;
10456 lua_State *L;
10457 int state_id;
10458
10459 if (!conf)
10460 return;
10461
10462 state_id = reg_flt_to_stack_id(conf->reg);
10463 L = hlua_states[state_id];
10464 luaL_unref(L, LUA_REGISTRYINDEX, conf->ref[state_id]);
10465}
10466
10467static int hlua_filter_init(struct proxy *px, struct flt_conf *fconf)
10468{
10469 struct hlua_flt_config *conf = fconf->conf;
10470 int state_id = reg_flt_to_stack_id(conf->reg);
10471
10472 /* Rely on per-thread init for global scripts */
10473 if (!state_id)
10474 return hlua_filter_init_per_thread(px, fconf);
10475 return 0;
10476}
10477
10478static void hlua_filter_deinit(struct proxy *px, struct flt_conf *fconf)
10479{
10480
10481 if (fconf->conf) {
10482 struct hlua_flt_config *conf = fconf->conf;
10483 int state_id = reg_flt_to_stack_id(conf->reg);
10484 int pos;
10485
10486 /* Rely on per-thread deinit for global scripts */
10487 if (!state_id)
10488 hlua_filter_deinit_per_thread(px, fconf);
10489
10490 for (pos = 0; conf->args[pos]; pos++)
10491 free(conf->args[pos]);
10492 free(conf->args);
10493 }
10494 ha_free(&fconf->conf);
10495 ha_free((char **)&fconf->id);
10496 ha_free(&fconf->ops);
10497}
10498
10499static int hlua_filter_new(struct stream *s, struct filter *filter)
10500{
10501 struct hlua_flt_config *conf = FLT_CONF(filter);
10502 struct hlua_flt_ctx *flt_ctx = NULL;
10503 int ret = 1;
10504
10505 /* In the execution wrappers linked with a stream, the
10506 * Lua context can be not initialized. This behavior
10507 * permits to save performances because a systematic
10508 * Lua initialization cause 5% performances loss.
10509 */
10510 if (!s->hlua) {
10511 struct hlua *hlua;
10512
10513 hlua = pool_alloc(pool_head_hlua);
10514 if (!hlua) {
10515 SEND_ERR(s->be, "Lua filter '%s': can't initialize Lua context.\n",
10516 conf->reg->name);
10517 ret = 0;
10518 goto end;
10519 }
10520 HLUA_INIT(hlua);
10521 s->hlua = hlua;
10522 if (!hlua_ctx_init(s->hlua, reg_flt_to_stack_id(conf->reg), s->task, 0)) {
10523 SEND_ERR(s->be, "Lua filter '%s': can't initialize Lua context.\n",
10524 conf->reg->name);
10525 ret = 0;
10526 goto end;
10527 }
10528 }
10529
10530 flt_ctx = pool_zalloc(pool_head_hlua_flt_ctx);
10531 if (!flt_ctx) {
10532 SEND_ERR(s->be, "Lua filter '%s': can't initialize filter Lua context.\n",
10533 conf->reg->name);
10534 ret = 0;
10535 goto end;
10536 }
10537 flt_ctx->hlua[0] = pool_alloc(pool_head_hlua);
10538 flt_ctx->hlua[1] = pool_alloc(pool_head_hlua);
10539 if (!flt_ctx->hlua[0] || !flt_ctx->hlua[1]) {
10540 SEND_ERR(s->be, "Lua filter '%s': can't initialize filter Lua context.\n",
10541 conf->reg->name);
10542 ret = 0;
10543 goto end;
10544 }
10545 HLUA_INIT(flt_ctx->hlua[0]);
10546 HLUA_INIT(flt_ctx->hlua[1]);
10547 if (!hlua_ctx_init(flt_ctx->hlua[0], reg_flt_to_stack_id(conf->reg), s->task, 0) ||
10548 !hlua_ctx_init(flt_ctx->hlua[1], reg_flt_to_stack_id(conf->reg), s->task, 0)) {
10549 SEND_ERR(s->be, "Lua filter '%s': can't initialize filter Lua context.\n",
10550 conf->reg->name);
10551 ret = 0;
10552 goto end;
10553 }
10554
10555 if (!HLUA_IS_RUNNING(s->hlua)) {
10556 /* The following Lua calls can fail. */
10557 if (!SET_SAFE_LJMP(s->hlua)) {
10558 const char *error;
10559
10560 if (lua_type(s->hlua->T, -1) == LUA_TSTRING)
10561 error = lua_tostring(s->hlua->T, -1);
10562 else
10563 error = "critical error";
10564 SEND_ERR(s->be, "Lua filter '%s': %s.\n", conf->reg->name, error);
10565 ret = 0;
10566 goto end;
10567 }
10568
10569 /* Check stack size. */
10570 if (!lua_checkstack(s->hlua->T, 1)) {
10571 SEND_ERR(s->be, "Lua filter '%s': full stack.\n", conf->reg->name);
Tim Duesterhus22817382021-09-11 23:17:25 +020010572 RESET_SAFE_LJMP(s->hlua);
Christopher Faulet69c581a2021-05-31 08:54:04 +020010573 ret = 0;
10574 goto end;
10575 }
10576
10577 lua_rawgeti(s->hlua->T, LUA_REGISTRYINDEX, conf->ref[s->hlua->state_id]);
10578 if (lua_getfield(s->hlua->T, -1, "new") != LUA_TFUNCTION) {
10579 SEND_ERR(s->be, "Lua filter '%s': 'new' field is not a function.\n",
10580 conf->reg->name);
10581 RESET_SAFE_LJMP(s->hlua);
10582 ret = 0;
10583 goto end;
10584 }
10585 lua_insert(s->hlua->T, -2);
10586
10587 /* Push the copy on the stack */
10588 s->hlua->nargs = 1;
10589
10590 /* We must initialize the execution timeouts. */
10591 s->hlua->max_time = hlua_timeout_session;
10592
10593 /* At this point the execution is safe. */
10594 RESET_SAFE_LJMP(s->hlua);
10595 }
10596
10597 switch (hlua_ctx_resume(s->hlua, 0)) {
10598 case HLUA_E_OK:
10599 /* Nothing returned or not a table, ignore the filter for current stream */
10600 if (!lua_gettop(s->hlua->T) || !lua_istable(s->hlua->T, 1)) {
10601 ret = 0;
10602 goto end;
10603 }
10604
10605 /* Attached the filter pointer to the ctx */
10606 lua_pushstring(s->hlua->T, "__filter");
10607 lua_pushlightuserdata(s->hlua->T, filter);
10608 lua_settable(s->hlua->T, -3);
10609
10610 /* Save a ref on the filter ctx */
10611 lua_pushvalue(s->hlua->T, 1);
10612 flt_ctx->ref = luaL_ref(s->hlua->T, LUA_REGISTRYINDEX);
10613 filter->ctx = flt_ctx;
10614 break;
10615 case HLUA_E_ERRMSG:
10616 SEND_ERR(s->be, "Lua filter '%s' : %s.\n", conf->reg->name, lua_tostring(s->hlua->T, -1));
10617 ret = -1;
10618 goto end;
10619 case HLUA_E_ETMOUT:
10620 SEND_ERR(s->be, "Lua filter '%s' : 'new' execution timeout.\n", conf->reg->name);
10621 ret = 0;
10622 goto end;
10623 case HLUA_E_NOMEM:
10624 SEND_ERR(s->be, "Lua filter '%s' : out of memory error.\n", conf->reg->name);
10625 ret = 0;
10626 goto end;
10627 case HLUA_E_AGAIN:
10628 case HLUA_E_YIELD:
10629 SEND_ERR(s->be, "Lua filter '%s': yield functions like core.tcp() or core.sleep()"
10630 " are not allowed from 'new' function.\n", conf->reg->name);
10631 ret = 0;
10632 goto end;
10633 case HLUA_E_ERR:
10634 SEND_ERR(s->be, "Lua filter '%s': 'new' returns an unknown error.\n", conf->reg->name);
10635 ret = 0;
10636 goto end;
10637 default:
10638 ret = 0;
10639 goto end;
10640 }
10641
10642 end:
10643 if (s->hlua)
10644 lua_settop(s->hlua->T, 0);
10645 if (ret <= 0) {
10646 if (flt_ctx) {
10647 hlua_ctx_destroy(flt_ctx->hlua[0]);
10648 hlua_ctx_destroy(flt_ctx->hlua[1]);
10649 pool_free(pool_head_hlua_flt_ctx, flt_ctx);
10650 }
10651 }
10652 return ret;
10653}
10654
10655static void hlua_filter_delete(struct stream *s, struct filter *filter)
10656{
10657 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10658
10659 luaL_unref(s->hlua->T, LUA_REGISTRYINDEX, flt_ctx->ref);
10660 hlua_ctx_destroy(flt_ctx->hlua[0]);
10661 hlua_ctx_destroy(flt_ctx->hlua[1]);
10662 pool_free(pool_head_hlua_flt_ctx, flt_ctx);
10663 filter->ctx = NULL;
10664}
10665
Christopher Faulet9f55a502020-02-25 15:21:02 +010010666static int hlua_filter_from_payload(struct filter *filter)
10667{
10668 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10669
10670 return (flt_ctx && !!(flt_ctx->flags & HLUA_FLT_CTX_FL_PAYLOAD));
10671}
10672
Christopher Fauletc404f112020-02-26 15:03:09 +010010673static int hlua_filter_callback(struct stream *s, struct filter *filter, const char *fun,
10674 int dir, unsigned int flags)
10675{
10676 struct hlua *flt_hlua;
10677 struct hlua_flt_config *conf = FLT_CONF(filter);
10678 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10679 unsigned int hflags = HLUA_TXN_FLT_CTX;
10680 int ret = 1;
10681
10682 flt_hlua = flt_ctx->hlua[(dir == SMP_OPT_DIR_REQ ? 0 : 1)];
10683 if (!flt_hlua)
10684 goto end;
10685
10686 if (!HLUA_IS_RUNNING(flt_hlua)) {
10687 int extra_idx = lua_gettop(flt_hlua->T);
10688
10689 /* The following Lua calls can fail. */
10690 if (!SET_SAFE_LJMP(flt_hlua)) {
10691 const char *error;
10692
10693 if (lua_type(flt_hlua->T, -1) == LUA_TSTRING)
10694 error = lua_tostring(flt_hlua->T, -1);
10695 else
10696 error = "critical error";
10697 SEND_ERR(s->be, "Lua filter '%s': %s.\n", conf->reg->name, error);
10698 goto end;
10699 }
10700
10701 /* Check stack size. */
10702 if (!lua_checkstack(flt_hlua->T, 3)) {
10703 SEND_ERR(s->be, "Lua filter '%s': full stack.\n", conf->reg->name);
10704 RESET_SAFE_LJMP(flt_hlua);
10705 goto end;
10706 }
10707
10708 lua_rawgeti(flt_hlua->T, LUA_REGISTRYINDEX, flt_ctx->ref);
10709 if (lua_getfield(flt_hlua->T, -1, fun) != LUA_TFUNCTION) {
10710 RESET_SAFE_LJMP(flt_hlua);
10711 goto end;
10712 }
10713 lua_insert(flt_hlua->T, -2);
10714
10715 if (!hlua_txn_new(flt_hlua->T, s, s->be, dir, hflags)) {
10716 SEND_ERR(s->be, "Lua filter '%s': full stack.\n", conf->reg->name);
10717 RESET_SAFE_LJMP(flt_hlua);
10718 goto end;
10719 }
10720 flt_hlua->nargs = 2;
10721
10722 if (flags & HLUA_FLT_CB_ARG_CHN) {
10723 if (dir == SMP_OPT_DIR_REQ)
10724 lua_getfield(flt_hlua->T, -1, "req");
10725 else
10726 lua_getfield(flt_hlua->T, -1, "res");
10727 if (lua_type(flt_hlua->T, -1) == LUA_TTABLE) {
10728 lua_pushstring(flt_hlua->T, "__filter");
10729 lua_pushlightuserdata(flt_hlua->T, filter);
10730 lua_settable(flt_hlua->T, -3);
10731 }
10732 flt_hlua->nargs++;
10733 }
10734 else if (flags & HLUA_FLT_CB_ARG_HTTP_MSG) {
Christopher Fauleteae8afa2020-02-26 17:15:48 +010010735 if (dir == SMP_OPT_DIR_REQ)
10736 lua_getfield(flt_hlua->T, -1, "http_req");
10737 else
10738 lua_getfield(flt_hlua->T, -1, "http_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++;
Christopher Fauletc404f112020-02-26 15:03:09 +010010745 }
10746
10747 /* Check stack size. */
10748 if (!lua_checkstack(flt_hlua->T, 1)) {
10749 SEND_ERR(s->be, "Lua filter '%s': full stack.\n", conf->reg->name);
10750 RESET_SAFE_LJMP(flt_hlua);
10751 goto end;
10752 }
10753
10754 while (extra_idx--) {
10755 lua_pushvalue(flt_hlua->T, 1);
10756 lua_remove(flt_hlua->T, 1);
10757 flt_hlua->nargs++;
10758 }
10759
10760 /* We must initialize the execution timeouts. */
10761 flt_hlua->max_time = hlua_timeout_session;
10762
10763 /* At this point the execution is safe. */
10764 RESET_SAFE_LJMP(flt_hlua);
10765 }
10766
10767 switch (hlua_ctx_resume(flt_hlua, !(flags & HLUA_FLT_CB_FINAL))) {
10768 case HLUA_E_OK:
10769 /* Catch the return value if it required */
10770 if ((flags & HLUA_FLT_CB_RETVAL) && lua_gettop(flt_hlua->T) > 0) {
10771 ret = lua_tointeger(flt_hlua->T, -1);
10772 lua_settop(flt_hlua->T, 0); /* Empty the stack. */
10773 }
10774
10775 /* Set timeout in the required channel. */
10776 if (flt_hlua->wake_time != TICK_ETERNITY) {
10777 if (dir == SMP_OPT_DIR_REQ)
10778 s->req.analyse_exp = flt_hlua->wake_time;
10779 else
10780 s->res.analyse_exp = flt_hlua->wake_time;
10781 }
10782 break;
10783 case HLUA_E_AGAIN:
10784 /* Set timeout in the required channel. */
10785 if (flt_hlua->wake_time != TICK_ETERNITY) {
10786 if (dir == SMP_OPT_DIR_REQ)
10787 s->req.analyse_exp = flt_hlua->wake_time;
10788 else
10789 s->res.analyse_exp = flt_hlua->wake_time;
10790 }
10791 /* Some actions can be wake up when a "write" event
10792 * is detected on a response channel. This is useful
10793 * only for actions targeted on the requests.
10794 */
10795 if (HLUA_IS_WAKERESWR(flt_hlua))
10796 s->res.flags |= CF_WAKE_WRITE;
10797 if (HLUA_IS_WAKEREQWR(flt_hlua))
10798 s->req.flags |= CF_WAKE_WRITE;
10799 ret = 0;
10800 goto end;
10801 case HLUA_E_ERRMSG:
10802 SEND_ERR(s->be, "Lua filter '%s' : %s.\n", conf->reg->name, lua_tostring(flt_hlua->T, -1));
10803 ret = -1;
10804 goto end;
10805 case HLUA_E_ETMOUT:
10806 SEND_ERR(s->be, "Lua filter '%s' : '%s' callback execution timeout.\n", conf->reg->name, fun);
10807 goto end;
10808 case HLUA_E_NOMEM:
10809 SEND_ERR(s->be, "Lua filter '%s' : out of memory error.\n", conf->reg->name);
10810 goto end;
10811 case HLUA_E_YIELD:
10812 SEND_ERR(s->be, "Lua filter '%s': yield functions like core.tcp() or core.sleep()"
10813 " are not allowed from '%s' callback.\n", conf->reg->name, fun);
10814 goto end;
10815 case HLUA_E_ERR:
10816 SEND_ERR(s->be, "Lua filter '%s': '%s' returns an unknown error.\n", conf->reg->name, fun);
10817 goto end;
10818 default:
10819 goto end;
10820 }
10821
10822
10823 end:
10824 return ret;
10825}
10826
10827static int hlua_filter_start_analyze(struct stream *s, struct filter *filter, struct channel *chn)
10828{
10829 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10830
10831 flt_ctx->flags = 0;
10832 return hlua_filter_callback(s, filter, "start_analyze",
10833 (!(chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES),
10834 (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_RETVAL | HLUA_FLT_CB_ARG_CHN));
10835}
10836
10837static int hlua_filter_end_analyze(struct stream *s, struct filter *filter, struct channel *chn)
10838{
10839 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10840
10841 flt_ctx->flags &= ~HLUA_FLT_CTX_FL_PAYLOAD;
10842 return hlua_filter_callback(s, filter, "end_analyze",
10843 (!(chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES),
10844 (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_RETVAL | HLUA_FLT_CB_ARG_CHN));
10845}
10846
Christopher Fauleteae8afa2020-02-26 17:15:48 +010010847static int hlua_filter_http_headers(struct stream *s, struct filter *filter, struct http_msg *msg)
10848{
10849 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10850
10851 flt_ctx->flags &= ~HLUA_FLT_CTX_FL_PAYLOAD;
10852 return hlua_filter_callback(s, filter, "http_headers",
10853 (!(msg->chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES),
10854 (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_RETVAL | HLUA_FLT_CB_ARG_HTTP_MSG));
10855}
10856
10857static int hlua_filter_http_payload(struct stream *s, struct filter *filter, struct http_msg *msg,
10858 unsigned int offset, unsigned int len)
10859{
10860 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10861 struct hlua *flt_hlua;
10862 int dir = (!(msg->chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES);
10863 int idx = (dir == SMP_OPT_DIR_REQ ? 0 : 1);
10864 int ret;
10865
10866 flt_hlua = flt_ctx->hlua[idx];
10867 flt_ctx->cur_off[idx] = offset;
10868 flt_ctx->cur_len[idx] = len;
10869 flt_ctx->flags |= HLUA_FLT_CTX_FL_PAYLOAD;
10870 ret = hlua_filter_callback(s, filter, "http_payload", dir, (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_ARG_HTTP_MSG));
10871 if (ret != -1) {
10872 ret = flt_ctx->cur_len[idx];
10873 if (lua_gettop(flt_hlua->T) > 0) {
10874 ret = lua_tointeger(flt_hlua->T, -1);
10875 if (ret > flt_ctx->cur_len[idx])
10876 ret = flt_ctx->cur_len[idx];
10877 lua_settop(flt_hlua->T, 0); /* Empty the stack. */
10878 }
10879 }
10880 return ret;
10881}
10882
10883static int hlua_filter_http_end(struct stream *s, struct filter *filter, struct http_msg *msg)
10884{
10885 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10886
10887 flt_ctx->flags &= ~HLUA_FLT_CTX_FL_PAYLOAD;
10888 return hlua_filter_callback(s, filter, "http_end",
10889 (!(msg->chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES),
10890 (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_RETVAL | HLUA_FLT_CB_ARG_HTTP_MSG));
10891}
10892
Christopher Fauletc404f112020-02-26 15:03:09 +010010893static int hlua_filter_tcp_payload(struct stream *s, struct filter *filter, struct channel *chn,
10894 unsigned int offset, unsigned int len)
10895{
10896 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10897 struct hlua *flt_hlua;
10898 int dir = (!(chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES);
10899 int idx = (dir == SMP_OPT_DIR_REQ ? 0 : 1);
10900 int ret;
10901
10902 flt_hlua = flt_ctx->hlua[idx];
10903 flt_ctx->cur_off[idx] = offset;
10904 flt_ctx->cur_len[idx] = len;
10905 flt_ctx->flags |= HLUA_FLT_CTX_FL_PAYLOAD;
10906 ret = hlua_filter_callback(s, filter, "tcp_payload", dir, (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_ARG_CHN));
10907 if (ret != -1) {
10908 ret = flt_ctx->cur_len[idx];
10909 if (lua_gettop(flt_hlua->T) > 0) {
10910 ret = lua_tointeger(flt_hlua->T, -1);
10911 if (ret > flt_ctx->cur_len[idx])
10912 ret = flt_ctx->cur_len[idx];
10913 lua_settop(flt_hlua->T, 0); /* Empty the stack. */
10914 }
10915 }
10916 return ret;
10917}
10918
Christopher Faulet69c581a2021-05-31 08:54:04 +020010919static int hlua_filter_parse_fct(char **args, int *cur_arg, struct proxy *px,
10920 struct flt_conf *fconf, char **err, void *private)
10921{
10922 struct hlua_reg_filter *reg_flt = private;
10923 lua_State *L;
10924 struct hlua_flt_config *conf = NULL;
10925 const char *flt_id = NULL;
10926 int state_id, pos, flt_flags = 0;
10927 struct flt_ops *hlua_flt_ops = NULL;
10928
10929 state_id = reg_flt_to_stack_id(reg_flt);
10930 L = hlua_states[state_id];
10931
10932 /* Initialize the filter ops with default callbacks */
10933 hlua_flt_ops = calloc(1, sizeof(*hlua_flt_ops));
Christopher Fauletc86bb872021-08-13 08:33:57 +020010934 if (!hlua_flt_ops)
10935 goto error;
Christopher Faulet69c581a2021-05-31 08:54:04 +020010936 hlua_flt_ops->init = hlua_filter_init;
10937 hlua_flt_ops->deinit = hlua_filter_deinit;
10938 if (state_id) {
10939 /* Set per-thread callback if script is loaded per-thread */
10940 hlua_flt_ops->init_per_thread = hlua_filter_init_per_thread;
10941 hlua_flt_ops->deinit_per_thread = hlua_filter_deinit_per_thread;
10942 }
10943 hlua_flt_ops->attach = hlua_filter_new;
10944 hlua_flt_ops->detach = hlua_filter_delete;
10945
10946 /* Push the filter class on the stack and resolve all callbacks */
10947 lua_rawgeti(L, LUA_REGISTRYINDEX, reg_flt->flt_ref[state_id]);
10948
Christopher Fauletc404f112020-02-26 15:03:09 +010010949 if (lua_getfield(L, -1, "start_analyze") == LUA_TFUNCTION)
10950 hlua_flt_ops->channel_start_analyze = hlua_filter_start_analyze;
10951 lua_pop(L, 1);
10952 if (lua_getfield(L, -1, "end_analyze") == LUA_TFUNCTION)
10953 hlua_flt_ops->channel_end_analyze = hlua_filter_end_analyze;
10954 lua_pop(L, 1);
Christopher Fauleteae8afa2020-02-26 17:15:48 +010010955 if (lua_getfield(L, -1, "http_headers") == LUA_TFUNCTION)
10956 hlua_flt_ops->http_headers = hlua_filter_http_headers;
10957 lua_pop(L, 1);
10958 if (lua_getfield(L, -1, "http_payload") == LUA_TFUNCTION)
10959 hlua_flt_ops->http_payload = hlua_filter_http_payload;
10960 lua_pop(L, 1);
10961 if (lua_getfield(L, -1, "http_end") == LUA_TFUNCTION)
10962 hlua_flt_ops->http_end = hlua_filter_http_end;
10963 lua_pop(L, 1);
Christopher Fauletc404f112020-02-26 15:03:09 +010010964 if (lua_getfield(L, -1, "tcp_payload") == LUA_TFUNCTION)
10965 hlua_flt_ops->tcp_payload = hlua_filter_tcp_payload;
10966 lua_pop(L, 1);
Christopher Faulet69c581a2021-05-31 08:54:04 +020010967
10968 /* Get id and flags of the filter class */
10969 if (lua_getfield(L, -1, "id") == LUA_TSTRING)
10970 flt_id = lua_tostring(L, -1);
10971 lua_pop(L, 1);
10972 if (lua_getfield(L, -1, "flags") == LUA_TNUMBER)
10973 flt_flags = lua_tointeger(L, -1);
10974 lua_pop(L, 1);
10975
10976 /* Create the filter config */
10977 conf = calloc(1, sizeof(*conf));
Christopher Fauletc86bb872021-08-13 08:33:57 +020010978 if (!conf)
Christopher Faulet69c581a2021-05-31 08:54:04 +020010979 goto error;
Christopher Faulet69c581a2021-05-31 08:54:04 +020010980 conf->reg = reg_flt;
10981
10982 /* duplicate args */
10983 for (pos = 0; *args[*cur_arg + 1 + pos]; pos++);
10984 conf->args = calloc(pos + 1, sizeof(*conf->args));
Christopher Fauletc86bb872021-08-13 08:33:57 +020010985 if (!conf->args)
10986 goto error;
10987 for (pos = 0; *args[*cur_arg + 1 + pos]; pos++) {
Christopher Faulet69c581a2021-05-31 08:54:04 +020010988 conf->args[pos] = strdup(args[*cur_arg + 1 + pos]);
Christopher Fauletc86bb872021-08-13 08:33:57 +020010989 if (!conf->args[pos])
10990 goto error;
10991 }
Christopher Faulet69c581a2021-05-31 08:54:04 +020010992 conf->args[pos] = NULL;
10993 *cur_arg += pos + 1;
10994
Christopher Fauletc86bb872021-08-13 08:33:57 +020010995 if (flt_id) {
10996 fconf->id = strdup(flt_id);
10997 if (!fconf->id)
10998 goto error;
10999 }
Christopher Faulet69c581a2021-05-31 08:54:04 +020011000 fconf->flags = flt_flags;
11001 fconf->conf = conf;
11002 fconf->ops = hlua_flt_ops;
11003
11004 lua_settop(L, 0);
11005 return 0;
11006
11007 error:
Christopher Fauletc86bb872021-08-13 08:33:57 +020011008 memprintf(err, "Lua filter '%s' : Lua out of memory error", reg_flt->name);
Christopher Faulet69c581a2021-05-31 08:54:04 +020011009 free(hlua_flt_ops);
Christopher Fauletc86bb872021-08-13 08:33:57 +020011010 if (conf && conf->args) {
11011 for (pos = 0; conf->args[pos]; pos++)
11012 free(conf->args[pos]);
11013 free(conf->args);
11014 }
Christopher Faulet69c581a2021-05-31 08:54:04 +020011015 free(conf);
Christopher Fauletc86bb872021-08-13 08:33:57 +020011016 free((char *)fconf->id);
Christopher Faulet69c581a2021-05-31 08:54:04 +020011017 lua_settop(L, 0);
11018 return -1;
11019}
11020
Christopher Fauletc404f112020-02-26 15:03:09 +010011021__LJMP static int hlua_register_data_filter(lua_State *L)
11022{
11023 struct filter *filter;
11024 struct channel *chn;
11025
11026 MAY_LJMP(check_args(L, 2, "register_data_filter"));
11027 MAY_LJMP(luaL_checktype(L, 1, LUA_TTABLE));
11028 chn = MAY_LJMP(hlua_checkchannel(L, 2));
11029
11030 lua_getfield(L, 1, "__filter");
11031 MAY_LJMP(luaL_checktype(L, -1, LUA_TLIGHTUSERDATA));
11032 filter = lua_touserdata (L, -1);
11033 lua_pop(L, 1);
11034
11035 register_data_filter(chn_strm(chn), chn, filter);
11036 return 1;
11037}
11038
11039__LJMP static int hlua_unregister_data_filter(lua_State *L)
11040{
11041 struct filter *filter;
11042 struct channel *chn;
11043
11044 MAY_LJMP(check_args(L, 2, "unregister_data_filter"));
11045 MAY_LJMP(luaL_checktype(L, 1, LUA_TTABLE));
11046 chn = MAY_LJMP(hlua_checkchannel(L, 2));
11047
11048 lua_getfield(L, 1, "__filter");
11049 MAY_LJMP(luaL_checktype(L, -1, LUA_TLIGHTUSERDATA));
11050 filter = lua_touserdata (L, -1);
11051 lua_pop(L, 1);
11052
11053 unregister_data_filter(chn_strm(chn), chn, filter);
11054 return 1;
11055}
11056
Christopher Faulet69c581a2021-05-31 08:54:04 +020011057/* This function is an LUA binding used for registering a filter. It expects a
Ilya Shipitsinff0f2782021-08-22 22:18:07 +050011058 * filter name used in the haproxy configuration file and a LUA function to
Christopher Faulet69c581a2021-05-31 08:54:04 +020011059 * parse configuration arguments.
11060 */
11061__LJMP static int hlua_register_filter(lua_State *L)
11062{
11063 struct buffer *trash;
11064 struct flt_kw_list *fkl;
11065 struct flt_kw *fkw;
11066 const char *name;
11067 struct hlua_reg_filter *reg_flt= NULL;
11068 int flt_ref, fun_ref;
11069 int len;
11070
11071 MAY_LJMP(check_args(L, 3, "register_filter"));
11072
11073 /* First argument : filter name. */
11074 name = MAY_LJMP(luaL_checkstring(L, 1));
11075
11076 /* Second argument : The filter class */
11077 flt_ref = MAY_LJMP(hlua_checktable(L, 2));
11078
11079 /* Third argument : lua function. */
11080 fun_ref = MAY_LJMP(hlua_checkfunction(L, 3));
11081
11082 trash = get_trash_chunk();
11083 chunk_printf(trash, "lua.%s", name);
11084 fkw = flt_find_kw(trash->area);
11085 if (fkw != NULL) {
11086 reg_flt = fkw->private;
11087 if (reg_flt->flt_ref[hlua_state_id] != -1 || reg_flt->fun_ref[hlua_state_id] != -1) {
11088 ha_warning("Trying to register filter 'lua.%s' more than once. "
11089 "This will become a hard error in version 2.5.\n", name);
11090 }
11091 reg_flt->flt_ref[hlua_state_id] = flt_ref;
11092 reg_flt->fun_ref[hlua_state_id] = fun_ref;
11093 return 0;
11094 }
11095
11096 fkl = calloc(1, sizeof(*fkl) + sizeof(struct flt_kw) * 2);
11097 if (!fkl)
11098 goto alloc_error;
11099 fkl->scope = "HLUA";
11100
11101 reg_flt = new_hlua_reg_filter(name);
11102 if (!reg_flt)
11103 goto alloc_error;
11104
11105 reg_flt->flt_ref[hlua_state_id] = flt_ref;
11106 reg_flt->fun_ref[hlua_state_id] = fun_ref;
11107
11108 /* The filter keyword */
11109 len = strlen("lua.") + strlen(name) + 1;
11110 fkl->kw[0].kw = calloc(1, len);
11111 if (!fkl->kw[0].kw)
11112 goto alloc_error;
11113
11114 snprintf((char *)fkl->kw[0].kw, len, "lua.%s", name);
11115
11116 fkl->kw[0].parse = hlua_filter_parse_fct;
11117 fkl->kw[0].private = reg_flt;
11118 memset(&fkl->kw[1], 0, sizeof(*fkl->kw));
11119
11120 /* Register this new filter */
11121 flt_register_keywords(fkl);
11122
11123 return 0;
11124
11125 alloc_error:
11126 release_hlua_reg_filter(reg_flt);
11127 ha_free(&fkl);
11128 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
11129 return 0; /* Never reached */
11130}
11131
Thierry FOURNIERbd413492015-03-03 16:52:26 +010011132static int hlua_read_timeout(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011133 const struct proxy *defpx, const char *file, int line,
Thierry FOURNIERbd413492015-03-03 16:52:26 +010011134 char **err, unsigned int *timeout)
11135{
11136 const char *error;
11137
11138 error = parse_time_err(args[1], timeout, TIME_UNIT_MS);
Willy Tarreau9faebe32019-06-07 19:00:37 +020011139 if (error == PARSE_TIME_OVER) {
11140 memprintf(err, "timer overflow in argument <%s> to <%s> (maximum value is 2147483647 ms or ~24.8 days)",
11141 args[1], args[0]);
11142 return -1;
11143 }
11144 else if (error == PARSE_TIME_UNDER) {
11145 memprintf(err, "timer underflow in argument <%s> to <%s> (minimum non-null value is 1 ms)",
11146 args[1], args[0]);
11147 return -1;
11148 }
11149 else if (error) {
Thierry FOURNIERbd413492015-03-03 16:52:26 +010011150 memprintf(err, "%s: invalid timeout", args[0]);
11151 return -1;
11152 }
11153 return 0;
11154}
11155
11156static int hlua_session_timeout(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011157 const struct proxy *defpx, const char *file, int line,
Thierry FOURNIERbd413492015-03-03 16:52:26 +010011158 char **err)
11159{
11160 return hlua_read_timeout(args, section_type, curpx, defpx,
11161 file, line, err, &hlua_timeout_session);
11162}
11163
11164static int hlua_task_timeout(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011165 const struct proxy *defpx, const char *file, int line,
Thierry FOURNIERbd413492015-03-03 16:52:26 +010011166 char **err)
11167{
11168 return hlua_read_timeout(args, section_type, curpx, defpx,
11169 file, line, err, &hlua_timeout_task);
11170}
11171
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020011172static int hlua_applet_timeout(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011173 const struct proxy *defpx, const char *file, int line,
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020011174 char **err)
11175{
11176 return hlua_read_timeout(args, section_type, curpx, defpx,
11177 file, line, err, &hlua_timeout_applet);
11178}
11179
Thierry FOURNIERee9f8022015-03-03 17:37:37 +010011180static int hlua_forced_yield(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011181 const struct proxy *defpx, const char *file, int line,
Thierry FOURNIERee9f8022015-03-03 17:37:37 +010011182 char **err)
11183{
11184 char *error;
11185
11186 hlua_nb_instruction = strtoll(args[1], &error, 10);
11187 if (*error != '\0') {
11188 memprintf(err, "%s: invalid number", args[0]);
11189 return -1;
11190 }
11191 return 0;
11192}
11193
Willy Tarreau32f61e22015-03-18 17:54:59 +010011194static int hlua_parse_maxmem(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011195 const struct proxy *defpx, const char *file, int line,
Willy Tarreau32f61e22015-03-18 17:54:59 +010011196 char **err)
11197{
11198 char *error;
11199
11200 if (*(args[1]) == 0) {
11201 memprintf(err, "'%s' expects an integer argument (Lua memory size in MB).\n", args[0]);
11202 return -1;
11203 }
11204 hlua_global_allocator.limit = strtoll(args[1], &error, 10) * 1024L * 1024L;
11205 if (*error != '\0') {
11206 memprintf(err, "%s: invalid number %s (error at '%c')", args[0], args[1], *error);
11207 return -1;
11208 }
11209 return 0;
11210}
11211
11212
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011213/* This function is called by the main configuration key "lua-load". It loads and
11214 * execute an lua file during the parsing of the HAProxy configuration file. It is
11215 * the main lua entry point.
11216 *
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -080011217 * This function runs with the HAProxy keywords API. It returns -1 if an error
11218 * occurs, otherwise it returns 0.
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011219 *
11220 * In some error case, LUA set an error message in top of the stack. This function
11221 * returns this error message in the HAProxy logs and pop it from the stack.
Thierry FOURNIERbabae282015-09-17 11:36:37 +020011222 *
11223 * This function can fail with an abort() due to an Lua critical error.
11224 * We are in the configuration parsing process of HAProxy, this abort() is
11225 * tolerated.
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011226 */
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011227static int hlua_load_state(char *filename, lua_State *L, char **err)
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011228{
11229 int error;
11230
11231 /* Just load and compile the file. */
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011232 error = luaL_loadfile(L, filename);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011233 if (error) {
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011234 memprintf(err, "error in Lua file '%s': %s", filename, lua_tostring(L, -1));
11235 lua_pop(L, 1);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011236 return -1;
11237 }
11238
11239 /* If no syntax error where detected, execute the code. */
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011240 error = lua_pcall(L, 0, LUA_MULTRET, 0);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011241 switch (error) {
11242 case LUA_OK:
11243 break;
11244 case LUA_ERRRUN:
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011245 memprintf(err, "Lua runtime error: %s\n", lua_tostring(L, -1));
11246 lua_pop(L, 1);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011247 return -1;
11248 case LUA_ERRMEM:
Thierry Fournierde6145f2020-11-29 00:55:53 +010011249 memprintf(err, "Lua out of memory error\n");
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011250 return -1;
11251 case LUA_ERRERR:
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011252 memprintf(err, "Lua message handler error: %s\n", lua_tostring(L, -1));
11253 lua_pop(L, 1);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011254 return -1;
Christopher Faulet08ed98f2020-07-28 10:33:25 +020011255#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM <= 503
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011256 case LUA_ERRGCMM:
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011257 memprintf(err, "Lua garbage collector error: %s\n", lua_tostring(L, -1));
11258 lua_pop(L, 1);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011259 return -1;
Christopher Faulet08ed98f2020-07-28 10:33:25 +020011260#endif
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011261 default:
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011262 memprintf(err, "Lua unknown error: %s\n", lua_tostring(L, -1));
11263 lua_pop(L, 1);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011264 return -1;
11265 }
11266
11267 return 0;
11268}
11269
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011270static int hlua_load(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011271 const struct proxy *defpx, const char *file, int line,
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011272 char **err)
11273{
11274 if (*(args[1]) == 0) {
11275 memprintf(err, "'%s' expects a file name as parameter.\n", args[0]);
11276 return -1;
11277 }
11278
Thierry Fournier59f11be2020-11-29 00:37:41 +010011279 /* loading for global state */
Thierry Fournierc7492592020-11-28 23:57:24 +010011280 hlua_state_id = 0;
Willy Tarreau43ab05b2021-09-28 09:43:11 +020011281 ha_set_thread(NULL);
Thierry Fournierafc63e22020-11-28 17:06:51 +010011282 return hlua_load_state(args[1], hlua_states[0], err);
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011283}
11284
Thierry Fournier59f11be2020-11-29 00:37:41 +010011285static int hlua_load_per_thread(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011286 const struct proxy *defpx, const char *file, int line,
Thierry Fournier59f11be2020-11-29 00:37:41 +010011287 char **err)
11288{
11289 int len;
11290
11291 if (*(args[1]) == 0) {
11292 memprintf(err, "'%s' expects a file as parameter.\n", args[0]);
11293 return -1;
11294 }
11295
11296 if (per_thread_load == NULL) {
11297 /* allocate the first entry large enough to store the final NULL */
11298 per_thread_load = calloc(1, sizeof(*per_thread_load));
11299 if (per_thread_load == NULL) {
11300 memprintf(err, "out of memory error");
11301 return -1;
11302 }
11303 }
11304
11305 /* count used entries */
11306 for (len = 0; per_thread_load[len] != NULL; len++)
11307 ;
11308
11309 per_thread_load = realloc(per_thread_load, (len + 2) * sizeof(*per_thread_load));
11310 if (per_thread_load == NULL) {
11311 memprintf(err, "out of memory error");
11312 return -1;
11313 }
11314
11315 per_thread_load[len] = strdup(args[1]);
11316 per_thread_load[len + 1] = NULL;
11317
11318 if (per_thread_load[len] == NULL) {
11319 memprintf(err, "out of memory error");
11320 return -1;
11321 }
11322
11323 /* loading for thread 1 only */
11324 hlua_state_id = 1;
Willy Tarreau43ab05b2021-09-28 09:43:11 +020011325 ha_set_thread(NULL);
Thierry Fournier59f11be2020-11-29 00:37:41 +010011326 return hlua_load_state(args[1], hlua_states[1], err);
11327}
11328
Tim Duesterhusc9fc9f22020-01-12 13:55:39 +010011329/* Prepend the given <path> followed by a semicolon to the `package.<type>` variable
11330 * in the given <ctx>.
11331 */
Thierry Fournier3fb9e512020-11-28 10:13:12 +010011332static int hlua_prepend_path(lua_State *L, char *type, char *path)
Tim Duesterhusc9fc9f22020-01-12 13:55:39 +010011333{
Thierry Fournier3fb9e512020-11-28 10:13:12 +010011334 lua_getglobal(L, "package"); /* push package variable */
11335 lua_pushstring(L, path); /* push given path */
11336 lua_pushstring(L, ";"); /* push semicolon */
11337 lua_getfield(L, -3, type); /* push old path */
11338 lua_concat(L, 3); /* concatenate to new path */
11339 lua_setfield(L, -2, type); /* store new path */
11340 lua_pop(L, 1); /* pop package variable */
Tim Duesterhusc9fc9f22020-01-12 13:55:39 +010011341
11342 return 0;
11343}
11344
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010011345static int hlua_config_prepend_path(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011346 const struct proxy *defpx, const char *file, int line,
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010011347 char **err)
11348{
11349 char *path;
11350 char *type = "path";
Tim Duesterhus621e74a2021-01-03 20:04:36 +010011351 struct prepend_path *p = NULL;
Bertrand Jacquin7fbc7702021-11-24 21:16:06 +000011352 size_t i;
Thierry Fournier59f11be2020-11-29 00:37:41 +010011353
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010011354 if (too_many_args(2, args, err, NULL)) {
Tim Duesterhus621e74a2021-01-03 20:04:36 +010011355 goto err;
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010011356 }
11357
11358 if (!(*args[1])) {
11359 memprintf(err, "'%s' expects to receive a <path> as argument", args[0]);
Tim Duesterhus621e74a2021-01-03 20:04:36 +010011360 goto err;
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010011361 }
11362 path = args[1];
11363
11364 if (*args[2]) {
11365 if (strcmp(args[2], "path") != 0 && strcmp(args[2], "cpath") != 0) {
11366 memprintf(err, "'%s' expects <type> to either be 'path' or 'cpath'", args[0]);
Tim Duesterhus621e74a2021-01-03 20:04:36 +010011367 goto err;
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010011368 }
11369 type = args[2];
11370 }
11371
Thierry Fournier59f11be2020-11-29 00:37:41 +010011372 p = calloc(1, sizeof(*p));
11373 if (p == NULL) {
Tim Duesterhusf89d43a2021-01-03 20:04:37 +010011374 memprintf(err, "memory allocation failed");
Tim Duesterhus621e74a2021-01-03 20:04:36 +010011375 goto err;
Thierry Fournier59f11be2020-11-29 00:37:41 +010011376 }
11377 p->path = strdup(path);
11378 if (p->path == NULL) {
Tim Duesterhusf89d43a2021-01-03 20:04:37 +010011379 memprintf(err, "memory allocation failed");
Tim Duesterhus621e74a2021-01-03 20:04:36 +010011380 goto err2;
Thierry Fournier59f11be2020-11-29 00:37:41 +010011381 }
11382 p->type = strdup(type);
11383 if (p->type == NULL) {
Tim Duesterhusf89d43a2021-01-03 20:04:37 +010011384 memprintf(err, "memory allocation failed");
Tim Duesterhus621e74a2021-01-03 20:04:36 +010011385 goto err2;
Thierry Fournier59f11be2020-11-29 00:37:41 +010011386 }
Willy Tarreau2b718102021-04-21 07:32:39 +020011387 LIST_APPEND(&prepend_path_list, &p->l);
Thierry Fournier59f11be2020-11-29 00:37:41 +010011388
Tim Duesterhus9e5e5862021-10-11 18:51:08 +020011389 /* Handle the global state and the per-thread state for the first
11390 * thread. The remaining threads will be initialized based on
11391 * prepend_path_list.
11392 */
Bertrand Jacquin7fbc7702021-11-24 21:16:06 +000011393 for (i = 0; i < 2; i++) {
Tim Duesterhus9e5e5862021-10-11 18:51:08 +020011394 lua_State *L = hlua_states[i];
11395 const char *error;
11396
11397 if (setjmp(safe_ljmp_env) != 0) {
11398 lua_atpanic(L, hlua_panic_safe);
11399 if (lua_type(L, -1) == LUA_TSTRING)
11400 error = lua_tostring(L, -1);
11401 else
11402 error = "critical error";
11403 fprintf(stderr, "lua-prepend-path: %s.\n", error);
11404 exit(1);
11405 } else {
11406 lua_atpanic(L, hlua_panic_ljmp);
11407 }
11408
11409 hlua_prepend_path(L, type, path);
11410
11411 lua_atpanic(L, hlua_panic_safe);
11412 }
11413
Thierry Fournier59f11be2020-11-29 00:37:41 +010011414 return 0;
Tim Duesterhus621e74a2021-01-03 20:04:36 +010011415
11416err2:
11417 free(p->type);
11418 free(p->path);
11419err:
11420 free(p);
11421 return -1;
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010011422}
11423
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011424/* configuration keywords declaration */
11425static struct cfg_kw_list cfg_kws = {{ },{
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010011426 { CFG_GLOBAL, "lua-prepend-path", hlua_config_prepend_path },
Thierry FOURNIERbd413492015-03-03 16:52:26 +010011427 { CFG_GLOBAL, "lua-load", hlua_load },
Thierry Fournier59f11be2020-11-29 00:37:41 +010011428 { CFG_GLOBAL, "lua-load-per-thread", hlua_load_per_thread },
Thierry FOURNIERbd413492015-03-03 16:52:26 +010011429 { CFG_GLOBAL, "tune.lua.session-timeout", hlua_session_timeout },
11430 { CFG_GLOBAL, "tune.lua.task-timeout", hlua_task_timeout },
Thierry FOURNIER56da1012015-10-01 08:42:31 +020011431 { CFG_GLOBAL, "tune.lua.service-timeout", hlua_applet_timeout },
Thierry FOURNIERee9f8022015-03-03 17:37:37 +010011432 { CFG_GLOBAL, "tune.lua.forced-yield", hlua_forced_yield },
Willy Tarreau32f61e22015-03-18 17:54:59 +010011433 { CFG_GLOBAL, "tune.lua.maxmem", hlua_parse_maxmem },
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011434 { 0, NULL, NULL },
11435}};
11436
Willy Tarreau0108d902018-11-25 19:14:37 +010011437INITCALL1(STG_REGISTER, cfg_register_keywords, &cfg_kws);
11438
William Lallemand52139182022-03-30 15:05:42 +020011439#ifdef USE_OPENSSL
Christopher Fauletafd8f102018-11-08 11:34:21 +010011440
William Lallemand30fcca12022-03-30 12:03:12 +020011441/*
11442 * This function replace a ckch_store by another one, and rebuild the ckch_inst and all its dependencies.
11443 * It does the sam as "cli_io_handler_commit_cert" but for lua, the major
11444 * difference is that the yield in lua and for the CLI is not handled the same
11445 * way.
11446 */
11447__LJMP static int hlua_ckch_commit_yield(lua_State *L, int status, lua_KContext ctx)
11448{
11449 struct ckch_inst **lua_ckchi = lua_touserdata(L, -1);
11450 struct ckch_store **lua_ckchs = lua_touserdata(L, -2);
11451 struct ckch_inst *ckchi = *lua_ckchi;
11452 struct ckch_store *old_ckchs = lua_ckchs[0];
11453 struct ckch_store *new_ckchs = lua_ckchs[1];
11454 struct hlua *hlua;
11455 char *err = NULL;
11456 int y = 1;
11457
11458 hlua = hlua_gethlua(L);
11459
11460 /* get the first ckchi to copy */
11461 if (ckchi == NULL)
11462 ckchi = LIST_ELEM(old_ckchs->ckch_inst.n, typeof(ckchi), by_ckchs);
11463
11464 /* walk through the old ckch_inst and creates new ckch_inst using the updated ckchs */
11465 list_for_each_entry_from(ckchi, &old_ckchs->ckch_inst, by_ckchs) {
11466 struct ckch_inst *new_inst;
11467
11468 /* it takes a lot of CPU to creates SSL_CTXs, so we yield every 10 CKCH instances */
11469 if (y % 10 == 0) {
11470
11471 *lua_ckchi = ckchi;
11472
11473 task_wakeup(hlua->task, TASK_WOKEN_MSG);
11474 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_ckch_commit_yield, TICK_ETERNITY, 0));
11475 }
11476
11477 if (ckch_inst_rebuild(new_ckchs, ckchi, &new_inst, &err))
11478 goto error;
11479
11480 /* link the new ckch_inst to the duplicate */
11481 LIST_APPEND(&new_ckchs->ckch_inst, &new_inst->by_ckchs);
11482 y++;
11483 }
11484
11485 /* The generation is finished, we can insert everything */
11486 ckch_store_replace(old_ckchs, new_ckchs);
11487
11488 lua_pop(L, 2); /* pop the lua_ckchs and ckchi */
11489
11490 HA_SPIN_UNLOCK(CKCH_LOCK, &ckch_lock);
11491
11492 return 0;
11493
11494error:
11495 ckch_store_free(new_ckchs);
11496 HA_SPIN_UNLOCK(CKCH_LOCK, &ckch_lock);
11497 WILL_LJMP(luaL_error(L, "%s", err));
11498 free(err);
11499
11500 return 0;
11501}
11502
11503/*
11504 * Replace a ckch_store <filename> in the ckchs_tree with a ckch_store created
11505 * from the table in parameter.
11506 *
11507 * This is equivalent to "set ssl cert" + "commit ssl cert" over the CLI, which
11508 * means it does not need to have a transaction since everything is done in the
11509 * same function.
11510 *
11511 * CertCache.set{filename="", crt="", key="", sctl="", ocsp="", issuer=""}
11512 *
11513 */
11514__LJMP static int hlua_ckch_set(lua_State *L)
11515{
11516 struct hlua *hlua;
11517 struct ckch_inst **lua_ckchi;
11518 struct ckch_store **lua_ckchs;
11519 struct ckch_store *old_ckchs = NULL;
11520 struct ckch_store *new_ckchs = NULL;
11521 int errcode = 0;
11522 char *err = NULL;
11523 struct cert_exts *cert_ext = NULL;
11524 char *filename;
11525 struct cert_key_and_chain *ckch;
11526 int ret;
11527
11528 if (lua_type(L, -1) != LUA_TTABLE)
11529 WILL_LJMP(luaL_error(L, "'CertCache.set' needs a table as argument"));
11530
11531 hlua = hlua_gethlua(L);
11532
11533 /* FIXME: this should not return an error but should come back later */
11534 if (HA_SPIN_TRYLOCK(CKCH_LOCK, &ckch_lock))
11535 WILL_LJMP(luaL_error(L, "CertCache already under lock"));
11536
11537 ret = lua_getfield(L, -1, "filename");
11538 if (ret != LUA_TSTRING) {
11539 memprintf(&err, "%sNo filename specified!\n", err ? err : "");
11540 errcode |= ERR_ALERT | ERR_FATAL;
11541 goto end;
11542 }
11543 filename = (char *)lua_tostring(L, -1);
11544
11545
11546 /* look for the filename in the tree */
11547 old_ckchs = ckchs_lookup(filename);
11548 if (!old_ckchs) {
11549 memprintf(&err, "%sCan't replace a certificate which is not referenced by the configuration!\n", err ? err : "");
11550 errcode |= ERR_ALERT | ERR_FATAL;
11551 goto end;
11552 }
11553 /* TODO: handle extra_files_noext */
11554
11555 new_ckchs = ckchs_dup(old_ckchs);
11556 if (!new_ckchs) {
11557 memprintf(&err, "%sCannot allocate memory!\n", err ? err : "");
11558 errcode |= ERR_ALERT | ERR_FATAL;
11559 goto end;
11560 }
11561
11562 ckch = new_ckchs->ckch;
11563
11564 /* loop on the field in the table, which have the same name as the
11565 * possible extensions of files */
11566 lua_pushnil(L);
11567 while (lua_next(L, 1)) {
11568 int i;
11569 const char *field = lua_tostring(L, -2);
11570 char *payload = (char *)lua_tostring(L, -1);
11571
11572 if (!field || strcmp(field, "filename") == 0) {
11573 lua_pop(L, 1);
11574 continue;
11575 }
11576
11577 for (i = 0; field && cert_exts[i].ext != NULL; i++) {
11578 if (strcmp(field, cert_exts[i].ext) == 0) {
11579 cert_ext = &cert_exts[i];
11580 break;
11581 }
11582 }
11583
11584 /* this is the default type, the field is not supported */
11585 if (cert_ext == NULL) {
11586 memprintf(&err, "%sUnsupported field '%s'\n", err ? err : "", field);
11587 errcode |= ERR_ALERT | ERR_FATAL;
11588 goto end;
11589 }
11590
11591 /* appply the change on the duplicate */
11592 if (cert_exts->load(filename, payload, ckch, &err) != 0) {
11593 memprintf(&err, "%sCan't load the payload\n", err ? err : "");
11594 errcode |= ERR_ALERT | ERR_FATAL;
11595 goto end;
11596 }
11597 lua_pop(L, 1);
11598 }
11599
11600 /* store the pointers on the lua stack */
11601 lua_ckchs = lua_newuserdata(L, sizeof(struct ckch_store *) * 2);
11602 lua_ckchs[0] = old_ckchs;
11603 lua_ckchs[1] = new_ckchs;
11604 lua_ckchi = lua_newuserdata(L, sizeof(struct ckch_inst *));
11605 *lua_ckchi = NULL;
11606
11607 task_wakeup(hlua->task, TASK_WOKEN_MSG);
11608 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_ckch_commit_yield, TICK_ETERNITY, 0));
11609
11610end:
11611 HA_SPIN_UNLOCK(CKCH_LOCK, &ckch_lock);
11612
11613 if (errcode & ERR_CODE) {
11614 ckch_store_free(new_ckchs);
11615 WILL_LJMP(luaL_error(L, "%s", err));
11616 }
11617 free(err);
11618
11619 return 0;
11620}
11621
William Lallemand52139182022-03-30 15:05:42 +020011622#else
11623
11624__LJMP static int hlua_ckch_set(lua_State *L)
11625{
11626 WILL_LJMP(luaL_error(L, "'CertCache.set' needs an HAProxy built with OpenSSL"));
11627
11628 return 0;
11629}
11630#endif /* ! USE_OPENSSL */
11631
11632
11633
Thierry FOURNIERbabae282015-09-17 11:36:37 +020011634/* This function can fail with an abort() due to an Lua critical error.
11635 * We are in the initialisation process of HAProxy, this abort() is
11636 * tolerated.
11637 */
Thierry Fournierb8cef172020-11-28 15:37:17 +010011638int hlua_post_init_state(lua_State *L)
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010011639{
11640 struct hlua_init_function *init;
11641 const char *msg;
11642 enum hlua_exec ret;
Thierry Fournierfd107a22016-02-19 19:57:23 +010011643 const char *error;
Thierry Fournier670db242020-11-28 10:49:59 +010011644 const char *kind;
11645 const char *trace;
11646 int return_status = 1;
11647#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM >= 504
11648 int nres;
11649#endif
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010011650
Willy Tarreaucdb53462020-12-02 12:12:00 +010011651 /* disable memory limit checks if limit is not set */
11652 if (!hlua_global_allocator.limit)
11653 hlua_global_allocator.limit = ~hlua_global_allocator.limit;
11654
Ilya Shipitsin856aabc2020-04-16 23:51:34 +050011655 /* Call post initialisation function in safe environment. */
Thierry Fournier3c539322020-11-28 16:05:05 +010011656 if (setjmp(safe_ljmp_env) != 0) {
11657 lua_atpanic(L, hlua_panic_safe);
Thierry Fournierb8cef172020-11-28 15:37:17 +010011658 if (lua_type(L, -1) == LUA_TSTRING)
11659 error = lua_tostring(L, -1);
Thierry Fournier3d4a6752016-02-19 20:53:30 +010011660 else
11661 error = "critical error";
11662 fprintf(stderr, "Lua post-init: %s.\n", error);
11663 exit(1);
Thierry Fournier3c539322020-11-28 16:05:05 +010011664 } else {
11665 lua_atpanic(L, hlua_panic_ljmp);
Thierry Fournier3d4a6752016-02-19 20:53:30 +010011666 }
Frédéric Lécaille54f2bcf2018-08-29 13:46:24 +020011667
Thierry Fournierb8cef172020-11-28 15:37:17 +010011668 hlua_fcn_post_init(L);
Thierry Fournier3d4a6752016-02-19 20:53:30 +010011669
Thierry Fournierc7492592020-11-28 23:57:24 +010011670 list_for_each_entry(init, &hlua_init_functions[hlua_state_id], l) {
Thierry Fournierb8cef172020-11-28 15:37:17 +010011671 lua_rawgeti(L, LUA_REGISTRYINDEX, init->function_ref);
Thierry Fournier670db242020-11-28 10:49:59 +010011672
11673#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM >= 504
Thierry Fournierb8cef172020-11-28 15:37:17 +010011674 ret = lua_resume(L, L, 0, &nres);
Thierry Fournier670db242020-11-28 10:49:59 +010011675#else
Thierry Fournierb8cef172020-11-28 15:37:17 +010011676 ret = lua_resume(L, L, 0);
Thierry Fournier670db242020-11-28 10:49:59 +010011677#endif
11678 kind = NULL;
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010011679 switch (ret) {
Thierry Fournier670db242020-11-28 10:49:59 +010011680
11681 case LUA_OK:
Thierry Fournierb8cef172020-11-28 15:37:17 +010011682 lua_pop(L, -1);
Thierry Fournier13d08b72020-11-28 11:02:58 +010011683 break;
Thierry Fournier670db242020-11-28 10:49:59 +010011684
11685 case LUA_ERRERR:
11686 kind = "message handler error";
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -070011687 /* Fall through */
Thierry Fournier670db242020-11-28 10:49:59 +010011688 case LUA_ERRRUN:
11689 if (!kind)
11690 kind = "runtime error";
Thierry Fournierb8cef172020-11-28 15:37:17 +010011691 msg = lua_tostring(L, -1);
11692 lua_settop(L, 0); /* Empty the stack. */
11693 lua_pop(L, 1);
Christopher Fauletd09cc512021-03-24 14:48:45 +010011694 trace = hlua_traceback(L, ", ");
Thierry Fournier670db242020-11-28 10:49:59 +010011695 if (msg)
11696 ha_alert("Lua init: %s: '%s' from %s\n", kind, msg, trace);
11697 else
11698 ha_alert("Lua init: unknown %s from %s\n", kind, trace);
11699 return_status = 0;
11700 break;
11701
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010011702 default:
Thierry Fournier670db242020-11-28 10:49:59 +010011703 /* Unknown error */
11704 kind = "Unknown error";
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -070011705 /* Fall through */
Thierry Fournier670db242020-11-28 10:49:59 +010011706 case LUA_YIELD:
11707 /* yield is not configured at this step, this state doesn't happen */
11708 if (!kind)
11709 kind = "yield not allowed";
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -070011710 /* Fall through */
Thierry Fournier670db242020-11-28 10:49:59 +010011711 case LUA_ERRMEM:
11712 if (!kind)
11713 kind = "out of memory error";
Thierry Fournierb8cef172020-11-28 15:37:17 +010011714 lua_settop(L, 0);
11715 lua_pop(L, 1);
Christopher Fauletd09cc512021-03-24 14:48:45 +010011716 trace = hlua_traceback(L, ", ");
Thierry Fournier670db242020-11-28 10:49:59 +010011717 ha_alert("Lua init: %s: %s\n", kind, trace);
11718 return_status = 0;
11719 break;
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010011720 }
Thierry Fournier670db242020-11-28 10:49:59 +010011721 if (!return_status)
11722 break;
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010011723 }
Thierry Fournier3c539322020-11-28 16:05:05 +010011724
11725 lua_atpanic(L, hlua_panic_safe);
Thierry Fournier670db242020-11-28 10:49:59 +010011726 return return_status;
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010011727}
11728
Thierry Fournierb8cef172020-11-28 15:37:17 +010011729int hlua_post_init()
11730{
Thierry Fournier59f11be2020-11-29 00:37:41 +010011731 int ret;
11732 int i;
11733 int errors;
11734 char *err = NULL;
11735 struct hlua_function *fcn;
Christopher Faulet69c581a2021-05-31 08:54:04 +020011736 struct hlua_reg_filter *reg_flt;
Thierry Fournier59f11be2020-11-29 00:37:41 +010011737
Willy Tarreaub1310492021-08-30 09:35:18 +020011738#if defined(USE_OPENSSL)
Thierry Fournierb8cef172020-11-28 15:37:17 +010011739 /* Initialize SSL server. */
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010011740 if (socket_ssl->xprt->prepare_srv) {
Thierry Fournierb8cef172020-11-28 15:37:17 +010011741 int saved_used_backed = global.ssl_used_backend;
11742 // don't affect maxconn automatic computation
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010011743 socket_ssl->xprt->prepare_srv(socket_ssl);
Thierry Fournierb8cef172020-11-28 15:37:17 +010011744 global.ssl_used_backend = saved_used_backed;
11745 }
11746#endif
11747
Thierry Fournierc7492592020-11-28 23:57:24 +010011748 /* Perform post init of common thread */
11749 hlua_state_id = 0;
Willy Tarreau43ab05b2021-09-28 09:43:11 +020011750 ha_set_thread(&ha_thread_info[0]);
Thierry Fournier59f11be2020-11-29 00:37:41 +010011751 ret = hlua_post_init_state(hlua_states[hlua_state_id]);
11752 if (ret == 0)
11753 return 0;
11754
11755 /* init remaining lua states and load files */
11756 for (hlua_state_id = 2; hlua_state_id < global.nbthread + 1; hlua_state_id++) {
11757
11758 /* set thread context */
Willy Tarreau43ab05b2021-09-28 09:43:11 +020011759 ha_set_thread(&ha_thread_info[hlua_state_id - 1]);
Thierry Fournier59f11be2020-11-29 00:37:41 +010011760
11761 /* Init lua state */
11762 hlua_states[hlua_state_id] = hlua_init_state(hlua_state_id);
11763
11764 /* Load lua files */
11765 for (i = 0; per_thread_load && per_thread_load[i]; i++) {
11766 ret = hlua_load_state(per_thread_load[i], hlua_states[hlua_state_id], &err);
11767 if (ret != 0) {
11768 ha_alert("Lua init: %s\n", err);
11769 return 0;
11770 }
11771 }
11772 }
11773
11774 /* Reset thread context */
Willy Tarreau43ab05b2021-09-28 09:43:11 +020011775 ha_set_thread(NULL);
Thierry Fournier59f11be2020-11-29 00:37:41 +010011776
11777 /* Execute post init for all states */
11778 for (hlua_state_id = 1; hlua_state_id < global.nbthread + 1; hlua_state_id++) {
11779
11780 /* set thread context */
Willy Tarreau43ab05b2021-09-28 09:43:11 +020011781 ha_set_thread(&ha_thread_info[hlua_state_id - 1]);
Thierry Fournier59f11be2020-11-29 00:37:41 +010011782
11783 /* run post init */
11784 ret = hlua_post_init_state(hlua_states[hlua_state_id]);
11785 if (ret == 0)
11786 return 0;
11787 }
11788
11789 /* Reset thread context */
Willy Tarreau43ab05b2021-09-28 09:43:11 +020011790 ha_set_thread(NULL);
Thierry Fournier59f11be2020-11-29 00:37:41 +010011791
11792 /* control functions registering. Each function must have:
11793 * - only the function_ref[0] set positive and all other to -1
11794 * - only the function_ref[0] set to -1 and all other positive
11795 * This ensure a same reference is not used both in shared
11796 * lua state and thread dedicated lua state. Note: is the case
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +050011797 * reach, the shared state is priority, but the bug will be
Thierry Fournier59f11be2020-11-29 00:37:41 +010011798 * complicated to found for the end user.
11799 */
11800 errors = 0;
11801 list_for_each_entry(fcn, &referenced_functions, l) {
11802 ret = 0;
11803 for (i = 1; i < global.nbthread + 1; i++) {
11804 if (fcn->function_ref[i] == -1)
11805 ret--;
11806 else
11807 ret++;
11808 }
11809 if (abs(ret) != global.nbthread) {
11810 ha_alert("Lua function '%s' is not referenced in all thread. "
11811 "Expect function in all thread or in none thread.\n", fcn->name);
11812 errors++;
11813 continue;
11814 }
11815
11816 if ((fcn->function_ref[0] == -1) == (ret < 0)) {
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +050011817 ha_alert("Lua function '%s' is referenced both ins shared Lua context (through lua-load) "
11818 "and per-thread Lua context (through lua-load-per-thread). these two context "
Thierry Fournier59f11be2020-11-29 00:37:41 +010011819 "exclusive.\n", fcn->name);
11820 errors++;
11821 }
11822 }
11823
Christopher Faulet69c581a2021-05-31 08:54:04 +020011824 /* Do the same with registered filters */
11825 list_for_each_entry(reg_flt, &referenced_filters, l) {
11826 ret = 0;
11827 for (i = 1; i < global.nbthread + 1; i++) {
11828 if (reg_flt->flt_ref[i] == -1)
11829 ret--;
11830 else
11831 ret++;
11832 }
11833 if (abs(ret) != global.nbthread) {
11834 ha_alert("Lua filter '%s' is not referenced in all thread. "
11835 "Expect function in all thread or in none thread.\n", reg_flt->name);
11836 errors++;
11837 continue;
11838 }
11839
11840 if ((reg_flt->flt_ref[0] == -1) == (ret < 0)) {
11841 ha_alert("Lua filter '%s' is referenced both ins shared Lua context (through lua-load) "
11842 "and per-thread Lua context (through lua-load-per-thread). these two context "
11843 "exclusive.\n", fcn->name);
11844 errors++;
11845 }
11846 }
11847
11848
Thierry Fournier59f11be2020-11-29 00:37:41 +010011849 if (errors > 0)
11850 return 0;
11851
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +050011852 /* after this point, this global will no longer be used, so set to
Thierry Fournier59f11be2020-11-29 00:37:41 +010011853 * -1 in order to have probably a segfault if someone use it
11854 */
11855 hlua_state_id = -1;
11856
11857 return 1;
Thierry Fournierb8cef172020-11-28 15:37:17 +010011858}
11859
Willy Tarreau32f61e22015-03-18 17:54:59 +010011860/* The memory allocator used by the Lua stack. <ud> is a pointer to the
11861 * allocator's context. <ptr> is the pointer to alloc/free/realloc. <osize>
11862 * is the previously allocated size or the kind of object in case of a new
Willy Tarreaud36c7fa2020-12-02 12:26:29 +010011863 * allocation. <nsize> is the requested new size. A new allocation is
11864 * indicated by <ptr> being NULL. A free is indicated by <nsize> being
Willy Tarreaucdb53462020-12-02 12:12:00 +010011865 * zero. This one verifies that the limits are respected but is optimized
11866 * for the fast case where limits are not used, hence stats are not updated.
Willy Tarreaua5efdff2021-10-22 16:00:02 +020011867 *
11868 * Warning: while this API ressembles glibc's realloc() a lot, glibc surpasses
11869 * POSIX by making realloc(ptr,0) an effective free(), but others do not do
11870 * that and will simply allocate zero as if it were the result of malloc(0),
11871 * so mapping this onto realloc() will lead to memory leaks on non-glibc
11872 * systems.
Willy Tarreau32f61e22015-03-18 17:54:59 +010011873 */
11874static void *hlua_alloc(void *ud, void *ptr, size_t osize, size_t nsize)
11875{
11876 struct hlua_mem_allocator *zone = ud;
Willy Tarreaucdb53462020-12-02 12:12:00 +010011877 size_t limit, old, new;
11878
11879 /* a limit of ~0 means unlimited and boot complete, so there's no need
11880 * for accounting anymore.
11881 */
Willy Tarreaua5efdff2021-10-22 16:00:02 +020011882 if (likely(~zone->limit == 0)) {
11883 if (!nsize)
11884 ha_free(&ptr);
11885 else
11886 ptr = realloc(ptr, nsize);
11887 return ptr;
11888 }
Willy Tarreau32f61e22015-03-18 17:54:59 +010011889
Willy Tarreaud36c7fa2020-12-02 12:26:29 +010011890 if (!ptr)
11891 osize = 0;
Willy Tarreau32f61e22015-03-18 17:54:59 +010011892
Willy Tarreaucdb53462020-12-02 12:12:00 +010011893 /* enforce strict limits across all threads */
11894 limit = zone->limit;
11895 old = _HA_ATOMIC_LOAD(&zone->allocated);
11896 do {
11897 new = old + nsize - osize;
11898 if (unlikely(nsize && limit && new > limit))
11899 return NULL;
11900 } while (!_HA_ATOMIC_CAS(&zone->allocated, &old, new));
Willy Tarreau32f61e22015-03-18 17:54:59 +010011901
Willy Tarreaua5efdff2021-10-22 16:00:02 +020011902 if (!nsize)
11903 ha_free(&ptr);
11904 else
11905 ptr = realloc(ptr, nsize);
Willy Tarreaucdb53462020-12-02 12:12:00 +010011906
11907 if (unlikely(!ptr && nsize)) // failed
11908 _HA_ATOMIC_SUB(&zone->allocated, nsize - osize);
11909
11910 __ha_barrier_atomic_store();
Willy Tarreau32f61e22015-03-18 17:54:59 +010011911 return ptr;
11912}
11913
Thierry Fournierecb83c22020-11-28 15:49:44 +010011914/* This function can fail with an abort() due to a Lua critical error.
Thierry FOURNIERbabae282015-09-17 11:36:37 +020011915 * We are in the initialisation process of HAProxy, this abort() is
11916 * tolerated.
11917 */
Thierry Fournierecb83c22020-11-28 15:49:44 +010011918lua_State *hlua_init_state(int thread_num)
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +010011919{
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010011920 int i;
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010011921 int idx;
11922 struct sample_fetch *sf;
Thierry FOURNIER594afe72015-03-10 23:58:30 +010011923 struct sample_conv *sc;
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010011924 char *p;
Thierry Fournierfd107a22016-02-19 19:57:23 +010011925 const char *error_msg;
Thierry Fournier4234dbd2020-11-28 13:18:23 +010011926 void **context;
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011927 lua_State *L;
Thierry Fournier59f11be2020-11-29 00:37:41 +010011928 struct prepend_path *pp;
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010011929
Thierry FOURNIER380d0932015-01-23 14:27:52 +010011930 /* Init main lua stack. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011931 L = lua_newstate(hlua_alloc, &hlua_global_allocator);
Thierry FOURNIER380d0932015-01-23 14:27:52 +010011932
Thierry Fournier4234dbd2020-11-28 13:18:23 +010011933 /* Initialise Lua context to NULL */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011934 context = lua_getextraspace(L);
Thierry Fournier4234dbd2020-11-28 13:18:23 +010011935 *context = NULL;
11936
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -080011937 /* From this point, until the end of the initialisation function,
Thierry FOURNIERbabae282015-09-17 11:36:37 +020011938 * the Lua function can fail with an abort. We are in the initialisation
11939 * process of HAProxy, this abort() is tolerated.
11940 */
11941
Thierry Fournier3c539322020-11-28 16:05:05 +010011942 /* Call post initialisation function in safe environment. */
11943 if (setjmp(safe_ljmp_env) != 0) {
11944 lua_atpanic(L, hlua_panic_safe);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011945 if (lua_type(L, -1) == LUA_TSTRING)
11946 error_msg = lua_tostring(L, -1);
Thierry Fournier2f05cc62020-11-28 16:08:02 +010011947 else
11948 error_msg = "critical error";
11949 fprintf(stderr, "Lua init: %s.\n", error_msg);
11950 exit(1);
Thierry Fournier3c539322020-11-28 16:05:05 +010011951 } else {
11952 lua_atpanic(L, hlua_panic_ljmp);
Thierry Fournier2f05cc62020-11-28 16:08:02 +010011953 }
11954
Thierry FOURNIER380d0932015-01-23 14:27:52 +010011955 /* Initialise lua. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011956 luaL_openlibs(L);
Tim Duesterhus541fe1e2020-01-12 13:55:41 +010011957#define HLUA_PREPEND_PATH_TOSTRING1(x) #x
11958#define HLUA_PREPEND_PATH_TOSTRING(x) HLUA_PREPEND_PATH_TOSTRING1(x)
11959#ifdef HLUA_PREPEND_PATH
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011960 hlua_prepend_path(L, "path", HLUA_PREPEND_PATH_TOSTRING(HLUA_PREPEND_PATH));
Tim Duesterhus541fe1e2020-01-12 13:55:41 +010011961#endif
11962#ifdef HLUA_PREPEND_CPATH
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011963 hlua_prepend_path(L, "cpath", HLUA_PREPEND_PATH_TOSTRING(HLUA_PREPEND_CPATH));
Tim Duesterhus541fe1e2020-01-12 13:55:41 +010011964#endif
11965#undef HLUA_PREPEND_PATH_TOSTRING
11966#undef HLUA_PREPEND_PATH_TOSTRING1
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010011967
Thierry Fournier59f11be2020-11-29 00:37:41 +010011968 /* Apply configured prepend path */
11969 list_for_each_entry(pp, &prepend_path_list, l)
11970 hlua_prepend_path(L, pp->type, pp->path);
11971
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010011972 /*
11973 *
11974 * Create "core" object.
11975 *
11976 */
11977
Thierry FOURNIERa2d8c652015-03-11 17:29:39 +010011978 /* This table entry is the object "core" base. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011979 lua_newtable(L);
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010011980
Thierry Fournierecb83c22020-11-28 15:49:44 +010011981 /* set the thread id */
11982 hlua_class_const_int(L, "thread", thread_num);
11983
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010011984 /* Push the loglevel constants. */
Willy Tarreau80f5fae2015-02-27 16:38:20 +010011985 for (i = 0; i < NB_LOG_LEVELS; i++)
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011986 hlua_class_const_int(L, log_levels[i], i);
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010011987
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010011988 /* Register special functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011989 hlua_class_function(L, "register_init", hlua_register_init);
11990 hlua_class_function(L, "register_task", hlua_register_task);
11991 hlua_class_function(L, "register_fetches", hlua_register_fetches);
11992 hlua_class_function(L, "register_converters", hlua_register_converters);
11993 hlua_class_function(L, "register_action", hlua_register_action);
11994 hlua_class_function(L, "register_service", hlua_register_service);
11995 hlua_class_function(L, "register_cli", hlua_register_cli);
Christopher Faulet69c581a2021-05-31 08:54:04 +020011996 hlua_class_function(L, "register_filter", hlua_register_filter);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011997 hlua_class_function(L, "yield", hlua_yield);
11998 hlua_class_function(L, "set_nice", hlua_set_nice);
11999 hlua_class_function(L, "sleep", hlua_sleep);
12000 hlua_class_function(L, "msleep", hlua_msleep);
12001 hlua_class_function(L, "add_acl", hlua_add_acl);
12002 hlua_class_function(L, "del_acl", hlua_del_acl);
12003 hlua_class_function(L, "set_map", hlua_set_map);
12004 hlua_class_function(L, "del_map", hlua_del_map);
12005 hlua_class_function(L, "tcp", hlua_socket_new);
William Lallemand3956c4e2021-09-21 16:25:15 +020012006 hlua_class_function(L, "httpclient", hlua_httpclient_new);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012007 hlua_class_function(L, "log", hlua_log);
12008 hlua_class_function(L, "Debug", hlua_log_debug);
12009 hlua_class_function(L, "Info", hlua_log_info);
12010 hlua_class_function(L, "Warning", hlua_log_warning);
12011 hlua_class_function(L, "Alert", hlua_log_alert);
12012 hlua_class_function(L, "done", hlua_done);
12013 hlua_fcn_reg_core_fcn(L);
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010012014
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012015 lua_setglobal(L, "core");
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010012016
12017 /*
12018 *
Christopher Faulet0f3c8902020-01-31 18:57:12 +010012019 * Create "act" object.
12020 *
12021 */
12022
12023 /* This table entry is the object "act" base. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012024 lua_newtable(L);
Christopher Faulet0f3c8902020-01-31 18:57:12 +010012025
12026 /* push action return constants */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012027 hlua_class_const_int(L, "CONTINUE", ACT_RET_CONT);
12028 hlua_class_const_int(L, "STOP", ACT_RET_STOP);
12029 hlua_class_const_int(L, "YIELD", ACT_RET_YIELD);
12030 hlua_class_const_int(L, "ERROR", ACT_RET_ERR);
12031 hlua_class_const_int(L, "DONE", ACT_RET_DONE);
12032 hlua_class_const_int(L, "DENY", ACT_RET_DENY);
12033 hlua_class_const_int(L, "ABORT", ACT_RET_ABRT);
12034 hlua_class_const_int(L, "INVALID", ACT_RET_INV);
Christopher Faulet0f3c8902020-01-31 18:57:12 +010012035
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012036 hlua_class_function(L, "wake_time", hlua_set_wake_time);
Christopher Faulet2c2c2e32020-01-31 19:07:52 +010012037
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012038 lua_setglobal(L, "act");
Christopher Faulet0f3c8902020-01-31 18:57:12 +010012039
12040 /*
12041 *
Christopher Faulet69c581a2021-05-31 08:54:04 +020012042 * Create "Filter" object.
12043 *
12044 */
12045
12046 /* This table entry is the object "filter" base. */
12047 lua_newtable(L);
12048
12049 /* push flags and constants */
12050 hlua_class_const_int(L, "CONTINUE", 1);
12051 hlua_class_const_int(L, "WAIT", 0);
12052 hlua_class_const_int(L, "ERROR", -1);
12053
12054 hlua_class_const_int(L, "FLT_CFG_FL_HTX", FLT_CFG_FL_HTX);
12055
Christopher Fauletc404f112020-02-26 15:03:09 +010012056 hlua_class_function(L, "wake_time", hlua_set_wake_time);
12057 hlua_class_function(L, "register_data_filter", hlua_register_data_filter);
12058 hlua_class_function(L, "unregister_data_filter", hlua_unregister_data_filter);
12059
Christopher Faulet69c581a2021-05-31 08:54:04 +020012060 lua_setglobal(L, "filter");
12061
12062 /*
12063 *
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012064 * Register class Map
12065 *
12066 */
12067
12068 /* This table entry is the object "Map" base. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012069 lua_newtable(L);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012070
12071 /* register pattern types. */
12072 for (i=0; i<PAT_MATCH_NUM; i++)
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012073 hlua_class_const_int(L, pat_match_names[i], i);
Thierry FOURNIER4dc71972017-01-28 08:33:08 +010012074 for (i=0; i<PAT_MATCH_NUM; i++) {
Willy Tarreau843b7cb2018-07-13 10:54:26 +020012075 snprintf(trash.area, trash.size, "_%s", pat_match_names[i]);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012076 hlua_class_const_int(L, trash.area, i);
Thierry FOURNIER4dc71972017-01-28 08:33:08 +010012077 }
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012078
12079 /* register constructor. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012080 hlua_class_function(L, "new", hlua_map_new);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012081
12082 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012083 lua_newtable(L);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012084
Ilya Shipitsind4259502020-04-08 01:07:56 +050012085 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012086 lua_pushstring(L, "__index");
12087 lua_newtable(L);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012088
12089 /* Register . */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012090 hlua_class_function(L, "lookup", hlua_map_lookup);
12091 hlua_class_function(L, "slookup", hlua_map_slookup);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012092
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012093 lua_rawset(L, -3);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012094
Thierry Fournier45e78d72016-02-19 18:34:46 +010012095 /* Register previous table in the registry with reference and named entry.
12096 * The function hlua_register_metatable() pops the stack, so we
12097 * previously create a copy of the table.
12098 */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012099 lua_pushvalue(L, -1); /* Copy the -1 entry and push it on the stack. */
12100 class_map_ref = hlua_register_metatable(L, CLASS_MAP);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012101
12102 /* Assign the metatable to the mai Map object. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012103 lua_setmetatable(L, -2);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012104
12105 /* Set a name to the table. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012106 lua_setglobal(L, "Map");
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012107
12108 /*
12109 *
William Lallemand30fcca12022-03-30 12:03:12 +020012110 * Register "CertCache" class
12111 *
12112 */
12113
12114 /* Create and fill the metatable. */
12115 lua_newtable(L);
12116 /* Register */
12117 hlua_class_function(L, "set", hlua_ckch_set);
12118 lua_setglobal(L, CLASS_CERTCACHE); /* Create global object called Regex */
12119
12120 /*
12121 *
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010012122 * Register class Channel
12123 *
12124 */
12125
12126 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012127 lua_newtable(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010012128
Ilya Shipitsind4259502020-04-08 01:07:56 +050012129 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012130 lua_pushstring(L, "__index");
12131 lua_newtable(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010012132
12133 /* Register . */
Christopher Faulet6a79fc12021-08-06 16:02:36 +020012134 hlua_class_function(L, "data", hlua_channel_get_data);
12135 hlua_class_function(L, "line", hlua_channel_get_line);
12136 hlua_class_function(L, "set", hlua_channel_set_data);
12137 hlua_class_function(L, "remove", hlua_channel_del_data);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012138 hlua_class_function(L, "append", hlua_channel_append);
Christopher Faulet6a79fc12021-08-06 16:02:36 +020012139 hlua_class_function(L, "prepend", hlua_channel_prepend);
12140 hlua_class_function(L, "insert", hlua_channel_insert_data);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012141 hlua_class_function(L, "send", hlua_channel_send);
12142 hlua_class_function(L, "forward", hlua_channel_forward);
Christopher Faulet6a79fc12021-08-06 16:02:36 +020012143 hlua_class_function(L, "input", hlua_channel_get_in_len);
12144 hlua_class_function(L, "output", hlua_channel_get_out_len);
12145 hlua_class_function(L, "may_recv", hlua_channel_may_recv);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012146 hlua_class_function(L, "is_full", hlua_channel_is_full);
12147 hlua_class_function(L, "is_resp", hlua_channel_is_resp);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010012148
Christopher Faulet6a79fc12021-08-06 16:02:36 +020012149 /* Deprecated API */
12150 hlua_class_function(L, "get", hlua_channel_get);
12151 hlua_class_function(L, "dup", hlua_channel_dup);
12152 hlua_class_function(L, "getline", hlua_channel_getline);
12153 hlua_class_function(L, "get_in_len", hlua_channel_get_in_len);
12154 hlua_class_function(L, "get_out_len", hlua_channel_get_out_len);
12155
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012156 lua_rawset(L, -3);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010012157
12158 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012159 class_channel_ref = hlua_register_metatable(L, CLASS_CHANNEL);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010012160
12161 /*
12162 *
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010012163 * Register class Fetches
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010012164 *
12165 */
12166
12167 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012168 lua_newtable(L);
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010012169
Ilya Shipitsind4259502020-04-08 01:07:56 +050012170 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012171 lua_pushstring(L, "__index");
12172 lua_newtable(L);
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010012173
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010012174 /* Browse existing fetches and create the associated
12175 * object method.
12176 */
12177 sf = NULL;
12178 while ((sf = sample_fetch_getnext(sf, &idx)) != NULL) {
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010012179 /* gL.Tua doesn't support '.' and '-' in the function names, replace it
12180 * by an underscore.
12181 */
Willy Tarreau5ef96562021-08-26 16:48:53 +020012182 strlcpy2(trash.area, sf->kw, trash.size);
Willy Tarreau843b7cb2018-07-13 10:54:26 +020012183 for (p = trash.area; *p; p++)
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010012184 if (*p == '.' || *p == '-' || *p == '+')
12185 *p = '_';
12186
12187 /* Register the function. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012188 lua_pushstring(L, trash.area);
12189 lua_pushlightuserdata(L, sf);
12190 lua_pushcclosure(L, hlua_run_sample_fetch, 1);
12191 lua_rawset(L, -3);
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010012192 }
12193
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012194 lua_rawset(L, -3);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010012195
12196 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012197 class_fetches_ref = hlua_register_metatable(L, CLASS_FETCHES);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010012198
12199 /*
12200 *
Thierry FOURNIER594afe72015-03-10 23:58:30 +010012201 * Register class Converters
12202 *
12203 */
12204
12205 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012206 lua_newtable(L);
Thierry FOURNIER594afe72015-03-10 23:58:30 +010012207
12208 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012209 lua_pushstring(L, "__index");
12210 lua_newtable(L);
Thierry FOURNIER594afe72015-03-10 23:58:30 +010012211
12212 /* Browse existing converters and create the associated
12213 * object method.
12214 */
12215 sc = NULL;
12216 while ((sc = sample_conv_getnext(sc, &idx)) != NULL) {
Thierry FOURNIER594afe72015-03-10 23:58:30 +010012217 /* gL.Tua doesn't support '.' and '-' in the function names, replace it
12218 * by an underscore.
12219 */
Willy Tarreau5ef96562021-08-26 16:48:53 +020012220 strlcpy2(trash.area, sc->kw, trash.size);
Willy Tarreau843b7cb2018-07-13 10:54:26 +020012221 for (p = trash.area; *p; p++)
Thierry FOURNIER594afe72015-03-10 23:58:30 +010012222 if (*p == '.' || *p == '-' || *p == '+')
12223 *p = '_';
12224
12225 /* Register the function. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012226 lua_pushstring(L, trash.area);
12227 lua_pushlightuserdata(L, sc);
12228 lua_pushcclosure(L, hlua_run_sample_conv, 1);
12229 lua_rawset(L, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +010012230 }
12231
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012232 lua_rawset(L, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +010012233
12234 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012235 class_converters_ref = hlua_register_metatable(L, CLASS_CONVERTERS);
Thierry FOURNIER594afe72015-03-10 23:58:30 +010012236
12237 /*
12238 *
Thierry FOURNIER08504f42015-03-16 14:17:08 +010012239 * Register class HTTP
12240 *
12241 */
12242
12243 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012244 lua_newtable(L);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010012245
Ilya Shipitsind4259502020-04-08 01:07:56 +050012246 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012247 lua_pushstring(L, "__index");
12248 lua_newtable(L);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010012249
12250 /* Register Lua functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012251 hlua_class_function(L, "req_get_headers",hlua_http_req_get_headers);
12252 hlua_class_function(L, "req_del_header", hlua_http_req_del_hdr);
12253 hlua_class_function(L, "req_rep_header", hlua_http_req_rep_hdr);
12254 hlua_class_function(L, "req_rep_value", hlua_http_req_rep_val);
12255 hlua_class_function(L, "req_add_header", hlua_http_req_add_hdr);
12256 hlua_class_function(L, "req_set_header", hlua_http_req_set_hdr);
12257 hlua_class_function(L, "req_set_method", hlua_http_req_set_meth);
12258 hlua_class_function(L, "req_set_path", hlua_http_req_set_path);
12259 hlua_class_function(L, "req_set_query", hlua_http_req_set_query);
12260 hlua_class_function(L, "req_set_uri", hlua_http_req_set_uri);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010012261
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012262 hlua_class_function(L, "res_get_headers",hlua_http_res_get_headers);
12263 hlua_class_function(L, "res_del_header", hlua_http_res_del_hdr);
12264 hlua_class_function(L, "res_rep_header", hlua_http_res_rep_hdr);
12265 hlua_class_function(L, "res_rep_value", hlua_http_res_rep_val);
12266 hlua_class_function(L, "res_add_header", hlua_http_res_add_hdr);
12267 hlua_class_function(L, "res_set_header", hlua_http_res_set_hdr);
12268 hlua_class_function(L, "res_set_status", hlua_http_res_set_status);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010012269
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012270 lua_rawset(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010012271
12272 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012273 class_http_ref = hlua_register_metatable(L, CLASS_HTTP);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010012274
Christopher Fauletdf97ac42020-02-26 16:57:19 +010012275 /*
12276 *
12277 * Register class HTTPMessage
12278 *
12279 */
12280
12281 /* Create and fill the metatable. */
12282 lua_newtable(L);
12283
Ilya Shipitsinff0f2782021-08-22 22:18:07 +050012284 /* Create and fill the __index entry. */
Christopher Fauletdf97ac42020-02-26 16:57:19 +010012285 lua_pushstring(L, "__index");
12286 lua_newtable(L);
12287
12288 /* Register Lua functions. */
12289 hlua_class_function(L, "is_resp", hlua_http_msg_is_resp);
12290 hlua_class_function(L, "get_stline", hlua_http_msg_get_stline);
12291 hlua_class_function(L, "get_headers", hlua_http_msg_get_headers);
12292 hlua_class_function(L, "del_header", hlua_http_msg_del_hdr);
12293 hlua_class_function(L, "rep_header", hlua_http_msg_rep_hdr);
12294 hlua_class_function(L, "rep_value", hlua_http_msg_rep_val);
12295 hlua_class_function(L, "add_header", hlua_http_msg_add_hdr);
12296 hlua_class_function(L, "set_header", hlua_http_msg_set_hdr);
12297 hlua_class_function(L, "set_method", hlua_http_msg_set_meth);
12298 hlua_class_function(L, "set_path", hlua_http_msg_set_path);
12299 hlua_class_function(L, "set_query", hlua_http_msg_set_query);
12300 hlua_class_function(L, "set_uri", hlua_http_msg_set_uri);
12301 hlua_class_function(L, "set_status", hlua_http_msg_set_status);
12302 hlua_class_function(L, "is_full", hlua_http_msg_is_full);
12303 hlua_class_function(L, "may_recv", hlua_http_msg_may_recv);
12304 hlua_class_function(L, "eom", hlua_http_msg_is_eom);
12305 hlua_class_function(L, "input", hlua_http_msg_get_in_len);
12306 hlua_class_function(L, "output", hlua_http_msg_get_out_len);
12307
12308 hlua_class_function(L, "body", hlua_http_msg_get_body);
12309 hlua_class_function(L, "set", hlua_http_msg_set_data);
12310 hlua_class_function(L, "remove", hlua_http_msg_del_data);
12311 hlua_class_function(L, "append", hlua_http_msg_append);
12312 hlua_class_function(L, "prepend", hlua_http_msg_prepend);
12313 hlua_class_function(L, "insert", hlua_http_msg_insert_data);
12314 hlua_class_function(L, "set_eom", hlua_http_msg_set_eom);
12315 hlua_class_function(L, "unset_eom", hlua_http_msg_unset_eom);
12316
12317 hlua_class_function(L, "send", hlua_http_msg_send);
12318 hlua_class_function(L, "forward", hlua_http_msg_forward);
12319
12320 lua_rawset(L, -3);
12321
12322 /* Register previous table in the registry with reference and named entry. */
12323 class_http_msg_ref = hlua_register_metatable(L, CLASS_HTTP_MSG);
William Lallemand3956c4e2021-09-21 16:25:15 +020012324
12325 /*
12326 *
12327 * Register class HTTPClient
12328 *
12329 */
12330
12331 /* Create and fill the metatable. */
12332 lua_newtable(L);
12333 lua_pushstring(L, "__index");
12334 lua_newtable(L);
12335 hlua_class_function(L, "get", hlua_httpclient_get);
William Lallemanddc2cc902021-10-26 11:43:26 +020012336 hlua_class_function(L, "head", hlua_httpclient_head);
12337 hlua_class_function(L, "put", hlua_httpclient_put);
12338 hlua_class_function(L, "post", hlua_httpclient_post);
12339 hlua_class_function(L, "delete", hlua_httpclient_delete);
William Lallemand3956c4e2021-09-21 16:25:15 +020012340 lua_settable(L, -3); /* Sets the __index entry. */
William Lallemandf77f1de2021-09-28 19:10:38 +020012341 /* Register the garbage collector entry. */
12342 lua_pushstring(L, "__gc");
12343 lua_pushcclosure(L, hlua_httpclient_gc, 0);
12344 lua_settable(L, -3); /* Push the last 2 entries in the table at index -3 */
12345
William Lallemand3956c4e2021-09-21 16:25:15 +020012346
12347
12348 class_httpclient_ref = hlua_register_metatable(L, CLASS_HTTPCLIENT);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010012349 /*
12350 *
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020012351 * Register class AppletTCP
12352 *
12353 */
12354
12355 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012356 lua_newtable(L);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020012357
Ilya Shipitsind4259502020-04-08 01:07:56 +050012358 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012359 lua_pushstring(L, "__index");
12360 lua_newtable(L);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020012361
12362 /* Register Lua functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012363 hlua_class_function(L, "getline", hlua_applet_tcp_getline);
12364 hlua_class_function(L, "receive", hlua_applet_tcp_recv);
12365 hlua_class_function(L, "send", hlua_applet_tcp_send);
12366 hlua_class_function(L, "set_priv", hlua_applet_tcp_set_priv);
12367 hlua_class_function(L, "get_priv", hlua_applet_tcp_get_priv);
12368 hlua_class_function(L, "set_var", hlua_applet_tcp_set_var);
12369 hlua_class_function(L, "unset_var", hlua_applet_tcp_unset_var);
12370 hlua_class_function(L, "get_var", hlua_applet_tcp_get_var);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020012371
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012372 lua_settable(L, -3);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020012373
12374 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012375 class_applet_tcp_ref = hlua_register_metatable(L, CLASS_APPLET_TCP);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020012376
12377 /*
12378 *
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020012379 * Register class AppletHTTP
12380 *
12381 */
12382
12383 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012384 lua_newtable(L);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020012385
Ilya Shipitsind4259502020-04-08 01:07:56 +050012386 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012387 lua_pushstring(L, "__index");
12388 lua_newtable(L);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020012389
12390 /* Register Lua functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012391 hlua_class_function(L, "set_priv", hlua_applet_http_set_priv);
12392 hlua_class_function(L, "get_priv", hlua_applet_http_get_priv);
12393 hlua_class_function(L, "set_var", hlua_applet_http_set_var);
12394 hlua_class_function(L, "unset_var", hlua_applet_http_unset_var);
12395 hlua_class_function(L, "get_var", hlua_applet_http_get_var);
12396 hlua_class_function(L, "getline", hlua_applet_http_getline);
12397 hlua_class_function(L, "receive", hlua_applet_http_recv);
12398 hlua_class_function(L, "send", hlua_applet_http_send);
12399 hlua_class_function(L, "add_header", hlua_applet_http_addheader);
12400 hlua_class_function(L, "set_status", hlua_applet_http_status);
12401 hlua_class_function(L, "start_response", hlua_applet_http_start_response);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020012402
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012403 lua_settable(L, -3);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020012404
12405 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012406 class_applet_http_ref = hlua_register_metatable(L, CLASS_APPLET_HTTP);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020012407
12408 /*
12409 *
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010012410 * Register class TXN
12411 *
12412 */
12413
12414 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012415 lua_newtable(L);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010012416
Ilya Shipitsind4259502020-04-08 01:07:56 +050012417 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012418 lua_pushstring(L, "__index");
12419 lua_newtable(L);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010012420
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +010012421 /* Register Lua functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012422 hlua_class_function(L, "set_priv", hlua_set_priv);
12423 hlua_class_function(L, "get_priv", hlua_get_priv);
12424 hlua_class_function(L, "set_var", hlua_set_var);
12425 hlua_class_function(L, "unset_var", hlua_unset_var);
12426 hlua_class_function(L, "get_var", hlua_get_var);
12427 hlua_class_function(L, "done", hlua_txn_done);
12428 hlua_class_function(L, "reply", hlua_txn_reply_new);
12429 hlua_class_function(L, "set_loglevel", hlua_txn_set_loglevel);
12430 hlua_class_function(L, "set_tos", hlua_txn_set_tos);
12431 hlua_class_function(L, "set_mark", hlua_txn_set_mark);
12432 hlua_class_function(L, "set_priority_class", hlua_txn_set_priority_class);
12433 hlua_class_function(L, "set_priority_offset", hlua_txn_set_priority_offset);
12434 hlua_class_function(L, "deflog", hlua_txn_deflog);
12435 hlua_class_function(L, "log", hlua_txn_log);
12436 hlua_class_function(L, "Debug", hlua_txn_log_debug);
12437 hlua_class_function(L, "Info", hlua_txn_log_info);
12438 hlua_class_function(L, "Warning", hlua_txn_log_warning);
12439 hlua_class_function(L, "Alert", hlua_txn_log_alert);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +010012440
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012441 lua_rawset(L, -3);
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010012442
12443 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012444 class_txn_ref = hlua_register_metatable(L, CLASS_TXN);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012445
12446 /*
12447 *
Christopher Faulet700d9e82020-01-31 12:21:52 +010012448 * Register class reply
12449 *
12450 */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012451 lua_newtable(L);
12452 lua_pushstring(L, "__index");
12453 lua_newtable(L);
12454 hlua_class_function(L, "set_status", hlua_txn_reply_set_status);
12455 hlua_class_function(L, "add_header", hlua_txn_reply_add_header);
12456 hlua_class_function(L, "del_header", hlua_txn_reply_del_header);
12457 hlua_class_function(L, "set_body", hlua_txn_reply_set_body);
12458 lua_settable(L, -3); /* Sets the __index entry. */
12459 class_txn_reply_ref = luaL_ref(L, LUA_REGISTRYINDEX);
Christopher Faulet700d9e82020-01-31 12:21:52 +010012460
12461
12462 /*
12463 *
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012464 * Register class Socket
12465 *
12466 */
12467
12468 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012469 lua_newtable(L);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012470
Ilya Shipitsind4259502020-04-08 01:07:56 +050012471 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012472 lua_pushstring(L, "__index");
12473 lua_newtable(L);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012474
Baptiste Assmann84bb4932015-03-02 21:40:06 +010012475#ifdef USE_OPENSSL
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012476 hlua_class_function(L, "connect_ssl", hlua_socket_connect_ssl);
Baptiste Assmann84bb4932015-03-02 21:40:06 +010012477#endif
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012478 hlua_class_function(L, "connect", hlua_socket_connect);
12479 hlua_class_function(L, "send", hlua_socket_send);
12480 hlua_class_function(L, "receive", hlua_socket_receive);
12481 hlua_class_function(L, "close", hlua_socket_close);
12482 hlua_class_function(L, "getpeername", hlua_socket_getpeername);
12483 hlua_class_function(L, "getsockname", hlua_socket_getsockname);
12484 hlua_class_function(L, "setoption", hlua_socket_setoption);
12485 hlua_class_function(L, "settimeout", hlua_socket_settimeout);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012486
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012487 lua_rawset(L, -3); /* Push the last 2 entries in the table at index -3 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012488
12489 /* Register the garbage collector entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012490 lua_pushstring(L, "__gc");
12491 lua_pushcclosure(L, hlua_socket_gc, 0);
12492 lua_rawset(L, -3); /* Push the last 2 entries in the table at index -3 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012493
12494 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012495 class_socket_ref = hlua_register_metatable(L, CLASS_SOCKET);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012496
Thierry Fournieraafc7772020-12-04 11:47:47 +010012497 lua_atpanic(L, hlua_panic_safe);
12498
12499 return L;
12500}
12501
12502void hlua_init(void) {
12503 int i;
Amaury Denoyelle239fdbf2021-03-24 10:22:03 +010012504 char *errmsg;
Thierry Fournieraafc7772020-12-04 11:47:47 +010012505#ifdef USE_OPENSSL
12506 struct srv_kw *kw;
12507 int tmp_error;
12508 char *error;
12509 char *args[] = { /* SSL client configuration. */
12510 "ssl",
12511 "verify",
12512 "none",
12513 NULL
12514 };
12515#endif
12516
12517 /* Init post init function list head */
12518 for (i = 0; i < MAX_THREADS + 1; i++)
12519 LIST_INIT(&hlua_init_functions[i]);
12520
12521 /* Init state for common/shared lua parts */
12522 hlua_state_id = 0;
Willy Tarreau43ab05b2021-09-28 09:43:11 +020012523 ha_set_thread(NULL);
Thierry Fournieraafc7772020-12-04 11:47:47 +010012524 hlua_states[0] = hlua_init_state(0);
12525
12526 /* Init state 1 for thread 0. We have at least one thread. */
12527 hlua_state_id = 1;
Willy Tarreau43ab05b2021-09-28 09:43:11 +020012528 ha_set_thread(NULL);
Thierry Fournieraafc7772020-12-04 11:47:47 +010012529 hlua_states[1] = hlua_init_state(1);
12530
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012531 /* Proxy and server configuration initialisation. */
William Lallemand6bb77b92021-07-28 15:48:16 +020012532 socket_proxy = alloc_new_proxy("LUA-SOCKET", PR_CAP_FE|PR_CAP_BE|PR_CAP_INT, &errmsg);
Amaury Denoyelle239fdbf2021-03-24 10:22:03 +010012533 if (!socket_proxy) {
12534 fprintf(stderr, "Lua init: %s\n", errmsg);
12535 exit(1);
12536 }
12537 proxy_preset_defaults(socket_proxy);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012538
12539 /* Init TCP server: unchanged parameters */
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010012540 socket_tcp = new_server(socket_proxy);
12541 if (!socket_tcp) {
12542 fprintf(stderr, "Lua init: failed to allocate tcp server socket\n");
12543 exit(1);
12544 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012545
12546#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012547 /* Init TCP server: unchanged parameters */
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010012548 socket_ssl = new_server(socket_proxy);
12549 if (!socket_ssl) {
12550 fprintf(stderr, "Lua init: failed to allocate ssl server socket\n");
12551 exit(1);
12552 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012553
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010012554 socket_ssl->use_ssl = 1;
12555 socket_ssl->xprt = xprt_get(XPRT_SSL);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012556
Bertrand Jacquin80839ff2021-01-21 19:14:46 +000012557 for (i = 0; args[i] != NULL; i++) {
12558 if ((kw = srv_find_kw(args[i])) != NULL) { /* Maybe it's registered server keyword */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012559 /*
12560 *
12561 * If the keyword is not known, we can search in the registered
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -080012562 * server keywords. This is useful to configure special SSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012563 * features like client certificates and ssl_verify.
12564 *
12565 */
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010012566 tmp_error = kw->parse(args, &i, socket_proxy, socket_ssl, &error);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012567 if (tmp_error != 0) {
12568 fprintf(stderr, "INTERNAL ERROR: %s\n", error);
12569 abort(); /* This must be never arrives because the command line
12570 not editable by the user. */
12571 }
Bertrand Jacquin80839ff2021-01-21 19:14:46 +000012572 i += kw->skip;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012573 }
12574 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012575#endif
Thierry Fournier75933d42016-01-21 09:30:18 +010012576
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +010012577}
Willy Tarreaubb57d942016-12-21 19:04:56 +010012578
Tim Duesterhusd0c0ca22020-07-04 11:53:26 +020012579static void hlua_deinit()
12580{
Willy Tarreau186f3762020-12-04 11:48:12 +010012581 int thr;
Christopher Faulet69c581a2021-05-31 08:54:04 +020012582 struct hlua_reg_filter *reg_flt, *reg_flt_bck;
12583
12584 list_for_each_entry_safe(reg_flt, reg_flt_bck, &referenced_filters, l)
12585 release_hlua_reg_filter(reg_flt);
Willy Tarreau186f3762020-12-04 11:48:12 +010012586
12587 for (thr = 0; thr < MAX_THREADS+1; thr++) {
12588 if (hlua_states[thr])
12589 lua_close(hlua_states[thr]);
12590 }
Willy Tarreau430bf4a2021-03-04 09:45:32 +010012591
Amaury Denoyellebc2ebfa2021-08-25 15:34:53 +020012592 srv_drop(socket_tcp);
Willy Tarreau430bf4a2021-03-04 09:45:32 +010012593
Willy Tarreau0f143af2021-03-05 10:41:48 +010012594#ifdef USE_OPENSSL
Amaury Denoyellebc2ebfa2021-08-25 15:34:53 +020012595 srv_drop(socket_ssl);
Willy Tarreau0f143af2021-03-05 10:41:48 +010012596#endif
Amaury Denoyelle239fdbf2021-03-24 10:22:03 +010012597
12598 free_proxy(socket_proxy);
Tim Duesterhusd0c0ca22020-07-04 11:53:26 +020012599}
12600
12601REGISTER_POST_DEINIT(hlua_deinit);
12602
Willy Tarreau80713382018-11-26 10:19:54 +010012603static void hlua_register_build_options(void)
12604{
Willy Tarreaubb57d942016-12-21 19:04:56 +010012605 char *ptr = NULL;
Willy Tarreau80713382018-11-26 10:19:54 +010012606
Willy Tarreaubb57d942016-12-21 19:04:56 +010012607 memprintf(&ptr, "Built with Lua version : %s", LUA_RELEASE);
12608 hap_register_build_opts(ptr, 1);
12609}
Willy Tarreau80713382018-11-26 10:19:54 +010012610
12611INITCALL0(STG_REGISTER, hlua_register_build_options);