blob: 292d8f28a8be19c496f9ccb3897c5fab7691eac5 [file] [log] [blame]
Thierry Fourniere726b142016-02-11 17:57:57 +01001/*
2 * Lua unsafe core engine
3 *
4 * Copyright 2015-2016 Thierry Fournier <tfournier@arpalert.org>
5 *
6 * This program is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU General Public License
8 * as published by the Free Software Foundation; either version
9 * 2 of the License, or (at your option) any later version.
10 *
11 */
12
Bertrand Jacquinf4c12d42021-01-21 21:14:07 +000013#define _GNU_SOURCE
14
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +010015#include <ctype.h>
Thierry FOURNIERbabae282015-09-17 11:36:37 +020016#include <setjmp.h>
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +010017
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +010018#include <lauxlib.h>
19#include <lua.h>
20#include <lualib.h>
21
Thierry FOURNIER463119c2015-03-10 00:35:36 +010022#if !defined(LUA_VERSION_NUM) || LUA_VERSION_NUM < 503
23#error "Requires Lua 5.3 or later."
Cyril Bontédc0306e2015-03-02 00:08:40 +010024#endif
25
Willy Tarreau8d2b7772020-05-27 10:58:19 +020026#include <import/ebpttree.h>
Thierry FOURNIER380d0932015-01-23 14:27:52 +010027
Willy Tarreaub2551052020-06-09 09:07:15 +020028#include <haproxy/api.h>
29#include <haproxy/applet.h>
Willy Tarreaudfd3de82020-06-04 23:46:14 +020030#include <haproxy/arg.h>
Christopher Fauletd25d9262020-08-06 11:04:46 +020031#include <haproxy/auth.h>
Willy Tarreau6be78492020-06-05 00:00:29 +020032#include <haproxy/cfgparse.h>
Willy Tarreauf1d32c42020-06-04 21:07:02 +020033#include <haproxy/channel.h>
Willy Tarreau83487a82020-06-04 20:19:54 +020034#include <haproxy/cli.h>
Willy Tarreau55542642021-10-08 09:33:24 +020035#include <haproxy/clock.h>
Willy Tarreau7ea393d2020-06-04 18:02:10 +020036#include <haproxy/connection.h>
Christopher Faulet908628c2022-03-25 16:43:49 +010037#include <haproxy/conn_stream.h>
38#include <haproxy/cs_utils.h>
Christopher Faulet69c581a2021-05-31 08:54:04 +020039#include <haproxy/filters.h>
Willy Tarreau5413a872020-06-02 19:33:08 +020040#include <haproxy/h1.h>
Willy Tarreau86416052020-06-04 09:20:54 +020041#include <haproxy/hlua.h>
Willy Tarreau8c794002020-06-04 10:05:25 +020042#include <haproxy/hlua_fcn.h>
Willy Tarreauc2b1ff02020-06-04 21:21:03 +020043#include <haproxy/http_ana.h>
William Lallemand3956c4e2021-09-21 16:25:15 +020044#include <haproxy/http_client.h>
Willy Tarreau126ba3a2020-06-04 18:26:43 +020045#include <haproxy/http_fetch.h>
Willy Tarreaub2551052020-06-09 09:07:15 +020046#include <haproxy/http_htx.h>
Willy Tarreauc761f842020-06-04 11:40:28 +020047#include <haproxy/http_rules.h>
Willy Tarreau36979d92020-06-05 17:27:29 +020048#include <haproxy/log.h>
Willy Tarreau2cd58092020-06-04 15:10:43 +020049#include <haproxy/map.h>
Willy Tarreau8efbdfb2020-06-04 11:29:21 +020050#include <haproxy/obj_type.h>
Willy Tarreau225a90a2020-06-04 15:06:28 +020051#include <haproxy/pattern.h>
Willy Tarreau469509b2020-06-04 15:13:30 +020052#include <haproxy/payload.h>
Willy Tarreau3d6ee402021-05-08 20:28:07 +020053#include <haproxy/proxy.h>
Willy Tarreaub2551052020-06-09 09:07:15 +020054#include <haproxy/regex.h>
Willy Tarreaue6ce10b2020-06-04 15:33:47 +020055#include <haproxy/sample.h>
Willy Tarreau198e92a2021-03-05 10:23:32 +010056#include <haproxy/server.h>
Willy Tarreau48d25b32020-06-04 18:58:52 +020057#include <haproxy/session.h>
William Lallemand30fcca12022-03-30 12:03:12 +020058#include <haproxy/ssl_ckch.h>
59#include <haproxy/ssl_sock.h>
Willy Tarreau2eec9b52020-06-04 19:58:55 +020060#include <haproxy/stats-t.h>
Willy Tarreaudfd3de82020-06-04 23:46:14 +020061#include <haproxy/stream.h>
Willy Tarreaucea0e1b2020-06-04 17:25:40 +020062#include <haproxy/task.h>
Willy Tarreau8b550af2020-06-04 17:42:48 +020063#include <haproxy/tcp_rules.h>
Willy Tarreaub2551052020-06-09 09:07:15 +020064#include <haproxy/thread.h>
Willy Tarreau48fbcae2020-06-03 18:09:46 +020065#include <haproxy/tools.h>
Willy Tarreaua1718922020-06-04 16:25:31 +020066#include <haproxy/vars.h>
Willy Tarreaub2551052020-06-09 09:07:15 +020067#include <haproxy/xref.h>
68
Thierry FOURNIER380d0932015-01-23 14:27:52 +010069
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +010070/* Lua uses longjmp to perform yield or throwing errors. This
71 * macro is used only for identifying the function that can
72 * not return because a longjmp is executed.
73 * __LJMP marks a prototype of hlua file that can use longjmp.
74 * WILL_LJMP() marks an lua function that will use longjmp.
75 * MAY_LJMP() marks an lua function that may use longjmp.
76 */
77#define __LJMP
Willy Tarreau4e7cc332018-10-20 17:45:48 +020078#define WILL_LJMP(func) do { func; my_unreachable(); } while(0)
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +010079#define MAY_LJMP(func) func
80
Thierry FOURNIERbabae282015-09-17 11:36:37 +020081/* This couple of function executes securely some Lua calls outside of
82 * the lua runtime environment. Each Lua call can return a longjmp
83 * if it encounter a memory error.
84 *
85 * Lua documentation extract:
86 *
87 * If an error happens outside any protected environment, Lua calls
88 * a panic function (see lua_atpanic) and then calls abort, thus
89 * exiting the host application. Your panic function can avoid this
90 * exit by never returning (e.g., doing a long jump to your own
91 * recovery point outside Lua).
92 *
93 * The panic function runs as if it were a message handler (see
Willy Tarreau3dfb7da2022-03-02 22:33:39 +010094 * #2.3); in particular, the error message is at the top of the
Thierry FOURNIERbabae282015-09-17 11:36:37 +020095 * stack. However, there is no guarantee about stack space. To push
96 * anything on the stack, the panic function must first check the
Willy Tarreau3dfb7da2022-03-02 22:33:39 +010097 * available space (see #4.2).
Thierry FOURNIERbabae282015-09-17 11:36:37 +020098 *
99 * We must check all the Lua entry point. This includes:
100 * - The include/proto/hlua.h exported functions
101 * - the task wrapper function
102 * - The action wrapper function
103 * - The converters wrapper function
104 * - The sample-fetch wrapper functions
105 *
Ilya Shipitsin46a030c2020-07-05 16:36:08 +0500106 * It is tolerated that the initialisation function returns an abort.
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -0800107 * Before each Lua abort, an error message is written on stderr.
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200108 *
109 * The macro SET_SAFE_LJMP initialise the longjmp. The Macro
110 * RESET_SAFE_LJMP reset the longjmp. These function must be macro
111 * because they must be exists in the program stack when the longjmp
112 * is called.
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +0200113 *
114 * Note that the Lua processing is not really thread safe. It provides
115 * heavy system which consists to add our own lock function in the Lua
116 * code and recompile the library. This system will probably not accepted
117 * by maintainers of various distribs.
118 *
Ilya Shipitsin856aabc2020-04-16 23:51:34 +0500119 * Our main execution point of the Lua is the function lua_resume(). A
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +0200120 * quick looking on the Lua sources displays a lua_lock() a the start
121 * of function and a lua_unlock() at the end of the function. So I
122 * conclude that the Lua thread safe mode just perform a mutex around
123 * all execution. So I prefer to do this in the HAProxy code, it will be
124 * easier for distro maintainers.
125 *
126 * Note that the HAProxy lua functions rounded by the macro SET_SAFE_LJMP
127 * and RESET_SAFE_LJMP manipulates the Lua stack, so it will be careful
128 * to set mutex around these functions.
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200129 */
Willy Tarreau86abe442018-11-25 20:12:18 +0100130__decl_spinlock(hlua_global_lock);
Thierry FOURNIERffbad792017-07-12 11:39:04 +0200131THREAD_LOCAL jmp_buf safe_ljmp_env;
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200132static int hlua_panic_safe(lua_State *L) { return 0; }
Willy Tarreau6a510902021-07-14 19:41:25 +0200133static int hlua_panic_ljmp(lua_State *L) { WILL_LJMP(longjmp(safe_ljmp_env, 1)); return 0; }
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200134
Thierry Fournier62a22aa2020-11-28 21:06:35 +0100135/* This is the chained list of struct hlua_function referenced
136 * for haproxy action, sample-fetches, converters, cli and
137 * applet bindings. It is used for a post-initialisation control.
138 */
139static struct list referenced_functions = LIST_HEAD_INIT(referenced_functions);
140
Thierry Fournierc7492592020-11-28 23:57:24 +0100141/* This variable is used only during initialization to identify the Lua state
142 * currently being initialized. 0 is the common lua state, 1 to n are the Lua
143 * states dedicated to each thread (in this case hlua_state_id==tid+1).
144 */
145static int hlua_state_id;
146
Thierry Fournier59f11be2020-11-29 00:37:41 +0100147/* This is a NULL-terminated list of lua file which are referenced to load per thread */
148static char **per_thread_load = NULL;
149
150lua_State *hlua_init_state(int thread_id);
151
Willy Tarreau1e7bef12021-08-20 15:47:25 +0200152/* This function takes the Lua global lock. Keep this function's visibility
153 * global so that it can appear in stack dumps and performance profiles!
154 */
155void lua_take_global_lock()
156{
157 HA_SPIN_LOCK(LUA_LOCK, &hlua_global_lock);
158}
159
160static inline void lua_drop_global_lock()
161{
162 HA_SPIN_UNLOCK(LUA_LOCK, &hlua_global_lock);
163}
164
Thierry Fournier7cbe5042020-11-28 17:02:21 +0100165#define SET_SAFE_LJMP_L(__L, __HLUA) \
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200166 ({ \
167 int ret; \
Thierry Fournier021d9862020-11-28 23:42:03 +0100168 if ((__HLUA)->state_id == 0) \
Willy Tarreau1e7bef12021-08-20 15:47:25 +0200169 lua_take_global_lock(); \
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200170 if (setjmp(safe_ljmp_env) != 0) { \
171 lua_atpanic(__L, hlua_panic_safe); \
172 ret = 0; \
Thierry Fournier021d9862020-11-28 23:42:03 +0100173 if ((__HLUA)->state_id == 0) \
Willy Tarreau1e7bef12021-08-20 15:47:25 +0200174 lua_drop_global_lock(); \
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200175 } else { \
176 lua_atpanic(__L, hlua_panic_ljmp); \
177 ret = 1; \
178 } \
179 ret; \
180 })
181
182/* If we are the last function catching Lua errors, we
183 * must reset the panic function.
184 */
Thierry Fournier7cbe5042020-11-28 17:02:21 +0100185#define RESET_SAFE_LJMP_L(__L, __HLUA) \
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200186 do { \
187 lua_atpanic(__L, hlua_panic_safe); \
Thierry Fournier021d9862020-11-28 23:42:03 +0100188 if ((__HLUA)->state_id == 0) \
Willy Tarreau1e7bef12021-08-20 15:47:25 +0200189 lua_drop_global_lock(); \
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200190 } while(0)
191
Thierry Fournier7cbe5042020-11-28 17:02:21 +0100192#define SET_SAFE_LJMP(__HLUA) \
193 SET_SAFE_LJMP_L((__HLUA)->T, __HLUA)
194
195#define RESET_SAFE_LJMP(__HLUA) \
196 RESET_SAFE_LJMP_L((__HLUA)->T, __HLUA)
197
198#define SET_SAFE_LJMP_PARENT(__HLUA) \
Thierry Fournier021d9862020-11-28 23:42:03 +0100199 SET_SAFE_LJMP_L(hlua_states[(__HLUA)->state_id], __HLUA)
Thierry Fournier7cbe5042020-11-28 17:02:21 +0100200
201#define RESET_SAFE_LJMP_PARENT(__HLUA) \
Thierry Fournier021d9862020-11-28 23:42:03 +0100202 RESET_SAFE_LJMP_L(hlua_states[(__HLUA)->state_id], __HLUA)
Thierry Fournier7cbe5042020-11-28 17:02:21 +0100203
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +0200204/* Applet status flags */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200205#define APPLET_DONE 0x01 /* applet processing is done. */
Christopher Faulet18c2e8d2019-03-01 12:02:08 +0100206/* unused: 0x02 */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200207#define APPLET_HDR_SENT 0x04 /* Response header sent. */
Christopher Fauleta2097962019-07-15 16:25:33 +0200208/* unused: 0x08, 0x10 */
Thierry FOURNIERd93ea2b2015-12-20 19:14:52 +0100209#define APPLET_HTTP11 0x20 /* Last chunk sent. */
Christopher Faulet56a3d6e2019-02-27 22:06:23 +0100210#define APPLET_RSP_SENT 0x40 /* The response was fully sent */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200211
Thierry Fournierafc63e22020-11-28 17:06:51 +0100212/* The main Lua execution context. The 0 index is the
213 * common state shared by all threads.
214 */
Willy Tarreau186f3762020-12-04 11:48:12 +0100215static lua_State *hlua_states[MAX_THREADS + 1];
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100216
Christopher Fauletc404f112020-02-26 15:03:09 +0100217#define HLUA_FLT_CB_FINAL 0x00000001
218#define HLUA_FLT_CB_RETVAL 0x00000002
219#define HLUA_FLT_CB_ARG_CHN 0x00000004
220#define HLUA_FLT_CB_ARG_HTTP_MSG 0x00000008
221
Christopher Faulet9f55a502020-02-25 15:21:02 +0100222#define HLUA_FLT_CTX_FL_PAYLOAD 0x00000001
223
Christopher Faulet69c581a2021-05-31 08:54:04 +0200224struct hlua_reg_filter {
225 char *name;
226 int flt_ref[MAX_THREADS + 1];
227 int fun_ref[MAX_THREADS + 1];
228 struct list l;
229};
230
231struct hlua_flt_config {
232 struct hlua_reg_filter *reg;
233 int ref[MAX_THREADS + 1];
234 char **args;
235};
236
237struct hlua_flt_ctx {
238 int ref; /* ref to the filter lua object */
239 struct hlua *hlua[2]; /* lua runtime context (0: request, 1: response) */
240 unsigned int cur_off[2]; /* current offset (0: request, 1: response) */
241 unsigned int cur_len[2]; /* current forwardable length (0: request, 1: response) */
242 unsigned int flags; /* HLUA_FLT_CTX_FL_* */
243};
244
Willy Tarreau5321da92022-05-06 11:57:34 +0200245/* appctx context used by the cosockets */
246struct hlua_csk_ctx {
247 int connected;
248 struct xref xref; /* cross reference with the Lua object owner. */
249 struct list wake_on_read;
250 struct list wake_on_write;
251 struct appctx *appctx;
252 int die;
253};
254
Willy Tarreaue23f33b2022-05-06 14:07:13 +0200255/* appctx context used by TCP services */
256struct hlua_tcp_ctx {
257 struct hlua *hlua;
258 int flags;
259 struct task *task;
260};
261
Willy Tarreauaa229cc2022-05-06 14:26:10 +0200262/* appctx context used by HTTP services */
263struct hlua_http_ctx {
264 struct hlua *hlua;
265 int left_bytes; /* The max amount of bytes that we can read. */
266 int flags;
267 int status;
268 const char *reason;
269 struct task *task;
270};
271
Willy Tarreaubcda5f62022-05-03 18:13:39 +0200272/* used by registered CLI keywords */
273struct hlua_cli_ctx {
274 struct hlua *hlua;
275 struct task *task;
276 struct hlua_function *fcn;
277};
278
Christopher Faulet69c581a2021-05-31 08:54:04 +0200279DECLARE_STATIC_POOL(pool_head_hlua_flt_ctx, "hlua_flt_ctx", sizeof(struct hlua_flt_ctx));
280
Christopher Faulet9f55a502020-02-25 15:21:02 +0100281static int hlua_filter_from_payload(struct filter *filter);
282
Christopher Faulet69c581a2021-05-31 08:54:04 +0200283/* This is the chained list of struct hlua_flt referenced
284 * for haproxy filters. It is used for a post-initialisation control.
285 */
286static struct list referenced_filters = LIST_HEAD_INIT(referenced_filters);
287
288
Thierry FOURNIERebed6e92016-12-16 11:54:07 +0100289/* This is the memory pool containing struct lua for applets
290 * (including cli).
291 */
Willy Tarreau8ceae722018-11-26 11:58:30 +0100292DECLARE_STATIC_POOL(pool_head_hlua, "hlua", sizeof(struct hlua));
Thierry FOURNIERebed6e92016-12-16 11:54:07 +0100293
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +0100294/* Used for Socket connection. */
Amaury Denoyelle239fdbf2021-03-24 10:22:03 +0100295static struct proxy *socket_proxy;
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +0100296static struct server *socket_tcp;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +0100297#ifdef USE_OPENSSL
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +0100298static struct server *socket_ssl;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +0100299#endif
300
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +0100301/* List head of the function called at the initialisation time. */
Thierry Fournierc7492592020-11-28 23:57:24 +0100302struct list hlua_init_functions[MAX_THREADS + 1];
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +0100303
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +0100304/* The following variables contains the reference of the different
305 * Lua classes. These references are useful for identify metadata
306 * associated with an object.
307 */
Thierry FOURNIER65f34c62015-02-16 20:11:43 +0100308static int class_txn_ref;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +0100309static int class_socket_ref;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +0100310static int class_channel_ref;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +0100311static int class_fetches_ref;
Thierry FOURNIER594afe72015-03-10 23:58:30 +0100312static int class_converters_ref;
Thierry FOURNIER08504f42015-03-16 14:17:08 +0100313static int class_http_ref;
Christopher Fauletdf97ac42020-02-26 16:57:19 +0100314static int class_http_msg_ref;
William Lallemand3956c4e2021-09-21 16:25:15 +0200315static int class_httpclient_ref;
Thierry FOURNIER3def3932015-04-07 11:27:54 +0200316static int class_map_ref;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +0200317static int class_applet_tcp_ref;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200318static int class_applet_http_ref;
Christopher Faulet700d9e82020-01-31 12:21:52 +0100319static int class_txn_reply_ref;
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +0100320
Thierry FOURNIERbd413492015-03-03 16:52:26 +0100321/* Global Lua execution timeout. By default Lua, execution linked
Willy Tarreau87b09662015-04-03 00:22:06 +0200322 * with stream (actions, sample-fetches and converters) have a
Thierry FOURNIERbd413492015-03-03 16:52:26 +0100323 * short timeout. Lua linked with tasks doesn't have a timeout
324 * because a task may remain alive during all the haproxy execution.
325 */
326static unsigned int hlua_timeout_session = 4000; /* session timeout. */
327static unsigned int hlua_timeout_task = TICK_ETERNITY; /* task timeout. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +0200328static unsigned int hlua_timeout_applet = 4000; /* applet timeout. */
Thierry FOURNIERbd413492015-03-03 16:52:26 +0100329
Thierry FOURNIERee9f8022015-03-03 17:37:37 +0100330/* Interrupts the Lua processing each "hlua_nb_instruction" instructions.
331 * it is used for preventing infinite loops.
332 *
333 * I test the scheer with an infinite loop containing one incrementation
334 * and one test. I run this loop between 10 seconds, I raise a ceil of
335 * 710M loops from one interrupt each 9000 instructions, so I fix the value
336 * to one interrupt each 10 000 instructions.
337 *
338 * configured | Number of
339 * instructions | loops executed
340 * between two | in milions
341 * forced yields |
342 * ---------------+---------------
343 * 10 | 160
344 * 500 | 670
345 * 1000 | 680
346 * 5000 | 700
347 * 7000 | 700
348 * 8000 | 700
349 * 9000 | 710 <- ceil
350 * 10000 | 710
351 * 100000 | 710
352 * 1000000 | 710
353 *
354 */
355static unsigned int hlua_nb_instruction = 10000;
356
Willy Tarreaucdb53462020-12-02 12:12:00 +0100357/* Descriptor for the memory allocation state. The limit is pre-initialised to
358 * 0 until it is replaced by "tune.lua.maxmem" during the config parsing, or it
359 * is replaced with ~0 during post_init after everything was loaded. This way
360 * it is guaranteed that if limit is ~0 the boot is complete and that if it's
361 * zero it's not yet limited and proper accounting is required.
Willy Tarreau32f61e22015-03-18 17:54:59 +0100362 */
363struct hlua_mem_allocator {
364 size_t allocated;
365 size_t limit;
366};
367
Willy Tarreaucdb53462020-12-02 12:12:00 +0100368static struct hlua_mem_allocator hlua_global_allocator THREAD_ALIGNED(64);
Willy Tarreau32f61e22015-03-18 17:54:59 +0100369
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100370/* These functions converts types between HAProxy internal args or
371 * sample and LUA types. Another function permits to check if the
372 * LUA stack contains arguments according with an required ARG_T
373 * format.
374 */
375static int hlua_arg2lua(lua_State *L, const struct arg *arg);
376static int hlua_lua2arg(lua_State *L, int ud, struct arg *arg);
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100377__LJMP static int hlua_lua2arg_check(lua_State *L, int first, struct arg *argp,
David Carlier0c437f42016-04-27 16:21:56 +0100378 uint64_t mask, struct proxy *p);
Willy Tarreau5eadada2015-03-10 17:28:54 +0100379static int hlua_smp2lua(lua_State *L, struct sample *smp);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100380static int hlua_smp2lua_str(lua_State *L, struct sample *smp);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100381static int hlua_lua2smp(lua_State *L, int ud, struct sample *smp);
382
Christopher Faulet9d1332b2020-02-24 16:46:16 +0100383__LJMP static int hlua_http_get_headers(lua_State *L, struct http_msg *msg);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200384
Thierry Fournier59f11be2020-11-29 00:37:41 +0100385struct prepend_path {
386 struct list l;
387 char *type;
388 char *path;
389};
390
391static struct list prepend_path_list = LIST_HEAD_INIT(prepend_path_list);
392
Thierry FOURNIER23bc3752015-09-11 19:15:43 +0200393#define SEND_ERR(__be, __fmt, __args...) \
394 do { \
395 send_log(__be, LOG_ERR, __fmt, ## __args); \
396 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE)) \
Christopher Faulet767a84b2017-11-24 16:50:31 +0100397 ha_alert(__fmt, ## __args); \
Thierry FOURNIER23bc3752015-09-11 19:15:43 +0200398 } while (0)
399
Thierry Fournier62a22aa2020-11-28 21:06:35 +0100400static inline struct hlua_function *new_hlua_function()
401{
402 struct hlua_function *fcn;
Thierry Fournierc7492592020-11-28 23:57:24 +0100403 int i;
Thierry Fournier62a22aa2020-11-28 21:06:35 +0100404
405 fcn = calloc(1, sizeof(*fcn));
406 if (!fcn)
407 return NULL;
Willy Tarreau2b718102021-04-21 07:32:39 +0200408 LIST_APPEND(&referenced_functions, &fcn->l);
Thierry Fournierc7492592020-11-28 23:57:24 +0100409 for (i = 0; i < MAX_THREADS + 1; i++)
410 fcn->function_ref[i] = -1;
Thierry Fournier62a22aa2020-11-28 21:06:35 +0100411 return fcn;
412}
413
Christopher Fauletdda44442021-04-12 14:05:43 +0200414static inline void release_hlua_function(struct hlua_function *fcn)
415{
416 if (!fcn)
417 return;
418 if (fcn->name)
419 ha_free(&fcn->name);
Willy Tarreau2b718102021-04-21 07:32:39 +0200420 LIST_DELETE(&fcn->l);
Christopher Fauletdda44442021-04-12 14:05:43 +0200421 ha_free(&fcn);
422}
423
Thierry Fournierc7492592020-11-28 23:57:24 +0100424/* If the common state is set, the stack id is 0, otherwise it is the tid + 1 */
425static inline int fcn_ref_to_stack_id(struct hlua_function *fcn)
426{
427 if (fcn->function_ref[0] == -1)
428 return tid + 1;
429 return 0;
430}
431
Christopher Faulet69c581a2021-05-31 08:54:04 +0200432/* Create a new registered filter. Only its name is filled */
433static inline struct hlua_reg_filter *new_hlua_reg_filter(const char *name)
434{
435 struct hlua_reg_filter *reg_flt;
436 int i;
437
438 reg_flt = calloc(1, sizeof(*reg_flt));
439 if (!reg_flt)
440 return NULL;
441 reg_flt->name = strdup(name);
442 if (!reg_flt->name) {
443 free(reg_flt);
444 return NULL;
445 }
446 LIST_APPEND(&referenced_filters, &reg_flt->l);
447 for (i = 0; i < MAX_THREADS + 1; i++) {
448 reg_flt->flt_ref[i] = -1;
449 reg_flt->fun_ref[i] = -1;
450 }
451 return reg_flt;
452}
453
454/* Release a registered filter */
455static inline void release_hlua_reg_filter(struct hlua_reg_filter *reg_flt)
456{
457 if (!reg_flt)
458 return;
459 if (reg_flt->name)
460 ha_free(&reg_flt->name);
461 LIST_DELETE(&reg_flt->l);
462 ha_free(&reg_flt);
463}
464
465/* If the common state is set, the stack id is 0, otherwise it is the tid + 1 */
466static inline int reg_flt_to_stack_id(struct hlua_reg_filter *reg_flt)
467{
468 if (reg_flt->fun_ref[0] == -1)
469 return tid + 1;
470 return 0;
471}
472
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100473/* Used to check an Lua function type in the stack. It creates and
474 * returns a reference of the function. This function throws an
475 * error if the rgument is not a "function".
476 */
477__LJMP unsigned int hlua_checkfunction(lua_State *L, int argno)
478{
479 if (!lua_isfunction(L, argno)) {
Thierry FOURNIERfd1e9552018-02-23 18:41:18 +0100480 const char *msg = lua_pushfstring(L, "function expected, got %s", luaL_typename(L, argno));
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100481 WILL_LJMP(luaL_argerror(L, argno, msg));
482 }
483 lua_pushvalue(L, argno);
484 return luaL_ref(L, LUA_REGISTRYINDEX);
485}
486
Christopher Fauletba9e21d2020-02-25 10:20:04 +0100487/* Used to check an Lua table type in the stack. It creates and
488 * returns a reference of the table. This function throws an
489 * error if the rgument is not a "table".
490 */
491__LJMP unsigned int hlua_checktable(lua_State *L, int argno)
492{
493 if (!lua_istable(L, argno)) {
494 const char *msg = lua_pushfstring(L, "table expected, got %s", luaL_typename(L, argno));
495 WILL_LJMP(luaL_argerror(L, argno, msg));
496 }
497 lua_pushvalue(L, argno);
498 return luaL_ref(L, LUA_REGISTRYINDEX);
499}
500
Christopher Fauletd09cc512021-03-24 14:48:45 +0100501__LJMP const char *hlua_traceback(lua_State *L, const char* sep)
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200502{
503 lua_Debug ar;
504 int level = 0;
Willy Tarreau83061a82018-07-13 11:56:34 +0200505 struct buffer *msg = get_trash_chunk();
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200506
507 while (lua_getstack(L, level++, &ar)) {
508
509 /* Add separator */
Christopher Fauletd09cc512021-03-24 14:48:45 +0100510 if (b_data(msg))
511 chunk_appendf(msg, "%s", sep);
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200512
513 /* Fill fields:
514 * 'S': fills in the fields source, short_src, linedefined, lastlinedefined, and what;
515 * 'l': fills in the field currentline;
516 * 'n': fills in the field name and namewhat;
517 * 't': fills in the field istailcall;
518 */
519 lua_getinfo(L, "Slnt", &ar);
520
521 /* Append code localisation */
522 if (ar.currentline > 0)
Christopher Fauletd09cc512021-03-24 14:48:45 +0100523 chunk_appendf(msg, "%s:%d: ", ar.short_src, ar.currentline);
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200524 else
Christopher Fauletd09cc512021-03-24 14:48:45 +0100525 chunk_appendf(msg, "%s: ", ar.short_src);
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200526
527 /*
528 * Get function name
529 *
530 * if namewhat is no empty, name is defined.
531 * what contains "Lua" for Lua function, "C" for C function,
532 * or "main" for main code.
533 */
534 if (*ar.namewhat != '\0' && ar.name != NULL) /* is there a name from code? */
Christopher Fauletd09cc512021-03-24 14:48:45 +0100535 chunk_appendf(msg, "in %s '%s'", ar.namewhat, ar.name); /* use it */
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200536
537 else if (*ar.what == 'm') /* "main", the code is not executed in a function */
Christopher Fauletd09cc512021-03-24 14:48:45 +0100538 chunk_appendf(msg, "in main chunk");
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200539
540 else if (*ar.what != 'C') /* for Lua functions, use <file:line> */
Christopher Fauletd09cc512021-03-24 14:48:45 +0100541 chunk_appendf(msg, "in function line %d", ar.linedefined);
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200542
543 else /* nothing left... */
544 chunk_appendf(msg, "?");
545
546
547 /* Display tailed call */
548 if (ar.istailcall)
549 chunk_appendf(msg, " ...");
550 }
551
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200552 return msg->area;
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200553}
554
555
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100556/* This function check the number of arguments available in the
557 * stack. If the number of arguments available is not the same
Ilya Shipitsinc02a23f2020-05-06 00:53:22 +0500558 * then <nb> an error is thrown.
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100559 */
560__LJMP static inline void check_args(lua_State *L, int nb, char *fcn)
561{
562 if (lua_gettop(L) == nb)
563 return;
564 WILL_LJMP(luaL_error(L, "'%s' needs %d arguments", fcn, nb));
565}
566
Mark Lakes22154b42018-01-29 14:38:40 -0800567/* This function pushes an error string prefixed by the file name
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100568 * and the line number where the error is encountered.
569 */
570static int hlua_pusherror(lua_State *L, const char *fmt, ...)
571{
572 va_list argp;
573 va_start(argp, fmt);
574 luaL_where(L, 1);
575 lua_pushvfstring(L, fmt, argp);
576 va_end(argp);
577 lua_concat(L, 2);
578 return 1;
579}
580
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100581/* This functions is used with sample fetch and converters. It
582 * converts the HAProxy configuration argument in a lua stack
583 * values.
584 *
585 * It takes an array of "arg", and each entry of the array is
586 * converted and pushed in the LUA stack.
587 */
588static int hlua_arg2lua(lua_State *L, const struct arg *arg)
589{
590 switch (arg->type) {
591 case ARGT_SINT:
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100592 case ARGT_TIME:
593 case ARGT_SIZE:
Thierry FOURNIERf90838b2015-03-06 13:48:32 +0100594 lua_pushinteger(L, arg->data.sint);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100595 break;
596
597 case ARGT_STR:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200598 lua_pushlstring(L, arg->data.str.area, arg->data.str.data);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100599 break;
600
601 case ARGT_IPV4:
602 case ARGT_IPV6:
603 case ARGT_MSK4:
604 case ARGT_MSK6:
605 case ARGT_FE:
606 case ARGT_BE:
607 case ARGT_TAB:
608 case ARGT_SRV:
609 case ARGT_USR:
610 case ARGT_MAP:
611 default:
612 lua_pushnil(L);
613 break;
614 }
615 return 1;
616}
617
Ilya Shipitsinc02a23f2020-05-06 00:53:22 +0500618/* This function take one entry in an LUA stack at the index "ud",
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100619 * and try to convert it in an HAProxy argument entry. This is useful
Ilya Shipitsind4259502020-04-08 01:07:56 +0500620 * with sample fetch wrappers. The input arguments are given to the
621 * lua wrapper and converted as arg list by the function.
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100622 */
623static int hlua_lua2arg(lua_State *L, int ud, struct arg *arg)
624{
625 switch (lua_type(L, ud)) {
626
627 case LUA_TNUMBER:
628 case LUA_TBOOLEAN:
629 arg->type = ARGT_SINT;
630 arg->data.sint = lua_tointeger(L, ud);
631 break;
632
633 case LUA_TSTRING:
634 arg->type = ARGT_STR;
Tim Duesterhus2e89dec2019-09-29 23:03:08 +0200635 arg->data.str.area = (char *)lua_tolstring(L, ud, &arg->data.str.data);
Tim Duesterhus29d2e8a2019-09-29 23:03:07 +0200636 /* We don't know the actual size of the underlying allocation, so be conservative. */
Christopher Fauletfdea1b62020-08-06 08:29:18 +0200637 arg->data.str.size = arg->data.str.data+1; /* count the terminating null byte */
Tim Duesterhus29d2e8a2019-09-29 23:03:07 +0200638 arg->data.str.head = 0;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100639 break;
640
641 case LUA_TUSERDATA:
642 case LUA_TNIL:
643 case LUA_TTABLE:
644 case LUA_TFUNCTION:
645 case LUA_TTHREAD:
646 case LUA_TLIGHTUSERDATA:
647 arg->type = ARGT_SINT;
Thierry FOURNIERbf65cd42015-07-20 17:45:02 +0200648 arg->data.sint = 0;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100649 break;
650 }
651 return 1;
652}
653
654/* the following functions are used to convert a struct sample
655 * in Lua type. This useful to convert the return of the
Ilya Shipitsind4259502020-04-08 01:07:56 +0500656 * fetches or converters.
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100657 */
Willy Tarreau5eadada2015-03-10 17:28:54 +0100658static int hlua_smp2lua(lua_State *L, struct sample *smp)
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100659{
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200660 switch (smp->data.type) {
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100661 case SMP_T_SINT:
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100662 case SMP_T_BOOL:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200663 lua_pushinteger(L, smp->data.u.sint);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100664 break;
665
666 case SMP_T_BIN:
667 case SMP_T_STR:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200668 lua_pushlstring(L, smp->data.u.str.area, smp->data.u.str.data);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100669 break;
670
671 case SMP_T_METH:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200672 switch (smp->data.u.meth.meth) {
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100673 case HTTP_METH_OPTIONS: lua_pushstring(L, "OPTIONS"); break;
674 case HTTP_METH_GET: lua_pushstring(L, "GET"); break;
675 case HTTP_METH_HEAD: lua_pushstring(L, "HEAD"); break;
676 case HTTP_METH_POST: lua_pushstring(L, "POST"); break;
677 case HTTP_METH_PUT: lua_pushstring(L, "PUT"); break;
678 case HTTP_METH_DELETE: lua_pushstring(L, "DELETE"); break;
679 case HTTP_METH_TRACE: lua_pushstring(L, "TRACE"); break;
680 case HTTP_METH_CONNECT: lua_pushstring(L, "CONNECT"); break;
681 case HTTP_METH_OTHER:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200682 lua_pushlstring(L, smp->data.u.meth.str.area, smp->data.u.meth.str.data);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100683 break;
684 default:
685 lua_pushnil(L);
686 break;
687 }
688 break;
689
690 case SMP_T_IPV4:
691 case SMP_T_IPV6:
692 case SMP_T_ADDR: /* This type is never used to qualify a sample. */
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200693 if (sample_casts[smp->data.type][SMP_T_STR] &&
694 sample_casts[smp->data.type][SMP_T_STR](smp))
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200695 lua_pushlstring(L, smp->data.u.str.area, smp->data.u.str.data);
Willy Tarreau5eadada2015-03-10 17:28:54 +0100696 else
697 lua_pushnil(L);
698 break;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100699 default:
700 lua_pushnil(L);
701 break;
702 }
703 return 1;
704}
705
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100706/* the following functions are used to convert a struct sample
707 * in Lua strings. This is useful to convert the return of the
Ilya Shipitsind4259502020-04-08 01:07:56 +0500708 * fetches or converters.
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100709 */
710static int hlua_smp2lua_str(lua_State *L, struct sample *smp)
711{
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200712 switch (smp->data.type) {
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100713
714 case SMP_T_BIN:
715 case SMP_T_STR:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200716 lua_pushlstring(L, smp->data.u.str.area, smp->data.u.str.data);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100717 break;
718
719 case SMP_T_METH:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200720 switch (smp->data.u.meth.meth) {
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100721 case HTTP_METH_OPTIONS: lua_pushstring(L, "OPTIONS"); break;
722 case HTTP_METH_GET: lua_pushstring(L, "GET"); break;
723 case HTTP_METH_HEAD: lua_pushstring(L, "HEAD"); break;
724 case HTTP_METH_POST: lua_pushstring(L, "POST"); break;
725 case HTTP_METH_PUT: lua_pushstring(L, "PUT"); break;
726 case HTTP_METH_DELETE: lua_pushstring(L, "DELETE"); break;
727 case HTTP_METH_TRACE: lua_pushstring(L, "TRACE"); break;
728 case HTTP_METH_CONNECT: lua_pushstring(L, "CONNECT"); break;
729 case HTTP_METH_OTHER:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200730 lua_pushlstring(L, smp->data.u.meth.str.area, smp->data.u.meth.str.data);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100731 break;
732 default:
733 lua_pushstring(L, "");
734 break;
735 }
736 break;
737
738 case SMP_T_SINT:
739 case SMP_T_BOOL:
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100740 case SMP_T_IPV4:
741 case SMP_T_IPV6:
742 case SMP_T_ADDR: /* This type is never used to qualify a sample. */
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200743 if (sample_casts[smp->data.type][SMP_T_STR] &&
744 sample_casts[smp->data.type][SMP_T_STR](smp))
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200745 lua_pushlstring(L, smp->data.u.str.area, smp->data.u.str.data);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100746 else
747 lua_pushstring(L, "");
748 break;
749 default:
750 lua_pushstring(L, "");
751 break;
752 }
753 return 1;
754}
755
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100756/* the following functions are used to convert an Lua type in a
757 * struct sample. This is useful to provide data from a converter
758 * to the LUA code.
759 */
760static int hlua_lua2smp(lua_State *L, int ud, struct sample *smp)
761{
762 switch (lua_type(L, ud)) {
763
764 case LUA_TNUMBER:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200765 smp->data.type = SMP_T_SINT;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200766 smp->data.u.sint = lua_tointeger(L, ud);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100767 break;
768
769
770 case LUA_TBOOLEAN:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200771 smp->data.type = SMP_T_BOOL;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200772 smp->data.u.sint = lua_toboolean(L, ud);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100773 break;
774
775 case LUA_TSTRING:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200776 smp->data.type = SMP_T_STR;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100777 smp->flags |= SMP_F_CONST;
Tim Duesterhus2e89dec2019-09-29 23:03:08 +0200778 smp->data.u.str.area = (char *)lua_tolstring(L, ud, &smp->data.u.str.data);
Tim Duesterhus29d2e8a2019-09-29 23:03:07 +0200779 /* We don't know the actual size of the underlying allocation, so be conservative. */
Christopher Fauletfdea1b62020-08-06 08:29:18 +0200780 smp->data.u.str.size = smp->data.u.str.data+1; /* count the terminating null byte */
Tim Duesterhus29d2e8a2019-09-29 23:03:07 +0200781 smp->data.u.str.head = 0;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100782 break;
783
784 case LUA_TUSERDATA:
785 case LUA_TNIL:
786 case LUA_TTABLE:
787 case LUA_TFUNCTION:
788 case LUA_TTHREAD:
789 case LUA_TLIGHTUSERDATA:
Thierry FOURNIER93405e12015-08-26 14:19:03 +0200790 case LUA_TNONE:
791 default:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200792 smp->data.type = SMP_T_BOOL;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200793 smp->data.u.sint = 0;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100794 break;
795 }
796 return 1;
797}
798
Ilya Shipitsind4259502020-04-08 01:07:56 +0500799/* This function check the "argp" built by another conversion function
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -0800800 * is in accord with the expected argp defined by the "mask". The function
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100801 * returns true or false. It can be adjust the types if there compatibles.
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100802 *
Ilya Shipitsinc02a23f2020-05-06 00:53:22 +0500803 * This function assumes that the argp argument contains ARGM_NBARGS + 1
Willy Tarreauee0d7272021-07-16 10:26:56 +0200804 * entries and that there is at least one stop at the last position.
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100805 */
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100806__LJMP int hlua_lua2arg_check(lua_State *L, int first, struct arg *argp,
David Carlier0c437f42016-04-27 16:21:56 +0100807 uint64_t mask, struct proxy *p)
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100808{
809 int min_arg;
Willy Tarreauee0d7272021-07-16 10:26:56 +0200810 int idx;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100811 struct proxy *px;
Christopher Fauletd25d9262020-08-06 11:04:46 +0200812 struct userlist *ul;
Christopher Fauletfd2e9062020-08-06 11:10:57 +0200813 struct my_regex *reg;
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200814 const char *msg = NULL;
Christopher Fauletfd2e9062020-08-06 11:10:57 +0200815 char *sname, *pname, *err = NULL;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100816
817 idx = 0;
818 min_arg = ARGM(mask);
819 mask >>= ARGM_BITS;
820
821 while (1) {
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200822 struct buffer tmp = BUF_NULL;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100823
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100824 /* Check for mandatory arguments. */
825 if (argp[idx].type == ARGT_STOP) {
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100826 if (idx < min_arg) {
827
828 /* If miss other argument than the first one, we return an error. */
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200829 if (idx > 0) {
830 msg = "Mandatory argument expected";
831 goto error;
832 }
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100833
834 /* If first argument have a certain type, some default values
835 * may be used. See the function smp_resolve_args().
836 */
837 switch (mask & ARGT_MASK) {
838
839 case ARGT_FE:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200840 if (!(p->cap & PR_CAP_FE)) {
841 msg = "Mandatory argument expected";
842 goto error;
843 }
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100844 argp[idx].data.prx = p;
845 argp[idx].type = ARGT_FE;
846 argp[idx+1].type = ARGT_STOP;
847 break;
848
849 case ARGT_BE:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200850 if (!(p->cap & PR_CAP_BE)) {
851 msg = "Mandatory argument expected";
852 goto error;
853 }
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100854 argp[idx].data.prx = p;
855 argp[idx].type = ARGT_BE;
856 argp[idx+1].type = ARGT_STOP;
857 break;
858
859 case ARGT_TAB:
860 argp[idx].data.prx = p;
861 argp[idx].type = ARGT_TAB;
862 argp[idx+1].type = ARGT_STOP;
863 break;
864
865 default:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200866 msg = "Mandatory argument expected";
867 goto error;
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100868 break;
869 }
870 }
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200871 break;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100872 }
873
Ilya Shipitsin856aabc2020-04-16 23:51:34 +0500874 /* Check for exceed the number of required argument. */
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100875 if ((mask & ARGT_MASK) == ARGT_STOP &&
876 argp[idx].type != ARGT_STOP) {
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200877 msg = "Last argument expected";
878 goto error;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100879 }
880
881 if ((mask & ARGT_MASK) == ARGT_STOP &&
882 argp[idx].type == ARGT_STOP) {
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200883 break;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100884 }
885
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200886 /* Convert some argument types. All string in argp[] are for not
887 * duplicated yet.
888 */
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100889 switch (mask & ARGT_MASK) {
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100890 case ARGT_SINT:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200891 if (argp[idx].type != ARGT_SINT) {
892 msg = "integer expected";
893 goto error;
894 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100895 argp[idx].type = ARGT_SINT;
896 break;
897
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100898 case ARGT_TIME:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200899 if (argp[idx].type != ARGT_SINT) {
900 msg = "integer expected";
901 goto error;
902 }
Thierry FOURNIER29176f32015-07-07 00:41:29 +0200903 argp[idx].type = ARGT_TIME;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100904 break;
905
906 case ARGT_SIZE:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200907 if (argp[idx].type != ARGT_SINT) {
908 msg = "integer expected";
909 goto error;
910 }
Thierry FOURNIER29176f32015-07-07 00:41:29 +0200911 argp[idx].type = ARGT_SIZE;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100912 break;
913
914 case ARGT_FE:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200915 if (argp[idx].type != ARGT_STR) {
916 msg = "string expected";
917 goto error;
918 }
Christopher Fauletfdea1b62020-08-06 08:29:18 +0200919 argp[idx].data.prx = proxy_fe_by_name(argp[idx].data.str.area);
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200920 if (!argp[idx].data.prx) {
921 msg = "frontend doesn't exist";
922 goto error;
923 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100924 argp[idx].type = ARGT_FE;
925 break;
926
927 case ARGT_BE:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200928 if (argp[idx].type != ARGT_STR) {
929 msg = "string expected";
930 goto error;
931 }
Christopher Fauletfdea1b62020-08-06 08:29:18 +0200932 argp[idx].data.prx = proxy_be_by_name(argp[idx].data.str.area);
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200933 if (!argp[idx].data.prx) {
934 msg = "backend doesn't exist";
935 goto error;
936 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100937 argp[idx].type = ARGT_BE;
938 break;
939
940 case ARGT_TAB:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200941 if (argp[idx].type != ARGT_STR) {
942 msg = "string expected";
943 goto error;
944 }
Christopher Fauletfdea1b62020-08-06 08:29:18 +0200945 argp[idx].data.t = stktable_find_by_name(argp[idx].data.str.area);
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200946 if (!argp[idx].data.t) {
947 msg = "table doesn't exist";
948 goto error;
949 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100950 argp[idx].type = ARGT_TAB;
951 break;
952
953 case ARGT_SRV:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200954 if (argp[idx].type != ARGT_STR) {
955 msg = "string expected";
956 goto error;
957 }
Christopher Fauletfdea1b62020-08-06 08:29:18 +0200958 sname = strrchr(argp[idx].data.str.area, '/');
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100959 if (sname) {
960 *sname++ = '\0';
Christopher Fauletfdea1b62020-08-06 08:29:18 +0200961 pname = argp[idx].data.str.area;
Willy Tarreau9e0bb102015-05-26 11:24:42 +0200962 px = proxy_be_by_name(pname);
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200963 if (!px) {
964 msg = "backend doesn't exist";
965 goto error;
966 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100967 }
968 else {
Christopher Fauletfdea1b62020-08-06 08:29:18 +0200969 sname = argp[idx].data.str.area;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100970 px = p;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100971 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100972 argp[idx].data.srv = findserver(px, sname);
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200973 if (!argp[idx].data.srv) {
974 msg = "server doesn't exist";
975 goto error;
976 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100977 argp[idx].type = ARGT_SRV;
978 break;
979
980 case ARGT_IPV4:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200981 if (argp[idx].type != ARGT_STR) {
982 msg = "string expected";
983 goto error;
984 }
985 if (inet_pton(AF_INET, argp[idx].data.str.area, &argp[idx].data.ipv4)) {
986 msg = "invalid IPv4 address";
987 goto error;
988 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100989 argp[idx].type = ARGT_IPV4;
990 break;
991
992 case ARGT_MSK4:
Christopher Faulete663a6e2020-08-07 09:11:22 +0200993 if (argp[idx].type == ARGT_SINT)
994 len2mask4(argp[idx].data.sint, &argp[idx].data.ipv4);
995 else if (argp[idx].type == ARGT_STR) {
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200996 if (!str2mask(argp[idx].data.str.area, &argp[idx].data.ipv4)) {
997 msg = "invalid IPv4 mask";
998 goto error;
999 }
1000 }
1001 else {
1002 msg = "integer or string expected";
1003 goto error;
Christopher Faulete663a6e2020-08-07 09:11:22 +02001004 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001005 argp[idx].type = ARGT_MSK4;
1006 break;
1007
1008 case ARGT_IPV6:
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001009 if (argp[idx].type != ARGT_STR) {
1010 msg = "string expected";
1011 goto error;
1012 }
1013 if (inet_pton(AF_INET6, argp[idx].data.str.area, &argp[idx].data.ipv6)) {
1014 msg = "invalid IPv6 address";
1015 goto error;
1016 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001017 argp[idx].type = ARGT_IPV6;
1018 break;
1019
1020 case ARGT_MSK6:
Christopher Faulete663a6e2020-08-07 09:11:22 +02001021 if (argp[idx].type == ARGT_SINT)
1022 len2mask6(argp[idx].data.sint, &argp[idx].data.ipv6);
1023 else if (argp[idx].type == ARGT_STR) {
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001024 if (!str2mask6(argp[idx].data.str.area, &argp[idx].data.ipv6)) {
1025 msg = "invalid IPv6 mask";
1026 goto error;
1027 }
1028 }
1029 else {
1030 msg = "integer or string expected";
1031 goto error;
Christopher Faulete663a6e2020-08-07 09:11:22 +02001032 }
Tim Duesterhusb814da62018-01-25 16:24:50 +01001033 argp[idx].type = ARGT_MSK6;
1034 break;
1035
Christopher Fauletfd2e9062020-08-06 11:10:57 +02001036 case ARGT_REG:
1037 if (argp[idx].type != ARGT_STR) {
1038 msg = "string expected";
1039 goto error;
1040 }
1041 reg = regex_comp(argp[idx].data.str.area, !(argp[idx].type_flags & ARGF_REG_ICASE), 1, &err);
1042 if (!reg) {
1043 msg = lua_pushfstring(L, "error compiling regex '%s' : '%s'",
1044 argp[idx].data.str.area, err);
1045 free(err);
1046 goto error;
1047 }
1048 argp[idx].type = ARGT_REG;
1049 argp[idx].data.reg = reg;
1050 break;
1051
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001052 case ARGT_USR:
Christopher Fauletd25d9262020-08-06 11:04:46 +02001053 if (argp[idx].type != ARGT_STR) {
1054 msg = "string expected";
1055 goto error;
1056 }
1057 if (p->uri_auth && p->uri_auth->userlist &&
Tim Duesterhuse5ff1412021-01-02 22:31:53 +01001058 strcmp(p->uri_auth->userlist->name, argp[idx].data.str.area) == 0)
Christopher Fauletd25d9262020-08-06 11:04:46 +02001059 ul = p->uri_auth->userlist;
1060 else
1061 ul = auth_find_userlist(argp[idx].data.str.area);
1062
1063 if (!ul) {
1064 msg = lua_pushfstring(L, "unable to find userlist '%s'", argp[idx].data.str.area);
1065 goto error;
1066 }
1067 argp[idx].type = ARGT_USR;
1068 argp[idx].data.usr = ul;
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001069 break;
1070
1071 case ARGT_STR:
1072 if (!chunk_dup(&tmp, &argp[idx].data.str)) {
1073 msg = "unable to duplicate string arg";
1074 goto error;
1075 }
1076 argp[idx].data.str = tmp;
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001077 break;
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001078
Christopher Fauletd25d9262020-08-06 11:04:46 +02001079 case ARGT_MAP:
Christopher Fauletd25d9262020-08-06 11:04:46 +02001080 msg = "type not yet supported";
1081 goto error;
1082 break;
1083
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001084 }
1085
1086 /* Check for type of argument. */
1087 if ((mask & ARGT_MASK) != argp[idx].type) {
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001088 msg = lua_pushfstring(L, "'%s' expected, got '%s'",
1089 arg_type_names[(mask & ARGT_MASK)],
1090 arg_type_names[argp[idx].type & ARGT_MASK]);
1091 goto error;
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001092 }
1093
1094 /* Next argument. */
1095 mask >>= ARGT_BITS;
1096 idx++;
1097 }
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001098 return 0;
1099
1100 error:
Willy Tarreauee0d7272021-07-16 10:26:56 +02001101 free_args(argp);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001102 WILL_LJMP(luaL_argerror(L, first + idx, msg));
1103 return 0; /* Never reached */
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001104}
1105
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001106/*
Ilya Shipitsinc02a23f2020-05-06 00:53:22 +05001107 * The following functions are used to make correspondence between the the
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001108 * executed lua pointer and the "struct hlua *" that contain the context.
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001109 *
1110 * - hlua_gethlua : return the hlua context associated with an lua_State.
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001111 * - hlua_sethlua : create the association between hlua context and lua_state.
1112 */
1113static inline struct hlua *hlua_gethlua(lua_State *L)
1114{
Thierry FOURNIER38c5fd62015-03-10 02:40:29 +01001115 struct hlua **hlua = lua_getextraspace(L);
1116 return *hlua;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001117}
1118static inline void hlua_sethlua(struct hlua *hlua)
1119{
Thierry FOURNIER38c5fd62015-03-10 02:40:29 +01001120 struct hlua **hlua_store = lua_getextraspace(hlua->T);
1121 *hlua_store = hlua;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001122}
1123
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01001124/* This function is used to send logs. It try to send on screen (stderr)
1125 * and on the default syslog server.
1126 */
1127static inline void hlua_sendlog(struct proxy *px, int level, const char *msg)
1128{
1129 struct tm tm;
1130 char *p;
1131
1132 /* Cleanup the log message. */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001133 p = trash.area;
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01001134 for (; *msg != '\0'; msg++, p++) {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001135 if (p >= trash.area + trash.size - 1) {
Thierry FOURNIERccf00632015-09-16 12:47:03 +02001136 /* Break the message if exceed the buffer size. */
1137 *(p-4) = ' ';
1138 *(p-3) = '.';
1139 *(p-2) = '.';
1140 *(p-1) = '.';
1141 break;
1142 }
Willy Tarreau90807112020-02-25 08:16:33 +01001143 if (isprint((unsigned char)*msg))
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01001144 *p = *msg;
1145 else
1146 *p = '.';
1147 }
1148 *p = '\0';
1149
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001150 send_log(px, level, "%s\n", trash.area);
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01001151 if (!(global.mode & MODE_QUIET) || (global.mode & (MODE_VERBOSE | MODE_STARTING))) {
Christopher Fauletf98d8212020-10-02 18:13:52 +02001152 if (level == LOG_DEBUG && !(global.mode & MODE_DEBUG))
1153 return;
1154
Willy Tarreaua678b432015-08-28 10:14:59 +02001155 get_localtime(date.tv_sec, &tm);
1156 fprintf(stderr, "[%s] %03d/%02d%02d%02d (%d) : %s\n",
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01001157 log_levels[level], tm.tm_yday, tm.tm_hour, tm.tm_min, tm.tm_sec,
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001158 (int)getpid(), trash.area);
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01001159 fflush(stderr);
1160 }
1161}
1162
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001163/* This function just ensure that the yield will be always
1164 * returned with a timeout and permit to set some flags
1165 */
1166__LJMP void hlua_yieldk(lua_State *L, int nresults, int ctx,
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001167 lua_KFunction k, int timeout, unsigned int flags)
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001168{
Thierry Fournier4234dbd2020-11-28 13:18:23 +01001169 struct hlua *hlua;
1170
1171 /* Get hlua struct, or NULL if we execute from main lua state */
1172 hlua = hlua_gethlua(L);
1173 if (!hlua) {
1174 return;
1175 }
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001176
1177 /* Set the wake timeout. If timeout is required, we set
1178 * the expiration time.
1179 */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001180 hlua->wake_time = timeout;
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001181
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01001182 hlua->flags |= flags;
1183
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001184 /* Process the yield. */
Willy Tarreau9635e032018-10-16 17:52:55 +02001185 MAY_LJMP(lua_yieldk(L, nresults, ctx, k));
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001186}
1187
Willy Tarreau87b09662015-04-03 00:22:06 +02001188/* This function initialises the Lua environment stored in the stream.
1189 * It must be called at the start of the stream. This function creates
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001190 * an LUA coroutine. It can not be use to crete the main LUA context.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02001191 *
1192 * This function is particular. it initialises a new Lua thread. If the
1193 * initialisation fails (example: out of memory error), the lua function
1194 * throws an error (longjmp).
1195 *
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +01001196 * In some case (at least one), this function can be called from safe
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001197 * environment, so we must not initialise it. While the support of
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +01001198 * threads appear, the safe environment set a lock to ensure only one
1199 * Lua execution at a time. If we initialize safe environment in another
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001200 * safe environment, we have a dead lock.
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +01001201 *
1202 * set "already_safe" true if the context is initialized form safe
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001203 * Lua function.
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +01001204 *
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001205 * This function manipulates two Lua stacks: the main and the thread. Only
Thierry FOURNIERbabae282015-09-17 11:36:37 +02001206 * the main stack can fail. The thread is not manipulated. This function
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001207 * MUST NOT manipulate the created thread stack state, because it is not
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001208 * protected against errors thrown by the thread stack.
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001209 */
Thierry Fournier021d9862020-11-28 23:42:03 +01001210int hlua_ctx_init(struct hlua *lua, int state_id, struct task *task, int already_safe)
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001211{
1212 lua->Mref = LUA_REFNIL;
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001213 lua->flags = 0;
Willy Tarreauf31af932020-01-14 09:59:38 +01001214 lua->gc_count = 0;
Christopher Fauletbc275a92020-02-26 14:55:16 +01001215 lua->wake_time = TICK_ETERNITY;
Thierry Fournier021d9862020-11-28 23:42:03 +01001216 lua->state_id = state_id;
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01001217 LIST_INIT(&lua->com);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001218 if (!already_safe) {
1219 if (!SET_SAFE_LJMP_PARENT(lua)) {
1220 lua->Tref = LUA_REFNIL;
1221 return 0;
1222 }
1223 }
Thierry Fournier021d9862020-11-28 23:42:03 +01001224 lua->T = lua_newthread(hlua_states[state_id]);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001225 if (!lua->T) {
1226 lua->Tref = LUA_REFNIL;
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +01001227 if (!already_safe)
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001228 RESET_SAFE_LJMP_PARENT(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001229 return 0;
1230 }
1231 hlua_sethlua(lua);
Thierry Fournier021d9862020-11-28 23:42:03 +01001232 lua->Tref = luaL_ref(hlua_states[state_id], LUA_REGISTRYINDEX);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001233 lua->task = task;
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +01001234 if (!already_safe)
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001235 RESET_SAFE_LJMP_PARENT(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001236 return 1;
1237}
1238
Willy Tarreau87b09662015-04-03 00:22:06 +02001239/* Used to destroy the Lua coroutine when the attached stream or task
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001240 * is destroyed. The destroy also the memory context. The struct "lua"
1241 * is not freed.
1242 */
1243void hlua_ctx_destroy(struct hlua *lua)
1244{
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01001245 if (!lua)
Thierry FOURNIERa718b292015-03-04 16:48:34 +01001246 return;
1247
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01001248 if (!lua->T)
1249 goto end;
1250
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01001251 /* Purge all the pending signals. */
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001252 notification_purge(&lua->com);
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01001253
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001254 if (!SET_SAFE_LJMP(lua))
Thierry FOURNIER75d02082017-07-12 13:41:33 +02001255 return;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001256 luaL_unref(lua->T, LUA_REGISTRYINDEX, lua->Mref);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001257 RESET_SAFE_LJMP(lua);
Thierry FOURNIER5a50a852015-09-23 16:59:28 +02001258
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001259 if (!SET_SAFE_LJMP_PARENT(lua))
Thierry FOURNIER75d02082017-07-12 13:41:33 +02001260 return;
Thierry Fournier021d9862020-11-28 23:42:03 +01001261 luaL_unref(hlua_states[lua->state_id], LUA_REGISTRYINDEX, lua->Tref);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001262 RESET_SAFE_LJMP_PARENT(lua);
Thierry FOURNIER5a50a852015-09-23 16:59:28 +02001263 /* Forces a garbage collecting process. If the Lua program is finished
1264 * without error, we run the GC on the thread pointer. Its freed all
1265 * the unused memory.
1266 * If the thread is finnish with an error or is currently yielded,
1267 * it seems that the GC applied on the thread doesn't clean anything,
1268 * so e run the GC on the main thread.
1269 * NOTE: maybe this action locks all the Lua threads untiml the en of
1270 * the garbage collection.
1271 */
Willy Tarreauf31af932020-01-14 09:59:38 +01001272 if (lua->gc_count) {
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001273 if (!SET_SAFE_LJMP_PARENT(lua))
Thierry FOURNIER75d02082017-07-12 13:41:33 +02001274 return;
Thierry Fournier021d9862020-11-28 23:42:03 +01001275 lua_gc(hlua_states[lua->state_id], LUA_GCCOLLECT, 0);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001276 RESET_SAFE_LJMP_PARENT(lua);
Thierry FOURNIER7c39ab42015-09-27 22:53:33 +02001277 }
Thierry FOURNIER5a50a852015-09-23 16:59:28 +02001278
Thierry FOURNIERa7b536b2015-09-21 22:50:24 +02001279 lua->T = NULL;
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01001280
1281end:
Willy Tarreaubafbe012017-11-24 17:34:44 +01001282 pool_free(pool_head_hlua, lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001283}
1284
1285/* This function is used to restore the Lua context when a coroutine
1286 * fails. This function copy the common memory between old coroutine
1287 * and the new coroutine. The old coroutine is destroyed, and its
1288 * replaced by the new coroutine.
1289 * If the flag "keep_msg" is set, the last entry of the old is assumed
1290 * as string error message and it is copied in the new stack.
1291 */
1292static int hlua_ctx_renew(struct hlua *lua, int keep_msg)
1293{
1294 lua_State *T;
1295 int new_ref;
1296
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001297 /* New Lua coroutine. */
Thierry Fournier021d9862020-11-28 23:42:03 +01001298 T = lua_newthread(hlua_states[lua->state_id]);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001299 if (!T)
1300 return 0;
1301
1302 /* Copy last error message. */
1303 if (keep_msg)
1304 lua_xmove(lua->T, T, 1);
1305
1306 /* Copy data between the coroutines. */
1307 lua_rawgeti(lua->T, LUA_REGISTRYINDEX, lua->Mref);
1308 lua_xmove(lua->T, T, 1);
Ilya Shipitsin46a030c2020-07-05 16:36:08 +05001309 new_ref = luaL_ref(T, LUA_REGISTRYINDEX); /* Value popped. */
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001310
1311 /* Destroy old data. */
1312 luaL_unref(lua->T, LUA_REGISTRYINDEX, lua->Mref);
1313
1314 /* The thread is garbage collected by Lua. */
Thierry Fournier021d9862020-11-28 23:42:03 +01001315 luaL_unref(hlua_states[lua->state_id], LUA_REGISTRYINDEX, lua->Tref);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001316
1317 /* Fill the struct with the new coroutine values. */
1318 lua->Mref = new_ref;
1319 lua->T = T;
Thierry Fournier021d9862020-11-28 23:42:03 +01001320 lua->Tref = luaL_ref(hlua_states[lua->state_id], LUA_REGISTRYINDEX);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001321
1322 /* Set context. */
1323 hlua_sethlua(lua);
1324
1325 return 1;
1326}
1327
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001328void hlua_hook(lua_State *L, lua_Debug *ar)
1329{
Thierry Fournier4234dbd2020-11-28 13:18:23 +01001330 struct hlua *hlua;
1331
1332 /* Get hlua struct, or NULL if we execute from main lua state */
1333 hlua = hlua_gethlua(L);
1334 if (!hlua)
1335 return;
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001336
1337 /* Lua cannot yield when its returning from a function,
1338 * so, we can fix the interrupt hook to 1 instruction,
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001339 * expecting that the function is finished.
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001340 */
1341 if (lua_gethookmask(L) & LUA_MASKRET) {
1342 lua_sethook(hlua->T, hlua_hook, LUA_MASKCOUNT, 1);
1343 return;
1344 }
1345
1346 /* restore the interrupt condition. */
1347 lua_sethook(hlua->T, hlua_hook, LUA_MASKCOUNT, hlua_nb_instruction);
1348
1349 /* If we interrupt the Lua processing in yieldable state, we yield.
1350 * If the state is not yieldable, trying yield causes an error.
1351 */
1352 if (lua_isyieldable(L))
Willy Tarreau9635e032018-10-16 17:52:55 +02001353 MAY_LJMP(hlua_yieldk(L, 0, 0, NULL, TICK_ETERNITY, HLUA_CTRLYIELD));
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001354
Thierry FOURNIERa85cfb12015-03-13 14:50:06 +01001355 /* If we cannot yield, update the clock and check the timeout. */
Willy Tarreau55542642021-10-08 09:33:24 +02001356 clock_update_date(0, 1);
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001357 hlua->run_time += now_ms - hlua->start_time;
1358 if (hlua->max_time && hlua->run_time >= hlua->max_time) {
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001359 lua_pushfstring(L, "execution timeout");
1360 WILL_LJMP(lua_error(L));
1361 }
1362
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001363 /* Update the start time. */
1364 hlua->start_time = now_ms;
1365
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001366 /* Try to interrupt the process at the end of the current
1367 * unyieldable function.
1368 */
1369 lua_sethook(hlua->T, hlua_hook, LUA_MASKRET|LUA_MASKCOUNT, hlua_nb_instruction);
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001370}
1371
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001372/* This function start or resumes the Lua stack execution. If the flag
1373 * "yield_allowed" if no set and the LUA stack execution returns a yield
1374 * The function return an error.
1375 *
1376 * The function can returns 4 values:
1377 * - HLUA_E_OK : The execution is terminated without any errors.
1378 * - HLUA_E_AGAIN : The execution must continue at the next associated
1379 * task wakeup.
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001380 * - HLUA_E_ERRMSG : An error has occurred, an error message is set in
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001381 * the top of the stack.
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001382 * - HLUA_E_ERR : An error has occurred without error message.
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001383 *
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001384 * If an error occurred, the stack is renewed and it is ready to run new
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001385 * LUA code.
1386 */
1387static enum hlua_exec hlua_ctx_resume(struct hlua *lua, int yield_allowed)
1388{
Christopher Faulet08ed98f2020-07-28 10:33:25 +02001389#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM >= 504
1390 int nres;
1391#endif
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001392 int ret;
1393 const char *msg;
Thierry FOURNIERfc044c92018-06-07 14:40:48 +02001394 const char *trace;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001395
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001396 /* Initialise run time counter. */
1397 if (!HLUA_IS_RUNNING(lua))
1398 lua->run_time = 0;
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001399
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +02001400 /* Lock the whole Lua execution. This lock must be before the
1401 * label "resume_execution".
1402 */
Thierry Fournier021d9862020-11-28 23:42:03 +01001403 if (lua->state_id == 0)
Willy Tarreau1e7bef12021-08-20 15:47:25 +02001404 lua_take_global_lock();
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +02001405
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001406resume_execution:
1407
1408 /* This hook interrupts the Lua processing each 'hlua_nb_instruction'
1409 * instructions. it is used for preventing infinite loops.
1410 */
1411 lua_sethook(lua->T, hlua_hook, LUA_MASKCOUNT, hlua_nb_instruction);
1412
Thierry FOURNIER1bfc09b2015-03-05 17:10:14 +01001413 /* Remove all flags except the running flags. */
Thierry FOURNIER2f3867f2015-09-28 01:02:01 +02001414 HLUA_SET_RUN(lua);
1415 HLUA_CLR_CTRLYIELD(lua);
1416 HLUA_CLR_WAKERESWR(lua);
1417 HLUA_CLR_WAKEREQWR(lua);
Christopher Faulet1f43a342021-08-04 17:58:21 +02001418 HLUA_CLR_NOYIELD(lua);
1419 if (!yield_allowed)
1420 HLUA_SET_NOYIELD(lua);
Thierry FOURNIER1bfc09b2015-03-05 17:10:14 +01001421
Christopher Fauletbc275a92020-02-26 14:55:16 +01001422 /* Update the start time and reset wake_time. */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001423 lua->start_time = now_ms;
Christopher Fauletbc275a92020-02-26 14:55:16 +01001424 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001425
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001426 /* Call the function. */
Christopher Faulet08ed98f2020-07-28 10:33:25 +02001427#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM >= 504
Thierry Fournier021d9862020-11-28 23:42:03 +01001428 ret = lua_resume(lua->T, hlua_states[lua->state_id], lua->nargs, &nres);
Christopher Faulet08ed98f2020-07-28 10:33:25 +02001429#else
Thierry Fournier021d9862020-11-28 23:42:03 +01001430 ret = lua_resume(lua->T, hlua_states[lua->state_id], lua->nargs);
Christopher Faulet08ed98f2020-07-28 10:33:25 +02001431#endif
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001432 switch (ret) {
1433
1434 case LUA_OK:
1435 ret = HLUA_E_OK;
1436 break;
1437
1438 case LUA_YIELD:
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001439 /* Check if the execution timeout is expired. It it is the case, we
1440 * break the Lua execution.
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001441 */
Willy Tarreau55542642021-10-08 09:33:24 +02001442 clock_update_date(0, 1);
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001443 lua->run_time += now_ms - lua->start_time;
1444 if (lua->max_time && lua->run_time > lua->max_time) {
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001445 lua_settop(lua->T, 0); /* Empty the stack. */
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001446 ret = HLUA_E_ETMOUT;
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001447 break;
1448 }
1449 /* Process the forced yield. if the general yield is not allowed or
1450 * if no task were associated this the current Lua execution
1451 * coroutine, we resume the execution. Else we want to return in the
1452 * scheduler and we want to be waked up again, to continue the
1453 * current Lua execution. So we schedule our own task.
1454 */
1455 if (HLUA_IS_CTRLYIELDING(lua)) {
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001456 if (!yield_allowed || !lua->task)
1457 goto resume_execution;
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001458 task_wakeup(lua->task, TASK_WOKEN_MSG);
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001459 }
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001460 if (!yield_allowed) {
1461 lua_settop(lua->T, 0); /* Empty the stack. */
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001462 ret = HLUA_E_YIELD;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001463 break;
1464 }
1465 ret = HLUA_E_AGAIN;
1466 break;
1467
1468 case LUA_ERRRUN:
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001469
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001470 /* Special exit case. The traditional exit is returned as an error
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001471 * because the errors ares the only one mean to return immediately
1472 * from and lua execution.
1473 */
1474 if (lua->flags & HLUA_EXIT) {
1475 ret = HLUA_E_OK;
Christopher Faulet7716cdf2020-01-29 11:53:30 +01001476 hlua_ctx_renew(lua, 1);
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001477 break;
1478 }
1479
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001480 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001481 if (!lua_checkstack(lua->T, 1)) {
1482 ret = HLUA_E_ERR;
1483 break;
1484 }
1485 msg = lua_tostring(lua->T, -1);
1486 lua_settop(lua->T, 0); /* Empty the stack. */
1487 lua_pop(lua->T, 1);
Christopher Fauletd09cc512021-03-24 14:48:45 +01001488 trace = hlua_traceback(lua->T, ", ");
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001489 if (msg)
Thierry Fournier46278ff2020-11-29 11:48:12 +01001490 lua_pushfstring(lua->T, "[state-id %d] runtime error: %s from %s", lua->state_id, msg, trace);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001491 else
Thierry Fournier46278ff2020-11-29 11:48:12 +01001492 lua_pushfstring(lua->T, "[state-id %d] unknown runtime error from %s", lua->state_id, trace);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001493 ret = HLUA_E_ERRMSG;
1494 break;
1495
1496 case LUA_ERRMEM:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001497 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001498 lua_settop(lua->T, 0); /* Empty the stack. */
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001499 ret = HLUA_E_NOMEM;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001500 break;
1501
1502 case LUA_ERRERR:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001503 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001504 if (!lua_checkstack(lua->T, 1)) {
1505 ret = HLUA_E_ERR;
1506 break;
1507 }
1508 msg = lua_tostring(lua->T, -1);
1509 lua_settop(lua->T, 0); /* Empty the stack. */
1510 lua_pop(lua->T, 1);
1511 if (msg)
Thierry Fournier46278ff2020-11-29 11:48:12 +01001512 lua_pushfstring(lua->T, "[state-id %d] message handler error: %s", lua->state_id, msg);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001513 else
Thierry Fournier46278ff2020-11-29 11:48:12 +01001514 lua_pushfstring(lua->T, "[state-id %d] message handler error", lua->state_id);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001515 ret = HLUA_E_ERRMSG;
1516 break;
1517
1518 default:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001519 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001520 lua_settop(lua->T, 0); /* Empty the stack. */
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001521 ret = HLUA_E_ERR;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001522 break;
1523 }
1524
1525 switch (ret) {
1526 case HLUA_E_AGAIN:
1527 break;
1528
1529 case HLUA_E_ERRMSG:
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001530 notification_purge(&lua->com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001531 hlua_ctx_renew(lua, 1);
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001532 HLUA_CLR_RUN(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001533 break;
1534
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001535 case HLUA_E_ETMOUT:
1536 case HLUA_E_NOMEM:
1537 case HLUA_E_YIELD:
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001538 case HLUA_E_ERR:
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001539 HLUA_CLR_RUN(lua);
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001540 notification_purge(&lua->com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001541 hlua_ctx_renew(lua, 0);
1542 break;
1543
1544 case HLUA_E_OK:
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001545 HLUA_CLR_RUN(lua);
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001546 notification_purge(&lua->com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001547 break;
1548 }
1549
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +02001550 /* This is the main exit point, remove the Lua lock. */
Thierry Fournier021d9862020-11-28 23:42:03 +01001551 if (lua->state_id == 0)
Willy Tarreau1e7bef12021-08-20 15:47:25 +02001552 lua_drop_global_lock();
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +02001553
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001554 return ret;
1555}
1556
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001557/* This function exit the current code. */
1558__LJMP static int hlua_done(lua_State *L)
1559{
Thierry Fournier4234dbd2020-11-28 13:18:23 +01001560 struct hlua *hlua;
1561
1562 /* Get hlua struct, or NULL if we execute from main lua state */
1563 hlua = hlua_gethlua(L);
1564 if (!hlua)
1565 return 0;
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001566
1567 hlua->flags |= HLUA_EXIT;
1568 WILL_LJMP(lua_error(L));
1569
1570 return 0;
1571}
1572
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001573/* This function is an LUA binding. It provides a function
1574 * for deleting ACL from a referenced ACL file.
1575 */
1576__LJMP static int hlua_del_acl(lua_State *L)
1577{
1578 const char *name;
1579 const char *key;
1580 struct pat_ref *ref;
1581
1582 MAY_LJMP(check_args(L, 2, "del_acl"));
1583
1584 name = MAY_LJMP(luaL_checkstring(L, 1));
1585 key = MAY_LJMP(luaL_checkstring(L, 2));
1586
1587 ref = pat_ref_lookup(name);
1588 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001589 WILL_LJMP(luaL_error(L, "'del_acl': unknown acl file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001590
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001591 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001592 pat_ref_delete(ref, key);
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001593 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001594 return 0;
1595}
1596
1597/* This function is an LUA binding. It provides a function
1598 * for deleting map entry from a referenced map file.
1599 */
1600static int hlua_del_map(lua_State *L)
1601{
1602 const char *name;
1603 const char *key;
1604 struct pat_ref *ref;
1605
1606 MAY_LJMP(check_args(L, 2, "del_map"));
1607
1608 name = MAY_LJMP(luaL_checkstring(L, 1));
1609 key = MAY_LJMP(luaL_checkstring(L, 2));
1610
1611 ref = pat_ref_lookup(name);
1612 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001613 WILL_LJMP(luaL_error(L, "'del_map': unknown acl file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001614
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001615 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001616 pat_ref_delete(ref, key);
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001617 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001618 return 0;
1619}
1620
1621/* This function is an LUA binding. It provides a function
1622 * for adding ACL pattern from a referenced ACL file.
1623 */
1624static int hlua_add_acl(lua_State *L)
1625{
1626 const char *name;
1627 const char *key;
1628 struct pat_ref *ref;
1629
1630 MAY_LJMP(check_args(L, 2, "add_acl"));
1631
1632 name = MAY_LJMP(luaL_checkstring(L, 1));
1633 key = MAY_LJMP(luaL_checkstring(L, 2));
1634
1635 ref = pat_ref_lookup(name);
1636 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001637 WILL_LJMP(luaL_error(L, "'add_acl': unknown acl file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001638
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001639 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001640 if (pat_ref_find_elt(ref, key) == NULL)
1641 pat_ref_add(ref, key, NULL, NULL);
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001642 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001643 return 0;
1644}
1645
1646/* This function is an LUA binding. It provides a function
1647 * for setting map pattern and sample from a referenced map
1648 * file.
1649 */
1650static int hlua_set_map(lua_State *L)
1651{
1652 const char *name;
1653 const char *key;
1654 const char *value;
1655 struct pat_ref *ref;
1656
1657 MAY_LJMP(check_args(L, 3, "set_map"));
1658
1659 name = MAY_LJMP(luaL_checkstring(L, 1));
1660 key = MAY_LJMP(luaL_checkstring(L, 2));
1661 value = MAY_LJMP(luaL_checkstring(L, 3));
1662
1663 ref = pat_ref_lookup(name);
1664 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001665 WILL_LJMP(luaL_error(L, "'set_map': unknown map file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001666
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001667 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001668 if (pat_ref_find_elt(ref, key) != NULL)
1669 pat_ref_set(ref, key, value, NULL);
1670 else
1671 pat_ref_add(ref, key, value, NULL);
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001672 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001673 return 0;
1674}
1675
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01001676/* A class is a lot of memory that contain data. This data can be a table,
1677 * an integer or user data. This data is associated with a metatable. This
Ilya Shipitsinc02a23f2020-05-06 00:53:22 +05001678 * metatable have an original version registered in the global context with
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01001679 * the name of the object (_G[<name>] = <metable> ).
1680 *
1681 * A metable is a table that modify the standard behavior of a standard
1682 * access to the associated data. The entries of this new metatable are
1683 * defined as is:
1684 *
1685 * http://lua-users.org/wiki/MetatableEvents
1686 *
1687 * __index
1688 *
1689 * we access an absent field in a table, the result is nil. This is
1690 * true, but it is not the whole truth. Actually, such access triggers
1691 * the interpreter to look for an __index metamethod: If there is no
1692 * such method, as usually happens, then the access results in nil;
1693 * otherwise, the metamethod will provide the result.
1694 *
1695 * Control 'prototype' inheritance. When accessing "myTable[key]" and
1696 * the key does not appear in the table, but the metatable has an __index
1697 * property:
1698 *
1699 * - if the value is a function, the function is called, passing in the
1700 * table and the key; the return value of that function is returned as
1701 * the result.
1702 *
1703 * - if the value is another table, the value of the key in that table is
1704 * asked for and returned (and if it doesn't exist in that table, but that
1705 * table's metatable has an __index property, then it continues on up)
1706 *
1707 * - Use "rawget(myTable,key)" to skip this metamethod.
1708 *
1709 * http://www.lua.org/pil/13.4.1.html
1710 *
1711 * __newindex
1712 *
1713 * Like __index, but control property assignment.
1714 *
1715 * __mode - Control weak references. A string value with one or both
1716 * of the characters 'k' and 'v' which specifies that the the
1717 * keys and/or values in the table are weak references.
1718 *
1719 * __call - Treat a table like a function. When a table is followed by
1720 * parenthesis such as "myTable( 'foo' )" and the metatable has
1721 * a __call key pointing to a function, that function is invoked
1722 * (passing any specified arguments) and the return value is
1723 * returned.
1724 *
1725 * __metatable - Hide the metatable. When "getmetatable( myTable )" is
1726 * called, if the metatable for myTable has a __metatable
1727 * key, the value of that key is returned instead of the
1728 * actual metatable.
1729 *
1730 * __tostring - Control string representation. When the builtin
1731 * "tostring( myTable )" function is called, if the metatable
1732 * for myTable has a __tostring property set to a function,
1733 * that function is invoked (passing myTable to it) and the
1734 * return value is used as the string representation.
1735 *
1736 * __len - Control table length. When the table length is requested using
1737 * the length operator ( '#' ), if the metatable for myTable has
1738 * a __len key pointing to a function, that function is invoked
1739 * (passing myTable to it) and the return value used as the value
1740 * of "#myTable".
1741 *
1742 * __gc - Userdata finalizer code. When userdata is set to be garbage
1743 * collected, if the metatable has a __gc field pointing to a
1744 * function, that function is first invoked, passing the userdata
1745 * to it. The __gc metamethod is not called for tables.
1746 * (See http://lua-users.org/lists/lua-l/2006-11/msg00508.html)
1747 *
1748 * Special metamethods for redefining standard operators:
1749 * http://www.lua.org/pil/13.1.html
1750 *
1751 * __add "+"
1752 * __sub "-"
1753 * __mul "*"
1754 * __div "/"
1755 * __unm "!"
1756 * __pow "^"
1757 * __concat ".."
1758 *
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001759 * Special methods for redefining standard relations
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01001760 * http://www.lua.org/pil/13.2.html
1761 *
1762 * __eq "=="
1763 * __lt "<"
1764 * __le "<="
1765 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001766
1767/*
1768 *
1769 *
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001770 * Class Map
1771 *
1772 *
1773 */
1774
1775/* Returns a struct hlua_map if the stack entry "ud" is
1776 * a class session, otherwise it throws an error.
1777 */
1778__LJMP static struct map_descriptor *hlua_checkmap(lua_State *L, int ud)
1779{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02001780 return MAY_LJMP(hlua_checkudata(L, ud, class_map_ref));
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001781}
1782
1783/* This function is the map constructor. It don't need
1784 * the class Map object. It creates and return a new Map
1785 * object. It must be called only during "body" or "init"
1786 * context because it process some filesystem accesses.
1787 */
1788__LJMP static int hlua_map_new(struct lua_State *L)
1789{
1790 const char *fn;
1791 int match = PAT_MATCH_STR;
1792 struct sample_conv conv;
1793 const char *file = "";
1794 int line = 0;
1795 lua_Debug ar;
1796 char *err = NULL;
1797 struct arg args[2];
1798
1799 if (lua_gettop(L) < 1 || lua_gettop(L) > 2)
1800 WILL_LJMP(luaL_error(L, "'new' needs at least 1 argument."));
1801
1802 fn = MAY_LJMP(luaL_checkstring(L, 1));
1803
1804 if (lua_gettop(L) >= 2) {
1805 match = MAY_LJMP(luaL_checkinteger(L, 2));
1806 if (match < 0 || match >= PAT_MATCH_NUM)
1807 WILL_LJMP(luaL_error(L, "'new' needs a valid match method."));
1808 }
1809
1810 /* Get Lua filename and line number. */
1811 if (lua_getstack(L, 1, &ar)) { /* check function at level */
1812 lua_getinfo(L, "Sl", &ar); /* get info about it */
1813 if (ar.currentline > 0) { /* is there info? */
1814 file = ar.short_src;
1815 line = ar.currentline;
1816 }
1817 }
1818
1819 /* fill fake sample_conv struct. */
1820 conv.kw = ""; /* unused. */
1821 conv.process = NULL; /* unused. */
1822 conv.arg_mask = 0; /* unused. */
1823 conv.val_args = NULL; /* unused. */
1824 conv.out_type = SMP_T_STR;
1825 conv.private = (void *)(long)match;
1826 switch (match) {
1827 case PAT_MATCH_STR: conv.in_type = SMP_T_STR; break;
1828 case PAT_MATCH_BEG: conv.in_type = SMP_T_STR; break;
1829 case PAT_MATCH_SUB: conv.in_type = SMP_T_STR; break;
1830 case PAT_MATCH_DIR: conv.in_type = SMP_T_STR; break;
1831 case PAT_MATCH_DOM: conv.in_type = SMP_T_STR; break;
1832 case PAT_MATCH_END: conv.in_type = SMP_T_STR; break;
1833 case PAT_MATCH_REG: conv.in_type = SMP_T_STR; break;
Thierry FOURNIER07ee64e2015-07-06 23:43:03 +02001834 case PAT_MATCH_INT: conv.in_type = SMP_T_SINT; break;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001835 case PAT_MATCH_IP: conv.in_type = SMP_T_ADDR; break;
1836 default:
1837 WILL_LJMP(luaL_error(L, "'new' doesn't support this match mode."));
1838 }
1839
1840 /* fill fake args. */
1841 args[0].type = ARGT_STR;
Christopher Faulet73292e92020-08-06 08:40:09 +02001842 args[0].data.str.area = strdup(fn);
1843 args[0].data.str.data = strlen(fn);
1844 args[0].data.str.size = args[0].data.str.data+1;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001845 args[1].type = ARGT_STOP;
1846
1847 /* load the map. */
1848 if (!sample_load_map(args, &conv, file, line, &err)) {
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +05001849 /* error case: we can't use luaL_error because we must
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001850 * free the err variable.
1851 */
1852 luaL_where(L, 1);
1853 lua_pushfstring(L, "'new': %s.", err);
1854 lua_concat(L, 2);
1855 free(err);
Christopher Faulet6ad7df42020-08-07 11:45:18 +02001856 chunk_destroy(&args[0].data.str);
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001857 WILL_LJMP(lua_error(L));
1858 }
1859
1860 /* create the lua object. */
1861 lua_newtable(L);
1862 lua_pushlightuserdata(L, args[0].data.map);
1863 lua_rawseti(L, -2, 0);
1864
1865 /* Pop a class Map metatable and affect it to the userdata. */
1866 lua_rawgeti(L, LUA_REGISTRYINDEX, class_map_ref);
1867 lua_setmetatable(L, -2);
1868
1869
1870 return 1;
1871}
1872
1873__LJMP static inline int _hlua_map_lookup(struct lua_State *L, int str)
1874{
1875 struct map_descriptor *desc;
1876 struct pattern *pat;
1877 struct sample smp;
1878
1879 MAY_LJMP(check_args(L, 2, "lookup"));
1880 desc = MAY_LJMP(hlua_checkmap(L, 1));
Thierry FOURNIER07ee64e2015-07-06 23:43:03 +02001881 if (desc->pat.expect_type == SMP_T_SINT) {
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02001882 smp.data.type = SMP_T_SINT;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +02001883 smp.data.u.sint = MAY_LJMP(luaL_checkinteger(L, 2));
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001884 }
1885 else {
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02001886 smp.data.type = SMP_T_STR;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001887 smp.flags = SMP_F_CONST;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001888 smp.data.u.str.area = (char *)MAY_LJMP(luaL_checklstring(L, 2, (size_t *)&smp.data.u.str.data));
Thierry Fournier91dc0c02020-11-10 20:38:20 +01001889 smp.data.u.str.size = smp.data.u.str.data + 1;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001890 }
1891
1892 pat = pattern_exec_match(&desc->pat, &smp, 1);
Thierry FOURNIER503bb092015-08-19 08:35:43 +02001893 if (!pat || !pat->data) {
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001894 if (str)
1895 lua_pushstring(L, "");
1896 else
1897 lua_pushnil(L);
1898 return 1;
1899 }
1900
1901 /* The Lua pattern must return a string, so we can't check the returned type */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001902 lua_pushlstring(L, pat->data->u.str.area, pat->data->u.str.data);
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001903 return 1;
1904}
1905
1906__LJMP static int hlua_map_lookup(struct lua_State *L)
1907{
1908 return _hlua_map_lookup(L, 0);
1909}
1910
1911__LJMP static int hlua_map_slookup(struct lua_State *L)
1912{
1913 return _hlua_map_lookup(L, 1);
1914}
1915
1916/*
1917 *
1918 *
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001919 * Class Socket
1920 *
1921 *
1922 */
1923
1924__LJMP static struct hlua_socket *hlua_checksocket(lua_State *L, int ud)
1925{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02001926 return MAY_LJMP(hlua_checkudata(L, ud, class_socket_ref));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001927}
1928
1929/* This function is the handler called for each I/O on the established
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001930 * connection. It is used for notify space available to send or data
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001931 * received.
1932 */
Willy Tarreau00a37f02015-04-13 12:05:19 +02001933static void hlua_socket_handler(struct appctx *appctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001934{
Willy Tarreau5321da92022-05-06 11:57:34 +02001935 struct hlua_csk_ctx *ctx = appctx->svcctx;
Willy Tarreau4596fe22022-05-17 19:07:51 +02001936 struct stconn *cs = appctx_cs(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001937
Willy Tarreau5321da92022-05-06 11:57:34 +02001938 if (ctx->die) {
Christopher Fauletda098e62022-03-31 17:44:45 +02001939 cs_shutw(cs);
1940 cs_shutr(cs);
Willy Tarreau40a9c322022-05-18 15:55:18 +02001941 sc_ic(cs)->flags |= CF_READ_NULL;
Willy Tarreau5321da92022-05-06 11:57:34 +02001942 notification_wake(&ctx->wake_on_read);
1943 notification_wake(&ctx->wake_on_write);
Willy Tarreauea27f482022-05-18 16:10:52 +02001944 stream_shutdown(__sc_strm(cs), SF_ERR_KILLED);
Thierry FOURNIERb13b20a2017-07-16 20:48:54 +02001945 }
1946
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +05001947 /* If we can't write, wakeup the pending write signals. */
Willy Tarreau40a9c322022-05-18 15:55:18 +02001948 if (channel_output_closed(sc_ic(cs)))
Willy Tarreau5321da92022-05-06 11:57:34 +02001949 notification_wake(&ctx->wake_on_write);
Thierry FOURNIER6d695e62015-09-27 19:29:38 +02001950
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +05001951 /* If we can't read, wakeup the pending read signals. */
Willy Tarreau40a9c322022-05-18 15:55:18 +02001952 if (channel_input_closed(sc_oc(cs)))
Willy Tarreau5321da92022-05-06 11:57:34 +02001953 notification_wake(&ctx->wake_on_read);
Thierry FOURNIER6d695e62015-09-27 19:29:38 +02001954
Willy Tarreau5a0b25d2019-07-18 18:01:14 +02001955 /* if the connection is not established, inform the stream that we want
Thierry FOURNIER316e3192015-09-04 18:25:53 +02001956 * to be notified whenever the connection completes.
1957 */
Willy Tarreau026e8fb2022-05-17 19:47:17 +02001958 if (cs_opposite(cs)->state < SC_ST_EST) {
Willy Tarreau90e8b452022-05-25 18:21:43 +02001959 applet_need_more_data(appctx);
Willy Tarreaub23edc82022-05-24 16:49:03 +02001960 se_need_remote_conn(appctx->sedesc);
Willy Tarreau4164eb92022-05-25 15:42:03 +02001961 applet_have_more_data(appctx);
Willy Tarreaud4da1962015-04-20 01:31:23 +02001962 return;
Thierry FOURNIER316e3192015-09-04 18:25:53 +02001963 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001964
1965 /* This function is called after the connect. */
Willy Tarreau5321da92022-05-06 11:57:34 +02001966 ctx->connected = 1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001967
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001968 /* Wake the tasks which wants to write if the buffer have available space. */
Willy Tarreau40a9c322022-05-18 15:55:18 +02001969 if (channel_may_recv(sc_ic(cs)))
Willy Tarreau5321da92022-05-06 11:57:34 +02001970 notification_wake(&ctx->wake_on_write);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001971
1972 /* Wake the tasks which wants to read if the buffer contains data. */
Willy Tarreau40a9c322022-05-18 15:55:18 +02001973 if (!channel_is_empty(sc_oc(cs)))
Willy Tarreau5321da92022-05-06 11:57:34 +02001974 notification_wake(&ctx->wake_on_read);
Thierry FOURNIER101b9762018-05-27 01:27:40 +02001975
1976 /* Some data were injected in the buffer, notify the stream
1977 * interface.
1978 */
Willy Tarreau40a9c322022-05-18 15:55:18 +02001979 if (!channel_is_empty(sc_ic(cs)))
Christopher Faulet13045f02022-04-01 14:23:38 +02001980 cs_update(cs);
Thierry FOURNIER101b9762018-05-27 01:27:40 +02001981
1982 /* If write notifications are registered, we considers we want
Willy Tarreau3367d412018-11-15 10:57:41 +01001983 * to write, so we clear the blocking flag.
Thierry FOURNIER101b9762018-05-27 01:27:40 +02001984 */
Willy Tarreau5321da92022-05-06 11:57:34 +02001985 if (notification_registered(&ctx->wake_on_write))
Willy Tarreau4164eb92022-05-25 15:42:03 +02001986 applet_have_more_data(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001987}
1988
Christopher Faulet5f35a3e2022-05-12 15:31:05 +02001989static int hlua_socket_init(struct appctx *appctx)
1990{
1991 struct hlua_csk_ctx *ctx = appctx->svcctx;
1992 struct stream *s;
1993
1994 if (appctx_finalize_startup(appctx, socket_proxy, &BUF_NULL) == -1)
1995 goto error;
1996
1997 s = appctx_strm(appctx);
1998
Willy Tarreau4596fe22022-05-17 19:07:51 +02001999 /* Configure "right" stream connector. This stconn is used to connect
Christopher Faulet5f35a3e2022-05-12 15:31:05 +02002000 * and retrieve data from the server. The connection is initialized
2001 * with the "struct server".
2002 */
Willy Tarreau026e8fb2022-05-17 19:47:17 +02002003 cs_set_state(s->scb, SC_ST_ASS);
Christopher Faulet5f35a3e2022-05-12 15:31:05 +02002004
2005 /* Force destination server. */
2006 s->flags |= SF_DIRECT | SF_ASSIGNED | SF_BE_ASSIGNED;
2007 s->target = &socket_tcp->obj_type;
2008
2009 ctx->appctx = appctx;
2010 return 0;
2011
2012 error:
2013 return -1;
2014}
2015
Willy Tarreau87b09662015-04-03 00:22:06 +02002016/* This function is called when the "struct stream" is destroyed.
2017 * Remove the link from the object to this stream.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002018 * Wake all the pending signals.
2019 */
Willy Tarreau00a37f02015-04-13 12:05:19 +02002020static void hlua_socket_release(struct appctx *appctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002021{
Willy Tarreau5321da92022-05-06 11:57:34 +02002022 struct hlua_csk_ctx *ctx = appctx->svcctx;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002023 struct xref *peer;
2024
Christopher Faulet5f35a3e2022-05-12 15:31:05 +02002025 /* Remove my link in the original objects. */
Willy Tarreau5321da92022-05-06 11:57:34 +02002026 peer = xref_get_peer_and_lock(&ctx->xref);
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002027 if (peer)
Willy Tarreau5321da92022-05-06 11:57:34 +02002028 xref_disconnect(&ctx->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002029
2030 /* Wake all the task waiting for me. */
Willy Tarreau5321da92022-05-06 11:57:34 +02002031 notification_wake(&ctx->wake_on_read);
2032 notification_wake(&ctx->wake_on_write);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002033}
2034
2035/* If the garbage collectio of the object is launch, nobody
Willy Tarreau87b09662015-04-03 00:22:06 +02002036 * uses this object. If the stream does not exists, just quit.
2037 * Send the shutdown signal to the stream. In some cases,
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002038 * pending signal can rest in the read and write lists. destroy
2039 * it.
2040 */
2041__LJMP static int hlua_socket_gc(lua_State *L)
2042{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002043 struct hlua_socket *socket;
Willy Tarreau5321da92022-05-06 11:57:34 +02002044 struct hlua_csk_ctx *ctx;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002045 struct xref *peer;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002046
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002047 MAY_LJMP(check_args(L, 1, "__gc"));
2048
2049 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002050 peer = xref_get_peer_and_lock(&socket->xref);
2051 if (!peer)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002052 return 0;
Willy Tarreau5321da92022-05-06 11:57:34 +02002053
2054 ctx = container_of(peer, struct hlua_csk_ctx, xref);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002055
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002056 /* Set the flag which destroy the session. */
Willy Tarreau5321da92022-05-06 11:57:34 +02002057 ctx->die = 1;
2058 appctx_wakeup(ctx->appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002059
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002060 /* Remove all reference between the Lua stack and the coroutine stream. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002061 xref_disconnect(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002062 return 0;
2063}
2064
2065/* The close function send shutdown signal and break the
Willy Tarreau87b09662015-04-03 00:22:06 +02002066 * links between the stream and the object.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002067 */
sada05ed3302018-05-11 11:48:18 -07002068__LJMP static int hlua_socket_close_helper(lua_State *L)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002069{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002070 struct hlua_socket *socket;
Willy Tarreau5321da92022-05-06 11:57:34 +02002071 struct hlua_csk_ctx *ctx;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002072 struct xref *peer;
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002073 struct hlua *hlua;
2074
2075 /* Get hlua struct, or NULL if we execute from main lua state */
2076 hlua = hlua_gethlua(L);
2077 if (!hlua)
2078 return 0;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002079
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002080 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002081
2082 /* Check if we run on the same thread than the xreator thread.
2083 * We cannot access to the socket if the thread is different.
2084 */
2085 if (socket->tid != tid)
2086 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2087
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002088 peer = xref_get_peer_and_lock(&socket->xref);
2089 if (!peer)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002090 return 0;
Willy Tarreauf31af932020-01-14 09:59:38 +01002091
2092 hlua->gc_count--;
Willy Tarreau5321da92022-05-06 11:57:34 +02002093 ctx = container_of(peer, struct hlua_csk_ctx, xref);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002094
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002095 /* Set the flag which destroy the session. */
Willy Tarreau5321da92022-05-06 11:57:34 +02002096 ctx->die = 1;
2097 appctx_wakeup(ctx->appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002098
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002099 /* Remove all reference between the Lua stack and the coroutine stream. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002100 xref_disconnect(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002101 return 0;
2102}
2103
sada05ed3302018-05-11 11:48:18 -07002104/* The close function calls close_helper.
2105 */
2106__LJMP static int hlua_socket_close(lua_State *L)
2107{
2108 MAY_LJMP(check_args(L, 1, "close"));
2109 return hlua_socket_close_helper(L);
2110}
2111
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002112/* This Lua function assumes that the stack contain three parameters.
2113 * 1 - USERDATA containing a struct socket
2114 * 2 - INTEGER with values of the macro defined below
2115 * If the integer is -1, we must read at most one line.
2116 * If the integer is -2, we ust read all the data until the
2117 * end of the stream.
2118 * If the integer is positive value, we must read a number of
2119 * bytes corresponding to this value.
2120 */
2121#define HLSR_READ_LINE (-1)
2122#define HLSR_READ_ALL (-2)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002123__LJMP static int hlua_socket_receive_yield(struct lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002124{
2125 struct hlua_socket *socket = MAY_LJMP(hlua_checksocket(L, 1));
2126 int wanted = lua_tointeger(L, 2);
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002127 struct hlua *hlua;
Willy Tarreau5321da92022-05-06 11:57:34 +02002128 struct hlua_csk_ctx *csk_ctx;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002129 struct appctx *appctx;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02002130 size_t len;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002131 int nblk;
Willy Tarreau206ba832018-06-14 15:27:31 +02002132 const char *blk1;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02002133 size_t len1;
Willy Tarreau206ba832018-06-14 15:27:31 +02002134 const char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02002135 size_t len2;
Thierry FOURNIER00543922015-03-09 18:35:06 +01002136 int skip_at_end = 0;
Willy Tarreau81389672015-03-10 12:03:52 +01002137 struct channel *oc;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002138 struct stream *s;
2139 struct xref *peer;
Thierry FOURNIER8c126c72018-05-25 16:27:44 +02002140 int missing_bytes;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002141
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002142 /* Get hlua struct, or NULL if we execute from main lua state */
2143 hlua = hlua_gethlua(L);
2144
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002145 /* Check if this lua stack is schedulable. */
2146 if (!hlua || !hlua->task)
2147 WILL_LJMP(luaL_error(L, "The 'receive' function is only allowed in "
2148 "'frontend', 'backend' or 'task'"));
2149
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002150 /* Check if we run on the same thread than the xreator thread.
2151 * We cannot access to the socket if the thread is different.
2152 */
2153 if (socket->tid != tid)
2154 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2155
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002156 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002157 peer = xref_get_peer_and_lock(&socket->xref);
2158 if (!peer)
2159 goto no_peer;
Willy Tarreau5321da92022-05-06 11:57:34 +02002160
2161 csk_ctx = container_of(peer, struct hlua_csk_ctx, xref);
2162 appctx = csk_ctx->appctx;
Willy Tarreau0698c802022-05-11 14:09:57 +02002163 s = appctx_strm(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002164
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002165 oc = &s->res;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002166 if (wanted == HLSR_READ_LINE) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002167 /* Read line. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02002168 nblk = co_getline_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002169 if (nblk < 0) /* Connection close. */
2170 goto connection_closed;
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002171 if (nblk == 0) /* No data available. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002172 goto connection_empty;
Thierry FOURNIER00543922015-03-09 18:35:06 +01002173
2174 /* remove final \r\n. */
2175 if (nblk == 1) {
2176 if (blk1[len1-1] == '\n') {
2177 len1--;
2178 skip_at_end++;
2179 if (blk1[len1-1] == '\r') {
2180 len1--;
2181 skip_at_end++;
2182 }
2183 }
2184 }
2185 else {
2186 if (blk2[len2-1] == '\n') {
2187 len2--;
2188 skip_at_end++;
2189 if (blk2[len2-1] == '\r') {
2190 len2--;
2191 skip_at_end++;
2192 }
2193 }
2194 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002195 }
2196
2197 else if (wanted == HLSR_READ_ALL) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002198 /* Read all the available data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02002199 nblk = co_getblk_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002200 if (nblk < 0) /* Connection close. */
2201 goto connection_closed;
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002202 if (nblk == 0) /* No data available. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002203 goto connection_empty;
2204 }
2205
2206 else {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002207 /* Read a block of data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02002208 nblk = co_getblk_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002209 if (nblk < 0) /* Connection close. */
2210 goto connection_closed;
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002211 if (nblk == 0) /* No data available. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002212 goto connection_empty;
2213
Thierry FOURNIER8c126c72018-05-25 16:27:44 +02002214 missing_bytes = wanted - socket->b.n;
2215 if (len1 > missing_bytes) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002216 nblk = 1;
Thierry FOURNIER8c126c72018-05-25 16:27:44 +02002217 len1 = missing_bytes;
2218 } if (nblk == 2 && len1 + len2 > missing_bytes)
2219 len2 = missing_bytes - len1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002220 }
2221
2222 len = len1;
2223
2224 luaL_addlstring(&socket->b, blk1, len1);
2225 if (nblk == 2) {
2226 len += len2;
2227 luaL_addlstring(&socket->b, blk2, len2);
2228 }
2229
2230 /* Consume data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02002231 co_skip(oc, len + skip_at_end);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002232
2233 /* Don't wait anything. */
Thierry FOURNIER7e4ee472018-05-25 15:03:50 +02002234 appctx_wakeup(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002235
2236 /* If the pattern reclaim to read all the data
2237 * in the connection, got out.
2238 */
2239 if (wanted == HLSR_READ_ALL)
2240 goto connection_empty;
Thierry FOURNIER8c126c72018-05-25 16:27:44 +02002241 else if (wanted >= 0 && socket->b.n < wanted)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002242 goto connection_empty;
2243
2244 /* Return result. */
2245 luaL_pushresult(&socket->b);
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002246 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002247 return 1;
2248
2249connection_closed:
2250
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002251 xref_unlock(&socket->xref, peer);
2252
2253no_peer:
2254
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002255 /* If the buffer containds data. */
2256 if (socket->b.n > 0) {
2257 luaL_pushresult(&socket->b);
2258 return 1;
2259 }
2260 lua_pushnil(L);
2261 lua_pushstring(L, "connection closed.");
2262 return 2;
2263
2264connection_empty:
2265
Willy Tarreau5321da92022-05-06 11:57:34 +02002266 if (!notification_new(&hlua->com, &csk_ctx->wake_on_read, hlua->task)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002267 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002268 WILL_LJMP(luaL_error(L, "out of memory"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002269 }
2270 xref_unlock(&socket->xref, peer);
Willy Tarreau9635e032018-10-16 17:52:55 +02002271 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_receive_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002272 return 0;
2273}
2274
Tim Duesterhusb33754c2018-01-04 19:32:14 +01002275/* This Lua function gets two parameters. The first one can be string
2276 * or a number. If the string is "*l", the user requires one line. If
2277 * the string is "*a", the user requires all the contents of the stream.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002278 * If the value is a number, the user require a number of bytes equal
2279 * to the value. The default value is "*l" (a line).
2280 *
Tim Duesterhusb33754c2018-01-04 19:32:14 +01002281 * This parameter with a variable type is converted in integer. This
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002282 * integer takes this values:
2283 * -1 : read a line
2284 * -2 : read all the stream
Tim Duesterhusb33754c2018-01-04 19:32:14 +01002285 * >0 : amount of bytes.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002286 *
Tim Duesterhusb33754c2018-01-04 19:32:14 +01002287 * The second parameter is optional. It contains a string that must be
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002288 * concatenated with the read data.
2289 */
2290__LJMP static int hlua_socket_receive(struct lua_State *L)
2291{
2292 int wanted = HLSR_READ_LINE;
2293 const char *pattern;
Christopher Fauletc31b2002021-05-03 10:11:13 +02002294 int lastarg, type;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002295 char *error;
2296 size_t len;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002297 struct hlua_socket *socket;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002298
2299 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
2300 WILL_LJMP(luaL_error(L, "The 'receive' function requires between 1 and 3 arguments."));
2301
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002302 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002303
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002304 /* Check if we run on the same thread than the xreator thread.
2305 * We cannot access to the socket if the thread is different.
2306 */
2307 if (socket->tid != tid)
2308 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2309
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002310 /* check for pattern. */
2311 if (lua_gettop(L) >= 2) {
2312 type = lua_type(L, 2);
2313 if (type == LUA_TSTRING) {
2314 pattern = lua_tostring(L, 2);
2315 if (strcmp(pattern, "*a") == 0)
2316 wanted = HLSR_READ_ALL;
2317 else if (strcmp(pattern, "*l") == 0)
2318 wanted = HLSR_READ_LINE;
2319 else {
2320 wanted = strtoll(pattern, &error, 10);
2321 if (*error != '\0')
2322 WILL_LJMP(luaL_error(L, "Unsupported pattern."));
2323 }
2324 }
2325 else if (type == LUA_TNUMBER) {
2326 wanted = lua_tointeger(L, 2);
2327 if (wanted < 0)
2328 WILL_LJMP(luaL_error(L, "Unsupported size."));
2329 }
2330 }
2331
2332 /* Set pattern. */
2333 lua_pushinteger(L, wanted);
Tim Duesterhusc6e377e2018-01-04 19:32:13 +01002334
2335 /* Check if we would replace the top by itself. */
2336 if (lua_gettop(L) != 2)
2337 lua_replace(L, 2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002338
Christopher Fauletc31b2002021-05-03 10:11:13 +02002339 /* Save index of the top of the stack because since buffers are used, it
2340 * may change
2341 */
2342 lastarg = lua_gettop(L);
2343
Tim Duesterhusb33754c2018-01-04 19:32:14 +01002344 /* init buffer, and fill it with prefix. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002345 luaL_buffinit(L, &socket->b);
2346
2347 /* Check prefix. */
Christopher Fauletc31b2002021-05-03 10:11:13 +02002348 if (lastarg >= 3) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002349 if (lua_type(L, 3) != LUA_TSTRING)
2350 WILL_LJMP(luaL_error(L, "Expect a 'string' for the prefix"));
2351 pattern = lua_tolstring(L, 3, &len);
2352 luaL_addlstring(&socket->b, pattern, len);
2353 }
2354
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002355 return __LJMP(hlua_socket_receive_yield(L, 0, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002356}
2357
2358/* Write the Lua input string in the output buffer.
Mark Lakes22154b42018-01-29 14:38:40 -08002359 * This function returns a yield if no space is available.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002360 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002361static int hlua_socket_write_yield(struct lua_State *L,int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002362{
2363 struct hlua_socket *socket;
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002364 struct hlua *hlua;
Willy Tarreau5321da92022-05-06 11:57:34 +02002365 struct hlua_csk_ctx *csk_ctx;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002366 struct appctx *appctx;
2367 size_t buf_len;
2368 const char *buf;
2369 int len;
2370 int send_len;
2371 int sent;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002372 struct xref *peer;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002373 struct stream *s;
Willy Tarreau4596fe22022-05-17 19:07:51 +02002374 struct stconn *cs;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002375
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002376 /* Get hlua struct, or NULL if we execute from main lua state */
2377 hlua = hlua_gethlua(L);
2378
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002379 /* Check if this lua stack is schedulable. */
2380 if (!hlua || !hlua->task)
2381 WILL_LJMP(luaL_error(L, "The 'write' function is only allowed in "
2382 "'frontend', 'backend' or 'task'"));
2383
2384 /* Get object */
2385 socket = MAY_LJMP(hlua_checksocket(L, 1));
2386 buf = MAY_LJMP(luaL_checklstring(L, 2, &buf_len));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002387 sent = MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002388
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002389 /* Check if we run on the same thread than the xreator thread.
2390 * We cannot access to the socket if the thread is different.
2391 */
2392 if (socket->tid != tid)
2393 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2394
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002395 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002396 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002397 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002398 lua_pushinteger(L, -1);
2399 return 1;
2400 }
Willy Tarreau5321da92022-05-06 11:57:34 +02002401
2402 csk_ctx = container_of(peer, struct hlua_csk_ctx, xref);
2403 appctx = csk_ctx->appctx;
Willy Tarreau0698c802022-05-11 14:09:57 +02002404 cs = appctx_cs(appctx);
Willy Tarreauea27f482022-05-18 16:10:52 +02002405 s = __sc_strm(cs);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002406
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002407 /* Check for connection close. */
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002408 if (channel_output_closed(&s->req)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002409 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002410 lua_pushinteger(L, -1);
2411 return 1;
2412 }
2413
2414 /* Update the input buffer data. */
2415 buf += sent;
2416 send_len = buf_len - sent;
2417
2418 /* All the data are sent. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002419 if (sent >= buf_len) {
2420 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002421 return 1; /* Implicitly return the length sent. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002422 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002423
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002424 /* Check if the buffer is available because HAProxy doesn't allocate
Thierry FOURNIER486d52a2015-03-09 17:51:43 +01002425 * the request buffer if its not required.
2426 */
Willy Tarreauc9fa0482018-07-10 17:43:27 +02002427 if (s->req.buf.size == 0) {
Christopher Faulet8f45eec2022-04-01 17:19:36 +02002428 if (!cs_alloc_ibuf(cs, &appctx->buffer_wait))
Christopher Faulet33834b12016-12-19 09:29:06 +01002429 goto hlua_socket_write_yield_return;
Thierry FOURNIER486d52a2015-03-09 17:51:43 +01002430 }
2431
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002432 /* Check for available space. */
Willy Tarreauc9fa0482018-07-10 17:43:27 +02002433 len = b_room(&s->req.buf);
Christopher Faulet33834b12016-12-19 09:29:06 +01002434 if (len <= 0) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002435 goto hlua_socket_write_yield_return;
Christopher Faulet33834b12016-12-19 09:29:06 +01002436 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002437
2438 /* send data */
2439 if (len < send_len)
2440 send_len = len;
Thierry FOURNIER66b89192018-05-27 01:14:47 +02002441 len = ci_putblk(&s->req, buf, send_len);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002442
2443 /* "Not enough space" (-1), "Buffer too little to contain
2444 * the data" (-2) are not expected because the available length
2445 * is tested.
2446 * Other unknown error are also not expected.
2447 */
2448 if (len <= 0) {
Willy Tarreaubc18da12015-03-13 14:00:47 +01002449 if (len == -1)
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002450 s->req.flags |= CF_WAKE_WRITE;
Willy Tarreaubc18da12015-03-13 14:00:47 +01002451
sada05ed3302018-05-11 11:48:18 -07002452 MAY_LJMP(hlua_socket_close_helper(L));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002453 lua_pop(L, 1);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002454 lua_pushinteger(L, -1);
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002455 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002456 return 1;
2457 }
2458
2459 /* update buffers. */
Thierry FOURNIER101b9762018-05-27 01:27:40 +02002460 appctx_wakeup(appctx);
Willy Tarreaude70fa12015-09-26 11:25:05 +02002461
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002462 s->req.rex = TICK_ETERNITY;
2463 s->res.wex = TICK_ETERNITY;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002464
2465 /* Update length sent. */
2466 lua_pop(L, 1);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002467 lua_pushinteger(L, sent + len);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002468
2469 /* All the data buffer is sent ? */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002470 if (sent + len >= buf_len) {
2471 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002472 return 1;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002473 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002474
2475hlua_socket_write_yield_return:
Willy Tarreau5321da92022-05-06 11:57:34 +02002476 if (!notification_new(&hlua->com, &csk_ctx->wake_on_write, hlua->task)) {
Thierry FOURNIERba42fcd2018-05-27 00:59:48 +02002477 xref_unlock(&socket->xref, peer);
2478 WILL_LJMP(luaL_error(L, "out of memory"));
2479 }
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002480 xref_unlock(&socket->xref, peer);
Willy Tarreau9635e032018-10-16 17:52:55 +02002481 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_write_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002482 return 0;
2483}
2484
2485/* This function initiate the send of data. It just check the input
2486 * parameters and push an integer in the Lua stack that contain the
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002487 * amount of data written to the buffer. This is used by the function
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002488 * "hlua_socket_write_yield" that can yield.
2489 *
2490 * The Lua function gets between 3 and 4 parameters. The first one is
2491 * the associated object. The second is a string buffer. The third is
2492 * a facultative integer that represents where is the buffer position
2493 * of the start of the data that can send. The first byte is the
2494 * position "1". The default value is "1". The fourth argument is a
2495 * facultative integer that represents where is the buffer position
2496 * of the end of the data that can send. The default is the last byte.
2497 */
2498static int hlua_socket_send(struct lua_State *L)
2499{
2500 int i;
2501 int j;
2502 const char *buf;
2503 size_t buf_len;
2504
2505 /* Check number of arguments. */
2506 if (lua_gettop(L) < 2 || lua_gettop(L) > 4)
2507 WILL_LJMP(luaL_error(L, "'send' needs between 2 and 4 arguments"));
2508
2509 /* Get the string. */
2510 buf = MAY_LJMP(luaL_checklstring(L, 2, &buf_len));
2511
2512 /* Get and check j. */
2513 if (lua_gettop(L) == 4) {
2514 j = MAY_LJMP(luaL_checkinteger(L, 4));
2515 if (j < 0)
2516 j = buf_len + j + 1;
2517 if (j > buf_len)
2518 j = buf_len + 1;
2519 lua_pop(L, 1);
2520 }
2521 else
2522 j = buf_len;
2523
2524 /* Get and check i. */
2525 if (lua_gettop(L) == 3) {
2526 i = MAY_LJMP(luaL_checkinteger(L, 3));
2527 if (i < 0)
2528 i = buf_len + i + 1;
2529 if (i > buf_len)
2530 i = buf_len + 1;
2531 lua_pop(L, 1);
2532 } else
2533 i = 1;
2534
2535 /* Check bth i and j. */
2536 if (i > j) {
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002537 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002538 return 1;
2539 }
2540 if (i == 0 && j == 0) {
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002541 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002542 return 1;
2543 }
2544 if (i == 0)
2545 i = 1;
2546 if (j == 0)
2547 j = 1;
2548
2549 /* Pop the string. */
2550 lua_pop(L, 1);
2551
2552 /* Update the buffer length. */
2553 buf += i - 1;
2554 buf_len = j - i + 1;
2555 lua_pushlstring(L, buf, buf_len);
2556
2557 /* This unsigned is used to remember the amount of sent data. */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002558 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002559
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002560 return MAY_LJMP(hlua_socket_write_yield(L, 0, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002561}
2562
Willy Tarreau22b0a682015-06-17 19:43:49 +02002563#define SOCKET_INFO_MAX_LEN sizeof("[0000:0000:0000:0000:0000:0000:0000:0000]:12345")
Christopher Faulete6465b32021-10-22 15:36:08 +02002564__LJMP static inline int hlua_socket_info(struct lua_State *L, const struct sockaddr_storage *addr)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002565{
2566 static char buffer[SOCKET_INFO_MAX_LEN];
2567 int ret;
2568 int len;
2569 char *p;
2570
2571 ret = addr_to_str(addr, buffer+1, SOCKET_INFO_MAX_LEN-1);
2572 if (ret <= 0) {
2573 lua_pushnil(L);
2574 return 1;
2575 }
2576
2577 if (ret == AF_UNIX) {
2578 lua_pushstring(L, buffer+1);
2579 return 1;
2580 }
2581 else if (ret == AF_INET6) {
2582 buffer[0] = '[';
2583 len = strlen(buffer);
2584 buffer[len] = ']';
2585 len++;
2586 buffer[len] = ':';
2587 len++;
2588 p = buffer;
2589 }
2590 else if (ret == AF_INET) {
2591 p = buffer + 1;
2592 len = strlen(p);
2593 p[len] = ':';
2594 len++;
2595 }
2596 else {
2597 lua_pushnil(L);
2598 return 1;
2599 }
2600
2601 if (port_to_str(addr, p + len, SOCKET_INFO_MAX_LEN-1 - len) <= 0) {
2602 lua_pushnil(L);
2603 return 1;
2604 }
2605
2606 lua_pushstring(L, p);
2607 return 1;
2608}
2609
2610/* Returns information about the peer of the connection. */
2611__LJMP static int hlua_socket_getpeername(struct lua_State *L)
2612{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002613 struct hlua_socket *socket;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002614 struct xref *peer;
2615 struct appctx *appctx;
Willy Tarreau4596fe22022-05-17 19:07:51 +02002616 struct stconn *cs;
Christopher Faulet16f16af2021-10-27 09:34:56 +02002617 const struct sockaddr_storage *dst;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002618 int ret;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002619
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002620 MAY_LJMP(check_args(L, 1, "getpeername"));
2621
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002622 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002623
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002624 /* Check if we run on the same thread than the xreator thread.
2625 * We cannot access to the socket if the thread is different.
2626 */
2627 if (socket->tid != tid)
2628 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2629
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002630 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002631 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002632 if (!peer) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002633 lua_pushnil(L);
2634 return 1;
2635 }
Willy Tarreau5321da92022-05-06 11:57:34 +02002636
2637 appctx = container_of(peer, struct hlua_csk_ctx, xref)->appctx;
Willy Tarreau0698c802022-05-11 14:09:57 +02002638 cs = appctx_cs(appctx);
Christopher Faulet8da67aa2022-03-29 17:53:09 +02002639 dst = cs_dst(cs_opposite(cs));
Christopher Faulet16f16af2021-10-27 09:34:56 +02002640 if (!dst) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002641 xref_unlock(&socket->xref, peer);
Willy Tarreaua71f6422016-11-16 17:00:14 +01002642 lua_pushnil(L);
2643 return 1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002644 }
2645
Christopher Faulet16f16af2021-10-27 09:34:56 +02002646 ret = MAY_LJMP(hlua_socket_info(L, dst));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002647 xref_unlock(&socket->xref, peer);
2648 return ret;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002649}
2650
2651/* Returns information about my connection side. */
2652static int hlua_socket_getsockname(struct lua_State *L)
2653{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002654 struct hlua_socket *socket;
2655 struct connection *conn;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002656 struct appctx *appctx;
2657 struct xref *peer;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002658 struct stream *s;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002659 int ret;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002660
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002661 MAY_LJMP(check_args(L, 1, "getsockname"));
2662
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002663 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002664
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002665 /* Check if we run on the same thread than the xreator thread.
2666 * We cannot access to the socket if the thread is different.
2667 */
2668 if (socket->tid != tid)
2669 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2670
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002671 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002672 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002673 if (!peer) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002674 lua_pushnil(L);
2675 return 1;
2676 }
Willy Tarreau5321da92022-05-06 11:57:34 +02002677
2678 appctx = container_of(peer, struct hlua_csk_ctx, xref)->appctx;
Willy Tarreau0698c802022-05-11 14:09:57 +02002679 s = appctx_strm(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002680
Willy Tarreaufd9417b2022-05-18 16:23:22 +02002681 conn = sc_conn(s->scb);
Willy Tarreau5a0b25d2019-07-18 18:01:14 +02002682 if (!conn || !conn_get_src(conn)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002683 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002684 lua_pushnil(L);
2685 return 1;
2686 }
2687
Willy Tarreau9da9a6f2019-07-17 14:49:44 +02002688 ret = hlua_socket_info(L, conn->src);
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002689 xref_unlock(&socket->xref, peer);
2690 return ret;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002691}
2692
2693/* This struct define the applet. */
Willy Tarreau30576452015-04-13 13:50:30 +02002694static struct applet update_applet = {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002695 .obj_type = OBJ_TYPE_APPLET,
2696 .name = "<LUA_TCP>",
2697 .fct = hlua_socket_handler,
Christopher Faulet5f35a3e2022-05-12 15:31:05 +02002698 .init = hlua_socket_init,
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002699 .release = hlua_socket_release,
2700};
2701
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002702__LJMP static int hlua_socket_connect_yield(struct lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002703{
2704 struct hlua_socket *socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002705 struct hlua *hlua;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002706 struct xref *peer;
Willy Tarreau5321da92022-05-06 11:57:34 +02002707 struct hlua_csk_ctx *csk_ctx;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002708 struct appctx *appctx;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002709 struct stream *s;
2710
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002711 /* Get hlua struct, or NULL if we execute from main lua state */
2712 hlua = hlua_gethlua(L);
2713 if (!hlua)
2714 return 0;
2715
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 */
2719 if (socket->tid != tid)
2720 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2721
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002722 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002723 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002724 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002725 lua_pushnil(L);
2726 lua_pushstring(L, "Can't connect");
2727 return 2;
2728 }
Willy Tarreau5321da92022-05-06 11:57:34 +02002729
2730 csk_ctx = container_of(peer, struct hlua_csk_ctx, xref);
2731 appctx = csk_ctx->appctx;
Willy Tarreau0698c802022-05-11 14:09:57 +02002732 s = appctx_strm(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002733
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002734 /* Check if we run on the same thread than the xreator thread.
2735 * We cannot access to the socket if the thread is different.
2736 */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002737 if (socket->tid != tid) {
2738 xref_unlock(&socket->xref, peer);
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002739 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002740 }
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002741
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002742 /* Check for connection close. */
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002743 if (!hlua || channel_output_closed(&s->req)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002744 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002745 lua_pushnil(L);
2746 lua_pushstring(L, "Can't connect");
2747 return 2;
2748 }
2749
Willy Tarreau8e7c6e62022-05-18 17:58:02 +02002750 appctx = __sc_appctx(s->scf);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002751
2752 /* Check for connection established. */
Willy Tarreau5321da92022-05-06 11:57:34 +02002753 if (csk_ctx->connected) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002754 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002755 lua_pushinteger(L, 1);
2756 return 1;
2757 }
2758
Willy Tarreau5321da92022-05-06 11:57:34 +02002759 if (!notification_new(&hlua->com, &csk_ctx->wake_on_write, hlua->task)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002760 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002761 WILL_LJMP(luaL_error(L, "out of memory error"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002762 }
2763 xref_unlock(&socket->xref, peer);
Willy Tarreau9635e032018-10-16 17:52:55 +02002764 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_connect_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002765 return 0;
2766}
2767
2768/* This function fail or initite the connection. */
2769__LJMP static int hlua_socket_connect(struct lua_State *L)
2770{
2771 struct hlua_socket *socket;
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002772 int port = -1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002773 const char *ip;
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002774 struct hlua *hlua;
Willy Tarreau5321da92022-05-06 11:57:34 +02002775 struct hlua_csk_ctx *csk_ctx;
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002776 struct appctx *appctx;
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002777 int low, high;
2778 struct sockaddr_storage *addr;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002779 struct xref *peer;
Willy Tarreau4596fe22022-05-17 19:07:51 +02002780 struct stconn *cs;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002781 struct stream *s;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002782
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002783 if (lua_gettop(L) < 2)
2784 WILL_LJMP(luaL_error(L, "connect: need at least 2 arguments"));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002785
2786 /* Get args. */
2787 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002788
2789 /* Check if we run on the same thread than the xreator thread.
2790 * We cannot access to the socket if the thread is different.
2791 */
2792 if (socket->tid != tid)
2793 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2794
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002795 ip = MAY_LJMP(luaL_checkstring(L, 2));
Tim Duesterhus6edab862018-01-06 19:04:45 +01002796 if (lua_gettop(L) >= 3) {
2797 luaL_Buffer b;
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002798 port = MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002799
Tim Duesterhus6edab862018-01-06 19:04:45 +01002800 /* Force the ip to end with a colon, to support IPv6 addresses
2801 * that are not enclosed within square brackets.
2802 */
2803 if (port > 0) {
2804 luaL_buffinit(L, &b);
2805 luaL_addstring(&b, ip);
2806 luaL_addchar(&b, ':');
2807 luaL_pushresult(&b);
2808 ip = lua_tolstring(L, lua_gettop(L), NULL);
2809 }
2810 }
2811
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002812 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002813 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002814 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002815 lua_pushnil(L);
2816 return 1;
2817 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002818
2819 /* Parse ip address. */
Willy Tarreau5fc93282020-09-16 18:25:03 +02002820 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 +02002821 if (!addr) {
2822 xref_unlock(&socket->xref, peer);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002823 WILL_LJMP(luaL_error(L, "connect: cannot parse destination address '%s'", ip));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002824 }
Willy Tarreau9da9a6f2019-07-17 14:49:44 +02002825
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002826 /* Set port. */
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002827 if (low == 0) {
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02002828 if (addr->ss_family == AF_INET) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002829 if (port == -1) {
2830 xref_unlock(&socket->xref, peer);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002831 WILL_LJMP(luaL_error(L, "connect: port missing"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002832 }
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02002833 ((struct sockaddr_in *)addr)->sin_port = htons(port);
2834 } else if (addr->ss_family == AF_INET6) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002835 if (port == -1) {
2836 xref_unlock(&socket->xref, peer);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002837 WILL_LJMP(luaL_error(L, "connect: port missing"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002838 }
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02002839 ((struct sockaddr_in6 *)addr)->sin6_port = htons(port);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002840 }
2841 }
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02002842
Willy Tarreau5321da92022-05-06 11:57:34 +02002843 csk_ctx = container_of(peer, struct hlua_csk_ctx, xref);
2844 appctx = csk_ctx->appctx;
Willy Tarreau0698c802022-05-11 14:09:57 +02002845 cs = appctx_cs(appctx);
Willy Tarreauea27f482022-05-18 16:10:52 +02002846 s = __sc_strm(cs);
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02002847
Christopher Faulet8da67aa2022-03-29 17:53:09 +02002848 if (!sockaddr_alloc(&cs_opposite(cs)->dst, addr, sizeof(*addr))) {
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02002849 xref_unlock(&socket->xref, peer);
2850 WILL_LJMP(luaL_error(L, "connect: internal error"));
2851 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002852
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002853 /* Get hlua struct, or NULL if we execute from main lua state */
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002854 hlua = hlua_gethlua(L);
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002855 if (!hlua)
2856 return 0;
Willy Tarreaubdc97a82015-08-24 15:42:28 +02002857
2858 /* inform the stream that we want to be notified whenever the
2859 * connection completes.
2860 */
Willy Tarreau90e8b452022-05-25 18:21:43 +02002861 applet_need_more_data(appctx);
Willy Tarreau4164eb92022-05-25 15:42:03 +02002862 applet_have_more_data(appctx);
Thierry FOURNIER8c8fbbe2015-09-26 17:02:35 +02002863 appctx_wakeup(appctx);
Willy Tarreaubdc97a82015-08-24 15:42:28 +02002864
Willy Tarreauf31af932020-01-14 09:59:38 +01002865 hlua->gc_count++;
Thierry FOURNIER7c39ab42015-09-27 22:53:33 +02002866
Willy Tarreau5321da92022-05-06 11:57:34 +02002867 if (!notification_new(&hlua->com, &csk_ctx->wake_on_write, hlua->task)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002868 xref_unlock(&socket->xref, peer);
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002869 WILL_LJMP(luaL_error(L, "out of memory"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002870 }
2871 xref_unlock(&socket->xref, peer);
PiBa-NL706d5ee2018-05-05 23:51:42 +02002872
2873 task_wakeup(s->task, TASK_WOKEN_INIT);
2874 /* Return yield waiting for connection. */
2875
Willy Tarreau9635e032018-10-16 17:52:55 +02002876 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_connect_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002877
2878 return 0;
2879}
2880
Baptiste Assmann84bb4932015-03-02 21:40:06 +01002881#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002882__LJMP static int hlua_socket_connect_ssl(struct lua_State *L)
2883{
2884 struct hlua_socket *socket;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002885 struct xref *peer;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002886 struct stream *s;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002887
2888 MAY_LJMP(check_args(L, 3, "connect_ssl"));
2889 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002890
2891 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002892 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002893 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002894 lua_pushnil(L);
2895 return 1;
2896 }
Willy Tarreau5321da92022-05-06 11:57:34 +02002897
Willy Tarreau0698c802022-05-11 14:09:57 +02002898 s = appctx_strm(container_of(peer, struct hlua_csk_ctx, xref)->appctx);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002899
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +01002900 s->target = &socket_ssl->obj_type;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002901 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002902 return MAY_LJMP(hlua_socket_connect(L));
2903}
Baptiste Assmann84bb4932015-03-02 21:40:06 +01002904#endif
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002905
2906__LJMP static int hlua_socket_setoption(struct lua_State *L)
2907{
2908 return 0;
2909}
2910
2911__LJMP static int hlua_socket_settimeout(struct lua_State *L)
2912{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002913 struct hlua_socket *socket;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002914 int tmout;
Mark Lakes56cc1252018-03-27 09:48:06 +02002915 double dtmout;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002916 struct xref *peer;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002917 struct stream *s;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002918
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002919 MAY_LJMP(check_args(L, 2, "settimeout"));
2920
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002921 socket = MAY_LJMP(hlua_checksocket(L, 1));
Mark Lakes56cc1252018-03-27 09:48:06 +02002922
Cyril Bonté7ee465f2018-08-19 22:08:50 +02002923 /* convert the timeout to millis */
2924 dtmout = MAY_LJMP(luaL_checknumber(L, 2)) * 1000;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002925
Thierry Fournier17a921b2018-03-08 09:59:02 +01002926 /* Check for negative values */
Mark Lakes56cc1252018-03-27 09:48:06 +02002927 if (dtmout < 0)
Thierry Fournier17a921b2018-03-08 09:59:02 +01002928 WILL_LJMP(luaL_error(L, "settimeout: cannot set negatives values"));
2929
Mark Lakes56cc1252018-03-27 09:48:06 +02002930 if (dtmout > INT_MAX) /* overflow check */
Cyril Bonté7ee465f2018-08-19 22:08:50 +02002931 WILL_LJMP(luaL_error(L, "settimeout: cannot set values larger than %d ms", INT_MAX));
Mark Lakes56cc1252018-03-27 09:48:06 +02002932
2933 tmout = MS_TO_TICKS((int)dtmout);
Cyril Bonté7ee465f2018-08-19 22:08:50 +02002934 if (tmout == 0)
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05002935 tmout++; /* very small timeouts are adjusted to a minimum of 1ms */
Mark Lakes56cc1252018-03-27 09:48:06 +02002936
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002937 /* Check if we run on the same thread than the xreator thread.
2938 * We cannot access to the socket if the thread is different.
2939 */
2940 if (socket->tid != tid)
2941 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2942
Mark Lakes56cc1252018-03-27 09:48:06 +02002943 /* check for connection break. If some data were read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002944 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002945 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002946 hlua_pusherror(L, "socket: not yet initialised, you can't set timeouts.");
2947 WILL_LJMP(lua_error(L));
2948 return 0;
2949 }
Willy Tarreau5321da92022-05-06 11:57:34 +02002950
Willy Tarreau0698c802022-05-11 14:09:57 +02002951 s = appctx_strm(container_of(peer, struct hlua_csk_ctx, xref)->appctx);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002952
Cyril Bonté7bb63452018-08-17 23:51:02 +02002953 s->sess->fe->timeout.connect = tmout;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002954 s->req.rto = tmout;
2955 s->req.wto = tmout;
2956 s->res.rto = tmout;
2957 s->res.wto = tmout;
Cyril Bonté7bb63452018-08-17 23:51:02 +02002958 s->req.rex = tick_add_ifset(now_ms, tmout);
2959 s->req.wex = tick_add_ifset(now_ms, tmout);
2960 s->res.rex = tick_add_ifset(now_ms, tmout);
2961 s->res.wex = tick_add_ifset(now_ms, tmout);
2962
2963 s->task->expire = tick_add_ifset(now_ms, tmout);
2964 task_queue(s->task);
2965
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002966 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002967
Thierry Fourniere9636f12018-03-08 09:54:32 +01002968 lua_pushinteger(L, 1);
Tim Duesterhus119a5f12018-01-06 19:16:25 +01002969 return 1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002970}
2971
2972__LJMP static int hlua_socket_new(lua_State *L)
2973{
2974 struct hlua_socket *socket;
Willy Tarreau5321da92022-05-06 11:57:34 +02002975 struct hlua_csk_ctx *ctx;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002976 struct appctx *appctx;
2977
2978 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002979 if (!lua_checkstack(L, 3)) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002980 hlua_pusherror(L, "socket: full stack");
2981 goto out_fail_conf;
2982 }
2983
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002984 /* Create the object: obj[0] = userdata. */
2985 lua_newtable(L);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002986 socket = MAY_LJMP(lua_newuserdata(L, sizeof(*socket)));
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002987 lua_rawseti(L, -2, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002988 memset(socket, 0, sizeof(*socket));
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002989 socket->tid = tid;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002990
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05002991 /* Check if the various memory pools are initialized. */
Willy Tarreaubafbe012017-11-24 17:34:44 +01002992 if (!pool_head_stream || !pool_head_buffer) {
Thierry FOURNIER4a6170c2015-03-09 17:07:10 +01002993 hlua_pusherror(L, "socket: uninitialized pools.");
2994 goto out_fail_conf;
2995 }
2996
Willy Tarreau87b09662015-04-03 00:22:06 +02002997 /* Pop a class stream metatable and affect it to the userdata. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002998 lua_rawgeti(L, LUA_REGISTRYINDEX, class_socket_ref);
2999 lua_setmetatable(L, -2);
3000
Willy Tarreaud420a972015-04-06 00:39:18 +02003001 /* Create the applet context */
Christopher Faulet6095d572022-05-16 17:09:48 +02003002 appctx = appctx_new_here(&update_applet, NULL);
Willy Tarreau61cf7c82015-04-06 00:48:33 +02003003 if (!appctx) {
3004 hlua_pusherror(L, "socket: out of memory");
Christopher Fauleta9e8b392022-03-23 11:01:09 +01003005 goto out_fail_conf;
Willy Tarreau61cf7c82015-04-06 00:48:33 +02003006 }
Willy Tarreau5321da92022-05-06 11:57:34 +02003007 ctx = applet_reserve_svcctx(appctx, sizeof(*ctx));
3008 ctx->connected = 0;
Willy Tarreau5321da92022-05-06 11:57:34 +02003009 ctx->die = 0;
3010 LIST_INIT(&ctx->wake_on_write);
3011 LIST_INIT(&ctx->wake_on_read);
Willy Tarreaub2bf8332015-04-04 15:58:58 +02003012
Christopher Faulet5f35a3e2022-05-12 15:31:05 +02003013 if (appctx_init(appctx) == -1) {
3014 hlua_pusherror(L, "socket: fail to init applet.");
Christopher Faulet13a35e52021-12-20 15:34:16 +01003015 goto out_fail_appctx;
3016 }
3017
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003018 /* Initialise cross reference between stream and Lua socket object. */
Willy Tarreau5321da92022-05-06 11:57:34 +02003019 xref_create(&socket->xref, &ctx->xref);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003020 return 1;
3021
Christopher Faulet13a35e52021-12-20 15:34:16 +01003022 out_fail_appctx:
Christopher Faulet5f35a3e2022-05-12 15:31:05 +02003023 appctx_free_on_early_error(appctx);
Willy Tarreaud420a972015-04-06 00:39:18 +02003024 out_fail_conf:
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003025 WILL_LJMP(lua_error(L));
3026 return 0;
3027}
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01003028
3029/*
3030 *
3031 *
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003032 * Class Channel
3033 *
3034 *
3035 */
3036
3037/* Returns the struct hlua_channel join to the class channel in the
3038 * stack entry "ud" or throws an argument error.
3039 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01003040__LJMP static struct channel *hlua_checkchannel(lua_State *L, int ud)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003041{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003042 return MAY_LJMP(hlua_checkudata(L, ud, class_channel_ref));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003043}
3044
Willy Tarreau47860ed2015-03-10 14:07:50 +01003045/* Pushes the channel onto the top of the stack. If the stask does not have a
3046 * free slots, the function fails and returns 0;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003047 */
Willy Tarreau2a71af42015-03-10 13:51:50 +01003048static int hlua_channel_new(lua_State *L, struct channel *channel)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003049{
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003050 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003051 if (!lua_checkstack(L, 3))
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003052 return 0;
3053
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003054 lua_newtable(L);
Willy Tarreau47860ed2015-03-10 14:07:50 +01003055 lua_pushlightuserdata(L, channel);
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003056 lua_rawseti(L, -2, 0);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003057
3058 /* Pop a class sesison metatable and affect it to the userdata. */
3059 lua_rawgeti(L, LUA_REGISTRYINDEX, class_channel_ref);
3060 lua_setmetatable(L, -2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003061 return 1;
3062}
3063
Christopher Faulet9f55a502020-02-25 15:21:02 +01003064/* Helper function returning a filter attached to a channel at the position <ud>
3065 * in the stack, filling the current offset and length of the filter. If no
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05003066 * filter is attached, NULL is returned and <offset> and <len> are not
Christopher Faulet9f55a502020-02-25 15:21:02 +01003067 * initialized.
3068 */
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003069static 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 +01003070{
3071 struct filter *filter = NULL;
3072
3073 if (lua_getfield(L, ud, "__filter") == LUA_TLIGHTUSERDATA) {
3074 struct hlua_flt_ctx *flt_ctx;
3075
3076 filter = lua_touserdata (L, -1);
3077 flt_ctx = filter->ctx;
3078 if (hlua_filter_from_payload(filter)) {
3079 *offset = flt_ctx->cur_off[CHN_IDX(chn)];
3080 *len = flt_ctx->cur_len[CHN_IDX(chn)];
3081 }
3082 }
3083
3084 lua_pop(L, 1);
3085 return filter;
3086}
3087
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003088/* Copies <len> bytes of data present in the channel's buffer, starting at the
3089* offset <offset>, and put it in a LUA string variable. It is the caller
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003090* responsibility to ensure <len> and <offset> are valid. It always return the
3091* length of the built string. <len> may be 0, in this case, an empty string is
3092* created and 0 is returned.
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003093*/
3094static inline int _hlua_channel_dup(struct channel *chn, lua_State *L, size_t offset, size_t len)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003095{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003096 size_t block1, block2;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003097 luaL_Buffer b;
3098
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003099 block1 = len;
3100 if (block1 > b_contig_data(&chn->buf, b_peek_ofs(&chn->buf, offset)))
3101 block1 = b_contig_data(&chn->buf, b_peek_ofs(&chn->buf, offset));
3102 block2 = len - block1;
3103
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003104 luaL_buffinit(L, &b);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003105 luaL_addlstring(&b, b_peek(&chn->buf, offset), block1);
3106 if (block2)
3107 luaL_addlstring(&b, b_orig(&chn->buf), block2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003108 luaL_pushresult(&b);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003109 return len;
3110}
3111
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003112/* Inserts the string <str> to the channel's buffer at the offset <offset>. This
3113 * function returns -1 if data cannot be copied. Otherwise, it returns the
3114 * number of bytes copied.
3115 */
3116static int _hlua_channel_insert(struct channel *chn, lua_State *L, struct ist str, size_t offset)
3117{
3118 int ret = 0;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003119
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003120 /* Nothing to do, just return */
3121 if (unlikely(istlen(str) == 0))
3122 goto end;
3123
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003124 if (istlen(str) > c_room(chn)) {
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003125 ret = -1;
3126 goto end;
3127 }
3128 ret = b_insert_blk(&chn->buf, offset, istptr(str), istlen(str));
3129
3130 end:
3131 return ret;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003132}
3133
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003134/* Removes <len> bytes of data at the absolute position <offset>.
3135 */
3136static void _hlua_channel_delete(struct channel *chn, size_t offset, size_t len)
3137{
3138 size_t end = offset + len;
3139
3140 if (b_peek(&chn->buf, end) != b_tail(&chn->buf))
3141 b_move(&chn->buf, b_peek_ofs(&chn->buf, end),
3142 b_data(&chn->buf) - end, -len);
3143 b_sub(&chn->buf, len);
3144}
3145
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003146/* Copies input data in the channel's buffer. It is possible to set a specific
3147 * offset (0 by default) and a length (all remaining input data starting for the
3148 * offset by default). If there is not enough input data and more data can be
3149 * received, this function yields.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003150 *
3151 * From an action, All input data are considered. For a filter, the offset and
3152 * the length of input data to consider are retrieved from the filter context.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003153 */
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003154__LJMP static int hlua_channel_get_data_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003155{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003156 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003157 struct filter *filter;
3158 size_t input, output;
3159 int offset, len;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003160
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003161 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003162
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003163 output = co_data(chn);
3164 input = ci_data(chn);
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003165
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003166 filter = hlua_channel_filter(L, 1, chn, &output, &input);
3167 if (filter && !hlua_filter_from_payload(filter))
3168 WILL_LJMP(lua_error(L));
3169
3170 offset = output;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003171 if (lua_gettop(L) > 1) {
3172 offset = MAY_LJMP(luaL_checkinteger(L, 2));
3173 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02003174 offset = MAX(0, (int)input + offset);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003175 offset += output;
3176 if (offset < output || offset > input + output) {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003177 lua_pushfstring(L, "offset out of range.");
3178 WILL_LJMP(lua_error(L));
3179 }
3180 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003181 len = output + input - offset;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003182 if (lua_gettop(L) == 3) {
3183 len = MAY_LJMP(luaL_checkinteger(L, 3));
3184 if (!len)
3185 goto dup;
3186 if (len == -1)
3187 len = global.tune.bufsize;
3188 if (len < 0) {
3189 lua_pushfstring(L, "length out of range.");
3190 WILL_LJMP(lua_error(L));
3191 }
3192 }
3193
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003194 if (offset + len > output + input) {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003195 if (!HLUA_CANT_YIELD(hlua_gethlua(L)) && !channel_input_closed(chn) && channel_may_recv(chn)) {
3196 /* Yield waiting for more data, as requested */
3197 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_get_data_yield, TICK_ETERNITY, 0));
3198 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003199 len = output + input - offset;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003200 }
3201
3202 dup:
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003203 _hlua_channel_dup(chn, L, offset, len);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003204 return 1;
3205}
3206
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003207/* Copies the first line (including the trailing LF) of input data in the
3208 * channel's buffer. It is possible to set a specific offset (0 by default) and
3209 * a length (all remaining input data starting for the offset by default). If
3210 * there is not enough input data and more data can be received, the function
3211 * yields. If a length is explicitly specified, no more data are
3212 * copied. Otherwise, if no LF is found and more data can be received, this
3213 * function yields.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003214 *
3215 * From an action, All input data are considered. For a filter, the offset and
3216 * the length of input data to consider are retrieved from the filter context.
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003217 */
3218__LJMP static int hlua_channel_get_line_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003219{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003220 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003221 struct filter *filter;
3222 size_t l, input, output;
3223 int offset, len;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003224
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003225 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003226 output = co_data(chn);
3227 input = ci_data(chn);
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003228
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003229 filter = hlua_channel_filter(L, 1, chn, &output, &input);
3230 if (filter && !hlua_filter_from_payload(filter))
3231 WILL_LJMP(lua_error(L));
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003232
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003233 offset = output;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003234 if (lua_gettop(L) > 1) {
3235 offset = MAY_LJMP(luaL_checkinteger(L, 2));
3236 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02003237 offset = MAX(0, (int)input + offset);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003238 offset += output;
3239 if (offset < output || offset > input + output) {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003240 lua_pushfstring(L, "offset out of range.");
3241 WILL_LJMP(lua_error(L));
3242 }
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003243 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003244
3245 len = output + input - offset;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003246 if (lua_gettop(L) == 3) {
3247 len = MAY_LJMP(luaL_checkinteger(L, 3));
3248 if (!len)
3249 goto dup;
3250 if (len == -1)
3251 len = global.tune.bufsize;
3252 if (len < 0) {
3253 lua_pushfstring(L, "length out of range.");
3254 WILL_LJMP(lua_error(L));
3255 }
3256 }
3257
3258 for (l = 0; l < len; l++) {
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003259 if (l + offset >= output + input)
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003260 break;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003261 if (*(b_peek(&chn->buf, offset + l)) == '\n') {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003262 len = l+1;
3263 goto dup;
3264 }
3265 }
3266
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003267 if (offset + len > output + input) {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003268 if (!HLUA_CANT_YIELD(hlua_gethlua(L)) && !channel_input_closed(chn) && channel_may_recv(chn)) {
3269 /* Yield waiting for more data */
3270 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_get_line_yield, TICK_ETERNITY, 0));
3271 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003272 len = output + input - offset;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003273 }
3274
3275 dup:
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003276 _hlua_channel_dup(chn, L, offset, len);
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003277 return 1;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003278}
3279
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003280/* [ DEPRECATED ]
3281 *
3282 * Duplicate all input data foud in the channel's buffer. The data are not
3283 * removed from the buffer. This function relies on _hlua_channel_dup().
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003284 *
3285 * From an action, All input data are considered. For a filter, the offset and
3286 * the length of input data to consider are retrieved from the filter context.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003287 */
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003288__LJMP static int hlua_channel_dup(lua_State *L)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003289{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003290 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003291 struct filter *filter;
3292 size_t offset, len;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003293
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003294 MAY_LJMP(check_args(L, 1, "dup"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003295 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003296 if (IS_HTX_STRM(chn_strm(chn))) {
3297 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3298 WILL_LJMP(lua_error(L));
3299 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003300
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003301 offset = co_data(chn);
3302 len = ci_data(chn);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003303
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003304 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3305 if (filter && !hlua_filter_from_payload(filter))
3306 WILL_LJMP(lua_error(L));
3307
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003308 if (!ci_data(chn) && channel_input_closed(chn)) {
3309 lua_pushnil(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003310 return 1;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003311 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003312
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003313 _hlua_channel_dup(chn, L, offset, len);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003314 return 1;
3315}
3316
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003317/* [ DEPRECATED ]
3318 *
3319 * Get all input data foud in the channel's buffer. The data are removed from
3320 * the buffer after the copy. This function relies on _hlua_channel_dup() and
3321 * _hlua_channel_delete().
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003322 *
3323 * From an action, All input data are considered. For a filter, the offset and
3324 * the length of input data to consider are retrieved from the filter context.
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003325 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003326__LJMP static int hlua_channel_get(lua_State *L)
3327{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003328 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003329 struct filter *filter;
3330 size_t offset, len;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003331 int ret;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003332
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003333 MAY_LJMP(check_args(L, 1, "get"));
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003334 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3335 if (IS_HTX_STRM(chn_strm(chn))) {
3336 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3337 WILL_LJMP(lua_error(L));
3338 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003339
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003340 offset = co_data(chn);
3341 len = ci_data(chn);
3342
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003343 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3344 if (filter && !hlua_filter_from_payload(filter))
3345 WILL_LJMP(lua_error(L));
3346
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003347 if (!ci_data(chn) && channel_input_closed(chn)) {
3348 lua_pushnil(L);
3349 return 1;
3350 }
3351
3352 ret = _hlua_channel_dup(chn, L, offset, len);
3353 _hlua_channel_delete(chn, offset, ret);
3354 return 1;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003355}
3356
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003357/* This functions consumes and returns one line. If the channel is closed,
3358 * and the last data does not contains a final '\n', the data are returned
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003359 * without the final '\n'. When no more data are available, it returns nil
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003360 * value.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003361 *
3362 * From an action, All input data are considered. For a filter, the offset and
3363 * the length of input data to consider are retrieved from the filter context.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003364 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003365__LJMP static int hlua_channel_getline_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003366{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003367 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003368 struct filter *filter;
3369 size_t l, offset, len;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003370 int ret;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003371
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003372 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003373
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003374 offset = co_data(chn);
3375 len = ci_data(chn);
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003376
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003377 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3378 if (filter && !hlua_filter_from_payload(filter))
3379 WILL_LJMP(lua_error(L));
3380
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003381 if (!ci_data(chn) && channel_input_closed(chn)) {
3382 lua_pushnil(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003383 return 1;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003384 }
3385
3386 for (l = 0; l < len; l++) {
3387 if (*(b_peek(&chn->buf, offset+l)) == '\n') {
3388 len = l+1;
3389 goto dup;
3390 }
3391 }
3392
3393 if (!HLUA_CANT_YIELD(hlua_gethlua(L)) && !channel_input_closed(chn) && channel_may_recv(chn)) {
3394 /* Yield waiting for more data */
3395 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_getline_yield, TICK_ETERNITY, 0));
3396 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003397
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003398 dup:
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003399 ret = _hlua_channel_dup(chn, L, offset, len);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003400 _hlua_channel_delete(chn, offset, ret);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003401 return 1;
3402}
3403
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003404/* [ DEPRECATED ]
3405 *
3406 * Check arguments for the function "hlua_channel_getline_yield".
3407 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003408__LJMP static int hlua_channel_getline(lua_State *L)
3409{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003410 struct channel *chn;
3411
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003412 MAY_LJMP(check_args(L, 1, "getline"));
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003413 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3414 if (IS_HTX_STRM(chn_strm(chn))) {
3415 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3416 WILL_LJMP(lua_error(L));
3417 }
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003418 return MAY_LJMP(hlua_channel_getline_yield(L, 0, 0));
3419}
3420
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003421/* Retrieves a given amount of input data at the given offset. By default all
3422 * available input data are returned. The offset may be negactive to start from
3423 * the end of input data. The length may be -1 to set it to the maximum buffer
3424 * size.
3425 */
3426__LJMP static int hlua_channel_get_data(lua_State *L)
3427{
3428 struct channel *chn;
3429
3430 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
3431 WILL_LJMP(luaL_error(L, "'data' expects at most 2 arguments"));
3432 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3433 if (IS_HTX_STRM(chn_strm(chn))) {
3434 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3435 WILL_LJMP(lua_error(L));
3436 }
3437 return MAY_LJMP(hlua_channel_get_data_yield(L, 0, 0));
3438}
3439
3440/* Retrieves a given amount of input data at the given offset. By default all
3441 * available input data are returned. The offset may be negactive to start from
3442 * the end of input data. The length may be -1 to set it to the maximum buffer
3443 * size.
3444 */
3445__LJMP static int hlua_channel_get_line(lua_State *L)
3446{
3447 struct channel *chn;
3448
3449 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
3450 WILL_LJMP(luaL_error(L, "'line' expects at most 2 arguments"));
3451 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3452 if (IS_HTX_STRM(chn_strm(chn))) {
3453 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3454 WILL_LJMP(lua_error(L));
3455 }
3456 return MAY_LJMP(hlua_channel_get_line_yield(L, 0, 0));
3457}
3458
3459/* Appends a string into the input side of channel. It returns the length of the
3460 * written string, or -1 if the channel is closed or if the buffer size is too
3461 * little for the data. 0 may be returned if nothing is copied. This function
3462 * does not yield.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003463 *
3464 * For a filter, the context is updated on success.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003465 */
Christopher Faulet23976d92021-08-06 09:59:49 +02003466__LJMP static int hlua_channel_append(lua_State *L)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003467{
Christopher Faulet23976d92021-08-06 09:59:49 +02003468 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003469 struct filter *filter;
Christopher Faulet23976d92021-08-06 09:59:49 +02003470 const char *str;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003471 size_t sz, offset, len;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003472 int ret;
Christopher Faulet23976d92021-08-06 09:59:49 +02003473
3474 MAY_LJMP(check_args(L, 2, "append"));
3475 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003476 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
Christopher Faulet1bb6afa2021-03-08 17:57:53 +01003477 if (IS_HTX_STRM(chn_strm(chn))) {
Thierry Fournier77016da2020-08-15 14:35:51 +02003478 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
Christopher Faulet3f829a42018-12-13 21:56:45 +01003479 WILL_LJMP(lua_error(L));
Thierry Fournier77016da2020-08-15 14:35:51 +02003480 }
Christopher Faulet3f829a42018-12-13 21:56:45 +01003481
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003482 offset = co_data(chn);
3483 len = ci_data(chn);
3484
3485 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3486 if (filter && !hlua_filter_from_payload(filter))
3487 WILL_LJMP(lua_error(L));
3488
3489 ret = _hlua_channel_insert(chn, L, ist2(str, sz), offset);
3490 if (ret > 0 && filter) {
3491 struct hlua_flt_ctx *flt_ctx = filter->ctx;
3492
3493 flt_update_offsets(filter, chn, ret);
3494 flt_ctx->cur_len[CHN_IDX(chn)] += ret;
3495 }
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003496 lua_pushinteger(L, ret);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003497 return 1;
3498}
3499
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003500/* Prepends a string into the input side of channel. It returns the length of the
3501 * written string, or -1 if the channel is closed or if the buffer size is too
3502 * little for the data. 0 may be returned if nothing is copied. This function
3503 * does not yield.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003504 *
3505 * For a filter, the context is updated on success.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003506 */
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003507__LJMP static int hlua_channel_prepend(lua_State *L)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003508{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003509 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003510 struct filter *filter;
Christopher Faulet23976d92021-08-06 09:59:49 +02003511 const char *str;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003512 size_t sz, offset, len;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003513 int ret;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003514
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003515 MAY_LJMP(check_args(L, 2, "prepend"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003516 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003517 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
3518 if (IS_HTX_STRM(chn_strm(chn))) {
3519 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3520 WILL_LJMP(lua_error(L));
3521 }
3522
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003523 offset = co_data(chn);
3524 len = ci_data(chn);
3525
3526 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3527 if (filter && !hlua_filter_from_payload(filter))
3528 WILL_LJMP(lua_error(L));
3529
3530 ret = _hlua_channel_insert(chn, L, ist2(str, sz), offset);
3531 if (ret > 0 && filter) {
3532 struct hlua_flt_ctx *flt_ctx = filter->ctx;
3533
3534 flt_update_offsets(filter, chn, ret);
3535 flt_ctx->cur_len[CHN_IDX(chn)] += ret;
3536 }
3537
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003538 lua_pushinteger(L, ret);
3539 return 1;
3540}
3541
3542/* Inserts a given amount of input data at the given offset by a string
3543 * content. By default the string is appended at the end of input data. It
3544 * returns the length of the written string, or -1 if the channel is closed or
3545 * if the buffer size is too little for the data.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003546 *
3547 * For a filter, the context is updated on success.
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003548 */
3549__LJMP static int hlua_channel_insert_data(lua_State *L)
3550{
3551 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003552 struct filter *filter;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003553 const char *str;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003554 size_t sz, input, output;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003555 int ret, offset;
3556
3557 if (lua_gettop(L) < 2 || lua_gettop(L) > 3)
3558 WILL_LJMP(luaL_error(L, "'insert' expects at least 1 argument and at most 2 arguments"));
3559 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3560 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003561
3562 output = co_data(chn);
3563 input = ci_data(chn);
3564
3565 filter = hlua_channel_filter(L, 1, chn, &output, &input);
3566 if (filter && !hlua_filter_from_payload(filter))
3567 WILL_LJMP(lua_error(L));
3568
3569 offset = input + output;
3570 if (lua_gettop(L) > 2) {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003571 offset = MAY_LJMP(luaL_checkinteger(L, 3));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003572 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02003573 offset = MAX(0, (int)input + offset);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003574 offset += output;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003575 if (offset < output || offset > output + input) {
3576 lua_pushfstring(L, "offset out of range.");
3577 WILL_LJMP(lua_error(L));
3578 }
3579 }
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003580 if (IS_HTX_STRM(chn_strm(chn))) {
3581 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3582 WILL_LJMP(lua_error(L));
3583 }
3584
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003585 ret = _hlua_channel_insert(chn, L, ist2(str, sz), offset);
3586 if (ret > 0 && filter) {
3587 struct hlua_flt_ctx *flt_ctx = filter->ctx;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003588
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003589 flt_update_offsets(filter, chn, ret);
3590 flt_ctx->cur_len[CHN_IDX(chn)] += ret;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003591 }
3592
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003593 lua_pushinteger(L, ret);
3594 return 1;
3595}
3596/* Replaces a given amount of input data at the given offset by a string
3597 * content. By default all remaining data are removed (offset = 0 and len =
3598 * -1). It returns the length of the written string, or -1 if the channel is
3599 * closed or if the buffer size is too little for the data.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003600 *
3601 * For a filter, the context is updated on success.
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003602 */
3603__LJMP static int hlua_channel_set_data(lua_State *L)
3604{
3605 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003606 struct filter *filter;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003607 const char *str;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003608 size_t sz, input, output;
3609 int ret, offset, len;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003610
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003611 if (lua_gettop(L) < 2 || lua_gettop(L) > 4)
3612 WILL_LJMP(luaL_error(L, "'set' expects at least 1 argument and at most 3 arguments"));
3613 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3614 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003615
Christopher Faulet1bb6afa2021-03-08 17:57:53 +01003616 if (IS_HTX_STRM(chn_strm(chn))) {
Thierry Fournier77016da2020-08-15 14:35:51 +02003617 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
Christopher Faulet3f829a42018-12-13 21:56:45 +01003618 WILL_LJMP(lua_error(L));
Thierry Fournier77016da2020-08-15 14:35:51 +02003619 }
Christopher Faulet3f829a42018-12-13 21:56:45 +01003620
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003621 output = co_data(chn);
3622 input = ci_data(chn);
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003623
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003624 filter = hlua_channel_filter(L, 1, chn, &output, &input);
3625 if (filter && !hlua_filter_from_payload(filter))
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003626 WILL_LJMP(lua_error(L));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003627
3628 offset = output;
3629 if (lua_gettop(L) > 2) {
3630 offset = MAY_LJMP(luaL_checkinteger(L, 3));
3631 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02003632 offset = MAX(0, (int)input + offset);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003633 offset += output;
3634 if (offset < output || offset > input + output) {
3635 lua_pushfstring(L, "offset out of range.");
3636 WILL_LJMP(lua_error(L));
3637 }
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003638 }
3639
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003640 len = output + input - offset;
3641 if (lua_gettop(L) == 4) {
3642 len = MAY_LJMP(luaL_checkinteger(L, 4));
3643 if (!len)
3644 goto set;
3645 if (len == -1)
3646 len = output + input - offset;
3647 if (len < 0 || offset + len > output + input) {
3648 lua_pushfstring(L, "length out of range.");
3649 WILL_LJMP(lua_error(L));
3650 }
3651 }
3652
3653 set:
Christopher Faulet23976d92021-08-06 09:59:49 +02003654 /* Be sure we can copied the string once input data will be removed. */
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003655 if (sz > c_room(chn) + len)
Christopher Faulet23976d92021-08-06 09:59:49 +02003656 lua_pushinteger(L, -1);
3657 else {
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003658 _hlua_channel_delete(chn, offset, len);
3659 ret = _hlua_channel_insert(chn, L, ist2(str, sz), offset);
3660 if (filter) {
3661 struct hlua_flt_ctx *flt_ctx = filter->ctx;
3662
3663 len -= (ret > 0 ? ret : 0);
3664 flt_update_offsets(filter, chn, -len);
3665 flt_ctx->cur_len[CHN_IDX(chn)] -= len;
3666 }
3667
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003668 lua_pushinteger(L, ret);
Christopher Faulet23976d92021-08-06 09:59:49 +02003669 }
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003670 return 1;
3671}
3672
3673/* Removes a given amount of input data at the given offset. By default all
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003674 * input data are removed (offset = 0 and len = -1). It returns the amount of
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003675 * the removed data.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003676 *
3677 * For a filter, the context is updated on success.
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003678 */
3679__LJMP static int hlua_channel_del_data(lua_State *L)
3680{
3681 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003682 struct filter *filter;
3683 size_t input, output;
3684 int offset, len;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003685
3686 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
3687 WILL_LJMP(luaL_error(L, "'remove' expects at most 2 arguments"));
3688 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003689
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003690 if (IS_HTX_STRM(chn_strm(chn))) {
3691 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3692 WILL_LJMP(lua_error(L));
3693 }
3694
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003695 output = co_data(chn);
3696 input = ci_data(chn);
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003697
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003698 filter = hlua_channel_filter(L, 1, chn, &output, &input);
3699 if (filter && !hlua_filter_from_payload(filter))
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003700 WILL_LJMP(lua_error(L));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003701
3702 offset = output;
Boyang Lie0c54352022-05-10 17:47:23 +00003703 if (lua_gettop(L) > 1) {
3704 offset = MAY_LJMP(luaL_checkinteger(L, 2));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003705 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02003706 offset = MAX(0, (int)input + offset);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003707 offset += output;
3708 if (offset < output || offset > input + output) {
3709 lua_pushfstring(L, "offset out of range.");
3710 WILL_LJMP(lua_error(L));
3711 }
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003712 }
3713
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003714 len = output + input - offset;
Boyang Lie0c54352022-05-10 17:47:23 +00003715 if (lua_gettop(L) == 3) {
3716 len = MAY_LJMP(luaL_checkinteger(L, 3));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003717 if (!len)
3718 goto end;
3719 if (len == -1)
3720 len = output + input - offset;
3721 if (len < 0 || offset + len > output + input) {
3722 lua_pushfstring(L, "length out of range.");
3723 WILL_LJMP(lua_error(L));
3724 }
3725 }
3726
3727 _hlua_channel_delete(chn, offset, len);
3728 if (filter) {
3729 struct hlua_flt_ctx *flt_ctx = filter->ctx;
3730
3731 flt_update_offsets(filter, chn, -len);
3732 flt_ctx->cur_len[CHN_IDX(chn)] -= len;
3733 }
3734
3735 end:
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003736 lua_pushinteger(L, len);
Christopher Faulet23976d92021-08-06 09:59:49 +02003737 return 1;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003738}
3739
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003740/* Append data in the output side of the buffer. This data is immediately
3741 * sent. The function returns the amount of data written. If the buffer
3742 * cannot contain the data, the function yields. The function returns -1
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003743 * if the channel is closed.
3744 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003745__LJMP static int hlua_channel_send_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003746{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003747 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003748 struct filter *filter;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003749 const char *str;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003750 size_t offset, len, sz;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003751 int l, ret;
Thierry Fournier4234dbd2020-11-28 13:18:23 +01003752 struct hlua *hlua;
3753
3754 /* Get hlua struct, or NULL if we execute from main lua state */
3755 hlua = hlua_gethlua(L);
3756 if (!hlua) {
3757 lua_pushnil(L);
3758 return 1;
3759 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003760
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003761 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3762 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
3763 l = MAY_LJMP(luaL_checkinteger(L, 3));
Christopher Faulet3f829a42018-12-13 21:56:45 +01003764
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003765 offset = co_data(chn);
3766 len = ci_data(chn);
3767
3768 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3769 if (filter && !hlua_filter_from_payload(filter))
3770 WILL_LJMP(lua_error(L));
3771
3772
Willy Tarreau47860ed2015-03-10 14:07:50 +01003773 if (unlikely(channel_output_closed(chn))) {
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003774 lua_pushinteger(L, -1);
3775 return 1;
3776 }
3777
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003778 len = c_room(chn);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003779 if (len > sz -l) {
3780 if (filter) {
3781 lua_pushinteger(L, -1);
3782 return 1;
3783 }
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003784 len = sz - l;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003785 }
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01003786
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003787 ret = _hlua_channel_insert(chn, L, ist2(str, len), offset);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003788 if (ret == -1) {
3789 lua_pop(L, 1);
3790 lua_pushinteger(L, -1);
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01003791 return 1;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003792 }
3793 if (ret) {
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003794 if (filter) {
3795 struct hlua_flt_ctx *flt_ctx = filter->ctx;
3796
3797
3798 flt_update_offsets(filter, chn, ret);
3799 FLT_OFF(filter, chn) += ret;
3800 flt_ctx->cur_off[CHN_IDX(chn)] += ret;
3801 }
3802 else
3803 c_adv(chn, ret);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003804
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003805 l += ret;
3806 lua_pop(L, 1);
3807 lua_pushinteger(L, l);
3808 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003809
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003810 if (l < sz) {
3811 /* Yield only if the channel's output is not empty.
3812 * Otherwise it means we cannot add more data. */
3813 if (co_data(chn) == 0 || HLUA_CANT_YIELD(hlua_gethlua(L)))
Christopher Faulet2e60aa42021-08-05 11:58:37 +02003814 return 1;
3815
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003816 /* If we are waiting for space in the response buffer, we
3817 * must set the flag WAKERESWR. This flag required the task
3818 * wake up if any activity is detected on the response buffer.
3819 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01003820 if (chn->flags & CF_ISRESP)
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003821 HLUA_SET_WAKERESWR(hlua);
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01003822 else
3823 HLUA_SET_WAKEREQWR(hlua);
Willy Tarreau9635e032018-10-16 17:52:55 +02003824 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003825 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003826
3827 return 1;
3828}
3829
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05003830/* Just a wrapper of "_hlua_channel_send". This wrapper permits
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003831 * yield the LUA process, and resume it without checking the
3832 * input arguments.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003833 *
3834 * This function cannot be called from a filter.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003835 */
3836__LJMP static int hlua_channel_send(lua_State *L)
3837{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003838 struct channel *chn;
3839
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003840 MAY_LJMP(check_args(L, 2, "send"));
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003841 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3842 if (IS_HTX_STRM(chn_strm(chn))) {
3843 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3844 WILL_LJMP(lua_error(L));
3845 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003846 lua_pushinteger(L, 0);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003847 return MAY_LJMP(hlua_channel_send_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003848}
3849
3850/* This function forward and amount of butes. The data pass from
3851 * the input side of the buffer to the output side, and can be
3852 * forwarded. This function never fails.
3853 *
3854 * The Lua function takes an amount of bytes to be forwarded in
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05003855 * input. It returns the number of bytes forwarded.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003856 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003857__LJMP static int hlua_channel_forward_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003858{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003859 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003860 struct filter *filter;
3861 size_t offset, len, fwd;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003862 int l, max;
Thierry Fournier4234dbd2020-11-28 13:18:23 +01003863 struct hlua *hlua;
3864
3865 /* Get hlua struct, or NULL if we execute from main lua state */
3866 hlua = hlua_gethlua(L);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003867 if (!hlua) {
3868 lua_pushnil(L);
Thierry Fournier4234dbd2020-11-28 13:18:23 +01003869 return 1;
Thierry Fournier77016da2020-08-15 14:35:51 +02003870 }
Christopher Faulet3f829a42018-12-13 21:56:45 +01003871
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003872 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003873 fwd = MAY_LJMP(luaL_checkinteger(L, 2));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003874 l = MAY_LJMP(luaL_checkinteger(L, -1));
3875
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003876 offset = co_data(chn);
3877 len = ci_data(chn);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003878
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003879 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3880 if (filter && !hlua_filter_from_payload(filter))
3881 WILL_LJMP(lua_error(L));
3882
3883 max = fwd - l;
3884 if (max > len)
3885 max = len;
3886
3887 if (filter) {
3888 struct hlua_flt_ctx *flt_ctx = filter->ctx;
3889
3890 FLT_OFF(filter, chn) += max;
3891 flt_ctx->cur_off[CHN_IDX(chn)] += max;
3892 flt_ctx->cur_len[CHN_IDX(chn)] -= max;
3893 }
3894 else
3895 channel_forward(chn, max);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003896
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003897 l += max;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003898 lua_pop(L, 1);
3899 lua_pushinteger(L, l);
3900
3901 /* Check if it miss bytes to forward. */
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003902 if (l < fwd) {
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003903 /* The the input channel or the output channel are closed, we
3904 * must return the amount of data forwarded.
3905 */
Christopher Faulet2e60aa42021-08-05 11:58:37 +02003906 if (channel_input_closed(chn) || channel_output_closed(chn) || HLUA_CANT_YIELD(hlua_gethlua(L)))
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003907 return 1;
3908
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003909 /* If we are waiting for space data in the response buffer, we
3910 * must set the flag WAKERESWR. This flag required the task
3911 * wake up if any activity is detected on the response buffer.
3912 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01003913 if (chn->flags & CF_ISRESP)
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003914 HLUA_SET_WAKERESWR(hlua);
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01003915 else
3916 HLUA_SET_WAKEREQWR(hlua);
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003917
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003918 /* Otherwise, we can yield waiting for new data in the inpout side. */
Willy Tarreau9635e032018-10-16 17:52:55 +02003919 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_forward_yield, TICK_ETERNITY, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003920 }
3921
3922 return 1;
3923}
3924
3925/* Just check the input and prepare the stack for the previous
3926 * function "hlua_channel_forward_yield"
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003927 *
3928 * This function cannot be called from a filter.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003929 */
3930__LJMP static int hlua_channel_forward(lua_State *L)
3931{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003932 struct channel *chn;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003933
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003934 MAY_LJMP(check_args(L, 2, "forward"));
3935 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3936 if (IS_HTX_STRM(chn_strm(chn))) {
3937 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3938 WILL_LJMP(lua_error(L));
3939 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003940 lua_pushinteger(L, 0);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003941 return MAY_LJMP(hlua_channel_forward_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003942}
3943
3944/* Just returns the number of bytes available in the input
3945 * side of the buffer. This function never fails.
3946 */
3947__LJMP static int hlua_channel_get_in_len(lua_State *L)
3948{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003949 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003950 struct filter *filter;
3951 size_t output, input;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003952
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003953 MAY_LJMP(check_args(L, 1, "input"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003954 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003955
3956 output = co_data(chn);
3957 input = ci_data(chn);
3958 filter = hlua_channel_filter(L, 1, chn, &output, &input);
3959 if (filter || !IS_HTX_STRM(chn_strm(chn)))
3960 lua_pushinteger(L, input);
3961 else {
Christopher Fauleta3ceac12018-12-14 13:39:09 +01003962 struct htx *htx = htxbuf(&chn->buf);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003963
Christopher Fauleta3ceac12018-12-14 13:39:09 +01003964 lua_pushinteger(L, htx->data - co_data(chn));
3965 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003966 return 1;
3967}
3968
Thierry FOURNIER / OZON.IO65192f32016-11-07 15:28:40 +01003969/* Returns true if the channel is full. */
3970__LJMP static int hlua_channel_is_full(lua_State *L)
3971{
3972 struct channel *chn;
Thierry FOURNIER / OZON.IO65192f32016-11-07 15:28:40 +01003973
3974 MAY_LJMP(check_args(L, 1, "is_full"));
3975 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Faulet0ec740e2020-02-26 11:59:19 +01003976 /* ignore the reserve, we are not on a producer side (ie in an
3977 * applet).
3978 */
3979 lua_pushboolean(L, channel_full(chn, 0));
Thierry FOURNIER / OZON.IO65192f32016-11-07 15:28:40 +01003980 return 1;
3981}
3982
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003983/* Returns true if the channel may still receive data. */
3984__LJMP static int hlua_channel_may_recv(lua_State *L)
3985{
3986 struct channel *chn;
3987
3988 MAY_LJMP(check_args(L, 1, "may_recv"));
3989 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3990 lua_pushboolean(L, (!channel_input_closed(chn) && channel_may_recv(chn)));
3991 return 1;
3992}
3993
Christopher Faulet2ac9ba22020-02-25 10:15:50 +01003994/* Returns true if the channel is the response channel. */
3995__LJMP static int hlua_channel_is_resp(lua_State *L)
3996{
3997 struct channel *chn;
3998
3999 MAY_LJMP(check_args(L, 1, "is_resp"));
4000 chn = MAY_LJMP(hlua_checkchannel(L, 1));
4001
4002 lua_pushboolean(L, !!(chn->flags & CF_ISRESP));
4003 return 1;
4004}
4005
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004006/* Just returns the number of bytes available in the output
4007 * side of the buffer. This function never fails.
4008 */
4009__LJMP static int hlua_channel_get_out_len(lua_State *L)
4010{
Willy Tarreau47860ed2015-03-10 14:07:50 +01004011 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004012 size_t output, input;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004013
Christopher Faulet6a79fc12021-08-06 16:02:36 +02004014 MAY_LJMP(check_args(L, 1, "output"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004015 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004016
4017 output = co_data(chn);
4018 input = ci_data(chn);
4019 hlua_channel_filter(L, 1, chn, &output, &input);
4020
4021 lua_pushinteger(L, output);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004022 return 1;
4023}
4024
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004025/*
4026 *
4027 *
4028 * Class Fetches
4029 *
4030 *
4031 */
4032
4033/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02004034 * a class stream, otherwise it throws an error.
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004035 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004036__LJMP static struct hlua_smp *hlua_checkfetches(lua_State *L, int ud)
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004037{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004038 return MAY_LJMP(hlua_checkudata(L, ud, class_fetches_ref));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004039}
4040
4041/* This function creates and push in the stack a fetch object according
4042 * with a current TXN.
4043 */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004044static int hlua_fetches_new(lua_State *L, struct hlua_txn *txn, unsigned int flags)
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004045{
Willy Tarreau7073c472015-04-06 11:15:40 +02004046 struct hlua_smp *hsmp;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004047
4048 /* Check stack size. */
4049 if (!lua_checkstack(L, 3))
4050 return 0;
4051
4052 /* Create the object: obj[0] = userdata.
4053 * Note that the base of the Fetches object is the
4054 * transaction object.
4055 */
4056 lua_newtable(L);
Willy Tarreau7073c472015-04-06 11:15:40 +02004057 hsmp = lua_newuserdata(L, sizeof(*hsmp));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004058 lua_rawseti(L, -2, 0);
4059
Willy Tarreau7073c472015-04-06 11:15:40 +02004060 hsmp->s = txn->s;
4061 hsmp->p = txn->p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01004062 hsmp->dir = txn->dir;
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004063 hsmp->flags = flags;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004064
4065 /* Pop a class sesison metatable and affect it to the userdata. */
4066 lua_rawgeti(L, LUA_REGISTRYINDEX, class_fetches_ref);
4067 lua_setmetatable(L, -2);
4068
4069 return 1;
4070}
4071
4072/* This function is an LUA binding. It is called with each sample-fetch.
4073 * It uses closure argument to store the associated sample-fetch. It
4074 * returns only one argument or throws an error. An error is thrown
4075 * only if an error is encountered during the argument parsing. If
4076 * the "sample-fetch" function fails, nil is returned.
4077 */
4078__LJMP static int hlua_run_sample_fetch(lua_State *L)
4079{
Willy Tarreaub2ccb562015-04-06 11:11:15 +02004080 struct hlua_smp *hsmp;
Willy Tarreau2ec22742015-03-10 14:27:20 +01004081 struct sample_fetch *f;
Frédéric Lécaillef874a832018-06-15 13:56:04 +02004082 struct arg args[ARGM_NBARGS + 1] = {{0}};
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004083 int i;
4084 struct sample smp;
4085
4086 /* Get closure arguments. */
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004087 f = lua_touserdata(L, lua_upvalueindex(1));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004088
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004089 /* Get traditional arguments. */
Willy Tarreaub2ccb562015-04-06 11:11:15 +02004090 hsmp = MAY_LJMP(hlua_checkfetches(L, 1));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004091
Thierry FOURNIERca988662015-12-20 18:43:03 +01004092 /* Check execution authorization. */
4093 if (f->use & SMP_USE_HTTP_ANY &&
4094 !(hsmp->flags & HLUA_F_MAY_USE_HTTP)) {
4095 lua_pushfstring(L, "the sample-fetch '%s' needs an HTTP parser which "
4096 "is not available in Lua services", f->kw);
4097 WILL_LJMP(lua_error(L));
4098 }
4099
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004100 /* Get extra arguments. */
4101 for (i = 0; i < lua_gettop(L) - 1; i++) {
4102 if (i >= ARGM_NBARGS)
4103 break;
4104 hlua_lua2arg(L, i + 2, &args[i]);
4105 }
4106 args[i].type = ARGT_STOP;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004107 args[i].data.str.area = NULL;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004108
4109 /* Check arguments. */
Willy Tarreaub2ccb562015-04-06 11:11:15 +02004110 MAY_LJMP(hlua_lua2arg_check(L, 2, args, f->arg_mask, hsmp->p));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004111
4112 /* Run the special args checker. */
Willy Tarreau2ec22742015-03-10 14:27:20 +01004113 if (f->val_args && !f->val_args(args, NULL)) {
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004114 lua_pushfstring(L, "error in arguments");
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004115 goto error;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004116 }
4117
4118 /* Initialise the sample. */
4119 memset(&smp, 0, sizeof(smp));
4120
4121 /* Run the sample fetch process. */
Willy Tarreau1777ea62016-03-10 16:15:46 +01004122 smp_set_owner(&smp, hsmp->p, hsmp->s->sess, hsmp->s, hsmp->dir & SMP_OPT_DIR);
Thierry FOURNIER0786d052015-05-11 15:42:45 +02004123 if (!f->process(args, &smp, f->kw, f->private)) {
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004124 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004125 lua_pushstring(L, "");
4126 else
4127 lua_pushnil(L);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004128 goto end;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004129 }
4130
4131 /* Convert the returned sample in lua value. */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004132 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004133 hlua_smp2lua_str(L, &smp);
4134 else
4135 hlua_smp2lua(L, &smp);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004136
4137 end:
Willy Tarreauee0d7272021-07-16 10:26:56 +02004138 free_args(args);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004139 return 1;
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004140
4141 error:
Willy Tarreauee0d7272021-07-16 10:26:56 +02004142 free_args(args);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004143 WILL_LJMP(lua_error(L));
4144 return 0; /* Never reached */
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004145}
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004146
4147/*
4148 *
4149 *
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004150 * Class Converters
4151 *
4152 *
4153 */
4154
4155/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02004156 * a class stream, otherwise it throws an error.
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004157 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004158__LJMP static struct hlua_smp *hlua_checkconverters(lua_State *L, int ud)
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004159{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004160 return MAY_LJMP(hlua_checkudata(L, ud, class_converters_ref));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004161}
4162
4163/* This function creates and push in the stack a Converters object
4164 * according with a current TXN.
4165 */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004166static int hlua_converters_new(lua_State *L, struct hlua_txn *txn, unsigned int flags)
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004167{
Willy Tarreau7073c472015-04-06 11:15:40 +02004168 struct hlua_smp *hsmp;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004169
4170 /* Check stack size. */
4171 if (!lua_checkstack(L, 3))
4172 return 0;
4173
4174 /* Create the object: obj[0] = userdata.
4175 * Note that the base of the Converters object is the
4176 * same than the TXN object.
4177 */
4178 lua_newtable(L);
Willy Tarreau7073c472015-04-06 11:15:40 +02004179 hsmp = lua_newuserdata(L, sizeof(*hsmp));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004180 lua_rawseti(L, -2, 0);
4181
Willy Tarreau7073c472015-04-06 11:15:40 +02004182 hsmp->s = txn->s;
4183 hsmp->p = txn->p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01004184 hsmp->dir = txn->dir;
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004185 hsmp->flags = flags;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004186
Willy Tarreau87b09662015-04-03 00:22:06 +02004187 /* Pop a class stream metatable and affect it to the table. */
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004188 lua_rawgeti(L, LUA_REGISTRYINDEX, class_converters_ref);
4189 lua_setmetatable(L, -2);
4190
4191 return 1;
4192}
4193
4194/* This function is an LUA binding. It is called with each converter.
4195 * It uses closure argument to store the associated converter. It
4196 * returns only one argument or throws an error. An error is thrown
4197 * only if an error is encountered during the argument parsing. If
4198 * the converter function function fails, nil is returned.
4199 */
4200__LJMP static int hlua_run_sample_conv(lua_State *L)
4201{
Willy Tarreauda5f1082015-04-06 11:17:13 +02004202 struct hlua_smp *hsmp;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004203 struct sample_conv *conv;
Frédéric Lécaillef874a832018-06-15 13:56:04 +02004204 struct arg args[ARGM_NBARGS + 1] = {{0}};
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004205 int i;
4206 struct sample smp;
4207
4208 /* Get closure arguments. */
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004209 conv = lua_touserdata(L, lua_upvalueindex(1));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004210
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004211 /* Get traditional arguments. */
Willy Tarreauda5f1082015-04-06 11:17:13 +02004212 hsmp = MAY_LJMP(hlua_checkconverters(L, 1));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004213
4214 /* Get extra arguments. */
4215 for (i = 0; i < lua_gettop(L) - 2; i++) {
4216 if (i >= ARGM_NBARGS)
4217 break;
4218 hlua_lua2arg(L, i + 3, &args[i]);
4219 }
4220 args[i].type = ARGT_STOP;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004221 args[i].data.str.area = NULL;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004222
4223 /* Check arguments. */
Willy Tarreauda5f1082015-04-06 11:17:13 +02004224 MAY_LJMP(hlua_lua2arg_check(L, 3, args, conv->arg_mask, hsmp->p));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004225
4226 /* Run the special args checker. */
4227 if (conv->val_args && !conv->val_args(args, conv, "", 0, NULL)) {
4228 hlua_pusherror(L, "error in arguments");
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004229 goto error;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004230 }
4231
4232 /* Initialise the sample. */
Amaury Denoyellebc0af6a2020-10-29 17:21:20 +01004233 memset(&smp, 0, sizeof(smp));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004234 if (!hlua_lua2smp(L, 2, &smp)) {
4235 hlua_pusherror(L, "error in the input argument");
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004236 goto error;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004237 }
4238
Willy Tarreau1777ea62016-03-10 16:15:46 +01004239 smp_set_owner(&smp, hsmp->p, hsmp->s->sess, hsmp->s, hsmp->dir & SMP_OPT_DIR);
4240
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004241 /* Apply expected cast. */
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02004242 if (!sample_casts[smp.data.type][conv->in_type]) {
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004243 hlua_pusherror(L, "invalid input argument: cannot cast '%s' to '%s'",
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02004244 smp_to_type[smp.data.type], smp_to_type[conv->in_type]);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004245 goto error;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004246 }
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02004247 if (sample_casts[smp.data.type][conv->in_type] != c_none &&
4248 !sample_casts[smp.data.type][conv->in_type](&smp)) {
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004249 hlua_pusherror(L, "error during the input argument casting");
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004250 goto error;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004251 }
4252
4253 /* Run the sample conversion process. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02004254 if (!conv->process(args, &smp, conv->private)) {
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004255 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004256 lua_pushstring(L, "");
4257 else
Willy Tarreaua678b432015-08-28 10:14:59 +02004258 lua_pushnil(L);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004259 goto end;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004260 }
4261
4262 /* Convert the returned sample in lua value. */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004263 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004264 hlua_smp2lua_str(L, &smp);
4265 else
4266 hlua_smp2lua(L, &smp);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004267 end:
Willy Tarreauee0d7272021-07-16 10:26:56 +02004268 free_args(args);
Willy Tarreaua678b432015-08-28 10:14:59 +02004269 return 1;
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004270
4271 error:
Willy Tarreauee0d7272021-07-16 10:26:56 +02004272 free_args(args);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004273 WILL_LJMP(lua_error(L));
4274 return 0; /* Never reached */
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004275}
4276
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004277/*
4278 *
4279 *
4280 * Class AppletTCP
4281 *
4282 *
4283 */
4284
4285/* Returns a struct hlua_txn if the stack entry "ud" is
4286 * a class stream, otherwise it throws an error.
4287 */
4288__LJMP static struct hlua_appctx *hlua_checkapplet_tcp(lua_State *L, int ud)
4289{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004290 return MAY_LJMP(hlua_checkudata(L, ud, class_applet_tcp_ref));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004291}
4292
4293/* This function creates and push in the stack an Applet object
4294 * according with a current TXN.
4295 */
4296static int hlua_applet_tcp_new(lua_State *L, struct appctx *ctx)
4297{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004298 struct hlua_appctx *luactx;
Willy Tarreau0698c802022-05-11 14:09:57 +02004299 struct stream *s = appctx_strm(ctx);
Christopher Faulet2da02ae2022-02-24 13:45:27 +01004300 struct proxy *p;
4301
4302 ALREADY_CHECKED(s);
4303 p = s->be;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004304
4305 /* Check stack size. */
4306 if (!lua_checkstack(L, 3))
4307 return 0;
4308
4309 /* Create the object: obj[0] = userdata.
4310 * Note that the base of the Converters object is the
4311 * same than the TXN object.
4312 */
4313 lua_newtable(L);
Willy Tarreau7e702d12021-04-28 17:59:21 +02004314 luactx = lua_newuserdata(L, sizeof(*luactx));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004315 lua_rawseti(L, -2, 0);
Willy Tarreau7e702d12021-04-28 17:59:21 +02004316 luactx->appctx = ctx;
4317 luactx->htxn.s = s;
4318 luactx->htxn.p = p;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004319
4320 /* Create the "f" field that contains a list of fetches. */
4321 lua_pushstring(L, "f");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004322 if (!hlua_fetches_new(L, &luactx->htxn, 0))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004323 return 0;
4324 lua_settable(L, -3);
4325
4326 /* Create the "sf" field that contains a list of stringsafe fetches. */
4327 lua_pushstring(L, "sf");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004328 if (!hlua_fetches_new(L, &luactx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004329 return 0;
4330 lua_settable(L, -3);
4331
4332 /* Create the "c" field that contains a list of converters. */
4333 lua_pushstring(L, "c");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004334 if (!hlua_converters_new(L, &luactx->htxn, 0))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004335 return 0;
4336 lua_settable(L, -3);
4337
4338 /* Create the "sc" field that contains a list of stringsafe converters. */
4339 lua_pushstring(L, "sc");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004340 if (!hlua_converters_new(L, &luactx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004341 return 0;
4342 lua_settable(L, -3);
4343
4344 /* Pop a class stream metatable and affect it to the table. */
4345 lua_rawgeti(L, LUA_REGISTRYINDEX, class_applet_tcp_ref);
4346 lua_setmetatable(L, -2);
4347
4348 return 1;
4349}
4350
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004351__LJMP static int hlua_applet_tcp_set_var(lua_State *L)
4352{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004353 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004354 struct stream *s;
4355 const char *name;
4356 size_t len;
4357 struct sample smp;
4358
Tim Duesterhus4e172c92020-05-19 13:49:42 +02004359 if (lua_gettop(L) < 3 || lua_gettop(L) > 4)
4360 WILL_LJMP(luaL_error(L, "'set_var' needs between 3 and 4 arguments"));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004361
4362 /* It is useles to retrieve the stream, but this function
4363 * runs only in a stream context.
4364 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004365 luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004366 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02004367 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004368
4369 /* Converts the third argument in a sample. */
Amaury Denoyellebc0af6a2020-10-29 17:21:20 +01004370 memset(&smp, 0, sizeof(smp));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004371 hlua_lua2smp(L, 3, &smp);
4372
4373 /* Store the sample in a variable. */
4374 smp_set_owner(&smp, s->be, s->sess, s, 0);
Tim Duesterhus4e172c92020-05-19 13:49:42 +02004375
4376 if (lua_gettop(L) == 4 && lua_toboolean(L, 4))
4377 lua_pushboolean(L, vars_set_by_name_ifexist(name, len, &smp) != 0);
4378 else
4379 lua_pushboolean(L, vars_set_by_name(name, len, &smp) != 0);
4380
Tim Duesterhus84ebc132020-05-19 13:49:41 +02004381 return 1;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004382}
4383
4384__LJMP static int hlua_applet_tcp_unset_var(lua_State *L)
4385{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004386 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004387 struct stream *s;
4388 const char *name;
4389 size_t len;
4390 struct sample smp;
4391
4392 MAY_LJMP(check_args(L, 2, "unset_var"));
4393
4394 /* It is useles to retrieve the stream, but this function
4395 * runs only in a stream context.
4396 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004397 luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004398 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02004399 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004400
4401 /* Unset the variable. */
4402 smp_set_owner(&smp, s->be, s->sess, s, 0);
Tim Duesterhus84ebc132020-05-19 13:49:41 +02004403 lua_pushboolean(L, vars_unset_by_name_ifexist(name, len, &smp) != 0);
4404 return 1;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004405}
4406
4407__LJMP static int hlua_applet_tcp_get_var(lua_State *L)
4408{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004409 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004410 struct stream *s;
4411 const char *name;
4412 size_t len;
4413 struct sample smp;
4414
4415 MAY_LJMP(check_args(L, 2, "get_var"));
4416
4417 /* It is useles to retrieve the stream, but this function
4418 * runs only in a stream context.
4419 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004420 luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004421 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02004422 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004423
4424 smp_set_owner(&smp, s->be, s->sess, s, 0);
Willy Tarreaue352b9d2021-09-03 11:52:38 +02004425 if (!vars_get_by_name(name, len, &smp, NULL)) {
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004426 lua_pushnil(L);
4427 return 1;
4428 }
4429
4430 return hlua_smp2lua(L, &smp);
4431}
4432
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004433__LJMP static int hlua_applet_tcp_set_priv(lua_State *L)
4434{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004435 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
4436 struct stream *s = luactx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01004437 struct hlua *hlua;
4438
4439 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01004440 if (!s->hlua)
4441 return 0;
4442 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004443
4444 MAY_LJMP(check_args(L, 2, "set_priv"));
4445
4446 /* Remove previous value. */
Thierry FOURNIERe068b602017-04-26 13:27:05 +02004447 luaL_unref(L, LUA_REGISTRYINDEX, hlua->Mref);
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004448
4449 /* Get and store new value. */
4450 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
4451 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
4452
4453 return 0;
4454}
4455
4456__LJMP static int hlua_applet_tcp_get_priv(lua_State *L)
4457{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004458 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
4459 struct stream *s = luactx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01004460 struct hlua *hlua;
4461
4462 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01004463 if (!s->hlua) {
4464 lua_pushnil(L);
4465 return 1;
4466 }
4467 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004468
4469 /* Push configuration index in the stack. */
4470 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
4471
4472 return 1;
4473}
4474
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004475/* If expected data not yet available, it returns a yield. This function
4476 * consumes the data in the buffer. It returns a string containing the
4477 * data. This string can be empty.
4478 */
4479__LJMP static int hlua_applet_tcp_getline_yield(lua_State *L, int status, lua_KContext ctx)
4480{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004481 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Willy Tarreau4596fe22022-05-17 19:07:51 +02004482 struct stconn *cs = appctx_cs(luactx->appctx);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004483 int ret;
Willy Tarreau206ba832018-06-14 15:27:31 +02004484 const char *blk1;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004485 size_t len1;
Willy Tarreau206ba832018-06-14 15:27:31 +02004486 const char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004487 size_t len2;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004488
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004489 /* Read the maximum amount of data available. */
Willy Tarreau40a9c322022-05-18 15:55:18 +02004490 ret = co_getline_nc(sc_oc(cs), &blk1, &len1, &blk2, &len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004491
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004492 /* Data not yet available. return yield. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004493 if (ret == 0) {
Willy Tarreau90e8b452022-05-25 18:21:43 +02004494 applet_need_more_data(luactx->appctx);
Willy Tarreau9635e032018-10-16 17:52:55 +02004495 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_getline_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004496 }
4497
4498 /* End of data: commit the total strings and return. */
4499 if (ret < 0) {
Willy Tarreau7e702d12021-04-28 17:59:21 +02004500 luaL_pushresult(&luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004501 return 1;
4502 }
4503
4504 /* Ensure that the block 2 length is usable. */
4505 if (ret == 1)
4506 len2 = 0;
4507
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -07004508 /* don't check the max length read and don't check. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004509 luaL_addlstring(&luactx->b, blk1, len1);
4510 luaL_addlstring(&luactx->b, blk2, len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004511
4512 /* Consume input channel output buffer data. */
Willy Tarreau40a9c322022-05-18 15:55:18 +02004513 co_skip(sc_oc(cs), len1 + len2);
Willy Tarreau7e702d12021-04-28 17:59:21 +02004514 luaL_pushresult(&luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004515 return 1;
4516}
4517
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004518/* Check arguments for the function "hlua_channel_get_yield". */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004519__LJMP static int hlua_applet_tcp_getline(lua_State *L)
4520{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004521 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004522
4523 /* Initialise the string catenation. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004524 luaL_buffinit(L, &luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004525
4526 return MAY_LJMP(hlua_applet_tcp_getline_yield(L, 0, 0));
4527}
4528
4529/* If expected data not yet available, it returns a yield. This function
4530 * consumes the data in the buffer. It returns a string containing the
4531 * data. This string can be empty.
4532 */
4533__LJMP static int hlua_applet_tcp_recv_yield(lua_State *L, int status, lua_KContext ctx)
4534{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004535 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Willy Tarreau4596fe22022-05-17 19:07:51 +02004536 struct stconn *cs = appctx_cs(luactx->appctx);
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004537 size_t len = MAY_LJMP(luaL_checkinteger(L, 2));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004538 int ret;
Willy Tarreau206ba832018-06-14 15:27:31 +02004539 const char *blk1;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004540 size_t len1;
Willy Tarreau206ba832018-06-14 15:27:31 +02004541 const char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004542 size_t len2;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004543
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004544 /* Read the maximum amount of data available. */
Willy Tarreau40a9c322022-05-18 15:55:18 +02004545 ret = co_getblk_nc(sc_oc(cs), &blk1, &len1, &blk2, &len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004546
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004547 /* Data not yet available. return yield. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004548 if (ret == 0) {
Willy Tarreau90e8b452022-05-25 18:21:43 +02004549 applet_need_more_data(luactx->appctx);
Willy Tarreau9635e032018-10-16 17:52:55 +02004550 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004551 }
4552
4553 /* End of data: commit the total strings and return. */
4554 if (ret < 0) {
Willy Tarreau7e702d12021-04-28 17:59:21 +02004555 luaL_pushresult(&luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004556 return 1;
4557 }
4558
4559 /* Ensure that the block 2 length is usable. */
4560 if (ret == 1)
4561 len2 = 0;
4562
4563 if (len == -1) {
4564
4565 /* If len == -1, catenate all the data avalaile and
4566 * yield because we want to get all the data until
4567 * the end of data stream.
4568 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004569 luaL_addlstring(&luactx->b, blk1, len1);
4570 luaL_addlstring(&luactx->b, blk2, len2);
Willy Tarreau40a9c322022-05-18 15:55:18 +02004571 co_skip(sc_oc(cs), len1 + len2);
Willy Tarreau90e8b452022-05-25 18:21:43 +02004572 applet_need_more_data(luactx->appctx);
Willy Tarreau9635e032018-10-16 17:52:55 +02004573 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004574
4575 } else {
4576
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05004577 /* Copy the first block caping to the length required. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004578 if (len1 > len)
4579 len1 = len;
Willy Tarreau7e702d12021-04-28 17:59:21 +02004580 luaL_addlstring(&luactx->b, blk1, len1);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004581 len -= len1;
4582
4583 /* Copy the second block. */
4584 if (len2 > len)
4585 len2 = len;
Willy Tarreau7e702d12021-04-28 17:59:21 +02004586 luaL_addlstring(&luactx->b, blk2, len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004587 len -= len2;
4588
4589 /* Consume input channel output buffer data. */
Willy Tarreau40a9c322022-05-18 15:55:18 +02004590 co_skip(sc_oc(cs), len1 + len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004591
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004592 /* If there is no other data available, yield waiting for new data. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004593 if (len > 0) {
4594 lua_pushinteger(L, len);
4595 lua_replace(L, 2);
Willy Tarreau90e8b452022-05-25 18:21:43 +02004596 applet_need_more_data(luactx->appctx);
Willy Tarreau9635e032018-10-16 17:52:55 +02004597 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004598 }
4599
4600 /* return the result. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004601 luaL_pushresult(&luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004602 return 1;
4603 }
4604
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004605 /* we never execute this */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004606 hlua_pusherror(L, "Lua: internal error");
4607 WILL_LJMP(lua_error(L));
4608 return 0;
4609}
4610
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004611/* Check arguments for the function "hlua_channel_get_yield". */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004612__LJMP static int hlua_applet_tcp_recv(lua_State *L)
4613{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004614 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004615 int len = -1;
4616
4617 if (lua_gettop(L) > 2)
4618 WILL_LJMP(luaL_error(L, "The 'recv' function requires between 1 and 2 arguments."));
4619 if (lua_gettop(L) >= 2) {
4620 len = MAY_LJMP(luaL_checkinteger(L, 2));
4621 lua_pop(L, 1);
4622 }
4623
4624 /* Confirm or set the required length */
4625 lua_pushinteger(L, len);
4626
4627 /* Initialise the string catenation. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004628 luaL_buffinit(L, &luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004629
4630 return MAY_LJMP(hlua_applet_tcp_recv_yield(L, 0, 0));
4631}
4632
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004633/* Append data in the output side of the buffer. This data is immediately
4634 * sent. The function returns the amount of data written. If the buffer
4635 * cannot contain the data, the function yields. The function returns -1
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004636 * if the channel is closed.
4637 */
4638__LJMP static int hlua_applet_tcp_send_yield(lua_State *L, int status, lua_KContext ctx)
4639{
4640 size_t len;
Willy Tarreau7e702d12021-04-28 17:59:21 +02004641 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004642 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
4643 int l = MAY_LJMP(luaL_checkinteger(L, 3));
Willy Tarreau4596fe22022-05-17 19:07:51 +02004644 struct stconn *cs = appctx_cs(luactx->appctx);
Willy Tarreau40a9c322022-05-18 15:55:18 +02004645 struct channel *chn = sc_ic(cs);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004646 int max;
4647
4648 /* Get the max amount of data which can write as input in the channel. */
4649 max = channel_recv_max(chn);
4650 if (max > (len - l))
4651 max = len - l;
4652
4653 /* Copy data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02004654 ci_putblk(chn, str + l, max);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004655
4656 /* update counters. */
4657 l += max;
4658 lua_pop(L, 1);
4659 lua_pushinteger(L, l);
4660
4661 /* If some data is not send, declares the situation to the
4662 * applet, and returns a yield.
4663 */
4664 if (l < len) {
Willy Tarreau99615ed2022-05-25 07:29:36 +02004665 sc_need_room(cs);
Willy Tarreau9635e032018-10-16 17:52:55 +02004666 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004667 }
4668
4669 return 1;
4670}
4671
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05004672/* Just a wrapper of "hlua_applet_tcp_send_yield". This wrapper permits
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004673 * yield the LUA process, and resume it without checking the
4674 * input arguments.
4675 */
4676__LJMP static int hlua_applet_tcp_send(lua_State *L)
4677{
4678 MAY_LJMP(check_args(L, 2, "send"));
4679 lua_pushinteger(L, 0);
4680
4681 return MAY_LJMP(hlua_applet_tcp_send_yield(L, 0, 0));
4682}
4683
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004684/*
4685 *
4686 *
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004687 * Class AppletHTTP
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004688 *
4689 *
4690 */
4691
4692/* Returns a struct hlua_txn if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02004693 * a class stream, otherwise it throws an error.
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004694 */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004695__LJMP static struct hlua_appctx *hlua_checkapplet_http(lua_State *L, int ud)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004696{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004697 return MAY_LJMP(hlua_checkudata(L, ud, class_applet_http_ref));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004698}
4699
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004700/* This function creates and push in the stack an Applet object
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004701 * according with a current TXN.
Willy Tarreauaa229cc2022-05-06 14:26:10 +02004702 * It relies on the caller to have already reserved the room in ctx->svcctx
4703 * for the local storage of hlua_http_ctx.
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004704 */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004705static int hlua_applet_http_new(lua_State *L, struct appctx *ctx)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004706{
Willy Tarreauaa229cc2022-05-06 14:26:10 +02004707 struct hlua_http_ctx *http_ctx = ctx->svcctx;
Willy Tarreau7e702d12021-04-28 17:59:21 +02004708 struct hlua_appctx *luactx;
Thierry FOURNIER841475e2015-12-11 17:10:09 +01004709 struct hlua_txn htxn;
Willy Tarreau0698c802022-05-11 14:09:57 +02004710 struct stream *s = appctx_strm(ctx);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004711 struct proxy *px = s->be;
Christopher Fauleta2097962019-07-15 16:25:33 +02004712 struct htx *htx;
4713 struct htx_blk *blk;
4714 struct htx_sl *sl;
4715 struct ist path;
4716 unsigned long long len = 0;
4717 int32_t pos;
Amaury Denoyellec453f952021-07-06 11:40:12 +02004718 struct http_uri_parser parser;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004719
4720 /* Check stack size. */
4721 if (!lua_checkstack(L, 3))
4722 return 0;
4723
4724 /* Create the object: obj[0] = userdata.
4725 * Note that the base of the Converters object is the
4726 * same than the TXN object.
4727 */
4728 lua_newtable(L);
Willy Tarreau7e702d12021-04-28 17:59:21 +02004729 luactx = lua_newuserdata(L, sizeof(*luactx));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004730 lua_rawseti(L, -2, 0);
Willy Tarreau7e702d12021-04-28 17:59:21 +02004731 luactx->appctx = ctx;
Willy Tarreauaa229cc2022-05-06 14:26:10 +02004732 http_ctx->status = 200; /* Default status code returned. */
4733 http_ctx->reason = NULL; /* Use default reason based on status */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004734 luactx->htxn.s = s;
4735 luactx->htxn.p = px;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004736
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004737 /* Create the "f" field that contains a list of fetches. */
4738 lua_pushstring(L, "f");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004739 if (!hlua_fetches_new(L, &luactx->htxn, 0))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004740 return 0;
4741 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004742
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004743 /* Create the "sf" field that contains a list of stringsafe fetches. */
4744 lua_pushstring(L, "sf");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004745 if (!hlua_fetches_new(L, &luactx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004746 return 0;
4747 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004748
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004749 /* Create the "c" field that contains a list of converters. */
4750 lua_pushstring(L, "c");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004751 if (!hlua_converters_new(L, &luactx->htxn, 0))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004752 return 0;
4753 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004754
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004755 /* Create the "sc" field that contains a list of stringsafe converters. */
4756 lua_pushstring(L, "sc");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004757 if (!hlua_converters_new(L, &luactx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004758 return 0;
4759 lua_settable(L, -3);
Willy Tarreaueee5b512015-04-03 23:46:31 +02004760
Christopher Fauleta2097962019-07-15 16:25:33 +02004761 htx = htxbuf(&s->req.buf);
4762 blk = htx_get_first_blk(htx);
Christopher Fauletea009732019-11-18 15:50:25 +01004763 BUG_ON(!blk || htx_get_blk_type(blk) != HTX_BLK_REQ_SL);
Christopher Fauleta2097962019-07-15 16:25:33 +02004764 sl = htx_get_blk_ptr(htx, blk);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004765
Christopher Fauleta2097962019-07-15 16:25:33 +02004766 /* Stores the request method. */
4767 lua_pushstring(L, "method");
4768 lua_pushlstring(L, HTX_SL_REQ_MPTR(sl), HTX_SL_REQ_MLEN(sl));
4769 lua_settable(L, -3);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004770
Christopher Fauleta2097962019-07-15 16:25:33 +02004771 /* Stores the http version. */
4772 lua_pushstring(L, "version");
4773 lua_pushlstring(L, HTX_SL_REQ_VPTR(sl), HTX_SL_REQ_VLEN(sl));
4774 lua_settable(L, -3);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004775
Christopher Fauleta2097962019-07-15 16:25:33 +02004776 /* creates an array of headers. hlua_http_get_headers() crates and push
4777 * the array on the top of the stack.
4778 */
4779 lua_pushstring(L, "headers");
4780 htxn.s = s;
4781 htxn.p = px;
4782 htxn.dir = SMP_OPT_DIR_REQ;
Christopher Faulet9d1332b2020-02-24 16:46:16 +01004783 if (!hlua_http_get_headers(L, &htxn.s->txn->req))
Christopher Fauleta2097962019-07-15 16:25:33 +02004784 return 0;
4785 lua_settable(L, -3);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004786
Amaury Denoyellec453f952021-07-06 11:40:12 +02004787 parser = http_uri_parser_init(htx_sl_req_uri(sl));
4788 path = http_parse_path(&parser);
Tim Duesterhused526372020-03-05 17:56:33 +01004789 if (isttest(path)) {
Christopher Fauleta2097962019-07-15 16:25:33 +02004790 char *p, *q, *end;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004791
Christopher Fauleta2097962019-07-15 16:25:33 +02004792 p = path.ptr;
Tim Duesterhus4c8f75f2021-11-06 15:14:44 +01004793 end = istend(path);
Christopher Fauleta2097962019-07-15 16:25:33 +02004794 q = p;
4795 while (q < end && *q != '?')
4796 q++;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004797
Thierry FOURNIER7d388632017-02-22 02:06:16 +01004798 /* Stores the request path. */
Christopher Fauleta2097962019-07-15 16:25:33 +02004799 lua_pushstring(L, "path");
4800 lua_pushlstring(L, p, q - p);
Thierry FOURNIER7d388632017-02-22 02:06:16 +01004801 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01004802
Christopher Fauleta2097962019-07-15 16:25:33 +02004803 /* Stores the query string. */
4804 lua_pushstring(L, "qs");
4805 if (*q == '?')
4806 q++;
4807 lua_pushlstring(L, q, end - q);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004808 lua_settable(L, -3);
Christopher Fauleta2097962019-07-15 16:25:33 +02004809 }
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004810
Christopher Fauleta2097962019-07-15 16:25:33 +02004811 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
4812 struct htx_blk *blk = htx_get_blk(htx, pos);
4813 enum htx_blk_type type = htx_get_blk_type(blk);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004814
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01004815 if (type == HTX_BLK_TLR || type == HTX_BLK_EOT)
Christopher Fauleta2097962019-07-15 16:25:33 +02004816 break;
4817 if (type == HTX_BLK_DATA)
4818 len += htx_get_blksz(blk);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004819 }
Christopher Fauleta2097962019-07-15 16:25:33 +02004820 if (htx->extra != ULLONG_MAX)
4821 len += htx->extra;
4822
4823 /* Stores the request path. */
4824 lua_pushstring(L, "length");
4825 lua_pushinteger(L, len);
4826 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01004827
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004828 /* Create an empty array of HTTP request headers. */
4829 lua_pushstring(L, "response");
4830 lua_newtable(L);
4831 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01004832
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004833 /* Pop a class stream metatable and affect it to the table. */
4834 lua_rawgeti(L, LUA_REGISTRYINDEX, class_applet_http_ref);
4835 lua_setmetatable(L, -2);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004836
4837 return 1;
4838}
4839
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004840__LJMP static int hlua_applet_http_set_var(lua_State *L)
4841{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004842 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004843 struct stream *s;
4844 const char *name;
4845 size_t len;
4846 struct sample smp;
4847
Tim Duesterhus4e172c92020-05-19 13:49:42 +02004848 if (lua_gettop(L) < 3 || lua_gettop(L) > 4)
4849 WILL_LJMP(luaL_error(L, "'set_var' needs between 3 and 4 arguments"));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004850
4851 /* It is useles to retrieve the stream, but this function
4852 * runs only in a stream context.
4853 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004854 luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004855 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02004856 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004857
4858 /* Converts the third argument in a sample. */
Amaury Denoyellebc0af6a2020-10-29 17:21:20 +01004859 memset(&smp, 0, sizeof(smp));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004860 hlua_lua2smp(L, 3, &smp);
4861
4862 /* Store the sample in a variable. */
4863 smp_set_owner(&smp, s->be, s->sess, s, 0);
Tim Duesterhus4e172c92020-05-19 13:49:42 +02004864
4865 if (lua_gettop(L) == 4 && lua_toboolean(L, 4))
4866 lua_pushboolean(L, vars_set_by_name_ifexist(name, len, &smp) != 0);
4867 else
4868 lua_pushboolean(L, vars_set_by_name(name, len, &smp) != 0);
4869
Tim Duesterhus84ebc132020-05-19 13:49:41 +02004870 return 1;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004871}
4872
4873__LJMP static int hlua_applet_http_unset_var(lua_State *L)
4874{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004875 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004876 struct stream *s;
4877 const char *name;
4878 size_t len;
4879 struct sample smp;
4880
4881 MAY_LJMP(check_args(L, 2, "unset_var"));
4882
4883 /* It is useles to retrieve the stream, but this function
4884 * runs only in a stream context.
4885 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004886 luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004887 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02004888 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004889
4890 /* Unset the variable. */
4891 smp_set_owner(&smp, s->be, s->sess, s, 0);
Tim Duesterhus84ebc132020-05-19 13:49:41 +02004892 lua_pushboolean(L, vars_unset_by_name_ifexist(name, len, &smp) != 0);
4893 return 1;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004894}
4895
4896__LJMP static int hlua_applet_http_get_var(lua_State *L)
4897{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004898 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004899 struct stream *s;
4900 const char *name;
4901 size_t len;
4902 struct sample smp;
4903
4904 MAY_LJMP(check_args(L, 2, "get_var"));
4905
4906 /* It is useles to retrieve the stream, but this function
4907 * runs only in a stream context.
4908 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004909 luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004910 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02004911 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004912
4913 smp_set_owner(&smp, s->be, s->sess, s, 0);
Willy Tarreaue352b9d2021-09-03 11:52:38 +02004914 if (!vars_get_by_name(name, len, &smp, NULL)) {
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004915 lua_pushnil(L);
4916 return 1;
4917 }
4918
4919 return hlua_smp2lua(L, &smp);
4920}
4921
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004922__LJMP static int hlua_applet_http_set_priv(lua_State *L)
4923{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004924 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4925 struct stream *s = luactx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01004926 struct hlua *hlua;
4927
4928 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01004929 if (!s->hlua)
4930 return 0;
4931 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004932
4933 MAY_LJMP(check_args(L, 2, "set_priv"));
4934
4935 /* Remove previous value. */
Thierry FOURNIERe068b602017-04-26 13:27:05 +02004936 luaL_unref(L, LUA_REGISTRYINDEX, hlua->Mref);
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004937
4938 /* Get and store new value. */
4939 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
4940 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
4941
4942 return 0;
4943}
4944
4945__LJMP static int hlua_applet_http_get_priv(lua_State *L)
4946{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004947 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4948 struct stream *s = luactx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01004949 struct hlua *hlua;
4950
4951 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01004952 if (!s->hlua) {
4953 lua_pushnil(L);
4954 return 1;
4955 }
4956 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004957
4958 /* Push configuration index in the stack. */
4959 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
4960
4961 return 1;
4962}
4963
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004964/* If expected data not yet available, it returns a yield. This function
4965 * consumes the data in the buffer. It returns a string containing the
4966 * data. This string can be empty.
4967 */
Christopher Fauleta2097962019-07-15 16:25:33 +02004968__LJMP static int hlua_applet_http_getline_yield(lua_State *L, int status, lua_KContext ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004969{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004970 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Willy Tarreau4596fe22022-05-17 19:07:51 +02004971 struct stconn *cs = appctx_cs(luactx->appctx);
Willy Tarreau40a9c322022-05-18 15:55:18 +02004972 struct channel *req = sc_oc(cs);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004973 struct htx *htx;
4974 struct htx_blk *blk;
4975 size_t count;
4976 int stop = 0;
4977
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004978 htx = htx_from_buf(&req->buf);
4979 count = co_data(req);
Christopher Fauleta3f15502019-05-13 15:27:23 +02004980 blk = htx_get_first_blk(htx);
Christopher Fauletcc26b132018-12-18 21:20:57 +01004981
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004982 while (count && !stop && blk) {
4983 enum htx_blk_type type = htx_get_blk_type(blk);
4984 uint32_t sz = htx_get_blksz(blk);
4985 struct ist v;
4986 uint32_t vlen;
4987 char *nl;
4988
4989 vlen = sz;
4990 if (vlen > count) {
4991 if (type != HTX_BLK_DATA)
4992 break;
4993 vlen = count;
4994 }
4995
4996 switch (type) {
4997 case HTX_BLK_UNUSED:
4998 break;
4999
5000 case HTX_BLK_DATA:
5001 v = htx_get_blk_value(htx, blk);
5002 v.len = vlen;
5003 nl = istchr(v, '\n');
5004 if (nl != NULL) {
5005 stop = 1;
5006 vlen = nl - v.ptr + 1;
5007 }
Willy Tarreau7e702d12021-04-28 17:59:21 +02005008 luaL_addlstring(&luactx->b, v.ptr, vlen);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005009 break;
5010
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005011 case HTX_BLK_TLR:
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01005012 case HTX_BLK_EOT:
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005013 stop = 1;
5014 break;
5015
5016 default:
5017 break;
5018 }
5019
Willy Tarreau84240042022-02-28 16:51:23 +01005020 c_rew(req, vlen);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005021 count -= vlen;
5022 if (sz == vlen)
5023 blk = htx_remove_blk(htx, blk);
5024 else {
5025 htx_cut_data_blk(htx, blk, vlen);
5026 break;
5027 }
5028 }
5029
Christopher Fauleteccb31c2021-04-02 14:24:56 +02005030 /* The message was fully consumed and no more data are expected
5031 * (EOM flag set).
5032 */
5033 if (htx_is_empty(htx) && (htx->flags & HTX_FL_EOM))
5034 stop = 1;
5035
Christopher Faulet0ae79d02019-02-27 21:36:59 +01005036 htx_to_buf(htx, &req->buf);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005037 if (!stop) {
Willy Tarreau90e8b452022-05-25 18:21:43 +02005038 applet_need_more_data(luactx->appctx);
Christopher Fauleta2097962019-07-15 16:25:33 +02005039 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_getline_yield, TICK_ETERNITY, 0));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005040 }
5041
5042 /* return the result. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005043 luaL_pushresult(&luactx->b);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005044 return 1;
5045}
5046
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005047
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08005048/* Check arguments for the function "hlua_channel_get_yield". */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005049__LJMP static int hlua_applet_http_getline(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005050{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005051 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005052
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005053 /* Initialise the string catenation. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005054 luaL_buffinit(L, &luactx->b);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005055
Christopher Fauleta2097962019-07-15 16:25:33 +02005056 return MAY_LJMP(hlua_applet_http_getline_yield(L, 0, 0));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005057}
5058
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005059/* If expected data not yet available, it returns a yield. This function
5060 * consumes the data in the buffer. It returns a string containing the
5061 * data. This string can be empty.
5062 */
Christopher Fauleta2097962019-07-15 16:25:33 +02005063__LJMP static int hlua_applet_http_recv_yield(lua_State *L, int status, lua_KContext ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005064{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005065 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Willy Tarreau4596fe22022-05-17 19:07:51 +02005066 struct stconn *cs = appctx_cs(luactx->appctx);
Willy Tarreau40a9c322022-05-18 15:55:18 +02005067 struct channel *req = sc_oc(cs);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005068 struct htx *htx;
5069 struct htx_blk *blk;
5070 size_t count;
5071 int len;
5072
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005073 htx = htx_from_buf(&req->buf);
5074 len = MAY_LJMP(luaL_checkinteger(L, 2));
5075 count = co_data(req);
Christopher Faulet29f17582019-05-23 11:03:26 +02005076 blk = htx_get_head_blk(htx);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005077 while (count && len && blk) {
5078 enum htx_blk_type type = htx_get_blk_type(blk);
5079 uint32_t sz = htx_get_blksz(blk);
5080 struct ist v;
5081 uint32_t vlen;
5082
5083 vlen = sz;
5084 if (len > 0 && vlen > len)
5085 vlen = len;
5086 if (vlen > count) {
5087 if (type != HTX_BLK_DATA)
5088 break;
5089 vlen = count;
5090 }
5091
5092 switch (type) {
5093 case HTX_BLK_UNUSED:
5094 break;
5095
5096 case HTX_BLK_DATA:
5097 v = htx_get_blk_value(htx, blk);
Willy Tarreau7e702d12021-04-28 17:59:21 +02005098 luaL_addlstring(&luactx->b, v.ptr, vlen);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005099 break;
5100
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005101 case HTX_BLK_TLR:
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01005102 case HTX_BLK_EOT:
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005103 len = 0;
5104 break;
5105
5106 default:
5107 break;
5108 }
5109
Willy Tarreau84240042022-02-28 16:51:23 +01005110 c_rew(req, vlen);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005111 count -= vlen;
5112 if (len > 0)
5113 len -= vlen;
5114 if (sz == vlen)
5115 blk = htx_remove_blk(htx, blk);
5116 else {
5117 htx_cut_data_blk(htx, blk, vlen);
5118 break;
5119 }
5120 }
5121
Christopher Fauleteccb31c2021-04-02 14:24:56 +02005122 /* The message was fully consumed and no more data are expected
5123 * (EOM flag set).
5124 */
5125 if (htx_is_empty(htx) && (htx->flags & HTX_FL_EOM))
5126 len = 0;
5127
Christopher Faulet0ae79d02019-02-27 21:36:59 +01005128 htx_to_buf(htx, &req->buf);
5129
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005130 /* If we are no other data available, yield waiting for new data. */
5131 if (len) {
5132 if (len > 0) {
5133 lua_pushinteger(L, len);
5134 lua_replace(L, 2);
5135 }
Willy Tarreau90e8b452022-05-25 18:21:43 +02005136 applet_need_more_data(luactx->appctx);
Willy Tarreau9635e032018-10-16 17:52:55 +02005137 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005138 }
5139
5140 /* return the result. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005141 luaL_pushresult(&luactx->b);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005142 return 1;
5143}
5144
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08005145/* Check arguments for the function "hlua_channel_get_yield". */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005146__LJMP static int hlua_applet_http_recv(lua_State *L)
5147{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005148 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005149 int len = -1;
5150
5151 /* Check arguments. */
5152 if (lua_gettop(L) > 2)
5153 WILL_LJMP(luaL_error(L, "The 'recv' function requires between 1 and 2 arguments."));
5154 if (lua_gettop(L) >= 2) {
5155 len = MAY_LJMP(luaL_checkinteger(L, 2));
5156 lua_pop(L, 1);
5157 }
5158
Christopher Fauleta2097962019-07-15 16:25:33 +02005159 lua_pushinteger(L, len);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005160
Christopher Fauleta2097962019-07-15 16:25:33 +02005161 /* Initialise the string catenation. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005162 luaL_buffinit(L, &luactx->b);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005163
Christopher Fauleta2097962019-07-15 16:25:33 +02005164 return MAY_LJMP(hlua_applet_http_recv_yield(L, 0, 0));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005165}
5166
5167/* Append data in the output side of the buffer. This data is immediately
5168 * sent. The function returns the amount of data written. If the buffer
5169 * cannot contain the data, the function yields. The function returns -1
5170 * if the channel is closed.
5171 */
Christopher Fauleta2097962019-07-15 16:25:33 +02005172__LJMP static int hlua_applet_http_send_yield(lua_State *L, int status, lua_KContext ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005173{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005174 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Willy Tarreau4596fe22022-05-17 19:07:51 +02005175 struct stconn *cs = appctx_cs(luactx->appctx);
Willy Tarreau40a9c322022-05-18 15:55:18 +02005176 struct channel *res = sc_ic(cs);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005177 struct htx *htx = htx_from_buf(&res->buf);
5178 const char *data;
5179 size_t len;
5180 int l = MAY_LJMP(luaL_checkinteger(L, 3));
5181 int max;
5182
Christopher Faulet9060fc02019-07-03 11:39:30 +02005183 max = htx_get_max_blksz(htx, channel_htx_recv_max(res, htx));
Christopher Faulet4b0e9b22019-01-09 12:16:58 +01005184 if (!max)
5185 goto snd_yield;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005186
5187 data = MAY_LJMP(luaL_checklstring(L, 2, &len));
5188
5189 /* Get the max amount of data which can write as input in the channel. */
5190 if (max > (len - l))
5191 max = len - l;
5192
5193 /* Copy data. */
Willy Tarreau0a7ef022019-05-28 10:30:11 +02005194 max = htx_add_data(htx, ist2(data + l, max));
Christopher Fauletf6cce3f2019-02-27 21:20:09 +01005195 channel_add_input(res, max);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005196
5197 /* update counters. */
5198 l += max;
5199 lua_pop(L, 1);
5200 lua_pushinteger(L, l);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005201
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005202 /* If some data is not send, declares the situation to the
5203 * applet, and returns a yield.
5204 */
5205 if (l < len) {
Christopher Faulet4b0e9b22019-01-09 12:16:58 +01005206 snd_yield:
Christopher Faulet0ae79d02019-02-27 21:36:59 +01005207 htx_to_buf(htx, &res->buf);
Willy Tarreau99615ed2022-05-25 07:29:36 +02005208 sc_need_room(cs);
Willy Tarreau9635e032018-10-16 17:52:55 +02005209 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005210 }
5211
Christopher Fauleta2097962019-07-15 16:25:33 +02005212 htx_to_buf(htx, &res->buf);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005213 return 1;
5214}
5215
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05005216/* Just a wrapper of "hlua_applet_send_yield". This wrapper permits
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005217 * yield the LUA process, and resume it without checking the
5218 * input arguments.
5219 */
5220__LJMP static int hlua_applet_http_send(lua_State *L)
5221{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005222 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005223 struct hlua_http_ctx *http_ctx = luactx->appctx->svcctx;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005224
5225 /* We want to send some data. Headers must be sent. */
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005226 if (!(http_ctx->flags & APPLET_HDR_SENT)) {
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005227 hlua_pusherror(L, "Lua: 'send' you must call start_response() before sending data.");
5228 WILL_LJMP(lua_error(L));
5229 }
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005230
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05005231 /* This integer is used for followinf the amount of data sent. */
Christopher Fauleta2097962019-07-15 16:25:33 +02005232 lua_pushinteger(L, 0);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005233
Christopher Fauleta2097962019-07-15 16:25:33 +02005234 return MAY_LJMP(hlua_applet_http_send_yield(L, 0, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005235}
5236
5237__LJMP static int hlua_applet_http_addheader(lua_State *L)
5238{
5239 const char *name;
5240 int ret;
5241
5242 MAY_LJMP(hlua_checkapplet_http(L, 1));
5243 name = MAY_LJMP(luaL_checkstring(L, 2));
5244 MAY_LJMP(luaL_checkstring(L, 3));
5245
5246 /* Push in the stack the "response" entry. */
5247 ret = lua_getfield(L, 1, "response");
5248 if (ret != LUA_TTABLE) {
5249 hlua_pusherror(L, "Lua: 'add_header' internal error: AppletHTTP['response'] "
5250 "is expected as an array. %s found", lua_typename(L, ret));
5251 WILL_LJMP(lua_error(L));
5252 }
5253
5254 /* check if the header is already registered if it is not
5255 * the case, register it.
5256 */
5257 ret = lua_getfield(L, -1, name);
5258 if (ret == LUA_TNIL) {
5259
5260 /* Entry not found. */
5261 lua_pop(L, 1); /* remove the nil. The "response" table is the top of the stack. */
5262
5263 /* Insert the new header name in the array in the top of the stack.
5264 * It left the new array in the top of the stack.
5265 */
5266 lua_newtable(L);
5267 lua_pushvalue(L, 2);
5268 lua_pushvalue(L, -2);
5269 lua_settable(L, -4);
5270
5271 } else if (ret != LUA_TTABLE) {
5272
5273 /* corruption error. */
5274 hlua_pusherror(L, "Lua: 'add_header' internal error: AppletHTTP['response']['%s'] "
5275 "is expected as an array. %s found", name, lua_typename(L, ret));
5276 WILL_LJMP(lua_error(L));
5277 }
5278
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -07005279 /* Now the top of thestack is an array of values. We push
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005280 * the header value as new entry.
5281 */
5282 lua_pushvalue(L, 3);
5283 ret = lua_rawlen(L, -2);
5284 lua_rawseti(L, -2, ret + 1);
5285 lua_pushboolean(L, 1);
5286 return 1;
5287}
5288
5289__LJMP static int hlua_applet_http_status(lua_State *L)
5290{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005291 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005292 int status = MAY_LJMP(luaL_checkinteger(L, 2));
Robin H. Johnson52f5db22017-01-01 13:10:52 -08005293 const char *reason = MAY_LJMP(luaL_optlstring(L, 3, NULL, NULL));
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005294 struct hlua_http_ctx *http_ctx = luactx->appctx->svcctx;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005295
5296 if (status < 100 || status > 599) {
5297 lua_pushboolean(L, 0);
5298 return 1;
5299 }
5300
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005301 http_ctx->status = status;
5302 http_ctx->reason = reason;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005303 lua_pushboolean(L, 1);
5304 return 1;
5305}
5306
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005307
Christopher Fauleta2097962019-07-15 16:25:33 +02005308__LJMP static int hlua_applet_http_send_response(lua_State *L)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005309{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005310 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005311 struct hlua_http_ctx *http_ctx = luactx->appctx->svcctx;
Willy Tarreau4596fe22022-05-17 19:07:51 +02005312 struct stconn *cs = appctx_cs(luactx->appctx);
Willy Tarreau40a9c322022-05-18 15:55:18 +02005313 struct channel *res = sc_ic(cs);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005314 struct htx *htx;
5315 struct htx_sl *sl;
5316 struct h1m h1m;
5317 const char *status, *reason;
5318 const char *name, *value;
5319 size_t nlen, vlen;
5320 unsigned int flags;
5321
5322 /* Send the message at once. */
5323 htx = htx_from_buf(&res->buf);
5324 h1m_init_res(&h1m);
5325
5326 /* Use the same http version than the request. */
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005327 status = ultoa_r(http_ctx->status, trash.area, trash.size);
5328 reason = http_ctx->reason;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005329 if (reason == NULL)
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005330 reason = http_get_reason(http_ctx->status);
5331 if (http_ctx->flags & APPLET_HTTP11) {
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005332 flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11);
5333 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.1"), ist(status), ist(reason));
5334 }
5335 else {
5336 flags = HTX_SL_F_IS_RESP;
5337 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.0"), ist(status), ist(reason));
5338 }
5339 if (!sl) {
5340 hlua_pusherror(L, "Lua applet http '%s': Failed to create response.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005341 luactx->appctx->rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005342 WILL_LJMP(lua_error(L));
5343 }
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005344 sl->info.res.status = http_ctx->status;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005345
5346 /* Get the array associated to the field "response" in the object AppletHTTP. */
5347 lua_pushvalue(L, 0);
5348 if (lua_getfield(L, 1, "response") != LUA_TTABLE) {
5349 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response'] missing.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005350 luactx->appctx->rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005351 WILL_LJMP(lua_error(L));
5352 }
5353
5354 /* Browse the list of headers. */
5355 lua_pushnil(L);
5356 while(lua_next(L, -2) != 0) {
5357 /* We expect a string as -2. */
5358 if (lua_type(L, -2) != LUA_TSTRING) {
5359 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response'][] element must be a string. got %s.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005360 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005361 lua_typename(L, lua_type(L, -2)));
5362 WILL_LJMP(lua_error(L));
5363 }
5364 name = lua_tolstring(L, -2, &nlen);
5365
5366 /* We expect an array as -1. */
5367 if (lua_type(L, -1) != LUA_TTABLE) {
5368 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 +02005369 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005370 name,
5371 lua_typename(L, lua_type(L, -1)));
5372 WILL_LJMP(lua_error(L));
5373 }
5374
5375 /* Browse the table who is on the top of the stack. */
5376 lua_pushnil(L);
5377 while(lua_next(L, -2) != 0) {
5378 int id;
5379
5380 /* We expect a number as -2. */
5381 if (lua_type(L, -2) != LUA_TNUMBER) {
5382 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 +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, -2)));
5386 WILL_LJMP(lua_error(L));
5387 }
5388 id = lua_tointeger(L, -2);
5389
5390 /* We expect a string as -2. */
5391 if (lua_type(L, -1) != LUA_TSTRING) {
5392 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 +02005393 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005394 name, id,
5395 lua_typename(L, lua_type(L, -1)));
5396 WILL_LJMP(lua_error(L));
5397 }
5398 value = lua_tolstring(L, -1, &vlen);
5399
5400 /* Simple Protocol checks. */
Christopher Faulet545fbba2021-09-28 09:36:25 +02005401 if (isteqi(ist2(name, nlen), ist("transfer-encoding"))) {
5402 int ret;
5403
5404 ret = h1_parse_xfer_enc_header(&h1m, ist2(value, vlen));
5405 if (ret < 0) {
5406 hlua_pusherror(L, "Lua applet http '%s': Invalid '%s' header.\n",
5407 luactx->appctx->rule->arg.hlua_rule->fcn->name,
5408 name);
5409 WILL_LJMP(lua_error(L));
5410 }
5411 else if (ret == 0)
5412 goto next; /* Skip it */
5413 }
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005414 else if (isteqi(ist2(name, nlen), ist("content-length"))) {
5415 struct ist v = ist2(value, vlen);
5416 int ret;
5417
5418 ret = h1_parse_cont_len_header(&h1m, &v);
5419 if (ret < 0) {
5420 hlua_pusherror(L, "Lua applet http '%s': Invalid '%s' header.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005421 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005422 name);
5423 WILL_LJMP(lua_error(L));
5424 }
5425 else if (ret == 0)
5426 goto next; /* Skip it */
5427 }
5428
5429 /* Add a new header */
5430 if (!htx_add_header(htx, ist2(name, nlen), ist2(value, vlen))) {
5431 hlua_pusherror(L, "Lua applet http '%s': Failed to add header '%s' in the response.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005432 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005433 name);
5434 WILL_LJMP(lua_error(L));
5435 }
5436 next:
5437 /* Remove the array from the stack, and get next element with a remaining string. */
5438 lua_pop(L, 1);
5439 }
5440
5441 /* Remove the array from the stack, and get next element with a remaining string. */
5442 lua_pop(L, 1);
5443 }
5444
5445 if (h1m.flags & H1_MF_CHNK)
5446 h1m.flags &= ~H1_MF_CLEN;
5447 if (h1m.flags & (H1_MF_CLEN|H1_MF_CHNK))
5448 h1m.flags |= H1_MF_XFER_LEN;
5449
5450 /* Uset HTX start-line flags */
5451 if (h1m.flags & H1_MF_XFER_ENC)
5452 flags |= HTX_SL_F_XFER_ENC;
5453 if (h1m.flags & H1_MF_XFER_LEN) {
5454 flags |= HTX_SL_F_XFER_LEN;
5455 if (h1m.flags & H1_MF_CHNK)
5456 flags |= HTX_SL_F_CHNK;
5457 else if (h1m.flags & H1_MF_CLEN)
5458 flags |= HTX_SL_F_CLEN;
5459 if (h1m.body_len == 0)
5460 flags |= HTX_SL_F_BODYLESS;
5461 }
5462 sl->flags |= flags;
5463
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -07005464 /* If we don't have a content-length set, and the HTTP version is 1.1
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005465 * and the status code implies the presence of a message body, we must
5466 * announce a transfer encoding chunked. This is required by haproxy
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05005467 * for the keepalive compliance. If the applet announces a transfer-encoding
5468 * chunked itself, don't do anything.
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005469 */
5470 if ((flags & (HTX_SL_F_VER_11|HTX_SL_F_XFER_LEN)) == HTX_SL_F_VER_11 &&
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005471 http_ctx->status >= 200 && http_ctx->status != 204 && http_ctx->status != 304) {
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005472 /* Add a new header */
5473 sl->flags |= (HTX_SL_F_XFER_ENC|H1_MF_CHNK|H1_MF_XFER_LEN);
5474 if (!htx_add_header(htx, ist("transfer-encoding"), ist("chunked"))) {
5475 hlua_pusherror(L, "Lua applet http '%s': Failed to add header 'transfer-encoding' in the response.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005476 luactx->appctx->rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005477 WILL_LJMP(lua_error(L));
5478 }
5479 }
5480
5481 /* Finalize headers. */
5482 if (!htx_add_endof(htx, HTX_BLK_EOH)) {
5483 hlua_pusherror(L, "Lua applet http '%s': Failed create the response.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005484 luactx->appctx->rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005485 WILL_LJMP(lua_error(L));
5486 }
5487
5488 if (htx_used_space(htx) > b_size(&res->buf) - global.tune.maxrewrite) {
5489 b_reset(&res->buf);
5490 hlua_pusherror(L, "Lua: 'start_response': response header block too big");
5491 WILL_LJMP(lua_error(L));
5492 }
5493
5494 htx_to_buf(htx, &res->buf);
Christopher Fauletf6cce3f2019-02-27 21:20:09 +01005495 channel_add_input(res, htx->data);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005496
5497 /* Headers sent, set the flag. */
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005498 http_ctx->flags |= APPLET_HDR_SENT;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005499 return 0;
5500
5501}
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005502/* We will build the status line and the headers of the HTTP response.
5503 * We will try send at once if its not possible, we give back the hand
5504 * waiting for more room.
5505 */
Christopher Fauleta2097962019-07-15 16:25:33 +02005506__LJMP static int hlua_applet_http_start_response_yield(lua_State *L, int status, lua_KContext ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005507{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005508 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Willy Tarreau4596fe22022-05-17 19:07:51 +02005509 struct stconn *cs = appctx_cs(luactx->appctx);
Willy Tarreau40a9c322022-05-18 15:55:18 +02005510 struct channel *res = sc_ic(cs);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005511
5512 if (co_data(res)) {
Willy Tarreau99615ed2022-05-25 07:29:36 +02005513 sc_need_room(cs);
Christopher Fauleta2097962019-07-15 16:25:33 +02005514 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_start_response_yield, TICK_ETERNITY, 0));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005515 }
Christopher Fauleta2097962019-07-15 16:25:33 +02005516 return MAY_LJMP(hlua_applet_http_send_response(L));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005517}
5518
5519
Christopher Fauleta2097962019-07-15 16:25:33 +02005520__LJMP static int hlua_applet_http_start_response(lua_State *L)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005521{
Christopher Fauleta2097962019-07-15 16:25:33 +02005522 return MAY_LJMP(hlua_applet_http_start_response_yield(L, 0, 0));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005523}
5524
Christopher Fauleta2097962019-07-15 16:25:33 +02005525/*
5526 *
5527 *
5528 * Class HTTP
5529 *
5530 *
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005531 */
Christopher Fauleta2097962019-07-15 16:25:33 +02005532
5533/* Returns a struct hlua_txn if the stack entry "ud" is
5534 * a class stream, otherwise it throws an error.
5535 */
5536__LJMP static struct hlua_txn *hlua_checkhttp(lua_State *L, int ud)
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005537{
Christopher Fauleta2097962019-07-15 16:25:33 +02005538 return MAY_LJMP(hlua_checkudata(L, ud, class_http_ref));
5539}
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005540
Christopher Fauleta2097962019-07-15 16:25:33 +02005541/* This function creates and push in the stack a HTTP object
5542 * according with a current TXN.
5543 */
5544static int hlua_http_new(lua_State *L, struct hlua_txn *txn)
5545{
5546 struct hlua_txn *htxn;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005547
Christopher Fauleta2097962019-07-15 16:25:33 +02005548 /* Check stack size. */
5549 if (!lua_checkstack(L, 3))
5550 return 0;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005551
Christopher Fauleta2097962019-07-15 16:25:33 +02005552 /* Create the object: obj[0] = userdata.
5553 * Note that the base of the Converters object is the
5554 * same than the TXN object.
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005555 */
Christopher Fauleta2097962019-07-15 16:25:33 +02005556 lua_newtable(L);
5557 htxn = lua_newuserdata(L, sizeof(*htxn));
5558 lua_rawseti(L, -2, 0);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005559
5560 htxn->s = txn->s;
5561 htxn->p = txn->p;
Christopher Faulet256b69a2019-05-23 11:14:21 +02005562 htxn->dir = txn->dir;
5563 htxn->flags = txn->flags;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005564
5565 /* Pop a class stream metatable and affect it to the table. */
5566 lua_rawgeti(L, LUA_REGISTRYINDEX, class_http_ref);
5567 lua_setmetatable(L, -2);
5568
5569 return 1;
5570}
5571
Christopher Fauletdf97ac42020-02-26 16:57:19 +01005572/* This function creates and returns an array containing the status-line
5573 * elements. This function does not fails.
5574 */
5575__LJMP static int hlua_http_get_stline(lua_State *L, struct htx_sl *sl)
5576{
5577 /* Create the table. */
5578 lua_newtable(L);
5579
5580 if (sl->flags & HTX_SL_F_IS_RESP) {
5581 lua_pushstring(L, "version");
5582 lua_pushlstring(L, HTX_SL_RES_VPTR(sl), HTX_SL_RES_VLEN(sl));
5583 lua_settable(L, -3);
5584 lua_pushstring(L, "code");
5585 lua_pushlstring(L, HTX_SL_RES_CPTR(sl), HTX_SL_RES_CLEN(sl));
5586 lua_settable(L, -3);
5587 lua_pushstring(L, "reason");
5588 lua_pushlstring(L, HTX_SL_RES_RPTR(sl), HTX_SL_RES_RLEN(sl));
5589 lua_settable(L, -3);
5590 }
5591 else {
5592 lua_pushstring(L, "method");
5593 lua_pushlstring(L, HTX_SL_REQ_MPTR(sl), HTX_SL_REQ_MLEN(sl));
5594 lua_settable(L, -3);
5595 lua_pushstring(L, "uri");
5596 lua_pushlstring(L, HTX_SL_REQ_UPTR(sl), HTX_SL_REQ_ULEN(sl));
5597 lua_settable(L, -3);
5598 lua_pushstring(L, "version");
5599 lua_pushlstring(L, HTX_SL_REQ_VPTR(sl), HTX_SL_REQ_VLEN(sl));
5600 lua_settable(L, -3);
5601 }
5602 return 1;
5603}
5604
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005605/* This function creates ans returns an array of HTTP headers.
5606 * This function does not fails. It is used as wrapper with the
5607 * 2 following functions.
5608 */
Christopher Faulet9d1332b2020-02-24 16:46:16 +01005609__LJMP static int hlua_http_get_headers(lua_State *L, struct http_msg *msg)
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005610{
Christopher Fauleta2097962019-07-15 16:25:33 +02005611 struct htx *htx;
5612 int32_t pos;
5613
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005614 /* Create the table. */
5615 lua_newtable(L);
5616
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005617
Christopher Fauleta2097962019-07-15 16:25:33 +02005618 htx = htxbuf(&msg->chn->buf);
5619 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
5620 struct htx_blk *blk = htx_get_blk(htx, pos);
5621 enum htx_blk_type type = htx_get_blk_type(blk);
5622 struct ist n, v;
5623 int len;
Christopher Faulet724a12c2018-12-13 22:12:15 +01005624
Christopher Fauleta2097962019-07-15 16:25:33 +02005625 if (type == HTX_BLK_HDR) {
5626 n = htx_get_blk_name(htx,blk);
5627 v = htx_get_blk_value(htx, blk);
Christopher Faulet724a12c2018-12-13 22:12:15 +01005628 }
Christopher Fauleta2097962019-07-15 16:25:33 +02005629 else if (type == HTX_BLK_EOH)
5630 break;
5631 else
5632 continue;
Christopher Faulet724a12c2018-12-13 22:12:15 +01005633
Christopher Fauleta2097962019-07-15 16:25:33 +02005634 /* Check for existing entry:
5635 * assume that the table is on the top of the stack, and
5636 * push the key in the stack, the function lua_gettable()
5637 * perform the lookup.
5638 */
5639 lua_pushlstring(L, n.ptr, n.len);
5640 lua_gettable(L, -2);
Christopher Faulet724a12c2018-12-13 22:12:15 +01005641
Christopher Fauleta2097962019-07-15 16:25:33 +02005642 switch (lua_type(L, -1)) {
5643 case LUA_TNIL:
5644 /* Table not found, create it. */
5645 lua_pop(L, 1); /* remove the nil value. */
5646 lua_pushlstring(L, n.ptr, n.len); /* push the header name as key. */
5647 lua_newtable(L); /* create and push empty table. */
5648 lua_pushlstring(L, v.ptr, v.len); /* push header value. */
5649 lua_rawseti(L, -2, 0); /* index header value (pop it). */
5650 lua_rawset(L, -3); /* index new table with header name (pop the values). */
Christopher Faulet724a12c2018-12-13 22:12:15 +01005651 break;
Christopher Faulet724a12c2018-12-13 22:12:15 +01005652
Christopher Fauleta2097962019-07-15 16:25:33 +02005653 case LUA_TTABLE:
5654 /* Entry found: push the value in the table. */
5655 len = lua_rawlen(L, -1);
5656 lua_pushlstring(L, v.ptr, v.len); /* push header value. */
5657 lua_rawseti(L, -2, len+1); /* index header value (pop it). */
5658 lua_pop(L, 1); /* remove the table (it is stored in the main table). */
5659 break;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005660
Christopher Fauleta2097962019-07-15 16:25:33 +02005661 default:
5662 /* Other cases are errors. */
5663 hlua_pusherror(L, "internal error during the parsing of headers.");
5664 WILL_LJMP(lua_error(L));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005665 }
5666 }
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005667 return 1;
5668}
5669
5670__LJMP static int hlua_http_req_get_headers(lua_State *L)
5671{
5672 struct hlua_txn *htxn;
5673
5674 MAY_LJMP(check_args(L, 1, "req_get_headers"));
5675 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5676
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005677 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005678 WILL_LJMP(lua_error(L));
5679
Christopher Faulet9d1332b2020-02-24 16:46:16 +01005680 return hlua_http_get_headers(L, &htxn->s->txn->req);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005681}
5682
5683__LJMP static int hlua_http_res_get_headers(lua_State *L)
5684{
5685 struct hlua_txn *htxn;
5686
5687 MAY_LJMP(check_args(L, 1, "res_get_headers"));
5688 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5689
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005690 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005691 WILL_LJMP(lua_error(L));
5692
Christopher Faulet9d1332b2020-02-24 16:46:16 +01005693 return hlua_http_get_headers(L, &htxn->s->txn->rsp);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005694}
5695
5696/* This function replace full header, or just a value in
5697 * the request or in the response. It is a wrapper fir the
5698 * 4 following functions.
5699 */
Christopher Fauletd1914aa2020-02-24 16:52:46 +01005700__LJMP static inline int hlua_http_rep_hdr(lua_State *L, struct http_msg *msg, int full)
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005701{
5702 size_t name_len;
5703 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
5704 const char *reg = MAY_LJMP(luaL_checkstring(L, 3));
5705 const char *value = MAY_LJMP(luaL_checkstring(L, 4));
Christopher Fauleta2097962019-07-15 16:25:33 +02005706 struct htx *htx;
Dragan Dosen26743032019-04-30 15:54:36 +02005707 struct my_regex *re;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005708
Dragan Dosen26743032019-04-30 15:54:36 +02005709 if (!(re = regex_comp(reg, 1, 1, NULL)))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005710 WILL_LJMP(luaL_argerror(L, 3, "invalid regex"));
5711
Christopher Fauleta2097962019-07-15 16:25:33 +02005712 htx = htxbuf(&msg->chn->buf);
Christopher Fauletd1914aa2020-02-24 16:52:46 +01005713 http_replace_hdrs(chn_strm(msg->chn), htx, ist2(name, name_len), value, re, full);
Dragan Dosen26743032019-04-30 15:54:36 +02005714 regex_free(re);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005715 return 0;
5716}
5717
5718__LJMP static int hlua_http_req_rep_hdr(lua_State *L)
5719{
5720 struct hlua_txn *htxn;
5721
5722 MAY_LJMP(check_args(L, 4, "req_rep_hdr"));
5723 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5724
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005725 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005726 WILL_LJMP(lua_error(L));
5727
Christopher Fauletd1914aa2020-02-24 16:52:46 +01005728 return MAY_LJMP(hlua_http_rep_hdr(L, &htxn->s->txn->req, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005729}
5730
5731__LJMP static int hlua_http_res_rep_hdr(lua_State *L)
5732{
5733 struct hlua_txn *htxn;
5734
5735 MAY_LJMP(check_args(L, 4, "res_rep_hdr"));
5736 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5737
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005738 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005739 WILL_LJMP(lua_error(L));
5740
Christopher Fauletd1914aa2020-02-24 16:52:46 +01005741 return MAY_LJMP(hlua_http_rep_hdr(L, &htxn->s->txn->rsp, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005742}
5743
5744__LJMP static int hlua_http_req_rep_val(lua_State *L)
5745{
5746 struct hlua_txn *htxn;
5747
5748 MAY_LJMP(check_args(L, 4, "req_rep_hdr"));
5749 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5750
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005751 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005752 WILL_LJMP(lua_error(L));
5753
Christopher Fauletd1914aa2020-02-24 16:52:46 +01005754 return MAY_LJMP(hlua_http_rep_hdr(L, &htxn->s->txn->req, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005755}
5756
5757__LJMP static int hlua_http_res_rep_val(lua_State *L)
5758{
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005759 struct hlua_txn *htxn;
5760
5761 MAY_LJMP(check_args(L, 4, "res_rep_val"));
5762 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5763
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005764 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005765 WILL_LJMP(lua_error(L));
5766
Christopher Fauletd1914aa2020-02-24 16:52:46 +01005767 return MAY_LJMP(hlua_http_rep_hdr(L, &htxn->s->txn->rsp, 0));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005768}
5769
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08005770/* This function deletes all the occurrences of an header.
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005771 * It is a wrapper for the 2 following functions.
5772 */
Christopher Fauletd31c7b32020-02-25 09:37:57 +01005773__LJMP static inline int hlua_http_del_hdr(lua_State *L, struct http_msg *msg)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005774{
5775 size_t len;
5776 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Christopher Fauleta2097962019-07-15 16:25:33 +02005777 struct htx *htx = htxbuf(&msg->chn->buf);
5778 struct http_hdr_ctx ctx;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005779
Christopher Fauleta2097962019-07-15 16:25:33 +02005780 ctx.blk = NULL;
5781 while (http_find_header(htx, ist2(name, len), &ctx, 1))
5782 http_remove_header(htx, &ctx);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005783 return 0;
5784}
5785
5786__LJMP static int hlua_http_req_del_hdr(lua_State *L)
5787{
5788 struct hlua_txn *htxn;
5789
5790 MAY_LJMP(check_args(L, 2, "req_del_hdr"));
5791 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5792
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005793 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005794 WILL_LJMP(lua_error(L));
5795
Christopher Fauletd31c7b32020-02-25 09:37:57 +01005796 return hlua_http_del_hdr(L, &htxn->s->txn->req);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005797}
5798
5799__LJMP static int hlua_http_res_del_hdr(lua_State *L)
5800{
5801 struct hlua_txn *htxn;
5802
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005803 MAY_LJMP(check_args(L, 2, "res_del_hdr"));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005804 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5805
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005806 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005807 WILL_LJMP(lua_error(L));
5808
Christopher Fauletd31c7b32020-02-25 09:37:57 +01005809 return hlua_http_del_hdr(L, &htxn->s->txn->rsp);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005810}
5811
5812/* This function adds an header. It is a wrapper used by
5813 * the 2 following functions.
5814 */
Christopher Fauletd31c7b32020-02-25 09:37:57 +01005815__LJMP static inline int hlua_http_add_hdr(lua_State *L, struct http_msg *msg)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005816{
5817 size_t name_len;
5818 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
5819 size_t value_len;
5820 const char *value = MAY_LJMP(luaL_checklstring(L, 3, &value_len));
Christopher Fauleta2097962019-07-15 16:25:33 +02005821 struct htx *htx = htxbuf(&msg->chn->buf);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005822
Christopher Fauleta2097962019-07-15 16:25:33 +02005823 lua_pushboolean(L, http_add_header(htx, ist2(name, name_len),
5824 ist2(value, value_len)));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005825 return 0;
5826}
5827
Christopher Fauletdf97ac42020-02-26 16:57:19 +01005828__LJMP static int hlua_http_req_add_hdr(lua_State *L)
5829{
5830 struct hlua_txn *htxn;
5831
5832 MAY_LJMP(check_args(L, 3, "req_add_hdr"));
5833 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5834
5835 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
5836 WILL_LJMP(lua_error(L));
5837
5838 return hlua_http_add_hdr(L, &htxn->s->txn->req);
5839}
5840
5841__LJMP static int hlua_http_res_add_hdr(lua_State *L)
5842{
5843 struct hlua_txn *htxn;
5844
5845 MAY_LJMP(check_args(L, 3, "res_add_hdr"));
5846 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5847
5848 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
5849 WILL_LJMP(lua_error(L));
5850
5851 return hlua_http_add_hdr(L, &htxn->s->txn->rsp);
5852}
5853
5854static int hlua_http_req_set_hdr(lua_State *L)
5855{
5856 struct hlua_txn *htxn;
5857
5858 MAY_LJMP(check_args(L, 3, "req_set_hdr"));
5859 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5860
5861 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
5862 WILL_LJMP(lua_error(L));
5863
5864 hlua_http_del_hdr(L, &htxn->s->txn->req);
5865 return hlua_http_add_hdr(L, &htxn->s->txn->req);
5866}
5867
5868static int hlua_http_res_set_hdr(lua_State *L)
5869{
5870 struct hlua_txn *htxn;
5871
5872 MAY_LJMP(check_args(L, 3, "res_set_hdr"));
5873 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5874
5875 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
5876 WILL_LJMP(lua_error(L));
5877
5878 hlua_http_del_hdr(L, &htxn->s->txn->rsp);
5879 return hlua_http_add_hdr(L, &htxn->s->txn->rsp);
5880}
5881
5882/* This function set the method. */
5883static int hlua_http_req_set_meth(lua_State *L)
5884{
5885 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5886 size_t name_len;
5887 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
5888
5889 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
5890 WILL_LJMP(lua_error(L));
5891
5892 lua_pushboolean(L, http_req_replace_stline(0, name, name_len, htxn->p, htxn->s) != -1);
5893 return 1;
5894}
5895
5896/* This function set the method. */
5897static int hlua_http_req_set_path(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(1, name, name_len, htxn->p, htxn->s) != -1);
5907 return 1;
5908}
5909
5910/* This function set the query-string. */
5911static int hlua_http_req_set_query(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 /* Check length. */
5921 if (name_len > trash.size - 1) {
5922 lua_pushboolean(L, 0);
5923 return 1;
5924 }
5925
5926 /* Add the mark question as prefix. */
5927 chunk_reset(&trash);
5928 trash.area[trash.data++] = '?';
5929 memcpy(trash.area + trash.data, name, name_len);
5930 trash.data += name_len;
5931
5932 lua_pushboolean(L,
5933 http_req_replace_stline(2, trash.area, trash.data, htxn->p, htxn->s) != -1);
5934 return 1;
5935}
5936
5937/* This function set the uri. */
5938static int hlua_http_req_set_uri(lua_State *L)
5939{
5940 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5941 size_t name_len;
5942 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
5943
5944 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
5945 WILL_LJMP(lua_error(L));
5946
5947 lua_pushboolean(L, http_req_replace_stline(3, name, name_len, htxn->p, htxn->s) != -1);
5948 return 1;
5949}
5950
5951/* This function set the response code & optionally reason. */
5952static int hlua_http_res_set_status(lua_State *L)
5953{
5954 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5955 unsigned int code = MAY_LJMP(luaL_checkinteger(L, 2));
5956 const char *str = MAY_LJMP(luaL_optlstring(L, 3, NULL, NULL));
5957 const struct ist reason = ist2(str, (str ? strlen(str) : 0));
5958
5959 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
5960 WILL_LJMP(lua_error(L));
5961
5962 http_res_set_status(code, reason, htxn->s);
5963 return 0;
5964}
5965
5966/*
5967 *
5968 *
5969 * Class HTTPMessage
5970 *
5971 *
5972 */
5973
5974/* Returns a struct http_msg if the stack entry "ud" is a class HTTPMessage,
5975 * otherwise it throws an error.
5976 */
5977__LJMP static struct http_msg *hlua_checkhttpmsg(lua_State *L, int ud)
5978{
5979 return MAY_LJMP(hlua_checkudata(L, ud, class_http_msg_ref));
5980}
5981
5982/* Creates and pushes on the stack a HTTP object according with a current TXN.
5983 */
Christopher Faulet78c35472020-02-26 17:14:08 +01005984static int hlua_http_msg_new(lua_State *L, struct http_msg *msg)
Christopher Fauletdf97ac42020-02-26 16:57:19 +01005985{
5986 /* Check stack size. */
5987 if (!lua_checkstack(L, 3))
5988 return 0;
5989
5990 lua_newtable(L);
5991 lua_pushlightuserdata(L, msg);
5992 lua_rawseti(L, -2, 0);
5993
5994 /* Create the "channel" field that contains the request channel object. */
5995 lua_pushstring(L, "channel");
5996 if (!hlua_channel_new(L, msg->chn))
5997 return 0;
5998 lua_rawset(L, -3);
5999
6000 /* Pop a class stream metatable and affect it to the table. */
6001 lua_rawgeti(L, LUA_REGISTRYINDEX, class_http_msg_ref);
6002 lua_setmetatable(L, -2);
6003
6004 return 1;
6005}
6006
6007/* Helper function returning a filter attached to the HTTP message at the
6008 * position <ud> in the stack, filling the current offset and length of the
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006009 * filter. If no filter is attached, NULL is returned and <offset> and <len> are
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006010 * filled with output and input length respectively.
6011 */
6012static struct filter *hlua_http_msg_filter(lua_State *L, int ud, struct http_msg *msg, size_t *offset, size_t *len)
6013{
6014 struct channel *chn = msg->chn;
6015 struct htx *htx = htxbuf(&chn->buf);
6016 struct filter *filter = NULL;
6017
6018 *offset = co_data(msg->chn);
6019 *len = htx->data - co_data(msg->chn);
6020
6021 if (lua_getfield(L, ud, "__filter") == LUA_TLIGHTUSERDATA) {
6022 filter = lua_touserdata (L, -1);
6023 if (msg->msg_state >= HTTP_MSG_DATA) {
6024 struct hlua_flt_ctx *flt_ctx = filter->ctx;
6025
6026 *offset = flt_ctx->cur_off[CHN_IDX(chn)];
6027 *len = flt_ctx->cur_len[CHN_IDX(chn)];
6028 }
6029 }
6030
6031 lua_pop(L, 1);
6032 return filter;
6033}
6034
6035/* Returns true if the channel attached to the HTTP message is the response
6036 * channel.
6037 */
6038__LJMP static int hlua_http_msg_is_resp(lua_State *L)
6039{
6040 struct http_msg *msg;
6041
6042 MAY_LJMP(check_args(L, 1, "is_resp"));
6043 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6044
6045 lua_pushboolean(L, !!(msg->chn->flags & CF_ISRESP));
6046 return 1;
6047}
6048
6049/* Returns an array containing the elements status-line of the HTTP message. It relies
6050 * on hlua_http_get_stline().
6051 */
6052__LJMP static int hlua_http_msg_get_stline(lua_State *L)
6053{
6054 struct http_msg *msg;
6055 struct htx *htx;
6056 struct htx_sl *sl;
6057
6058 MAY_LJMP(check_args(L, 1, "get_stline"));
6059 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6060
6061 if (msg->msg_state > HTTP_MSG_BODY)
6062 WILL_LJMP(lua_error(L));
6063
6064 htx = htxbuf(&msg->chn->buf);
6065 sl = http_get_stline(htx);
6066 if (!sl)
6067 return 0;
6068 return hlua_http_get_stline(L, sl);
6069}
6070
6071/* Returns an array containing all headers of the HTTP message. it relies on
6072 * hlua_http_get_headers().
6073 */
6074__LJMP static int hlua_http_msg_get_headers(lua_State *L)
6075{
6076 struct http_msg *msg;
6077
6078 MAY_LJMP(check_args(L, 1, "get_headers"));
6079 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6080
6081 if (msg->msg_state > HTTP_MSG_BODY)
6082 WILL_LJMP(lua_error(L));
6083
6084 return hlua_http_get_headers(L, msg);
6085}
6086
6087/* Deletes all occurrences of an header in the HTTP message matching on its
6088 * name. It relies on hlua_http_del_hdr().
6089 */
6090__LJMP static int hlua_http_msg_del_hdr(lua_State *L)
6091{
6092 struct http_msg *msg;
6093
6094 MAY_LJMP(check_args(L, 2, "del_header"));
6095 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6096
6097 if (msg->msg_state > HTTP_MSG_BODY)
6098 WILL_LJMP(lua_error(L));
6099
6100 return hlua_http_del_hdr(L, msg);
6101}
6102
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006103/* Matches the full value line of all occurrences of an header in the HTTP
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006104 * message given its name against a regex and replaces it if it matches. It
6105 * relies on hlua_http_rep_hdr().
6106 */
6107__LJMP static int hlua_http_msg_rep_hdr(lua_State *L)
6108{
6109 struct http_msg *msg;
6110
6111 MAY_LJMP(check_args(L, 4, "rep_header"));
6112 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6113
6114 if (msg->msg_state > HTTP_MSG_BODY)
6115 WILL_LJMP(lua_error(L));
6116
6117 return hlua_http_rep_hdr(L, msg, 1);
6118}
6119
Ilya Shipitsinbd6b4be2021-10-15 16:18:21 +05006120/* Matches all comma-separated values of all occurrences of an header in the HTTP
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006121 * message given its name against a regex and replaces it if it matches. It
6122 * relies on hlua_http_rep_hdr().
6123 */
6124__LJMP static int hlua_http_msg_rep_val(lua_State *L)
6125{
6126 struct http_msg *msg;
6127
6128 MAY_LJMP(check_args(L, 4, "rep_value"));
6129 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6130
6131 if (msg->msg_state > HTTP_MSG_BODY)
6132 WILL_LJMP(lua_error(L));
6133
6134 return hlua_http_rep_hdr(L, msg, 0);
6135}
6136
6137/* Add an header in the HTTP message. It relies on hlua_http_add_hdr() */
6138__LJMP static int hlua_http_msg_add_hdr(lua_State *L)
6139{
6140 struct http_msg *msg;
6141
6142 MAY_LJMP(check_args(L, 3, "add_header"));
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_add_hdr(L, msg);
6149}
6150
6151/* Add an header in the HTTP message removing existing headers with the same
6152 * name. It relies on hlua_http_del_hdr() and hlua_http_add_hdr().
6153 */
6154__LJMP static int hlua_http_msg_set_hdr(lua_State *L)
6155{
6156 struct http_msg *msg;
6157
6158 MAY_LJMP(check_args(L, 3, "set_header"));
6159 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6160
6161 if (msg->msg_state > HTTP_MSG_BODY)
6162 WILL_LJMP(lua_error(L));
6163
6164 hlua_http_del_hdr(L, msg);
6165 return hlua_http_add_hdr(L, msg);
6166}
6167
6168/* Rewrites the request method. It relies on http_req_replace_stline(). */
6169__LJMP static int hlua_http_msg_set_meth(lua_State *L)
6170{
6171 struct stream *s;
6172 struct http_msg *msg;
6173 const char *name;
6174 size_t name_len;
6175
6176 MAY_LJMP(check_args(L, 2, "set_method"));
6177 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6178 name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
6179
6180 if ((msg->chn->flags & CF_ISRESP) || msg->msg_state > HTTP_MSG_BODY)
6181 WILL_LJMP(lua_error(L));
6182
6183 s = chn_strm(msg->chn);
6184 lua_pushboolean(L, http_req_replace_stline(0, name, name_len, s->be, s) != -1);
6185 return 1;
6186}
6187
6188/* Rewrites the request path. It relies on http_req_replace_stline(). */
6189__LJMP static int hlua_http_msg_set_path(lua_State *L)
6190{
6191 struct stream *s;
6192 struct http_msg *msg;
6193 const char *name;
6194 size_t name_len;
6195
6196 MAY_LJMP(check_args(L, 2, "set_path"));
6197 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6198 name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
6199
6200 if ((msg->chn->flags & CF_ISRESP) || msg->msg_state > HTTP_MSG_BODY)
6201 WILL_LJMP(lua_error(L));
6202
6203 s = chn_strm(msg->chn);
6204 lua_pushboolean(L, http_req_replace_stline(1, name, name_len, s->be, s) != -1);
6205 return 1;
6206}
6207
6208/* Rewrites the request query-string. It relies on http_req_replace_stline(). */
6209__LJMP static int hlua_http_msg_set_query(lua_State *L)
6210{
6211 struct stream *s;
6212 struct http_msg *msg;
6213 const char *name;
6214 size_t name_len;
6215
6216 MAY_LJMP(check_args(L, 2, "set_query"));
6217 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6218 name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
6219
6220 if ((msg->chn->flags & CF_ISRESP) || msg->msg_state > HTTP_MSG_BODY)
6221 WILL_LJMP(lua_error(L));
6222
6223 /* Check length. */
6224 if (name_len > trash.size - 1) {
6225 lua_pushboolean(L, 0);
6226 return 1;
6227 }
6228
6229 /* Add the mark question as prefix. */
6230 chunk_reset(&trash);
6231 trash.area[trash.data++] = '?';
6232 memcpy(trash.area + trash.data, name, name_len);
6233 trash.data += name_len;
6234
6235 s = chn_strm(msg->chn);
6236 lua_pushboolean(L, http_req_replace_stline(2, trash.area, trash.data, s->be, s) != -1);
6237 return 1;
6238}
6239
6240/* Rewrites the request URI. It relies on http_req_replace_stline(). */
6241__LJMP static int hlua_http_msg_set_uri(lua_State *L)
6242{
6243 struct stream *s;
6244 struct http_msg *msg;
6245 const char *name;
6246 size_t name_len;
6247
6248 MAY_LJMP(check_args(L, 2, "set_uri"));
6249 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6250 name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
6251
6252 if ((msg->chn->flags & CF_ISRESP) || msg->msg_state > HTTP_MSG_BODY)
6253 WILL_LJMP(lua_error(L));
6254
6255 s = chn_strm(msg->chn);
6256 lua_pushboolean(L, http_req_replace_stline(3, name, name_len, s->be, s) != -1);
6257 return 1;
6258}
6259
6260/* Rewrites the response status code. It relies on http_res_set_status(). */
6261__LJMP static int hlua_http_msg_set_status(lua_State *L)
6262{
6263 struct http_msg *msg;
6264 unsigned int code;
6265 const char *reason;
6266 size_t reason_len;
6267
6268 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6269 code = MAY_LJMP(luaL_checkinteger(L, 2));
6270 reason = MAY_LJMP(luaL_optlstring(L, 3, NULL, &reason_len));
6271
6272 if (!(msg->chn->flags & CF_ISRESP) || msg->msg_state > HTTP_MSG_BODY)
6273 WILL_LJMP(lua_error(L));
6274
6275 lua_pushboolean(L, http_res_set_status(code, ist2(reason, reason_len), chn_strm(msg->chn)) != -1);
6276 return 1;
6277}
6278
6279/* Returns true if the HTTP message is full. */
6280__LJMP static int hlua_http_msg_is_full(lua_State *L)
6281{
6282 struct http_msg *msg;
6283
6284 MAY_LJMP(check_args(L, 1, "is_full"));
6285 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6286 lua_pushboolean(L, channel_full(msg->chn, 0));
6287 return 1;
6288}
6289
6290/* Returns true if the HTTP message may still receive data. */
6291__LJMP static int hlua_http_msg_may_recv(lua_State *L)
6292{
6293 struct http_msg *msg;
6294 struct htx *htx;
6295
6296 MAY_LJMP(check_args(L, 1, "may_recv"));
6297 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6298 htx = htxbuf(&msg->chn->buf);
6299 lua_pushboolean(L, (htx_expect_more(htx) && !channel_input_closed(msg->chn) && channel_may_recv(msg->chn)));
6300 return 1;
6301}
6302
6303/* Returns true if the HTTP message EOM was received */
6304__LJMP static int hlua_http_msg_is_eom(lua_State *L)
6305{
6306 struct http_msg *msg;
6307 struct htx *htx;
6308
6309 MAY_LJMP(check_args(L, 1, "may_recv"));
6310 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6311 htx = htxbuf(&msg->chn->buf);
6312 lua_pushboolean(L, !htx_expect_more(htx));
6313 return 1;
6314}
6315
6316/* Returns the number of bytes available in the input side of the HTTP
6317 * message. This function never fails.
6318 */
6319__LJMP static int hlua_http_msg_get_in_len(lua_State *L)
6320{
6321 struct http_msg *msg;
Christopher Fauleteae8afa2020-02-26 17:15:48 +01006322 size_t output, input;
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006323
6324 MAY_LJMP(check_args(L, 1, "input"));
6325 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
Christopher Fauleteae8afa2020-02-26 17:15:48 +01006326 hlua_http_msg_filter(L, 1, msg, &output, &input);
6327 lua_pushinteger(L, input);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006328 return 1;
6329}
6330
6331/* Returns the number of bytes available in the output side of the HTTP
6332 * message. This function never fails.
6333 */
6334__LJMP static int hlua_http_msg_get_out_len(lua_State *L)
6335{
6336 struct http_msg *msg;
Christopher Fauleteae8afa2020-02-26 17:15:48 +01006337 size_t output, input;
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006338
6339 MAY_LJMP(check_args(L, 1, "output"));
6340 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
Christopher Fauleteae8afa2020-02-26 17:15:48 +01006341 hlua_http_msg_filter(L, 1, msg, &output, &input);
6342 lua_pushinteger(L, output);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006343 return 1;
6344}
6345
6346/* Copies at most <len> bytes of DATA blocks from the HTTP message <msg>
6347 * starting at the offset <offset> and put it in a string LUA variables. It
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006348 * returns the built string length. It stops on the first non-DATA HTX
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006349 * block. This function is called during the payload filtering, so the headers
6350 * are already scheduled for output (from the filter point of view).
6351 */
6352static int _hlua_http_msg_dup(struct http_msg *msg, lua_State *L, size_t offset, size_t len)
6353{
6354 struct htx *htx = htxbuf(&msg->chn->buf);
6355 struct htx_blk *blk;
6356 struct htx_ret htxret;
6357 luaL_Buffer b;
6358 int ret = 0;
6359
6360 luaL_buffinit(L, &b);
6361 htxret = htx_find_offset(htx, offset);
6362 for (blk = htxret.blk, offset = htxret.ret; blk && len; blk = htx_get_next_blk(htx, blk)) {
6363 enum htx_blk_type type = htx_get_blk_type(blk);
6364 struct ist v;
6365
6366 switch (type) {
6367 case HTX_BLK_UNUSED:
6368 break;
6369
6370 case HTX_BLK_DATA:
6371 v = htx_get_blk_value(htx, blk);
Tim Duesterhusb113b5c2021-09-15 13:58:44 +02006372 v = istadv(v, offset);
Tim Duesterhus2471f5c2021-11-08 09:05:01 +01006373 v = isttrim(v, len);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006374
6375 luaL_addlstring(&b, v.ptr, v.len);
6376 ret += v.len;
6377 break;
6378
6379 default:
vishnu0af4bd72021-10-24 06:46:24 +05306380 if (!ret)
6381 goto no_data;
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006382 goto end;
6383 }
6384 offset = 0;
6385 }
6386
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006387end:
vishnu0af4bd72021-10-24 06:46:24 +05306388 if (!ret && (htx->flags & HTX_FL_EOM))
6389 goto no_data;
6390 luaL_pushresult(&b);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006391 return ret;
vishnu0af4bd72021-10-24 06:46:24 +05306392
6393 no_data:
6394 /* Remove the empty string and push nil on the stack */
6395 lua_pop(L, 1);
6396 lua_pushnil(L);
6397 return 0;
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006398}
6399
6400/* Copies the string <str> to the HTTP message <msg> at the offset
6401 * <offset>. This function returns -1 if data cannot be copied. Otherwise, it
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006402 * returns the amount of data written. This function is responsible to update
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006403 * the filter context.
6404 */
6405static int _hlua_http_msg_insert(struct http_msg *msg, struct filter *filter, struct ist str, size_t offset)
6406{
6407 struct htx *htx = htx_from_buf(&msg->chn->buf);
6408 struct htx_ret htxret;
6409 int /*max, */ret = 0;
6410
6411 /* Nothing to do, just return */
6412 if (unlikely(istlen(str) == 0))
6413 goto end;
6414
6415 if (istlen(str) > htx_free_data_space(htx)) {
6416 ret = -1;
6417 goto end;
6418 }
6419
6420 htxret = htx_find_offset(htx, offset);
6421 if (!htxret.blk || htx_get_blk_type(htxret.blk) != HTX_BLK_DATA) {
6422 if (!htx_add_last_data(htx, str))
6423 goto end;
6424 }
6425 else {
6426 struct ist v = htx_get_blk_value(htx, htxret.blk);
6427 v.ptr += htxret.ret;
6428 v.len = 0;
6429 if (!htx_replace_blk_value(htx, htxret.blk, v, str))
6430 goto end;
6431 }
6432 ret = str.len;
6433 if (ret) {
6434 struct hlua_flt_ctx *flt_ctx = filter->ctx;
6435 flt_update_offsets(filter, msg->chn, ret);
6436 flt_ctx->cur_len[CHN_IDX(msg->chn)] += ret;
6437 }
6438
6439 end:
6440 htx_to_buf(htx, &msg->chn->buf);
6441 return ret;
6442}
6443
6444/* Helper function removing at most <len> bytes of DATA blocks at the absolute
6445 * position <offset>. It stops on the first non-DATA HTX block. This function is
6446 * called during the payload filtering, so the headers are already scheduled for
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006447 * output (from the filter point of view). This function is responsible to
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006448 * update the filter context.
6449 */
6450static void _hlua_http_msg_delete(struct http_msg *msg, struct filter *filter, size_t offset, size_t len)
6451{
6452 struct hlua_flt_ctx *flt_ctx = filter->ctx;
6453 struct htx *htx = htx_from_buf(&msg->chn->buf);
6454 struct htx_blk *blk;
6455 struct htx_ret htxret;
6456 size_t ret = 0;
6457
6458 /* Be sure <len> is always the amount of DATA to remove */
6459 if (htx->data == offset+len && htx_get_tail_type(htx) == HTX_BLK_DATA) {
6460 htx_truncate(htx, offset);
6461 ret = len;
6462 goto end;
6463 }
6464
6465 htxret = htx_find_offset(htx, offset);
6466 blk = htxret.blk;
6467 if (htxret.ret) {
6468 struct ist v;
6469
6470 if (htx_get_blk_type(blk) != HTX_BLK_DATA)
6471 goto end;
6472 v = htx_get_blk_value(htx, blk);
6473 v.ptr += htxret.ret;
Tim Duesterhus2471f5c2021-11-08 09:05:01 +01006474 v = isttrim(v, len);
Tim Duesterhusb113b5c2021-09-15 13:58:44 +02006475 blk = htx_replace_blk_value(htx, blk, v, IST_NULL);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006476 len -= v.len;
6477 ret += v.len;
6478 }
6479
6480
6481 while (blk && len) {
6482 enum htx_blk_type type = htx_get_blk_type(blk);
6483 uint32_t sz = htx_get_blksz(blk);
6484
6485 switch (type) {
6486 case HTX_BLK_UNUSED:
6487 break;
6488
6489 case HTX_BLK_DATA:
6490 if (len < sz) {
6491 htx_cut_data_blk(htx, blk, len);
6492 ret += len;
6493 goto end;
6494 }
6495 break;
6496
6497 default:
6498 goto end;
6499 }
6500
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006501 /* Remove all the data block */
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006502 len -= sz;
6503 ret += sz;
6504 blk = htx_remove_blk(htx, blk);
6505 }
6506
6507end:
6508 flt_update_offsets(filter, msg->chn, -ret);
6509 flt_ctx->cur_len[CHN_IDX(msg->chn)] -= ret;
6510 /* WARNING: we don't call htx_to_buf() on purpose, because we don't want
6511 * to loose the EOM flag if the message is empty.
6512 */
6513}
6514
6515/* Copies input data found in an HTTP message. Unlike the channel function used
6516 * to duplicate raw data, this one can only be called inside a filter, from
6517 * http_payload callback. So it cannot yield. An exception is returned if it is
6518 * called from another callback. If nothing was copied, a nil value is pushed on
6519 * the stack.
6520 */
6521__LJMP static int hlua_http_msg_get_body(lua_State *L)
6522{
6523 struct http_msg *msg;
6524 struct filter *filter;
6525 size_t output, input;
6526 int offset, len;
6527
6528 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
6529 WILL_LJMP(luaL_error(L, "'data' expects at most 2 arguments"));
6530 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6531
6532 if (msg->msg_state < HTTP_MSG_DATA)
6533 WILL_LJMP(lua_error(L));
6534
6535 filter = hlua_http_msg_filter(L, 1, msg, &output, &input);
6536 if (!filter || !hlua_filter_from_payload(filter))
6537 WILL_LJMP(lua_error(L));
6538
6539 if (!ci_data(msg->chn) && channel_input_closed(msg->chn)) {
6540 lua_pushnil(L);
6541 return 1;
6542 }
6543
6544 offset = output;
6545 if (lua_gettop(L) > 1) {
6546 offset = MAY_LJMP(luaL_checkinteger(L, 2));
6547 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02006548 offset = MAX(0, (int)input + offset);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006549 offset += output;
6550 if (offset < output || offset > input + output) {
6551 lua_pushfstring(L, "offset out of range.");
6552 WILL_LJMP(lua_error(L));
6553 }
6554 }
6555 len = output + input - offset;
6556 if (lua_gettop(L) == 3) {
6557 len = MAY_LJMP(luaL_checkinteger(L, 3));
6558 if (!len)
6559 goto dup;
6560 if (len == -1)
6561 len = global.tune.bufsize;
6562 if (len < 0) {
6563 lua_pushfstring(L, "length out of range.");
6564 WILL_LJMP(lua_error(L));
6565 }
6566 }
6567
6568 dup:
6569 _hlua_http_msg_dup(msg, L, offset, len);
6570 return 1;
6571}
6572
6573/* Appends a string to the HTTP message, after all existing DATA blocks but
6574 * before the trailers, if any. It returns the amount of data written or -1 if
6575 * nothing was copied. Unlike the channel function used to append data, this one
6576 * can only be called inside a filter, from http_payload callback. So it cannot
6577 * yield. An exception is returned if it is called from another callback.
6578 */
6579__LJMP static int hlua_http_msg_append(lua_State *L)
6580{
6581 struct http_msg *msg;
6582 struct filter *filter;
6583 const char *str;
6584 size_t offset, len, sz;
6585 int ret;
6586
6587 MAY_LJMP(check_args(L, 2, "append"));
6588 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6589
6590 if (msg->msg_state < HTTP_MSG_DATA)
6591 WILL_LJMP(lua_error(L));
6592
6593 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
6594 filter = hlua_http_msg_filter(L, 1, msg, &offset, &len);
6595 if (!filter || !hlua_filter_from_payload(filter))
6596 WILL_LJMP(lua_error(L));
6597
6598 ret = _hlua_http_msg_insert(msg, filter, ist2(str, sz), offset+len);
6599 lua_pushinteger(L, ret);
6600 return 1;
6601}
6602
6603/* Prepends a string to the HTTP message, before all existing DATA blocks. It
6604 * returns the amount of data written or -1 if nothing was copied. Unlike the
6605 * channel function used to prepend data, this one can only be called inside a
6606 * filter, from http_payload callback. So it cannot yield. An exception is
6607 * returned if it is called from another callback.
6608 */
6609__LJMP static int hlua_http_msg_prepend(lua_State *L)
6610{
6611 struct http_msg *msg;
6612 struct filter *filter;
6613 const char *str;
6614 size_t offset, len, sz;
6615 int ret;
6616
6617 MAY_LJMP(check_args(L, 2, "prepend"));
6618 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006619
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006620 if (msg->msg_state < HTTP_MSG_DATA)
6621 WILL_LJMP(lua_error(L));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006622
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006623 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
6624 filter = hlua_http_msg_filter(L, 1, msg, &offset, &len);
6625 if (!filter || !hlua_filter_from_payload(filter))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006626 WILL_LJMP(lua_error(L));
6627
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006628 ret = _hlua_http_msg_insert(msg, filter, ist2(str, sz), offset);
6629 lua_pushinteger(L, ret);
6630 return 1;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006631}
6632
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006633/* Inserts a string to the HTTP message at a given offset. By default the string
6634 * is appended at the end of DATA blocks. It returns the amount of data written
6635 * or -1 if nothing was copied. Unlike the channel function used to insert data,
6636 * this one can only be called inside a filter, from http_payload callback. So
6637 * it cannot yield. An exception is returned if it is called from another
6638 * callback.
6639 */
6640__LJMP static int hlua_http_msg_insert_data(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006641{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006642 struct http_msg *msg;
6643 struct filter *filter;
6644 const char *str;
6645 size_t input, output, sz;
6646 int offset;
6647 int ret;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006648
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006649 if (lua_gettop(L) < 2 || lua_gettop(L) > 3)
6650 WILL_LJMP(luaL_error(L, "'insert' expects at least 1 argument and at most 2 arguments"));
6651 MAY_LJMP(check_args(L, 2, "insert"));
6652 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006653
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006654 if (msg->msg_state < HTTP_MSG_DATA)
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006655 WILL_LJMP(lua_error(L));
6656
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006657 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
6658 filter = hlua_http_msg_filter(L, 1, msg, &input, &output);
6659 if (!filter || !hlua_filter_from_payload(filter))
6660 WILL_LJMP(lua_error(L));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006661
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006662 offset = input + output;
6663 if (lua_gettop(L) > 2) {
6664 offset = MAY_LJMP(luaL_checkinteger(L, 3));
6665 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02006666 offset = MAX(0, (int)input + offset);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006667 offset += output;
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006668 if (offset < output || offset > output + input) {
6669 lua_pushfstring(L, "offset out of range.");
6670 WILL_LJMP(lua_error(L));
6671 }
6672 }
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006673
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006674 ret = _hlua_http_msg_insert(msg, filter, ist2(str, sz), offset);
6675 lua_pushinteger(L, ret);
6676 return 1;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006677}
6678
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006679/* Removes a given amount of data from the HTTP message at a given offset. By
6680 * default all DATA blocks are removed. It returns the amount of data
6681 * removed. Unlike the channel function used to remove data, this one can only
6682 * be called inside a filter, from http_payload callback. So it cannot yield. An
6683 * exception is returned if it is called from another callback.
6684 */
6685__LJMP static int hlua_http_msg_del_data(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006686{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006687 struct http_msg *msg;
6688 struct filter *filter;
6689 size_t input, output;
6690 int offset, len;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006691
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006692 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
Boyang Lie0c54352022-05-10 17:47:23 +00006693 WILL_LJMP(luaL_error(L, "'remove' expects at most 2 arguments"));
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006694 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006695
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006696 if (msg->msg_state < HTTP_MSG_DATA)
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006697 WILL_LJMP(lua_error(L));
6698
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006699 filter = hlua_http_msg_filter(L, 1, msg, &input, &output);
6700 if (!filter || !hlua_filter_from_payload(filter))
6701 WILL_LJMP(lua_error(L));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006702
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006703 offset = input + output;
Boyang Lie0c54352022-05-10 17:47:23 +00006704 if (lua_gettop(L) > 1) {
6705 offset = MAY_LJMP(luaL_checkinteger(L, 2));
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006706 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02006707 offset = MAX(0, (int)input + offset);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006708 offset += output;
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006709 if (offset < output || offset > output + input) {
6710 lua_pushfstring(L, "offset out of range.");
6711 WILL_LJMP(lua_error(L));
6712 }
6713 }
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006714
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006715 len = output + input - offset;
Boyang Lie0c54352022-05-10 17:47:23 +00006716 if (lua_gettop(L) == 3) {
6717 len = MAY_LJMP(luaL_checkinteger(L, 3));
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006718 if (!len)
6719 goto end;
6720 if (len == -1)
6721 len = output + input - offset;
6722 if (len < 0 || offset + len > output + input) {
6723 lua_pushfstring(L, "length out of range.");
6724 WILL_LJMP(lua_error(L));
6725 }
6726 }
6727
6728 _hlua_http_msg_delete(msg, filter, offset, len);
6729
6730 end:
6731 lua_pushinteger(L, len);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006732 return 1;
6733}
6734
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006735/* Replaces a given amount of data at the given offset by a string. By default,
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006736 * all remaining data are removed, accordingly to the filter context. It returns
6737 * the amount of data written or -1 if nothing was copied. Unlike the channel
6738 * function used to replace data, this one can only be called inside a filter,
6739 * from http_payload callback. So it cannot yield. An exception is returned if
6740 * it is called from another callback.
6741 */
6742__LJMP static int hlua_http_msg_set_data(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006743{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006744 struct http_msg *msg;
6745 struct filter *filter;
6746 struct htx *htx;
6747 const char *str;
6748 size_t input, output, sz;
6749 int offset, len;
6750 int ret;
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02006751
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006752 if (lua_gettop(L) < 2 || lua_gettop(L) > 4)
6753 WILL_LJMP(luaL_error(L, "'set' expects at least 1 argument and at most 3 arguments"));
6754 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6755
6756 if (msg->msg_state < HTTP_MSG_DATA)
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006757 WILL_LJMP(lua_error(L));
6758
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006759 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
6760 filter = hlua_http_msg_filter(L, 1, msg, &output, &input);
6761 if (!filter || !hlua_filter_from_payload(filter))
6762 WILL_LJMP(lua_error(L));
6763
6764 offset = output;
6765 if (lua_gettop(L) > 2) {
6766 offset = MAY_LJMP(luaL_checkinteger(L, 3));
6767 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02006768 offset = MAX(0, (int)input + offset);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006769 offset += output;
6770 if (offset < output || offset > input + output) {
6771 lua_pushfstring(L, "offset out of range.");
6772 WILL_LJMP(lua_error(L));
6773 }
6774 }
6775
6776 len = output + input - offset;
6777 if (lua_gettop(L) == 4) {
6778 len = MAY_LJMP(luaL_checkinteger(L, 4));
6779 if (!len)
6780 goto set;
6781 if (len == -1)
6782 len = output + input - offset;
6783 if (len < 0 || offset + len > output + input) {
6784 lua_pushfstring(L, "length out of range.");
6785 WILL_LJMP(lua_error(L));
6786 }
6787 }
6788
6789 set:
6790 /* Be sure we can copied the string once input data will be removed. */
6791 htx = htx_from_buf(&msg->chn->buf);
6792 if (sz > htx_free_data_space(htx) + len)
6793 lua_pushinteger(L, -1);
6794 else {
6795 _hlua_http_msg_delete(msg, filter, offset, len);
6796 ret = _hlua_http_msg_insert(msg, filter, ist2(str, sz), offset);
6797 lua_pushinteger(L, ret);
6798 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006799 return 1;
6800}
6801
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006802/* Prepends data into an HTTP message and forward it, from the filter point of
6803 * view. It returns the amount of data written or -1 if nothing was sent. Unlike
6804 * the channel function used to send data, this one can only be called inside a
6805 * filter, from http_payload callback. So it cannot yield. An exception is
6806 * returned if it is called from another callback.
6807 */
6808__LJMP static int hlua_http_msg_send(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006809{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006810 struct http_msg *msg;
6811 struct filter *filter;
6812 struct htx *htx;
6813 const char *str;
6814 size_t offset, len, sz;
6815 int ret;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006816
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006817 MAY_LJMP(check_args(L, 2, "send"));
6818 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6819
6820 if (msg->msg_state < HTTP_MSG_DATA)
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006821 WILL_LJMP(lua_error(L));
6822
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006823 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
6824 filter = hlua_http_msg_filter(L, 1, msg, &offset, &len);
6825 if (!filter || !hlua_filter_from_payload(filter))
6826 WILL_LJMP(lua_error(L));
6827
6828 /* Return an error if the channel's output is closed */
6829 if (unlikely(channel_output_closed(msg->chn))) {
6830 lua_pushinteger(L, -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006831 return 1;
6832 }
6833
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006834 htx = htx_from_buf(&msg->chn->buf);
6835 if (sz > htx_free_data_space(htx)) {
6836 lua_pushinteger(L, -1);
6837 return 1;
6838 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006839
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006840 ret = _hlua_http_msg_insert(msg, filter, ist2(str, sz), offset);
6841 if (ret > 0) {
6842 struct hlua_flt_ctx *flt_ctx = filter->ctx;
6843
6844 FLT_OFF(filter, msg->chn) += ret;
6845 flt_ctx->cur_len[CHN_IDX(msg->chn)] -= ret;
6846 flt_ctx->cur_off[CHN_IDX(msg->chn)] += ret;
6847 }
6848
6849 lua_pushinteger(L, ret);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006850 return 1;
6851}
6852
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006853/* Forwards a given amount of bytes. It return -1 if the channel's output is
6854 * closed. Otherwise, it returns the number of bytes forwarded. Unlike the
6855 * channel function used to forward data, this one can only be called inside a
6856 * filter, from http_payload callback. So it cannot yield. An exception is
6857 * returned if it is called from another callback. All other functions deal with
6858 * DATA block, this one not.
6859*/
6860__LJMP static int hlua_http_msg_forward(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006861{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006862 struct http_msg *msg;
6863 struct filter *filter;
6864 size_t offset, len;
6865 int fwd, ret = 0;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006866
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006867 MAY_LJMP(check_args(L, 2, "forward"));
6868 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6869
6870 if (msg->msg_state < HTTP_MSG_DATA)
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006871 WILL_LJMP(lua_error(L));
6872
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006873 fwd = MAY_LJMP(luaL_checkinteger(L, 2));
6874 filter = hlua_http_msg_filter(L, 1, msg, &offset, &len);
6875 if (!filter || !hlua_filter_from_payload(filter))
6876 WILL_LJMP(lua_error(L));
6877
6878 /* Nothing to do, just return */
6879 if (!fwd)
6880 goto end;
6881
6882 /* Return an error if the channel's output is closed */
6883 if (unlikely(channel_output_closed(msg->chn))) {
6884 ret = -1;
6885 goto end;
6886 }
6887
6888 ret = fwd;
6889 if (ret > len)
6890 ret = len;
6891
6892 if (ret) {
6893 struct hlua_flt_ctx *flt_ctx = filter->ctx;
6894
6895 FLT_OFF(filter, msg->chn) += ret;
6896 flt_ctx->cur_off[CHN_IDX(msg->chn)] += ret;
6897 flt_ctx->cur_len[CHN_IDX(msg->chn)] -= ret;
6898 }
6899
6900 end:
6901 lua_pushinteger(L, ret);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006902 return 1;
6903}
6904
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006905/* Set EOM flag on the HTX message.
6906 *
6907 * NOTE: Not sure it is a good idea to manipulate this flag but for now I don't
6908 * really know how to do without this feature.
6909 */
6910__LJMP static int hlua_http_msg_set_eom(lua_State *L)
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02006911{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006912 struct http_msg *msg;
6913 struct htx *htx;
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02006914
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006915 MAY_LJMP(check_args(L, 1, "set_eom"));
6916 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6917 htx = htxbuf(&msg->chn->buf);
6918 htx->flags |= HTX_FL_EOM;
6919 return 0;
6920}
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006921
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006922/* Unset EOM flag on the HTX message.
6923 *
6924 * NOTE: Not sure it is a good idea to manipulate this flag but for now I don't
6925 * really know how to do without this feature.
6926 */
6927__LJMP static int hlua_http_msg_unset_eom(lua_State *L)
6928{
6929 struct http_msg *msg;
6930 struct htx *htx;
6931
6932 MAY_LJMP(check_args(L, 1, "set_eom"));
6933 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6934 htx = htxbuf(&msg->chn->buf);
6935 htx->flags &= ~HTX_FL_EOM;
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02006936 return 0;
6937}
6938
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006939/*
6940 *
6941 *
William Lallemand3956c4e2021-09-21 16:25:15 +02006942 * Class HTTPClient
6943 *
6944 *
6945 */
6946__LJMP static struct hlua_httpclient *hlua_checkhttpclient(lua_State *L, int ud)
6947{
6948 return MAY_LJMP(hlua_checkudata(L, ud, class_httpclient_ref));
6949}
6950
William Lallemandf77f1de2021-09-28 19:10:38 +02006951
6952/* stops the httpclient and ask it to kill itself */
6953__LJMP static int hlua_httpclient_gc(lua_State *L)
6954{
6955 struct hlua_httpclient *hlua_hc;
6956
6957 MAY_LJMP(check_args(L, 1, "__gc"));
6958
6959 hlua_hc = MAY_LJMP(hlua_checkhttpclient(L, 1));
6960
6961 httpclient_stop_and_destroy(hlua_hc->hc);
6962
6963 hlua_hc->hc = NULL;
6964
6965
6966 return 0;
6967}
6968
6969
William Lallemand3956c4e2021-09-21 16:25:15 +02006970__LJMP static int hlua_httpclient_new(lua_State *L)
6971{
6972 struct hlua_httpclient *hlua_hc;
6973 struct hlua *hlua;
6974
6975 /* Get hlua struct, or NULL if we execute from main lua state */
6976 hlua = hlua_gethlua(L);
6977 if (!hlua)
6978 return 0;
6979
6980 /* Check stack size. */
6981 if (!lua_checkstack(L, 3)) {
6982 hlua_pusherror(L, "httpclient: full stack");
6983 goto err;
6984 }
6985 /* Create the object: obj[0] = userdata. */
6986 lua_newtable(L);
6987 hlua_hc = MAY_LJMP(lua_newuserdata(L, sizeof(*hlua_hc)));
6988 lua_rawseti(L, -2, 0);
6989 memset(hlua_hc, 0, sizeof(*hlua_hc));
6990
6991 hlua_hc->hc = httpclient_new(hlua, 0, IST_NULL);
6992 if (!hlua_hc->hc)
6993 goto err;
6994
6995 /* Pop a class stream metatable and affect it to the userdata. */
6996 lua_rawgeti(L, LUA_REGISTRYINDEX, class_httpclient_ref);
6997 lua_setmetatable(L, -2);
6998
6999 return 1;
7000
7001 err:
7002 WILL_LJMP(lua_error(L));
7003 return 0;
7004}
7005
7006
7007/*
7008 * Callback of the httpclient, this callback wakes the lua task up, once the
7009 * httpclient receives some data
7010 *
7011 */
7012
William Lallemandbd5739e2021-10-28 15:41:38 +02007013static void hlua_httpclient_cb(struct httpclient *hc)
William Lallemand3956c4e2021-09-21 16:25:15 +02007014{
7015 struct hlua *hlua = hc->caller;
7016
7017 if (!hlua || !hlua->task)
7018 return;
7019
7020 task_wakeup(hlua->task, TASK_WOKEN_MSG);
7021}
7022
7023/*
William Lallemandd7df73a2021-09-23 17:54:00 +02007024 * Fill the lua stack with headers from the httpclient response
7025 * This works the same way as the hlua_http_get_headers() function
7026 */
7027__LJMP static int hlua_httpclient_get_headers(lua_State *L, struct hlua_httpclient *hlua_hc)
7028{
7029 struct http_hdr *hdr;
7030
7031 lua_newtable(L);
7032
William Lallemandef574b22021-10-05 16:19:31 +02007033 for (hdr = hlua_hc->hc->res.hdrs; hdr && isttest(hdr->n); hdr++) {
William Lallemandd7df73a2021-09-23 17:54:00 +02007034 struct ist n, v;
7035 int len;
7036
7037 n = hdr->n;
7038 v = hdr->v;
7039
7040 /* Check for existing entry:
7041 * assume that the table is on the top of the stack, and
7042 * push the key in the stack, the function lua_gettable()
7043 * perform the lookup.
7044 */
7045
7046 lua_pushlstring(L, n.ptr, n.len);
7047 lua_gettable(L, -2);
7048
7049 switch (lua_type(L, -1)) {
7050 case LUA_TNIL:
7051 /* Table not found, create it. */
7052 lua_pop(L, 1); /* remove the nil value. */
7053 lua_pushlstring(L, n.ptr, n.len); /* push the header name as key. */
7054 lua_newtable(L); /* create and push empty table. */
7055 lua_pushlstring(L, v.ptr, v.len); /* push header value. */
7056 lua_rawseti(L, -2, 0); /* index header value (pop it). */
7057 lua_rawset(L, -3); /* index new table with header name (pop the values). */
7058 break;
7059
7060 case LUA_TTABLE:
7061 /* Entry found: push the value in the table. */
7062 len = lua_rawlen(L, -1);
7063 lua_pushlstring(L, v.ptr, v.len); /* push header value. */
7064 lua_rawseti(L, -2, len+1); /* index header value (pop it). */
7065 lua_pop(L, 1); /* remove the table (it is stored in the main table). */
7066 break;
7067
7068 default:
7069 /* Other cases are errors. */
7070 hlua_pusherror(L, "internal error during the parsing of headers.");
7071 WILL_LJMP(lua_error(L));
7072 }
7073 }
7074 return 1;
7075}
7076
7077/*
William Lallemand746e6f32021-10-06 10:57:44 +02007078 * Allocate and return an array of http_hdr ist extracted from the <headers> lua table
7079 *
7080 * Caller must free the result
7081 */
7082struct http_hdr *hlua_httpclient_table_to_hdrs(lua_State *L)
7083{
7084 struct http_hdr hdrs[global.tune.max_http_hdr];
7085 struct http_hdr *result = NULL;
7086 uint32_t hdr_num = 0;
7087
7088 lua_pushnil(L);
7089 while (lua_next(L, -2) != 0) {
7090 struct ist name, value;
7091 const char *n, *v;
7092 size_t nlen, vlen;
7093
7094 if (!lua_isstring(L, -2) || !lua_istable(L, -1)) {
7095 /* Skip element if the key is not a string or if the value is not a table */
7096 goto next_hdr;
7097 }
7098
7099 n = lua_tolstring(L, -2, &nlen);
7100 name = ist2(n, nlen);
7101
7102 /* Loop on header's values */
7103 lua_pushnil(L);
7104 while (lua_next(L, -2)) {
7105 if (!lua_isstring(L, -1)) {
7106 /* Skip the value if it is not a string */
7107 goto next_value;
7108 }
7109
7110 v = lua_tolstring(L, -1, &vlen);
7111 value = ist2(v, vlen);
7112 name = ist2(n, nlen);
7113
7114 hdrs[hdr_num].n = istdup(name);
7115 hdrs[hdr_num].v = istdup(value);
7116
7117 hdr_num++;
7118
7119 next_value:
7120 lua_pop(L, 1);
7121 }
7122
7123 next_hdr:
7124 lua_pop(L, 1);
7125
7126 }
7127
7128 if (hdr_num) {
7129 /* alloc and copy the headers in the httpclient struct */
Tim Duesterhus16cc16d2021-11-06 15:14:45 +01007130 result = calloc((hdr_num + 1), sizeof(*result));
William Lallemand746e6f32021-10-06 10:57:44 +02007131 if (!result)
7132 goto skip_headers;
7133 memcpy(result, hdrs, sizeof(struct http_hdr) * (hdr_num + 1));
7134
7135 result[hdr_num].n = IST_NULL;
7136 result[hdr_num].v = IST_NULL;
7137 }
7138
7139skip_headers:
William Lallemand746e6f32021-10-06 10:57:44 +02007140
7141 return result;
7142}
7143
7144
William Lallemandbd5739e2021-10-28 15:41:38 +02007145/*
7146 * For each yield, checks if there is some data in the httpclient and push them
7147 * in the lua buffer, once the httpclient finished its job, push the result on
7148 * the stack
7149 */
7150__LJMP static int hlua_httpclient_rcv_yield(lua_State *L, int status, lua_KContext ctx)
7151{
7152 struct buffer *tr;
7153 int res;
7154 struct hlua *hlua = hlua_gethlua(L);
7155 struct hlua_httpclient *hlua_hc = hlua_checkhttpclient(L, 1);
7156
7157
7158 tr = get_trash_chunk();
7159
7160 res = httpclient_res_xfer(hlua_hc->hc, tr);
7161 luaL_addlstring(&hlua_hc->b, b_orig(tr), res);
7162
7163 if (!httpclient_data(hlua_hc->hc) && httpclient_ended(hlua_hc->hc)) {
7164
7165 luaL_pushresult(&hlua_hc->b);
7166 lua_settable(L, -3);
7167
7168 lua_pushstring(L, "status");
7169 lua_pushinteger(L, hlua_hc->hc->res.status);
7170 lua_settable(L, -3);
7171
7172
7173 lua_pushstring(L, "reason");
7174 lua_pushlstring(L, hlua_hc->hc->res.reason.ptr, hlua_hc->hc->res.reason.len);
7175 lua_settable(L, -3);
7176
7177 lua_pushstring(L, "headers");
7178 hlua_httpclient_get_headers(L, hlua_hc);
7179 lua_settable(L, -3);
7180
7181 return 1;
7182 }
7183
7184 if (httpclient_data(hlua_hc->hc))
7185 task_wakeup(hlua->task, TASK_WOKEN_MSG);
7186
7187 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_httpclient_rcv_yield, TICK_ETERNITY, 0));
7188
7189 return 0;
7190}
7191
7192/*
7193 * Call this when trying to stream a body during a request
7194 */
7195__LJMP static int hlua_httpclient_snd_yield(lua_State *L, int status, lua_KContext ctx)
7196{
7197 struct hlua *hlua;
7198 struct hlua_httpclient *hlua_hc = hlua_checkhttpclient(L, 1);
7199 const char *body_str = NULL;
7200 int ret;
7201 int end = 0;
7202 size_t buf_len;
7203 size_t to_send = 0;
7204
7205 hlua = hlua_gethlua(L);
7206
7207 if (!hlua || !hlua->task)
7208 WILL_LJMP(luaL_error(L, "The 'get' function is only allowed in "
7209 "'frontend', 'backend' or 'task'"));
7210
7211 ret = lua_getfield(L, -1, "body");
7212 if (ret != LUA_TSTRING)
7213 goto rcv;
7214
7215 body_str = lua_tolstring(L, -1, &buf_len);
7216 lua_pop(L, 1);
7217
Christopher Fauletfc591292022-01-12 14:46:03 +01007218 to_send = buf_len - hlua_hc->sent;
William Lallemandbd5739e2021-10-28 15:41:38 +02007219
7220 if ((hlua_hc->sent + to_send) >= buf_len)
7221 end = 1;
7222
7223 /* the end flag is always set since we are using the whole remaining size */
7224 hlua_hc->sent += httpclient_req_xfer(hlua_hc->hc, ist2(body_str + hlua_hc->sent, to_send), end);
7225
7226 if (buf_len > hlua_hc->sent) {
7227 /* still need to process the buffer */
7228 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_httpclient_snd_yield, TICK_ETERNITY, 0));
7229 } else {
7230 goto rcv;
7231 /* we sent the whole request buffer we can recv */
7232 }
7233 return 0;
7234
7235rcv:
7236
7237 /* we return a "res" object */
7238 lua_newtable(L);
7239
William Lallemandbd5739e2021-10-28 15:41:38 +02007240 lua_pushstring(L, "body");
William Lallemandd1187eb2021-11-02 10:40:06 +01007241 luaL_buffinit(L, &hlua_hc->b);
William Lallemandbd5739e2021-10-28 15:41:38 +02007242
William Lallemand933fe392021-11-04 09:45:58 +01007243 task_wakeup(hlua->task, TASK_WOKEN_MSG);
William Lallemandbd5739e2021-10-28 15:41:38 +02007244 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_httpclient_rcv_yield, TICK_ETERNITY, 0));
7245
7246 return 1;
7247}
William Lallemand746e6f32021-10-06 10:57:44 +02007248
William Lallemand3956c4e2021-09-21 16:25:15 +02007249/*
William Lallemanddc2cc902021-10-26 11:43:26 +02007250 * Send an HTTP request and wait for a response
William Lallemand3956c4e2021-09-21 16:25:15 +02007251 */
7252
William Lallemanddc2cc902021-10-26 11:43:26 +02007253__LJMP static int hlua_httpclient_send(lua_State *L, enum http_meth_t meth)
William Lallemand3956c4e2021-09-21 16:25:15 +02007254{
7255 struct hlua_httpclient *hlua_hc;
William Lallemand746e6f32021-10-06 10:57:44 +02007256 struct http_hdr *hdrs = NULL;
7257 struct http_hdr *hdrs_i = NULL;
William Lallemand3956c4e2021-09-21 16:25:15 +02007258 struct hlua *hlua;
William Lallemand746e6f32021-10-06 10:57:44 +02007259 const char *url_str = NULL;
William Lallemanddec25c32021-10-25 19:48:37 +02007260 const char *body_str = NULL;
William Lallemandbd5739e2021-10-28 15:41:38 +02007261 size_t buf_len;
William Lallemand746e6f32021-10-06 10:57:44 +02007262 int ret;
William Lallemand3956c4e2021-09-21 16:25:15 +02007263
7264 hlua = hlua_gethlua(L);
7265
7266 if (!hlua || !hlua->task)
7267 WILL_LJMP(luaL_error(L, "The 'get' function is only allowed in "
7268 "'frontend', 'backend' or 'task'"));
7269
William Lallemand746e6f32021-10-06 10:57:44 +02007270 if (lua_gettop(L) != 2 || lua_type(L, -1) != LUA_TTABLE)
7271 WILL_LJMP(luaL_error(L, "'get' needs a table as argument"));
7272
William Lallemand4f4f2b72022-02-17 20:00:23 +01007273 hlua_hc = hlua_checkhttpclient(L, 1);
7274
William Lallemand7177a952022-03-03 15:33:12 +01007275 lua_pushnil(L); /* first key */
7276 while (lua_next(L, 2)) {
7277 if (strcmp(lua_tostring(L, -2), "dst") == 0) {
7278 if (httpclient_set_dst(hlua_hc->hc, lua_tostring(L, -1)) < 0)
7279 WILL_LJMP(luaL_error(L, "Can't use the 'dst' argument"));
William Lallemand4f4f2b72022-02-17 20:00:23 +01007280
William Lallemand7177a952022-03-03 15:33:12 +01007281 } else if (strcmp(lua_tostring(L, -2), "url") == 0) {
7282 if (lua_type(L, -1) != LUA_TSTRING)
7283 WILL_LJMP(luaL_error(L, "invalid parameter in 'url', must be a string"));
7284 url_str = lua_tostring(L, -1);
William Lallemand3956c4e2021-09-21 16:25:15 +02007285
William Lallemand7177a952022-03-03 15:33:12 +01007286 } else if (strcmp(lua_tostring(L, -2), "timeout") == 0) {
7287 if (lua_type(L, -1) != LUA_TNUMBER)
7288 WILL_LJMP(luaL_error(L, "invalid parameter in 'timeout', must be a number"));
7289 httpclient_set_timeout(hlua_hc->hc, lua_tointeger(L, -1));
William Lallemandb4a4ef62022-02-23 14:18:16 +01007290
William Lallemand7177a952022-03-03 15:33:12 +01007291 } else if (strcmp(lua_tostring(L, -2), "headers") == 0) {
7292 if (lua_type(L, -1) != LUA_TTABLE)
7293 WILL_LJMP(luaL_error(L, "invalid parameter in 'headers', must be a table"));
7294 hdrs = hlua_httpclient_table_to_hdrs(L);
William Lallemand79416cb2021-09-24 14:51:44 +02007295
William Lallemand7177a952022-03-03 15:33:12 +01007296 } else if (strcmp(lua_tostring(L, -2), "body") == 0) {
7297 if (lua_type(L, -1) != LUA_TSTRING)
7298 WILL_LJMP(luaL_error(L, "invalid parameter in 'body', must be a string"));
7299 body_str = lua_tolstring(L, -1, &buf_len);
William Lallemandbd5739e2021-10-28 15:41:38 +02007300
William Lallemand7177a952022-03-03 15:33:12 +01007301 } else {
7302 WILL_LJMP(luaL_error(L, "'%s' invalid parameter name", lua_tostring(L, -2)));
7303 }
7304 /* removes 'value'; keeps 'key' for next iteration */
7305 lua_pop(L, 1);
7306 }
William Lallemanddec25c32021-10-25 19:48:37 +02007307
William Lallemand746e6f32021-10-06 10:57:44 +02007308 if (!url_str) {
7309 WILL_LJMP(luaL_error(L, "'get' need a 'url' argument"));
7310 return 0;
7311 }
William Lallemand3956c4e2021-09-21 16:25:15 +02007312
William Lallemand10a37362022-03-02 16:18:26 +01007313 hlua_hc->sent = 0;
William Lallemand3956c4e2021-09-21 16:25:15 +02007314
7315 hlua_hc->hc->req.url = istdup(ist(url_str));
William Lallemanddc2cc902021-10-26 11:43:26 +02007316 hlua_hc->hc->req.meth = meth;
William Lallemand3956c4e2021-09-21 16:25:15 +02007317
7318 /* update the httpclient callbacks */
William Lallemandbd5739e2021-10-28 15:41:38 +02007319 hlua_hc->hc->ops.res_stline = hlua_httpclient_cb;
7320 hlua_hc->hc->ops.res_headers = hlua_httpclient_cb;
7321 hlua_hc->hc->ops.res_payload = hlua_httpclient_cb;
William Lallemand8f170c72022-03-15 10:52:07 +01007322 hlua_hc->hc->ops.res_end = hlua_httpclient_cb;
William Lallemand3956c4e2021-09-21 16:25:15 +02007323
William Lallemandbd5739e2021-10-28 15:41:38 +02007324 /* a body is available, it will use the request callback */
7325 if (body_str) {
7326 hlua_hc->hc->ops.req_payload = hlua_httpclient_cb;
7327 }
William Lallemand3956c4e2021-09-21 16:25:15 +02007328
William Lallemandbd5739e2021-10-28 15:41:38 +02007329 ret = httpclient_req_gen(hlua_hc->hc, hlua_hc->hc->req.url, meth, hdrs, IST_NULL);
William Lallemand3956c4e2021-09-21 16:25:15 +02007330
William Lallemand746e6f32021-10-06 10:57:44 +02007331 /* free the temporary headers array */
7332 hdrs_i = hdrs;
7333 while (hdrs_i && isttest(hdrs_i->n)) {
7334 istfree(&hdrs_i->n);
7335 istfree(&hdrs_i->v);
7336 hdrs_i++;
7337 }
7338 ha_free(&hdrs);
7339
7340
William Lallemand6137a9e2021-10-26 15:01:53 +02007341 if (ret != ERR_NONE) {
7342 WILL_LJMP(luaL_error(L, "Can't generate the HTTP request"));
7343 return 0;
7344 }
7345
William Lallemandc2d3db42022-04-26 11:46:13 +02007346 if (!httpclient_start(hlua_hc->hc))
7347 WILL_LJMP(luaL_error(L, "couldn't start the httpclient"));
William Lallemand6137a9e2021-10-26 15:01:53 +02007348
William Lallemandbd5739e2021-10-28 15:41:38 +02007349 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_httpclient_snd_yield, TICK_ETERNITY, 0));
William Lallemand3956c4e2021-09-21 16:25:15 +02007350
William Lallemand3956c4e2021-09-21 16:25:15 +02007351 return 0;
7352}
7353
7354/*
William Lallemanddc2cc902021-10-26 11:43:26 +02007355 * Sends an HTTP HEAD request and wait for a response
7356 *
7357 * httpclient:head(url, headers, payload)
7358 */
7359__LJMP static int hlua_httpclient_head(lua_State *L)
7360{
7361 return hlua_httpclient_send(L, HTTP_METH_HEAD);
7362}
7363
7364/*
7365 * Send an HTTP GET request and wait for a response
7366 *
7367 * httpclient:get(url, headers, payload)
7368 */
7369__LJMP static int hlua_httpclient_get(lua_State *L)
7370{
7371 return hlua_httpclient_send(L, HTTP_METH_GET);
7372
7373}
7374
7375/*
7376 * Sends an HTTP PUT request and wait for a response
7377 *
7378 * httpclient:put(url, headers, payload)
7379 */
7380__LJMP static int hlua_httpclient_put(lua_State *L)
7381{
7382 return hlua_httpclient_send(L, HTTP_METH_PUT);
7383}
7384
7385/*
7386 * Send an HTTP POST request and wait for a response
7387 *
7388 * httpclient:post(url, headers, payload)
7389 */
7390__LJMP static int hlua_httpclient_post(lua_State *L)
7391{
7392 return hlua_httpclient_send(L, HTTP_METH_POST);
7393}
7394
7395
7396/*
7397 * Sends an HTTP DELETE request and wait for a response
7398 *
7399 * httpclient:delete(url, headers, payload)
7400 */
7401__LJMP static int hlua_httpclient_delete(lua_State *L)
7402{
7403 return hlua_httpclient_send(L, HTTP_METH_DELETE);
7404}
7405
7406/*
William Lallemand3956c4e2021-09-21 16:25:15 +02007407 *
7408 *
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007409 * Class TXN
7410 *
7411 *
7412 */
7413
7414/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02007415 * a class stream, otherwise it throws an error.
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007416 */
7417__LJMP static struct hlua_txn *hlua_checktxn(lua_State *L, int ud)
7418{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02007419 return MAY_LJMP(hlua_checkudata(L, ud, class_txn_ref));
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007420}
7421
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007422__LJMP static int hlua_set_var(lua_State *L)
7423{
7424 struct hlua_txn *htxn;
7425 const char *name;
7426 size_t len;
7427 struct sample smp;
7428
Tim Duesterhus4e172c92020-05-19 13:49:42 +02007429 if (lua_gettop(L) < 3 || lua_gettop(L) > 4)
7430 WILL_LJMP(luaL_error(L, "'set_var' needs between 3 and 4 arguments"));
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007431
7432 /* It is useles to retrieve the stream, but this function
7433 * runs only in a stream context.
7434 */
7435 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7436 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
7437
7438 /* Converts the third argument in a sample. */
Amaury Denoyellebc0af6a2020-10-29 17:21:20 +01007439 memset(&smp, 0, sizeof(smp));
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007440 hlua_lua2smp(L, 3, &smp);
7441
7442 /* Store the sample in a variable. */
Willy Tarreau7560dd42016-03-10 16:28:58 +01007443 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
Tim Duesterhus4e172c92020-05-19 13:49:42 +02007444
7445 if (lua_gettop(L) == 4 && lua_toboolean(L, 4))
7446 lua_pushboolean(L, vars_set_by_name_ifexist(name, len, &smp) != 0);
7447 else
7448 lua_pushboolean(L, vars_set_by_name(name, len, &smp) != 0);
7449
Tim Duesterhus84ebc132020-05-19 13:49:41 +02007450 return 1;
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007451}
7452
Christopher Faulet85d79c92016-11-09 16:54:56 +01007453__LJMP static int hlua_unset_var(lua_State *L)
7454{
7455 struct hlua_txn *htxn;
7456 const char *name;
7457 size_t len;
7458 struct sample smp;
7459
7460 MAY_LJMP(check_args(L, 2, "unset_var"));
7461
7462 /* It is useles to retrieve the stream, but this function
7463 * runs only in a stream context.
7464 */
7465 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7466 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
7467
7468 /* Unset the variable. */
7469 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
Tim Duesterhus84ebc132020-05-19 13:49:41 +02007470 lua_pushboolean(L, vars_unset_by_name_ifexist(name, len, &smp) != 0);
7471 return 1;
Christopher Faulet85d79c92016-11-09 16:54:56 +01007472}
7473
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007474__LJMP static int hlua_get_var(lua_State *L)
7475{
7476 struct hlua_txn *htxn;
7477 const char *name;
7478 size_t len;
7479 struct sample smp;
7480
7481 MAY_LJMP(check_args(L, 2, "get_var"));
7482
7483 /* It is useles to retrieve the stream, but this function
7484 * runs only in a stream context.
7485 */
7486 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7487 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
7488
Willy Tarreau7560dd42016-03-10 16:28:58 +01007489 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
Willy Tarreaue352b9d2021-09-03 11:52:38 +02007490 if (!vars_get_by_name(name, len, &smp, NULL)) {
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007491 lua_pushnil(L);
7492 return 1;
7493 }
7494
7495 return hlua_smp2lua(L, &smp);
7496}
7497
Willy Tarreau59551662015-03-10 14:23:13 +01007498__LJMP static int hlua_set_priv(lua_State *L)
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007499{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007500 struct hlua *hlua;
7501
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007502 MAY_LJMP(check_args(L, 2, "set_priv"));
7503
Willy Tarreau87b09662015-04-03 00:22:06 +02007504 /* It is useles to retrieve the stream, but this function
7505 * runs only in a stream context.
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007506 */
7507 MAY_LJMP(hlua_checktxn(L, 1));
Thierry Fournier4234dbd2020-11-28 13:18:23 +01007508
7509 /* Get hlua struct, or NULL if we execute from main lua state */
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007510 hlua = hlua_gethlua(L);
Thierry Fournier4234dbd2020-11-28 13:18:23 +01007511 if (!hlua)
7512 return 0;
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007513
7514 /* Remove previous value. */
Thierry FOURNIERe068b602017-04-26 13:27:05 +02007515 luaL_unref(L, LUA_REGISTRYINDEX, hlua->Mref);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007516
7517 /* Get and store new value. */
7518 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
7519 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
7520
7521 return 0;
7522}
7523
Willy Tarreau59551662015-03-10 14:23:13 +01007524__LJMP static int hlua_get_priv(lua_State *L)
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007525{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007526 struct hlua *hlua;
7527
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007528 MAY_LJMP(check_args(L, 1, "get_priv"));
7529
Willy Tarreau87b09662015-04-03 00:22:06 +02007530 /* It is useles to retrieve the stream, but this function
7531 * runs only in a stream context.
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007532 */
7533 MAY_LJMP(hlua_checktxn(L, 1));
Thierry Fournier4234dbd2020-11-28 13:18:23 +01007534
7535 /* Get hlua struct, or NULL if we execute from main lua state */
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007536 hlua = hlua_gethlua(L);
Thierry Fournier4234dbd2020-11-28 13:18:23 +01007537 if (!hlua) {
7538 lua_pushnil(L);
7539 return 1;
7540 }
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007541
7542 /* Push configuration index in the stack. */
7543 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
7544
7545 return 1;
7546}
7547
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007548/* Create stack entry containing a class TXN. This function
7549 * return 0 if the stack does not contains free slots,
7550 * otherwise it returns 1.
7551 */
Thierry FOURNIERab00df62016-07-14 11:42:37 +02007552static int hlua_txn_new(lua_State *L, struct stream *s, struct proxy *p, int dir, int flags)
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007553{
Willy Tarreaude491382015-04-06 11:04:28 +02007554 struct hlua_txn *htxn;
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007555
7556 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01007557 if (!lua_checkstack(L, 3))
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007558 return 0;
7559
7560 /* NOTE: The allocation never fails. The failure
7561 * throw an error, and the function never returns.
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08007562 * if the throw is not available, the process is aborted.
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007563 */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01007564 /* Create the object: obj[0] = userdata. */
7565 lua_newtable(L);
Willy Tarreaude491382015-04-06 11:04:28 +02007566 htxn = lua_newuserdata(L, sizeof(*htxn));
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01007567 lua_rawseti(L, -2, 0);
7568
Willy Tarreaude491382015-04-06 11:04:28 +02007569 htxn->s = s;
7570 htxn->p = p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01007571 htxn->dir = dir;
Thierry FOURNIERab00df62016-07-14 11:42:37 +02007572 htxn->flags = flags;
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007573
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01007574 /* Create the "f" field that contains a list of fetches. */
7575 lua_pushstring(L, "f");
Thierry FOURNIERca988662015-12-20 18:43:03 +01007576 if (!hlua_fetches_new(L, htxn, HLUA_F_MAY_USE_HTTP))
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01007577 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007578 lua_rawset(L, -3);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01007579
7580 /* Create the "sf" field that contains a list of stringsafe fetches. */
7581 lua_pushstring(L, "sf");
Thierry FOURNIERca988662015-12-20 18:43:03 +01007582 if (!hlua_fetches_new(L, htxn, HLUA_F_MAY_USE_HTTP | HLUA_F_AS_STRING))
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01007583 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007584 lua_rawset(L, -3);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01007585
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007586 /* Create the "c" field that contains a list of converters. */
7587 lua_pushstring(L, "c");
Willy Tarreaude491382015-04-06 11:04:28 +02007588 if (!hlua_converters_new(L, htxn, 0))
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01007589 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007590 lua_rawset(L, -3);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01007591
7592 /* Create the "sc" field that contains a list of stringsafe converters. */
7593 lua_pushstring(L, "sc");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01007594 if (!hlua_converters_new(L, htxn, HLUA_F_AS_STRING))
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007595 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007596 lua_rawset(L, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007597
Thierry FOURNIER397826a2015-03-11 19:39:09 +01007598 /* Create the "req" field that contains the request channel object. */
7599 lua_pushstring(L, "req");
Willy Tarreau2a71af42015-03-10 13:51:50 +01007600 if (!hlua_channel_new(L, &s->req))
Thierry FOURNIER397826a2015-03-11 19:39:09 +01007601 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007602 lua_rawset(L, -3);
Thierry FOURNIER397826a2015-03-11 19:39:09 +01007603
7604 /* Create the "res" field that contains the response channel object. */
7605 lua_pushstring(L, "res");
Willy Tarreau2a71af42015-03-10 13:51:50 +01007606 if (!hlua_channel_new(L, &s->res))
Thierry FOURNIER397826a2015-03-11 19:39:09 +01007607 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007608 lua_rawset(L, -3);
Thierry FOURNIER397826a2015-03-11 19:39:09 +01007609
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007610 /* Creates the HTTP object is the current proxy allows http. */
7611 lua_pushstring(L, "http");
Christopher Faulet1bb6afa2021-03-08 17:57:53 +01007612 if (IS_HTX_STRM(s)) {
Willy Tarreaude491382015-04-06 11:04:28 +02007613 if (!hlua_http_new(L, htxn))
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007614 return 0;
7615 }
7616 else
7617 lua_pushnil(L);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007618 lua_rawset(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007619
Christopher Faulet78c35472020-02-26 17:14:08 +01007620 if ((htxn->flags & HLUA_TXN_CTX_MASK) == HLUA_TXN_FLT_CTX) {
7621 /* HTTPMessage object are created when a lua TXN is created from
7622 * a filter context only
7623 */
7624
7625 /* Creates the HTTP-Request object is the current proxy allows http. */
7626 lua_pushstring(L, "http_req");
7627 if (p->mode == PR_MODE_HTTP) {
7628 if (!hlua_http_msg_new(L, &s->txn->req))
7629 return 0;
7630 }
7631 else
7632 lua_pushnil(L);
7633 lua_rawset(L, -3);
7634
7635 /* Creates the HTTP-Response object is the current proxy allows http. */
7636 lua_pushstring(L, "http_res");
7637 if (p->mode == PR_MODE_HTTP) {
7638 if (!hlua_http_msg_new(L, &s->txn->rsp))
7639 return 0;
7640 }
7641 else
7642 lua_pushnil(L);
7643 lua_rawset(L, -3);
7644 }
7645
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007646 /* Pop a class sesison metatable and affect it to the userdata. */
7647 lua_rawgeti(L, LUA_REGISTRYINDEX, class_txn_ref);
7648 lua_setmetatable(L, -2);
7649
7650 return 1;
7651}
7652
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01007653__LJMP static int hlua_txn_deflog(lua_State *L)
7654{
7655 const char *msg;
7656 struct hlua_txn *htxn;
7657
7658 MAY_LJMP(check_args(L, 2, "deflog"));
7659 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7660 msg = MAY_LJMP(luaL_checkstring(L, 2));
7661
7662 hlua_sendlog(htxn->s->be, htxn->s->logs.level, msg);
7663 return 0;
7664}
7665
7666__LJMP static int hlua_txn_log(lua_State *L)
7667{
7668 int level;
7669 const char *msg;
7670 struct hlua_txn *htxn;
7671
7672 MAY_LJMP(check_args(L, 3, "log"));
7673 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7674 level = MAY_LJMP(luaL_checkinteger(L, 2));
7675 msg = MAY_LJMP(luaL_checkstring(L, 3));
7676
7677 if (level < 0 || level >= NB_LOG_LEVELS)
7678 WILL_LJMP(luaL_argerror(L, 1, "Invalid loglevel."));
7679
7680 hlua_sendlog(htxn->s->be, level, msg);
7681 return 0;
7682}
7683
7684__LJMP static int hlua_txn_log_debug(lua_State *L)
7685{
7686 const char *msg;
7687 struct hlua_txn *htxn;
7688
7689 MAY_LJMP(check_args(L, 2, "Debug"));
7690 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7691 msg = MAY_LJMP(luaL_checkstring(L, 2));
7692 hlua_sendlog(htxn->s->be, LOG_DEBUG, msg);
7693 return 0;
7694}
7695
7696__LJMP static int hlua_txn_log_info(lua_State *L)
7697{
7698 const char *msg;
7699 struct hlua_txn *htxn;
7700
7701 MAY_LJMP(check_args(L, 2, "Info"));
7702 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7703 msg = MAY_LJMP(luaL_checkstring(L, 2));
7704 hlua_sendlog(htxn->s->be, LOG_INFO, msg);
7705 return 0;
7706}
7707
7708__LJMP static int hlua_txn_log_warning(lua_State *L)
7709{
7710 const char *msg;
7711 struct hlua_txn *htxn;
7712
7713 MAY_LJMP(check_args(L, 2, "Warning"));
7714 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7715 msg = MAY_LJMP(luaL_checkstring(L, 2));
7716 hlua_sendlog(htxn->s->be, LOG_WARNING, msg);
7717 return 0;
7718}
7719
7720__LJMP static int hlua_txn_log_alert(lua_State *L)
7721{
7722 const char *msg;
7723 struct hlua_txn *htxn;
7724
7725 MAY_LJMP(check_args(L, 2, "Alert"));
7726 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7727 msg = MAY_LJMP(luaL_checkstring(L, 2));
7728 hlua_sendlog(htxn->s->be, LOG_ALERT, msg);
7729 return 0;
7730}
7731
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01007732__LJMP static int hlua_txn_set_loglevel(lua_State *L)
7733{
7734 struct hlua_txn *htxn;
7735 int ll;
7736
7737 MAY_LJMP(check_args(L, 2, "set_loglevel"));
7738 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7739 ll = MAY_LJMP(luaL_checkinteger(L, 2));
7740
7741 if (ll < 0 || ll > 7)
7742 WILL_LJMP(luaL_argerror(L, 2, "Bad log level. It must be between 0 and 7"));
7743
7744 htxn->s->logs.level = ll;
7745 return 0;
7746}
7747
7748__LJMP static int hlua_txn_set_tos(lua_State *L)
7749{
7750 struct hlua_txn *htxn;
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01007751 int tos;
7752
7753 MAY_LJMP(check_args(L, 2, "set_tos"));
7754 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7755 tos = MAY_LJMP(luaL_checkinteger(L, 2));
7756
Willy Tarreau1a18b542018-12-11 16:37:42 +01007757 conn_set_tos(objt_conn(htxn->s->sess->origin), tos);
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01007758 return 0;
7759}
7760
7761__LJMP static int hlua_txn_set_mark(lua_State *L)
7762{
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01007763 struct hlua_txn *htxn;
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01007764 int mark;
7765
7766 MAY_LJMP(check_args(L, 2, "set_mark"));
7767 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7768 mark = MAY_LJMP(luaL_checkinteger(L, 2));
7769
Lukas Tribus579e3e32019-08-11 18:03:45 +02007770 conn_set_mark(objt_conn(htxn->s->sess->origin), mark);
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01007771 return 0;
7772}
7773
Patrick Hemmer268a7072018-05-11 12:52:31 -04007774__LJMP static int hlua_txn_set_priority_class(lua_State *L)
7775{
7776 struct hlua_txn *htxn;
7777
7778 MAY_LJMP(check_args(L, 2, "set_priority_class"));
7779 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7780 htxn->s->priority_class = queue_limit_class(MAY_LJMP(luaL_checkinteger(L, 2)));
7781 return 0;
7782}
7783
7784__LJMP static int hlua_txn_set_priority_offset(lua_State *L)
7785{
7786 struct hlua_txn *htxn;
7787
7788 MAY_LJMP(check_args(L, 2, "set_priority_offset"));
7789 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7790 htxn->s->priority_offset = queue_limit_offset(MAY_LJMP(luaL_checkinteger(L, 2)));
7791 return 0;
7792}
7793
Christopher Faulet700d9e82020-01-31 12:21:52 +01007794/* Forward the Reply object to the client. This function converts the reply in
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05007795 * HTX an push it to into the response channel. It is response to forward the
Christopher Faulet700d9e82020-01-31 12:21:52 +01007796 * message and terminate the transaction. It returns 1 on success and 0 on
7797 * error. The Reply must be on top of the stack.
7798 */
7799__LJMP static int hlua_txn_forward_reply(lua_State *L, struct stream *s)
7800{
7801 struct htx *htx;
7802 struct htx_sl *sl;
7803 struct h1m h1m;
7804 const char *status, *reason, *body;
7805 size_t status_len, reason_len, body_len;
7806 int ret, code, flags;
7807
7808 code = 200;
7809 status = "200";
7810 status_len = 3;
7811 ret = lua_getfield(L, -1, "status");
7812 if (ret == LUA_TNUMBER) {
7813 code = lua_tointeger(L, -1);
7814 status = lua_tolstring(L, -1, &status_len);
7815 }
7816 lua_pop(L, 1);
7817
7818 reason = http_get_reason(code);
7819 reason_len = strlen(reason);
7820 ret = lua_getfield(L, -1, "reason");
7821 if (ret == LUA_TSTRING)
7822 reason = lua_tolstring(L, -1, &reason_len);
7823 lua_pop(L, 1);
7824
7825 body = NULL;
7826 body_len = 0;
7827 ret = lua_getfield(L, -1, "body");
7828 if (ret == LUA_TSTRING)
7829 body = lua_tolstring(L, -1, &body_len);
7830 lua_pop(L, 1);
7831
7832 /* Prepare the response before inserting the headers */
7833 h1m_init_res(&h1m);
7834 htx = htx_from_buf(&s->res.buf);
7835 channel_htx_truncate(&s->res, htx);
7836 if (s->txn->req.flags & HTTP_MSGF_VER_11) {
7837 flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11);
7838 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.1"),
7839 ist2(status, status_len), ist2(reason, reason_len));
7840 }
7841 else {
7842 flags = HTX_SL_F_IS_RESP;
7843 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.0"),
7844 ist2(status, status_len), ist2(reason, reason_len));
7845 }
7846 if (!sl)
7847 goto fail;
7848 sl->info.res.status = code;
7849
7850 /* Push in the stack the "headers" entry. */
7851 ret = lua_getfield(L, -1, "headers");
7852 if (ret != LUA_TTABLE)
7853 goto skip_headers;
7854
7855 lua_pushnil(L);
7856 while (lua_next(L, -2) != 0) {
7857 struct ist name, value;
7858 const char *n, *v;
7859 size_t nlen, vlen;
7860
7861 if (!lua_isstring(L, -2) || !lua_istable(L, -1)) {
7862 /* Skip element if the key is not a string or if the value is not a table */
7863 goto next_hdr;
7864 }
7865
7866 n = lua_tolstring(L, -2, &nlen);
7867 name = ist2(n, nlen);
7868 if (isteqi(name, ist("content-length"))) {
7869 /* Always skip content-length header. It will be added
7870 * later with the correct len
7871 */
7872 goto next_hdr;
7873 }
7874
7875 /* Loop on header's values */
7876 lua_pushnil(L);
7877 while (lua_next(L, -2)) {
7878 if (!lua_isstring(L, -1)) {
7879 /* Skip the value if it is not a string */
7880 goto next_value;
7881 }
7882
7883 v = lua_tolstring(L, -1, &vlen);
7884 value = ist2(v, vlen);
7885
7886 if (isteqi(name, ist("transfer-encoding")))
7887 h1_parse_xfer_enc_header(&h1m, value);
7888 if (!htx_add_header(htx, ist2(n, nlen), ist2(v, vlen)))
7889 goto fail;
7890
7891 next_value:
7892 lua_pop(L, 1);
7893 }
7894
7895 next_hdr:
7896 lua_pop(L, 1);
7897 }
7898 skip_headers:
7899 lua_pop(L, 1);
7900
7901 /* Update h1m flags: CLEN is set if CHNK is not present */
7902 if (!(h1m.flags & H1_MF_CHNK)) {
7903 const char *clen = ultoa(body_len);
7904
7905 h1m.flags |= H1_MF_CLEN;
7906 if (!htx_add_header(htx, ist("content-length"), ist(clen)))
7907 goto fail;
7908 }
7909 if (h1m.flags & (H1_MF_CLEN|H1_MF_CHNK))
7910 h1m.flags |= H1_MF_XFER_LEN;
7911
7912 /* Update HTX start-line flags */
7913 if (h1m.flags & H1_MF_XFER_ENC)
7914 flags |= HTX_SL_F_XFER_ENC;
7915 if (h1m.flags & H1_MF_XFER_LEN) {
7916 flags |= HTX_SL_F_XFER_LEN;
7917 if (h1m.flags & H1_MF_CHNK)
7918 flags |= HTX_SL_F_CHNK;
7919 else if (h1m.flags & H1_MF_CLEN)
7920 flags |= HTX_SL_F_CLEN;
7921 if (h1m.body_len == 0)
7922 flags |= HTX_SL_F_BODYLESS;
7923 }
7924 sl->flags |= flags;
7925
7926
7927 if (!htx_add_endof(htx, HTX_BLK_EOH) ||
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01007928 (body_len && !htx_add_data_atonce(htx, ist2(body, body_len))))
Christopher Faulet700d9e82020-01-31 12:21:52 +01007929 goto fail;
7930
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01007931 htx->flags |= HTX_FL_EOM;
7932
Christopher Faulet700d9e82020-01-31 12:21:52 +01007933 /* Now, forward the response and terminate the transaction */
7934 s->txn->status = code;
7935 htx_to_buf(htx, &s->res.buf);
7936 if (!http_forward_proxy_resp(s, 1))
7937 goto fail;
7938
7939 return 1;
7940
7941 fail:
7942 channel_htx_truncate(&s->res, htx);
7943 return 0;
7944}
7945
7946/* Terminate a transaction if called from a lua action. For TCP streams,
7947 * processing is just aborted. Nothing is returned to the client and all
7948 * arguments are ignored. For HTTP streams, if a reply is passed as argument, it
7949 * is forwarded to the client before terminating the transaction. On success,
7950 * the function exits with ACT_RET_DONE code. If an error occurred, it exits
7951 * with ACT_RET_ERR code. If this function is not called from a lua action, it
7952 * just exits without any processing.
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01007953 */
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02007954__LJMP static int hlua_txn_done(lua_State *L)
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01007955{
Willy Tarreaub2ccb562015-04-06 11:11:15 +02007956 struct hlua_txn *htxn;
Christopher Faulet700d9e82020-01-31 12:21:52 +01007957 struct stream *s;
7958 int finst;
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01007959
Willy Tarreaub2ccb562015-04-06 11:11:15 +02007960 htxn = MAY_LJMP(hlua_checktxn(L, 1));
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01007961
Christopher Faulet700d9e82020-01-31 12:21:52 +01007962 /* If the flags NOTERM is set, we cannot terminate the session, so we
7963 * just end the execution of the current lua code. */
7964 if (htxn->flags & HLUA_TXN_NOTERM)
Thierry FOURNIERab00df62016-07-14 11:42:37 +02007965 WILL_LJMP(hlua_done(L));
Thierry FOURNIERab00df62016-07-14 11:42:37 +02007966
Christopher Faulet700d9e82020-01-31 12:21:52 +01007967 s = htxn->s;
Christopher Fauletd8f0e072020-02-25 09:45:51 +01007968 if (!IS_HTX_STRM(htxn->s)) {
Christopher Faulet700d9e82020-01-31 12:21:52 +01007969 struct channel *req = &s->req;
7970 struct channel *res = &s->res;
Willy Tarreau81389672015-03-10 12:03:52 +01007971
Christopher Faulet700d9e82020-01-31 12:21:52 +01007972 channel_auto_read(req);
7973 channel_abort(req);
7974 channel_auto_close(req);
7975 channel_erase(req);
7976
7977 res->wex = tick_add_ifset(now_ms, res->wto);
7978 channel_auto_read(res);
7979 channel_auto_close(res);
7980 channel_shutr_now(res);
7981
7982 finst = ((htxn->dir == SMP_OPT_DIR_REQ) ? SF_FINST_R : SF_FINST_D);
7983 goto done;
Christopher Fauletfe6a71b2019-07-26 16:40:24 +02007984 }
Thierry FOURNIER10ec2142015-08-24 17:23:45 +02007985
Christopher Faulet700d9e82020-01-31 12:21:52 +01007986 if (lua_gettop(L) == 1 || !lua_istable(L, 2)) {
7987 /* No reply or invalid reply */
7988 s->txn->status = 0;
7989 http_reply_and_close(s, 0, NULL);
7990 }
7991 else {
7992 /* Remove extra args to have the reply on top of the stack */
7993 if (lua_gettop(L) > 2)
7994 lua_pop(L, lua_gettop(L) - 2);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01007995
Christopher Faulet700d9e82020-01-31 12:21:52 +01007996 if (!hlua_txn_forward_reply(L, s)) {
7997 if (!(s->flags & SF_ERR_MASK))
7998 s->flags |= SF_ERR_PRXCOND;
7999 lua_pushinteger(L, ACT_RET_ERR);
8000 WILL_LJMP(hlua_done(L));
8001 return 0; /* Never reached */
8002 }
Christopher Faulet4d0e2632019-07-16 10:52:40 +02008003 }
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02008004
Christopher Faulet700d9e82020-01-31 12:21:52 +01008005 finst = ((htxn->dir == SMP_OPT_DIR_REQ) ? SF_FINST_R : SF_FINST_H);
8006 if (htxn->dir == SMP_OPT_DIR_REQ) {
8007 /* let's log the request time */
8008 s->logs.tv_request = now;
8009 if (s->sess->fe == s->be) /* report it if the request was intercepted by the frontend */
Willy Tarreau4781b152021-04-06 13:53:36 +02008010 _HA_ATOMIC_INC(&s->sess->fe->fe_counters.intercepted_req);
Christopher Faulet700d9e82020-01-31 12:21:52 +01008011 }
Christopher Fauletfe6a71b2019-07-26 16:40:24 +02008012
Christopher Faulet700d9e82020-01-31 12:21:52 +01008013 done:
8014 if (!(s->flags & SF_ERR_MASK))
8015 s->flags |= SF_ERR_LOCAL;
8016 if (!(s->flags & SF_FINST_MASK))
8017 s->flags |= finst;
Christopher Fauletfe6a71b2019-07-26 16:40:24 +02008018
Christopher Faulete48d1dc2021-08-13 14:11:17 +02008019 if ((htxn->flags & HLUA_TXN_CTX_MASK) == HLUA_TXN_FLT_CTX)
8020 lua_pushinteger(L, -1);
8021 else
8022 lua_pushinteger(L, ACT_RET_ABRT);
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02008023 WILL_LJMP(hlua_done(L));
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01008024 return 0;
8025}
8026
Christopher Faulet700d9e82020-01-31 12:21:52 +01008027/*
8028 *
8029 *
8030 * Class REPLY
8031 *
8032 *
8033 */
8034
8035/* Pushes the TXN reply onto the top of the stack. If the stask does not have a
8036 * free slots, the function fails and returns 0;
8037 */
8038static int hlua_txn_reply_new(lua_State *L)
8039{
8040 struct hlua_txn *htxn;
8041 const char *reason, *body = NULL;
8042 int ret, status;
8043
8044 htxn = MAY_LJMP(hlua_checktxn(L, 1));
Christopher Fauletd8f0e072020-02-25 09:45:51 +01008045 if (!IS_HTX_STRM(htxn->s)) {
Christopher Faulet700d9e82020-01-31 12:21:52 +01008046 hlua_pusherror(L, "txn object is not an HTTP transaction.");
8047 WILL_LJMP(lua_error(L));
8048 }
8049
8050 /* Default value */
8051 status = 200;
8052 reason = http_get_reason(status);
8053
8054 if (lua_istable(L, 2)) {
8055 /* load status and reason from the table argument at index 2 */
8056 ret = lua_getfield(L, 2, "status");
8057 if (ret == LUA_TNIL)
8058 goto reason;
8059 else if (ret != LUA_TNUMBER) {
8060 /* invalid status: ignore the reason */
8061 goto body;
8062 }
8063 status = lua_tointeger(L, -1);
8064
8065 reason:
8066 lua_pop(L, 1); /* restore the stack: remove status */
8067 ret = lua_getfield(L, 2, "reason");
8068 if (ret == LUA_TSTRING)
8069 reason = lua_tostring(L, -1);
8070
8071 body:
8072 lua_pop(L, 1); /* restore the stack: remove invalid status or reason */
8073 ret = lua_getfield(L, 2, "body");
8074 if (ret == LUA_TSTRING)
8075 body = lua_tostring(L, -1);
8076 lua_pop(L, 1); /* restore the stack: remove body */
8077 }
8078
8079 /* Create the Reply table */
8080 lua_newtable(L);
8081
8082 /* Add status element */
8083 lua_pushstring(L, "status");
8084 lua_pushinteger(L, status);
8085 lua_settable(L, -3);
8086
8087 /* Add reason element */
8088 reason = http_get_reason(status);
8089 lua_pushstring(L, "reason");
8090 lua_pushstring(L, reason);
8091 lua_settable(L, -3);
8092
8093 /* Add body element, nil if undefined */
8094 lua_pushstring(L, "body");
8095 if (body)
8096 lua_pushstring(L, body);
8097 else
8098 lua_pushnil(L);
8099 lua_settable(L, -3);
8100
8101 /* Add headers element */
8102 lua_pushstring(L, "headers");
8103 lua_newtable(L);
8104
8105 /* stack: [ txn, <Arg:table>, <Reply:table>, "headers", <headers:table> ] */
8106 if (lua_istable(L, 2)) {
8107 /* load headers from the table argument at index 2. If it is a table, copy it. */
8108 ret = lua_getfield(L, 2, "headers");
8109 if (ret == LUA_TTABLE) {
8110 /* stack: [ ... <headers:table>, <table> ] */
8111 lua_pushnil(L);
8112 while (lua_next(L, -2) != 0) {
8113 /* stack: [ ... <headers:table>, <table>, k, v] */
8114 if (!lua_isstring(L, -1) && !lua_istable(L, -1)) {
8115 /* invalid value type, skip it */
8116 lua_pop(L, 1);
8117 continue;
8118 }
8119
8120
8121 /* Duplicate the key and swap it with the value. */
8122 lua_pushvalue(L, -2);
8123 lua_insert(L, -2);
8124 /* stack: [ ... <headers:table>, <table>, k, k, v ] */
8125
8126 lua_newtable(L);
8127 lua_insert(L, -2);
8128 /* stack: [ ... <headers:table>, <table>, k, k, <inner:table>, v ] */
8129
8130 if (lua_isstring(L, -1)) {
8131 /* push the value in the inner table */
8132 lua_rawseti(L, -2, 1);
8133 }
8134 else { /* table */
8135 lua_pushnil(L);
8136 while (lua_next(L, -2) != 0) {
8137 /* stack: [ ... <headers:table>, <table>, k, k, <inner:table>, <v:table>, k2, v2 ] */
8138 if (!lua_isstring(L, -1)) {
8139 /* invalid value type, skip it*/
8140 lua_pop(L, 1);
8141 continue;
8142 }
8143 /* push the value in the inner table */
8144 lua_rawseti(L, -4, lua_rawlen(L, -4) + 1);
8145 /* stack: [ ... <headers:table>, <table>, k, k, <inner:table>, <v:table>, k2 ] */
8146 }
8147 lua_pop(L, 1);
8148 /* stack: [ ... <headers:table>, <table>, k, k, <inner:table> ] */
8149 }
8150
8151 /* push (k,v) on the stack in the headers table:
8152 * stack: [ ... <headers:table>, <table>, k, k, v ]
8153 */
8154 lua_settable(L, -5);
8155 /* stack: [ ... <headers:table>, <table>, k ] */
8156 }
8157 }
8158 lua_pop(L, 1);
8159 }
8160 /* stack: [ txn, <Arg:table>, <Reply:table>, "headers", <headers:table> ] */
8161 lua_settable(L, -3);
8162 /* stack: [ txn, <Arg:table>, <Reply:table> ] */
8163
8164 /* Pop a class sesison metatable and affect it to the userdata. */
8165 lua_rawgeti(L, LUA_REGISTRYINDEX, class_txn_reply_ref);
8166 lua_setmetatable(L, -2);
8167 return 1;
8168}
8169
8170/* Set the reply status code, and optionally the reason. If no reason is
8171 * provided, the default one corresponding to the status code is used.
8172 */
8173__LJMP static int hlua_txn_reply_set_status(lua_State *L)
8174{
8175 int status = MAY_LJMP(luaL_checkinteger(L, 2));
8176 const char *reason = MAY_LJMP(luaL_optlstring(L, 3, NULL, NULL));
8177
8178 /* First argument (self) must be a table */
8179 luaL_checktype(L, 1, LUA_TTABLE);
8180
8181 if (status < 100 || status > 599) {
8182 lua_pushboolean(L, 0);
8183 return 1;
8184 }
8185 if (!reason)
8186 reason = http_get_reason(status);
8187
8188 lua_pushinteger(L, status);
8189 lua_setfield(L, 1, "status");
8190
8191 lua_pushstring(L, reason);
8192 lua_setfield(L, 1, "reason");
8193
8194 lua_pushboolean(L, 1);
8195 return 1;
8196}
8197
8198/* Add a header into the reply object. Each header name is associated to an
8199 * array of values in the "headers" table. If the header name is not found, a
8200 * new entry is created.
8201 */
8202__LJMP static int hlua_txn_reply_add_header(lua_State *L)
8203{
8204 const char *name = MAY_LJMP(luaL_checkstring(L, 2));
8205 const char *value = MAY_LJMP(luaL_checkstring(L, 3));
8206 int ret;
8207
8208 /* First argument (self) must be a table */
8209 luaL_checktype(L, 1, LUA_TTABLE);
8210
8211 /* Push in the stack the "headers" entry. */
8212 ret = lua_getfield(L, 1, "headers");
8213 if (ret != LUA_TTABLE) {
8214 hlua_pusherror(L, "Reply['headers'] is expected to a an array. %s found", lua_typename(L, ret));
8215 WILL_LJMP(lua_error(L));
8216 }
8217
8218 /* check if the header is already registered. If not, register it. */
8219 ret = lua_getfield(L, -1, name);
8220 if (ret == LUA_TNIL) {
8221 /* Entry not found. */
8222 lua_pop(L, 1); /* remove the nil. The "headers" table is the top of the stack. */
8223
8224 /* Insert the new header name in the array in the top of the stack.
8225 * It left the new array in the top of the stack.
8226 */
8227 lua_newtable(L);
8228 lua_pushstring(L, name);
8229 lua_pushvalue(L, -2);
8230 lua_settable(L, -4);
8231 }
8232 else if (ret != LUA_TTABLE) {
8233 hlua_pusherror(L, "Reply['headers']['%s'] is expected to be an array. %s found", name, lua_typename(L, ret));
8234 WILL_LJMP(lua_error(L));
8235 }
8236
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -07008237 /* Now the top of thestack is an array of values. We push
Christopher Faulet700d9e82020-01-31 12:21:52 +01008238 * the header value as new entry.
8239 */
8240 lua_pushstring(L, value);
8241 ret = lua_rawlen(L, -2);
8242 lua_rawseti(L, -2, ret + 1);
8243
8244 lua_pushboolean(L, 1);
8245 return 1;
8246}
8247
8248/* Remove all occurrences of a given header name. */
8249__LJMP static int hlua_txn_reply_del_header(lua_State *L)
8250{
8251 const char *name = MAY_LJMP(luaL_checkstring(L, 2));
8252 int ret;
8253
8254 /* First argument (self) must be a table */
8255 luaL_checktype(L, 1, LUA_TTABLE);
8256
8257 /* Push in the stack the "headers" entry. */
8258 ret = lua_getfield(L, 1, "headers");
8259 if (ret != LUA_TTABLE) {
8260 hlua_pusherror(L, "Reply['headers'] is expected to be an array. %s found", lua_typename(L, ret));
8261 WILL_LJMP(lua_error(L));
8262 }
8263
8264 lua_pushstring(L, name);
8265 lua_pushnil(L);
8266 lua_settable(L, -3);
8267
8268 lua_pushboolean(L, 1);
8269 return 1;
8270}
8271
8272/* Set the reply's body. Overwrite any existing entry. */
8273__LJMP static int hlua_txn_reply_set_body(lua_State *L)
8274{
8275 const char *payload = MAY_LJMP(luaL_checkstring(L, 2));
8276
8277 /* First argument (self) must be a table */
8278 luaL_checktype(L, 1, LUA_TTABLE);
8279
8280 lua_pushstring(L, payload);
8281 lua_setfield(L, 1, "body");
8282
8283 lua_pushboolean(L, 1);
8284 return 1;
8285}
8286
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01008287__LJMP static int hlua_log(lua_State *L)
8288{
8289 int level;
8290 const char *msg;
8291
8292 MAY_LJMP(check_args(L, 2, "log"));
8293 level = MAY_LJMP(luaL_checkinteger(L, 1));
8294 msg = MAY_LJMP(luaL_checkstring(L, 2));
8295
8296 if (level < 0 || level >= NB_LOG_LEVELS)
8297 WILL_LJMP(luaL_argerror(L, 1, "Invalid loglevel."));
8298
8299 hlua_sendlog(NULL, level, msg);
8300 return 0;
8301}
8302
8303__LJMP static int hlua_log_debug(lua_State *L)
8304{
8305 const char *msg;
8306
8307 MAY_LJMP(check_args(L, 1, "debug"));
8308 msg = MAY_LJMP(luaL_checkstring(L, 1));
8309 hlua_sendlog(NULL, LOG_DEBUG, msg);
8310 return 0;
8311}
8312
8313__LJMP static int hlua_log_info(lua_State *L)
8314{
8315 const char *msg;
8316
8317 MAY_LJMP(check_args(L, 1, "info"));
8318 msg = MAY_LJMP(luaL_checkstring(L, 1));
8319 hlua_sendlog(NULL, LOG_INFO, msg);
8320 return 0;
8321}
8322
8323__LJMP static int hlua_log_warning(lua_State *L)
8324{
8325 const char *msg;
8326
8327 MAY_LJMP(check_args(L, 1, "warning"));
8328 msg = MAY_LJMP(luaL_checkstring(L, 1));
8329 hlua_sendlog(NULL, LOG_WARNING, msg);
8330 return 0;
8331}
8332
8333__LJMP static int hlua_log_alert(lua_State *L)
8334{
8335 const char *msg;
8336
8337 MAY_LJMP(check_args(L, 1, "alert"));
8338 msg = MAY_LJMP(luaL_checkstring(L, 1));
8339 hlua_sendlog(NULL, LOG_ALERT, msg);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01008340 return 0;
8341}
8342
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01008343__LJMP static int hlua_sleep_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008344{
8345 int wakeup_ms = lua_tointeger(L, -1);
Willy Tarreau12c02702021-09-30 16:12:31 +02008346 if (!tick_is_expired(wakeup_ms, now_ms))
Willy Tarreau9635e032018-10-16 17:52:55 +02008347 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008348 return 0;
8349}
8350
8351__LJMP static int hlua_sleep(lua_State *L)
8352{
8353 unsigned int delay;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008354 unsigned int wakeup_ms;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008355
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008356 MAY_LJMP(check_args(L, 1, "sleep"));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008357
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01008358 delay = MAY_LJMP(luaL_checkinteger(L, 1)) * 1000;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008359 wakeup_ms = tick_add(now_ms, delay);
8360 lua_pushinteger(L, wakeup_ms);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008361
Willy Tarreau9635e032018-10-16 17:52:55 +02008362 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008363 return 0;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008364}
8365
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008366__LJMP static int hlua_msleep(lua_State *L)
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008367{
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, "msleep"));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008372
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01008373 delay = MAY_LJMP(luaL_checkinteger(L, 1));
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 FOURNIER13416fe2015-02-17 15:01:59 +01008381/* This functionis an LUA binding. it permits to give back
8382 * the hand at the HAProxy scheduler. It is used when the
8383 * LUA processing consumes a lot of time.
8384 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01008385__LJMP static int hlua_yield_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008386{
8387 return 0;
8388}
8389
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01008390__LJMP static int hlua_yield(lua_State *L)
8391{
Willy Tarreau9635e032018-10-16 17:52:55 +02008392 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_yield_yield, TICK_ETERNITY, HLUA_CTRLYIELD));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008393 return 0;
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01008394}
8395
Thierry FOURNIER37196f42015-02-16 19:34:56 +01008396/* This function change the nice of the currently executed
8397 * task. It is used set low or high priority at the current
8398 * task.
8399 */
Willy Tarreau59551662015-03-10 14:23:13 +01008400__LJMP static int hlua_set_nice(lua_State *L)
Thierry FOURNIER37196f42015-02-16 19:34:56 +01008401{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01008402 struct hlua *hlua;
8403 int nice;
Thierry FOURNIER37196f42015-02-16 19:34:56 +01008404
Willy Tarreau80f5fae2015-02-27 16:38:20 +01008405 MAY_LJMP(check_args(L, 1, "set_nice"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01008406 nice = MAY_LJMP(luaL_checkinteger(L, 1));
Thierry FOURNIER37196f42015-02-16 19:34:56 +01008407
Thierry Fournier4234dbd2020-11-28 13:18:23 +01008408 /* Get hlua struct, or NULL if we execute from main lua state */
8409 hlua = hlua_gethlua(L);
8410
8411 /* If the task is not set, I'm in a start mode. */
Thierry FOURNIER37196f42015-02-16 19:34:56 +01008412 if (!hlua || !hlua->task)
8413 return 0;
8414
8415 if (nice < -1024)
8416 nice = -1024;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01008417 else if (nice > 1024)
Thierry FOURNIER37196f42015-02-16 19:34:56 +01008418 nice = 1024;
8419
8420 hlua->task->nice = nice;
8421 return 0;
8422}
8423
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08008424/* This function is used as a callback of a task. It is called by the
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008425 * HAProxy task subsystem when the task is awaked. The LUA runtime can
8426 * return an E_AGAIN signal, the emmiter of this signal must set a
8427 * signal to wake the task.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008428 *
8429 * Task wrapper are longjmp safe because the only one Lua code
8430 * executed is the safe hlua_ctx_resume();
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008431 */
Willy Tarreau144f84a2021-03-02 16:09:26 +01008432struct task *hlua_process_task(struct task *task, void *context, unsigned int state)
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008433{
Olivier Houchard9f6af332018-05-25 14:04:04 +02008434 struct hlua *hlua = context;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008435 enum hlua_exec status;
8436
Christopher Faulet5bc99722018-04-25 10:34:45 +02008437 if (task->thread_mask == MAX_THREADS_MASK)
8438 task_set_affinity(task, tid_bit);
8439
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008440 /* If it is the first call to the task, we must initialize the
8441 * execution timeouts.
8442 */
8443 if (!HLUA_IS_RUNNING(hlua))
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02008444 hlua->max_time = hlua_timeout_task;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008445
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008446 /* Execute the Lua code. */
8447 status = hlua_ctx_resume(hlua, 1);
8448
8449 switch (status) {
8450 /* finished or yield */
8451 case HLUA_E_OK:
8452 hlua_ctx_destroy(hlua);
Olivier Houchard3f795f72019-04-17 22:51:06 +02008453 task_destroy(task);
Tim Duesterhuscd235c62018-04-24 13:56:01 +02008454 task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008455 break;
8456
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01008457 case HLUA_E_AGAIN: /* co process or timeout wake me later. */
Thierry FOURNIERcb146882017-12-10 17:10:57 +01008458 notification_gc(&hlua->com);
PiBa-NLfe971b32018-05-02 22:27:14 +02008459 task->expire = hlua->wake_time;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008460 break;
8461
8462 /* finished with error. */
8463 case HLUA_E_ERRMSG:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008464 SEND_ERR(NULL, "Lua task: %s.\n", lua_tostring(hlua->T, -1));
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008465 hlua_ctx_destroy(hlua);
Olivier Houchard3f795f72019-04-17 22:51:06 +02008466 task_destroy(task);
Emeric Brun253e53e2017-10-17 18:58:40 +02008467 task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008468 break;
8469
8470 case HLUA_E_ERR:
8471 default:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008472 SEND_ERR(NULL, "Lua task: unknown error.\n");
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008473 hlua_ctx_destroy(hlua);
Olivier Houchard3f795f72019-04-17 22:51:06 +02008474 task_destroy(task);
Emeric Brun253e53e2017-10-17 18:58:40 +02008475 task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008476 break;
8477 }
Emeric Brun253e53e2017-10-17 18:58:40 +02008478 return task;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008479}
8480
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008481/* This function is an LUA binding that register LUA function to be
8482 * executed after the HAProxy configuration parsing and before the
8483 * HAProxy scheduler starts. This function expect only one LUA
8484 * argument that is a function. This function returns nothing, but
8485 * throws if an error is encountered.
8486 */
8487__LJMP static int hlua_register_init(lua_State *L)
8488{
8489 struct hlua_init_function *init;
8490 int ref;
8491
8492 MAY_LJMP(check_args(L, 1, "register_init"));
8493
8494 ref = MAY_LJMP(hlua_checkfunction(L, 1));
8495
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02008496 init = calloc(1, sizeof(*init));
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008497 if (!init)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01008498 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008499
8500 init->function_ref = ref;
Willy Tarreau2b718102021-04-21 07:32:39 +02008501 LIST_APPEND(&hlua_init_functions[hlua_state_id], &init->l);
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008502 return 0;
8503}
8504
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008505/* This functio is an LUA binding. It permits to register a task
8506 * executed in parallel of the main HAroxy activity. The task is
8507 * created and it is set in the HAProxy scheduler. It can be called
8508 * from the "init" section, "post init" or during the runtime.
8509 *
8510 * Lua prototype:
8511 *
8512 * <none> core.register_task(<function>)
8513 */
8514static int hlua_register_task(lua_State *L)
8515{
Christopher Faulet5294ec02021-04-12 12:24:47 +02008516 struct hlua *hlua = NULL;
8517 struct task *task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008518 int ref;
Thierry Fournier021d9862020-11-28 23:42:03 +01008519 int state_id;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008520
8521 MAY_LJMP(check_args(L, 1, "register_task"));
8522
8523 ref = MAY_LJMP(hlua_checkfunction(L, 1));
8524
Thierry Fournier75fc0292020-11-28 13:18:56 +01008525 /* Get the reference state. If the reference is NULL, L is the master
8526 * state, otherwise hlua->T is.
8527 */
8528 hlua = hlua_gethlua(L);
8529 if (hlua)
Thierry Fournier021d9862020-11-28 23:42:03 +01008530 /* we are in runtime processing */
8531 state_id = hlua->state_id;
Thierry Fournier75fc0292020-11-28 13:18:56 +01008532 else
Thierry Fournier021d9862020-11-28 23:42:03 +01008533 /* we are in initialization mode */
Thierry Fournierc7492592020-11-28 23:57:24 +01008534 state_id = hlua_state_id;
Thierry Fournier75fc0292020-11-28 13:18:56 +01008535
Willy Tarreaubafbe012017-11-24 17:34:44 +01008536 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008537 if (!hlua)
Christopher Faulet5294ec02021-04-12 12:24:47 +02008538 goto alloc_error;
Christopher Faulet1e8433f2021-03-24 15:03:01 +01008539 HLUA_INIT(hlua);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008540
Thierry Fournier59f11be2020-11-29 00:37:41 +01008541 /* We are in the common lua state, execute the task anywhere,
8542 * otherwise, inherit the current thread identifier
8543 */
8544 if (state_id == 0)
Willy Tarreaubeeabf52021-10-01 18:23:30 +02008545 task = task_new_anywhere();
Thierry Fournier59f11be2020-11-29 00:37:41 +01008546 else
Willy Tarreaubeeabf52021-10-01 18:23:30 +02008547 task = task_new_here();
Willy Tarreaue09101e2018-10-16 17:37:12 +02008548 if (!task)
Christopher Faulet5294ec02021-04-12 12:24:47 +02008549 goto alloc_error;
Willy Tarreaue09101e2018-10-16 17:37:12 +02008550
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008551 task->context = hlua;
8552 task->process = hlua_process_task;
8553
Thierry Fournier021d9862020-11-28 23:42:03 +01008554 if (!hlua_ctx_init(hlua, state_id, task, 1))
Christopher Faulet5294ec02021-04-12 12:24:47 +02008555 goto alloc_error;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008556
8557 /* Restore the function in the stack. */
8558 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ref);
8559 hlua->nargs = 0;
8560
8561 /* Schedule task. */
Willy Tarreaue3957f82021-09-30 16:17:37 +02008562 task_wakeup(task, TASK_WOKEN_INIT);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008563
8564 return 0;
Christopher Faulet5294ec02021-04-12 12:24:47 +02008565
8566 alloc_error:
8567 task_destroy(task);
8568 hlua_ctx_destroy(hlua);
8569 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
8570 return 0; /* Never reached */
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008571}
8572
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008573/* Wrapper called by HAProxy to execute an LUA converter. This wrapper
8574 * doesn't allow "yield" functions because the HAProxy engine cannot
8575 * resume converters.
8576 */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02008577static int hlua_sample_conv_wrapper(const struct arg *arg_p, struct sample *smp, void *private)
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008578{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02008579 struct hlua_function *fcn = private;
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02008580 struct stream *stream = smp->strm;
Thierry Fournierfd107a22016-02-19 19:57:23 +01008581 const char *error;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008582
Willy Tarreaube508f12016-03-10 11:47:01 +01008583 if (!stream)
8584 return 0;
8585
Willy Tarreau87b09662015-04-03 00:22:06 +02008586 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01008587 * Lua context can be not initialized. This behavior
8588 * permits to save performances because a systematic
8589 * Lua initialization cause 5% performances loss.
8590 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008591 if (!stream->hlua) {
Christopher Faulet1e8433f2021-03-24 15:03:01 +01008592 struct hlua *hlua;
8593
8594 hlua = pool_alloc(pool_head_hlua);
8595 if (!hlua) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008596 SEND_ERR(stream->be, "Lua converter '%s': can't initialize Lua context.\n", fcn->name);
8597 return 0;
8598 }
Christopher Faulet1e8433f2021-03-24 15:03:01 +01008599 HLUA_INIT(hlua);
8600 stream->hlua = hlua;
Thierry Fournierc7492592020-11-28 23:57:24 +01008601 if (!hlua_ctx_init(stream->hlua, fcn_ref_to_stack_id(fcn), stream->task, 0)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008602 SEND_ERR(stream->be, "Lua converter '%s': can't initialize Lua context.\n", fcn->name);
8603 return 0;
8604 }
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01008605 }
8606
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008607 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008608 if (!HLUA_IS_RUNNING(stream->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008609
8610 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008611 if (!SET_SAFE_LJMP(stream->hlua)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008612 if (lua_type(stream->hlua->T, -1) == LUA_TSTRING)
8613 error = lua_tostring(stream->hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +01008614 else
8615 error = "critical error";
8616 SEND_ERR(stream->be, "Lua converter '%s': %s.\n", fcn->name, error);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008617 return 0;
8618 }
8619
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008620 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008621 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008622 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008623 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008624 return 0;
8625 }
8626
8627 /* Restore the function in the stack. */
Thierry Fournierc7492592020-11-28 23:57:24 +01008628 lua_rawgeti(stream->hlua->T, LUA_REGISTRYINDEX, fcn->function_ref[stream->hlua->state_id]);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008629
8630 /* convert input sample and pust-it in the stack. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008631 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008632 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008633 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008634 return 0;
8635 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008636 hlua_smp2lua(stream->hlua->T, smp);
8637 stream->hlua->nargs = 1;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008638
8639 /* push keywords in the stack. */
8640 if (arg_p) {
8641 for (; arg_p->type != ARGT_STOP; arg_p++) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008642 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008643 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008644 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008645 return 0;
8646 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008647 hlua_arg2lua(stream->hlua->T, arg_p);
8648 stream->hlua->nargs++;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008649 }
8650 }
8651
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008652 /* We must initialize the execution timeouts. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008653 stream->hlua->max_time = hlua_timeout_session;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008654
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008655 /* At this point the execution is safe. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008656 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008657 }
8658
8659 /* Execute the function. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008660 switch (hlua_ctx_resume(stream->hlua, 0)) {
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008661 /* finished. */
8662 case HLUA_E_OK:
Thierry FOURNIERfd80df12017-05-12 16:32:20 +02008663 /* If the stack is empty, the function fails. */
8664 if (lua_gettop(stream->hlua->T) <= 0)
8665 return 0;
8666
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008667 /* Convert the returned value in sample. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008668 hlua_lua2smp(stream->hlua->T, -1, smp);
8669 lua_pop(stream->hlua->T, 1);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008670 return 1;
8671
8672 /* yield. */
8673 case HLUA_E_AGAIN:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008674 SEND_ERR(stream->be, "Lua converter '%s': cannot use yielded functions.\n", fcn->name);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008675 return 0;
8676
8677 /* finished with error. */
8678 case HLUA_E_ERRMSG:
8679 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008680 SEND_ERR(stream->be, "Lua converter '%s': %s.\n",
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008681 fcn->name, lua_tostring(stream->hlua->T, -1));
8682 lua_pop(stream->hlua->T, 1);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008683 return 0;
8684
Thierry Fournierd5b073c2018-05-21 19:42:47 +02008685 case HLUA_E_ETMOUT:
8686 SEND_ERR(stream->be, "Lua converter '%s': execution timeout.\n", fcn->name);
8687 return 0;
8688
8689 case HLUA_E_NOMEM:
8690 SEND_ERR(stream->be, "Lua converter '%s': out of memory error.\n", fcn->name);
8691 return 0;
8692
8693 case HLUA_E_YIELD:
8694 SEND_ERR(stream->be, "Lua converter '%s': yield functions like core.tcp() or core.sleep() are not allowed.\n", fcn->name);
8695 return 0;
8696
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008697 case HLUA_E_ERR:
8698 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008699 SEND_ERR(stream->be, "Lua converter '%s' returns an unknown error.\n", fcn->name);
Tim Duesterhus588b3142020-05-29 14:35:51 +02008700 /* fall through */
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008701
8702 default:
8703 return 0;
8704 }
8705}
8706
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008707/* Wrapper called by HAProxy to execute a sample-fetch. this wrapper
8708 * doesn't allow "yield" functions because the HAProxy engine cannot
Willy Tarreaube508f12016-03-10 11:47:01 +01008709 * resume sample-fetches. This function will be called by the sample
8710 * fetch engine to call lua-based fetch operations.
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008711 */
Thierry FOURNIER0786d052015-05-11 15:42:45 +02008712static int hlua_sample_fetch_wrapper(const struct arg *arg_p, struct sample *smp,
8713 const char *kw, void *private)
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008714{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02008715 struct hlua_function *fcn = private;
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02008716 struct stream *stream = smp->strm;
Thierry Fournierfd107a22016-02-19 19:57:23 +01008717 const char *error;
Christopher Faulet8c9e6bb2021-08-06 16:29:41 +02008718 unsigned int hflags = HLUA_TXN_NOTERM | HLUA_TXN_SMP_CTX;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008719
Willy Tarreaube508f12016-03-10 11:47:01 +01008720 if (!stream)
8721 return 0;
Christopher Fauletafd8f102018-11-08 11:34:21 +01008722
Willy Tarreau87b09662015-04-03 00:22:06 +02008723 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01008724 * Lua context can be not initialized. This behavior
8725 * permits to save performances because a systematic
8726 * Lua initialization cause 5% performances loss.
8727 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008728 if (!stream->hlua) {
Christopher Faulet1e8433f2021-03-24 15:03:01 +01008729 struct hlua *hlua;
8730
8731 hlua = pool_alloc(pool_head_hlua);
8732 if (!hlua) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008733 SEND_ERR(stream->be, "Lua sample-fetch '%s': can't initialize Lua context.\n", fcn->name);
8734 return 0;
8735 }
Christopher Faulet1e8433f2021-03-24 15:03:01 +01008736 hlua->T = NULL;
8737 stream->hlua = hlua;
Thierry Fournierc7492592020-11-28 23:57:24 +01008738 if (!hlua_ctx_init(stream->hlua, fcn_ref_to_stack_id(fcn), stream->task, 0)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008739 SEND_ERR(stream->be, "Lua sample-fetch '%s': can't initialize Lua context.\n", fcn->name);
8740 return 0;
8741 }
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01008742 }
8743
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008744 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008745 if (!HLUA_IS_RUNNING(stream->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008746
8747 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008748 if (!SET_SAFE_LJMP(stream->hlua)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008749 if (lua_type(stream->hlua->T, -1) == LUA_TSTRING)
8750 error = lua_tostring(stream->hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +01008751 else
8752 error = "critical error";
8753 SEND_ERR(smp->px, "Lua sample-fetch '%s': %s.\n", fcn->name, error);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008754 return 0;
8755 }
8756
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008757 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008758 if (!lua_checkstack(stream->hlua->T, 2)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008759 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008760 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008761 return 0;
8762 }
8763
8764 /* Restore the function in the stack. */
Thierry Fournierc7492592020-11-28 23:57:24 +01008765 lua_rawgeti(stream->hlua->T, LUA_REGISTRYINDEX, fcn->function_ref[stream->hlua->state_id]);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008766
8767 /* push arguments in the stack. */
Christopher Fauletbfab2dd2019-07-26 15:09:53 +02008768 if (!hlua_txn_new(stream->hlua->T, stream, smp->px, smp->opt & SMP_OPT_DIR, hflags)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008769 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008770 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008771 return 0;
8772 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008773 stream->hlua->nargs = 1;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008774
8775 /* push keywords in the stack. */
8776 for (; arg_p && arg_p->type != ARGT_STOP; arg_p++) {
8777 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008778 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008779 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008780 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008781 return 0;
8782 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008783 hlua_arg2lua(stream->hlua->T, arg_p);
8784 stream->hlua->nargs++;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008785 }
8786
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008787 /* We must initialize the execution timeouts. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008788 stream->hlua->max_time = hlua_timeout_session;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008789
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008790 /* At this point the execution is safe. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008791 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008792 }
8793
8794 /* Execute the function. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008795 switch (hlua_ctx_resume(stream->hlua, 0)) {
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008796 /* finished. */
8797 case HLUA_E_OK:
Thierry FOURNIERfd80df12017-05-12 16:32:20 +02008798 /* If the stack is empty, the function fails. */
8799 if (lua_gettop(stream->hlua->T) <= 0)
8800 return 0;
8801
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008802 /* Convert the returned value in sample. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008803 hlua_lua2smp(stream->hlua->T, -1, smp);
8804 lua_pop(stream->hlua->T, 1);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008805
8806 /* Set the end of execution flag. */
8807 smp->flags &= ~SMP_F_MAY_CHANGE;
8808 return 1;
8809
8810 /* yield. */
8811 case HLUA_E_AGAIN:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008812 SEND_ERR(smp->px, "Lua sample-fetch '%s': cannot use yielded functions.\n", fcn->name);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008813 return 0;
8814
8815 /* finished with error. */
8816 case HLUA_E_ERRMSG:
8817 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008818 SEND_ERR(smp->px, "Lua sample-fetch '%s': %s.\n",
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008819 fcn->name, lua_tostring(stream->hlua->T, -1));
8820 lua_pop(stream->hlua->T, 1);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008821 return 0;
8822
Thierry Fournierd5b073c2018-05-21 19:42:47 +02008823 case HLUA_E_ETMOUT:
Thierry Fournierd5b073c2018-05-21 19:42:47 +02008824 SEND_ERR(smp->px, "Lua sample-fetch '%s': execution timeout.\n", fcn->name);
8825 return 0;
8826
8827 case HLUA_E_NOMEM:
Thierry Fournierd5b073c2018-05-21 19:42:47 +02008828 SEND_ERR(smp->px, "Lua sample-fetch '%s': out of memory error.\n", fcn->name);
8829 return 0;
8830
8831 case HLUA_E_YIELD:
Thierry Fournierd5b073c2018-05-21 19:42:47 +02008832 SEND_ERR(smp->px, "Lua sample-fetch '%s': yield not allowed.\n", fcn->name);
8833 return 0;
8834
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008835 case HLUA_E_ERR:
8836 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008837 SEND_ERR(smp->px, "Lua sample-fetch '%s' returns an unknown error.\n", fcn->name);
Tim Duesterhus588b3142020-05-29 14:35:51 +02008838 /* fall through */
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008839
8840 default:
8841 return 0;
8842 }
8843}
8844
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008845/* This function is an LUA binding used for registering
8846 * "sample-conv" functions. It expects a converter name used
8847 * in the haproxy configuration file, and an LUA function.
8848 */
8849__LJMP static int hlua_register_converters(lua_State *L)
8850{
8851 struct sample_conv_kw_list *sck;
8852 const char *name;
8853 int ref;
8854 int len;
Christopher Fauletaa224302021-04-12 14:08:21 +02008855 struct hlua_function *fcn = NULL;
Thierry Fournierf67442e2020-11-28 20:41:07 +01008856 struct sample_conv *sc;
8857 struct buffer *trash;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008858
8859 MAY_LJMP(check_args(L, 2, "register_converters"));
8860
8861 /* First argument : converter name. */
8862 name = MAY_LJMP(luaL_checkstring(L, 1));
8863
8864 /* Second argument : lua function. */
8865 ref = MAY_LJMP(hlua_checkfunction(L, 2));
8866
Thierry Fournierf67442e2020-11-28 20:41:07 +01008867 /* Check if the converter is already registered */
8868 trash = get_trash_chunk();
8869 chunk_printf(trash, "lua.%s", name);
8870 sc = find_sample_conv(trash->area, trash->data);
8871 if (sc != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +01008872 fcn = sc->private;
8873 if (fcn->function_ref[hlua_state_id] != -1) {
8874 ha_warning("Trying to register converter 'lua.%s' more than once. "
8875 "This will become a hard error in version 2.5.\n", name);
8876 }
8877 fcn->function_ref[hlua_state_id] = ref;
8878 return 0;
Thierry Fournierf67442e2020-11-28 20:41:07 +01008879 }
8880
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008881 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02008882 sck = calloc(1, sizeof(*sck) + sizeof(struct sample_conv) * 2);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008883 if (!sck)
Christopher Fauletaa224302021-04-12 14:08:21 +02008884 goto alloc_error;
Thierry Fournier62a22aa2020-11-28 21:06:35 +01008885 fcn = new_hlua_function();
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008886 if (!fcn)
Christopher Fauletaa224302021-04-12 14:08:21 +02008887 goto alloc_error;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008888
8889 /* Fill fcn. */
8890 fcn->name = strdup(name);
8891 if (!fcn->name)
Christopher Fauletaa224302021-04-12 14:08:21 +02008892 goto alloc_error;
Thierry Fournierc7492592020-11-28 23:57:24 +01008893 fcn->function_ref[hlua_state_id] = ref;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008894
8895 /* List head */
8896 sck->list.n = sck->list.p = NULL;
8897
8898 /* converter keyword. */
8899 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02008900 sck->kw[0].kw = calloc(1, len);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008901 if (!sck->kw[0].kw)
Christopher Fauletaa224302021-04-12 14:08:21 +02008902 goto alloc_error;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008903
8904 snprintf((char *)sck->kw[0].kw, len, "lua.%s", name);
8905 sck->kw[0].process = hlua_sample_conv_wrapper;
David Carlier0c437f42016-04-27 16:21:56 +01008906 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 +01008907 sck->kw[0].val_args = NULL;
8908 sck->kw[0].in_type = SMP_T_STR;
8909 sck->kw[0].out_type = SMP_T_STR;
8910 sck->kw[0].private = fcn;
8911
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008912 /* Register this new converter */
8913 sample_register_convs(sck);
8914
8915 return 0;
Christopher Fauletaa224302021-04-12 14:08:21 +02008916
8917 alloc_error:
8918 release_hlua_function(fcn);
8919 ha_free(&sck);
8920 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
8921 return 0; /* Never reached */
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008922}
8923
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08008924/* This function is an LUA binding used for registering
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008925 * "sample-fetch" functions. It expects a converter name used
8926 * in the haproxy configuration file, and an LUA function.
8927 */
8928__LJMP static int hlua_register_fetches(lua_State *L)
8929{
8930 const char *name;
8931 int ref;
8932 int len;
8933 struct sample_fetch_kw_list *sfk;
Christopher Faulet2567f182021-04-12 14:11:50 +02008934 struct hlua_function *fcn = NULL;
Thierry Fournierf67442e2020-11-28 20:41:07 +01008935 struct sample_fetch *sf;
8936 struct buffer *trash;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008937
8938 MAY_LJMP(check_args(L, 2, "register_fetches"));
8939
8940 /* First argument : sample-fetch name. */
8941 name = MAY_LJMP(luaL_checkstring(L, 1));
8942
8943 /* Second argument : lua function. */
8944 ref = MAY_LJMP(hlua_checkfunction(L, 2));
8945
Thierry Fournierf67442e2020-11-28 20:41:07 +01008946 /* Check if the sample-fetch is already registered */
8947 trash = get_trash_chunk();
8948 chunk_printf(trash, "lua.%s", name);
8949 sf = find_sample_fetch(trash->area, trash->data);
8950 if (sf != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +01008951 fcn = sf->private;
8952 if (fcn->function_ref[hlua_state_id] != -1) {
8953 ha_warning("Trying to register sample-fetch 'lua.%s' more than once. "
8954 "This will become a hard error in version 2.5.\n", name);
8955 }
8956 fcn->function_ref[hlua_state_id] = ref;
8957 return 0;
Thierry Fournierf67442e2020-11-28 20:41:07 +01008958 }
8959
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008960 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02008961 sfk = calloc(1, sizeof(*sfk) + sizeof(struct sample_fetch) * 2);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008962 if (!sfk)
Christopher Faulet2567f182021-04-12 14:11:50 +02008963 goto alloc_error;
Thierry Fournier62a22aa2020-11-28 21:06:35 +01008964 fcn = new_hlua_function();
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008965 if (!fcn)
Christopher Faulet2567f182021-04-12 14:11:50 +02008966 goto alloc_error;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008967
8968 /* Fill fcn. */
8969 fcn->name = strdup(name);
8970 if (!fcn->name)
Christopher Faulet2567f182021-04-12 14:11:50 +02008971 goto alloc_error;
Thierry Fournierc7492592020-11-28 23:57:24 +01008972 fcn->function_ref[hlua_state_id] = ref;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008973
8974 /* List head */
8975 sfk->list.n = sfk->list.p = NULL;
8976
8977 /* sample-fetch keyword. */
8978 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02008979 sfk->kw[0].kw = calloc(1, len);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008980 if (!sfk->kw[0].kw)
Christopher Faulet2567f182021-04-12 14:11:50 +02008981 goto alloc_error;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008982
8983 snprintf((char *)sfk->kw[0].kw, len, "lua.%s", name);
8984 sfk->kw[0].process = hlua_sample_fetch_wrapper;
David Carlier0c437f42016-04-27 16:21:56 +01008985 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 +01008986 sfk->kw[0].val_args = NULL;
8987 sfk->kw[0].out_type = SMP_T_STR;
8988 sfk->kw[0].use = SMP_USE_HTTP_ANY;
8989 sfk->kw[0].val = 0;
8990 sfk->kw[0].private = fcn;
8991
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008992 /* Register this new fetch. */
8993 sample_register_fetches(sfk);
8994
8995 return 0;
Christopher Faulet2567f182021-04-12 14:11:50 +02008996
8997 alloc_error:
8998 release_hlua_function(fcn);
8999 ha_free(&sfk);
9000 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
9001 return 0; /* Never reached */
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009002}
9003
Christopher Faulet501465d2020-02-26 14:54:16 +01009004/* This function is a lua binding to set the wake_time.
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01009005 */
Christopher Faulet501465d2020-02-26 14:54:16 +01009006__LJMP static int hlua_set_wake_time(lua_State *L)
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01009007{
Thierry Fournier4234dbd2020-11-28 13:18:23 +01009008 struct hlua *hlua;
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01009009 unsigned int delay;
9010 unsigned int wakeup_ms;
9011
Thierry Fournier4234dbd2020-11-28 13:18:23 +01009012 /* Get hlua struct, or NULL if we execute from main lua state */
9013 hlua = hlua_gethlua(L);
9014 if (!hlua) {
9015 return 0;
9016 }
9017
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01009018 MAY_LJMP(check_args(L, 1, "wake_time"));
9019
9020 delay = MAY_LJMP(luaL_checkinteger(L, 1));
9021 wakeup_ms = tick_add(now_ms, delay);
9022 hlua->wake_time = wakeup_ms;
9023 return 0;
9024}
9025
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009026/* This function is a wrapper to execute each LUA function declared as an action
9027 * wrapper during the initialisation period. This function may return any
9028 * ACT_RET_* value. On error ACT_RET_CONT is returned and the action is
9029 * ignored. If the lua action yields, ACT_RET_YIELD is returned. On success, the
9030 * return value is the first element on the stack.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009031 */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009032static enum act_return hlua_action(struct act_rule *rule, struct proxy *px,
Willy Tarreau658b85b2015-09-27 10:00:49 +02009033 struct session *sess, struct stream *s, int flags)
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009034{
9035 char **arg;
Christopher Faulet8c9e6bb2021-08-06 16:29:41 +02009036 unsigned int hflags = HLUA_TXN_ACT_CTX;
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009037 int dir, act_ret = ACT_RET_CONT;
Thierry Fournierfd107a22016-02-19 19:57:23 +01009038 const char *error;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009039
9040 switch (rule->from) {
Christopher Fauletd8f0e072020-02-25 09:45:51 +01009041 case ACT_F_TCP_REQ_CNT: dir = SMP_OPT_DIR_REQ; break;
9042 case ACT_F_TCP_RES_CNT: dir = SMP_OPT_DIR_RES; break;
9043 case ACT_F_HTTP_REQ: dir = SMP_OPT_DIR_REQ; break;
9044 case ACT_F_HTTP_RES: dir = SMP_OPT_DIR_RES; break;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009045 default:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009046 SEND_ERR(px, "Lua: internal error while execute action.\n");
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009047 goto end;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009048 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009049
Willy Tarreau87b09662015-04-03 00:22:06 +02009050 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01009051 * Lua context can be not initialized. This behavior
9052 * permits to save performances because a systematic
9053 * Lua initialization cause 5% performances loss.
9054 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009055 if (!s->hlua) {
Christopher Faulet1e8433f2021-03-24 15:03:01 +01009056 struct hlua *hlua;
9057
9058 hlua = pool_alloc(pool_head_hlua);
9059 if (!hlua) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009060 SEND_ERR(px, "Lua action '%s': can't initialize Lua context.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009061 rule->arg.hlua_rule->fcn->name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009062 goto end;
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009063 }
Christopher Faulet1e8433f2021-03-24 15:03:01 +01009064 HLUA_INIT(hlua);
9065 s->hlua = hlua;
Thierry Fournierc7492592020-11-28 23:57:24 +01009066 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 +01009067 SEND_ERR(px, "Lua action '%s': can't initialize Lua context.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009068 rule->arg.hlua_rule->fcn->name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009069 goto end;
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009070 }
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01009071 }
9072
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009073 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009074 if (!HLUA_IS_RUNNING(s->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02009075
9076 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009077 if (!SET_SAFE_LJMP(s->hlua)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009078 if (lua_type(s->hlua->T, -1) == LUA_TSTRING)
9079 error = lua_tostring(s->hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +01009080 else
9081 error = "critical error";
9082 SEND_ERR(px, "Lua function '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009083 rule->arg.hlua_rule->fcn->name, error);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009084 goto end;
Thierry FOURNIERbabae282015-09-17 11:36:37 +02009085 }
9086
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009087 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009088 if (!lua_checkstack(s->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009089 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009090 rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009091 RESET_SAFE_LJMP(s->hlua);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009092 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009093 }
9094
9095 /* Restore the function in the stack. */
Thierry Fournierc7492592020-11-28 23:57:24 +01009096 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 +01009097
Willy Tarreau87b09662015-04-03 00:22:06 +02009098 /* Create and and push object stream in the stack. */
Christopher Fauletbfab2dd2019-07-26 15:09:53 +02009099 if (!hlua_txn_new(s->hlua->T, s, px, dir, hflags)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009100 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009101 rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009102 RESET_SAFE_LJMP(s->hlua);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009103 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009104 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009105 s->hlua->nargs = 1;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009106
9107 /* push keywords in the stack. */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009108 for (arg = rule->arg.hlua_rule->args; arg && *arg; arg++) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009109 if (!lua_checkstack(s->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009110 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009111 rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009112 RESET_SAFE_LJMP(s->hlua);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009113 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009114 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009115 lua_pushstring(s->hlua->T, *arg);
9116 s->hlua->nargs++;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009117 }
9118
Thierry FOURNIERbabae282015-09-17 11:36:37 +02009119 /* Now the execution is safe. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009120 RESET_SAFE_LJMP(s->hlua);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02009121
Thierry FOURNIERbd413492015-03-03 16:52:26 +01009122 /* We must initialize the execution timeouts. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009123 s->hlua->max_time = hlua_timeout_session;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009124 }
9125
9126 /* Execute the function. */
Christopher Faulet105ba6c2019-12-18 14:41:51 +01009127 switch (hlua_ctx_resume(s->hlua, !(flags & ACT_OPT_FINAL))) {
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009128 /* finished. */
9129 case HLUA_E_OK:
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009130 /* Catch the return value */
9131 if (lua_gettop(s->hlua->T) > 0)
9132 act_ret = lua_tointeger(s->hlua->T, -1);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009133
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01009134 /* Set timeout in the required channel. */
Christopher Faulet498c4832020-07-28 11:59:58 +02009135 if (act_ret == ACT_RET_YIELD) {
9136 if (flags & ACT_OPT_FINAL)
9137 goto err_yield;
9138
Christopher Faulet8f587ea2020-07-28 12:01:55 +02009139 if (dir == SMP_OPT_DIR_REQ)
9140 s->req.analyse_exp = tick_first((tick_is_expired(s->req.analyse_exp, now_ms) ? 0 : s->req.analyse_exp),
9141 s->hlua->wake_time);
9142 else
9143 s->res.analyse_exp = tick_first((tick_is_expired(s->res.analyse_exp, now_ms) ? 0 : s->res.analyse_exp),
9144 s->hlua->wake_time);
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01009145 }
9146 goto end;
9147
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009148 /* yield. */
9149 case HLUA_E_AGAIN:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01009150 /* Set timeout in the required channel. */
Christopher Faulet8f587ea2020-07-28 12:01:55 +02009151 if (dir == SMP_OPT_DIR_REQ)
9152 s->req.analyse_exp = tick_first((tick_is_expired(s->req.analyse_exp, now_ms) ? 0 : s->req.analyse_exp),
9153 s->hlua->wake_time);
9154 else
9155 s->res.analyse_exp = tick_first((tick_is_expired(s->res.analyse_exp, now_ms) ? 0 : s->res.analyse_exp),
9156 s->hlua->wake_time);
9157
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009158 /* Some actions can be wake up when a "write" event
9159 * is detected on a response channel. This is useful
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08009160 * only for actions targeted on the requests.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009161 */
Christopher Faulet51fa3582019-07-26 14:54:52 +02009162 if (HLUA_IS_WAKERESWR(s->hlua))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01009163 s->res.flags |= CF_WAKE_WRITE;
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009164 if (HLUA_IS_WAKEREQWR(s->hlua))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01009165 s->req.flags |= CF_WAKE_WRITE;
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009166 act_ret = ACT_RET_YIELD;
9167 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009168
9169 /* finished with error. */
9170 case HLUA_E_ERRMSG:
9171 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009172 SEND_ERR(px, "Lua function '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009173 rule->arg.hlua_rule->fcn->name, lua_tostring(s->hlua->T, -1));
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009174 lua_pop(s->hlua->T, 1);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009175 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009176
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009177 case HLUA_E_ETMOUT:
Thierry Fournierad5345f2020-11-29 02:05:57 +01009178 SEND_ERR(px, "Lua function '%s': execution timeout.\n", rule->arg.hlua_rule->fcn->name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009179 goto end;
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009180
9181 case HLUA_E_NOMEM:
Thierry Fournierad5345f2020-11-29 02:05:57 +01009182 SEND_ERR(px, "Lua function '%s': out of memory error.\n", rule->arg.hlua_rule->fcn->name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009183 goto end;
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009184
9185 case HLUA_E_YIELD:
Christopher Faulet498c4832020-07-28 11:59:58 +02009186 err_yield:
9187 act_ret = ACT_RET_CONT;
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009188 SEND_ERR(px, "Lua function '%s': aborting Lua processing on expired timeout.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009189 rule->arg.hlua_rule->fcn->name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009190 goto end;
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009191
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009192 case HLUA_E_ERR:
9193 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009194 SEND_ERR(px, "Lua function '%s' return an unknown error.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009195 rule->arg.hlua_rule->fcn->name);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009196
9197 default:
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009198 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009199 }
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009200
9201 end:
Christopher Faulet2361fd92020-07-30 10:40:58 +02009202 if (act_ret != ACT_RET_YIELD && s->hlua)
Christopher Faulet8f587ea2020-07-28 12:01:55 +02009203 s->hlua->wake_time = TICK_ETERNITY;
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009204 return act_ret;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009205}
9206
Willy Tarreau144f84a2021-03-02 16:09:26 +01009207struct task *hlua_applet_wakeup(struct task *t, void *context, unsigned int state)
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009208{
Olivier Houchard9f6af332018-05-25 14:04:04 +02009209 struct appctx *ctx = context;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009210
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009211 appctx_wakeup(ctx);
Willy Tarreaud9587412017-08-23 16:07:33 +02009212 t->expire = TICK_ETERNITY;
Willy Tarreaud1aa41f2017-07-21 16:41:56 +02009213 return t;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009214}
9215
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009216static int hlua_applet_tcp_init(struct appctx *ctx)
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009217{
Willy Tarreaue23f33b2022-05-06 14:07:13 +02009218 struct hlua_tcp_ctx *tcp_ctx = applet_reserve_svcctx(ctx, sizeof(*tcp_ctx));
Willy Tarreau4596fe22022-05-17 19:07:51 +02009219 struct stconn *cs = appctx_cs(ctx);
Willy Tarreauea27f482022-05-18 16:10:52 +02009220 struct stream *strm = __sc_strm(cs);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009221 struct hlua *hlua;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009222 struct task *task;
9223 char **arg;
Thierry Fournierfd107a22016-02-19 19:57:23 +01009224 const char *error;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009225
Willy Tarreaubafbe012017-11-24 17:34:44 +01009226 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009227 if (!hlua) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009228 SEND_ERR(strm->be, "Lua applet tcp '%s': out of memory.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009229 ctx->rule->arg.hlua_rule->fcn->name);
Christopher Fauletc9929382022-05-12 11:52:27 +02009230 return -1;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009231 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009232 HLUA_INIT(hlua);
Willy Tarreaue23f33b2022-05-06 14:07:13 +02009233 tcp_ctx->hlua = hlua;
9234 tcp_ctx->flags = 0;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009235
9236 /* Create task used by signal to wakeup applets. */
Willy Tarreaubeeabf52021-10-01 18:23:30 +02009237 task = task_new_here();
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009238 if (!task) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009239 SEND_ERR(strm->be, "Lua applet tcp '%s': out of memory.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009240 ctx->rule->arg.hlua_rule->fcn->name);
Christopher Fauletc9929382022-05-12 11:52:27 +02009241 return -1;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009242 }
9243 task->nice = 0;
9244 task->context = ctx;
9245 task->process = hlua_applet_wakeup;
Willy Tarreaue23f33b2022-05-06 14:07:13 +02009246 tcp_ctx->task = task;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009247
9248 /* In the execution wrappers linked with a stream, the
9249 * Lua context can be not initialized. This behavior
9250 * permits to save performances because a systematic
9251 * Lua initialization cause 5% performances loss.
9252 */
Thierry Fournierc7492592020-11-28 23:57:24 +01009253 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 +01009254 SEND_ERR(strm->be, "Lua applet tcp '%s': can't initialize Lua context.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009255 ctx->rule->arg.hlua_rule->fcn->name);
Christopher Fauletc9929382022-05-12 11:52:27 +02009256 return -1;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009257 }
9258
9259 /* Set timeout according with the applet configuration. */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02009260 hlua->max_time = ctx->applet->timeout;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009261
9262 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009263 if (!SET_SAFE_LJMP(hlua)) {
Thierry Fournierfd107a22016-02-19 19:57:23 +01009264 if (lua_type(hlua->T, -1) == LUA_TSTRING)
9265 error = lua_tostring(hlua->T, -1);
9266 else
9267 error = "critical error";
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009268 SEND_ERR(strm->be, "Lua applet tcp '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009269 ctx->rule->arg.hlua_rule->fcn->name, error);
Christopher Fauletc9929382022-05-12 11:52:27 +02009270 return -1;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009271 }
9272
9273 /* Check stack available size. */
9274 if (!lua_checkstack(hlua->T, 1)) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009275 SEND_ERR(strm->be, "Lua applet tcp '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009276 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009277 RESET_SAFE_LJMP(hlua);
Christopher Fauletc9929382022-05-12 11:52:27 +02009278 return -1;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009279 }
9280
9281 /* Restore the function in the stack. */
Thierry Fournierc7492592020-11-28 23:57:24 +01009282 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ctx->rule->arg.hlua_rule->fcn->function_ref[hlua->state_id]);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009283
9284 /* Create and and push object stream in the stack. */
9285 if (!hlua_applet_tcp_new(hlua->T, ctx)) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009286 SEND_ERR(strm->be, "Lua applet tcp '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009287 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009288 RESET_SAFE_LJMP(hlua);
Christopher Fauletc9929382022-05-12 11:52:27 +02009289 return -1;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009290 }
9291 hlua->nargs = 1;
9292
9293 /* push keywords in the stack. */
9294 for (arg = ctx->rule->arg.hlua_rule->args; arg && *arg; arg++) {
9295 if (!lua_checkstack(hlua->T, 1)) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009296 SEND_ERR(strm->be, "Lua applet tcp '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009297 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009298 RESET_SAFE_LJMP(hlua);
Christopher Fauletc9929382022-05-12 11:52:27 +02009299 return -1;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009300 }
9301 lua_pushstring(hlua->T, *arg);
9302 hlua->nargs++;
9303 }
9304
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009305 RESET_SAFE_LJMP(hlua);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009306
9307 /* Wakeup the applet ASAP. */
Willy Tarreau90e8b452022-05-25 18:21:43 +02009308 applet_need_more_data(ctx);
Willy Tarreau4164eb92022-05-25 15:42:03 +02009309 applet_have_more_data(ctx);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009310
Christopher Fauletc9929382022-05-12 11:52:27 +02009311 return 0;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009312}
9313
Willy Tarreau60409db2019-08-21 14:14:50 +02009314void hlua_applet_tcp_fct(struct appctx *ctx)
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009315{
Willy Tarreaue23f33b2022-05-06 14:07:13 +02009316 struct hlua_tcp_ctx *tcp_ctx = ctx->svcctx;
Willy Tarreau4596fe22022-05-17 19:07:51 +02009317 struct stconn *cs = appctx_cs(ctx);
Willy Tarreauea27f482022-05-18 16:10:52 +02009318 struct stream *strm = __sc_strm(cs);
Willy Tarreau40a9c322022-05-18 15:55:18 +02009319 struct channel *res = sc_ic(cs);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009320 struct act_rule *rule = ctx->rule;
9321 struct proxy *px = strm->be;
Willy Tarreaue23f33b2022-05-06 14:07:13 +02009322 struct hlua *hlua = tcp_ctx->hlua;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009323
9324 /* The applet execution is already done. */
Willy Tarreaue23f33b2022-05-06 14:07:13 +02009325 if (tcp_ctx->flags & APPLET_DONE) {
Olivier Houchard594c8c52018-08-28 14:41:31 +02009326 /* eat the whole request */
Willy Tarreau40a9c322022-05-18 15:55:18 +02009327 co_skip(sc_oc(cs), co_data(sc_oc(cs)));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009328 return;
Olivier Houchard594c8c52018-08-28 14:41:31 +02009329 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009330
9331 /* If the stream is disconnect or closed, ldo nothing. */
Willy Tarreau026e8fb2022-05-17 19:47:17 +02009332 if (unlikely(cs->state == SC_ST_DIS || cs->state == SC_ST_CLO))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009333 return;
9334
9335 /* Execute the function. */
9336 switch (hlua_ctx_resume(hlua, 1)) {
9337 /* finished. */
9338 case HLUA_E_OK:
Willy Tarreaue23f33b2022-05-06 14:07:13 +02009339 tcp_ctx->flags |= APPLET_DONE;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009340
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009341 /* eat the whole request */
Willy Tarreau40a9c322022-05-18 15:55:18 +02009342 co_skip(sc_oc(cs), co_data(sc_oc(cs)));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009343 res->flags |= CF_READ_NULL;
Christopher Fauletda098e62022-03-31 17:44:45 +02009344 cs_shutr(cs);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009345 return;
9346
9347 /* yield. */
9348 case HLUA_E_AGAIN:
Thierry Fournier0164f202016-02-20 17:47:43 +01009349 if (hlua->wake_time != TICK_ETERNITY)
Willy Tarreaue23f33b2022-05-06 14:07:13 +02009350 task_schedule(tcp_ctx->task, hlua->wake_time);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009351 return;
9352
9353 /* finished with error. */
9354 case HLUA_E_ERRMSG:
9355 /* Display log. */
9356 SEND_ERR(px, "Lua applet tcp '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009357 rule->arg.hlua_rule->fcn->name, lua_tostring(hlua->T, -1));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009358 lua_pop(hlua->T, 1);
9359 goto error;
9360
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009361 case HLUA_E_ETMOUT:
9362 SEND_ERR(px, "Lua applet tcp '%s': execution timeout.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009363 rule->arg.hlua_rule->fcn->name);
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009364 goto error;
9365
9366 case HLUA_E_NOMEM:
9367 SEND_ERR(px, "Lua applet tcp '%s': out of memory error.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009368 rule->arg.hlua_rule->fcn->name);
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009369 goto error;
9370
9371 case HLUA_E_YIELD: /* unexpected */
9372 SEND_ERR(px, "Lua applet tcp '%s': yield not allowed.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009373 rule->arg.hlua_rule->fcn->name);
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009374 goto error;
9375
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009376 case HLUA_E_ERR:
9377 /* Display log. */
9378 SEND_ERR(px, "Lua applet tcp '%s' return an unknown error.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009379 rule->arg.hlua_rule->fcn->name);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009380 goto error;
9381
9382 default:
9383 goto error;
9384 }
9385
9386error:
9387
9388 /* For all other cases, just close the stream. */
Christopher Fauletda098e62022-03-31 17:44:45 +02009389 cs_shutw(cs);
9390 cs_shutr(cs);
Willy Tarreaue23f33b2022-05-06 14:07:13 +02009391 tcp_ctx->flags |= APPLET_DONE;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009392}
9393
9394static void hlua_applet_tcp_release(struct appctx *ctx)
9395{
Willy Tarreaue23f33b2022-05-06 14:07:13 +02009396 struct hlua_tcp_ctx *tcp_ctx = ctx->svcctx;
9397
9398 task_destroy(tcp_ctx->task);
9399 tcp_ctx->task = NULL;
9400 hlua_ctx_destroy(tcp_ctx->hlua);
9401 tcp_ctx->hlua = NULL;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009402}
9403
Christopher Fauletc9929382022-05-12 11:52:27 +02009404/* The function returns 0 if the initialisation is complete or -1 if
9405 * an errors occurs. It also reserves the appctx for an hlua_http_ctx.
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009406 */
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009407static int hlua_applet_http_init(struct appctx *ctx)
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009408{
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009409 struct hlua_http_ctx *http_ctx = applet_reserve_svcctx(ctx, sizeof(*http_ctx));
Willy Tarreau4596fe22022-05-17 19:07:51 +02009410 struct stconn *cs = appctx_cs(ctx);
Willy Tarreauea27f482022-05-18 16:10:52 +02009411 struct stream *strm = __sc_strm(cs);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009412 struct http_txn *txn;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009413 struct hlua *hlua;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009414 char **arg;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009415 struct task *task;
Thierry Fournierfd107a22016-02-19 19:57:23 +01009416 const char *error;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009417
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009418 txn = strm->txn;
Willy Tarreaubafbe012017-11-24 17:34:44 +01009419 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009420 if (!hlua) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009421 SEND_ERR(strm->be, "Lua applet http '%s': out of memory.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009422 ctx->rule->arg.hlua_rule->fcn->name);
Christopher Fauletc9929382022-05-12 11:52:27 +02009423 return -1;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009424 }
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009425 HLUA_INIT(hlua);
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009426 http_ctx->hlua = hlua;
9427 http_ctx->left_bytes = -1;
9428 http_ctx->flags = 0;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009429
Thierry FOURNIERd93ea2b2015-12-20 19:14:52 +01009430 if (txn->req.flags & HTTP_MSGF_VER_11)
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009431 http_ctx->flags |= APPLET_HTTP11;
Thierry FOURNIERd93ea2b2015-12-20 19:14:52 +01009432
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009433 /* Create task used by signal to wakeup applets. */
Willy Tarreaubeeabf52021-10-01 18:23:30 +02009434 task = task_new_here();
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009435 if (!task) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009436 SEND_ERR(strm->be, "Lua applet http '%s': out of memory.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009437 ctx->rule->arg.hlua_rule->fcn->name);
Christopher Fauletc9929382022-05-12 11:52:27 +02009438 return -1;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009439 }
9440 task->nice = 0;
9441 task->context = ctx;
9442 task->process = hlua_applet_wakeup;
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009443 http_ctx->task = task;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009444
9445 /* In the execution wrappers linked with a stream, the
9446 * Lua context can be not initialized. This behavior
9447 * permits to save performances because a systematic
9448 * Lua initialization cause 5% performances loss.
9449 */
Thierry Fournierc7492592020-11-28 23:57:24 +01009450 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 +01009451 SEND_ERR(strm->be, "Lua applet http '%s': can't initialize Lua context.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009452 ctx->rule->arg.hlua_rule->fcn->name);
Christopher Fauletc9929382022-05-12 11:52:27 +02009453 return -1;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009454 }
9455
9456 /* Set timeout according with the applet configuration. */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02009457 hlua->max_time = ctx->applet->timeout;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009458
9459 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009460 if (!SET_SAFE_LJMP(hlua)) {
Thierry Fournierfd107a22016-02-19 19:57:23 +01009461 if (lua_type(hlua->T, -1) == LUA_TSTRING)
9462 error = lua_tostring(hlua->T, -1);
9463 else
9464 error = "critical error";
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009465 SEND_ERR(strm->be, "Lua applet http '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009466 ctx->rule->arg.hlua_rule->fcn->name, error);
Christopher Fauletc9929382022-05-12 11:52:27 +02009467 return -1;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009468 }
9469
9470 /* Check stack available size. */
9471 if (!lua_checkstack(hlua->T, 1)) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009472 SEND_ERR(strm->be, "Lua applet http '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009473 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009474 RESET_SAFE_LJMP(hlua);
Christopher Fauletc9929382022-05-12 11:52:27 +02009475 return -1;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009476 }
9477
9478 /* Restore the function in the stack. */
Thierry Fournierc7492592020-11-28 23:57:24 +01009479 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ctx->rule->arg.hlua_rule->fcn->function_ref[hlua->state_id]);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009480
9481 /* Create and and push object stream in the stack. */
9482 if (!hlua_applet_http_new(hlua->T, ctx)) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009483 SEND_ERR(strm->be, "Lua applet http '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009484 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009485 RESET_SAFE_LJMP(hlua);
Christopher Fauletc9929382022-05-12 11:52:27 +02009486 return -1;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009487 }
9488 hlua->nargs = 1;
9489
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009490 /* push keywords in the stack. */
9491 for (arg = ctx->rule->arg.hlua_rule->args; arg && *arg; arg++) {
9492 if (!lua_checkstack(hlua->T, 1)) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009493 SEND_ERR(strm->be, "Lua applet http '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009494 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009495 RESET_SAFE_LJMP(hlua);
Christopher Fauletc9929382022-05-12 11:52:27 +02009496 return -1;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009497 }
9498 lua_pushstring(hlua->T, *arg);
9499 hlua->nargs++;
9500 }
9501
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009502 RESET_SAFE_LJMP(hlua);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009503
9504 /* Wakeup the applet when data is ready for read. */
Willy Tarreau90e8b452022-05-25 18:21:43 +02009505 applet_need_more_data(ctx);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009506
Christopher Fauletc9929382022-05-12 11:52:27 +02009507 return 0;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009508}
9509
Willy Tarreau60409db2019-08-21 14:14:50 +02009510void hlua_applet_http_fct(struct appctx *ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009511{
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009512 struct hlua_http_ctx *http_ctx = ctx->svcctx;
Willy Tarreau4596fe22022-05-17 19:07:51 +02009513 struct stconn *cs = appctx_cs(ctx);
Willy Tarreauea27f482022-05-18 16:10:52 +02009514 struct stream *strm = __sc_strm(cs);
Willy Tarreau40a9c322022-05-18 15:55:18 +02009515 struct channel *req = sc_oc(cs);
9516 struct channel *res = sc_ic(cs);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009517 struct act_rule *rule = ctx->rule;
9518 struct proxy *px = strm->be;
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009519 struct hlua *hlua = http_ctx->hlua;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009520 struct htx *req_htx, *res_htx;
9521
9522 res_htx = htx_from_buf(&res->buf);
9523
9524 /* If the stream is disconnect or closed, ldo nothing. */
Willy Tarreau026e8fb2022-05-17 19:47:17 +02009525 if (unlikely(cs->state == SC_ST_DIS || cs->state == SC_ST_CLO))
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009526 goto out;
9527
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05009528 /* Check if the input buffer is available. */
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009529 if (!b_size(&res->buf)) {
Willy Tarreau99615ed2022-05-25 07:29:36 +02009530 sc_need_room(cs);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009531 goto out;
9532 }
9533 /* check that the output is not closed */
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01009534 if (res->flags & (CF_SHUTW|CF_SHUTW_NOW|CF_SHUTR))
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009535 http_ctx->flags |= APPLET_DONE;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009536
9537 /* Set the currently running flag. */
9538 if (!HLUA_IS_RUNNING(hlua) &&
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009539 !(http_ctx->flags & APPLET_DONE)) {
Christopher Fauletbd878d22021-04-28 10:50:21 +02009540 if (!co_data(req)) {
Willy Tarreau90e8b452022-05-25 18:21:43 +02009541 applet_need_more_data(ctx);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009542 goto out;
9543 }
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009544 }
9545
9546 /* Executes The applet if it is not done. */
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009547 if (!(http_ctx->flags & APPLET_DONE)) {
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009548
9549 /* Execute the function. */
9550 switch (hlua_ctx_resume(hlua, 1)) {
9551 /* finished. */
9552 case HLUA_E_OK:
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009553 http_ctx->flags |= APPLET_DONE;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009554 break;
9555
9556 /* yield. */
9557 case HLUA_E_AGAIN:
9558 if (hlua->wake_time != TICK_ETERNITY)
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009559 task_schedule(http_ctx->task, hlua->wake_time);
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01009560 goto out;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009561
9562 /* finished with error. */
9563 case HLUA_E_ERRMSG:
9564 /* Display log. */
9565 SEND_ERR(px, "Lua applet http '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009566 rule->arg.hlua_rule->fcn->name, lua_tostring(hlua->T, -1));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009567 lua_pop(hlua->T, 1);
9568 goto error;
9569
9570 case HLUA_E_ETMOUT:
9571 SEND_ERR(px, "Lua applet http '%s': execution timeout.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009572 rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009573 goto error;
9574
9575 case HLUA_E_NOMEM:
9576 SEND_ERR(px, "Lua applet http '%s': out of memory error.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009577 rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009578 goto error;
9579
9580 case HLUA_E_YIELD: /* unexpected */
9581 SEND_ERR(px, "Lua applet http '%s': yield not allowed.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009582 rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009583 goto error;
9584
9585 case HLUA_E_ERR:
9586 /* Display log. */
9587 SEND_ERR(px, "Lua applet http '%s' return an unknown error.\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 default:
9592 goto error;
9593 }
9594 }
9595
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009596 if (http_ctx->flags & APPLET_DONE) {
9597 if (http_ctx->flags & APPLET_RSP_SENT)
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01009598 goto done;
9599
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009600 if (!(http_ctx->flags & APPLET_HDR_SENT))
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009601 goto error;
9602
Christopher Fauletf89af9c2022-04-07 10:07:18 +02009603 /* no more data are expected. If the response buffer is empty
9604 * for a chunked message, be sure to add something (EOT block in
9605 * this case) to have something to send. It is important to be
9606 * sure the EOM flags will be handled by the endpoint.
9607 */
9608 if (htx_is_empty(res_htx) && (strm->txn->rsp.flags & (HTTP_MSGF_XFER_LEN|HTTP_MSGF_CNT_LEN)) == HTTP_MSGF_XFER_LEN) {
9609 if (!htx_add_endof(res_htx, HTX_BLK_EOT)) {
Willy Tarreau99615ed2022-05-25 07:29:36 +02009610 sc_need_room(cs);
Christopher Fauletf89af9c2022-04-07 10:07:18 +02009611 goto out;
9612 }
9613 channel_add_input(res, 1);
9614 }
9615
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01009616 res_htx->flags |= HTX_FL_EOM;
Christopher Fauletd8d27082022-03-07 15:50:54 +01009617 res->flags |= CF_EOI;
Willy Tarreaud869e132022-05-17 18:05:31 +02009618 se_fl_set(ctx->sedesc, SE_FL_EOI);
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009619 strm->txn->status = http_ctx->status;
9620 http_ctx->flags |= APPLET_RSP_SENT;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009621 }
9622
9623 done:
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009624 if (http_ctx->flags & APPLET_DONE) {
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01009625 if (!(res->flags & CF_SHUTR)) {
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009626 res->flags |= CF_READ_NULL;
Christopher Fauletda098e62022-03-31 17:44:45 +02009627 cs_shutr(cs);
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01009628 }
9629
9630 /* eat the whole request */
9631 if (co_data(req)) {
9632 req_htx = htx_from_buf(&req->buf);
9633 co_htx_skip(req, req_htx, co_data(req));
9634 htx_to_buf(req_htx, &req->buf);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009635 }
9636 }
9637
9638 out:
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009639 htx_to_buf(res_htx, &res->buf);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009640 return;
9641
9642 error:
9643
9644 /* If we are in HTTP mode, and we are not send any
9645 * data, return a 500 server error in best effort:
9646 * if there is no room available in the buffer,
9647 * just close the connection.
9648 */
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009649 if (!(http_ctx->flags & APPLET_HDR_SENT)) {
Christopher Fauletf7346382019-07-17 22:02:08 +02009650 struct buffer *err = &http_err_chunks[HTTP_ERR_500];
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009651
9652 channel_erase(res);
9653 res->buf.data = b_data(err);
9654 memcpy(res->buf.area, b_head(err), b_data(err));
9655 res_htx = htx_from_buf(&res->buf);
Christopher Fauletf6cce3f2019-02-27 21:20:09 +01009656 channel_add_input(res, res_htx->data);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009657 }
9658 if (!(strm->flags & SF_ERR_MASK))
9659 strm->flags |= SF_ERR_RESOURCE;
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009660 http_ctx->flags |= APPLET_DONE;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009661 goto done;
9662}
9663
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009664static void hlua_applet_http_release(struct appctx *ctx)
9665{
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009666 struct hlua_http_ctx *http_ctx = ctx->svcctx;
9667
9668 task_destroy(http_ctx->task);
9669 http_ctx->task = NULL;
9670 hlua_ctx_destroy(http_ctx->hlua);
9671 http_ctx->hlua = NULL;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009672}
9673
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009674/* global {tcp|http}-request parser. Return ACT_RET_PRS_OK in
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05009675 * success case, else return ACT_RET_PRS_ERR.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02009676 *
9677 * This function can fail with an abort() due to an Lua critical error.
9678 * We are in the configuration parsing process of HAProxy, this abort() is
9679 * tolerated.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009680 */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009681static enum act_parse_ret action_register_lua(const char **args, int *cur_arg, struct proxy *px,
9682 struct act_rule *rule, char **err)
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009683{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02009684 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009685 int i;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009686
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009687 /* Memory for the rule. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02009688 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009689 if (!rule->arg.hlua_rule) {
9690 memprintf(err, "out of memory error");
Christopher Faulet528526f2021-04-12 14:37:32 +02009691 goto error;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009692 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009693
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009694 /* Memory for arguments. */
Tim Duesterhuse52b6e52020-09-12 20:26:43 +02009695 rule->arg.hlua_rule->args = calloc(fcn->nargs + 1,
9696 sizeof(*rule->arg.hlua_rule->args));
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009697 if (!rule->arg.hlua_rule->args) {
9698 memprintf(err, "out of memory error");
Christopher Faulet528526f2021-04-12 14:37:32 +02009699 goto error;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009700 }
9701
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009702 /* Reference the Lua function and store the reference. */
Thierry Fournierad5345f2020-11-29 02:05:57 +01009703 rule->arg.hlua_rule->fcn = fcn;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009704
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009705 /* Expect some arguments */
9706 for (i = 0; i < fcn->nargs; i++) {
Thierry FOURNIER1725c2e2019-01-06 19:38:49 +01009707 if (*args[*cur_arg] == '\0') {
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009708 memprintf(err, "expect %d arguments", fcn->nargs);
Christopher Faulet528526f2021-04-12 14:37:32 +02009709 goto error;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009710 }
Thierry FOURNIER1725c2e2019-01-06 19:38:49 +01009711 rule->arg.hlua_rule->args[i] = strdup(args[*cur_arg]);
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009712 if (!rule->arg.hlua_rule->args[i]) {
9713 memprintf(err, "out of memory error");
Christopher Faulet528526f2021-04-12 14:37:32 +02009714 goto error;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009715 }
9716 (*cur_arg)++;
9717 }
9718 rule->arg.hlua_rule->args[i] = NULL;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009719
Thierry FOURNIER42148732015-09-02 17:17:33 +02009720 rule->action = ACT_CUSTOM;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009721 rule->action_ptr = hlua_action;
Thierry FOURNIERafa80492015-08-19 09:04:15 +02009722 return ACT_RET_PRS_OK;
Christopher Faulet528526f2021-04-12 14:37:32 +02009723
9724 error:
9725 if (rule->arg.hlua_rule) {
9726 if (rule->arg.hlua_rule->args) {
9727 for (i = 0; i < fcn->nargs; i++)
9728 ha_free(&rule->arg.hlua_rule->args[i]);
9729 ha_free(&rule->arg.hlua_rule->args);
9730 }
9731 ha_free(&rule->arg.hlua_rule);
9732 }
9733 return ACT_RET_PRS_ERR;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009734}
9735
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009736static enum act_parse_ret action_register_service_http(const char **args, int *cur_arg, struct proxy *px,
9737 struct act_rule *rule, char **err)
9738{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02009739 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009740
Thierry FOURNIER718e2a72015-12-20 20:13:14 +01009741 /* HTTP applets are forbidden in tcp-request rules.
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05009742 * HTTP applet request requires everything initialized by
Thierry FOURNIER718e2a72015-12-20 20:13:14 +01009743 * "http_process_request" (analyzer flag AN_REQ_HTTP_INNER).
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05009744 * The applet will be immediately initialized, but its before
Thierry FOURNIER718e2a72015-12-20 20:13:14 +01009745 * the call of this analyzer.
9746 */
9747 if (rule->from != ACT_F_HTTP_REQ) {
9748 memprintf(err, "HTTP applets are forbidden from 'tcp-request' rulesets");
9749 return ACT_RET_PRS_ERR;
9750 }
9751
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009752 /* Memory for the rule. */
9753 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
9754 if (!rule->arg.hlua_rule) {
9755 memprintf(err, "out of memory error");
9756 return ACT_RET_PRS_ERR;
9757 }
9758
9759 /* Reference the Lua function and store the reference. */
Thierry Fournierad5345f2020-11-29 02:05:57 +01009760 rule->arg.hlua_rule->fcn = fcn;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009761
9762 /* TODO: later accept arguments. */
9763 rule->arg.hlua_rule->args = NULL;
9764
9765 /* Add applet pointer in the rule. */
9766 rule->applet.obj_type = OBJ_TYPE_APPLET;
9767 rule->applet.name = fcn->name;
9768 rule->applet.init = hlua_applet_http_init;
9769 rule->applet.fct = hlua_applet_http_fct;
9770 rule->applet.release = hlua_applet_http_release;
9771 rule->applet.timeout = hlua_timeout_applet;
9772
9773 return ACT_RET_PRS_OK;
9774}
9775
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009776/* This function is an LUA binding used for registering
9777 * "sample-conv" functions. It expects a converter name used
9778 * in the haproxy configuration file, and an LUA function.
9779 */
9780__LJMP static int hlua_register_action(lua_State *L)
9781{
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009782 struct action_kw_list *akl = NULL;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009783 const char *name;
9784 int ref;
9785 int len;
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009786 struct hlua_function *fcn = NULL;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009787 int nargs;
Thierry Fournierf67442e2020-11-28 20:41:07 +01009788 struct buffer *trash;
9789 struct action_kw *akw;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009790
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009791 /* Initialise the number of expected arguments at 0. */
9792 nargs = 0;
9793
9794 if (lua_gettop(L) < 3 || lua_gettop(L) > 4)
9795 WILL_LJMP(luaL_error(L, "'register_action' needs between 3 and 4 arguments"));
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009796
9797 /* First argument : converter name. */
9798 name = MAY_LJMP(luaL_checkstring(L, 1));
9799
9800 /* Second argument : environment. */
9801 if (lua_type(L, 2) != LUA_TTABLE)
9802 WILL_LJMP(luaL_error(L, "register_action: second argument must be a table of strings"));
9803
9804 /* Third argument : lua function. */
9805 ref = MAY_LJMP(hlua_checkfunction(L, 3));
9806
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08009807 /* Fourth argument : number of mandatory arguments expected on the configuration line. */
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009808 if (lua_gettop(L) >= 4)
9809 nargs = MAY_LJMP(luaL_checkinteger(L, 4));
9810
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08009811 /* browse the second argument as an array. */
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009812 lua_pushnil(L);
9813 while (lua_next(L, 2) != 0) {
9814 if (lua_type(L, -1) != LUA_TSTRING)
9815 WILL_LJMP(luaL_error(L, "register_action: second argument must be a table of strings"));
9816
Thierry Fournierf67442e2020-11-28 20:41:07 +01009817 /* Check if action exists */
9818 trash = get_trash_chunk();
9819 chunk_printf(trash, "lua.%s", name);
9820 if (strcmp(lua_tostring(L, -1), "tcp-req") == 0) {
9821 akw = tcp_req_cont_action(trash->area);
9822 } else if (strcmp(lua_tostring(L, -1), "tcp-res") == 0) {
9823 akw = tcp_res_cont_action(trash->area);
9824 } else if (strcmp(lua_tostring(L, -1), "http-req") == 0) {
9825 akw = action_http_req_custom(trash->area);
9826 } else if (strcmp(lua_tostring(L, -1), "http-res") == 0) {
9827 akw = action_http_res_custom(trash->area);
9828 } else {
9829 akw = NULL;
9830 }
9831 if (akw != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +01009832 fcn = akw->private;
9833 if (fcn->function_ref[hlua_state_id] != -1) {
9834 ha_warning("Trying to register action 'lua.%s' more than once. "
9835 "This will become a hard error in version 2.5.\n", name);
9836 }
9837 fcn->function_ref[hlua_state_id] = ref;
9838
9839 /* pop the environment string. */
9840 lua_pop(L, 1);
9841 continue;
Thierry Fournierf67442e2020-11-28 20:41:07 +01009842 }
9843
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009844 /* Check required environment. Only accepted "http" or "tcp". */
9845 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02009846 akl = calloc(1, sizeof(*akl) + sizeof(struct action_kw) * 2);
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009847 if (!akl)
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009848 goto alloc_error;;
Thierry Fournier62a22aa2020-11-28 21:06:35 +01009849 fcn = new_hlua_function();
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009850 if (!fcn)
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009851 goto alloc_error;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009852
9853 /* Fill fcn. */
9854 fcn->name = strdup(name);
9855 if (!fcn->name)
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009856 goto alloc_error;
Thierry Fournierc7492592020-11-28 23:57:24 +01009857 fcn->function_ref[hlua_state_id] = ref;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009858
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -07009859 /* Set the expected number of arguments. */
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009860 fcn->nargs = nargs;
9861
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009862 /* List head */
9863 akl->list.n = akl->list.p = NULL;
9864
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009865 /* action keyword. */
9866 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02009867 akl->kw[0].kw = calloc(1, len);
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009868 if (!akl->kw[0].kw)
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009869 goto alloc_error;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009870
9871 snprintf((char *)akl->kw[0].kw, len, "lua.%s", name);
9872
Amaury Denoyellee4a617c2021-05-06 15:33:09 +02009873 akl->kw[0].flags = 0;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009874 akl->kw[0].private = fcn;
9875 akl->kw[0].parse = action_register_lua;
9876
9877 /* select the action registering point. */
9878 if (strcmp(lua_tostring(L, -1), "tcp-req") == 0)
9879 tcp_req_cont_keywords_register(akl);
9880 else if (strcmp(lua_tostring(L, -1), "tcp-res") == 0)
9881 tcp_res_cont_keywords_register(akl);
9882 else if (strcmp(lua_tostring(L, -1), "http-req") == 0)
9883 http_req_keywords_register(akl);
9884 else if (strcmp(lua_tostring(L, -1), "http-res") == 0)
9885 http_res_keywords_register(akl);
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009886 else {
9887 release_hlua_function(fcn);
9888 if (akl)
9889 ha_free((char **)&(akl->kw[0].kw));
9890 ha_free(&akl);
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01009891 WILL_LJMP(luaL_error(L, "Lua action environment '%s' is unknown. "
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009892 "'tcp-req', 'tcp-res', 'http-req' or 'http-res' "
9893 "are expected.", lua_tostring(L, -1)));
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009894 }
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009895
9896 /* pop the environment string. */
9897 lua_pop(L, 1);
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009898
9899 /* reset for next loop */
9900 akl = NULL;
9901 fcn = NULL;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009902 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009903 return ACT_RET_PRS_OK;
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009904
9905 alloc_error:
9906 release_hlua_function(fcn);
9907 ha_free(&akl);
9908 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
9909 return 0; /* Never reached */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009910}
9911
9912static enum act_parse_ret action_register_service_tcp(const char **args, int *cur_arg, struct proxy *px,
9913 struct act_rule *rule, char **err)
9914{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02009915 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009916
Christopher Faulet280f85b2019-07-15 15:02:04 +02009917 if (px->mode == PR_MODE_HTTP) {
9918 memprintf(err, "Lua TCP services cannot be used on HTTP proxies");
Christopher Fauletafd8f102018-11-08 11:34:21 +01009919 return ACT_RET_PRS_ERR;
9920 }
9921
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009922 /* Memory for the rule. */
9923 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
9924 if (!rule->arg.hlua_rule) {
9925 memprintf(err, "out of memory error");
9926 return ACT_RET_PRS_ERR;
9927 }
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009928
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009929 /* Reference the Lua function and store the reference. */
Thierry Fournierad5345f2020-11-29 02:05:57 +01009930 rule->arg.hlua_rule->fcn = fcn;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009931
9932 /* TODO: later accept arguments. */
9933 rule->arg.hlua_rule->args = NULL;
9934
9935 /* Add applet pointer in the rule. */
9936 rule->applet.obj_type = OBJ_TYPE_APPLET;
9937 rule->applet.name = fcn->name;
9938 rule->applet.init = hlua_applet_tcp_init;
9939 rule->applet.fct = hlua_applet_tcp_fct;
9940 rule->applet.release = hlua_applet_tcp_release;
9941 rule->applet.timeout = hlua_timeout_applet;
9942
9943 return 0;
9944}
9945
9946/* This function is an LUA binding used for registering
9947 * "sample-conv" functions. It expects a converter name used
9948 * in the haproxy configuration file, and an LUA function.
9949 */
9950__LJMP static int hlua_register_service(lua_State *L)
9951{
9952 struct action_kw_list *akl;
9953 const char *name;
9954 const char *env;
9955 int ref;
9956 int len;
Christopher Faulet5c028d72021-04-12 15:11:44 +02009957 struct hlua_function *fcn = NULL;
Thierry Fournierf67442e2020-11-28 20:41:07 +01009958 struct buffer *trash;
9959 struct action_kw *akw;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009960
9961 MAY_LJMP(check_args(L, 3, "register_service"));
9962
9963 /* First argument : converter name. */
9964 name = MAY_LJMP(luaL_checkstring(L, 1));
9965
9966 /* Second argument : environment. */
9967 env = MAY_LJMP(luaL_checkstring(L, 2));
9968
9969 /* Third argument : lua function. */
9970 ref = MAY_LJMP(hlua_checkfunction(L, 3));
9971
Thierry Fournierf67442e2020-11-28 20:41:07 +01009972 /* Check for service already registered */
9973 trash = get_trash_chunk();
9974 chunk_printf(trash, "lua.%s", name);
9975 akw = service_find(trash->area);
9976 if (akw != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +01009977 fcn = akw->private;
9978 if (fcn->function_ref[hlua_state_id] != -1) {
9979 ha_warning("Trying to register service 'lua.%s' more than once. "
9980 "This will become a hard error in version 2.5.\n", name);
9981 }
9982 fcn->function_ref[hlua_state_id] = ref;
9983 return 0;
Thierry Fournierf67442e2020-11-28 20:41:07 +01009984 }
9985
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009986 /* Allocate and fill the sample fetch keyword struct. */
9987 akl = calloc(1, sizeof(*akl) + sizeof(struct action_kw) * 2);
9988 if (!akl)
Christopher Faulet5c028d72021-04-12 15:11:44 +02009989 goto alloc_error;
Thierry Fournier62a22aa2020-11-28 21:06:35 +01009990 fcn = new_hlua_function();
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009991 if (!fcn)
Christopher Faulet5c028d72021-04-12 15:11:44 +02009992 goto alloc_error;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009993
9994 /* Fill fcn. */
9995 len = strlen("<lua.>") + strlen(name) + 1;
9996 fcn->name = calloc(1, len);
9997 if (!fcn->name)
Christopher Faulet5c028d72021-04-12 15:11:44 +02009998 goto alloc_error;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009999 snprintf((char *)fcn->name, len, "<lua.%s>", name);
Thierry Fournierc7492592020-11-28 23:57:24 +010010000 fcn->function_ref[hlua_state_id] = ref;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010001
10002 /* List head */
10003 akl->list.n = akl->list.p = NULL;
10004
10005 /* converter keyword. */
10006 len = strlen("lua.") + strlen(name) + 1;
10007 akl->kw[0].kw = calloc(1, len);
10008 if (!akl->kw[0].kw)
Christopher Faulet5c028d72021-04-12 15:11:44 +020010009 goto alloc_error;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010010
10011 snprintf((char *)akl->kw[0].kw, len, "lua.%s", name);
10012
Thierry FOURNIER / OZON.IO02564fd2016-11-12 11:07:05 +010010013 /* Check required environment. Only accepted "http" or "tcp". */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010014 if (strcmp(env, "tcp") == 0)
10015 akl->kw[0].parse = action_register_service_tcp;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010016 else if (strcmp(env, "http") == 0)
10017 akl->kw[0].parse = action_register_service_http;
Christopher Faulet5c028d72021-04-12 15:11:44 +020010018 else {
10019 release_hlua_function(fcn);
10020 if (akl)
10021 ha_free((char **)&(akl->kw[0].kw));
10022 ha_free(&akl);
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +010010023 WILL_LJMP(luaL_error(L, "Lua service environment '%s' is unknown. "
Eric Salamafe7456f2017-12-21 14:30:07 +010010024 "'tcp' or 'http' are expected.", env));
Christopher Faulet5c028d72021-04-12 15:11:44 +020010025 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010026
Amaury Denoyellee4a617c2021-05-06 15:33:09 +020010027 akl->kw[0].flags = 0;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010028 akl->kw[0].private = fcn;
10029
10030 /* End of array. */
10031 memset(&akl->kw[1], 0, sizeof(*akl->kw));
10032
10033 /* Register this new converter */
10034 service_keywords_register(akl);
10035
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010036 return 0;
Christopher Faulet5c028d72021-04-12 15:11:44 +020010037
10038 alloc_error:
10039 release_hlua_function(fcn);
10040 ha_free(&akl);
10041 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
10042 return 0; /* Never reached */
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010043}
10044
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010045/* This function initialises Lua cli handler. It copies the
10046 * arguments in the Lua stack and create channel IO objects.
10047 */
Aurélien Nephtaliabbf6072018-04-18 13:26:46 +020010048static int hlua_cli_parse_fct(char **args, char *payload, struct appctx *appctx, void *private)
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010049{
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010050 struct hlua_cli_ctx *ctx = applet_reserve_svcctx(appctx, sizeof(*ctx));
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010051 struct hlua *hlua;
10052 struct hlua_function *fcn;
10053 int i;
10054 const char *error;
10055
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010056 fcn = private;
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010057 ctx->fcn = private;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +010010058
Willy Tarreaubafbe012017-11-24 17:34:44 +010010059 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +010010060 if (!hlua) {
10061 SEND_ERR(NULL, "Lua cli '%s': out of memory.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +010010062 return 1;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +010010063 }
10064 HLUA_INIT(hlua);
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010065 ctx->hlua = hlua;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010066
10067 /* Create task used by signal to wakeup applets.
Ilya Shipitsind4259502020-04-08 01:07:56 +050010068 * We use the same wakeup function than the Lua applet_tcp and
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010069 * applet_http. It is absolutely compatible.
10070 */
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010071 ctx->task = task_new_here();
10072 if (!ctx->task) {
Thierry FOURNIERffbf5692016-12-16 11:14:06 +010010073 SEND_ERR(NULL, "Lua cli '%s': out of memory.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +010010074 goto error;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010075 }
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010076 ctx->task->nice = 0;
10077 ctx->task->context = appctx;
10078 ctx->task->process = hlua_applet_wakeup;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010079
10080 /* Initialises the Lua context */
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010081 if (!hlua_ctx_init(hlua, fcn_ref_to_stack_id(fcn), ctx->task, 0)) {
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010082 SEND_ERR(NULL, "Lua cli '%s': can't initialize Lua context.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +010010083 goto error;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010084 }
10085
10086 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010087 if (!SET_SAFE_LJMP(hlua)) {
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010088 if (lua_type(hlua->T, -1) == LUA_TSTRING)
10089 error = lua_tostring(hlua->T, -1);
10090 else
10091 error = "critical error";
10092 SEND_ERR(NULL, "Lua cli '%s': %s.\n", fcn->name, error);
10093 goto error;
10094 }
10095
10096 /* Check stack available size. */
10097 if (!lua_checkstack(hlua->T, 2)) {
10098 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
10099 goto error;
10100 }
10101
10102 /* Restore the function in the stack. */
Thierry Fournierc7492592020-11-28 23:57:24 +010010103 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, fcn->function_ref[hlua->state_id]);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010104
10105 /* Once the arguments parsed, the CLI is like an AppletTCP,
10106 * so push AppletTCP in the stack.
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010107 */
10108 if (!hlua_applet_tcp_new(hlua->T, appctx)) {
10109 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
10110 goto error;
10111 }
10112 hlua->nargs = 1;
10113
10114 /* push keywords in the stack. */
10115 for (i = 0; *args[i]; i++) {
10116 /* Check stack available size. */
10117 if (!lua_checkstack(hlua->T, 1)) {
10118 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
10119 goto error;
10120 }
10121 lua_pushstring(hlua->T, args[i]);
10122 hlua->nargs++;
10123 }
10124
10125 /* We must initialize the execution timeouts. */
10126 hlua->max_time = hlua_timeout_session;
10127
10128 /* At this point the execution is safe. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010129 RESET_SAFE_LJMP(hlua);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010130
10131 /* It's ok */
10132 return 0;
10133
10134 /* It's not ok. */
10135error:
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010136 RESET_SAFE_LJMP(hlua);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010137 hlua_ctx_destroy(hlua);
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010138 ctx->hlua = NULL;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010139 return 1;
10140}
10141
10142static int hlua_cli_io_handler_fct(struct appctx *appctx)
10143{
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010144 struct hlua_cli_ctx *ctx = appctx->svcctx;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010145 struct hlua *hlua;
Willy Tarreau4596fe22022-05-17 19:07:51 +020010146 struct stconn *cs;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010147 struct hlua_function *fcn;
10148
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010149 hlua = ctx->hlua;
Willy Tarreau0698c802022-05-11 14:09:57 +020010150 cs = appctx_cs(appctx);
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010151 fcn = ctx->fcn;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010152
10153 /* If the stream is disconnect or closed, ldo nothing. */
Willy Tarreau026e8fb2022-05-17 19:47:17 +020010154 if (unlikely(cs->state == SC_ST_DIS || cs->state == SC_ST_CLO))
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010155 return 1;
10156
10157 /* Execute the function. */
10158 switch (hlua_ctx_resume(hlua, 1)) {
10159
10160 /* finished. */
10161 case HLUA_E_OK:
10162 return 1;
10163
10164 /* yield. */
10165 case HLUA_E_AGAIN:
10166 /* We want write. */
10167 if (HLUA_IS_WAKERESWR(hlua))
Willy Tarreau99615ed2022-05-25 07:29:36 +020010168 sc_need_room(cs);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010169 /* Set the timeout. */
10170 if (hlua->wake_time != TICK_ETERNITY)
10171 task_schedule(hlua->task, hlua->wake_time);
10172 return 0;
10173
10174 /* finished with error. */
10175 case HLUA_E_ERRMSG:
10176 /* Display log. */
10177 SEND_ERR(NULL, "Lua cli '%s': %s.\n",
10178 fcn->name, lua_tostring(hlua->T, -1));
10179 lua_pop(hlua->T, 1);
10180 return 1;
10181
Thierry Fournierd5b073c2018-05-21 19:42:47 +020010182 case HLUA_E_ETMOUT:
10183 SEND_ERR(NULL, "Lua converter '%s': execution timeout.\n",
10184 fcn->name);
10185 return 1;
10186
10187 case HLUA_E_NOMEM:
10188 SEND_ERR(NULL, "Lua converter '%s': out of memory error.\n",
10189 fcn->name);
10190 return 1;
10191
10192 case HLUA_E_YIELD: /* unexpected */
10193 SEND_ERR(NULL, "Lua converter '%s': yield not allowed.\n",
10194 fcn->name);
10195 return 1;
10196
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010197 case HLUA_E_ERR:
10198 /* Display log. */
10199 SEND_ERR(NULL, "Lua cli '%s' return an unknown error.\n",
10200 fcn->name);
10201 return 1;
10202
10203 default:
10204 return 1;
10205 }
10206
10207 return 1;
10208}
10209
10210static void hlua_cli_io_release_fct(struct appctx *appctx)
10211{
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010212 struct hlua_cli_ctx *ctx = appctx->svcctx;
10213
10214 hlua_ctx_destroy(ctx->hlua);
10215 ctx->hlua = NULL;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010216}
10217
10218/* This function is an LUA binding used for registering
10219 * new keywords in the cli. It expects a list of keywords
10220 * which are the "path". It is limited to 5 keywords. A
10221 * description of the command, a function to be executed
10222 * for the parsing and a function for io handlers.
10223 */
10224__LJMP static int hlua_register_cli(lua_State *L)
10225{
10226 struct cli_kw_list *cli_kws;
10227 const char *message;
10228 int ref_io;
10229 int len;
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010230 struct hlua_function *fcn = NULL;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010231 int index;
10232 int i;
Thierry Fournierf67442e2020-11-28 20:41:07 +010010233 struct buffer *trash;
10234 const char *kw[5];
10235 struct cli_kw *cli_kw;
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010236 const char *errmsg;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010237
10238 MAY_LJMP(check_args(L, 3, "register_cli"));
10239
10240 /* First argument : an array of maximum 5 keywords. */
10241 if (!lua_istable(L, 1))
10242 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table"));
10243
10244 /* Second argument : string with contextual message. */
10245 message = MAY_LJMP(luaL_checkstring(L, 2));
10246
10247 /* Third and fourth argument : lua function. */
10248 ref_io = MAY_LJMP(hlua_checkfunction(L, 3));
10249
Thierry Fournierf67442e2020-11-28 20:41:07 +010010250 /* Check for CLI service already registered */
10251 trash = get_trash_chunk();
10252 index = 0;
10253 lua_pushnil(L);
10254 memset(kw, 0, sizeof(kw));
10255 while (lua_next(L, 1) != 0) {
10256 if (index >= CLI_PREFIX_KW_NB)
10257 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table with a maximum of 5 entries"));
10258 if (lua_type(L, -1) != LUA_TSTRING)
10259 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table filled with strings"));
10260 kw[index] = lua_tostring(L, -1);
10261 if (index == 0)
10262 chunk_printf(trash, "%s", kw[index]);
10263 else
10264 chunk_appendf(trash, " %s", kw[index]);
10265 index++;
10266 lua_pop(L, 1);
10267 }
10268 cli_kw = cli_find_kw_exact((char **)kw);
10269 if (cli_kw != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +010010270 fcn = cli_kw->private;
10271 if (fcn->function_ref[hlua_state_id] != -1) {
10272 ha_warning("Trying to register CLI keyword 'lua.%s' more than once. "
10273 "This will become a hard error in version 2.5.\n", trash->area);
10274 }
10275 fcn->function_ref[hlua_state_id] = ref_io;
10276 return 0;
Thierry Fournierf67442e2020-11-28 20:41:07 +010010277 }
10278
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010279 /* Allocate and fill the sample fetch keyword struct. */
10280 cli_kws = calloc(1, sizeof(*cli_kws) + sizeof(struct cli_kw) * 2);
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010281 if (!cli_kws) {
10282 errmsg = "Lua out of memory error.";
10283 goto error;
10284 }
Thierry Fournier62a22aa2020-11-28 21:06:35 +010010285 fcn = new_hlua_function();
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010286 if (!fcn) {
10287 errmsg = "Lua out of memory error.";
10288 goto error;
10289 }
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010290
10291 /* Fill path. */
10292 index = 0;
10293 lua_pushnil(L);
10294 while(lua_next(L, 1) != 0) {
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010295 if (index >= 5) {
10296 errmsg = "1st argument must be a table with a maximum of 5 entries";
10297 goto error;
10298 }
10299 if (lua_type(L, -1) != LUA_TSTRING) {
10300 errmsg = "1st argument must be a table filled with strings";
10301 goto error;
10302 }
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010303 cli_kws->kw[0].str_kw[index] = strdup(lua_tostring(L, -1));
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010304 if (!cli_kws->kw[0].str_kw[index]) {
10305 errmsg = "Lua out of memory error.";
10306 goto error;
10307 }
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010308 index++;
10309 lua_pop(L, 1);
10310 }
10311
10312 /* Copy help message. */
10313 cli_kws->kw[0].usage = strdup(message);
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010314 if (!cli_kws->kw[0].usage) {
10315 errmsg = "Lua out of memory error.";
10316 goto error;
10317 }
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010318
10319 /* Fill fcn io handler. */
10320 len = strlen("<lua.cli>") + 1;
10321 for (i = 0; i < index; i++)
10322 len += strlen(cli_kws->kw[0].str_kw[i]) + 1;
10323 fcn->name = calloc(1, len);
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010324 if (!fcn->name) {
10325 errmsg = "Lua out of memory error.";
10326 goto error;
10327 }
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010328 strncat((char *)fcn->name, "<lua.cli", len);
10329 for (i = 0; i < index; i++) {
10330 strncat((char *)fcn->name, ".", len);
10331 strncat((char *)fcn->name, cli_kws->kw[0].str_kw[i], len);
10332 }
10333 strncat((char *)fcn->name, ">", len);
Thierry Fournierc7492592020-11-28 23:57:24 +010010334 fcn->function_ref[hlua_state_id] = ref_io;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010335
10336 /* Fill last entries. */
10337 cli_kws->kw[0].private = fcn;
10338 cli_kws->kw[0].parse = hlua_cli_parse_fct;
10339 cli_kws->kw[0].io_handler = hlua_cli_io_handler_fct;
10340 cli_kws->kw[0].io_release = hlua_cli_io_release_fct;
10341
10342 /* Register this new converter */
10343 cli_register_kw(cli_kws);
10344
10345 return 0;
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010346
10347 error:
10348 release_hlua_function(fcn);
10349 if (cli_kws) {
10350 for (i = 0; i < index; i++)
10351 ha_free((char **)&(cli_kws->kw[0].str_kw[i]));
10352 ha_free((char **)&(cli_kws->kw[0].usage));
10353 }
10354 ha_free(&cli_kws);
10355 WILL_LJMP(luaL_error(L, errmsg));
10356 return 0; /* Never reached */
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010357}
10358
Christopher Faulet69c581a2021-05-31 08:54:04 +020010359static int hlua_filter_init_per_thread(struct proxy *px, struct flt_conf *fconf)
10360{
10361 struct hlua_flt_config *conf = fconf->conf;
10362 lua_State *L;
10363 int error, pos, state_id, flt_ref;
10364
10365 state_id = reg_flt_to_stack_id(conf->reg);
10366 L = hlua_states[state_id];
10367 pos = lua_gettop(L);
10368
10369 /* The filter parsing function */
10370 lua_rawgeti(L, LUA_REGISTRYINDEX, conf->reg->fun_ref[state_id]);
10371
10372 /* Push the filter class on the stack and resolve all callbacks */
10373 lua_rawgeti(L, LUA_REGISTRYINDEX, conf->reg->flt_ref[state_id]);
10374
10375 /* Duplicate the filter class so each filter will have its own copy */
10376 lua_newtable(L);
10377 lua_pushnil(L);
10378
10379 while (lua_next(L, pos+2)) {
10380 lua_pushvalue(L, -2);
10381 lua_insert(L, -2);
10382 lua_settable(L, -4);
10383 }
10384 flt_ref = luaL_ref(L, LUA_REGISTRYINDEX);
10385
10386 /* Remove the original lua filter class from the stack */
10387 lua_pop(L, 1);
10388
10389 /* Push the copy on the stack */
10390 lua_rawgeti(L, LUA_REGISTRYINDEX, flt_ref);
10391
10392 /* extra args are pushed in a table */
10393 lua_newtable(L);
10394 for (pos = 0; conf->args[pos]; pos++) {
10395 /* Check stack available size. */
10396 if (!lua_checkstack(L, 1)) {
10397 ha_alert("Lua filter '%s' : Lua error : full stack.", conf->reg->name);
10398 goto error;
10399 }
10400 lua_pushstring(L, conf->args[pos]);
10401 lua_rawseti(L, -2, lua_rawlen(L, -2) + 1);
10402 }
10403
10404 error = lua_pcall(L, 2, LUA_MULTRET, 0);
10405 switch (error) {
10406 case LUA_OK:
10407 /* replace the filter ref */
10408 conf->ref[state_id] = flt_ref;
10409 break;
10410 case LUA_ERRRUN:
10411 ha_alert("Lua filter '%s' : runtime error : %s", conf->reg->name, lua_tostring(L, -1));
10412 goto error;
10413 case LUA_ERRMEM:
10414 ha_alert("Lua filter '%s' : out of memory error", conf->reg->name);
10415 goto error;
10416 case LUA_ERRERR:
10417 ha_alert("Lua filter '%s' : message handler error : %s", conf->reg->name, lua_tostring(L, -1));
10418 goto error;
10419#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM <= 503
10420 case LUA_ERRGCMM:
10421 ha_alert("Lua filter '%s' : garbage collector error : %s", conf->reg->name, lua_tostring(L, -1));
10422 goto error;
10423#endif
10424 default:
Ilya Shipitsinff0f2782021-08-22 22:18:07 +050010425 ha_alert("Lua filter '%s' : unknown error : %s", conf->reg->name, lua_tostring(L, -1));
Christopher Faulet69c581a2021-05-31 08:54:04 +020010426 goto error;
10427 }
10428
10429 lua_settop(L, 0);
10430 return 0;
10431
10432 error:
10433 lua_settop(L, 0);
10434 return -1;
10435}
10436
10437static void hlua_filter_deinit_per_thread(struct proxy *px, struct flt_conf *fconf)
10438{
10439 struct hlua_flt_config *conf = fconf->conf;
10440 lua_State *L;
10441 int state_id;
10442
10443 if (!conf)
10444 return;
10445
10446 state_id = reg_flt_to_stack_id(conf->reg);
10447 L = hlua_states[state_id];
10448 luaL_unref(L, LUA_REGISTRYINDEX, conf->ref[state_id]);
10449}
10450
10451static int hlua_filter_init(struct proxy *px, struct flt_conf *fconf)
10452{
10453 struct hlua_flt_config *conf = fconf->conf;
10454 int state_id = reg_flt_to_stack_id(conf->reg);
10455
10456 /* Rely on per-thread init for global scripts */
10457 if (!state_id)
10458 return hlua_filter_init_per_thread(px, fconf);
10459 return 0;
10460}
10461
10462static void hlua_filter_deinit(struct proxy *px, struct flt_conf *fconf)
10463{
10464
10465 if (fconf->conf) {
10466 struct hlua_flt_config *conf = fconf->conf;
10467 int state_id = reg_flt_to_stack_id(conf->reg);
10468 int pos;
10469
10470 /* Rely on per-thread deinit for global scripts */
10471 if (!state_id)
10472 hlua_filter_deinit_per_thread(px, fconf);
10473
10474 for (pos = 0; conf->args[pos]; pos++)
10475 free(conf->args[pos]);
10476 free(conf->args);
10477 }
10478 ha_free(&fconf->conf);
10479 ha_free((char **)&fconf->id);
10480 ha_free(&fconf->ops);
10481}
10482
10483static int hlua_filter_new(struct stream *s, struct filter *filter)
10484{
10485 struct hlua_flt_config *conf = FLT_CONF(filter);
10486 struct hlua_flt_ctx *flt_ctx = NULL;
10487 int ret = 1;
10488
10489 /* In the execution wrappers linked with a stream, the
10490 * Lua context can be not initialized. This behavior
10491 * permits to save performances because a systematic
10492 * Lua initialization cause 5% performances loss.
10493 */
10494 if (!s->hlua) {
10495 struct hlua *hlua;
10496
10497 hlua = pool_alloc(pool_head_hlua);
10498 if (!hlua) {
10499 SEND_ERR(s->be, "Lua filter '%s': can't initialize Lua context.\n",
10500 conf->reg->name);
10501 ret = 0;
10502 goto end;
10503 }
10504 HLUA_INIT(hlua);
10505 s->hlua = hlua;
10506 if (!hlua_ctx_init(s->hlua, reg_flt_to_stack_id(conf->reg), s->task, 0)) {
10507 SEND_ERR(s->be, "Lua filter '%s': can't initialize Lua context.\n",
10508 conf->reg->name);
10509 ret = 0;
10510 goto end;
10511 }
10512 }
10513
10514 flt_ctx = pool_zalloc(pool_head_hlua_flt_ctx);
10515 if (!flt_ctx) {
10516 SEND_ERR(s->be, "Lua filter '%s': can't initialize filter Lua context.\n",
10517 conf->reg->name);
10518 ret = 0;
10519 goto end;
10520 }
10521 flt_ctx->hlua[0] = pool_alloc(pool_head_hlua);
10522 flt_ctx->hlua[1] = pool_alloc(pool_head_hlua);
10523 if (!flt_ctx->hlua[0] || !flt_ctx->hlua[1]) {
10524 SEND_ERR(s->be, "Lua filter '%s': can't initialize filter Lua context.\n",
10525 conf->reg->name);
10526 ret = 0;
10527 goto end;
10528 }
10529 HLUA_INIT(flt_ctx->hlua[0]);
10530 HLUA_INIT(flt_ctx->hlua[1]);
10531 if (!hlua_ctx_init(flt_ctx->hlua[0], reg_flt_to_stack_id(conf->reg), s->task, 0) ||
10532 !hlua_ctx_init(flt_ctx->hlua[1], reg_flt_to_stack_id(conf->reg), s->task, 0)) {
10533 SEND_ERR(s->be, "Lua filter '%s': can't initialize filter Lua context.\n",
10534 conf->reg->name);
10535 ret = 0;
10536 goto end;
10537 }
10538
10539 if (!HLUA_IS_RUNNING(s->hlua)) {
10540 /* The following Lua calls can fail. */
10541 if (!SET_SAFE_LJMP(s->hlua)) {
10542 const char *error;
10543
10544 if (lua_type(s->hlua->T, -1) == LUA_TSTRING)
10545 error = lua_tostring(s->hlua->T, -1);
10546 else
10547 error = "critical error";
10548 SEND_ERR(s->be, "Lua filter '%s': %s.\n", conf->reg->name, error);
10549 ret = 0;
10550 goto end;
10551 }
10552
10553 /* Check stack size. */
10554 if (!lua_checkstack(s->hlua->T, 1)) {
10555 SEND_ERR(s->be, "Lua filter '%s': full stack.\n", conf->reg->name);
Tim Duesterhus22817382021-09-11 23:17:25 +020010556 RESET_SAFE_LJMP(s->hlua);
Christopher Faulet69c581a2021-05-31 08:54:04 +020010557 ret = 0;
10558 goto end;
10559 }
10560
10561 lua_rawgeti(s->hlua->T, LUA_REGISTRYINDEX, conf->ref[s->hlua->state_id]);
10562 if (lua_getfield(s->hlua->T, -1, "new") != LUA_TFUNCTION) {
10563 SEND_ERR(s->be, "Lua filter '%s': 'new' field is not a function.\n",
10564 conf->reg->name);
10565 RESET_SAFE_LJMP(s->hlua);
10566 ret = 0;
10567 goto end;
10568 }
10569 lua_insert(s->hlua->T, -2);
10570
10571 /* Push the copy on the stack */
10572 s->hlua->nargs = 1;
10573
10574 /* We must initialize the execution timeouts. */
10575 s->hlua->max_time = hlua_timeout_session;
10576
10577 /* At this point the execution is safe. */
10578 RESET_SAFE_LJMP(s->hlua);
10579 }
10580
10581 switch (hlua_ctx_resume(s->hlua, 0)) {
10582 case HLUA_E_OK:
10583 /* Nothing returned or not a table, ignore the filter for current stream */
10584 if (!lua_gettop(s->hlua->T) || !lua_istable(s->hlua->T, 1)) {
10585 ret = 0;
10586 goto end;
10587 }
10588
10589 /* Attached the filter pointer to the ctx */
10590 lua_pushstring(s->hlua->T, "__filter");
10591 lua_pushlightuserdata(s->hlua->T, filter);
10592 lua_settable(s->hlua->T, -3);
10593
10594 /* Save a ref on the filter ctx */
10595 lua_pushvalue(s->hlua->T, 1);
10596 flt_ctx->ref = luaL_ref(s->hlua->T, LUA_REGISTRYINDEX);
10597 filter->ctx = flt_ctx;
10598 break;
10599 case HLUA_E_ERRMSG:
10600 SEND_ERR(s->be, "Lua filter '%s' : %s.\n", conf->reg->name, lua_tostring(s->hlua->T, -1));
10601 ret = -1;
10602 goto end;
10603 case HLUA_E_ETMOUT:
10604 SEND_ERR(s->be, "Lua filter '%s' : 'new' execution timeout.\n", conf->reg->name);
10605 ret = 0;
10606 goto end;
10607 case HLUA_E_NOMEM:
10608 SEND_ERR(s->be, "Lua filter '%s' : out of memory error.\n", conf->reg->name);
10609 ret = 0;
10610 goto end;
10611 case HLUA_E_AGAIN:
10612 case HLUA_E_YIELD:
10613 SEND_ERR(s->be, "Lua filter '%s': yield functions like core.tcp() or core.sleep()"
10614 " are not allowed from 'new' function.\n", conf->reg->name);
10615 ret = 0;
10616 goto end;
10617 case HLUA_E_ERR:
10618 SEND_ERR(s->be, "Lua filter '%s': 'new' returns an unknown error.\n", conf->reg->name);
10619 ret = 0;
10620 goto end;
10621 default:
10622 ret = 0;
10623 goto end;
10624 }
10625
10626 end:
10627 if (s->hlua)
10628 lua_settop(s->hlua->T, 0);
10629 if (ret <= 0) {
10630 if (flt_ctx) {
10631 hlua_ctx_destroy(flt_ctx->hlua[0]);
10632 hlua_ctx_destroy(flt_ctx->hlua[1]);
10633 pool_free(pool_head_hlua_flt_ctx, flt_ctx);
10634 }
10635 }
10636 return ret;
10637}
10638
10639static void hlua_filter_delete(struct stream *s, struct filter *filter)
10640{
10641 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10642
10643 luaL_unref(s->hlua->T, LUA_REGISTRYINDEX, flt_ctx->ref);
10644 hlua_ctx_destroy(flt_ctx->hlua[0]);
10645 hlua_ctx_destroy(flt_ctx->hlua[1]);
10646 pool_free(pool_head_hlua_flt_ctx, flt_ctx);
10647 filter->ctx = NULL;
10648}
10649
Christopher Faulet9f55a502020-02-25 15:21:02 +010010650static int hlua_filter_from_payload(struct filter *filter)
10651{
10652 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10653
10654 return (flt_ctx && !!(flt_ctx->flags & HLUA_FLT_CTX_FL_PAYLOAD));
10655}
10656
Christopher Fauletc404f112020-02-26 15:03:09 +010010657static int hlua_filter_callback(struct stream *s, struct filter *filter, const char *fun,
10658 int dir, unsigned int flags)
10659{
10660 struct hlua *flt_hlua;
10661 struct hlua_flt_config *conf = FLT_CONF(filter);
10662 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10663 unsigned int hflags = HLUA_TXN_FLT_CTX;
10664 int ret = 1;
10665
10666 flt_hlua = flt_ctx->hlua[(dir == SMP_OPT_DIR_REQ ? 0 : 1)];
10667 if (!flt_hlua)
10668 goto end;
10669
10670 if (!HLUA_IS_RUNNING(flt_hlua)) {
10671 int extra_idx = lua_gettop(flt_hlua->T);
10672
10673 /* The following Lua calls can fail. */
10674 if (!SET_SAFE_LJMP(flt_hlua)) {
10675 const char *error;
10676
10677 if (lua_type(flt_hlua->T, -1) == LUA_TSTRING)
10678 error = lua_tostring(flt_hlua->T, -1);
10679 else
10680 error = "critical error";
10681 SEND_ERR(s->be, "Lua filter '%s': %s.\n", conf->reg->name, error);
10682 goto end;
10683 }
10684
10685 /* Check stack size. */
10686 if (!lua_checkstack(flt_hlua->T, 3)) {
10687 SEND_ERR(s->be, "Lua filter '%s': full stack.\n", conf->reg->name);
10688 RESET_SAFE_LJMP(flt_hlua);
10689 goto end;
10690 }
10691
10692 lua_rawgeti(flt_hlua->T, LUA_REGISTRYINDEX, flt_ctx->ref);
10693 if (lua_getfield(flt_hlua->T, -1, fun) != LUA_TFUNCTION) {
10694 RESET_SAFE_LJMP(flt_hlua);
10695 goto end;
10696 }
10697 lua_insert(flt_hlua->T, -2);
10698
10699 if (!hlua_txn_new(flt_hlua->T, s, s->be, dir, hflags)) {
10700 SEND_ERR(s->be, "Lua filter '%s': full stack.\n", conf->reg->name);
10701 RESET_SAFE_LJMP(flt_hlua);
10702 goto end;
10703 }
10704 flt_hlua->nargs = 2;
10705
10706 if (flags & HLUA_FLT_CB_ARG_CHN) {
10707 if (dir == SMP_OPT_DIR_REQ)
10708 lua_getfield(flt_hlua->T, -1, "req");
10709 else
10710 lua_getfield(flt_hlua->T, -1, "res");
10711 if (lua_type(flt_hlua->T, -1) == LUA_TTABLE) {
10712 lua_pushstring(flt_hlua->T, "__filter");
10713 lua_pushlightuserdata(flt_hlua->T, filter);
10714 lua_settable(flt_hlua->T, -3);
10715 }
10716 flt_hlua->nargs++;
10717 }
10718 else if (flags & HLUA_FLT_CB_ARG_HTTP_MSG) {
Christopher Fauleteae8afa2020-02-26 17:15:48 +010010719 if (dir == SMP_OPT_DIR_REQ)
10720 lua_getfield(flt_hlua->T, -1, "http_req");
10721 else
10722 lua_getfield(flt_hlua->T, -1, "http_res");
10723 if (lua_type(flt_hlua->T, -1) == LUA_TTABLE) {
10724 lua_pushstring(flt_hlua->T, "__filter");
10725 lua_pushlightuserdata(flt_hlua->T, filter);
10726 lua_settable(flt_hlua->T, -3);
10727 }
10728 flt_hlua->nargs++;
Christopher Fauletc404f112020-02-26 15:03:09 +010010729 }
10730
10731 /* Check stack size. */
10732 if (!lua_checkstack(flt_hlua->T, 1)) {
10733 SEND_ERR(s->be, "Lua filter '%s': full stack.\n", conf->reg->name);
10734 RESET_SAFE_LJMP(flt_hlua);
10735 goto end;
10736 }
10737
10738 while (extra_idx--) {
10739 lua_pushvalue(flt_hlua->T, 1);
10740 lua_remove(flt_hlua->T, 1);
10741 flt_hlua->nargs++;
10742 }
10743
10744 /* We must initialize the execution timeouts. */
10745 flt_hlua->max_time = hlua_timeout_session;
10746
10747 /* At this point the execution is safe. */
10748 RESET_SAFE_LJMP(flt_hlua);
10749 }
10750
10751 switch (hlua_ctx_resume(flt_hlua, !(flags & HLUA_FLT_CB_FINAL))) {
10752 case HLUA_E_OK:
10753 /* Catch the return value if it required */
10754 if ((flags & HLUA_FLT_CB_RETVAL) && lua_gettop(flt_hlua->T) > 0) {
10755 ret = lua_tointeger(flt_hlua->T, -1);
10756 lua_settop(flt_hlua->T, 0); /* Empty the stack. */
10757 }
10758
10759 /* Set timeout in the required channel. */
10760 if (flt_hlua->wake_time != TICK_ETERNITY) {
10761 if (dir == SMP_OPT_DIR_REQ)
10762 s->req.analyse_exp = flt_hlua->wake_time;
10763 else
10764 s->res.analyse_exp = flt_hlua->wake_time;
10765 }
10766 break;
10767 case HLUA_E_AGAIN:
10768 /* Set timeout in the required channel. */
10769 if (flt_hlua->wake_time != TICK_ETERNITY) {
10770 if (dir == SMP_OPT_DIR_REQ)
10771 s->req.analyse_exp = flt_hlua->wake_time;
10772 else
10773 s->res.analyse_exp = flt_hlua->wake_time;
10774 }
10775 /* Some actions can be wake up when a "write" event
10776 * is detected on a response channel. This is useful
10777 * only for actions targeted on the requests.
10778 */
10779 if (HLUA_IS_WAKERESWR(flt_hlua))
10780 s->res.flags |= CF_WAKE_WRITE;
10781 if (HLUA_IS_WAKEREQWR(flt_hlua))
10782 s->req.flags |= CF_WAKE_WRITE;
10783 ret = 0;
10784 goto end;
10785 case HLUA_E_ERRMSG:
10786 SEND_ERR(s->be, "Lua filter '%s' : %s.\n", conf->reg->name, lua_tostring(flt_hlua->T, -1));
10787 ret = -1;
10788 goto end;
10789 case HLUA_E_ETMOUT:
10790 SEND_ERR(s->be, "Lua filter '%s' : '%s' callback execution timeout.\n", conf->reg->name, fun);
10791 goto end;
10792 case HLUA_E_NOMEM:
10793 SEND_ERR(s->be, "Lua filter '%s' : out of memory error.\n", conf->reg->name);
10794 goto end;
10795 case HLUA_E_YIELD:
10796 SEND_ERR(s->be, "Lua filter '%s': yield functions like core.tcp() or core.sleep()"
10797 " are not allowed from '%s' callback.\n", conf->reg->name, fun);
10798 goto end;
10799 case HLUA_E_ERR:
10800 SEND_ERR(s->be, "Lua filter '%s': '%s' returns an unknown error.\n", conf->reg->name, fun);
10801 goto end;
10802 default:
10803 goto end;
10804 }
10805
10806
10807 end:
10808 return ret;
10809}
10810
10811static int hlua_filter_start_analyze(struct stream *s, struct filter *filter, struct channel *chn)
10812{
10813 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10814
10815 flt_ctx->flags = 0;
10816 return hlua_filter_callback(s, filter, "start_analyze",
10817 (!(chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES),
10818 (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_RETVAL | HLUA_FLT_CB_ARG_CHN));
10819}
10820
10821static int hlua_filter_end_analyze(struct stream *s, struct filter *filter, struct channel *chn)
10822{
10823 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10824
10825 flt_ctx->flags &= ~HLUA_FLT_CTX_FL_PAYLOAD;
10826 return hlua_filter_callback(s, filter, "end_analyze",
10827 (!(chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES),
10828 (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_RETVAL | HLUA_FLT_CB_ARG_CHN));
10829}
10830
Christopher Fauleteae8afa2020-02-26 17:15:48 +010010831static int hlua_filter_http_headers(struct stream *s, struct filter *filter, struct http_msg *msg)
10832{
10833 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10834
10835 flt_ctx->flags &= ~HLUA_FLT_CTX_FL_PAYLOAD;
10836 return hlua_filter_callback(s, filter, "http_headers",
10837 (!(msg->chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES),
10838 (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_RETVAL | HLUA_FLT_CB_ARG_HTTP_MSG));
10839}
10840
10841static int hlua_filter_http_payload(struct stream *s, struct filter *filter, struct http_msg *msg,
10842 unsigned int offset, unsigned int len)
10843{
10844 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10845 struct hlua *flt_hlua;
10846 int dir = (!(msg->chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES);
10847 int idx = (dir == SMP_OPT_DIR_REQ ? 0 : 1);
10848 int ret;
10849
10850 flt_hlua = flt_ctx->hlua[idx];
10851 flt_ctx->cur_off[idx] = offset;
10852 flt_ctx->cur_len[idx] = len;
10853 flt_ctx->flags |= HLUA_FLT_CTX_FL_PAYLOAD;
10854 ret = hlua_filter_callback(s, filter, "http_payload", dir, (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_ARG_HTTP_MSG));
10855 if (ret != -1) {
10856 ret = flt_ctx->cur_len[idx];
10857 if (lua_gettop(flt_hlua->T) > 0) {
10858 ret = lua_tointeger(flt_hlua->T, -1);
10859 if (ret > flt_ctx->cur_len[idx])
10860 ret = flt_ctx->cur_len[idx];
10861 lua_settop(flt_hlua->T, 0); /* Empty the stack. */
10862 }
10863 }
10864 return ret;
10865}
10866
10867static int hlua_filter_http_end(struct stream *s, struct filter *filter, struct http_msg *msg)
10868{
10869 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10870
10871 flt_ctx->flags &= ~HLUA_FLT_CTX_FL_PAYLOAD;
10872 return hlua_filter_callback(s, filter, "http_end",
10873 (!(msg->chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES),
10874 (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_RETVAL | HLUA_FLT_CB_ARG_HTTP_MSG));
10875}
10876
Christopher Fauletc404f112020-02-26 15:03:09 +010010877static int hlua_filter_tcp_payload(struct stream *s, struct filter *filter, struct channel *chn,
10878 unsigned int offset, unsigned int len)
10879{
10880 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10881 struct hlua *flt_hlua;
10882 int dir = (!(chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES);
10883 int idx = (dir == SMP_OPT_DIR_REQ ? 0 : 1);
10884 int ret;
10885
10886 flt_hlua = flt_ctx->hlua[idx];
10887 flt_ctx->cur_off[idx] = offset;
10888 flt_ctx->cur_len[idx] = len;
10889 flt_ctx->flags |= HLUA_FLT_CTX_FL_PAYLOAD;
10890 ret = hlua_filter_callback(s, filter, "tcp_payload", dir, (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_ARG_CHN));
10891 if (ret != -1) {
10892 ret = flt_ctx->cur_len[idx];
10893 if (lua_gettop(flt_hlua->T) > 0) {
10894 ret = lua_tointeger(flt_hlua->T, -1);
10895 if (ret > flt_ctx->cur_len[idx])
10896 ret = flt_ctx->cur_len[idx];
10897 lua_settop(flt_hlua->T, 0); /* Empty the stack. */
10898 }
10899 }
10900 return ret;
10901}
10902
Christopher Faulet69c581a2021-05-31 08:54:04 +020010903static int hlua_filter_parse_fct(char **args, int *cur_arg, struct proxy *px,
10904 struct flt_conf *fconf, char **err, void *private)
10905{
10906 struct hlua_reg_filter *reg_flt = private;
10907 lua_State *L;
10908 struct hlua_flt_config *conf = NULL;
10909 const char *flt_id = NULL;
10910 int state_id, pos, flt_flags = 0;
10911 struct flt_ops *hlua_flt_ops = NULL;
10912
10913 state_id = reg_flt_to_stack_id(reg_flt);
10914 L = hlua_states[state_id];
10915
10916 /* Initialize the filter ops with default callbacks */
10917 hlua_flt_ops = calloc(1, sizeof(*hlua_flt_ops));
Christopher Fauletc86bb872021-08-13 08:33:57 +020010918 if (!hlua_flt_ops)
10919 goto error;
Christopher Faulet69c581a2021-05-31 08:54:04 +020010920 hlua_flt_ops->init = hlua_filter_init;
10921 hlua_flt_ops->deinit = hlua_filter_deinit;
10922 if (state_id) {
10923 /* Set per-thread callback if script is loaded per-thread */
10924 hlua_flt_ops->init_per_thread = hlua_filter_init_per_thread;
10925 hlua_flt_ops->deinit_per_thread = hlua_filter_deinit_per_thread;
10926 }
10927 hlua_flt_ops->attach = hlua_filter_new;
10928 hlua_flt_ops->detach = hlua_filter_delete;
10929
10930 /* Push the filter class on the stack and resolve all callbacks */
10931 lua_rawgeti(L, LUA_REGISTRYINDEX, reg_flt->flt_ref[state_id]);
10932
Christopher Fauletc404f112020-02-26 15:03:09 +010010933 if (lua_getfield(L, -1, "start_analyze") == LUA_TFUNCTION)
10934 hlua_flt_ops->channel_start_analyze = hlua_filter_start_analyze;
10935 lua_pop(L, 1);
10936 if (lua_getfield(L, -1, "end_analyze") == LUA_TFUNCTION)
10937 hlua_flt_ops->channel_end_analyze = hlua_filter_end_analyze;
10938 lua_pop(L, 1);
Christopher Fauleteae8afa2020-02-26 17:15:48 +010010939 if (lua_getfield(L, -1, "http_headers") == LUA_TFUNCTION)
10940 hlua_flt_ops->http_headers = hlua_filter_http_headers;
10941 lua_pop(L, 1);
10942 if (lua_getfield(L, -1, "http_payload") == LUA_TFUNCTION)
10943 hlua_flt_ops->http_payload = hlua_filter_http_payload;
10944 lua_pop(L, 1);
10945 if (lua_getfield(L, -1, "http_end") == LUA_TFUNCTION)
10946 hlua_flt_ops->http_end = hlua_filter_http_end;
10947 lua_pop(L, 1);
Christopher Fauletc404f112020-02-26 15:03:09 +010010948 if (lua_getfield(L, -1, "tcp_payload") == LUA_TFUNCTION)
10949 hlua_flt_ops->tcp_payload = hlua_filter_tcp_payload;
10950 lua_pop(L, 1);
Christopher Faulet69c581a2021-05-31 08:54:04 +020010951
10952 /* Get id and flags of the filter class */
10953 if (lua_getfield(L, -1, "id") == LUA_TSTRING)
10954 flt_id = lua_tostring(L, -1);
10955 lua_pop(L, 1);
10956 if (lua_getfield(L, -1, "flags") == LUA_TNUMBER)
10957 flt_flags = lua_tointeger(L, -1);
10958 lua_pop(L, 1);
10959
10960 /* Create the filter config */
10961 conf = calloc(1, sizeof(*conf));
Christopher Fauletc86bb872021-08-13 08:33:57 +020010962 if (!conf)
Christopher Faulet69c581a2021-05-31 08:54:04 +020010963 goto error;
Christopher Faulet69c581a2021-05-31 08:54:04 +020010964 conf->reg = reg_flt;
10965
10966 /* duplicate args */
10967 for (pos = 0; *args[*cur_arg + 1 + pos]; pos++);
10968 conf->args = calloc(pos + 1, sizeof(*conf->args));
Christopher Fauletc86bb872021-08-13 08:33:57 +020010969 if (!conf->args)
10970 goto error;
10971 for (pos = 0; *args[*cur_arg + 1 + pos]; pos++) {
Christopher Faulet69c581a2021-05-31 08:54:04 +020010972 conf->args[pos] = strdup(args[*cur_arg + 1 + pos]);
Christopher Fauletc86bb872021-08-13 08:33:57 +020010973 if (!conf->args[pos])
10974 goto error;
10975 }
Christopher Faulet69c581a2021-05-31 08:54:04 +020010976 conf->args[pos] = NULL;
10977 *cur_arg += pos + 1;
10978
Christopher Fauletc86bb872021-08-13 08:33:57 +020010979 if (flt_id) {
10980 fconf->id = strdup(flt_id);
10981 if (!fconf->id)
10982 goto error;
10983 }
Christopher Faulet69c581a2021-05-31 08:54:04 +020010984 fconf->flags = flt_flags;
10985 fconf->conf = conf;
10986 fconf->ops = hlua_flt_ops;
10987
10988 lua_settop(L, 0);
10989 return 0;
10990
10991 error:
Christopher Fauletc86bb872021-08-13 08:33:57 +020010992 memprintf(err, "Lua filter '%s' : Lua out of memory error", reg_flt->name);
Christopher Faulet69c581a2021-05-31 08:54:04 +020010993 free(hlua_flt_ops);
Christopher Fauletc86bb872021-08-13 08:33:57 +020010994 if (conf && conf->args) {
10995 for (pos = 0; conf->args[pos]; pos++)
10996 free(conf->args[pos]);
10997 free(conf->args);
10998 }
Christopher Faulet69c581a2021-05-31 08:54:04 +020010999 free(conf);
Christopher Fauletc86bb872021-08-13 08:33:57 +020011000 free((char *)fconf->id);
Christopher Faulet69c581a2021-05-31 08:54:04 +020011001 lua_settop(L, 0);
11002 return -1;
11003}
11004
Christopher Fauletc404f112020-02-26 15:03:09 +010011005__LJMP static int hlua_register_data_filter(lua_State *L)
11006{
11007 struct filter *filter;
11008 struct channel *chn;
11009
11010 MAY_LJMP(check_args(L, 2, "register_data_filter"));
11011 MAY_LJMP(luaL_checktype(L, 1, LUA_TTABLE));
11012 chn = MAY_LJMP(hlua_checkchannel(L, 2));
11013
11014 lua_getfield(L, 1, "__filter");
11015 MAY_LJMP(luaL_checktype(L, -1, LUA_TLIGHTUSERDATA));
11016 filter = lua_touserdata (L, -1);
11017 lua_pop(L, 1);
11018
11019 register_data_filter(chn_strm(chn), chn, filter);
11020 return 1;
11021}
11022
11023__LJMP static int hlua_unregister_data_filter(lua_State *L)
11024{
11025 struct filter *filter;
11026 struct channel *chn;
11027
11028 MAY_LJMP(check_args(L, 2, "unregister_data_filter"));
11029 MAY_LJMP(luaL_checktype(L, 1, LUA_TTABLE));
11030 chn = MAY_LJMP(hlua_checkchannel(L, 2));
11031
11032 lua_getfield(L, 1, "__filter");
11033 MAY_LJMP(luaL_checktype(L, -1, LUA_TLIGHTUSERDATA));
11034 filter = lua_touserdata (L, -1);
11035 lua_pop(L, 1);
11036
11037 unregister_data_filter(chn_strm(chn), chn, filter);
11038 return 1;
11039}
11040
Christopher Faulet69c581a2021-05-31 08:54:04 +020011041/* This function is an LUA binding used for registering a filter. It expects a
Ilya Shipitsinff0f2782021-08-22 22:18:07 +050011042 * filter name used in the haproxy configuration file and a LUA function to
Christopher Faulet69c581a2021-05-31 08:54:04 +020011043 * parse configuration arguments.
11044 */
11045__LJMP static int hlua_register_filter(lua_State *L)
11046{
11047 struct buffer *trash;
11048 struct flt_kw_list *fkl;
11049 struct flt_kw *fkw;
11050 const char *name;
11051 struct hlua_reg_filter *reg_flt= NULL;
11052 int flt_ref, fun_ref;
11053 int len;
11054
11055 MAY_LJMP(check_args(L, 3, "register_filter"));
11056
11057 /* First argument : filter name. */
11058 name = MAY_LJMP(luaL_checkstring(L, 1));
11059
11060 /* Second argument : The filter class */
11061 flt_ref = MAY_LJMP(hlua_checktable(L, 2));
11062
11063 /* Third argument : lua function. */
11064 fun_ref = MAY_LJMP(hlua_checkfunction(L, 3));
11065
11066 trash = get_trash_chunk();
11067 chunk_printf(trash, "lua.%s", name);
11068 fkw = flt_find_kw(trash->area);
11069 if (fkw != NULL) {
11070 reg_flt = fkw->private;
11071 if (reg_flt->flt_ref[hlua_state_id] != -1 || reg_flt->fun_ref[hlua_state_id] != -1) {
11072 ha_warning("Trying to register filter 'lua.%s' more than once. "
11073 "This will become a hard error in version 2.5.\n", name);
11074 }
11075 reg_flt->flt_ref[hlua_state_id] = flt_ref;
11076 reg_flt->fun_ref[hlua_state_id] = fun_ref;
11077 return 0;
11078 }
11079
11080 fkl = calloc(1, sizeof(*fkl) + sizeof(struct flt_kw) * 2);
11081 if (!fkl)
11082 goto alloc_error;
11083 fkl->scope = "HLUA";
11084
11085 reg_flt = new_hlua_reg_filter(name);
11086 if (!reg_flt)
11087 goto alloc_error;
11088
11089 reg_flt->flt_ref[hlua_state_id] = flt_ref;
11090 reg_flt->fun_ref[hlua_state_id] = fun_ref;
11091
11092 /* The filter keyword */
11093 len = strlen("lua.") + strlen(name) + 1;
11094 fkl->kw[0].kw = calloc(1, len);
11095 if (!fkl->kw[0].kw)
11096 goto alloc_error;
11097
11098 snprintf((char *)fkl->kw[0].kw, len, "lua.%s", name);
11099
11100 fkl->kw[0].parse = hlua_filter_parse_fct;
11101 fkl->kw[0].private = reg_flt;
11102 memset(&fkl->kw[1], 0, sizeof(*fkl->kw));
11103
11104 /* Register this new filter */
11105 flt_register_keywords(fkl);
11106
11107 return 0;
11108
11109 alloc_error:
11110 release_hlua_reg_filter(reg_flt);
11111 ha_free(&fkl);
11112 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
11113 return 0; /* Never reached */
11114}
11115
Thierry FOURNIERbd413492015-03-03 16:52:26 +010011116static int hlua_read_timeout(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011117 const struct proxy *defpx, const char *file, int line,
Thierry FOURNIERbd413492015-03-03 16:52:26 +010011118 char **err, unsigned int *timeout)
11119{
11120 const char *error;
11121
11122 error = parse_time_err(args[1], timeout, TIME_UNIT_MS);
Willy Tarreau9faebe32019-06-07 19:00:37 +020011123 if (error == PARSE_TIME_OVER) {
11124 memprintf(err, "timer overflow in argument <%s> to <%s> (maximum value is 2147483647 ms or ~24.8 days)",
11125 args[1], args[0]);
11126 return -1;
11127 }
11128 else if (error == PARSE_TIME_UNDER) {
11129 memprintf(err, "timer underflow in argument <%s> to <%s> (minimum non-null value is 1 ms)",
11130 args[1], args[0]);
11131 return -1;
11132 }
11133 else if (error) {
Thierry FOURNIERbd413492015-03-03 16:52:26 +010011134 memprintf(err, "%s: invalid timeout", args[0]);
11135 return -1;
11136 }
11137 return 0;
11138}
11139
11140static int hlua_session_timeout(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011141 const struct proxy *defpx, const char *file, int line,
Thierry FOURNIERbd413492015-03-03 16:52:26 +010011142 char **err)
11143{
11144 return hlua_read_timeout(args, section_type, curpx, defpx,
11145 file, line, err, &hlua_timeout_session);
11146}
11147
11148static int hlua_task_timeout(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011149 const struct proxy *defpx, const char *file, int line,
Thierry FOURNIERbd413492015-03-03 16:52:26 +010011150 char **err)
11151{
11152 return hlua_read_timeout(args, section_type, curpx, defpx,
11153 file, line, err, &hlua_timeout_task);
11154}
11155
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020011156static int hlua_applet_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 FOURNIERf0a64b62015-09-19 12:36:17 +020011158 char **err)
11159{
11160 return hlua_read_timeout(args, section_type, curpx, defpx,
11161 file, line, err, &hlua_timeout_applet);
11162}
11163
Thierry FOURNIERee9f8022015-03-03 17:37:37 +010011164static int hlua_forced_yield(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 FOURNIERee9f8022015-03-03 17:37:37 +010011166 char **err)
11167{
11168 char *error;
11169
11170 hlua_nb_instruction = strtoll(args[1], &error, 10);
11171 if (*error != '\0') {
11172 memprintf(err, "%s: invalid number", args[0]);
11173 return -1;
11174 }
11175 return 0;
11176}
11177
Willy Tarreau32f61e22015-03-18 17:54:59 +010011178static int hlua_parse_maxmem(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011179 const struct proxy *defpx, const char *file, int line,
Willy Tarreau32f61e22015-03-18 17:54:59 +010011180 char **err)
11181{
11182 char *error;
11183
11184 if (*(args[1]) == 0) {
11185 memprintf(err, "'%s' expects an integer argument (Lua memory size in MB).\n", args[0]);
11186 return -1;
11187 }
11188 hlua_global_allocator.limit = strtoll(args[1], &error, 10) * 1024L * 1024L;
11189 if (*error != '\0') {
11190 memprintf(err, "%s: invalid number %s (error at '%c')", args[0], args[1], *error);
11191 return -1;
11192 }
11193 return 0;
11194}
11195
11196
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011197/* This function is called by the main configuration key "lua-load". It loads and
11198 * execute an lua file during the parsing of the HAProxy configuration file. It is
11199 * the main lua entry point.
11200 *
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -080011201 * This function runs with the HAProxy keywords API. It returns -1 if an error
11202 * occurs, otherwise it returns 0.
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011203 *
11204 * In some error case, LUA set an error message in top of the stack. This function
11205 * returns this error message in the HAProxy logs and pop it from the stack.
Thierry FOURNIERbabae282015-09-17 11:36:37 +020011206 *
11207 * This function can fail with an abort() due to an Lua critical error.
11208 * We are in the configuration parsing process of HAProxy, this abort() is
11209 * tolerated.
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011210 */
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011211static int hlua_load_state(char *filename, lua_State *L, char **err)
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011212{
11213 int error;
11214
11215 /* Just load and compile the file. */
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011216 error = luaL_loadfile(L, filename);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011217 if (error) {
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011218 memprintf(err, "error in Lua file '%s': %s", filename, lua_tostring(L, -1));
11219 lua_pop(L, 1);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011220 return -1;
11221 }
11222
11223 /* If no syntax error where detected, execute the code. */
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011224 error = lua_pcall(L, 0, LUA_MULTRET, 0);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011225 switch (error) {
11226 case LUA_OK:
11227 break;
11228 case LUA_ERRRUN:
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011229 memprintf(err, "Lua runtime error: %s\n", lua_tostring(L, -1));
11230 lua_pop(L, 1);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011231 return -1;
11232 case LUA_ERRMEM:
Thierry Fournierde6145f2020-11-29 00:55:53 +010011233 memprintf(err, "Lua out of memory error\n");
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011234 return -1;
11235 case LUA_ERRERR:
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011236 memprintf(err, "Lua message handler error: %s\n", lua_tostring(L, -1));
11237 lua_pop(L, 1);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011238 return -1;
Christopher Faulet08ed98f2020-07-28 10:33:25 +020011239#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM <= 503
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011240 case LUA_ERRGCMM:
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011241 memprintf(err, "Lua garbage collector error: %s\n", lua_tostring(L, -1));
11242 lua_pop(L, 1);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011243 return -1;
Christopher Faulet08ed98f2020-07-28 10:33:25 +020011244#endif
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011245 default:
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011246 memprintf(err, "Lua unknown error: %s\n", lua_tostring(L, -1));
11247 lua_pop(L, 1);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011248 return -1;
11249 }
11250
11251 return 0;
11252}
11253
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011254static int hlua_load(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011255 const struct proxy *defpx, const char *file, int line,
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011256 char **err)
11257{
11258 if (*(args[1]) == 0) {
11259 memprintf(err, "'%s' expects a file name as parameter.\n", args[0]);
11260 return -1;
11261 }
11262
Thierry Fournier59f11be2020-11-29 00:37:41 +010011263 /* loading for global state */
Thierry Fournierc7492592020-11-28 23:57:24 +010011264 hlua_state_id = 0;
Willy Tarreau43ab05b2021-09-28 09:43:11 +020011265 ha_set_thread(NULL);
Thierry Fournierafc63e22020-11-28 17:06:51 +010011266 return hlua_load_state(args[1], hlua_states[0], err);
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011267}
11268
Thierry Fournier59f11be2020-11-29 00:37:41 +010011269static int hlua_load_per_thread(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011270 const struct proxy *defpx, const char *file, int line,
Thierry Fournier59f11be2020-11-29 00:37:41 +010011271 char **err)
11272{
11273 int len;
11274
11275 if (*(args[1]) == 0) {
11276 memprintf(err, "'%s' expects a file as parameter.\n", args[0]);
11277 return -1;
11278 }
11279
11280 if (per_thread_load == NULL) {
11281 /* allocate the first entry large enough to store the final NULL */
11282 per_thread_load = calloc(1, sizeof(*per_thread_load));
11283 if (per_thread_load == NULL) {
11284 memprintf(err, "out of memory error");
11285 return -1;
11286 }
11287 }
11288
11289 /* count used entries */
11290 for (len = 0; per_thread_load[len] != NULL; len++)
11291 ;
11292
11293 per_thread_load = realloc(per_thread_load, (len + 2) * sizeof(*per_thread_load));
11294 if (per_thread_load == NULL) {
11295 memprintf(err, "out of memory error");
11296 return -1;
11297 }
11298
11299 per_thread_load[len] = strdup(args[1]);
11300 per_thread_load[len + 1] = NULL;
11301
11302 if (per_thread_load[len] == NULL) {
11303 memprintf(err, "out of memory error");
11304 return -1;
11305 }
11306
11307 /* loading for thread 1 only */
11308 hlua_state_id = 1;
Willy Tarreau43ab05b2021-09-28 09:43:11 +020011309 ha_set_thread(NULL);
Thierry Fournier59f11be2020-11-29 00:37:41 +010011310 return hlua_load_state(args[1], hlua_states[1], err);
11311}
11312
Tim Duesterhusc9fc9f22020-01-12 13:55:39 +010011313/* Prepend the given <path> followed by a semicolon to the `package.<type>` variable
11314 * in the given <ctx>.
11315 */
Thierry Fournier3fb9e512020-11-28 10:13:12 +010011316static int hlua_prepend_path(lua_State *L, char *type, char *path)
Tim Duesterhusc9fc9f22020-01-12 13:55:39 +010011317{
Thierry Fournier3fb9e512020-11-28 10:13:12 +010011318 lua_getglobal(L, "package"); /* push package variable */
11319 lua_pushstring(L, path); /* push given path */
11320 lua_pushstring(L, ";"); /* push semicolon */
11321 lua_getfield(L, -3, type); /* push old path */
11322 lua_concat(L, 3); /* concatenate to new path */
11323 lua_setfield(L, -2, type); /* store new path */
11324 lua_pop(L, 1); /* pop package variable */
Tim Duesterhusc9fc9f22020-01-12 13:55:39 +010011325
11326 return 0;
11327}
11328
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010011329static int hlua_config_prepend_path(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011330 const struct proxy *defpx, const char *file, int line,
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010011331 char **err)
11332{
11333 char *path;
11334 char *type = "path";
Tim Duesterhus621e74a2021-01-03 20:04:36 +010011335 struct prepend_path *p = NULL;
Bertrand Jacquin7fbc7702021-11-24 21:16:06 +000011336 size_t i;
Thierry Fournier59f11be2020-11-29 00:37:41 +010011337
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010011338 if (too_many_args(2, args, err, NULL)) {
Tim Duesterhus621e74a2021-01-03 20:04:36 +010011339 goto err;
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010011340 }
11341
11342 if (!(*args[1])) {
11343 memprintf(err, "'%s' expects to receive a <path> as argument", args[0]);
Tim Duesterhus621e74a2021-01-03 20:04:36 +010011344 goto err;
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010011345 }
11346 path = args[1];
11347
11348 if (*args[2]) {
11349 if (strcmp(args[2], "path") != 0 && strcmp(args[2], "cpath") != 0) {
11350 memprintf(err, "'%s' expects <type> to either be 'path' or 'cpath'", args[0]);
Tim Duesterhus621e74a2021-01-03 20:04:36 +010011351 goto err;
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010011352 }
11353 type = args[2];
11354 }
11355
Thierry Fournier59f11be2020-11-29 00:37:41 +010011356 p = calloc(1, sizeof(*p));
11357 if (p == NULL) {
Tim Duesterhusf89d43a2021-01-03 20:04:37 +010011358 memprintf(err, "memory allocation failed");
Tim Duesterhus621e74a2021-01-03 20:04:36 +010011359 goto err;
Thierry Fournier59f11be2020-11-29 00:37:41 +010011360 }
11361 p->path = strdup(path);
11362 if (p->path == NULL) {
Tim Duesterhusf89d43a2021-01-03 20:04:37 +010011363 memprintf(err, "memory allocation failed");
Tim Duesterhus621e74a2021-01-03 20:04:36 +010011364 goto err2;
Thierry Fournier59f11be2020-11-29 00:37:41 +010011365 }
11366 p->type = strdup(type);
11367 if (p->type == NULL) {
Tim Duesterhusf89d43a2021-01-03 20:04:37 +010011368 memprintf(err, "memory allocation failed");
Tim Duesterhus621e74a2021-01-03 20:04:36 +010011369 goto err2;
Thierry Fournier59f11be2020-11-29 00:37:41 +010011370 }
Willy Tarreau2b718102021-04-21 07:32:39 +020011371 LIST_APPEND(&prepend_path_list, &p->l);
Thierry Fournier59f11be2020-11-29 00:37:41 +010011372
Tim Duesterhus9e5e5862021-10-11 18:51:08 +020011373 /* Handle the global state and the per-thread state for the first
11374 * thread. The remaining threads will be initialized based on
11375 * prepend_path_list.
11376 */
Bertrand Jacquin7fbc7702021-11-24 21:16:06 +000011377 for (i = 0; i < 2; i++) {
Tim Duesterhus9e5e5862021-10-11 18:51:08 +020011378 lua_State *L = hlua_states[i];
11379 const char *error;
11380
11381 if (setjmp(safe_ljmp_env) != 0) {
11382 lua_atpanic(L, hlua_panic_safe);
11383 if (lua_type(L, -1) == LUA_TSTRING)
11384 error = lua_tostring(L, -1);
11385 else
11386 error = "critical error";
11387 fprintf(stderr, "lua-prepend-path: %s.\n", error);
11388 exit(1);
11389 } else {
11390 lua_atpanic(L, hlua_panic_ljmp);
11391 }
11392
11393 hlua_prepend_path(L, type, path);
11394
11395 lua_atpanic(L, hlua_panic_safe);
11396 }
11397
Thierry Fournier59f11be2020-11-29 00:37:41 +010011398 return 0;
Tim Duesterhus621e74a2021-01-03 20:04:36 +010011399
11400err2:
11401 free(p->type);
11402 free(p->path);
11403err:
11404 free(p);
11405 return -1;
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010011406}
11407
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011408/* configuration keywords declaration */
11409static struct cfg_kw_list cfg_kws = {{ },{
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010011410 { CFG_GLOBAL, "lua-prepend-path", hlua_config_prepend_path },
Thierry FOURNIERbd413492015-03-03 16:52:26 +010011411 { CFG_GLOBAL, "lua-load", hlua_load },
Thierry Fournier59f11be2020-11-29 00:37:41 +010011412 { CFG_GLOBAL, "lua-load-per-thread", hlua_load_per_thread },
Thierry FOURNIERbd413492015-03-03 16:52:26 +010011413 { CFG_GLOBAL, "tune.lua.session-timeout", hlua_session_timeout },
11414 { CFG_GLOBAL, "tune.lua.task-timeout", hlua_task_timeout },
Thierry FOURNIER56da1012015-10-01 08:42:31 +020011415 { CFG_GLOBAL, "tune.lua.service-timeout", hlua_applet_timeout },
Thierry FOURNIERee9f8022015-03-03 17:37:37 +010011416 { CFG_GLOBAL, "tune.lua.forced-yield", hlua_forced_yield },
Willy Tarreau32f61e22015-03-18 17:54:59 +010011417 { CFG_GLOBAL, "tune.lua.maxmem", hlua_parse_maxmem },
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011418 { 0, NULL, NULL },
11419}};
11420
Willy Tarreau0108d902018-11-25 19:14:37 +010011421INITCALL1(STG_REGISTER, cfg_register_keywords, &cfg_kws);
11422
William Lallemand52139182022-03-30 15:05:42 +020011423#ifdef USE_OPENSSL
Christopher Fauletafd8f102018-11-08 11:34:21 +010011424
William Lallemand30fcca12022-03-30 12:03:12 +020011425/*
11426 * This function replace a ckch_store by another one, and rebuild the ckch_inst and all its dependencies.
11427 * It does the sam as "cli_io_handler_commit_cert" but for lua, the major
11428 * difference is that the yield in lua and for the CLI is not handled the same
11429 * way.
11430 */
11431__LJMP static int hlua_ckch_commit_yield(lua_State *L, int status, lua_KContext ctx)
11432{
11433 struct ckch_inst **lua_ckchi = lua_touserdata(L, -1);
11434 struct ckch_store **lua_ckchs = lua_touserdata(L, -2);
11435 struct ckch_inst *ckchi = *lua_ckchi;
11436 struct ckch_store *old_ckchs = lua_ckchs[0];
11437 struct ckch_store *new_ckchs = lua_ckchs[1];
11438 struct hlua *hlua;
11439 char *err = NULL;
11440 int y = 1;
11441
11442 hlua = hlua_gethlua(L);
11443
11444 /* get the first ckchi to copy */
11445 if (ckchi == NULL)
11446 ckchi = LIST_ELEM(old_ckchs->ckch_inst.n, typeof(ckchi), by_ckchs);
11447
11448 /* walk through the old ckch_inst and creates new ckch_inst using the updated ckchs */
11449 list_for_each_entry_from(ckchi, &old_ckchs->ckch_inst, by_ckchs) {
11450 struct ckch_inst *new_inst;
11451
11452 /* it takes a lot of CPU to creates SSL_CTXs, so we yield every 10 CKCH instances */
11453 if (y % 10 == 0) {
11454
11455 *lua_ckchi = ckchi;
11456
11457 task_wakeup(hlua->task, TASK_WOKEN_MSG);
11458 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_ckch_commit_yield, TICK_ETERNITY, 0));
11459 }
11460
11461 if (ckch_inst_rebuild(new_ckchs, ckchi, &new_inst, &err))
11462 goto error;
11463
11464 /* link the new ckch_inst to the duplicate */
11465 LIST_APPEND(&new_ckchs->ckch_inst, &new_inst->by_ckchs);
11466 y++;
11467 }
11468
11469 /* The generation is finished, we can insert everything */
11470 ckch_store_replace(old_ckchs, new_ckchs);
11471
11472 lua_pop(L, 2); /* pop the lua_ckchs and ckchi */
11473
11474 HA_SPIN_UNLOCK(CKCH_LOCK, &ckch_lock);
11475
11476 return 0;
11477
11478error:
11479 ckch_store_free(new_ckchs);
11480 HA_SPIN_UNLOCK(CKCH_LOCK, &ckch_lock);
11481 WILL_LJMP(luaL_error(L, "%s", err));
11482 free(err);
11483
11484 return 0;
11485}
11486
11487/*
11488 * Replace a ckch_store <filename> in the ckchs_tree with a ckch_store created
11489 * from the table in parameter.
11490 *
11491 * This is equivalent to "set ssl cert" + "commit ssl cert" over the CLI, which
11492 * means it does not need to have a transaction since everything is done in the
11493 * same function.
11494 *
11495 * CertCache.set{filename="", crt="", key="", sctl="", ocsp="", issuer=""}
11496 *
11497 */
11498__LJMP static int hlua_ckch_set(lua_State *L)
11499{
11500 struct hlua *hlua;
11501 struct ckch_inst **lua_ckchi;
11502 struct ckch_store **lua_ckchs;
11503 struct ckch_store *old_ckchs = NULL;
11504 struct ckch_store *new_ckchs = NULL;
11505 int errcode = 0;
11506 char *err = NULL;
11507 struct cert_exts *cert_ext = NULL;
11508 char *filename;
11509 struct cert_key_and_chain *ckch;
11510 int ret;
11511
11512 if (lua_type(L, -1) != LUA_TTABLE)
11513 WILL_LJMP(luaL_error(L, "'CertCache.set' needs a table as argument"));
11514
11515 hlua = hlua_gethlua(L);
11516
11517 /* FIXME: this should not return an error but should come back later */
11518 if (HA_SPIN_TRYLOCK(CKCH_LOCK, &ckch_lock))
11519 WILL_LJMP(luaL_error(L, "CertCache already under lock"));
11520
11521 ret = lua_getfield(L, -1, "filename");
11522 if (ret != LUA_TSTRING) {
11523 memprintf(&err, "%sNo filename specified!\n", err ? err : "");
11524 errcode |= ERR_ALERT | ERR_FATAL;
11525 goto end;
11526 }
11527 filename = (char *)lua_tostring(L, -1);
11528
11529
11530 /* look for the filename in the tree */
11531 old_ckchs = ckchs_lookup(filename);
11532 if (!old_ckchs) {
11533 memprintf(&err, "%sCan't replace a certificate which is not referenced by the configuration!\n", err ? err : "");
11534 errcode |= ERR_ALERT | ERR_FATAL;
11535 goto end;
11536 }
11537 /* TODO: handle extra_files_noext */
11538
11539 new_ckchs = ckchs_dup(old_ckchs);
11540 if (!new_ckchs) {
11541 memprintf(&err, "%sCannot allocate memory!\n", err ? err : "");
11542 errcode |= ERR_ALERT | ERR_FATAL;
11543 goto end;
11544 }
11545
11546 ckch = new_ckchs->ckch;
11547
11548 /* loop on the field in the table, which have the same name as the
11549 * possible extensions of files */
11550 lua_pushnil(L);
11551 while (lua_next(L, 1)) {
11552 int i;
11553 const char *field = lua_tostring(L, -2);
11554 char *payload = (char *)lua_tostring(L, -1);
11555
11556 if (!field || strcmp(field, "filename") == 0) {
11557 lua_pop(L, 1);
11558 continue;
11559 }
11560
11561 for (i = 0; field && cert_exts[i].ext != NULL; i++) {
11562 if (strcmp(field, cert_exts[i].ext) == 0) {
11563 cert_ext = &cert_exts[i];
11564 break;
11565 }
11566 }
11567
11568 /* this is the default type, the field is not supported */
11569 if (cert_ext == NULL) {
11570 memprintf(&err, "%sUnsupported field '%s'\n", err ? err : "", field);
11571 errcode |= ERR_ALERT | ERR_FATAL;
11572 goto end;
11573 }
11574
11575 /* appply the change on the duplicate */
William Lallemandd8c195a2022-05-26 11:20:13 +020011576 if (cert_ext->load(filename, payload, ckch, &err) != 0) {
11577 memprintf(&err, "%sCan't load the payload for '%s'\n", err ? err : "", cert_ext->ext);
William Lallemand30fcca12022-03-30 12:03:12 +020011578 errcode |= ERR_ALERT | ERR_FATAL;
11579 goto end;
11580 }
11581 lua_pop(L, 1);
11582 }
11583
11584 /* store the pointers on the lua stack */
11585 lua_ckchs = lua_newuserdata(L, sizeof(struct ckch_store *) * 2);
11586 lua_ckchs[0] = old_ckchs;
11587 lua_ckchs[1] = new_ckchs;
11588 lua_ckchi = lua_newuserdata(L, sizeof(struct ckch_inst *));
11589 *lua_ckchi = NULL;
11590
11591 task_wakeup(hlua->task, TASK_WOKEN_MSG);
11592 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_ckch_commit_yield, TICK_ETERNITY, 0));
11593
11594end:
11595 HA_SPIN_UNLOCK(CKCH_LOCK, &ckch_lock);
11596
11597 if (errcode & ERR_CODE) {
11598 ckch_store_free(new_ckchs);
11599 WILL_LJMP(luaL_error(L, "%s", err));
11600 }
11601 free(err);
11602
11603 return 0;
11604}
11605
William Lallemand52139182022-03-30 15:05:42 +020011606#else
11607
11608__LJMP static int hlua_ckch_set(lua_State *L)
11609{
11610 WILL_LJMP(luaL_error(L, "'CertCache.set' needs an HAProxy built with OpenSSL"));
11611
11612 return 0;
11613}
11614#endif /* ! USE_OPENSSL */
11615
11616
11617
Thierry FOURNIERbabae282015-09-17 11:36:37 +020011618/* This function can fail with an abort() due to an Lua critical error.
11619 * We are in the initialisation process of HAProxy, this abort() is
11620 * tolerated.
11621 */
Thierry Fournierb8cef172020-11-28 15:37:17 +010011622int hlua_post_init_state(lua_State *L)
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010011623{
11624 struct hlua_init_function *init;
11625 const char *msg;
11626 enum hlua_exec ret;
Thierry Fournierfd107a22016-02-19 19:57:23 +010011627 const char *error;
Thierry Fournier670db242020-11-28 10:49:59 +010011628 const char *kind;
11629 const char *trace;
11630 int return_status = 1;
11631#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM >= 504
11632 int nres;
11633#endif
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010011634
Willy Tarreaucdb53462020-12-02 12:12:00 +010011635 /* disable memory limit checks if limit is not set */
11636 if (!hlua_global_allocator.limit)
11637 hlua_global_allocator.limit = ~hlua_global_allocator.limit;
11638
Ilya Shipitsin856aabc2020-04-16 23:51:34 +050011639 /* Call post initialisation function in safe environment. */
Thierry Fournier3c539322020-11-28 16:05:05 +010011640 if (setjmp(safe_ljmp_env) != 0) {
11641 lua_atpanic(L, hlua_panic_safe);
Thierry Fournierb8cef172020-11-28 15:37:17 +010011642 if (lua_type(L, -1) == LUA_TSTRING)
11643 error = lua_tostring(L, -1);
Thierry Fournier3d4a6752016-02-19 20:53:30 +010011644 else
11645 error = "critical error";
11646 fprintf(stderr, "Lua post-init: %s.\n", error);
11647 exit(1);
Thierry Fournier3c539322020-11-28 16:05:05 +010011648 } else {
11649 lua_atpanic(L, hlua_panic_ljmp);
Thierry Fournier3d4a6752016-02-19 20:53:30 +010011650 }
Frédéric Lécaille54f2bcf2018-08-29 13:46:24 +020011651
Thierry Fournierb8cef172020-11-28 15:37:17 +010011652 hlua_fcn_post_init(L);
Thierry Fournier3d4a6752016-02-19 20:53:30 +010011653
Thierry Fournierc7492592020-11-28 23:57:24 +010011654 list_for_each_entry(init, &hlua_init_functions[hlua_state_id], l) {
Thierry Fournierb8cef172020-11-28 15:37:17 +010011655 lua_rawgeti(L, LUA_REGISTRYINDEX, init->function_ref);
Thierry Fournier670db242020-11-28 10:49:59 +010011656
11657#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM >= 504
Thierry Fournierb8cef172020-11-28 15:37:17 +010011658 ret = lua_resume(L, L, 0, &nres);
Thierry Fournier670db242020-11-28 10:49:59 +010011659#else
Thierry Fournierb8cef172020-11-28 15:37:17 +010011660 ret = lua_resume(L, L, 0);
Thierry Fournier670db242020-11-28 10:49:59 +010011661#endif
11662 kind = NULL;
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010011663 switch (ret) {
Thierry Fournier670db242020-11-28 10:49:59 +010011664
11665 case LUA_OK:
Thierry Fournierb8cef172020-11-28 15:37:17 +010011666 lua_pop(L, -1);
Thierry Fournier13d08b72020-11-28 11:02:58 +010011667 break;
Thierry Fournier670db242020-11-28 10:49:59 +010011668
11669 case LUA_ERRERR:
11670 kind = "message handler error";
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -070011671 /* Fall through */
Thierry Fournier670db242020-11-28 10:49:59 +010011672 case LUA_ERRRUN:
11673 if (!kind)
11674 kind = "runtime error";
Thierry Fournierb8cef172020-11-28 15:37:17 +010011675 msg = lua_tostring(L, -1);
11676 lua_settop(L, 0); /* Empty the stack. */
11677 lua_pop(L, 1);
Christopher Fauletd09cc512021-03-24 14:48:45 +010011678 trace = hlua_traceback(L, ", ");
Thierry Fournier670db242020-11-28 10:49:59 +010011679 if (msg)
11680 ha_alert("Lua init: %s: '%s' from %s\n", kind, msg, trace);
11681 else
11682 ha_alert("Lua init: unknown %s from %s\n", kind, trace);
11683 return_status = 0;
11684 break;
11685
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010011686 default:
Thierry Fournier670db242020-11-28 10:49:59 +010011687 /* Unknown error */
11688 kind = "Unknown error";
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -070011689 /* Fall through */
Thierry Fournier670db242020-11-28 10:49:59 +010011690 case LUA_YIELD:
11691 /* yield is not configured at this step, this state doesn't happen */
11692 if (!kind)
11693 kind = "yield not allowed";
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -070011694 /* Fall through */
Thierry Fournier670db242020-11-28 10:49:59 +010011695 case LUA_ERRMEM:
11696 if (!kind)
11697 kind = "out of memory error";
Thierry Fournierb8cef172020-11-28 15:37:17 +010011698 lua_settop(L, 0);
11699 lua_pop(L, 1);
Christopher Fauletd09cc512021-03-24 14:48:45 +010011700 trace = hlua_traceback(L, ", ");
Thierry Fournier670db242020-11-28 10:49:59 +010011701 ha_alert("Lua init: %s: %s\n", kind, trace);
11702 return_status = 0;
11703 break;
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010011704 }
Thierry Fournier670db242020-11-28 10:49:59 +010011705 if (!return_status)
11706 break;
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010011707 }
Thierry Fournier3c539322020-11-28 16:05:05 +010011708
11709 lua_atpanic(L, hlua_panic_safe);
Thierry Fournier670db242020-11-28 10:49:59 +010011710 return return_status;
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010011711}
11712
Thierry Fournierb8cef172020-11-28 15:37:17 +010011713int hlua_post_init()
11714{
Thierry Fournier59f11be2020-11-29 00:37:41 +010011715 int ret;
11716 int i;
11717 int errors;
11718 char *err = NULL;
11719 struct hlua_function *fcn;
Christopher Faulet69c581a2021-05-31 08:54:04 +020011720 struct hlua_reg_filter *reg_flt;
Thierry Fournier59f11be2020-11-29 00:37:41 +010011721
Willy Tarreaub1310492021-08-30 09:35:18 +020011722#if defined(USE_OPENSSL)
Thierry Fournierb8cef172020-11-28 15:37:17 +010011723 /* Initialize SSL server. */
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010011724 if (socket_ssl->xprt->prepare_srv) {
Thierry Fournierb8cef172020-11-28 15:37:17 +010011725 int saved_used_backed = global.ssl_used_backend;
11726 // don't affect maxconn automatic computation
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010011727 socket_ssl->xprt->prepare_srv(socket_ssl);
Thierry Fournierb8cef172020-11-28 15:37:17 +010011728 global.ssl_used_backend = saved_used_backed;
11729 }
11730#endif
11731
Thierry Fournierc7492592020-11-28 23:57:24 +010011732 /* Perform post init of common thread */
11733 hlua_state_id = 0;
Willy Tarreau43ab05b2021-09-28 09:43:11 +020011734 ha_set_thread(&ha_thread_info[0]);
Thierry Fournier59f11be2020-11-29 00:37:41 +010011735 ret = hlua_post_init_state(hlua_states[hlua_state_id]);
11736 if (ret == 0)
11737 return 0;
11738
11739 /* init remaining lua states and load files */
11740 for (hlua_state_id = 2; hlua_state_id < global.nbthread + 1; hlua_state_id++) {
11741
11742 /* set thread context */
Willy Tarreau43ab05b2021-09-28 09:43:11 +020011743 ha_set_thread(&ha_thread_info[hlua_state_id - 1]);
Thierry Fournier59f11be2020-11-29 00:37:41 +010011744
11745 /* Init lua state */
11746 hlua_states[hlua_state_id] = hlua_init_state(hlua_state_id);
11747
11748 /* Load lua files */
11749 for (i = 0; per_thread_load && per_thread_load[i]; i++) {
11750 ret = hlua_load_state(per_thread_load[i], hlua_states[hlua_state_id], &err);
11751 if (ret != 0) {
11752 ha_alert("Lua init: %s\n", err);
11753 return 0;
11754 }
11755 }
11756 }
11757
11758 /* Reset thread context */
Willy Tarreau43ab05b2021-09-28 09:43:11 +020011759 ha_set_thread(NULL);
Thierry Fournier59f11be2020-11-29 00:37:41 +010011760
11761 /* Execute post init for all states */
11762 for (hlua_state_id = 1; hlua_state_id < global.nbthread + 1; hlua_state_id++) {
11763
11764 /* set thread context */
Willy Tarreau43ab05b2021-09-28 09:43:11 +020011765 ha_set_thread(&ha_thread_info[hlua_state_id - 1]);
Thierry Fournier59f11be2020-11-29 00:37:41 +010011766
11767 /* run post init */
11768 ret = hlua_post_init_state(hlua_states[hlua_state_id]);
11769 if (ret == 0)
11770 return 0;
11771 }
11772
11773 /* Reset thread context */
Willy Tarreau43ab05b2021-09-28 09:43:11 +020011774 ha_set_thread(NULL);
Thierry Fournier59f11be2020-11-29 00:37:41 +010011775
11776 /* control functions registering. Each function must have:
11777 * - only the function_ref[0] set positive and all other to -1
11778 * - only the function_ref[0] set to -1 and all other positive
11779 * This ensure a same reference is not used both in shared
11780 * lua state and thread dedicated lua state. Note: is the case
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +050011781 * reach, the shared state is priority, but the bug will be
Thierry Fournier59f11be2020-11-29 00:37:41 +010011782 * complicated to found for the end user.
11783 */
11784 errors = 0;
11785 list_for_each_entry(fcn, &referenced_functions, l) {
11786 ret = 0;
11787 for (i = 1; i < global.nbthread + 1; i++) {
11788 if (fcn->function_ref[i] == -1)
11789 ret--;
11790 else
11791 ret++;
11792 }
11793 if (abs(ret) != global.nbthread) {
11794 ha_alert("Lua function '%s' is not referenced in all thread. "
11795 "Expect function in all thread or in none thread.\n", fcn->name);
11796 errors++;
11797 continue;
11798 }
11799
11800 if ((fcn->function_ref[0] == -1) == (ret < 0)) {
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +050011801 ha_alert("Lua function '%s' is referenced both ins shared Lua context (through lua-load) "
11802 "and per-thread Lua context (through lua-load-per-thread). these two context "
Thierry Fournier59f11be2020-11-29 00:37:41 +010011803 "exclusive.\n", fcn->name);
11804 errors++;
11805 }
11806 }
11807
Christopher Faulet69c581a2021-05-31 08:54:04 +020011808 /* Do the same with registered filters */
11809 list_for_each_entry(reg_flt, &referenced_filters, l) {
11810 ret = 0;
11811 for (i = 1; i < global.nbthread + 1; i++) {
11812 if (reg_flt->flt_ref[i] == -1)
11813 ret--;
11814 else
11815 ret++;
11816 }
11817 if (abs(ret) != global.nbthread) {
11818 ha_alert("Lua filter '%s' is not referenced in all thread. "
11819 "Expect function in all thread or in none thread.\n", reg_flt->name);
11820 errors++;
11821 continue;
11822 }
11823
11824 if ((reg_flt->flt_ref[0] == -1) == (ret < 0)) {
11825 ha_alert("Lua filter '%s' is referenced both ins shared Lua context (through lua-load) "
11826 "and per-thread Lua context (through lua-load-per-thread). these two context "
11827 "exclusive.\n", fcn->name);
11828 errors++;
11829 }
11830 }
11831
11832
Thierry Fournier59f11be2020-11-29 00:37:41 +010011833 if (errors > 0)
11834 return 0;
11835
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +050011836 /* after this point, this global will no longer be used, so set to
Thierry Fournier59f11be2020-11-29 00:37:41 +010011837 * -1 in order to have probably a segfault if someone use it
11838 */
11839 hlua_state_id = -1;
11840
11841 return 1;
Thierry Fournierb8cef172020-11-28 15:37:17 +010011842}
11843
Willy Tarreau32f61e22015-03-18 17:54:59 +010011844/* The memory allocator used by the Lua stack. <ud> is a pointer to the
11845 * allocator's context. <ptr> is the pointer to alloc/free/realloc. <osize>
11846 * is the previously allocated size or the kind of object in case of a new
Willy Tarreaud36c7fa2020-12-02 12:26:29 +010011847 * allocation. <nsize> is the requested new size. A new allocation is
11848 * indicated by <ptr> being NULL. A free is indicated by <nsize> being
Willy Tarreaucdb53462020-12-02 12:12:00 +010011849 * zero. This one verifies that the limits are respected but is optimized
11850 * for the fast case where limits are not used, hence stats are not updated.
Willy Tarreaua5efdff2021-10-22 16:00:02 +020011851 *
11852 * Warning: while this API ressembles glibc's realloc() a lot, glibc surpasses
11853 * POSIX by making realloc(ptr,0) an effective free(), but others do not do
11854 * that and will simply allocate zero as if it were the result of malloc(0),
11855 * so mapping this onto realloc() will lead to memory leaks on non-glibc
11856 * systems.
Willy Tarreau32f61e22015-03-18 17:54:59 +010011857 */
11858static void *hlua_alloc(void *ud, void *ptr, size_t osize, size_t nsize)
11859{
11860 struct hlua_mem_allocator *zone = ud;
Willy Tarreaucdb53462020-12-02 12:12:00 +010011861 size_t limit, old, new;
11862
11863 /* a limit of ~0 means unlimited and boot complete, so there's no need
11864 * for accounting anymore.
11865 */
Willy Tarreaua5efdff2021-10-22 16:00:02 +020011866 if (likely(~zone->limit == 0)) {
11867 if (!nsize)
11868 ha_free(&ptr);
11869 else
11870 ptr = realloc(ptr, nsize);
11871 return ptr;
11872 }
Willy Tarreau32f61e22015-03-18 17:54:59 +010011873
Willy Tarreaud36c7fa2020-12-02 12:26:29 +010011874 if (!ptr)
11875 osize = 0;
Willy Tarreau32f61e22015-03-18 17:54:59 +010011876
Willy Tarreaucdb53462020-12-02 12:12:00 +010011877 /* enforce strict limits across all threads */
11878 limit = zone->limit;
11879 old = _HA_ATOMIC_LOAD(&zone->allocated);
11880 do {
11881 new = old + nsize - osize;
11882 if (unlikely(nsize && limit && new > limit))
11883 return NULL;
11884 } while (!_HA_ATOMIC_CAS(&zone->allocated, &old, new));
Willy Tarreau32f61e22015-03-18 17:54:59 +010011885
Willy Tarreaua5efdff2021-10-22 16:00:02 +020011886 if (!nsize)
11887 ha_free(&ptr);
11888 else
11889 ptr = realloc(ptr, nsize);
Willy Tarreaucdb53462020-12-02 12:12:00 +010011890
11891 if (unlikely(!ptr && nsize)) // failed
11892 _HA_ATOMIC_SUB(&zone->allocated, nsize - osize);
11893
11894 __ha_barrier_atomic_store();
Willy Tarreau32f61e22015-03-18 17:54:59 +010011895 return ptr;
11896}
11897
Thierry Fournierecb83c22020-11-28 15:49:44 +010011898/* This function can fail with an abort() due to a Lua critical error.
Thierry FOURNIERbabae282015-09-17 11:36:37 +020011899 * We are in the initialisation process of HAProxy, this abort() is
11900 * tolerated.
11901 */
Thierry Fournierecb83c22020-11-28 15:49:44 +010011902lua_State *hlua_init_state(int thread_num)
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +010011903{
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010011904 int i;
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010011905 int idx;
11906 struct sample_fetch *sf;
Thierry FOURNIER594afe72015-03-10 23:58:30 +010011907 struct sample_conv *sc;
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010011908 char *p;
Thierry Fournierfd107a22016-02-19 19:57:23 +010011909 const char *error_msg;
Thierry Fournier4234dbd2020-11-28 13:18:23 +010011910 void **context;
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011911 lua_State *L;
Thierry Fournier59f11be2020-11-29 00:37:41 +010011912 struct prepend_path *pp;
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010011913
Thierry FOURNIER380d0932015-01-23 14:27:52 +010011914 /* Init main lua stack. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011915 L = lua_newstate(hlua_alloc, &hlua_global_allocator);
Thierry FOURNIER380d0932015-01-23 14:27:52 +010011916
Thierry Fournier4234dbd2020-11-28 13:18:23 +010011917 /* Initialise Lua context to NULL */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011918 context = lua_getextraspace(L);
Thierry Fournier4234dbd2020-11-28 13:18:23 +010011919 *context = NULL;
11920
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -080011921 /* From this point, until the end of the initialisation function,
Thierry FOURNIERbabae282015-09-17 11:36:37 +020011922 * the Lua function can fail with an abort. We are in the initialisation
11923 * process of HAProxy, this abort() is tolerated.
11924 */
11925
Thierry Fournier3c539322020-11-28 16:05:05 +010011926 /* Call post initialisation function in safe environment. */
11927 if (setjmp(safe_ljmp_env) != 0) {
11928 lua_atpanic(L, hlua_panic_safe);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011929 if (lua_type(L, -1) == LUA_TSTRING)
11930 error_msg = lua_tostring(L, -1);
Thierry Fournier2f05cc62020-11-28 16:08:02 +010011931 else
11932 error_msg = "critical error";
11933 fprintf(stderr, "Lua init: %s.\n", error_msg);
11934 exit(1);
Thierry Fournier3c539322020-11-28 16:05:05 +010011935 } else {
11936 lua_atpanic(L, hlua_panic_ljmp);
Thierry Fournier2f05cc62020-11-28 16:08:02 +010011937 }
11938
Thierry FOURNIER380d0932015-01-23 14:27:52 +010011939 /* Initialise lua. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011940 luaL_openlibs(L);
Tim Duesterhus541fe1e2020-01-12 13:55:41 +010011941#define HLUA_PREPEND_PATH_TOSTRING1(x) #x
11942#define HLUA_PREPEND_PATH_TOSTRING(x) HLUA_PREPEND_PATH_TOSTRING1(x)
11943#ifdef HLUA_PREPEND_PATH
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011944 hlua_prepend_path(L, "path", HLUA_PREPEND_PATH_TOSTRING(HLUA_PREPEND_PATH));
Tim Duesterhus541fe1e2020-01-12 13:55:41 +010011945#endif
11946#ifdef HLUA_PREPEND_CPATH
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011947 hlua_prepend_path(L, "cpath", HLUA_PREPEND_PATH_TOSTRING(HLUA_PREPEND_CPATH));
Tim Duesterhus541fe1e2020-01-12 13:55:41 +010011948#endif
11949#undef HLUA_PREPEND_PATH_TOSTRING
11950#undef HLUA_PREPEND_PATH_TOSTRING1
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010011951
Thierry Fournier59f11be2020-11-29 00:37:41 +010011952 /* Apply configured prepend path */
11953 list_for_each_entry(pp, &prepend_path_list, l)
11954 hlua_prepend_path(L, pp->type, pp->path);
11955
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010011956 /*
11957 *
11958 * Create "core" object.
11959 *
11960 */
11961
Thierry FOURNIERa2d8c652015-03-11 17:29:39 +010011962 /* This table entry is the object "core" base. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011963 lua_newtable(L);
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010011964
Thierry Fournierecb83c22020-11-28 15:49:44 +010011965 /* set the thread id */
11966 hlua_class_const_int(L, "thread", thread_num);
11967
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010011968 /* Push the loglevel constants. */
Willy Tarreau80f5fae2015-02-27 16:38:20 +010011969 for (i = 0; i < NB_LOG_LEVELS; i++)
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011970 hlua_class_const_int(L, log_levels[i], i);
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010011971
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010011972 /* Register special functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011973 hlua_class_function(L, "register_init", hlua_register_init);
11974 hlua_class_function(L, "register_task", hlua_register_task);
11975 hlua_class_function(L, "register_fetches", hlua_register_fetches);
11976 hlua_class_function(L, "register_converters", hlua_register_converters);
11977 hlua_class_function(L, "register_action", hlua_register_action);
11978 hlua_class_function(L, "register_service", hlua_register_service);
11979 hlua_class_function(L, "register_cli", hlua_register_cli);
Christopher Faulet69c581a2021-05-31 08:54:04 +020011980 hlua_class_function(L, "register_filter", hlua_register_filter);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011981 hlua_class_function(L, "yield", hlua_yield);
11982 hlua_class_function(L, "set_nice", hlua_set_nice);
11983 hlua_class_function(L, "sleep", hlua_sleep);
11984 hlua_class_function(L, "msleep", hlua_msleep);
11985 hlua_class_function(L, "add_acl", hlua_add_acl);
11986 hlua_class_function(L, "del_acl", hlua_del_acl);
11987 hlua_class_function(L, "set_map", hlua_set_map);
11988 hlua_class_function(L, "del_map", hlua_del_map);
11989 hlua_class_function(L, "tcp", hlua_socket_new);
William Lallemand3956c4e2021-09-21 16:25:15 +020011990 hlua_class_function(L, "httpclient", hlua_httpclient_new);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011991 hlua_class_function(L, "log", hlua_log);
11992 hlua_class_function(L, "Debug", hlua_log_debug);
11993 hlua_class_function(L, "Info", hlua_log_info);
11994 hlua_class_function(L, "Warning", hlua_log_warning);
11995 hlua_class_function(L, "Alert", hlua_log_alert);
11996 hlua_class_function(L, "done", hlua_done);
11997 hlua_fcn_reg_core_fcn(L);
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010011998
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011999 lua_setglobal(L, "core");
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010012000
12001 /*
12002 *
Christopher Faulet0f3c8902020-01-31 18:57:12 +010012003 * Create "act" object.
12004 *
12005 */
12006
12007 /* This table entry is the object "act" base. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012008 lua_newtable(L);
Christopher Faulet0f3c8902020-01-31 18:57:12 +010012009
12010 /* push action return constants */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012011 hlua_class_const_int(L, "CONTINUE", ACT_RET_CONT);
12012 hlua_class_const_int(L, "STOP", ACT_RET_STOP);
12013 hlua_class_const_int(L, "YIELD", ACT_RET_YIELD);
12014 hlua_class_const_int(L, "ERROR", ACT_RET_ERR);
12015 hlua_class_const_int(L, "DONE", ACT_RET_DONE);
12016 hlua_class_const_int(L, "DENY", ACT_RET_DENY);
12017 hlua_class_const_int(L, "ABORT", ACT_RET_ABRT);
12018 hlua_class_const_int(L, "INVALID", ACT_RET_INV);
Christopher Faulet0f3c8902020-01-31 18:57:12 +010012019
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012020 hlua_class_function(L, "wake_time", hlua_set_wake_time);
Christopher Faulet2c2c2e32020-01-31 19:07:52 +010012021
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012022 lua_setglobal(L, "act");
Christopher Faulet0f3c8902020-01-31 18:57:12 +010012023
12024 /*
12025 *
Christopher Faulet69c581a2021-05-31 08:54:04 +020012026 * Create "Filter" object.
12027 *
12028 */
12029
12030 /* This table entry is the object "filter" base. */
12031 lua_newtable(L);
12032
12033 /* push flags and constants */
12034 hlua_class_const_int(L, "CONTINUE", 1);
12035 hlua_class_const_int(L, "WAIT", 0);
12036 hlua_class_const_int(L, "ERROR", -1);
12037
12038 hlua_class_const_int(L, "FLT_CFG_FL_HTX", FLT_CFG_FL_HTX);
12039
Christopher Fauletc404f112020-02-26 15:03:09 +010012040 hlua_class_function(L, "wake_time", hlua_set_wake_time);
12041 hlua_class_function(L, "register_data_filter", hlua_register_data_filter);
12042 hlua_class_function(L, "unregister_data_filter", hlua_unregister_data_filter);
12043
Christopher Faulet69c581a2021-05-31 08:54:04 +020012044 lua_setglobal(L, "filter");
12045
12046 /*
12047 *
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012048 * Register class Map
12049 *
12050 */
12051
12052 /* This table entry is the object "Map" base. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012053 lua_newtable(L);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012054
12055 /* register pattern types. */
12056 for (i=0; i<PAT_MATCH_NUM; i++)
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012057 hlua_class_const_int(L, pat_match_names[i], i);
Thierry FOURNIER4dc71972017-01-28 08:33:08 +010012058 for (i=0; i<PAT_MATCH_NUM; i++) {
Willy Tarreau843b7cb2018-07-13 10:54:26 +020012059 snprintf(trash.area, trash.size, "_%s", pat_match_names[i]);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012060 hlua_class_const_int(L, trash.area, i);
Thierry FOURNIER4dc71972017-01-28 08:33:08 +010012061 }
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012062
12063 /* register constructor. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012064 hlua_class_function(L, "new", hlua_map_new);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012065
12066 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012067 lua_newtable(L);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012068
Ilya Shipitsind4259502020-04-08 01:07:56 +050012069 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012070 lua_pushstring(L, "__index");
12071 lua_newtable(L);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012072
12073 /* Register . */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012074 hlua_class_function(L, "lookup", hlua_map_lookup);
12075 hlua_class_function(L, "slookup", hlua_map_slookup);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012076
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012077 lua_rawset(L, -3);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012078
Thierry Fournier45e78d72016-02-19 18:34:46 +010012079 /* Register previous table in the registry with reference and named entry.
12080 * The function hlua_register_metatable() pops the stack, so we
12081 * previously create a copy of the table.
12082 */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012083 lua_pushvalue(L, -1); /* Copy the -1 entry and push it on the stack. */
12084 class_map_ref = hlua_register_metatable(L, CLASS_MAP);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012085
12086 /* Assign the metatable to the mai Map object. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012087 lua_setmetatable(L, -2);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012088
12089 /* Set a name to the table. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012090 lua_setglobal(L, "Map");
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012091
12092 /*
12093 *
William Lallemand30fcca12022-03-30 12:03:12 +020012094 * Register "CertCache" class
12095 *
12096 */
12097
12098 /* Create and fill the metatable. */
12099 lua_newtable(L);
12100 /* Register */
12101 hlua_class_function(L, "set", hlua_ckch_set);
12102 lua_setglobal(L, CLASS_CERTCACHE); /* Create global object called Regex */
12103
12104 /*
12105 *
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010012106 * Register class Channel
12107 *
12108 */
12109
12110 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012111 lua_newtable(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010012112
Ilya Shipitsind4259502020-04-08 01:07:56 +050012113 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012114 lua_pushstring(L, "__index");
12115 lua_newtable(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010012116
12117 /* Register . */
Christopher Faulet6a79fc12021-08-06 16:02:36 +020012118 hlua_class_function(L, "data", hlua_channel_get_data);
12119 hlua_class_function(L, "line", hlua_channel_get_line);
12120 hlua_class_function(L, "set", hlua_channel_set_data);
12121 hlua_class_function(L, "remove", hlua_channel_del_data);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012122 hlua_class_function(L, "append", hlua_channel_append);
Christopher Faulet6a79fc12021-08-06 16:02:36 +020012123 hlua_class_function(L, "prepend", hlua_channel_prepend);
12124 hlua_class_function(L, "insert", hlua_channel_insert_data);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012125 hlua_class_function(L, "send", hlua_channel_send);
12126 hlua_class_function(L, "forward", hlua_channel_forward);
Christopher Faulet6a79fc12021-08-06 16:02:36 +020012127 hlua_class_function(L, "input", hlua_channel_get_in_len);
12128 hlua_class_function(L, "output", hlua_channel_get_out_len);
12129 hlua_class_function(L, "may_recv", hlua_channel_may_recv);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012130 hlua_class_function(L, "is_full", hlua_channel_is_full);
12131 hlua_class_function(L, "is_resp", hlua_channel_is_resp);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010012132
Christopher Faulet6a79fc12021-08-06 16:02:36 +020012133 /* Deprecated API */
12134 hlua_class_function(L, "get", hlua_channel_get);
12135 hlua_class_function(L, "dup", hlua_channel_dup);
12136 hlua_class_function(L, "getline", hlua_channel_getline);
12137 hlua_class_function(L, "get_in_len", hlua_channel_get_in_len);
12138 hlua_class_function(L, "get_out_len", hlua_channel_get_out_len);
12139
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012140 lua_rawset(L, -3);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010012141
12142 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012143 class_channel_ref = hlua_register_metatable(L, CLASS_CHANNEL);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010012144
12145 /*
12146 *
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010012147 * Register class Fetches
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010012148 *
12149 */
12150
12151 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012152 lua_newtable(L);
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010012153
Ilya Shipitsind4259502020-04-08 01:07:56 +050012154 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012155 lua_pushstring(L, "__index");
12156 lua_newtable(L);
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010012157
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010012158 /* Browse existing fetches and create the associated
12159 * object method.
12160 */
12161 sf = NULL;
12162 while ((sf = sample_fetch_getnext(sf, &idx)) != NULL) {
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010012163 /* gL.Tua doesn't support '.' and '-' in the function names, replace it
12164 * by an underscore.
12165 */
Willy Tarreau5ef96562021-08-26 16:48:53 +020012166 strlcpy2(trash.area, sf->kw, trash.size);
Willy Tarreau843b7cb2018-07-13 10:54:26 +020012167 for (p = trash.area; *p; p++)
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010012168 if (*p == '.' || *p == '-' || *p == '+')
12169 *p = '_';
12170
12171 /* Register the function. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012172 lua_pushstring(L, trash.area);
12173 lua_pushlightuserdata(L, sf);
12174 lua_pushcclosure(L, hlua_run_sample_fetch, 1);
12175 lua_rawset(L, -3);
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010012176 }
12177
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012178 lua_rawset(L, -3);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010012179
12180 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012181 class_fetches_ref = hlua_register_metatable(L, CLASS_FETCHES);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010012182
12183 /*
12184 *
Thierry FOURNIER594afe72015-03-10 23:58:30 +010012185 * Register class Converters
12186 *
12187 */
12188
12189 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012190 lua_newtable(L);
Thierry FOURNIER594afe72015-03-10 23:58:30 +010012191
12192 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012193 lua_pushstring(L, "__index");
12194 lua_newtable(L);
Thierry FOURNIER594afe72015-03-10 23:58:30 +010012195
12196 /* Browse existing converters and create the associated
12197 * object method.
12198 */
12199 sc = NULL;
12200 while ((sc = sample_conv_getnext(sc, &idx)) != NULL) {
Thierry FOURNIER594afe72015-03-10 23:58:30 +010012201 /* gL.Tua doesn't support '.' and '-' in the function names, replace it
12202 * by an underscore.
12203 */
Willy Tarreau5ef96562021-08-26 16:48:53 +020012204 strlcpy2(trash.area, sc->kw, trash.size);
Willy Tarreau843b7cb2018-07-13 10:54:26 +020012205 for (p = trash.area; *p; p++)
Thierry FOURNIER594afe72015-03-10 23:58:30 +010012206 if (*p == '.' || *p == '-' || *p == '+')
12207 *p = '_';
12208
12209 /* Register the function. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012210 lua_pushstring(L, trash.area);
12211 lua_pushlightuserdata(L, sc);
12212 lua_pushcclosure(L, hlua_run_sample_conv, 1);
12213 lua_rawset(L, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +010012214 }
12215
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012216 lua_rawset(L, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +010012217
12218 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012219 class_converters_ref = hlua_register_metatable(L, CLASS_CONVERTERS);
Thierry FOURNIER594afe72015-03-10 23:58:30 +010012220
12221 /*
12222 *
Thierry FOURNIER08504f42015-03-16 14:17:08 +010012223 * Register class HTTP
12224 *
12225 */
12226
12227 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012228 lua_newtable(L);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010012229
Ilya Shipitsind4259502020-04-08 01:07:56 +050012230 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012231 lua_pushstring(L, "__index");
12232 lua_newtable(L);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010012233
12234 /* Register Lua functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012235 hlua_class_function(L, "req_get_headers",hlua_http_req_get_headers);
12236 hlua_class_function(L, "req_del_header", hlua_http_req_del_hdr);
12237 hlua_class_function(L, "req_rep_header", hlua_http_req_rep_hdr);
12238 hlua_class_function(L, "req_rep_value", hlua_http_req_rep_val);
12239 hlua_class_function(L, "req_add_header", hlua_http_req_add_hdr);
12240 hlua_class_function(L, "req_set_header", hlua_http_req_set_hdr);
12241 hlua_class_function(L, "req_set_method", hlua_http_req_set_meth);
12242 hlua_class_function(L, "req_set_path", hlua_http_req_set_path);
12243 hlua_class_function(L, "req_set_query", hlua_http_req_set_query);
12244 hlua_class_function(L, "req_set_uri", hlua_http_req_set_uri);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010012245
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012246 hlua_class_function(L, "res_get_headers",hlua_http_res_get_headers);
12247 hlua_class_function(L, "res_del_header", hlua_http_res_del_hdr);
12248 hlua_class_function(L, "res_rep_header", hlua_http_res_rep_hdr);
12249 hlua_class_function(L, "res_rep_value", hlua_http_res_rep_val);
12250 hlua_class_function(L, "res_add_header", hlua_http_res_add_hdr);
12251 hlua_class_function(L, "res_set_header", hlua_http_res_set_hdr);
12252 hlua_class_function(L, "res_set_status", hlua_http_res_set_status);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010012253
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012254 lua_rawset(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010012255
12256 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012257 class_http_ref = hlua_register_metatable(L, CLASS_HTTP);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010012258
Christopher Fauletdf97ac42020-02-26 16:57:19 +010012259 /*
12260 *
12261 * Register class HTTPMessage
12262 *
12263 */
12264
12265 /* Create and fill the metatable. */
12266 lua_newtable(L);
12267
Ilya Shipitsinff0f2782021-08-22 22:18:07 +050012268 /* Create and fill the __index entry. */
Christopher Fauletdf97ac42020-02-26 16:57:19 +010012269 lua_pushstring(L, "__index");
12270 lua_newtable(L);
12271
12272 /* Register Lua functions. */
12273 hlua_class_function(L, "is_resp", hlua_http_msg_is_resp);
12274 hlua_class_function(L, "get_stline", hlua_http_msg_get_stline);
12275 hlua_class_function(L, "get_headers", hlua_http_msg_get_headers);
12276 hlua_class_function(L, "del_header", hlua_http_msg_del_hdr);
12277 hlua_class_function(L, "rep_header", hlua_http_msg_rep_hdr);
12278 hlua_class_function(L, "rep_value", hlua_http_msg_rep_val);
12279 hlua_class_function(L, "add_header", hlua_http_msg_add_hdr);
12280 hlua_class_function(L, "set_header", hlua_http_msg_set_hdr);
12281 hlua_class_function(L, "set_method", hlua_http_msg_set_meth);
12282 hlua_class_function(L, "set_path", hlua_http_msg_set_path);
12283 hlua_class_function(L, "set_query", hlua_http_msg_set_query);
12284 hlua_class_function(L, "set_uri", hlua_http_msg_set_uri);
12285 hlua_class_function(L, "set_status", hlua_http_msg_set_status);
12286 hlua_class_function(L, "is_full", hlua_http_msg_is_full);
12287 hlua_class_function(L, "may_recv", hlua_http_msg_may_recv);
12288 hlua_class_function(L, "eom", hlua_http_msg_is_eom);
12289 hlua_class_function(L, "input", hlua_http_msg_get_in_len);
12290 hlua_class_function(L, "output", hlua_http_msg_get_out_len);
12291
12292 hlua_class_function(L, "body", hlua_http_msg_get_body);
12293 hlua_class_function(L, "set", hlua_http_msg_set_data);
12294 hlua_class_function(L, "remove", hlua_http_msg_del_data);
12295 hlua_class_function(L, "append", hlua_http_msg_append);
12296 hlua_class_function(L, "prepend", hlua_http_msg_prepend);
12297 hlua_class_function(L, "insert", hlua_http_msg_insert_data);
12298 hlua_class_function(L, "set_eom", hlua_http_msg_set_eom);
12299 hlua_class_function(L, "unset_eom", hlua_http_msg_unset_eom);
12300
12301 hlua_class_function(L, "send", hlua_http_msg_send);
12302 hlua_class_function(L, "forward", hlua_http_msg_forward);
12303
12304 lua_rawset(L, -3);
12305
12306 /* Register previous table in the registry with reference and named entry. */
12307 class_http_msg_ref = hlua_register_metatable(L, CLASS_HTTP_MSG);
William Lallemand3956c4e2021-09-21 16:25:15 +020012308
12309 /*
12310 *
12311 * Register class HTTPClient
12312 *
12313 */
12314
12315 /* Create and fill the metatable. */
12316 lua_newtable(L);
12317 lua_pushstring(L, "__index");
12318 lua_newtable(L);
12319 hlua_class_function(L, "get", hlua_httpclient_get);
William Lallemanddc2cc902021-10-26 11:43:26 +020012320 hlua_class_function(L, "head", hlua_httpclient_head);
12321 hlua_class_function(L, "put", hlua_httpclient_put);
12322 hlua_class_function(L, "post", hlua_httpclient_post);
12323 hlua_class_function(L, "delete", hlua_httpclient_delete);
William Lallemand3956c4e2021-09-21 16:25:15 +020012324 lua_settable(L, -3); /* Sets the __index entry. */
William Lallemandf77f1de2021-09-28 19:10:38 +020012325 /* Register the garbage collector entry. */
12326 lua_pushstring(L, "__gc");
12327 lua_pushcclosure(L, hlua_httpclient_gc, 0);
12328 lua_settable(L, -3); /* Push the last 2 entries in the table at index -3 */
12329
William Lallemand3956c4e2021-09-21 16:25:15 +020012330
12331
12332 class_httpclient_ref = hlua_register_metatable(L, CLASS_HTTPCLIENT);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010012333 /*
12334 *
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020012335 * Register class AppletTCP
12336 *
12337 */
12338
12339 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012340 lua_newtable(L);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020012341
Ilya Shipitsind4259502020-04-08 01:07:56 +050012342 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012343 lua_pushstring(L, "__index");
12344 lua_newtable(L);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020012345
12346 /* Register Lua functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012347 hlua_class_function(L, "getline", hlua_applet_tcp_getline);
12348 hlua_class_function(L, "receive", hlua_applet_tcp_recv);
12349 hlua_class_function(L, "send", hlua_applet_tcp_send);
12350 hlua_class_function(L, "set_priv", hlua_applet_tcp_set_priv);
12351 hlua_class_function(L, "get_priv", hlua_applet_tcp_get_priv);
12352 hlua_class_function(L, "set_var", hlua_applet_tcp_set_var);
12353 hlua_class_function(L, "unset_var", hlua_applet_tcp_unset_var);
12354 hlua_class_function(L, "get_var", hlua_applet_tcp_get_var);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020012355
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012356 lua_settable(L, -3);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020012357
12358 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012359 class_applet_tcp_ref = hlua_register_metatable(L, CLASS_APPLET_TCP);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020012360
12361 /*
12362 *
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020012363 * Register class AppletHTTP
12364 *
12365 */
12366
12367 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012368 lua_newtable(L);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020012369
Ilya Shipitsind4259502020-04-08 01:07:56 +050012370 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012371 lua_pushstring(L, "__index");
12372 lua_newtable(L);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020012373
12374 /* Register Lua functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012375 hlua_class_function(L, "set_priv", hlua_applet_http_set_priv);
12376 hlua_class_function(L, "get_priv", hlua_applet_http_get_priv);
12377 hlua_class_function(L, "set_var", hlua_applet_http_set_var);
12378 hlua_class_function(L, "unset_var", hlua_applet_http_unset_var);
12379 hlua_class_function(L, "get_var", hlua_applet_http_get_var);
12380 hlua_class_function(L, "getline", hlua_applet_http_getline);
12381 hlua_class_function(L, "receive", hlua_applet_http_recv);
12382 hlua_class_function(L, "send", hlua_applet_http_send);
12383 hlua_class_function(L, "add_header", hlua_applet_http_addheader);
12384 hlua_class_function(L, "set_status", hlua_applet_http_status);
12385 hlua_class_function(L, "start_response", hlua_applet_http_start_response);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020012386
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012387 lua_settable(L, -3);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020012388
12389 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012390 class_applet_http_ref = hlua_register_metatable(L, CLASS_APPLET_HTTP);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020012391
12392 /*
12393 *
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010012394 * Register class TXN
12395 *
12396 */
12397
12398 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012399 lua_newtable(L);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010012400
Ilya Shipitsind4259502020-04-08 01:07:56 +050012401 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012402 lua_pushstring(L, "__index");
12403 lua_newtable(L);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010012404
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +010012405 /* Register Lua functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012406 hlua_class_function(L, "set_priv", hlua_set_priv);
12407 hlua_class_function(L, "get_priv", hlua_get_priv);
12408 hlua_class_function(L, "set_var", hlua_set_var);
12409 hlua_class_function(L, "unset_var", hlua_unset_var);
12410 hlua_class_function(L, "get_var", hlua_get_var);
12411 hlua_class_function(L, "done", hlua_txn_done);
12412 hlua_class_function(L, "reply", hlua_txn_reply_new);
12413 hlua_class_function(L, "set_loglevel", hlua_txn_set_loglevel);
12414 hlua_class_function(L, "set_tos", hlua_txn_set_tos);
12415 hlua_class_function(L, "set_mark", hlua_txn_set_mark);
12416 hlua_class_function(L, "set_priority_class", hlua_txn_set_priority_class);
12417 hlua_class_function(L, "set_priority_offset", hlua_txn_set_priority_offset);
12418 hlua_class_function(L, "deflog", hlua_txn_deflog);
12419 hlua_class_function(L, "log", hlua_txn_log);
12420 hlua_class_function(L, "Debug", hlua_txn_log_debug);
12421 hlua_class_function(L, "Info", hlua_txn_log_info);
12422 hlua_class_function(L, "Warning", hlua_txn_log_warning);
12423 hlua_class_function(L, "Alert", hlua_txn_log_alert);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +010012424
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012425 lua_rawset(L, -3);
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010012426
12427 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012428 class_txn_ref = hlua_register_metatable(L, CLASS_TXN);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012429
12430 /*
12431 *
Christopher Faulet700d9e82020-01-31 12:21:52 +010012432 * Register class reply
12433 *
12434 */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012435 lua_newtable(L);
12436 lua_pushstring(L, "__index");
12437 lua_newtable(L);
12438 hlua_class_function(L, "set_status", hlua_txn_reply_set_status);
12439 hlua_class_function(L, "add_header", hlua_txn_reply_add_header);
12440 hlua_class_function(L, "del_header", hlua_txn_reply_del_header);
12441 hlua_class_function(L, "set_body", hlua_txn_reply_set_body);
12442 lua_settable(L, -3); /* Sets the __index entry. */
12443 class_txn_reply_ref = luaL_ref(L, LUA_REGISTRYINDEX);
Christopher Faulet700d9e82020-01-31 12:21:52 +010012444
12445
12446 /*
12447 *
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012448 * Register class Socket
12449 *
12450 */
12451
12452 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012453 lua_newtable(L);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012454
Ilya Shipitsind4259502020-04-08 01:07:56 +050012455 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012456 lua_pushstring(L, "__index");
12457 lua_newtable(L);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012458
Baptiste Assmann84bb4932015-03-02 21:40:06 +010012459#ifdef USE_OPENSSL
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012460 hlua_class_function(L, "connect_ssl", hlua_socket_connect_ssl);
Baptiste Assmann84bb4932015-03-02 21:40:06 +010012461#endif
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012462 hlua_class_function(L, "connect", hlua_socket_connect);
12463 hlua_class_function(L, "send", hlua_socket_send);
12464 hlua_class_function(L, "receive", hlua_socket_receive);
12465 hlua_class_function(L, "close", hlua_socket_close);
12466 hlua_class_function(L, "getpeername", hlua_socket_getpeername);
12467 hlua_class_function(L, "getsockname", hlua_socket_getsockname);
12468 hlua_class_function(L, "setoption", hlua_socket_setoption);
12469 hlua_class_function(L, "settimeout", hlua_socket_settimeout);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012470
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012471 lua_rawset(L, -3); /* Push the last 2 entries in the table at index -3 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012472
12473 /* Register the garbage collector entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012474 lua_pushstring(L, "__gc");
12475 lua_pushcclosure(L, hlua_socket_gc, 0);
12476 lua_rawset(L, -3); /* Push the last 2 entries in the table at index -3 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012477
12478 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012479 class_socket_ref = hlua_register_metatable(L, CLASS_SOCKET);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012480
Thierry Fournieraafc7772020-12-04 11:47:47 +010012481 lua_atpanic(L, hlua_panic_safe);
12482
12483 return L;
12484}
12485
12486void hlua_init(void) {
12487 int i;
Amaury Denoyelle239fdbf2021-03-24 10:22:03 +010012488 char *errmsg;
Thierry Fournieraafc7772020-12-04 11:47:47 +010012489#ifdef USE_OPENSSL
12490 struct srv_kw *kw;
12491 int tmp_error;
12492 char *error;
12493 char *args[] = { /* SSL client configuration. */
12494 "ssl",
12495 "verify",
12496 "none",
12497 NULL
12498 };
12499#endif
12500
12501 /* Init post init function list head */
12502 for (i = 0; i < MAX_THREADS + 1; i++)
12503 LIST_INIT(&hlua_init_functions[i]);
12504
12505 /* Init state for common/shared lua parts */
12506 hlua_state_id = 0;
Willy Tarreau43ab05b2021-09-28 09:43:11 +020012507 ha_set_thread(NULL);
Thierry Fournieraafc7772020-12-04 11:47:47 +010012508 hlua_states[0] = hlua_init_state(0);
12509
12510 /* Init state 1 for thread 0. We have at least one thread. */
12511 hlua_state_id = 1;
Willy Tarreau43ab05b2021-09-28 09:43:11 +020012512 ha_set_thread(NULL);
Thierry Fournieraafc7772020-12-04 11:47:47 +010012513 hlua_states[1] = hlua_init_state(1);
12514
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012515 /* Proxy and server configuration initialisation. */
William Lallemand6bb77b92021-07-28 15:48:16 +020012516 socket_proxy = alloc_new_proxy("LUA-SOCKET", PR_CAP_FE|PR_CAP_BE|PR_CAP_INT, &errmsg);
Amaury Denoyelle239fdbf2021-03-24 10:22:03 +010012517 if (!socket_proxy) {
12518 fprintf(stderr, "Lua init: %s\n", errmsg);
12519 exit(1);
12520 }
12521 proxy_preset_defaults(socket_proxy);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012522
12523 /* Init TCP server: unchanged parameters */
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010012524 socket_tcp = new_server(socket_proxy);
12525 if (!socket_tcp) {
12526 fprintf(stderr, "Lua init: failed to allocate tcp server socket\n");
12527 exit(1);
12528 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012529
12530#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012531 /* Init TCP server: unchanged parameters */
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010012532 socket_ssl = new_server(socket_proxy);
12533 if (!socket_ssl) {
12534 fprintf(stderr, "Lua init: failed to allocate ssl server socket\n");
12535 exit(1);
12536 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012537
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010012538 socket_ssl->use_ssl = 1;
12539 socket_ssl->xprt = xprt_get(XPRT_SSL);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012540
Bertrand Jacquin80839ff2021-01-21 19:14:46 +000012541 for (i = 0; args[i] != NULL; i++) {
12542 if ((kw = srv_find_kw(args[i])) != NULL) { /* Maybe it's registered server keyword */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012543 /*
12544 *
12545 * If the keyword is not known, we can search in the registered
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -080012546 * server keywords. This is useful to configure special SSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012547 * features like client certificates and ssl_verify.
12548 *
12549 */
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010012550 tmp_error = kw->parse(args, &i, socket_proxy, socket_ssl, &error);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012551 if (tmp_error != 0) {
12552 fprintf(stderr, "INTERNAL ERROR: %s\n", error);
12553 abort(); /* This must be never arrives because the command line
12554 not editable by the user. */
12555 }
Bertrand Jacquin80839ff2021-01-21 19:14:46 +000012556 i += kw->skip;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012557 }
12558 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012559#endif
Thierry Fournier75933d42016-01-21 09:30:18 +010012560
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +010012561}
Willy Tarreaubb57d942016-12-21 19:04:56 +010012562
Tim Duesterhusd0c0ca22020-07-04 11:53:26 +020012563static void hlua_deinit()
12564{
Willy Tarreau186f3762020-12-04 11:48:12 +010012565 int thr;
Christopher Faulet69c581a2021-05-31 08:54:04 +020012566 struct hlua_reg_filter *reg_flt, *reg_flt_bck;
12567
12568 list_for_each_entry_safe(reg_flt, reg_flt_bck, &referenced_filters, l)
12569 release_hlua_reg_filter(reg_flt);
Willy Tarreau186f3762020-12-04 11:48:12 +010012570
12571 for (thr = 0; thr < MAX_THREADS+1; thr++) {
12572 if (hlua_states[thr])
12573 lua_close(hlua_states[thr]);
12574 }
Willy Tarreau430bf4a2021-03-04 09:45:32 +010012575
Amaury Denoyellebc2ebfa2021-08-25 15:34:53 +020012576 srv_drop(socket_tcp);
Willy Tarreau430bf4a2021-03-04 09:45:32 +010012577
Willy Tarreau0f143af2021-03-05 10:41:48 +010012578#ifdef USE_OPENSSL
Amaury Denoyellebc2ebfa2021-08-25 15:34:53 +020012579 srv_drop(socket_ssl);
Willy Tarreau0f143af2021-03-05 10:41:48 +010012580#endif
Amaury Denoyelle239fdbf2021-03-24 10:22:03 +010012581
12582 free_proxy(socket_proxy);
Tim Duesterhusd0c0ca22020-07-04 11:53:26 +020012583}
12584
12585REGISTER_POST_DEINIT(hlua_deinit);
12586
Willy Tarreau80713382018-11-26 10:19:54 +010012587static void hlua_register_build_options(void)
12588{
Willy Tarreaubb57d942016-12-21 19:04:56 +010012589 char *ptr = NULL;
Willy Tarreau80713382018-11-26 10:19:54 +010012590
Willy Tarreaubb57d942016-12-21 19:04:56 +010012591 memprintf(&ptr, "Built with Lua version : %s", LUA_RELEASE);
12592 hap_register_build_opts(ptr, 1);
12593}
Willy Tarreau80713382018-11-26 10:19:54 +010012594
12595INITCALL0(STG_REGISTER, hlua_register_build_options);