blob: 6bbf5c97ab739557cb3c33a2e0af514cb8c79717 [file] [log] [blame]
Thierry Fourniere726b142016-02-11 17:57:57 +01001/*
2 * Lua unsafe core engine
3 *
4 * Copyright 2015-2016 Thierry Fournier <tfournier@arpalert.org>
5 *
6 * This program is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU General Public License
8 * as published by the Free Software Foundation; either version
9 * 2 of the License, or (at your option) any later version.
10 *
11 */
12
Bertrand Jacquinf4c12d42021-01-21 21:14:07 +000013#define _GNU_SOURCE
14
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +010015#include <ctype.h>
Thierry FOURNIERbabae282015-09-17 11:36:37 +020016#include <setjmp.h>
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +010017
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +010018#include <lauxlib.h>
19#include <lua.h>
20#include <lualib.h>
21
Thierry FOURNIER463119c2015-03-10 00:35:36 +010022#if !defined(LUA_VERSION_NUM) || LUA_VERSION_NUM < 503
23#error "Requires Lua 5.3 or later."
Cyril Bontédc0306e2015-03-02 00:08:40 +010024#endif
25
Willy Tarreau8d2b7772020-05-27 10:58:19 +020026#include <import/ebpttree.h>
Thierry FOURNIER380d0932015-01-23 14:27:52 +010027
Willy Tarreaub2551052020-06-09 09:07:15 +020028#include <haproxy/api.h>
29#include <haproxy/applet.h>
Willy Tarreaudfd3de82020-06-04 23:46:14 +020030#include <haproxy/arg.h>
Christopher Fauletd25d9262020-08-06 11:04:46 +020031#include <haproxy/auth.h>
Willy Tarreau6be78492020-06-05 00:00:29 +020032#include <haproxy/cfgparse.h>
Willy Tarreauf1d32c42020-06-04 21:07:02 +020033#include <haproxy/channel.h>
Willy Tarreau83487a82020-06-04 20:19:54 +020034#include <haproxy/cli.h>
Willy Tarreau55542642021-10-08 09:33:24 +020035#include <haproxy/clock.h>
Willy Tarreau7ea393d2020-06-04 18:02:10 +020036#include <haproxy/connection.h>
Christopher Faulet69c581a2021-05-31 08:54:04 +020037#include <haproxy/filters.h>
Willy Tarreau5413a872020-06-02 19:33:08 +020038#include <haproxy/h1.h>
Willy Tarreau86416052020-06-04 09:20:54 +020039#include <haproxy/hlua.h>
Willy Tarreau8c794002020-06-04 10:05:25 +020040#include <haproxy/hlua_fcn.h>
Willy Tarreauc2b1ff02020-06-04 21:21:03 +020041#include <haproxy/http_ana.h>
William Lallemand3956c4e2021-09-21 16:25:15 +020042#include <haproxy/http_client.h>
Willy Tarreau126ba3a2020-06-04 18:26:43 +020043#include <haproxy/http_fetch.h>
Willy Tarreaub2551052020-06-09 09:07:15 +020044#include <haproxy/http_htx.h>
Willy Tarreauc761f842020-06-04 11:40:28 +020045#include <haproxy/http_rules.h>
Willy Tarreau36979d92020-06-05 17:27:29 +020046#include <haproxy/log.h>
Willy Tarreau2cd58092020-06-04 15:10:43 +020047#include <haproxy/map.h>
Willy Tarreau8efbdfb2020-06-04 11:29:21 +020048#include <haproxy/obj_type.h>
Willy Tarreau225a90a2020-06-04 15:06:28 +020049#include <haproxy/pattern.h>
Willy Tarreau469509b2020-06-04 15:13:30 +020050#include <haproxy/payload.h>
Willy Tarreau3d6ee402021-05-08 20:28:07 +020051#include <haproxy/proxy.h>
Willy Tarreaub2551052020-06-09 09:07:15 +020052#include <haproxy/regex.h>
Willy Tarreaue6ce10b2020-06-04 15:33:47 +020053#include <haproxy/sample.h>
Willy Tarreau5edca2f2022-05-27 09:25:10 +020054#include <haproxy/sc_strm.h>
Willy Tarreau198e92a2021-03-05 10:23:32 +010055#include <haproxy/server.h>
Willy Tarreau48d25b32020-06-04 18:58:52 +020056#include <haproxy/session.h>
William Lallemand30fcca12022-03-30 12:03:12 +020057#include <haproxy/ssl_ckch.h>
58#include <haproxy/ssl_sock.h>
Willy Tarreau2eec9b52020-06-04 19:58:55 +020059#include <haproxy/stats-t.h>
Willy Tarreaucb086c62022-05-27 09:47:12 +020060#include <haproxy/stconn.h>
Willy Tarreaudfd3de82020-06-04 23:46:14 +020061#include <haproxy/stream.h>
Willy Tarreaucea0e1b2020-06-04 17:25:40 +020062#include <haproxy/task.h>
Willy Tarreau8b550af2020-06-04 17:42:48 +020063#include <haproxy/tcp_rules.h>
Willy Tarreaub2551052020-06-09 09:07:15 +020064#include <haproxy/thread.h>
Willy Tarreau48fbcae2020-06-03 18:09:46 +020065#include <haproxy/tools.h>
Willy Tarreaua1718922020-06-04 16:25:31 +020066#include <haproxy/vars.h>
Willy Tarreaub2551052020-06-09 09:07:15 +020067#include <haproxy/xref.h>
Aurelien DARRAGONc84899c2023-02-20 18:18:59 +010068#include <haproxy/event_hdl.h>
Thierry FOURNIER380d0932015-01-23 14:27:52 +010069
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +010070/* Lua uses longjmp to perform yield or throwing errors. This
71 * macro is used only for identifying the function that can
72 * not return because a longjmp is executed.
73 * __LJMP marks a prototype of hlua file that can use longjmp.
74 * WILL_LJMP() marks an lua function that will use longjmp.
75 * MAY_LJMP() marks an lua function that may use longjmp.
76 */
77#define __LJMP
Willy Tarreau4e7cc332018-10-20 17:45:48 +020078#define WILL_LJMP(func) do { func; my_unreachable(); } while(0)
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +010079#define MAY_LJMP(func) func
80
Thierry FOURNIERbabae282015-09-17 11:36:37 +020081/* This couple of function executes securely some Lua calls outside of
82 * the lua runtime environment. Each Lua call can return a longjmp
83 * if it encounter a memory error.
84 *
85 * Lua documentation extract:
86 *
87 * If an error happens outside any protected environment, Lua calls
88 * a panic function (see lua_atpanic) and then calls abort, thus
89 * exiting the host application. Your panic function can avoid this
90 * exit by never returning (e.g., doing a long jump to your own
91 * recovery point outside Lua).
92 *
93 * The panic function runs as if it were a message handler (see
Willy Tarreau3dfb7da2022-03-02 22:33:39 +010094 * #2.3); in particular, the error message is at the top of the
Thierry FOURNIERbabae282015-09-17 11:36:37 +020095 * stack. However, there is no guarantee about stack space. To push
96 * anything on the stack, the panic function must first check the
Willy Tarreau3dfb7da2022-03-02 22:33:39 +010097 * available space (see #4.2).
Thierry FOURNIERbabae282015-09-17 11:36:37 +020098 *
99 * We must check all the Lua entry point. This includes:
100 * - The include/proto/hlua.h exported functions
101 * - the task wrapper function
102 * - The action wrapper function
103 * - The converters wrapper function
104 * - The sample-fetch wrapper functions
105 *
Ilya Shipitsin46a030c2020-07-05 16:36:08 +0500106 * It is tolerated that the initialisation function returns an abort.
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -0800107 * Before each Lua abort, an error message is written on stderr.
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200108 *
109 * The macro SET_SAFE_LJMP initialise the longjmp. The Macro
110 * RESET_SAFE_LJMP reset the longjmp. These function must be macro
111 * because they must be exists in the program stack when the longjmp
112 * is called.
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +0200113 *
114 * Note that the Lua processing is not really thread safe. It provides
115 * heavy system which consists to add our own lock function in the Lua
116 * code and recompile the library. This system will probably not accepted
117 * by maintainers of various distribs.
118 *
Ilya Shipitsin856aabc2020-04-16 23:51:34 +0500119 * Our main execution point of the Lua is the function lua_resume(). A
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +0200120 * quick looking on the Lua sources displays a lua_lock() a the start
121 * of function and a lua_unlock() at the end of the function. So I
122 * conclude that the Lua thread safe mode just perform a mutex around
123 * all execution. So I prefer to do this in the HAProxy code, it will be
124 * easier for distro maintainers.
125 *
126 * Note that the HAProxy lua functions rounded by the macro SET_SAFE_LJMP
127 * and RESET_SAFE_LJMP manipulates the Lua stack, so it will be careful
128 * to set mutex around these functions.
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200129 */
Willy Tarreau86abe442018-11-25 20:12:18 +0100130__decl_spinlock(hlua_global_lock);
Thierry FOURNIERffbad792017-07-12 11:39:04 +0200131THREAD_LOCAL jmp_buf safe_ljmp_env;
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200132static int hlua_panic_safe(lua_State *L) { return 0; }
Willy Tarreau6a510902021-07-14 19:41:25 +0200133static int hlua_panic_ljmp(lua_State *L) { WILL_LJMP(longjmp(safe_ljmp_env, 1)); return 0; }
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200134
Thierry Fournier62a22aa2020-11-28 21:06:35 +0100135/* This is the chained list of struct hlua_function referenced
136 * for haproxy action, sample-fetches, converters, cli and
137 * applet bindings. It is used for a post-initialisation control.
138 */
139static struct list referenced_functions = LIST_HEAD_INIT(referenced_functions);
140
Thierry Fournierc7492592020-11-28 23:57:24 +0100141/* This variable is used only during initialization to identify the Lua state
142 * currently being initialized. 0 is the common lua state, 1 to n are the Lua
143 * states dedicated to each thread (in this case hlua_state_id==tid+1).
144 */
145static int hlua_state_id;
146
Thierry Fournier59f11be2020-11-29 00:37:41 +0100147/* This is a NULL-terminated list of lua file which are referenced to load per thread */
Thierry Fournierae6b5682022-09-19 09:04:16 +0200148static char ***per_thread_load = NULL;
Thierry Fournier59f11be2020-11-29 00:37:41 +0100149
150lua_State *hlua_init_state(int thread_id);
151
Willy Tarreau1e7bef12021-08-20 15:47:25 +0200152/* This function takes the Lua global lock. Keep this function's visibility
153 * global so that it can appear in stack dumps and performance profiles!
154 */
Aurelien DARRAGONe36f8032023-03-21 13:22:33 +0100155static inline void lua_take_global_lock()
Willy Tarreau1e7bef12021-08-20 15:47:25 +0200156{
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
Aurelien DARRAGON6b0b9bd2023-03-21 14:02:16 +0100165/* lua lock helpers: only lock when required
166 *
167 * state_id == 0: we're operating on the main lua stack (shared between
168 * os threads), so we need to acquire the main lock
169 *
170 * If the thread already owns the lock (_hlua_locked != 0), skip the lock
171 * attempt. This could happen if we run under protected lua environment.
172 * Not doing this could result in deadlocks because of nested locking
173 * attempts from the same thread
174 */
175static THREAD_LOCAL int _hlua_locked = 0;
Aurelien DARRAGONe36f8032023-03-21 13:22:33 +0100176static inline void hlua_lock(struct hlua *hlua)
177{
Aurelien DARRAGON6b0b9bd2023-03-21 14:02:16 +0100178 if (hlua->state_id != 0)
179 return;
180 if (!_hlua_locked)
Aurelien DARRAGONe36f8032023-03-21 13:22:33 +0100181 lua_take_global_lock();
Aurelien DARRAGON6b0b9bd2023-03-21 14:02:16 +0100182 _hlua_locked += 1;
Aurelien DARRAGONe36f8032023-03-21 13:22:33 +0100183}
184static inline void hlua_unlock(struct hlua *hlua)
185{
Aurelien DARRAGON6b0b9bd2023-03-21 14:02:16 +0100186 if (hlua->state_id != 0)
187 return;
188 BUG_ON(_hlua_locked <= 0);
189 _hlua_locked--;
190 /* drop the lock once the lock count reaches 0 */
191 if (!_hlua_locked)
Aurelien DARRAGONe36f8032023-03-21 13:22:33 +0100192 lua_drop_global_lock();
193}
194
Thierry Fournier7cbe5042020-11-28 17:02:21 +0100195#define SET_SAFE_LJMP_L(__L, __HLUA) \
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200196 ({ \
197 int ret; \
Aurelien DARRAGONe36f8032023-03-21 13:22:33 +0100198 hlua_lock(__HLUA); \
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200199 if (setjmp(safe_ljmp_env) != 0) { \
200 lua_atpanic(__L, hlua_panic_safe); \
201 ret = 0; \
Aurelien DARRAGONe36f8032023-03-21 13:22:33 +0100202 hlua_unlock(__HLUA); \
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200203 } else { \
204 lua_atpanic(__L, hlua_panic_ljmp); \
205 ret = 1; \
206 } \
207 ret; \
208 })
209
210/* If we are the last function catching Lua errors, we
211 * must reset the panic function.
212 */
Thierry Fournier7cbe5042020-11-28 17:02:21 +0100213#define RESET_SAFE_LJMP_L(__L, __HLUA) \
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200214 do { \
215 lua_atpanic(__L, hlua_panic_safe); \
Aurelien DARRAGONe36f8032023-03-21 13:22:33 +0100216 hlua_unlock(__HLUA); \
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200217 } while(0)
218
Thierry Fournier7cbe5042020-11-28 17:02:21 +0100219#define SET_SAFE_LJMP(__HLUA) \
220 SET_SAFE_LJMP_L((__HLUA)->T, __HLUA)
221
222#define RESET_SAFE_LJMP(__HLUA) \
223 RESET_SAFE_LJMP_L((__HLUA)->T, __HLUA)
224
225#define SET_SAFE_LJMP_PARENT(__HLUA) \
Thierry Fournier021d9862020-11-28 23:42:03 +0100226 SET_SAFE_LJMP_L(hlua_states[(__HLUA)->state_id], __HLUA)
Thierry Fournier7cbe5042020-11-28 17:02:21 +0100227
228#define RESET_SAFE_LJMP_PARENT(__HLUA) \
Thierry Fournier021d9862020-11-28 23:42:03 +0100229 RESET_SAFE_LJMP_L(hlua_states[(__HLUA)->state_id], __HLUA)
Thierry Fournier7cbe5042020-11-28 17:02:21 +0100230
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +0200231/* Applet status flags */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200232#define APPLET_DONE 0x01 /* applet processing is done. */
Christopher Faulet18c2e8d2019-03-01 12:02:08 +0100233/* unused: 0x02 */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200234#define APPLET_HDR_SENT 0x04 /* Response header sent. */
Christopher Fauleta2097962019-07-15 16:25:33 +0200235/* unused: 0x08, 0x10 */
Thierry FOURNIERd93ea2b2015-12-20 19:14:52 +0100236#define APPLET_HTTP11 0x20 /* Last chunk sent. */
Christopher Faulet56a3d6e2019-02-27 22:06:23 +0100237#define APPLET_RSP_SENT 0x40 /* The response was fully sent */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200238
Thierry Fournierafc63e22020-11-28 17:06:51 +0100239/* The main Lua execution context. The 0 index is the
240 * common state shared by all threads.
241 */
Willy Tarreau186f3762020-12-04 11:48:12 +0100242static lua_State *hlua_states[MAX_THREADS + 1];
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100243
Christopher Fauletc404f112020-02-26 15:03:09 +0100244#define HLUA_FLT_CB_FINAL 0x00000001
245#define HLUA_FLT_CB_RETVAL 0x00000002
246#define HLUA_FLT_CB_ARG_CHN 0x00000004
247#define HLUA_FLT_CB_ARG_HTTP_MSG 0x00000008
248
Christopher Faulet9f55a502020-02-25 15:21:02 +0100249#define HLUA_FLT_CTX_FL_PAYLOAD 0x00000001
250
Christopher Faulet69c581a2021-05-31 08:54:04 +0200251struct hlua_reg_filter {
252 char *name;
253 int flt_ref[MAX_THREADS + 1];
254 int fun_ref[MAX_THREADS + 1];
255 struct list l;
256};
257
258struct hlua_flt_config {
259 struct hlua_reg_filter *reg;
260 int ref[MAX_THREADS + 1];
261 char **args;
262};
263
264struct hlua_flt_ctx {
265 int ref; /* ref to the filter lua object */
266 struct hlua *hlua[2]; /* lua runtime context (0: request, 1: response) */
267 unsigned int cur_off[2]; /* current offset (0: request, 1: response) */
268 unsigned int cur_len[2]; /* current forwardable length (0: request, 1: response) */
269 unsigned int flags; /* HLUA_FLT_CTX_FL_* */
270};
271
Willy Tarreau5321da92022-05-06 11:57:34 +0200272/* appctx context used by the cosockets */
273struct hlua_csk_ctx {
274 int connected;
275 struct xref xref; /* cross reference with the Lua object owner. */
276 struct list wake_on_read;
277 struct list wake_on_write;
278 struct appctx *appctx;
279 int die;
280};
281
Willy Tarreaue23f33b2022-05-06 14:07:13 +0200282/* appctx context used by TCP services */
283struct hlua_tcp_ctx {
284 struct hlua *hlua;
285 int flags;
286 struct task *task;
287};
288
Willy Tarreauaa229cc2022-05-06 14:26:10 +0200289/* appctx context used by HTTP services */
290struct hlua_http_ctx {
291 struct hlua *hlua;
292 int left_bytes; /* The max amount of bytes that we can read. */
293 int flags;
294 int status;
295 const char *reason;
296 struct task *task;
297};
298
Willy Tarreaubcda5f62022-05-03 18:13:39 +0200299/* used by registered CLI keywords */
300struct hlua_cli_ctx {
301 struct hlua *hlua;
302 struct task *task;
303 struct hlua_function *fcn;
304};
305
Christopher Faulet69c581a2021-05-31 08:54:04 +0200306DECLARE_STATIC_POOL(pool_head_hlua_flt_ctx, "hlua_flt_ctx", sizeof(struct hlua_flt_ctx));
307
Christopher Faulet9f55a502020-02-25 15:21:02 +0100308static int hlua_filter_from_payload(struct filter *filter);
309
Christopher Faulet69c581a2021-05-31 08:54:04 +0200310/* This is the chained list of struct hlua_flt referenced
311 * for haproxy filters. It is used for a post-initialisation control.
312 */
313static struct list referenced_filters = LIST_HEAD_INIT(referenced_filters);
314
315
Thierry FOURNIERebed6e92016-12-16 11:54:07 +0100316/* This is the memory pool containing struct lua for applets
317 * (including cli).
318 */
Willy Tarreau8ceae722018-11-26 11:58:30 +0100319DECLARE_STATIC_POOL(pool_head_hlua, "hlua", sizeof(struct hlua));
Thierry FOURNIERebed6e92016-12-16 11:54:07 +0100320
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +0100321/* Used for Socket connection. */
Amaury Denoyelle239fdbf2021-03-24 10:22:03 +0100322static struct proxy *socket_proxy;
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +0100323static struct server *socket_tcp;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +0100324#ifdef USE_OPENSSL
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +0100325static struct server *socket_ssl;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +0100326#endif
327
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +0100328/* List head of the function called at the initialisation time. */
Thierry Fournierc7492592020-11-28 23:57:24 +0100329struct list hlua_init_functions[MAX_THREADS + 1];
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +0100330
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +0100331/* The following variables contains the reference of the different
332 * Lua classes. These references are useful for identify metadata
333 * associated with an object.
334 */
Thierry FOURNIER65f34c62015-02-16 20:11:43 +0100335static int class_txn_ref;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +0100336static int class_socket_ref;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +0100337static int class_channel_ref;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +0100338static int class_fetches_ref;
Thierry FOURNIER594afe72015-03-10 23:58:30 +0100339static int class_converters_ref;
Thierry FOURNIER08504f42015-03-16 14:17:08 +0100340static int class_http_ref;
Christopher Fauletdf97ac42020-02-26 16:57:19 +0100341static int class_http_msg_ref;
William Lallemand3956c4e2021-09-21 16:25:15 +0200342static int class_httpclient_ref;
Thierry FOURNIER3def3932015-04-07 11:27:54 +0200343static int class_map_ref;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +0200344static int class_applet_tcp_ref;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200345static int class_applet_http_ref;
Christopher Faulet700d9e82020-01-31 12:21:52 +0100346static int class_txn_reply_ref;
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +0100347
Thierry FOURNIERbd413492015-03-03 16:52:26 +0100348/* Global Lua execution timeout. By default Lua, execution linked
Willy Tarreau87b09662015-04-03 00:22:06 +0200349 * with stream (actions, sample-fetches and converters) have a
Thierry FOURNIERbd413492015-03-03 16:52:26 +0100350 * short timeout. Lua linked with tasks doesn't have a timeout
351 * because a task may remain alive during all the haproxy execution.
352 */
353static unsigned int hlua_timeout_session = 4000; /* session timeout. */
354static unsigned int hlua_timeout_task = TICK_ETERNITY; /* task timeout. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +0200355static unsigned int hlua_timeout_applet = 4000; /* applet timeout. */
Thierry FOURNIERbd413492015-03-03 16:52:26 +0100356
Thierry FOURNIERee9f8022015-03-03 17:37:37 +0100357/* Interrupts the Lua processing each "hlua_nb_instruction" instructions.
358 * it is used for preventing infinite loops.
359 *
360 * I test the scheer with an infinite loop containing one incrementation
361 * and one test. I run this loop between 10 seconds, I raise a ceil of
362 * 710M loops from one interrupt each 9000 instructions, so I fix the value
363 * to one interrupt each 10 000 instructions.
364 *
365 * configured | Number of
366 * instructions | loops executed
367 * between two | in milions
368 * forced yields |
369 * ---------------+---------------
370 * 10 | 160
371 * 500 | 670
372 * 1000 | 680
373 * 5000 | 700
374 * 7000 | 700
375 * 8000 | 700
376 * 9000 | 710 <- ceil
377 * 10000 | 710
378 * 100000 | 710
379 * 1000000 | 710
380 *
381 */
382static unsigned int hlua_nb_instruction = 10000;
383
Willy Tarreaucdb53462020-12-02 12:12:00 +0100384/* Descriptor for the memory allocation state. The limit is pre-initialised to
385 * 0 until it is replaced by "tune.lua.maxmem" during the config parsing, or it
386 * is replaced with ~0 during post_init after everything was loaded. This way
387 * it is guaranteed that if limit is ~0 the boot is complete and that if it's
388 * zero it's not yet limited and proper accounting is required.
Willy Tarreau32f61e22015-03-18 17:54:59 +0100389 */
390struct hlua_mem_allocator {
391 size_t allocated;
392 size_t limit;
393};
394
Willy Tarreaucdb53462020-12-02 12:12:00 +0100395static struct hlua_mem_allocator hlua_global_allocator THREAD_ALIGNED(64);
Willy Tarreau32f61e22015-03-18 17:54:59 +0100396
Aurelien DARRAGONc84899c2023-02-20 18:18:59 +0100397/* hlua event subscription */
398struct hlua_event_sub {
399 int fcn_ref;
400 int state_id;
401 struct hlua *hlua;
402 struct task *task;
403 event_hdl_async_equeue equeue;
404 struct event_hdl_sub *sub;
405 uint8_t paused;
406};
407
408/* This is the memory pool containing struct hlua_event_sub
409 * for event subscriptions from lua
410 */
411DECLARE_STATIC_POOL(pool_head_hlua_event_sub, "hlua_esub", sizeof(struct hlua_event_sub));
412
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100413/* These functions converts types between HAProxy internal args or
414 * sample and LUA types. Another function permits to check if the
415 * LUA stack contains arguments according with an required ARG_T
416 * format.
417 */
418static int hlua_arg2lua(lua_State *L, const struct arg *arg);
419static int hlua_lua2arg(lua_State *L, int ud, struct arg *arg);
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100420__LJMP static int hlua_lua2arg_check(lua_State *L, int first, struct arg *argp,
David Carlier0c437f42016-04-27 16:21:56 +0100421 uint64_t mask, struct proxy *p);
Willy Tarreau5eadada2015-03-10 17:28:54 +0100422static int hlua_smp2lua(lua_State *L, struct sample *smp);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100423static int hlua_smp2lua_str(lua_State *L, struct sample *smp);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100424static int hlua_lua2smp(lua_State *L, int ud, struct sample *smp);
425
Christopher Faulet9d1332b2020-02-24 16:46:16 +0100426__LJMP static int hlua_http_get_headers(lua_State *L, struct http_msg *msg);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200427
Thierry Fournier59f11be2020-11-29 00:37:41 +0100428struct prepend_path {
429 struct list l;
430 char *type;
431 char *path;
432};
433
434static struct list prepend_path_list = LIST_HEAD_INIT(prepend_path_list);
435
Thierry FOURNIER23bc3752015-09-11 19:15:43 +0200436#define SEND_ERR(__be, __fmt, __args...) \
437 do { \
438 send_log(__be, LOG_ERR, __fmt, ## __args); \
439 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE)) \
Christopher Faulet767a84b2017-11-24 16:50:31 +0100440 ha_alert(__fmt, ## __args); \
Thierry FOURNIER23bc3752015-09-11 19:15:43 +0200441 } while (0)
442
Thierry Fournier62a22aa2020-11-28 21:06:35 +0100443static inline struct hlua_function *new_hlua_function()
444{
445 struct hlua_function *fcn;
Thierry Fournierc7492592020-11-28 23:57:24 +0100446 int i;
Thierry Fournier62a22aa2020-11-28 21:06:35 +0100447
448 fcn = calloc(1, sizeof(*fcn));
449 if (!fcn)
450 return NULL;
Willy Tarreau2b718102021-04-21 07:32:39 +0200451 LIST_APPEND(&referenced_functions, &fcn->l);
Thierry Fournierc7492592020-11-28 23:57:24 +0100452 for (i = 0; i < MAX_THREADS + 1; i++)
453 fcn->function_ref[i] = -1;
Thierry Fournier62a22aa2020-11-28 21:06:35 +0100454 return fcn;
455}
456
Christopher Fauletdda44442021-04-12 14:05:43 +0200457static inline void release_hlua_function(struct hlua_function *fcn)
458{
459 if (!fcn)
460 return;
461 if (fcn->name)
462 ha_free(&fcn->name);
Willy Tarreau2b718102021-04-21 07:32:39 +0200463 LIST_DELETE(&fcn->l);
Christopher Fauletdda44442021-04-12 14:05:43 +0200464 ha_free(&fcn);
465}
466
Thierry Fournierc7492592020-11-28 23:57:24 +0100467/* If the common state is set, the stack id is 0, otherwise it is the tid + 1 */
468static inline int fcn_ref_to_stack_id(struct hlua_function *fcn)
469{
470 if (fcn->function_ref[0] == -1)
471 return tid + 1;
472 return 0;
473}
474
Christopher Faulet69c581a2021-05-31 08:54:04 +0200475/* Create a new registered filter. Only its name is filled */
476static inline struct hlua_reg_filter *new_hlua_reg_filter(const char *name)
477{
478 struct hlua_reg_filter *reg_flt;
479 int i;
480
481 reg_flt = calloc(1, sizeof(*reg_flt));
482 if (!reg_flt)
483 return NULL;
484 reg_flt->name = strdup(name);
485 if (!reg_flt->name) {
486 free(reg_flt);
487 return NULL;
488 }
489 LIST_APPEND(&referenced_filters, &reg_flt->l);
490 for (i = 0; i < MAX_THREADS + 1; i++) {
491 reg_flt->flt_ref[i] = -1;
492 reg_flt->fun_ref[i] = -1;
493 }
494 return reg_flt;
495}
496
497/* Release a registered filter */
498static inline void release_hlua_reg_filter(struct hlua_reg_filter *reg_flt)
499{
500 if (!reg_flt)
501 return;
502 if (reg_flt->name)
503 ha_free(&reg_flt->name);
504 LIST_DELETE(&reg_flt->l);
505 ha_free(&reg_flt);
506}
507
508/* If the common state is set, the stack id is 0, otherwise it is the tid + 1 */
509static inline int reg_flt_to_stack_id(struct hlua_reg_filter *reg_flt)
510{
511 if (reg_flt->fun_ref[0] == -1)
512 return tid + 1;
513 return 0;
514}
515
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100516/* Used to check an Lua function type in the stack. It creates and
517 * returns a reference of the function. This function throws an
Aurelien DARRAGONf8f8a2b2023-03-02 17:50:49 +0100518 * error if the argument is not a "function".
519 * When no longer used, the ref must be released with hlua_unref()
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100520 */
Aurelien DARRAGON9ee0d042023-03-20 18:36:08 +0100521__LJMP int hlua_checkfunction(lua_State *L, int argno)
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100522{
523 if (!lua_isfunction(L, argno)) {
Thierry FOURNIERfd1e9552018-02-23 18:41:18 +0100524 const char *msg = lua_pushfstring(L, "function expected, got %s", luaL_typename(L, argno));
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100525 WILL_LJMP(luaL_argerror(L, argno, msg));
526 }
527 lua_pushvalue(L, argno);
528 return luaL_ref(L, LUA_REGISTRYINDEX);
529}
530
Christopher Fauletba9e21d2020-02-25 10:20:04 +0100531/* Used to check an Lua table type in the stack. It creates and
532 * returns a reference of the table. This function throws an
Aurelien DARRAGONf8f8a2b2023-03-02 17:50:49 +0100533 * error if the argument is not a "table".
534 * When no longer used, the ref must be released with hlua_unref()
Christopher Fauletba9e21d2020-02-25 10:20:04 +0100535 */
Aurelien DARRAGON9ee0d042023-03-20 18:36:08 +0100536__LJMP int hlua_checktable(lua_State *L, int argno)
Christopher Fauletba9e21d2020-02-25 10:20:04 +0100537{
538 if (!lua_istable(L, argno)) {
539 const char *msg = lua_pushfstring(L, "table expected, got %s", luaL_typename(L, argno));
540 WILL_LJMP(luaL_argerror(L, argno, msg));
541 }
542 lua_pushvalue(L, argno);
543 return luaL_ref(L, LUA_REGISTRYINDEX);
544}
545
Aurelien DARRAGONf8f8a2b2023-03-02 17:50:49 +0100546/* Get a reference to the object that is at the top of the stack
547 * The referenced object will be popped from the stack
548 *
549 * The function returns the reference to the object which must
550 * be cleared using hlua_unref() when no longer used
551 */
552__LJMP int hlua_ref(lua_State *L)
553{
554 return MAY_LJMP(luaL_ref(L, LUA_REGISTRYINDEX));
555}
556
557/* Pushes a reference previously created using luaL_ref(L, LUA_REGISTRYINDEX)
558 * on <L> stack
559 * (ie: hlua_checkfunction(), hlua_checktable() or hlua_ref())
560 *
561 * When the reference is no longer used, it should be released by calling
562 * hlua_unref()
563 *
564 * <L> can be from any co-routine as long as it belongs to the same lua
565 * parent state that the one used to get the reference.
566 */
567void hlua_pushref(lua_State *L, int ref)
568{
569 lua_rawgeti(L, LUA_REGISTRYINDEX, ref);
570}
571
572/* Releases a reference previously created using luaL_ref(L, LUA_REGISTRYINDEX)
573 * (ie: hlua_checkfunction(), hlua_checktable() or hlua_ref())
574 *
575 * This will allow the reference to be reused and the referred object
576 * to be garbage collected.
577 *
578 * <L> can be from any co-routine as long as it belongs to the same lua
579 * parent state that the one used to get the reference.
580 */
581void hlua_unref(lua_State *L, int ref)
582{
583 luaL_unref(L, LUA_REGISTRYINDEX, ref);
584}
585
Christopher Fauletd09cc512021-03-24 14:48:45 +0100586__LJMP const char *hlua_traceback(lua_State *L, const char* sep)
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200587{
588 lua_Debug ar;
589 int level = 0;
Willy Tarreau83061a82018-07-13 11:56:34 +0200590 struct buffer *msg = get_trash_chunk();
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200591
592 while (lua_getstack(L, level++, &ar)) {
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200593 /* Fill fields:
594 * 'S': fills in the fields source, short_src, linedefined, lastlinedefined, and what;
595 * 'l': fills in the field currentline;
596 * 'n': fills in the field name and namewhat;
597 * 't': fills in the field istailcall;
598 */
599 lua_getinfo(L, "Slnt", &ar);
600
Willy Tarreau5c143402022-06-19 17:35:53 +0200601 /* skip these empty entries, usually they come from deep C functions */
602 if (ar.currentline < 0 && *ar.what == 'C' && !*ar.namewhat && !ar.name)
603 continue;
604
605 /* Add separator */
606 if (b_data(msg))
607 chunk_appendf(msg, "%s", sep);
608
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200609 /* Append code localisation */
610 if (ar.currentline > 0)
Christopher Fauletd09cc512021-03-24 14:48:45 +0100611 chunk_appendf(msg, "%s:%d: ", ar.short_src, ar.currentline);
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200612 else
Christopher Fauletd09cc512021-03-24 14:48:45 +0100613 chunk_appendf(msg, "%s: ", ar.short_src);
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200614
615 /*
616 * Get function name
617 *
618 * if namewhat is no empty, name is defined.
619 * what contains "Lua" for Lua function, "C" for C function,
620 * or "main" for main code.
621 */
622 if (*ar.namewhat != '\0' && ar.name != NULL) /* is there a name from code? */
Christopher Fauletd09cc512021-03-24 14:48:45 +0100623 chunk_appendf(msg, "in %s '%s'", ar.namewhat, ar.name); /* use it */
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200624
625 else if (*ar.what == 'm') /* "main", the code is not executed in a function */
Christopher Fauletd09cc512021-03-24 14:48:45 +0100626 chunk_appendf(msg, "in main chunk");
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200627
628 else if (*ar.what != 'C') /* for Lua functions, use <file:line> */
Christopher Fauletd09cc512021-03-24 14:48:45 +0100629 chunk_appendf(msg, "in function line %d", ar.linedefined);
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200630
631 else /* nothing left... */
632 chunk_appendf(msg, "?");
633
634
635 /* Display tailed call */
636 if (ar.istailcall)
637 chunk_appendf(msg, " ...");
638 }
639
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200640 return msg->area;
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200641}
642
643
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100644/* This function check the number of arguments available in the
645 * stack. If the number of arguments available is not the same
Ilya Shipitsinc02a23f2020-05-06 00:53:22 +0500646 * then <nb> an error is thrown.
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100647 */
648__LJMP static inline void check_args(lua_State *L, int nb, char *fcn)
649{
650 if (lua_gettop(L) == nb)
651 return;
652 WILL_LJMP(luaL_error(L, "'%s' needs %d arguments", fcn, nb));
653}
654
Mark Lakes22154b42018-01-29 14:38:40 -0800655/* This function pushes an error string prefixed by the file name
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100656 * and the line number where the error is encountered.
657 */
658static int hlua_pusherror(lua_State *L, const char *fmt, ...)
659{
660 va_list argp;
661 va_start(argp, fmt);
662 luaL_where(L, 1);
663 lua_pushvfstring(L, fmt, argp);
664 va_end(argp);
665 lua_concat(L, 2);
666 return 1;
667}
668
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100669/* This functions is used with sample fetch and converters. It
670 * converts the HAProxy configuration argument in a lua stack
671 * values.
672 *
673 * It takes an array of "arg", and each entry of the array is
674 * converted and pushed in the LUA stack.
675 */
676static int hlua_arg2lua(lua_State *L, const struct arg *arg)
677{
678 switch (arg->type) {
679 case ARGT_SINT:
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100680 case ARGT_TIME:
681 case ARGT_SIZE:
Thierry FOURNIERf90838b2015-03-06 13:48:32 +0100682 lua_pushinteger(L, arg->data.sint);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100683 break;
684
685 case ARGT_STR:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200686 lua_pushlstring(L, arg->data.str.area, arg->data.str.data);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100687 break;
688
689 case ARGT_IPV4:
690 case ARGT_IPV6:
691 case ARGT_MSK4:
692 case ARGT_MSK6:
693 case ARGT_FE:
694 case ARGT_BE:
695 case ARGT_TAB:
696 case ARGT_SRV:
697 case ARGT_USR:
698 case ARGT_MAP:
699 default:
700 lua_pushnil(L);
701 break;
702 }
703 return 1;
704}
705
Ilya Shipitsinc02a23f2020-05-06 00:53:22 +0500706/* This function take one entry in an LUA stack at the index "ud",
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100707 * and try to convert it in an HAProxy argument entry. This is useful
Ilya Shipitsind4259502020-04-08 01:07:56 +0500708 * with sample fetch wrappers. The input arguments are given to the
709 * lua wrapper and converted as arg list by the function.
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100710 */
711static int hlua_lua2arg(lua_State *L, int ud, struct arg *arg)
712{
713 switch (lua_type(L, ud)) {
714
715 case LUA_TNUMBER:
716 case LUA_TBOOLEAN:
717 arg->type = ARGT_SINT;
718 arg->data.sint = lua_tointeger(L, ud);
719 break;
720
721 case LUA_TSTRING:
722 arg->type = ARGT_STR;
Tim Duesterhus2e89dec2019-09-29 23:03:08 +0200723 arg->data.str.area = (char *)lua_tolstring(L, ud, &arg->data.str.data);
Tim Duesterhus29d2e8a2019-09-29 23:03:07 +0200724 /* We don't know the actual size of the underlying allocation, so be conservative. */
Christopher Fauletfdea1b62020-08-06 08:29:18 +0200725 arg->data.str.size = arg->data.str.data+1; /* count the terminating null byte */
Tim Duesterhus29d2e8a2019-09-29 23:03:07 +0200726 arg->data.str.head = 0;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100727 break;
728
729 case LUA_TUSERDATA:
730 case LUA_TNIL:
731 case LUA_TTABLE:
732 case LUA_TFUNCTION:
733 case LUA_TTHREAD:
734 case LUA_TLIGHTUSERDATA:
735 arg->type = ARGT_SINT;
Thierry FOURNIERbf65cd42015-07-20 17:45:02 +0200736 arg->data.sint = 0;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100737 break;
738 }
739 return 1;
740}
741
742/* the following functions are used to convert a struct sample
743 * in Lua type. This useful to convert the return of the
Ilya Shipitsind4259502020-04-08 01:07:56 +0500744 * fetches or converters.
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100745 */
Willy Tarreau5eadada2015-03-10 17:28:54 +0100746static int hlua_smp2lua(lua_State *L, struct sample *smp)
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100747{
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200748 switch (smp->data.type) {
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100749 case SMP_T_SINT:
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100750 case SMP_T_BOOL:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200751 lua_pushinteger(L, smp->data.u.sint);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100752 break;
753
754 case SMP_T_BIN:
755 case SMP_T_STR:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200756 lua_pushlstring(L, smp->data.u.str.area, smp->data.u.str.data);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100757 break;
758
759 case SMP_T_METH:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200760 switch (smp->data.u.meth.meth) {
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100761 case HTTP_METH_OPTIONS: lua_pushstring(L, "OPTIONS"); break;
762 case HTTP_METH_GET: lua_pushstring(L, "GET"); break;
763 case HTTP_METH_HEAD: lua_pushstring(L, "HEAD"); break;
764 case HTTP_METH_POST: lua_pushstring(L, "POST"); break;
765 case HTTP_METH_PUT: lua_pushstring(L, "PUT"); break;
766 case HTTP_METH_DELETE: lua_pushstring(L, "DELETE"); break;
767 case HTTP_METH_TRACE: lua_pushstring(L, "TRACE"); break;
768 case HTTP_METH_CONNECT: lua_pushstring(L, "CONNECT"); break;
769 case HTTP_METH_OTHER:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200770 lua_pushlstring(L, smp->data.u.meth.str.area, smp->data.u.meth.str.data);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100771 break;
772 default:
773 lua_pushnil(L);
774 break;
775 }
776 break;
777
778 case SMP_T_IPV4:
779 case SMP_T_IPV6:
780 case SMP_T_ADDR: /* This type is never used to qualify a sample. */
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200781 if (sample_casts[smp->data.type][SMP_T_STR] &&
782 sample_casts[smp->data.type][SMP_T_STR](smp))
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200783 lua_pushlstring(L, smp->data.u.str.area, smp->data.u.str.data);
Willy Tarreau5eadada2015-03-10 17:28:54 +0100784 else
785 lua_pushnil(L);
786 break;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100787 default:
788 lua_pushnil(L);
789 break;
790 }
791 return 1;
792}
793
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100794/* the following functions are used to convert a struct sample
795 * in Lua strings. This is useful to convert the return of the
Ilya Shipitsind4259502020-04-08 01:07:56 +0500796 * fetches or converters.
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100797 */
798static int hlua_smp2lua_str(lua_State *L, struct sample *smp)
799{
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200800 switch (smp->data.type) {
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100801
802 case SMP_T_BIN:
803 case SMP_T_STR:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200804 lua_pushlstring(L, smp->data.u.str.area, smp->data.u.str.data);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100805 break;
806
807 case SMP_T_METH:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200808 switch (smp->data.u.meth.meth) {
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100809 case HTTP_METH_OPTIONS: lua_pushstring(L, "OPTIONS"); break;
810 case HTTP_METH_GET: lua_pushstring(L, "GET"); break;
811 case HTTP_METH_HEAD: lua_pushstring(L, "HEAD"); break;
812 case HTTP_METH_POST: lua_pushstring(L, "POST"); break;
813 case HTTP_METH_PUT: lua_pushstring(L, "PUT"); break;
814 case HTTP_METH_DELETE: lua_pushstring(L, "DELETE"); break;
815 case HTTP_METH_TRACE: lua_pushstring(L, "TRACE"); break;
816 case HTTP_METH_CONNECT: lua_pushstring(L, "CONNECT"); break;
817 case HTTP_METH_OTHER:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200818 lua_pushlstring(L, smp->data.u.meth.str.area, smp->data.u.meth.str.data);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100819 break;
820 default:
821 lua_pushstring(L, "");
822 break;
823 }
824 break;
825
826 case SMP_T_SINT:
827 case SMP_T_BOOL:
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100828 case SMP_T_IPV4:
829 case SMP_T_IPV6:
830 case SMP_T_ADDR: /* This type is never used to qualify a sample. */
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200831 if (sample_casts[smp->data.type][SMP_T_STR] &&
832 sample_casts[smp->data.type][SMP_T_STR](smp))
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200833 lua_pushlstring(L, smp->data.u.str.area, smp->data.u.str.data);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100834 else
835 lua_pushstring(L, "");
836 break;
837 default:
838 lua_pushstring(L, "");
839 break;
840 }
841 return 1;
842}
843
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100844/* the following functions are used to convert an Lua type in a
845 * struct sample. This is useful to provide data from a converter
846 * to the LUA code.
847 */
848static int hlua_lua2smp(lua_State *L, int ud, struct sample *smp)
849{
850 switch (lua_type(L, ud)) {
851
852 case LUA_TNUMBER:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200853 smp->data.type = SMP_T_SINT;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200854 smp->data.u.sint = lua_tointeger(L, ud);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100855 break;
856
857
858 case LUA_TBOOLEAN:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200859 smp->data.type = SMP_T_BOOL;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200860 smp->data.u.sint = lua_toboolean(L, ud);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100861 break;
862
863 case LUA_TSTRING:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200864 smp->data.type = SMP_T_STR;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100865 smp->flags |= SMP_F_CONST;
Tim Duesterhus2e89dec2019-09-29 23:03:08 +0200866 smp->data.u.str.area = (char *)lua_tolstring(L, ud, &smp->data.u.str.data);
Tim Duesterhus29d2e8a2019-09-29 23:03:07 +0200867 /* We don't know the actual size of the underlying allocation, so be conservative. */
Christopher Fauletfdea1b62020-08-06 08:29:18 +0200868 smp->data.u.str.size = smp->data.u.str.data+1; /* count the terminating null byte */
Tim Duesterhus29d2e8a2019-09-29 23:03:07 +0200869 smp->data.u.str.head = 0;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100870 break;
871
872 case LUA_TUSERDATA:
873 case LUA_TNIL:
874 case LUA_TTABLE:
875 case LUA_TFUNCTION:
876 case LUA_TTHREAD:
877 case LUA_TLIGHTUSERDATA:
Thierry FOURNIER93405e12015-08-26 14:19:03 +0200878 case LUA_TNONE:
879 default:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200880 smp->data.type = SMP_T_BOOL;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200881 smp->data.u.sint = 0;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100882 break;
883 }
884 return 1;
885}
886
Ilya Shipitsind4259502020-04-08 01:07:56 +0500887/* This function check the "argp" built by another conversion function
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -0800888 * is in accord with the expected argp defined by the "mask". The function
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100889 * returns true or false. It can be adjust the types if there compatibles.
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100890 *
Ilya Shipitsinc02a23f2020-05-06 00:53:22 +0500891 * This function assumes that the argp argument contains ARGM_NBARGS + 1
Willy Tarreauee0d7272021-07-16 10:26:56 +0200892 * entries and that there is at least one stop at the last position.
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100893 */
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100894__LJMP int hlua_lua2arg_check(lua_State *L, int first, struct arg *argp,
David Carlier0c437f42016-04-27 16:21:56 +0100895 uint64_t mask, struct proxy *p)
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100896{
897 int min_arg;
Willy Tarreauee0d7272021-07-16 10:26:56 +0200898 int idx;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100899 struct proxy *px;
Christopher Fauletd25d9262020-08-06 11:04:46 +0200900 struct userlist *ul;
Christopher Fauletfd2e9062020-08-06 11:10:57 +0200901 struct my_regex *reg;
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200902 const char *msg = NULL;
Christopher Fauletfd2e9062020-08-06 11:10:57 +0200903 char *sname, *pname, *err = NULL;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100904
905 idx = 0;
906 min_arg = ARGM(mask);
907 mask >>= ARGM_BITS;
908
909 while (1) {
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200910 struct buffer tmp = BUF_NULL;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100911
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100912 /* Check for mandatory arguments. */
913 if (argp[idx].type == ARGT_STOP) {
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100914 if (idx < min_arg) {
915
916 /* If miss other argument than the first one, we return an error. */
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200917 if (idx > 0) {
918 msg = "Mandatory argument expected";
919 goto error;
920 }
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100921
922 /* If first argument have a certain type, some default values
923 * may be used. See the function smp_resolve_args().
924 */
925 switch (mask & ARGT_MASK) {
926
927 case ARGT_FE:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200928 if (!(p->cap & PR_CAP_FE)) {
929 msg = "Mandatory argument expected";
930 goto error;
931 }
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100932 argp[idx].data.prx = p;
933 argp[idx].type = ARGT_FE;
934 argp[idx+1].type = ARGT_STOP;
935 break;
936
937 case ARGT_BE:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200938 if (!(p->cap & PR_CAP_BE)) {
939 msg = "Mandatory argument expected";
940 goto error;
941 }
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100942 argp[idx].data.prx = p;
943 argp[idx].type = ARGT_BE;
944 argp[idx+1].type = ARGT_STOP;
945 break;
946
947 case ARGT_TAB:
Olivier Houchard14f62682022-09-13 00:35:53 +0200948 if (!p->table) {
949 msg = "Mandatory argument expected";
950 goto error;
951 }
952 argp[idx].data.t = p->table;
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100953 argp[idx].type = ARGT_TAB;
954 argp[idx+1].type = ARGT_STOP;
955 break;
956
957 default:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200958 msg = "Mandatory argument expected";
959 goto error;
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100960 break;
961 }
962 }
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200963 break;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100964 }
965
Ilya Shipitsin856aabc2020-04-16 23:51:34 +0500966 /* Check for exceed the number of required argument. */
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100967 if ((mask & ARGT_MASK) == ARGT_STOP &&
968 argp[idx].type != ARGT_STOP) {
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200969 msg = "Last argument expected";
970 goto error;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100971 }
972
973 if ((mask & ARGT_MASK) == ARGT_STOP &&
974 argp[idx].type == ARGT_STOP) {
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200975 break;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100976 }
977
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200978 /* Convert some argument types. All string in argp[] are for not
979 * duplicated yet.
980 */
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100981 switch (mask & ARGT_MASK) {
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100982 case ARGT_SINT:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200983 if (argp[idx].type != ARGT_SINT) {
984 msg = "integer expected";
985 goto error;
986 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100987 argp[idx].type = ARGT_SINT;
988 break;
989
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100990 case ARGT_TIME:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200991 if (argp[idx].type != ARGT_SINT) {
992 msg = "integer expected";
993 goto error;
994 }
Thierry FOURNIER29176f32015-07-07 00:41:29 +0200995 argp[idx].type = ARGT_TIME;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100996 break;
997
998 case ARGT_SIZE:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200999 if (argp[idx].type != ARGT_SINT) {
1000 msg = "integer expected";
1001 goto error;
1002 }
Thierry FOURNIER29176f32015-07-07 00:41:29 +02001003 argp[idx].type = ARGT_SIZE;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001004 break;
1005
1006 case ARGT_FE:
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001007 if (argp[idx].type != ARGT_STR) {
1008 msg = "string expected";
1009 goto error;
1010 }
Christopher Fauletfdea1b62020-08-06 08:29:18 +02001011 argp[idx].data.prx = proxy_fe_by_name(argp[idx].data.str.area);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001012 if (!argp[idx].data.prx) {
1013 msg = "frontend doesn't exist";
1014 goto error;
1015 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001016 argp[idx].type = ARGT_FE;
1017 break;
1018
1019 case ARGT_BE:
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001020 if (argp[idx].type != ARGT_STR) {
1021 msg = "string expected";
1022 goto error;
1023 }
Christopher Fauletfdea1b62020-08-06 08:29:18 +02001024 argp[idx].data.prx = proxy_be_by_name(argp[idx].data.str.area);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001025 if (!argp[idx].data.prx) {
1026 msg = "backend doesn't exist";
1027 goto error;
1028 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001029 argp[idx].type = ARGT_BE;
1030 break;
1031
1032 case ARGT_TAB:
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001033 if (argp[idx].type != ARGT_STR) {
1034 msg = "string expected";
1035 goto error;
1036 }
Christopher Fauletfdea1b62020-08-06 08:29:18 +02001037 argp[idx].data.t = stktable_find_by_name(argp[idx].data.str.area);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001038 if (!argp[idx].data.t) {
1039 msg = "table doesn't exist";
1040 goto error;
1041 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001042 argp[idx].type = ARGT_TAB;
1043 break;
1044
1045 case ARGT_SRV:
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001046 if (argp[idx].type != ARGT_STR) {
1047 msg = "string expected";
1048 goto error;
1049 }
Christopher Fauletfdea1b62020-08-06 08:29:18 +02001050 sname = strrchr(argp[idx].data.str.area, '/');
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001051 if (sname) {
1052 *sname++ = '\0';
Christopher Fauletfdea1b62020-08-06 08:29:18 +02001053 pname = argp[idx].data.str.area;
Willy Tarreau9e0bb102015-05-26 11:24:42 +02001054 px = proxy_be_by_name(pname);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001055 if (!px) {
1056 msg = "backend doesn't exist";
1057 goto error;
1058 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001059 }
1060 else {
Christopher Fauletfdea1b62020-08-06 08:29:18 +02001061 sname = argp[idx].data.str.area;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001062 px = p;
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001063 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001064 argp[idx].data.srv = findserver(px, sname);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001065 if (!argp[idx].data.srv) {
1066 msg = "server doesn't exist";
1067 goto error;
1068 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001069 argp[idx].type = ARGT_SRV;
1070 break;
1071
1072 case ARGT_IPV4:
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001073 if (argp[idx].type != ARGT_STR) {
1074 msg = "string expected";
1075 goto error;
1076 }
1077 if (inet_pton(AF_INET, argp[idx].data.str.area, &argp[idx].data.ipv4)) {
1078 msg = "invalid IPv4 address";
1079 goto error;
1080 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001081 argp[idx].type = ARGT_IPV4;
1082 break;
1083
1084 case ARGT_MSK4:
Christopher Faulete663a6e2020-08-07 09:11:22 +02001085 if (argp[idx].type == ARGT_SINT)
1086 len2mask4(argp[idx].data.sint, &argp[idx].data.ipv4);
1087 else if (argp[idx].type == ARGT_STR) {
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001088 if (!str2mask(argp[idx].data.str.area, &argp[idx].data.ipv4)) {
1089 msg = "invalid IPv4 mask";
1090 goto error;
1091 }
1092 }
1093 else {
1094 msg = "integer or string expected";
1095 goto error;
Christopher Faulete663a6e2020-08-07 09:11:22 +02001096 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001097 argp[idx].type = ARGT_MSK4;
1098 break;
1099
1100 case ARGT_IPV6:
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001101 if (argp[idx].type != ARGT_STR) {
1102 msg = "string expected";
1103 goto error;
1104 }
1105 if (inet_pton(AF_INET6, argp[idx].data.str.area, &argp[idx].data.ipv6)) {
1106 msg = "invalid IPv6 address";
1107 goto error;
1108 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001109 argp[idx].type = ARGT_IPV6;
1110 break;
1111
1112 case ARGT_MSK6:
Christopher Faulete663a6e2020-08-07 09:11:22 +02001113 if (argp[idx].type == ARGT_SINT)
1114 len2mask6(argp[idx].data.sint, &argp[idx].data.ipv6);
1115 else if (argp[idx].type == ARGT_STR) {
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001116 if (!str2mask6(argp[idx].data.str.area, &argp[idx].data.ipv6)) {
1117 msg = "invalid IPv6 mask";
1118 goto error;
1119 }
1120 }
1121 else {
1122 msg = "integer or string expected";
1123 goto error;
Christopher Faulete663a6e2020-08-07 09:11:22 +02001124 }
Tim Duesterhusb814da62018-01-25 16:24:50 +01001125 argp[idx].type = ARGT_MSK6;
1126 break;
1127
Christopher Fauletfd2e9062020-08-06 11:10:57 +02001128 case ARGT_REG:
1129 if (argp[idx].type != ARGT_STR) {
1130 msg = "string expected";
1131 goto error;
1132 }
1133 reg = regex_comp(argp[idx].data.str.area, !(argp[idx].type_flags & ARGF_REG_ICASE), 1, &err);
1134 if (!reg) {
1135 msg = lua_pushfstring(L, "error compiling regex '%s' : '%s'",
1136 argp[idx].data.str.area, err);
1137 free(err);
1138 goto error;
1139 }
1140 argp[idx].type = ARGT_REG;
1141 argp[idx].data.reg = reg;
1142 break;
1143
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001144 case ARGT_USR:
Christopher Fauletd25d9262020-08-06 11:04:46 +02001145 if (argp[idx].type != ARGT_STR) {
1146 msg = "string expected";
1147 goto error;
1148 }
1149 if (p->uri_auth && p->uri_auth->userlist &&
Tim Duesterhuse5ff1412021-01-02 22:31:53 +01001150 strcmp(p->uri_auth->userlist->name, argp[idx].data.str.area) == 0)
Christopher Fauletd25d9262020-08-06 11:04:46 +02001151 ul = p->uri_auth->userlist;
1152 else
1153 ul = auth_find_userlist(argp[idx].data.str.area);
1154
1155 if (!ul) {
1156 msg = lua_pushfstring(L, "unable to find userlist '%s'", argp[idx].data.str.area);
1157 goto error;
1158 }
1159 argp[idx].type = ARGT_USR;
1160 argp[idx].data.usr = ul;
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001161 break;
1162
1163 case ARGT_STR:
1164 if (!chunk_dup(&tmp, &argp[idx].data.str)) {
1165 msg = "unable to duplicate string arg";
1166 goto error;
1167 }
1168 argp[idx].data.str = tmp;
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001169 break;
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001170
Christopher Fauletd25d9262020-08-06 11:04:46 +02001171 case ARGT_MAP:
Christopher Fauletd25d9262020-08-06 11:04:46 +02001172 msg = "type not yet supported";
1173 goto error;
1174 break;
1175
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001176 }
1177
1178 /* Check for type of argument. */
1179 if ((mask & ARGT_MASK) != argp[idx].type) {
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001180 msg = lua_pushfstring(L, "'%s' expected, got '%s'",
1181 arg_type_names[(mask & ARGT_MASK)],
1182 arg_type_names[argp[idx].type & ARGT_MASK]);
1183 goto error;
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001184 }
1185
1186 /* Next argument. */
1187 mask >>= ARGT_BITS;
1188 idx++;
1189 }
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001190 return 0;
1191
1192 error:
Olivier Houchardca431612022-09-13 00:31:17 +02001193 argp[idx].type = ARGT_STOP;
Willy Tarreauee0d7272021-07-16 10:26:56 +02001194 free_args(argp);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001195 WILL_LJMP(luaL_argerror(L, first + idx, msg));
1196 return 0; /* Never reached */
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001197}
1198
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001199/*
Ilya Shipitsinc02a23f2020-05-06 00:53:22 +05001200 * The following functions are used to make correspondence between the the
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001201 * executed lua pointer and the "struct hlua *" that contain the context.
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001202 *
1203 * - hlua_gethlua : return the hlua context associated with an lua_State.
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001204 * - hlua_sethlua : create the association between hlua context and lua_state.
1205 */
1206static inline struct hlua *hlua_gethlua(lua_State *L)
1207{
Thierry FOURNIER38c5fd62015-03-10 02:40:29 +01001208 struct hlua **hlua = lua_getextraspace(L);
1209 return *hlua;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001210}
1211static inline void hlua_sethlua(struct hlua *hlua)
1212{
Thierry FOURNIER38c5fd62015-03-10 02:40:29 +01001213 struct hlua **hlua_store = lua_getextraspace(hlua->T);
1214 *hlua_store = hlua;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001215}
1216
Willy Tarreau0b7b6392022-06-19 17:39:33 +02001217/* Will return a non-NULL string indicating the Lua call trace if the caller
1218 * currently is executing from within a Lua function. One line per entry will
1219 * be emitted, and each extra line will be prefixed with <pfx>. If a current
1220 * Lua function is not detected, NULL is returned.
1221 */
1222const char *hlua_show_current_location(const char *pfx)
1223{
1224 lua_State *L;
1225 lua_Debug ar;
1226
1227 /* global or per-thread stack initializing ? */
1228 if (hlua_state_id != -1 && (L = hlua_states[hlua_state_id]) && lua_getstack(L, 0, &ar))
1229 return hlua_traceback(L, pfx);
1230
1231 /* per-thread stack running ? */
1232 if (hlua_states[tid + 1] && (L = hlua_states[tid + 1]) && lua_getstack(L, 0, &ar))
1233 return hlua_traceback(L, pfx);
1234
1235 /* global stack running ? */
1236 if (hlua_states[0] && (L = hlua_states[0]) && lua_getstack(L, 0, &ar))
1237 return hlua_traceback(L, pfx);
1238
1239 return NULL;
1240}
1241
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01001242/* This function is used to send logs. It try to send on screen (stderr)
1243 * and on the default syslog server.
1244 */
1245static inline void hlua_sendlog(struct proxy *px, int level, const char *msg)
1246{
1247 struct tm tm;
1248 char *p;
1249
1250 /* Cleanup the log message. */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001251 p = trash.area;
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01001252 for (; *msg != '\0'; msg++, p++) {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001253 if (p >= trash.area + trash.size - 1) {
Thierry FOURNIERccf00632015-09-16 12:47:03 +02001254 /* Break the message if exceed the buffer size. */
1255 *(p-4) = ' ';
1256 *(p-3) = '.';
1257 *(p-2) = '.';
1258 *(p-1) = '.';
1259 break;
1260 }
Willy Tarreau90807112020-02-25 08:16:33 +01001261 if (isprint((unsigned char)*msg))
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01001262 *p = *msg;
1263 else
1264 *p = '.';
1265 }
1266 *p = '\0';
1267
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001268 send_log(px, level, "%s\n", trash.area);
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01001269 if (!(global.mode & MODE_QUIET) || (global.mode & (MODE_VERBOSE | MODE_STARTING))) {
Christopher Fauletf98d8212020-10-02 18:13:52 +02001270 if (level == LOG_DEBUG && !(global.mode & MODE_DEBUG))
1271 return;
1272
Willy Tarreaua678b432015-08-28 10:14:59 +02001273 get_localtime(date.tv_sec, &tm);
1274 fprintf(stderr, "[%s] %03d/%02d%02d%02d (%d) : %s\n",
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01001275 log_levels[level], tm.tm_yday, tm.tm_hour, tm.tm_min, tm.tm_sec,
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001276 (int)getpid(), trash.area);
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01001277 fflush(stderr);
1278 }
1279}
1280
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001281/* This function just ensure that the yield will be always
1282 * returned with a timeout and permit to set some flags
1283 */
1284__LJMP void hlua_yieldk(lua_State *L, int nresults, int ctx,
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001285 lua_KFunction k, int timeout, unsigned int flags)
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001286{
Thierry Fournier4234dbd2020-11-28 13:18:23 +01001287 struct hlua *hlua;
1288
1289 /* Get hlua struct, or NULL if we execute from main lua state */
1290 hlua = hlua_gethlua(L);
1291 if (!hlua) {
1292 return;
1293 }
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001294
1295 /* Set the wake timeout. If timeout is required, we set
1296 * the expiration time.
1297 */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001298 hlua->wake_time = timeout;
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001299
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01001300 hlua->flags |= flags;
1301
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001302 /* Process the yield. */
Willy Tarreau9635e032018-10-16 17:52:55 +02001303 MAY_LJMP(lua_yieldk(L, nresults, ctx, k));
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001304}
1305
Willy Tarreau87b09662015-04-03 00:22:06 +02001306/* This function initialises the Lua environment stored in the stream.
1307 * It must be called at the start of the stream. This function creates
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001308 * an LUA coroutine. It can not be use to crete the main LUA context.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02001309 *
1310 * This function is particular. it initialises a new Lua thread. If the
1311 * initialisation fails (example: out of memory error), the lua function
1312 * throws an error (longjmp).
1313 *
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001314 * This function manipulates two Lua stacks: the main and the thread. Only
Thierry FOURNIERbabae282015-09-17 11:36:37 +02001315 * the main stack can fail. The thread is not manipulated. This function
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001316 * MUST NOT manipulate the created thread stack state, because it is not
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001317 * protected against errors thrown by the thread stack.
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001318 */
Aurelien DARRAGON6b0b9bd2023-03-21 14:02:16 +01001319int hlua_ctx_init(struct hlua *lua, int state_id, struct task *task)
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001320{
1321 lua->Mref = LUA_REFNIL;
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001322 lua->flags = 0;
Willy Tarreauf31af932020-01-14 09:59:38 +01001323 lua->gc_count = 0;
Christopher Fauletbc275a92020-02-26 14:55:16 +01001324 lua->wake_time = TICK_ETERNITY;
Thierry Fournier021d9862020-11-28 23:42:03 +01001325 lua->state_id = state_id;
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01001326 LIST_INIT(&lua->com);
Aurelien DARRAGON3ffbf382023-02-09 17:02:57 +01001327 MT_LIST_INIT(&lua->hc_list);
Aurelien DARRAGON6b0b9bd2023-03-21 14:02:16 +01001328 if (!SET_SAFE_LJMP_PARENT(lua)) {
1329 lua->Tref = LUA_REFNIL;
1330 return 0;
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001331 }
Thierry Fournier021d9862020-11-28 23:42:03 +01001332 lua->T = lua_newthread(hlua_states[state_id]);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001333 if (!lua->T) {
1334 lua->Tref = LUA_REFNIL;
Aurelien DARRAGON6b0b9bd2023-03-21 14:02:16 +01001335 RESET_SAFE_LJMP_PARENT(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001336 return 0;
1337 }
1338 hlua_sethlua(lua);
Thierry Fournier021d9862020-11-28 23:42:03 +01001339 lua->Tref = luaL_ref(hlua_states[state_id], LUA_REGISTRYINDEX);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001340 lua->task = task;
Aurelien DARRAGON6b0b9bd2023-03-21 14:02:16 +01001341 RESET_SAFE_LJMP_PARENT(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001342 return 1;
1343}
1344
Aurelien DARRAGON3ffbf382023-02-09 17:02:57 +01001345/* kill all associated httpclient to this hlua task
1346 * We must take extra precautions as we're manipulating lua-exposed
1347 * objects without the main lua lock.
1348 */
William Lallemandbb581422022-10-20 10:57:28 +02001349static void hlua_httpclient_destroy_all(struct hlua *hlua)
1350{
Aurelien DARRAGON3ffbf382023-02-09 17:02:57 +01001351 struct hlua_httpclient *hlua_hc;
William Lallemandbb581422022-10-20 10:57:28 +02001352
Aurelien DARRAGON3ffbf382023-02-09 17:02:57 +01001353 /* use thread-safe accessors for hc_list since GC cycle initiated by
1354 * another thread sharing the same main lua stack (lua coroutine)
1355 * could execute hlua_httpclient_gc() on the hlua->hc_list items
1356 * in parallel: Lua GC applies on the main stack, it is not limited to
1357 * a single coroutine stack, see Github issue #2037 for reference.
1358 * Remember, coroutines created using lua_newthread() are not meant to
1359 * be thread safe in Lua. (From lua co-author:
1360 * http://lua-users.org/lists/lua-l/2011-07/msg00072.html)
1361 *
1362 * This security measure is superfluous when 'lua-load-per-thread' is used
1363 * since in this case coroutines exclusively run on the same thread
1364 * (main stack is not shared between OS threads).
1365 */
1366 while ((hlua_hc = MT_LIST_POP(&hlua->hc_list, typeof(hlua_hc), by_hlua))) {
1367 httpclient_stop_and_destroy(hlua_hc->hc);
William Lallemandbb581422022-10-20 10:57:28 +02001368 hlua_hc->hc = NULL;
William Lallemandbb581422022-10-20 10:57:28 +02001369 }
1370}
1371
1372
Willy Tarreau87b09662015-04-03 00:22:06 +02001373/* Used to destroy the Lua coroutine when the attached stream or task
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001374 * is destroyed. The destroy also the memory context. The struct "lua"
Aurelien DARRAGON60ab0f72023-03-01 16:45:50 +01001375 * will be freed.
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001376 */
1377void hlua_ctx_destroy(struct hlua *lua)
1378{
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01001379 if (!lua)
Thierry FOURNIERa718b292015-03-04 16:48:34 +01001380 return;
1381
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01001382 if (!lua->T)
1383 goto end;
1384
William Lallemandbb581422022-10-20 10:57:28 +02001385 /* clean all running httpclient */
1386 hlua_httpclient_destroy_all(lua);
1387
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01001388 /* Purge all the pending signals. */
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001389 notification_purge(&lua->com);
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01001390
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001391 if (!SET_SAFE_LJMP(lua))
Thierry FOURNIER75d02082017-07-12 13:41:33 +02001392 return;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001393 luaL_unref(lua->T, LUA_REGISTRYINDEX, lua->Mref);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001394 RESET_SAFE_LJMP(lua);
Thierry FOURNIER5a50a852015-09-23 16:59:28 +02001395
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001396 if (!SET_SAFE_LJMP_PARENT(lua))
Thierry FOURNIER75d02082017-07-12 13:41:33 +02001397 return;
Thierry Fournier021d9862020-11-28 23:42:03 +01001398 luaL_unref(hlua_states[lua->state_id], LUA_REGISTRYINDEX, lua->Tref);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001399 RESET_SAFE_LJMP_PARENT(lua);
Thierry FOURNIER5a50a852015-09-23 16:59:28 +02001400 /* Forces a garbage collecting process. If the Lua program is finished
1401 * without error, we run the GC on the thread pointer. Its freed all
1402 * the unused memory.
1403 * If the thread is finnish with an error or is currently yielded,
1404 * it seems that the GC applied on the thread doesn't clean anything,
1405 * so e run the GC on the main thread.
1406 * NOTE: maybe this action locks all the Lua threads untiml the en of
1407 * the garbage collection.
1408 */
Willy Tarreauf31af932020-01-14 09:59:38 +01001409 if (lua->gc_count) {
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001410 if (!SET_SAFE_LJMP_PARENT(lua))
Thierry FOURNIER75d02082017-07-12 13:41:33 +02001411 return;
Thierry Fournier021d9862020-11-28 23:42:03 +01001412 lua_gc(hlua_states[lua->state_id], LUA_GCCOLLECT, 0);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001413 RESET_SAFE_LJMP_PARENT(lua);
Thierry FOURNIER7c39ab42015-09-27 22:53:33 +02001414 }
Thierry FOURNIER5a50a852015-09-23 16:59:28 +02001415
Thierry FOURNIERa7b536b2015-09-21 22:50:24 +02001416 lua->T = NULL;
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01001417
1418end:
Willy Tarreaubafbe012017-11-24 17:34:44 +01001419 pool_free(pool_head_hlua, lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001420}
1421
1422/* This function is used to restore the Lua context when a coroutine
1423 * fails. This function copy the common memory between old coroutine
1424 * and the new coroutine. The old coroutine is destroyed, and its
1425 * replaced by the new coroutine.
1426 * If the flag "keep_msg" is set, the last entry of the old is assumed
1427 * as string error message and it is copied in the new stack.
1428 */
1429static int hlua_ctx_renew(struct hlua *lua, int keep_msg)
1430{
1431 lua_State *T;
1432 int new_ref;
1433
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001434 /* New Lua coroutine. */
Thierry Fournier021d9862020-11-28 23:42:03 +01001435 T = lua_newthread(hlua_states[lua->state_id]);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001436 if (!T)
1437 return 0;
1438
1439 /* Copy last error message. */
1440 if (keep_msg)
1441 lua_xmove(lua->T, T, 1);
1442
1443 /* Copy data between the coroutines. */
1444 lua_rawgeti(lua->T, LUA_REGISTRYINDEX, lua->Mref);
1445 lua_xmove(lua->T, T, 1);
Ilya Shipitsin46a030c2020-07-05 16:36:08 +05001446 new_ref = luaL_ref(T, LUA_REGISTRYINDEX); /* Value popped. */
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001447
1448 /* Destroy old data. */
1449 luaL_unref(lua->T, LUA_REGISTRYINDEX, lua->Mref);
1450
1451 /* The thread is garbage collected by Lua. */
Thierry Fournier021d9862020-11-28 23:42:03 +01001452 luaL_unref(hlua_states[lua->state_id], LUA_REGISTRYINDEX, lua->Tref);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001453
1454 /* Fill the struct with the new coroutine values. */
1455 lua->Mref = new_ref;
1456 lua->T = T;
Thierry Fournier021d9862020-11-28 23:42:03 +01001457 lua->Tref = luaL_ref(hlua_states[lua->state_id], LUA_REGISTRYINDEX);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001458
1459 /* Set context. */
1460 hlua_sethlua(lua);
1461
1462 return 1;
1463}
1464
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001465void hlua_hook(lua_State *L, lua_Debug *ar)
1466{
Thierry Fournier4234dbd2020-11-28 13:18:23 +01001467 struct hlua *hlua;
1468
1469 /* Get hlua struct, or NULL if we execute from main lua state */
1470 hlua = hlua_gethlua(L);
1471 if (!hlua)
1472 return;
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001473
1474 /* Lua cannot yield when its returning from a function,
1475 * so, we can fix the interrupt hook to 1 instruction,
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001476 * expecting that the function is finished.
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001477 */
1478 if (lua_gethookmask(L) & LUA_MASKRET) {
1479 lua_sethook(hlua->T, hlua_hook, LUA_MASKCOUNT, 1);
1480 return;
1481 }
1482
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001483 /* If we interrupt the Lua processing in yieldable state, we yield.
1484 * If the state is not yieldable, trying yield causes an error.
1485 */
Aurelien DARRAGON0ebd41f2022-11-24 09:51:40 +01001486 if (lua_isyieldable(L)) {
1487 /* note: for converters/fetches.. where yielding is not allowed
1488 * hlua_ctx_resume() will simply perform a goto resume_execution
1489 * instead of rescheduling hlua->task.
1490 * also: hlua_ctx_resume() will take care of checking execution
1491 * timeout and re-applying the hook as needed.
1492 */
Willy Tarreau9635e032018-10-16 17:52:55 +02001493 MAY_LJMP(hlua_yieldk(L, 0, 0, NULL, TICK_ETERNITY, HLUA_CTRLYIELD));
Aurelien DARRAGON0ebd41f2022-11-24 09:51:40 +01001494 /* lua docs says that the hook should return immediately after lua_yieldk
1495 *
1496 * From: https://www.lua.org/manual/5.3/manual.html#lua_yieldk
1497 *
1498 * Moreover, it seems that we don't want to continue after the yield
1499 * because the end of the function is about handling unyieldable function,
1500 * which is not the case here.
1501 *
1502 * ->if we don't return lua_sethook gets incorrectly set with MASKRET later
1503 * in the function.
1504 */
1505 return;
1506 }
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001507
Thierry FOURNIERa85cfb12015-03-13 14:50:06 +01001508 /* If we cannot yield, update the clock and check the timeout. */
Willy Tarreau55542642021-10-08 09:33:24 +02001509 clock_update_date(0, 1);
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001510 hlua->run_time += now_ms - hlua->start_time;
1511 if (hlua->max_time && hlua->run_time >= hlua->max_time) {
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001512 lua_pushfstring(L, "execution timeout");
1513 WILL_LJMP(lua_error(L));
1514 }
1515
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001516 /* Update the start time. */
1517 hlua->start_time = now_ms;
1518
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001519 /* Try to interrupt the process at the end of the current
1520 * unyieldable function.
1521 */
1522 lua_sethook(hlua->T, hlua_hook, LUA_MASKRET|LUA_MASKCOUNT, hlua_nb_instruction);
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001523}
1524
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001525/* This function start or resumes the Lua stack execution. If the flag
1526 * "yield_allowed" if no set and the LUA stack execution returns a yield
1527 * The function return an error.
1528 *
1529 * The function can returns 4 values:
1530 * - HLUA_E_OK : The execution is terminated without any errors.
1531 * - HLUA_E_AGAIN : The execution must continue at the next associated
1532 * task wakeup.
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001533 * - HLUA_E_ERRMSG : An error has occurred, an error message is set in
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001534 * the top of the stack.
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001535 * - HLUA_E_ERR : An error has occurred without error message.
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001536 *
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001537 * If an error occurred, the stack is renewed and it is ready to run new
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001538 * LUA code.
1539 */
1540static enum hlua_exec hlua_ctx_resume(struct hlua *lua, int yield_allowed)
1541{
Christopher Faulet08ed98f2020-07-28 10:33:25 +02001542#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM >= 504
1543 int nres;
1544#endif
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001545 int ret;
1546 const char *msg;
Thierry FOURNIERfc044c92018-06-07 14:40:48 +02001547 const char *trace;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001548
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001549 /* Initialise run time counter. */
1550 if (!HLUA_IS_RUNNING(lua))
1551 lua->run_time = 0;
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001552
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +02001553 /* Lock the whole Lua execution. This lock must be before the
1554 * label "resume_execution".
1555 */
Aurelien DARRAGONe36f8032023-03-21 13:22:33 +01001556 hlua_lock(lua);
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +02001557
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001558resume_execution:
1559
1560 /* This hook interrupts the Lua processing each 'hlua_nb_instruction'
1561 * instructions. it is used for preventing infinite loops.
1562 */
1563 lua_sethook(lua->T, hlua_hook, LUA_MASKCOUNT, hlua_nb_instruction);
1564
Thierry FOURNIER1bfc09b2015-03-05 17:10:14 +01001565 /* Remove all flags except the running flags. */
Thierry FOURNIER2f3867f2015-09-28 01:02:01 +02001566 HLUA_SET_RUN(lua);
1567 HLUA_CLR_CTRLYIELD(lua);
1568 HLUA_CLR_WAKERESWR(lua);
1569 HLUA_CLR_WAKEREQWR(lua);
Christopher Faulet1f43a342021-08-04 17:58:21 +02001570 HLUA_CLR_NOYIELD(lua);
1571 if (!yield_allowed)
1572 HLUA_SET_NOYIELD(lua);
Thierry FOURNIER1bfc09b2015-03-05 17:10:14 +01001573
Christopher Fauletbc275a92020-02-26 14:55:16 +01001574 /* Update the start time and reset wake_time. */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001575 lua->start_time = now_ms;
Christopher Fauletbc275a92020-02-26 14:55:16 +01001576 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001577
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001578 /* Call the function. */
Christopher Faulet08ed98f2020-07-28 10:33:25 +02001579#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM >= 504
Thierry Fournier021d9862020-11-28 23:42:03 +01001580 ret = lua_resume(lua->T, hlua_states[lua->state_id], lua->nargs, &nres);
Christopher Faulet08ed98f2020-07-28 10:33:25 +02001581#else
Thierry Fournier021d9862020-11-28 23:42:03 +01001582 ret = lua_resume(lua->T, hlua_states[lua->state_id], lua->nargs);
Christopher Faulet08ed98f2020-07-28 10:33:25 +02001583#endif
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001584 switch (ret) {
1585
1586 case LUA_OK:
1587 ret = HLUA_E_OK;
1588 break;
1589
1590 case LUA_YIELD:
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001591 /* Check if the execution timeout is expired. It it is the case, we
1592 * break the Lua execution.
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001593 */
Willy Tarreau55542642021-10-08 09:33:24 +02001594 clock_update_date(0, 1);
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001595 lua->run_time += now_ms - lua->start_time;
1596 if (lua->max_time && lua->run_time > lua->max_time) {
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001597 lua_settop(lua->T, 0); /* Empty the stack. */
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001598 ret = HLUA_E_ETMOUT;
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001599 break;
1600 }
1601 /* Process the forced yield. if the general yield is not allowed or
1602 * if no task were associated this the current Lua execution
1603 * coroutine, we resume the execution. Else we want to return in the
1604 * scheduler and we want to be waked up again, to continue the
1605 * current Lua execution. So we schedule our own task.
1606 */
1607 if (HLUA_IS_CTRLYIELDING(lua)) {
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001608 if (!yield_allowed || !lua->task)
1609 goto resume_execution;
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001610 task_wakeup(lua->task, TASK_WOKEN_MSG);
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001611 }
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001612 if (!yield_allowed) {
1613 lua_settop(lua->T, 0); /* Empty the stack. */
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001614 ret = HLUA_E_YIELD;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001615 break;
1616 }
1617 ret = HLUA_E_AGAIN;
1618 break;
1619
1620 case LUA_ERRRUN:
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001621
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001622 /* Special exit case. The traditional exit is returned as an error
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001623 * because the errors ares the only one mean to return immediately
1624 * from and lua execution.
1625 */
1626 if (lua->flags & HLUA_EXIT) {
1627 ret = HLUA_E_OK;
Christopher Faulet7716cdf2020-01-29 11:53:30 +01001628 hlua_ctx_renew(lua, 1);
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001629 break;
1630 }
1631
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001632 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001633 if (!lua_checkstack(lua->T, 1)) {
1634 ret = HLUA_E_ERR;
1635 break;
1636 }
1637 msg = lua_tostring(lua->T, -1);
1638 lua_settop(lua->T, 0); /* Empty the stack. */
1639 lua_pop(lua->T, 1);
Christopher Fauletd09cc512021-03-24 14:48:45 +01001640 trace = hlua_traceback(lua->T, ", ");
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001641 if (msg)
Thierry Fournier46278ff2020-11-29 11:48:12 +01001642 lua_pushfstring(lua->T, "[state-id %d] runtime error: %s from %s", lua->state_id, msg, trace);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001643 else
Thierry Fournier46278ff2020-11-29 11:48:12 +01001644 lua_pushfstring(lua->T, "[state-id %d] unknown runtime error from %s", lua->state_id, trace);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001645 ret = HLUA_E_ERRMSG;
1646 break;
1647
1648 case LUA_ERRMEM:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001649 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001650 lua_settop(lua->T, 0); /* Empty the stack. */
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001651 ret = HLUA_E_NOMEM;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001652 break;
1653
1654 case LUA_ERRERR:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001655 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001656 if (!lua_checkstack(lua->T, 1)) {
1657 ret = HLUA_E_ERR;
1658 break;
1659 }
1660 msg = lua_tostring(lua->T, -1);
1661 lua_settop(lua->T, 0); /* Empty the stack. */
1662 lua_pop(lua->T, 1);
1663 if (msg)
Thierry Fournier46278ff2020-11-29 11:48:12 +01001664 lua_pushfstring(lua->T, "[state-id %d] message handler error: %s", lua->state_id, msg);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001665 else
Thierry Fournier46278ff2020-11-29 11:48:12 +01001666 lua_pushfstring(lua->T, "[state-id %d] message handler error", lua->state_id);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001667 ret = HLUA_E_ERRMSG;
1668 break;
1669
1670 default:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001671 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001672 lua_settop(lua->T, 0); /* Empty the stack. */
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001673 ret = HLUA_E_ERR;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001674 break;
1675 }
1676
1677 switch (ret) {
1678 case HLUA_E_AGAIN:
1679 break;
1680
1681 case HLUA_E_ERRMSG:
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001682 notification_purge(&lua->com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001683 hlua_ctx_renew(lua, 1);
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001684 HLUA_CLR_RUN(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001685 break;
1686
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001687 case HLUA_E_ETMOUT:
1688 case HLUA_E_NOMEM:
1689 case HLUA_E_YIELD:
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001690 case HLUA_E_ERR:
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001691 HLUA_CLR_RUN(lua);
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001692 notification_purge(&lua->com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001693 hlua_ctx_renew(lua, 0);
1694 break;
1695
1696 case HLUA_E_OK:
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001697 HLUA_CLR_RUN(lua);
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001698 notification_purge(&lua->com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001699 break;
1700 }
1701
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +02001702 /* This is the main exit point, remove the Lua lock. */
Aurelien DARRAGONe36f8032023-03-21 13:22:33 +01001703 hlua_unlock(lua);
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +02001704
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001705 return ret;
1706}
1707
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001708/* This function exit the current code. */
1709__LJMP static int hlua_done(lua_State *L)
1710{
Thierry Fournier4234dbd2020-11-28 13:18:23 +01001711 struct hlua *hlua;
1712
1713 /* Get hlua struct, or NULL if we execute from main lua state */
1714 hlua = hlua_gethlua(L);
1715 if (!hlua)
1716 return 0;
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001717
1718 hlua->flags |= HLUA_EXIT;
1719 WILL_LJMP(lua_error(L));
1720
1721 return 0;
1722}
1723
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001724/* This function is an LUA binding. It provides a function
1725 * for deleting ACL from a referenced ACL file.
1726 */
1727__LJMP static int hlua_del_acl(lua_State *L)
1728{
1729 const char *name;
1730 const char *key;
1731 struct pat_ref *ref;
1732
1733 MAY_LJMP(check_args(L, 2, "del_acl"));
1734
1735 name = MAY_LJMP(luaL_checkstring(L, 1));
1736 key = MAY_LJMP(luaL_checkstring(L, 2));
1737
1738 ref = pat_ref_lookup(name);
1739 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001740 WILL_LJMP(luaL_error(L, "'del_acl': unknown acl file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001741
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001742 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001743 pat_ref_delete(ref, key);
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001744 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001745 return 0;
1746}
1747
1748/* This function is an LUA binding. It provides a function
1749 * for deleting map entry from a referenced map file.
1750 */
1751static int hlua_del_map(lua_State *L)
1752{
1753 const char *name;
1754 const char *key;
1755 struct pat_ref *ref;
1756
1757 MAY_LJMP(check_args(L, 2, "del_map"));
1758
1759 name = MAY_LJMP(luaL_checkstring(L, 1));
1760 key = MAY_LJMP(luaL_checkstring(L, 2));
1761
1762 ref = pat_ref_lookup(name);
1763 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001764 WILL_LJMP(luaL_error(L, "'del_map': unknown acl file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001765
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001766 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001767 pat_ref_delete(ref, key);
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001768 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001769 return 0;
1770}
1771
1772/* This function is an LUA binding. It provides a function
1773 * for adding ACL pattern from a referenced ACL file.
1774 */
1775static int hlua_add_acl(lua_State *L)
1776{
1777 const char *name;
1778 const char *key;
1779 struct pat_ref *ref;
1780
1781 MAY_LJMP(check_args(L, 2, "add_acl"));
1782
1783 name = MAY_LJMP(luaL_checkstring(L, 1));
1784 key = MAY_LJMP(luaL_checkstring(L, 2));
1785
1786 ref = pat_ref_lookup(name);
1787 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001788 WILL_LJMP(luaL_error(L, "'add_acl': unknown acl file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001789
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001790 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001791 if (pat_ref_find_elt(ref, key) == NULL)
1792 pat_ref_add(ref, key, NULL, NULL);
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001793 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001794 return 0;
1795}
1796
1797/* This function is an LUA binding. It provides a function
1798 * for setting map pattern and sample from a referenced map
1799 * file.
1800 */
1801static int hlua_set_map(lua_State *L)
1802{
1803 const char *name;
1804 const char *key;
1805 const char *value;
1806 struct pat_ref *ref;
1807
1808 MAY_LJMP(check_args(L, 3, "set_map"));
1809
1810 name = MAY_LJMP(luaL_checkstring(L, 1));
1811 key = MAY_LJMP(luaL_checkstring(L, 2));
1812 value = MAY_LJMP(luaL_checkstring(L, 3));
1813
1814 ref = pat_ref_lookup(name);
1815 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001816 WILL_LJMP(luaL_error(L, "'set_map': unknown map file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001817
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001818 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001819 if (pat_ref_find_elt(ref, key) != NULL)
1820 pat_ref_set(ref, key, value, NULL);
1821 else
1822 pat_ref_add(ref, key, value, NULL);
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001823 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001824 return 0;
1825}
1826
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01001827/* A class is a lot of memory that contain data. This data can be a table,
1828 * an integer or user data. This data is associated with a metatable. This
Ilya Shipitsinc02a23f2020-05-06 00:53:22 +05001829 * metatable have an original version registered in the global context with
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01001830 * the name of the object (_G[<name>] = <metable> ).
1831 *
1832 * A metable is a table that modify the standard behavior of a standard
1833 * access to the associated data. The entries of this new metatable are
1834 * defined as is:
1835 *
1836 * http://lua-users.org/wiki/MetatableEvents
1837 *
1838 * __index
1839 *
1840 * we access an absent field in a table, the result is nil. This is
1841 * true, but it is not the whole truth. Actually, such access triggers
1842 * the interpreter to look for an __index metamethod: If there is no
1843 * such method, as usually happens, then the access results in nil;
1844 * otherwise, the metamethod will provide the result.
1845 *
1846 * Control 'prototype' inheritance. When accessing "myTable[key]" and
1847 * the key does not appear in the table, but the metatable has an __index
1848 * property:
1849 *
1850 * - if the value is a function, the function is called, passing in the
1851 * table and the key; the return value of that function is returned as
1852 * the result.
1853 *
1854 * - if the value is another table, the value of the key in that table is
1855 * asked for and returned (and if it doesn't exist in that table, but that
1856 * table's metatable has an __index property, then it continues on up)
1857 *
1858 * - Use "rawget(myTable,key)" to skip this metamethod.
1859 *
1860 * http://www.lua.org/pil/13.4.1.html
1861 *
1862 * __newindex
1863 *
1864 * Like __index, but control property assignment.
1865 *
1866 * __mode - Control weak references. A string value with one or both
1867 * of the characters 'k' and 'v' which specifies that the the
1868 * keys and/or values in the table are weak references.
1869 *
1870 * __call - Treat a table like a function. When a table is followed by
1871 * parenthesis such as "myTable( 'foo' )" and the metatable has
1872 * a __call key pointing to a function, that function is invoked
1873 * (passing any specified arguments) and the return value is
1874 * returned.
1875 *
1876 * __metatable - Hide the metatable. When "getmetatable( myTable )" is
1877 * called, if the metatable for myTable has a __metatable
1878 * key, the value of that key is returned instead of the
1879 * actual metatable.
1880 *
1881 * __tostring - Control string representation. When the builtin
1882 * "tostring( myTable )" function is called, if the metatable
1883 * for myTable has a __tostring property set to a function,
1884 * that function is invoked (passing myTable to it) and the
1885 * return value is used as the string representation.
1886 *
1887 * __len - Control table length. When the table length is requested using
1888 * the length operator ( '#' ), if the metatable for myTable has
1889 * a __len key pointing to a function, that function is invoked
1890 * (passing myTable to it) and the return value used as the value
1891 * of "#myTable".
1892 *
1893 * __gc - Userdata finalizer code. When userdata is set to be garbage
1894 * collected, if the metatable has a __gc field pointing to a
1895 * function, that function is first invoked, passing the userdata
1896 * to it. The __gc metamethod is not called for tables.
1897 * (See http://lua-users.org/lists/lua-l/2006-11/msg00508.html)
1898 *
1899 * Special metamethods for redefining standard operators:
1900 * http://www.lua.org/pil/13.1.html
1901 *
1902 * __add "+"
1903 * __sub "-"
1904 * __mul "*"
1905 * __div "/"
1906 * __unm "!"
1907 * __pow "^"
1908 * __concat ".."
1909 *
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001910 * Special methods for redefining standard relations
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01001911 * http://www.lua.org/pil/13.2.html
1912 *
1913 * __eq "=="
1914 * __lt "<"
1915 * __le "<="
1916 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001917
1918/*
1919 *
1920 *
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001921 * Class Map
1922 *
1923 *
1924 */
1925
1926/* Returns a struct hlua_map if the stack entry "ud" is
1927 * a class session, otherwise it throws an error.
1928 */
1929__LJMP static struct map_descriptor *hlua_checkmap(lua_State *L, int ud)
1930{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02001931 return MAY_LJMP(hlua_checkudata(L, ud, class_map_ref));
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001932}
1933
1934/* This function is the map constructor. It don't need
1935 * the class Map object. It creates and return a new Map
1936 * object. It must be called only during "body" or "init"
1937 * context because it process some filesystem accesses.
1938 */
1939__LJMP static int hlua_map_new(struct lua_State *L)
1940{
1941 const char *fn;
1942 int match = PAT_MATCH_STR;
1943 struct sample_conv conv;
1944 const char *file = "";
1945 int line = 0;
1946 lua_Debug ar;
1947 char *err = NULL;
1948 struct arg args[2];
1949
1950 if (lua_gettop(L) < 1 || lua_gettop(L) > 2)
1951 WILL_LJMP(luaL_error(L, "'new' needs at least 1 argument."));
1952
1953 fn = MAY_LJMP(luaL_checkstring(L, 1));
1954
1955 if (lua_gettop(L) >= 2) {
1956 match = MAY_LJMP(luaL_checkinteger(L, 2));
1957 if (match < 0 || match >= PAT_MATCH_NUM)
1958 WILL_LJMP(luaL_error(L, "'new' needs a valid match method."));
1959 }
1960
1961 /* Get Lua filename and line number. */
1962 if (lua_getstack(L, 1, &ar)) { /* check function at level */
1963 lua_getinfo(L, "Sl", &ar); /* get info about it */
1964 if (ar.currentline > 0) { /* is there info? */
1965 file = ar.short_src;
1966 line = ar.currentline;
1967 }
1968 }
1969
1970 /* fill fake sample_conv struct. */
1971 conv.kw = ""; /* unused. */
1972 conv.process = NULL; /* unused. */
1973 conv.arg_mask = 0; /* unused. */
1974 conv.val_args = NULL; /* unused. */
1975 conv.out_type = SMP_T_STR;
1976 conv.private = (void *)(long)match;
1977 switch (match) {
1978 case PAT_MATCH_STR: conv.in_type = SMP_T_STR; break;
1979 case PAT_MATCH_BEG: conv.in_type = SMP_T_STR; break;
1980 case PAT_MATCH_SUB: conv.in_type = SMP_T_STR; break;
1981 case PAT_MATCH_DIR: conv.in_type = SMP_T_STR; break;
1982 case PAT_MATCH_DOM: conv.in_type = SMP_T_STR; break;
1983 case PAT_MATCH_END: conv.in_type = SMP_T_STR; break;
1984 case PAT_MATCH_REG: conv.in_type = SMP_T_STR; break;
Thierry FOURNIER07ee64e2015-07-06 23:43:03 +02001985 case PAT_MATCH_INT: conv.in_type = SMP_T_SINT; break;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001986 case PAT_MATCH_IP: conv.in_type = SMP_T_ADDR; break;
1987 default:
1988 WILL_LJMP(luaL_error(L, "'new' doesn't support this match mode."));
1989 }
1990
1991 /* fill fake args. */
1992 args[0].type = ARGT_STR;
Christopher Faulet73292e92020-08-06 08:40:09 +02001993 args[0].data.str.area = strdup(fn);
1994 args[0].data.str.data = strlen(fn);
1995 args[0].data.str.size = args[0].data.str.data+1;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001996 args[1].type = ARGT_STOP;
1997
1998 /* load the map. */
1999 if (!sample_load_map(args, &conv, file, line, &err)) {
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +05002000 /* error case: we can't use luaL_error because we must
Thierry FOURNIER3def3932015-04-07 11:27:54 +02002001 * free the err variable.
2002 */
2003 luaL_where(L, 1);
2004 lua_pushfstring(L, "'new': %s.", err);
2005 lua_concat(L, 2);
2006 free(err);
Christopher Faulet6ad7df42020-08-07 11:45:18 +02002007 chunk_destroy(&args[0].data.str);
Thierry FOURNIER3def3932015-04-07 11:27:54 +02002008 WILL_LJMP(lua_error(L));
2009 }
2010
2011 /* create the lua object. */
2012 lua_newtable(L);
2013 lua_pushlightuserdata(L, args[0].data.map);
2014 lua_rawseti(L, -2, 0);
2015
2016 /* Pop a class Map metatable and affect it to the userdata. */
2017 lua_rawgeti(L, LUA_REGISTRYINDEX, class_map_ref);
2018 lua_setmetatable(L, -2);
2019
2020
2021 return 1;
2022}
2023
2024__LJMP static inline int _hlua_map_lookup(struct lua_State *L, int str)
2025{
2026 struct map_descriptor *desc;
2027 struct pattern *pat;
2028 struct sample smp;
2029
2030 MAY_LJMP(check_args(L, 2, "lookup"));
2031 desc = MAY_LJMP(hlua_checkmap(L, 1));
Thierry FOURNIER07ee64e2015-07-06 23:43:03 +02002032 if (desc->pat.expect_type == SMP_T_SINT) {
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02002033 smp.data.type = SMP_T_SINT;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +02002034 smp.data.u.sint = MAY_LJMP(luaL_checkinteger(L, 2));
Thierry FOURNIER3def3932015-04-07 11:27:54 +02002035 }
2036 else {
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02002037 smp.data.type = SMP_T_STR;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02002038 smp.flags = SMP_F_CONST;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02002039 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 +01002040 smp.data.u.str.size = smp.data.u.str.data + 1;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02002041 }
2042
2043 pat = pattern_exec_match(&desc->pat, &smp, 1);
Thierry FOURNIER503bb092015-08-19 08:35:43 +02002044 if (!pat || !pat->data) {
Thierry FOURNIER3def3932015-04-07 11:27:54 +02002045 if (str)
2046 lua_pushstring(L, "");
2047 else
2048 lua_pushnil(L);
2049 return 1;
2050 }
2051
2052 /* The Lua pattern must return a string, so we can't check the returned type */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02002053 lua_pushlstring(L, pat->data->u.str.area, pat->data->u.str.data);
Thierry FOURNIER3def3932015-04-07 11:27:54 +02002054 return 1;
2055}
2056
2057__LJMP static int hlua_map_lookup(struct lua_State *L)
2058{
2059 return _hlua_map_lookup(L, 0);
2060}
2061
2062__LJMP static int hlua_map_slookup(struct lua_State *L)
2063{
2064 return _hlua_map_lookup(L, 1);
2065}
2066
2067/*
2068 *
2069 *
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002070 * Class Socket
2071 *
2072 *
2073 */
2074
2075__LJMP static struct hlua_socket *hlua_checksocket(lua_State *L, int ud)
2076{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02002077 return MAY_LJMP(hlua_checkudata(L, ud, class_socket_ref));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002078}
2079
2080/* This function is the handler called for each I/O on the established
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002081 * connection. It is used for notify space available to send or data
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002082 * received.
2083 */
Willy Tarreau00a37f02015-04-13 12:05:19 +02002084static void hlua_socket_handler(struct appctx *appctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002085{
Willy Tarreau5321da92022-05-06 11:57:34 +02002086 struct hlua_csk_ctx *ctx = appctx->svcctx;
Willy Tarreauc12b3212022-05-27 11:08:15 +02002087 struct stconn *sc = appctx_sc(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002088
Christopher Faulet31572222023-03-31 11:13:48 +02002089 if (unlikely(se_fl_test(appctx->sedesc, (SE_FL_EOS|SE_FL_ERROR|SE_FL_SHR|SE_FL_SHW)))) {
2090 notification_wake(&ctx->wake_on_read);
2091 notification_wake(&ctx->wake_on_write);
2092 return;
2093 }
2094
Willy Tarreau5321da92022-05-06 11:57:34 +02002095 if (ctx->die) {
Christopher Faulet31572222023-03-31 11:13:48 +02002096 se_fl_set(appctx->sedesc, SE_FL_EOI|SE_FL_EOS);
Willy Tarreau5321da92022-05-06 11:57:34 +02002097 notification_wake(&ctx->wake_on_read);
2098 notification_wake(&ctx->wake_on_write);
Christopher Faulet31572222023-03-31 11:13:48 +02002099 return;
Thierry FOURNIERb13b20a2017-07-16 20:48:54 +02002100 }
2101
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +05002102 /* If we can't write, wakeup the pending write signals. */
Willy Tarreau3e7be362022-05-27 10:35:27 +02002103 if (channel_output_closed(sc_ic(sc)))
Willy Tarreau5321da92022-05-06 11:57:34 +02002104 notification_wake(&ctx->wake_on_write);
Thierry FOURNIER6d695e62015-09-27 19:29:38 +02002105
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +05002106 /* If we can't read, wakeup the pending read signals. */
Willy Tarreau3e7be362022-05-27 10:35:27 +02002107 if (channel_input_closed(sc_oc(sc)))
Willy Tarreau5321da92022-05-06 11:57:34 +02002108 notification_wake(&ctx->wake_on_read);
Thierry FOURNIER6d695e62015-09-27 19:29:38 +02002109
Willy Tarreau5a0b25d2019-07-18 18:01:14 +02002110 /* if the connection is not established, inform the stream that we want
Thierry FOURNIER316e3192015-09-04 18:25:53 +02002111 * to be notified whenever the connection completes.
2112 */
Willy Tarreau3e7be362022-05-27 10:35:27 +02002113 if (sc_opposite(sc)->state < SC_ST_EST) {
Willy Tarreau90e8b452022-05-25 18:21:43 +02002114 applet_need_more_data(appctx);
Willy Tarreaub23edc82022-05-24 16:49:03 +02002115 se_need_remote_conn(appctx->sedesc);
Willy Tarreau4164eb92022-05-25 15:42:03 +02002116 applet_have_more_data(appctx);
Willy Tarreaud4da1962015-04-20 01:31:23 +02002117 return;
Thierry FOURNIER316e3192015-09-04 18:25:53 +02002118 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002119
2120 /* This function is called after the connect. */
Willy Tarreau5321da92022-05-06 11:57:34 +02002121 ctx->connected = 1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002122
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002123 /* Wake the tasks which wants to write if the buffer have available space. */
Willy Tarreau3e7be362022-05-27 10:35:27 +02002124 if (channel_may_recv(sc_ic(sc)))
Willy Tarreau5321da92022-05-06 11:57:34 +02002125 notification_wake(&ctx->wake_on_write);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002126
2127 /* Wake the tasks which wants to read if the buffer contains data. */
Willy Tarreau3e7be362022-05-27 10:35:27 +02002128 if (!channel_is_empty(sc_oc(sc)))
Willy Tarreau5321da92022-05-06 11:57:34 +02002129 notification_wake(&ctx->wake_on_read);
Thierry FOURNIER101b9762018-05-27 01:27:40 +02002130
Thierry FOURNIER101b9762018-05-27 01:27:40 +02002131 /* If write notifications are registered, we considers we want
Willy Tarreau3367d412018-11-15 10:57:41 +01002132 * to write, so we clear the blocking flag.
Thierry FOURNIER101b9762018-05-27 01:27:40 +02002133 */
Willy Tarreau5321da92022-05-06 11:57:34 +02002134 if (notification_registered(&ctx->wake_on_write))
Willy Tarreau4164eb92022-05-25 15:42:03 +02002135 applet_have_more_data(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002136}
2137
Christopher Faulet5f35a3e2022-05-12 15:31:05 +02002138static int hlua_socket_init(struct appctx *appctx)
2139{
2140 struct hlua_csk_ctx *ctx = appctx->svcctx;
2141 struct stream *s;
2142
2143 if (appctx_finalize_startup(appctx, socket_proxy, &BUF_NULL) == -1)
2144 goto error;
2145
2146 s = appctx_strm(appctx);
2147
Willy Tarreau4596fe22022-05-17 19:07:51 +02002148 /* Configure "right" stream connector. This stconn is used to connect
Christopher Faulet5f35a3e2022-05-12 15:31:05 +02002149 * and retrieve data from the server. The connection is initialized
2150 * with the "struct server".
2151 */
Willy Tarreau74568cf2022-05-27 09:03:30 +02002152 sc_set_state(s->scb, SC_ST_ASS);
Christopher Faulet5f35a3e2022-05-12 15:31:05 +02002153
2154 /* Force destination server. */
2155 s->flags |= SF_DIRECT | SF_ASSIGNED | SF_BE_ASSIGNED;
2156 s->target = &socket_tcp->obj_type;
2157
2158 ctx->appctx = appctx;
2159 return 0;
2160
2161 error:
2162 return -1;
2163}
2164
Willy Tarreau87b09662015-04-03 00:22:06 +02002165/* This function is called when the "struct stream" is destroyed.
2166 * Remove the link from the object to this stream.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002167 * Wake all the pending signals.
2168 */
Willy Tarreau00a37f02015-04-13 12:05:19 +02002169static void hlua_socket_release(struct appctx *appctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002170{
Willy Tarreau5321da92022-05-06 11:57:34 +02002171 struct hlua_csk_ctx *ctx = appctx->svcctx;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002172 struct xref *peer;
2173
Christopher Faulet5f35a3e2022-05-12 15:31:05 +02002174 /* Remove my link in the original objects. */
Willy Tarreau5321da92022-05-06 11:57:34 +02002175 peer = xref_get_peer_and_lock(&ctx->xref);
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002176 if (peer)
Willy Tarreau5321da92022-05-06 11:57:34 +02002177 xref_disconnect(&ctx->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002178
2179 /* Wake all the task waiting for me. */
Willy Tarreau5321da92022-05-06 11:57:34 +02002180 notification_wake(&ctx->wake_on_read);
2181 notification_wake(&ctx->wake_on_write);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002182}
2183
2184/* If the garbage collectio of the object is launch, nobody
Willy Tarreau87b09662015-04-03 00:22:06 +02002185 * uses this object. If the stream does not exists, just quit.
2186 * Send the shutdown signal to the stream. In some cases,
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002187 * pending signal can rest in the read and write lists. destroy
2188 * it.
2189 */
2190__LJMP static int hlua_socket_gc(lua_State *L)
2191{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002192 struct hlua_socket *socket;
Willy Tarreau5321da92022-05-06 11:57:34 +02002193 struct hlua_csk_ctx *ctx;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002194 struct xref *peer;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002195
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002196 MAY_LJMP(check_args(L, 1, "__gc"));
2197
2198 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002199 peer = xref_get_peer_and_lock(&socket->xref);
2200 if (!peer)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002201 return 0;
Willy Tarreau5321da92022-05-06 11:57:34 +02002202
2203 ctx = container_of(peer, struct hlua_csk_ctx, xref);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002204
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002205 /* Set the flag which destroy the session. */
Willy Tarreau5321da92022-05-06 11:57:34 +02002206 ctx->die = 1;
2207 appctx_wakeup(ctx->appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002208
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002209 /* Remove all reference between the Lua stack and the coroutine stream. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002210 xref_disconnect(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002211 return 0;
2212}
2213
2214/* The close function send shutdown signal and break the
Willy Tarreau87b09662015-04-03 00:22:06 +02002215 * links between the stream and the object.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002216 */
sada05ed3302018-05-11 11:48:18 -07002217__LJMP static int hlua_socket_close_helper(lua_State *L)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002218{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002219 struct hlua_socket *socket;
Willy Tarreau5321da92022-05-06 11:57:34 +02002220 struct hlua_csk_ctx *ctx;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002221 struct xref *peer;
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002222 struct hlua *hlua;
2223
2224 /* Get hlua struct, or NULL if we execute from main lua state */
2225 hlua = hlua_gethlua(L);
2226 if (!hlua)
2227 return 0;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002228
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002229 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002230
2231 /* Check if we run on the same thread than the xreator thread.
2232 * We cannot access to the socket if the thread is different.
2233 */
2234 if (socket->tid != tid)
2235 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2236
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002237 peer = xref_get_peer_and_lock(&socket->xref);
2238 if (!peer)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002239 return 0;
Willy Tarreauf31af932020-01-14 09:59:38 +01002240
2241 hlua->gc_count--;
Willy Tarreau5321da92022-05-06 11:57:34 +02002242 ctx = container_of(peer, struct hlua_csk_ctx, xref);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002243
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002244 /* Set the flag which destroy the session. */
Willy Tarreau5321da92022-05-06 11:57:34 +02002245 ctx->die = 1;
2246 appctx_wakeup(ctx->appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002247
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002248 /* Remove all reference between the Lua stack and the coroutine stream. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002249 xref_disconnect(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002250 return 0;
2251}
2252
sada05ed3302018-05-11 11:48:18 -07002253/* The close function calls close_helper.
2254 */
2255__LJMP static int hlua_socket_close(lua_State *L)
2256{
2257 MAY_LJMP(check_args(L, 1, "close"));
2258 return hlua_socket_close_helper(L);
2259}
2260
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002261/* This Lua function assumes that the stack contain three parameters.
2262 * 1 - USERDATA containing a struct socket
2263 * 2 - INTEGER with values of the macro defined below
2264 * If the integer is -1, we must read at most one line.
2265 * If the integer is -2, we ust read all the data until the
2266 * end of the stream.
2267 * If the integer is positive value, we must read a number of
2268 * bytes corresponding to this value.
2269 */
2270#define HLSR_READ_LINE (-1)
2271#define HLSR_READ_ALL (-2)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002272__LJMP static int hlua_socket_receive_yield(struct lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002273{
2274 struct hlua_socket *socket = MAY_LJMP(hlua_checksocket(L, 1));
2275 int wanted = lua_tointeger(L, 2);
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002276 struct hlua *hlua;
Willy Tarreau5321da92022-05-06 11:57:34 +02002277 struct hlua_csk_ctx *csk_ctx;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002278 struct appctx *appctx;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02002279 size_t len;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002280 int nblk;
Willy Tarreau206ba832018-06-14 15:27:31 +02002281 const char *blk1;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02002282 size_t len1;
Willy Tarreau206ba832018-06-14 15:27:31 +02002283 const char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02002284 size_t len2;
Thierry FOURNIER00543922015-03-09 18:35:06 +01002285 int skip_at_end = 0;
Willy Tarreau81389672015-03-10 12:03:52 +01002286 struct channel *oc;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002287 struct stream *s;
2288 struct xref *peer;
Thierry FOURNIER8c126c72018-05-25 16:27:44 +02002289 int missing_bytes;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002290
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002291 /* Get hlua struct, or NULL if we execute from main lua state */
2292 hlua = hlua_gethlua(L);
2293
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002294 /* Check if this lua stack is schedulable. */
2295 if (!hlua || !hlua->task)
2296 WILL_LJMP(luaL_error(L, "The 'receive' function is only allowed in "
2297 "'frontend', 'backend' or 'task'"));
2298
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002299 /* Check if we run on the same thread than the xreator thread.
2300 * We cannot access to the socket if the thread is different.
2301 */
2302 if (socket->tid != tid)
2303 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2304
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002305 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002306 peer = xref_get_peer_and_lock(&socket->xref);
2307 if (!peer)
2308 goto no_peer;
Willy Tarreau5321da92022-05-06 11:57:34 +02002309
2310 csk_ctx = container_of(peer, struct hlua_csk_ctx, xref);
2311 appctx = csk_ctx->appctx;
Willy Tarreau0698c802022-05-11 14:09:57 +02002312 s = appctx_strm(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002313
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002314 oc = &s->res;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002315 if (wanted == HLSR_READ_LINE) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002316 /* Read line. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02002317 nblk = co_getline_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002318 if (nblk < 0) /* Connection close. */
2319 goto connection_closed;
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002320 if (nblk == 0) /* No data available. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002321 goto connection_empty;
Thierry FOURNIER00543922015-03-09 18:35:06 +01002322
2323 /* remove final \r\n. */
2324 if (nblk == 1) {
2325 if (blk1[len1-1] == '\n') {
2326 len1--;
2327 skip_at_end++;
2328 if (blk1[len1-1] == '\r') {
2329 len1--;
2330 skip_at_end++;
2331 }
2332 }
2333 }
2334 else {
2335 if (blk2[len2-1] == '\n') {
2336 len2--;
2337 skip_at_end++;
2338 if (blk2[len2-1] == '\r') {
2339 len2--;
2340 skip_at_end++;
2341 }
2342 }
2343 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002344 }
2345
2346 else if (wanted == HLSR_READ_ALL) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002347 /* Read all the available data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02002348 nblk = co_getblk_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002349 if (nblk < 0) /* Connection close. */
2350 goto connection_closed;
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002351 if (nblk == 0) /* No data available. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002352 goto connection_empty;
2353 }
2354
2355 else {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002356 /* Read a block of data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02002357 nblk = co_getblk_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002358 if (nblk < 0) /* Connection close. */
2359 goto connection_closed;
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002360 if (nblk == 0) /* No data available. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002361 goto connection_empty;
2362
Thierry FOURNIER8c126c72018-05-25 16:27:44 +02002363 missing_bytes = wanted - socket->b.n;
2364 if (len1 > missing_bytes) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002365 nblk = 1;
Thierry FOURNIER8c126c72018-05-25 16:27:44 +02002366 len1 = missing_bytes;
2367 } if (nblk == 2 && len1 + len2 > missing_bytes)
2368 len2 = missing_bytes - len1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002369 }
2370
2371 len = len1;
2372
2373 luaL_addlstring(&socket->b, blk1, len1);
2374 if (nblk == 2) {
2375 len += len2;
2376 luaL_addlstring(&socket->b, blk2, len2);
2377 }
2378
2379 /* Consume data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02002380 co_skip(oc, len + skip_at_end);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002381
2382 /* Don't wait anything. */
Thierry FOURNIER7e4ee472018-05-25 15:03:50 +02002383 appctx_wakeup(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002384
2385 /* If the pattern reclaim to read all the data
2386 * in the connection, got out.
2387 */
2388 if (wanted == HLSR_READ_ALL)
2389 goto connection_empty;
Thierry FOURNIER8c126c72018-05-25 16:27:44 +02002390 else if (wanted >= 0 && socket->b.n < wanted)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002391 goto connection_empty;
2392
2393 /* Return result. */
2394 luaL_pushresult(&socket->b);
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002395 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002396 return 1;
2397
2398connection_closed:
2399
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002400 xref_unlock(&socket->xref, peer);
2401
2402no_peer:
2403
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002404 /* If the buffer containds data. */
2405 if (socket->b.n > 0) {
2406 luaL_pushresult(&socket->b);
2407 return 1;
2408 }
2409 lua_pushnil(L);
2410 lua_pushstring(L, "connection closed.");
2411 return 2;
2412
2413connection_empty:
2414
Willy Tarreau5321da92022-05-06 11:57:34 +02002415 if (!notification_new(&hlua->com, &csk_ctx->wake_on_read, hlua->task)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002416 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002417 WILL_LJMP(luaL_error(L, "out of memory"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002418 }
2419 xref_unlock(&socket->xref, peer);
Willy Tarreau9635e032018-10-16 17:52:55 +02002420 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_receive_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002421 return 0;
2422}
2423
Tim Duesterhusb33754c2018-01-04 19:32:14 +01002424/* This Lua function gets two parameters. The first one can be string
2425 * or a number. If the string is "*l", the user requires one line. If
2426 * the string is "*a", the user requires all the contents of the stream.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002427 * If the value is a number, the user require a number of bytes equal
2428 * to the value. The default value is "*l" (a line).
2429 *
Tim Duesterhusb33754c2018-01-04 19:32:14 +01002430 * This parameter with a variable type is converted in integer. This
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002431 * integer takes this values:
2432 * -1 : read a line
2433 * -2 : read all the stream
Tim Duesterhusb33754c2018-01-04 19:32:14 +01002434 * >0 : amount of bytes.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002435 *
Tim Duesterhusb33754c2018-01-04 19:32:14 +01002436 * The second parameter is optional. It contains a string that must be
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002437 * concatenated with the read data.
2438 */
2439__LJMP static int hlua_socket_receive(struct lua_State *L)
2440{
2441 int wanted = HLSR_READ_LINE;
2442 const char *pattern;
Christopher Fauletc31b2002021-05-03 10:11:13 +02002443 int lastarg, type;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002444 char *error;
2445 size_t len;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002446 struct hlua_socket *socket;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002447
2448 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
2449 WILL_LJMP(luaL_error(L, "The 'receive' function requires between 1 and 3 arguments."));
2450
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002451 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002452
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002453 /* Check if we run on the same thread than the xreator thread.
2454 * We cannot access to the socket if the thread is different.
2455 */
2456 if (socket->tid != tid)
2457 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2458
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002459 /* check for pattern. */
2460 if (lua_gettop(L) >= 2) {
2461 type = lua_type(L, 2);
2462 if (type == LUA_TSTRING) {
2463 pattern = lua_tostring(L, 2);
2464 if (strcmp(pattern, "*a") == 0)
2465 wanted = HLSR_READ_ALL;
2466 else if (strcmp(pattern, "*l") == 0)
2467 wanted = HLSR_READ_LINE;
2468 else {
2469 wanted = strtoll(pattern, &error, 10);
2470 if (*error != '\0')
2471 WILL_LJMP(luaL_error(L, "Unsupported pattern."));
2472 }
2473 }
2474 else if (type == LUA_TNUMBER) {
2475 wanted = lua_tointeger(L, 2);
2476 if (wanted < 0)
2477 WILL_LJMP(luaL_error(L, "Unsupported size."));
2478 }
2479 }
2480
2481 /* Set pattern. */
2482 lua_pushinteger(L, wanted);
Tim Duesterhusc6e377e2018-01-04 19:32:13 +01002483
2484 /* Check if we would replace the top by itself. */
2485 if (lua_gettop(L) != 2)
2486 lua_replace(L, 2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002487
Christopher Fauletc31b2002021-05-03 10:11:13 +02002488 /* Save index of the top of the stack because since buffers are used, it
2489 * may change
2490 */
2491 lastarg = lua_gettop(L);
2492
Tim Duesterhusb33754c2018-01-04 19:32:14 +01002493 /* init buffer, and fill it with prefix. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002494 luaL_buffinit(L, &socket->b);
2495
2496 /* Check prefix. */
Christopher Fauletc31b2002021-05-03 10:11:13 +02002497 if (lastarg >= 3) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002498 if (lua_type(L, 3) != LUA_TSTRING)
2499 WILL_LJMP(luaL_error(L, "Expect a 'string' for the prefix"));
2500 pattern = lua_tolstring(L, 3, &len);
2501 luaL_addlstring(&socket->b, pattern, len);
2502 }
2503
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002504 return __LJMP(hlua_socket_receive_yield(L, 0, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002505}
2506
2507/* Write the Lua input string in the output buffer.
Mark Lakes22154b42018-01-29 14:38:40 -08002508 * This function returns a yield if no space is available.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002509 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002510static int hlua_socket_write_yield(struct lua_State *L,int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002511{
2512 struct hlua_socket *socket;
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002513 struct hlua *hlua;
Willy Tarreau5321da92022-05-06 11:57:34 +02002514 struct hlua_csk_ctx *csk_ctx;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002515 struct appctx *appctx;
2516 size_t buf_len;
2517 const char *buf;
2518 int len;
2519 int send_len;
2520 int sent;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002521 struct xref *peer;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002522 struct stream *s;
Willy Tarreau3e7be362022-05-27 10:35:27 +02002523 struct stconn *sc;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002524
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002525 /* Get hlua struct, or NULL if we execute from main lua state */
2526 hlua = hlua_gethlua(L);
2527
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002528 /* Check if this lua stack is schedulable. */
2529 if (!hlua || !hlua->task)
2530 WILL_LJMP(luaL_error(L, "The 'write' function is only allowed in "
2531 "'frontend', 'backend' or 'task'"));
2532
2533 /* Get object */
2534 socket = MAY_LJMP(hlua_checksocket(L, 1));
2535 buf = MAY_LJMP(luaL_checklstring(L, 2, &buf_len));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002536 sent = MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002537
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002538 /* Check if we run on the same thread than the xreator thread.
2539 * We cannot access to the socket if the thread is different.
2540 */
2541 if (socket->tid != tid)
2542 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2543
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002544 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002545 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002546 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002547 lua_pushinteger(L, -1);
2548 return 1;
2549 }
Willy Tarreau5321da92022-05-06 11:57:34 +02002550
2551 csk_ctx = container_of(peer, struct hlua_csk_ctx, xref);
2552 appctx = csk_ctx->appctx;
Willy Tarreauc12b3212022-05-27 11:08:15 +02002553 sc = appctx_sc(appctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02002554 s = __sc_strm(sc);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002555
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002556 /* Check for connection close. */
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002557 if (channel_output_closed(&s->req)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002558 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002559 lua_pushinteger(L, -1);
2560 return 1;
2561 }
2562
2563 /* Update the input buffer data. */
2564 buf += sent;
2565 send_len = buf_len - sent;
2566
2567 /* All the data are sent. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002568 if (sent >= buf_len) {
2569 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002570 return 1; /* Implicitly return the length sent. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002571 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002572
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002573 /* Check if the buffer is available because HAProxy doesn't allocate
Thierry FOURNIER486d52a2015-03-09 17:51:43 +01002574 * the request buffer if its not required.
2575 */
Willy Tarreauc9fa0482018-07-10 17:43:27 +02002576 if (s->req.buf.size == 0) {
Willy Tarreau3e7be362022-05-27 10:35:27 +02002577 if (!sc_alloc_ibuf(sc, &appctx->buffer_wait))
Christopher Faulet33834b12016-12-19 09:29:06 +01002578 goto hlua_socket_write_yield_return;
Thierry FOURNIER486d52a2015-03-09 17:51:43 +01002579 }
2580
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002581 /* Check for available space. */
Willy Tarreauc9fa0482018-07-10 17:43:27 +02002582 len = b_room(&s->req.buf);
Christopher Faulet33834b12016-12-19 09:29:06 +01002583 if (len <= 0) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002584 goto hlua_socket_write_yield_return;
Christopher Faulet33834b12016-12-19 09:29:06 +01002585 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002586
2587 /* send data */
2588 if (len < send_len)
2589 send_len = len;
Thierry FOURNIER66b89192018-05-27 01:14:47 +02002590 len = ci_putblk(&s->req, buf, send_len);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002591
2592 /* "Not enough space" (-1), "Buffer too little to contain
2593 * the data" (-2) are not expected because the available length
2594 * is tested.
2595 * Other unknown error are also not expected.
2596 */
2597 if (len <= 0) {
Willy Tarreaubc18da12015-03-13 14:00:47 +01002598 if (len == -1)
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002599 s->req.flags |= CF_WAKE_WRITE;
Willy Tarreaubc18da12015-03-13 14:00:47 +01002600
sada05ed3302018-05-11 11:48:18 -07002601 MAY_LJMP(hlua_socket_close_helper(L));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002602 lua_pop(L, 1);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002603 lua_pushinteger(L, -1);
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002604 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002605 return 1;
2606 }
2607
2608 /* update buffers. */
Thierry FOURNIER101b9762018-05-27 01:27:40 +02002609 appctx_wakeup(appctx);
Willy Tarreaude70fa12015-09-26 11:25:05 +02002610
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002611 /* Update length sent. */
2612 lua_pop(L, 1);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002613 lua_pushinteger(L, sent + len);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002614
2615 /* All the data buffer is sent ? */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002616 if (sent + len >= buf_len) {
2617 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002618 return 1;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002619 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002620
2621hlua_socket_write_yield_return:
Willy Tarreau5321da92022-05-06 11:57:34 +02002622 if (!notification_new(&hlua->com, &csk_ctx->wake_on_write, hlua->task)) {
Thierry FOURNIERba42fcd2018-05-27 00:59:48 +02002623 xref_unlock(&socket->xref, peer);
2624 WILL_LJMP(luaL_error(L, "out of memory"));
2625 }
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002626 xref_unlock(&socket->xref, peer);
Willy Tarreau9635e032018-10-16 17:52:55 +02002627 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_write_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002628 return 0;
2629}
2630
2631/* This function initiate the send of data. It just check the input
2632 * parameters and push an integer in the Lua stack that contain the
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002633 * amount of data written to the buffer. This is used by the function
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002634 * "hlua_socket_write_yield" that can yield.
2635 *
2636 * The Lua function gets between 3 and 4 parameters. The first one is
2637 * the associated object. The second is a string buffer. The third is
2638 * a facultative integer that represents where is the buffer position
2639 * of the start of the data that can send. The first byte is the
2640 * position "1". The default value is "1". The fourth argument is a
2641 * facultative integer that represents where is the buffer position
2642 * of the end of the data that can send. The default is the last byte.
2643 */
2644static int hlua_socket_send(struct lua_State *L)
2645{
2646 int i;
2647 int j;
2648 const char *buf;
2649 size_t buf_len;
2650
2651 /* Check number of arguments. */
2652 if (lua_gettop(L) < 2 || lua_gettop(L) > 4)
2653 WILL_LJMP(luaL_error(L, "'send' needs between 2 and 4 arguments"));
2654
2655 /* Get the string. */
2656 buf = MAY_LJMP(luaL_checklstring(L, 2, &buf_len));
2657
2658 /* Get and check j. */
2659 if (lua_gettop(L) == 4) {
2660 j = MAY_LJMP(luaL_checkinteger(L, 4));
2661 if (j < 0)
2662 j = buf_len + j + 1;
2663 if (j > buf_len)
2664 j = buf_len + 1;
2665 lua_pop(L, 1);
2666 }
2667 else
2668 j = buf_len;
2669
2670 /* Get and check i. */
2671 if (lua_gettop(L) == 3) {
2672 i = MAY_LJMP(luaL_checkinteger(L, 3));
2673 if (i < 0)
2674 i = buf_len + i + 1;
2675 if (i > buf_len)
2676 i = buf_len + 1;
2677 lua_pop(L, 1);
2678 } else
2679 i = 1;
2680
2681 /* Check bth i and j. */
2682 if (i > j) {
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002683 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002684 return 1;
2685 }
2686 if (i == 0 && j == 0) {
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002687 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002688 return 1;
2689 }
2690 if (i == 0)
2691 i = 1;
2692 if (j == 0)
2693 j = 1;
2694
2695 /* Pop the string. */
2696 lua_pop(L, 1);
2697
2698 /* Update the buffer length. */
2699 buf += i - 1;
2700 buf_len = j - i + 1;
2701 lua_pushlstring(L, buf, buf_len);
2702
2703 /* This unsigned is used to remember the amount of sent data. */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002704 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002705
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002706 return MAY_LJMP(hlua_socket_write_yield(L, 0, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002707}
2708
Willy Tarreau22b0a682015-06-17 19:43:49 +02002709#define SOCKET_INFO_MAX_LEN sizeof("[0000:0000:0000:0000:0000:0000:0000:0000]:12345")
Christopher Faulete6465b32021-10-22 15:36:08 +02002710__LJMP static inline int hlua_socket_info(struct lua_State *L, const struct sockaddr_storage *addr)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002711{
2712 static char buffer[SOCKET_INFO_MAX_LEN];
2713 int ret;
2714 int len;
2715 char *p;
2716
2717 ret = addr_to_str(addr, buffer+1, SOCKET_INFO_MAX_LEN-1);
2718 if (ret <= 0) {
2719 lua_pushnil(L);
2720 return 1;
2721 }
2722
2723 if (ret == AF_UNIX) {
2724 lua_pushstring(L, buffer+1);
2725 return 1;
2726 }
2727 else if (ret == AF_INET6) {
2728 buffer[0] = '[';
2729 len = strlen(buffer);
2730 buffer[len] = ']';
2731 len++;
2732 buffer[len] = ':';
2733 len++;
2734 p = buffer;
2735 }
2736 else if (ret == AF_INET) {
2737 p = buffer + 1;
2738 len = strlen(p);
2739 p[len] = ':';
2740 len++;
2741 }
2742 else {
2743 lua_pushnil(L);
2744 return 1;
2745 }
2746
2747 if (port_to_str(addr, p + len, SOCKET_INFO_MAX_LEN-1 - len) <= 0) {
2748 lua_pushnil(L);
2749 return 1;
2750 }
2751
2752 lua_pushstring(L, p);
2753 return 1;
2754}
2755
2756/* Returns information about the peer of the connection. */
2757__LJMP static int hlua_socket_getpeername(struct lua_State *L)
2758{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002759 struct hlua_socket *socket;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002760 struct xref *peer;
2761 struct appctx *appctx;
Willy Tarreau3e7be362022-05-27 10:35:27 +02002762 struct stconn *sc;
Christopher Faulet16f16af2021-10-27 09:34:56 +02002763 const struct sockaddr_storage *dst;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002764 int ret;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002765
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002766 MAY_LJMP(check_args(L, 1, "getpeername"));
2767
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002768 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002769
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002770 /* Check if we run on the same thread than the xreator thread.
2771 * We cannot access to the socket if the thread is different.
2772 */
2773 if (socket->tid != tid)
2774 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2775
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002776 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002777 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002778 if (!peer) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002779 lua_pushnil(L);
2780 return 1;
2781 }
Willy Tarreau5321da92022-05-06 11:57:34 +02002782
2783 appctx = container_of(peer, struct hlua_csk_ctx, xref)->appctx;
Willy Tarreauc12b3212022-05-27 11:08:15 +02002784 sc = appctx_sc(appctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02002785 dst = sc_dst(sc_opposite(sc));
Christopher Faulet16f16af2021-10-27 09:34:56 +02002786 if (!dst) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002787 xref_unlock(&socket->xref, peer);
Willy Tarreaua71f6422016-11-16 17:00:14 +01002788 lua_pushnil(L);
2789 return 1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002790 }
2791
Christopher Faulet16f16af2021-10-27 09:34:56 +02002792 ret = MAY_LJMP(hlua_socket_info(L, dst));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002793 xref_unlock(&socket->xref, peer);
2794 return ret;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002795}
2796
2797/* Returns information about my connection side. */
2798static int hlua_socket_getsockname(struct lua_State *L)
2799{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002800 struct hlua_socket *socket;
2801 struct connection *conn;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002802 struct appctx *appctx;
2803 struct xref *peer;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002804 struct stream *s;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002805 int ret;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002806
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002807 MAY_LJMP(check_args(L, 1, "getsockname"));
2808
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002809 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002810
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002811 /* Check if we run on the same thread than the xreator thread.
2812 * We cannot access to the socket if the thread is different.
2813 */
2814 if (socket->tid != tid)
2815 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2816
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002817 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002818 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002819 if (!peer) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002820 lua_pushnil(L);
2821 return 1;
2822 }
Willy Tarreau5321da92022-05-06 11:57:34 +02002823
2824 appctx = container_of(peer, struct hlua_csk_ctx, xref)->appctx;
Willy Tarreau0698c802022-05-11 14:09:57 +02002825 s = appctx_strm(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002826
Willy Tarreaufd9417b2022-05-18 16:23:22 +02002827 conn = sc_conn(s->scb);
Willy Tarreau5a0b25d2019-07-18 18:01:14 +02002828 if (!conn || !conn_get_src(conn)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002829 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002830 lua_pushnil(L);
2831 return 1;
2832 }
2833
Willy Tarreau9da9a6f2019-07-17 14:49:44 +02002834 ret = hlua_socket_info(L, conn->src);
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002835 xref_unlock(&socket->xref, peer);
2836 return ret;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002837}
2838
2839/* This struct define the applet. */
Willy Tarreau30576452015-04-13 13:50:30 +02002840static struct applet update_applet = {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002841 .obj_type = OBJ_TYPE_APPLET,
2842 .name = "<LUA_TCP>",
2843 .fct = hlua_socket_handler,
Christopher Faulet5f35a3e2022-05-12 15:31:05 +02002844 .init = hlua_socket_init,
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002845 .release = hlua_socket_release,
2846};
2847
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002848__LJMP static int hlua_socket_connect_yield(struct lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002849{
2850 struct hlua_socket *socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002851 struct hlua *hlua;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002852 struct xref *peer;
Willy Tarreau5321da92022-05-06 11:57:34 +02002853 struct hlua_csk_ctx *csk_ctx;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002854 struct appctx *appctx;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002855 struct stream *s;
2856
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002857 /* Get hlua struct, or NULL if we execute from main lua state */
2858 hlua = hlua_gethlua(L);
2859 if (!hlua)
2860 return 0;
2861
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002862 /* Check if we run on the same thread than the xreator thread.
2863 * We cannot access to the socket if the thread is different.
2864 */
2865 if (socket->tid != tid)
2866 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2867
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002868 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002869 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002870 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002871 lua_pushnil(L);
2872 lua_pushstring(L, "Can't connect");
2873 return 2;
2874 }
Willy Tarreau5321da92022-05-06 11:57:34 +02002875
2876 csk_ctx = container_of(peer, struct hlua_csk_ctx, xref);
2877 appctx = csk_ctx->appctx;
Willy Tarreau0698c802022-05-11 14:09:57 +02002878 s = appctx_strm(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002879
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002880 /* Check if we run on the same thread than the xreator thread.
2881 * We cannot access to the socket if the thread is different.
2882 */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002883 if (socket->tid != tid) {
2884 xref_unlock(&socket->xref, peer);
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002885 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002886 }
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002887
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002888 /* Check for connection close. */
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002889 if (!hlua || channel_output_closed(&s->req)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002890 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002891 lua_pushnil(L);
2892 lua_pushstring(L, "Can't connect");
2893 return 2;
2894 }
2895
Willy Tarreau8e7c6e62022-05-18 17:58:02 +02002896 appctx = __sc_appctx(s->scf);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002897
2898 /* Check for connection established. */
Willy Tarreau5321da92022-05-06 11:57:34 +02002899 if (csk_ctx->connected) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002900 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002901 lua_pushinteger(L, 1);
2902 return 1;
2903 }
2904
Willy Tarreau5321da92022-05-06 11:57:34 +02002905 if (!notification_new(&hlua->com, &csk_ctx->wake_on_write, hlua->task)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002906 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002907 WILL_LJMP(luaL_error(L, "out of memory error"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002908 }
2909 xref_unlock(&socket->xref, peer);
Willy Tarreau9635e032018-10-16 17:52:55 +02002910 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_connect_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002911 return 0;
2912}
2913
2914/* This function fail or initite the connection. */
2915__LJMP static int hlua_socket_connect(struct lua_State *L)
2916{
2917 struct hlua_socket *socket;
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002918 int port = -1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002919 const char *ip;
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002920 struct hlua *hlua;
Willy Tarreau5321da92022-05-06 11:57:34 +02002921 struct hlua_csk_ctx *csk_ctx;
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002922 struct appctx *appctx;
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002923 int low, high;
2924 struct sockaddr_storage *addr;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002925 struct xref *peer;
Willy Tarreau3e7be362022-05-27 10:35:27 +02002926 struct stconn *sc;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002927 struct stream *s;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002928
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002929 if (lua_gettop(L) < 2)
2930 WILL_LJMP(luaL_error(L, "connect: need at least 2 arguments"));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002931
2932 /* Get args. */
2933 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002934
2935 /* Check if we run on the same thread than the xreator thread.
2936 * We cannot access to the socket if the thread is different.
2937 */
2938 if (socket->tid != tid)
2939 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2940
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002941 ip = MAY_LJMP(luaL_checkstring(L, 2));
Tim Duesterhus6edab862018-01-06 19:04:45 +01002942 if (lua_gettop(L) >= 3) {
2943 luaL_Buffer b;
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002944 port = MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002945
Tim Duesterhus6edab862018-01-06 19:04:45 +01002946 /* Force the ip to end with a colon, to support IPv6 addresses
2947 * that are not enclosed within square brackets.
2948 */
2949 if (port > 0) {
2950 luaL_buffinit(L, &b);
2951 luaL_addstring(&b, ip);
2952 luaL_addchar(&b, ':');
2953 luaL_pushresult(&b);
2954 ip = lua_tolstring(L, lua_gettop(L), NULL);
2955 }
2956 }
2957
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002958 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002959 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002960 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002961 lua_pushnil(L);
2962 return 1;
2963 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002964
2965 /* Parse ip address. */
Willy Tarreau5fc93282020-09-16 18:25:03 +02002966 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 +02002967 if (!addr) {
2968 xref_unlock(&socket->xref, peer);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002969 WILL_LJMP(luaL_error(L, "connect: cannot parse destination address '%s'", ip));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002970 }
Willy Tarreau9da9a6f2019-07-17 14:49:44 +02002971
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002972 /* Set port. */
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002973 if (low == 0) {
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02002974 if (addr->ss_family == AF_INET) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002975 if (port == -1) {
2976 xref_unlock(&socket->xref, peer);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002977 WILL_LJMP(luaL_error(L, "connect: port missing"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002978 }
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02002979 ((struct sockaddr_in *)addr)->sin_port = htons(port);
2980 } else if (addr->ss_family == AF_INET6) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002981 if (port == -1) {
2982 xref_unlock(&socket->xref, peer);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002983 WILL_LJMP(luaL_error(L, "connect: port missing"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002984 }
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02002985 ((struct sockaddr_in6 *)addr)->sin6_port = htons(port);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002986 }
2987 }
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02002988
Willy Tarreau5321da92022-05-06 11:57:34 +02002989 csk_ctx = container_of(peer, struct hlua_csk_ctx, xref);
2990 appctx = csk_ctx->appctx;
Willy Tarreauc12b3212022-05-27 11:08:15 +02002991 sc = appctx_sc(appctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02002992 s = __sc_strm(sc);
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02002993
Willy Tarreau3e7be362022-05-27 10:35:27 +02002994 if (!sockaddr_alloc(&sc_opposite(sc)->dst, addr, sizeof(*addr))) {
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02002995 xref_unlock(&socket->xref, peer);
2996 WILL_LJMP(luaL_error(L, "connect: internal error"));
2997 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002998
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002999 /* Get hlua struct, or NULL if we execute from main lua state */
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01003000 hlua = hlua_gethlua(L);
Thierry Fournier4234dbd2020-11-28 13:18:23 +01003001 if (!hlua)
3002 return 0;
Willy Tarreaubdc97a82015-08-24 15:42:28 +02003003
3004 /* inform the stream that we want to be notified whenever the
3005 * connection completes.
3006 */
Willy Tarreau90e8b452022-05-25 18:21:43 +02003007 applet_need_more_data(appctx);
Willy Tarreau4164eb92022-05-25 15:42:03 +02003008 applet_have_more_data(appctx);
Thierry FOURNIER8c8fbbe2015-09-26 17:02:35 +02003009 appctx_wakeup(appctx);
Willy Tarreaubdc97a82015-08-24 15:42:28 +02003010
Willy Tarreauf31af932020-01-14 09:59:38 +01003011 hlua->gc_count++;
Thierry FOURNIER7c39ab42015-09-27 22:53:33 +02003012
Willy Tarreau5321da92022-05-06 11:57:34 +02003013 if (!notification_new(&hlua->com, &csk_ctx->wake_on_write, hlua->task)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02003014 xref_unlock(&socket->xref, peer);
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01003015 WILL_LJMP(luaL_error(L, "out of memory"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02003016 }
3017 xref_unlock(&socket->xref, peer);
PiBa-NL706d5ee2018-05-05 23:51:42 +02003018
3019 task_wakeup(s->task, TASK_WOKEN_INIT);
3020 /* Return yield waiting for connection. */
3021
Willy Tarreau9635e032018-10-16 17:52:55 +02003022 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_connect_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003023
3024 return 0;
3025}
3026
Baptiste Assmann84bb4932015-03-02 21:40:06 +01003027#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003028__LJMP static int hlua_socket_connect_ssl(struct lua_State *L)
3029{
3030 struct hlua_socket *socket;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003031 struct xref *peer;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003032 struct stream *s;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003033
3034 MAY_LJMP(check_args(L, 3, "connect_ssl"));
3035 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003036
3037 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02003038 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003039 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003040 lua_pushnil(L);
3041 return 1;
3042 }
Willy Tarreau5321da92022-05-06 11:57:34 +02003043
Willy Tarreau0698c802022-05-11 14:09:57 +02003044 s = appctx_strm(container_of(peer, struct hlua_csk_ctx, xref)->appctx);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003045
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +01003046 s->target = &socket_ssl->obj_type;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02003047 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003048 return MAY_LJMP(hlua_socket_connect(L));
3049}
Baptiste Assmann84bb4932015-03-02 21:40:06 +01003050#endif
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003051
3052__LJMP static int hlua_socket_setoption(struct lua_State *L)
3053{
3054 return 0;
3055}
3056
3057__LJMP static int hlua_socket_settimeout(struct lua_State *L)
3058{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003059 struct hlua_socket *socket;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003060 int tmout;
Mark Lakes56cc1252018-03-27 09:48:06 +02003061 double dtmout;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003062 struct xref *peer;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003063 struct stream *s;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003064
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003065 MAY_LJMP(check_args(L, 2, "settimeout"));
3066
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003067 socket = MAY_LJMP(hlua_checksocket(L, 1));
Mark Lakes56cc1252018-03-27 09:48:06 +02003068
Cyril Bonté7ee465f2018-08-19 22:08:50 +02003069 /* convert the timeout to millis */
3070 dtmout = MAY_LJMP(luaL_checknumber(L, 2)) * 1000;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003071
Thierry Fournier17a921b2018-03-08 09:59:02 +01003072 /* Check for negative values */
Mark Lakes56cc1252018-03-27 09:48:06 +02003073 if (dtmout < 0)
Thierry Fournier17a921b2018-03-08 09:59:02 +01003074 WILL_LJMP(luaL_error(L, "settimeout: cannot set negatives values"));
3075
Mark Lakes56cc1252018-03-27 09:48:06 +02003076 if (dtmout > INT_MAX) /* overflow check */
Cyril Bonté7ee465f2018-08-19 22:08:50 +02003077 WILL_LJMP(luaL_error(L, "settimeout: cannot set values larger than %d ms", INT_MAX));
Mark Lakes56cc1252018-03-27 09:48:06 +02003078
3079 tmout = MS_TO_TICKS((int)dtmout);
Cyril Bonté7ee465f2018-08-19 22:08:50 +02003080 if (tmout == 0)
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05003081 tmout++; /* very small timeouts are adjusted to a minimum of 1ms */
Mark Lakes56cc1252018-03-27 09:48:06 +02003082
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02003083 /* Check if we run on the same thread than the xreator thread.
3084 * We cannot access to the socket if the thread is different.
3085 */
3086 if (socket->tid != tid)
3087 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
3088
Mark Lakes56cc1252018-03-27 09:48:06 +02003089 /* check for connection break. If some data were read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02003090 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003091 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003092 hlua_pusherror(L, "socket: not yet initialised, you can't set timeouts.");
3093 WILL_LJMP(lua_error(L));
3094 return 0;
3095 }
Willy Tarreau5321da92022-05-06 11:57:34 +02003096
Willy Tarreau0698c802022-05-11 14:09:57 +02003097 s = appctx_strm(container_of(peer, struct hlua_csk_ctx, xref)->appctx);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003098
Cyril Bonté7bb63452018-08-17 23:51:02 +02003099 s->sess->fe->timeout.connect = tmout;
Christopher Faulet5aaacfb2023-02-15 08:13:33 +01003100 s->scf->ioto = tmout;
3101 s->scb->ioto = tmout;
Cyril Bonté7bb63452018-08-17 23:51:02 +02003102
3103 s->task->expire = tick_add_ifset(now_ms, tmout);
3104 task_queue(s->task);
3105
Thierry FOURNIER952939d2017-09-01 14:17:32 +02003106 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003107
Thierry Fourniere9636f12018-03-08 09:54:32 +01003108 lua_pushinteger(L, 1);
Tim Duesterhus119a5f12018-01-06 19:16:25 +01003109 return 1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003110}
3111
3112__LJMP static int hlua_socket_new(lua_State *L)
3113{
3114 struct hlua_socket *socket;
Willy Tarreau5321da92022-05-06 11:57:34 +02003115 struct hlua_csk_ctx *ctx;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003116 struct appctx *appctx;
3117
3118 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003119 if (!lua_checkstack(L, 3)) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003120 hlua_pusherror(L, "socket: full stack");
3121 goto out_fail_conf;
3122 }
3123
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003124 /* Create the object: obj[0] = userdata. */
3125 lua_newtable(L);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003126 socket = MAY_LJMP(lua_newuserdata(L, sizeof(*socket)));
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003127 lua_rawseti(L, -2, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003128 memset(socket, 0, sizeof(*socket));
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02003129 socket->tid = tid;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003130
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05003131 /* Check if the various memory pools are initialized. */
Willy Tarreaubafbe012017-11-24 17:34:44 +01003132 if (!pool_head_stream || !pool_head_buffer) {
Thierry FOURNIER4a6170c2015-03-09 17:07:10 +01003133 hlua_pusherror(L, "socket: uninitialized pools.");
3134 goto out_fail_conf;
3135 }
3136
Willy Tarreau87b09662015-04-03 00:22:06 +02003137 /* Pop a class stream metatable and affect it to the userdata. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003138 lua_rawgeti(L, LUA_REGISTRYINDEX, class_socket_ref);
3139 lua_setmetatable(L, -2);
3140
Willy Tarreaud420a972015-04-06 00:39:18 +02003141 /* Create the applet context */
Christopher Faulet6095d572022-05-16 17:09:48 +02003142 appctx = appctx_new_here(&update_applet, NULL);
Willy Tarreau61cf7c82015-04-06 00:48:33 +02003143 if (!appctx) {
3144 hlua_pusherror(L, "socket: out of memory");
Christopher Fauleta9e8b392022-03-23 11:01:09 +01003145 goto out_fail_conf;
Willy Tarreau61cf7c82015-04-06 00:48:33 +02003146 }
Willy Tarreau5321da92022-05-06 11:57:34 +02003147 ctx = applet_reserve_svcctx(appctx, sizeof(*ctx));
3148 ctx->connected = 0;
Willy Tarreau5321da92022-05-06 11:57:34 +02003149 ctx->die = 0;
3150 LIST_INIT(&ctx->wake_on_write);
3151 LIST_INIT(&ctx->wake_on_read);
Willy Tarreaub2bf8332015-04-04 15:58:58 +02003152
Christopher Faulet5f35a3e2022-05-12 15:31:05 +02003153 if (appctx_init(appctx) == -1) {
3154 hlua_pusherror(L, "socket: fail to init applet.");
Christopher Faulet13a35e52021-12-20 15:34:16 +01003155 goto out_fail_appctx;
3156 }
3157
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003158 /* Initialise cross reference between stream and Lua socket object. */
Willy Tarreau5321da92022-05-06 11:57:34 +02003159 xref_create(&socket->xref, &ctx->xref);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003160 return 1;
3161
Christopher Faulet13a35e52021-12-20 15:34:16 +01003162 out_fail_appctx:
Christopher Faulet5f35a3e2022-05-12 15:31:05 +02003163 appctx_free_on_early_error(appctx);
Willy Tarreaud420a972015-04-06 00:39:18 +02003164 out_fail_conf:
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003165 WILL_LJMP(lua_error(L));
3166 return 0;
3167}
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01003168
3169/*
3170 *
3171 *
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003172 * Class Channel
3173 *
3174 *
3175 */
3176
3177/* Returns the struct hlua_channel join to the class channel in the
3178 * stack entry "ud" or throws an argument error.
3179 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01003180__LJMP static struct channel *hlua_checkchannel(lua_State *L, int ud)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003181{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003182 return MAY_LJMP(hlua_checkudata(L, ud, class_channel_ref));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003183}
3184
Willy Tarreau47860ed2015-03-10 14:07:50 +01003185/* Pushes the channel onto the top of the stack. If the stask does not have a
3186 * free slots, the function fails and returns 0;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003187 */
Willy Tarreau2a71af42015-03-10 13:51:50 +01003188static int hlua_channel_new(lua_State *L, struct channel *channel)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003189{
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003190 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003191 if (!lua_checkstack(L, 3))
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003192 return 0;
3193
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003194 lua_newtable(L);
Willy Tarreau47860ed2015-03-10 14:07:50 +01003195 lua_pushlightuserdata(L, channel);
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003196 lua_rawseti(L, -2, 0);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003197
3198 /* Pop a class sesison metatable and affect it to the userdata. */
3199 lua_rawgeti(L, LUA_REGISTRYINDEX, class_channel_ref);
3200 lua_setmetatable(L, -2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003201 return 1;
3202}
3203
Christopher Faulet9f55a502020-02-25 15:21:02 +01003204/* Helper function returning a filter attached to a channel at the position <ud>
3205 * in the stack, filling the current offset and length of the filter. If no
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05003206 * filter is attached, NULL is returned and <offset> and <len> are not
Christopher Faulet9f55a502020-02-25 15:21:02 +01003207 * initialized.
3208 */
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003209static 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 +01003210{
3211 struct filter *filter = NULL;
3212
3213 if (lua_getfield(L, ud, "__filter") == LUA_TLIGHTUSERDATA) {
3214 struct hlua_flt_ctx *flt_ctx;
3215
3216 filter = lua_touserdata (L, -1);
3217 flt_ctx = filter->ctx;
3218 if (hlua_filter_from_payload(filter)) {
3219 *offset = flt_ctx->cur_off[CHN_IDX(chn)];
3220 *len = flt_ctx->cur_len[CHN_IDX(chn)];
3221 }
3222 }
3223
3224 lua_pop(L, 1);
3225 return filter;
3226}
3227
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003228/* Copies <len> bytes of data present in the channel's buffer, starting at the
3229* offset <offset>, and put it in a LUA string variable. It is the caller
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003230* responsibility to ensure <len> and <offset> are valid. It always return the
3231* length of the built string. <len> may be 0, in this case, an empty string is
3232* created and 0 is returned.
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003233*/
3234static inline int _hlua_channel_dup(struct channel *chn, lua_State *L, size_t offset, size_t len)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003235{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003236 size_t block1, block2;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003237 luaL_Buffer b;
3238
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003239 block1 = len;
3240 if (block1 > b_contig_data(&chn->buf, b_peek_ofs(&chn->buf, offset)))
3241 block1 = b_contig_data(&chn->buf, b_peek_ofs(&chn->buf, offset));
3242 block2 = len - block1;
3243
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003244 luaL_buffinit(L, &b);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003245 luaL_addlstring(&b, b_peek(&chn->buf, offset), block1);
3246 if (block2)
3247 luaL_addlstring(&b, b_orig(&chn->buf), block2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003248 luaL_pushresult(&b);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003249 return len;
3250}
3251
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003252/* Inserts the string <str> to the channel's buffer at the offset <offset>. This
3253 * function returns -1 if data cannot be copied. Otherwise, it returns the
3254 * number of bytes copied.
3255 */
3256static int _hlua_channel_insert(struct channel *chn, lua_State *L, struct ist str, size_t offset)
3257{
3258 int ret = 0;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003259
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003260 /* Nothing to do, just return */
3261 if (unlikely(istlen(str) == 0))
3262 goto end;
3263
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003264 if (istlen(str) > c_room(chn)) {
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003265 ret = -1;
3266 goto end;
3267 }
3268 ret = b_insert_blk(&chn->buf, offset, istptr(str), istlen(str));
3269
3270 end:
3271 return ret;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003272}
3273
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003274/* Removes <len> bytes of data at the absolute position <offset>.
3275 */
3276static void _hlua_channel_delete(struct channel *chn, size_t offset, size_t len)
3277{
3278 size_t end = offset + len;
3279
3280 if (b_peek(&chn->buf, end) != b_tail(&chn->buf))
3281 b_move(&chn->buf, b_peek_ofs(&chn->buf, end),
3282 b_data(&chn->buf) - end, -len);
3283 b_sub(&chn->buf, len);
3284}
3285
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003286/* Copies input data in the channel's buffer. It is possible to set a specific
3287 * offset (0 by default) and a length (all remaining input data starting for the
3288 * offset by default). If there is not enough input data and more data can be
3289 * received, this function yields.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003290 *
3291 * From an action, All input data are considered. For a filter, the offset and
3292 * the length of input data to consider are retrieved from the filter context.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003293 */
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003294__LJMP static int hlua_channel_get_data_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003295{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003296 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003297 struct filter *filter;
3298 size_t input, output;
3299 int offset, len;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003300
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003301 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003302
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003303 output = co_data(chn);
3304 input = ci_data(chn);
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003305
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003306 filter = hlua_channel_filter(L, 1, chn, &output, &input);
3307 if (filter && !hlua_filter_from_payload(filter))
3308 WILL_LJMP(lua_error(L));
3309
3310 offset = output;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003311 if (lua_gettop(L) > 1) {
3312 offset = MAY_LJMP(luaL_checkinteger(L, 2));
3313 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02003314 offset = MAX(0, (int)input + offset);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003315 offset += output;
3316 if (offset < output || offset > input + output) {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003317 lua_pushfstring(L, "offset out of range.");
3318 WILL_LJMP(lua_error(L));
3319 }
3320 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003321 len = output + input - offset;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003322 if (lua_gettop(L) == 3) {
3323 len = MAY_LJMP(luaL_checkinteger(L, 3));
3324 if (!len)
3325 goto dup;
3326 if (len == -1)
3327 len = global.tune.bufsize;
3328 if (len < 0) {
3329 lua_pushfstring(L, "length out of range.");
3330 WILL_LJMP(lua_error(L));
3331 }
3332 }
3333
Christopher Faulet0ae2e632023-01-10 15:29:54 +01003334 /* Wait for more data if possible if no length was specified and there
3335 * is no data or not enough data was received.
3336 */
3337 if (!len || offset + len > output + input) {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003338 if (!HLUA_CANT_YIELD(hlua_gethlua(L)) && !channel_input_closed(chn) && channel_may_recv(chn)) {
3339 /* Yield waiting for more data, as requested */
3340 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_get_data_yield, TICK_ETERNITY, 0));
3341 }
Christopher Faulet0ae2e632023-01-10 15:29:54 +01003342
3343 /* Return 'nil' if there is no data and the channel can't receive more data */
3344 if (!len) {
3345 lua_pushnil(L);
3346 return -1;
3347 }
3348
3349 /* Otherwise, return all data */
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003350 len = output + input - offset;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003351 }
3352
3353 dup:
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003354 _hlua_channel_dup(chn, L, offset, len);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003355 return 1;
3356}
3357
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003358/* Copies the first line (including the trailing LF) of input data in the
3359 * channel's buffer. It is possible to set a specific offset (0 by default) and
3360 * a length (all remaining input data starting for the offset by default). If
3361 * there is not enough input data and more data can be received, the function
3362 * yields. If a length is explicitly specified, no more data are
3363 * copied. Otherwise, if no LF is found and more data can be received, this
3364 * function yields.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003365 *
3366 * From an action, All input data are considered. For a filter, the offset and
3367 * the length of input data to consider are retrieved from the filter context.
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003368 */
3369__LJMP static int hlua_channel_get_line_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003370{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003371 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003372 struct filter *filter;
3373 size_t l, input, output;
3374 int offset, len;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003375
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003376 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003377 output = co_data(chn);
3378 input = ci_data(chn);
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003379
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003380 filter = hlua_channel_filter(L, 1, chn, &output, &input);
3381 if (filter && !hlua_filter_from_payload(filter))
3382 WILL_LJMP(lua_error(L));
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003383
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003384 offset = output;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003385 if (lua_gettop(L) > 1) {
3386 offset = MAY_LJMP(luaL_checkinteger(L, 2));
3387 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02003388 offset = MAX(0, (int)input + offset);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003389 offset += output;
3390 if (offset < output || offset > input + output) {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003391 lua_pushfstring(L, "offset out of range.");
3392 WILL_LJMP(lua_error(L));
3393 }
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003394 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003395
3396 len = output + input - offset;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003397 if (lua_gettop(L) == 3) {
3398 len = MAY_LJMP(luaL_checkinteger(L, 3));
3399 if (!len)
3400 goto dup;
3401 if (len == -1)
3402 len = global.tune.bufsize;
3403 if (len < 0) {
3404 lua_pushfstring(L, "length out of range.");
3405 WILL_LJMP(lua_error(L));
3406 }
3407 }
3408
3409 for (l = 0; l < len; l++) {
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003410 if (l + offset >= output + input)
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003411 break;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003412 if (*(b_peek(&chn->buf, offset + l)) == '\n') {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003413 len = l+1;
3414 goto dup;
3415 }
3416 }
3417
Christopher Faulet0ae2e632023-01-10 15:29:54 +01003418 /* Wait for more data if possible if no line is found and no length was
3419 * specified or not enough data was received.
3420 */
3421 if (lua_gettop(L) != 3 || offset + len > output + input) {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003422 if (!HLUA_CANT_YIELD(hlua_gethlua(L)) && !channel_input_closed(chn) && channel_may_recv(chn)) {
3423 /* Yield waiting for more data */
3424 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_get_line_yield, TICK_ETERNITY, 0));
3425 }
Christopher Faulet0ae2e632023-01-10 15:29:54 +01003426
3427 /* Return 'nil' if there is no data and the channel can't receive more data */
3428 if (!len) {
3429 lua_pushnil(L);
3430 return -1;
3431 }
3432
3433 /* Otherwise, return all data */
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003434 len = output + input - offset;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003435 }
3436
3437 dup:
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003438 _hlua_channel_dup(chn, L, offset, len);
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003439 return 1;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003440}
3441
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003442/* [ DEPRECATED ]
3443 *
3444 * Duplicate all input data foud in the channel's buffer. The data are not
3445 * removed from the buffer. This function relies on _hlua_channel_dup().
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003446 *
3447 * From an action, All input data are considered. For a filter, the offset and
3448 * the length of input data to consider are retrieved from the filter context.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003449 */
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003450__LJMP static int hlua_channel_dup(lua_State *L)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003451{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003452 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003453 struct filter *filter;
3454 size_t offset, len;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003455
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003456 MAY_LJMP(check_args(L, 1, "dup"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003457 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003458 if (IS_HTX_STRM(chn_strm(chn))) {
3459 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3460 WILL_LJMP(lua_error(L));
3461 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003462
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003463 offset = co_data(chn);
3464 len = ci_data(chn);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003465
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003466 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3467 if (filter && !hlua_filter_from_payload(filter))
3468 WILL_LJMP(lua_error(L));
3469
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003470 if (!ci_data(chn) && channel_input_closed(chn)) {
3471 lua_pushnil(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003472 return 1;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003473 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003474
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003475 _hlua_channel_dup(chn, L, offset, len);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003476 return 1;
3477}
3478
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003479/* [ DEPRECATED ]
3480 *
3481 * Get all input data foud in the channel's buffer. The data are removed from
3482 * the buffer after the copy. This function relies on _hlua_channel_dup() and
3483 * _hlua_channel_delete().
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003484 *
3485 * From an action, All input data are considered. For a filter, the offset and
3486 * the length of input data to consider are retrieved from the filter context.
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003487 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003488__LJMP static int hlua_channel_get(lua_State *L)
3489{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003490 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003491 struct filter *filter;
3492 size_t offset, len;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003493 int ret;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003494
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003495 MAY_LJMP(check_args(L, 1, "get"));
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003496 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3497 if (IS_HTX_STRM(chn_strm(chn))) {
3498 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3499 WILL_LJMP(lua_error(L));
3500 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003501
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003502 offset = co_data(chn);
3503 len = ci_data(chn);
3504
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003505 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3506 if (filter && !hlua_filter_from_payload(filter))
3507 WILL_LJMP(lua_error(L));
3508
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003509 if (!ci_data(chn) && channel_input_closed(chn)) {
3510 lua_pushnil(L);
3511 return 1;
3512 }
3513
3514 ret = _hlua_channel_dup(chn, L, offset, len);
3515 _hlua_channel_delete(chn, offset, ret);
3516 return 1;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003517}
3518
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003519/* This functions consumes and returns one line. If the channel is closed,
3520 * and the last data does not contains a final '\n', the data are returned
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003521 * without the final '\n'. When no more data are available, it returns nil
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003522 * value.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003523 *
3524 * From an action, All input data are considered. For a filter, the offset and
3525 * the length of input data to consider are retrieved from the filter context.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003526 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003527__LJMP static int hlua_channel_getline_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003528{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003529 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003530 struct filter *filter;
3531 size_t l, offset, len;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003532 int ret;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003533
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003534 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003535
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003536 offset = co_data(chn);
3537 len = ci_data(chn);
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003538
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003539 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3540 if (filter && !hlua_filter_from_payload(filter))
3541 WILL_LJMP(lua_error(L));
3542
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003543 if (!ci_data(chn) && channel_input_closed(chn)) {
3544 lua_pushnil(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003545 return 1;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003546 }
3547
3548 for (l = 0; l < len; l++) {
3549 if (*(b_peek(&chn->buf, offset+l)) == '\n') {
3550 len = l+1;
3551 goto dup;
3552 }
3553 }
3554
3555 if (!HLUA_CANT_YIELD(hlua_gethlua(L)) && !channel_input_closed(chn) && channel_may_recv(chn)) {
3556 /* Yield waiting for more data */
3557 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_getline_yield, TICK_ETERNITY, 0));
3558 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003559
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003560 dup:
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003561 ret = _hlua_channel_dup(chn, L, offset, len);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003562 _hlua_channel_delete(chn, offset, ret);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003563 return 1;
3564}
3565
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003566/* [ DEPRECATED ]
3567 *
3568 * Check arguments for the function "hlua_channel_getline_yield".
3569 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003570__LJMP static int hlua_channel_getline(lua_State *L)
3571{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003572 struct channel *chn;
3573
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003574 MAY_LJMP(check_args(L, 1, "getline"));
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003575 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3576 if (IS_HTX_STRM(chn_strm(chn))) {
3577 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3578 WILL_LJMP(lua_error(L));
3579 }
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003580 return MAY_LJMP(hlua_channel_getline_yield(L, 0, 0));
3581}
3582
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003583/* Retrieves a given amount of input data at the given offset. By default all
3584 * available input data are returned. The offset may be negactive to start from
3585 * the end of input data. The length may be -1 to set it to the maximum buffer
3586 * size.
3587 */
3588__LJMP static int hlua_channel_get_data(lua_State *L)
3589{
3590 struct channel *chn;
3591
3592 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
3593 WILL_LJMP(luaL_error(L, "'data' expects at most 2 arguments"));
3594 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3595 if (IS_HTX_STRM(chn_strm(chn))) {
3596 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3597 WILL_LJMP(lua_error(L));
3598 }
3599 return MAY_LJMP(hlua_channel_get_data_yield(L, 0, 0));
3600}
3601
3602/* Retrieves a given amount of input data at the given offset. By default all
3603 * available input data are returned. The offset may be negactive to start from
3604 * the end of input data. The length may be -1 to set it to the maximum buffer
3605 * size.
3606 */
3607__LJMP static int hlua_channel_get_line(lua_State *L)
3608{
3609 struct channel *chn;
3610
3611 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
3612 WILL_LJMP(luaL_error(L, "'line' expects at most 2 arguments"));
3613 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3614 if (IS_HTX_STRM(chn_strm(chn))) {
3615 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3616 WILL_LJMP(lua_error(L));
3617 }
3618 return MAY_LJMP(hlua_channel_get_line_yield(L, 0, 0));
3619}
3620
3621/* Appends a string into the input side of channel. It returns the length of the
3622 * written string, or -1 if the channel is closed or if the buffer size is too
3623 * little for the data. 0 may be returned if nothing is copied. This function
3624 * does not yield.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003625 *
3626 * For a filter, the context is updated on success.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003627 */
Christopher Faulet23976d92021-08-06 09:59:49 +02003628__LJMP static int hlua_channel_append(lua_State *L)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003629{
Christopher Faulet23976d92021-08-06 09:59:49 +02003630 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003631 struct filter *filter;
Christopher Faulet23976d92021-08-06 09:59:49 +02003632 const char *str;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003633 size_t sz, offset, len;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003634 int ret;
Christopher Faulet23976d92021-08-06 09:59:49 +02003635
3636 MAY_LJMP(check_args(L, 2, "append"));
3637 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003638 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
Christopher Faulet1bb6afa2021-03-08 17:57:53 +01003639 if (IS_HTX_STRM(chn_strm(chn))) {
Thierry Fournier77016da2020-08-15 14:35:51 +02003640 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
Christopher Faulet3f829a42018-12-13 21:56:45 +01003641 WILL_LJMP(lua_error(L));
Thierry Fournier77016da2020-08-15 14:35:51 +02003642 }
Christopher Faulet3f829a42018-12-13 21:56:45 +01003643
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003644 offset = co_data(chn);
3645 len = ci_data(chn);
3646
3647 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3648 if (filter && !hlua_filter_from_payload(filter))
3649 WILL_LJMP(lua_error(L));
3650
3651 ret = _hlua_channel_insert(chn, L, ist2(str, sz), offset);
3652 if (ret > 0 && filter) {
3653 struct hlua_flt_ctx *flt_ctx = filter->ctx;
3654
3655 flt_update_offsets(filter, chn, ret);
3656 flt_ctx->cur_len[CHN_IDX(chn)] += ret;
3657 }
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003658 lua_pushinteger(L, ret);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003659 return 1;
3660}
3661
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003662/* Prepends a string into the input side of channel. It returns the length of the
3663 * written string, or -1 if the channel is closed or if the buffer size is too
3664 * little for the data. 0 may be returned if nothing is copied. This function
3665 * does not yield.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003666 *
3667 * For a filter, the context is updated on success.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003668 */
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003669__LJMP static int hlua_channel_prepend(lua_State *L)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003670{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003671 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003672 struct filter *filter;
Christopher Faulet23976d92021-08-06 09:59:49 +02003673 const char *str;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003674 size_t sz, offset, len;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003675 int ret;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003676
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003677 MAY_LJMP(check_args(L, 2, "prepend"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003678 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003679 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
3680 if (IS_HTX_STRM(chn_strm(chn))) {
3681 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3682 WILL_LJMP(lua_error(L));
3683 }
3684
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003685 offset = co_data(chn);
3686 len = ci_data(chn);
3687
3688 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3689 if (filter && !hlua_filter_from_payload(filter))
3690 WILL_LJMP(lua_error(L));
3691
3692 ret = _hlua_channel_insert(chn, L, ist2(str, sz), offset);
3693 if (ret > 0 && filter) {
3694 struct hlua_flt_ctx *flt_ctx = filter->ctx;
3695
3696 flt_update_offsets(filter, chn, ret);
3697 flt_ctx->cur_len[CHN_IDX(chn)] += ret;
3698 }
3699
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003700 lua_pushinteger(L, ret);
3701 return 1;
3702}
3703
3704/* Inserts a given amount of input data at the given offset by a string
Aurelien DARRAGONafb7daf2022-10-04 12:16:05 +02003705 * content. By default the string is appended in front of input data. It
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003706 * returns the length of the written string, or -1 if the channel is closed or
3707 * if the buffer size is too little for the data.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003708 *
3709 * For a filter, the context is updated on success.
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003710 */
3711__LJMP static int hlua_channel_insert_data(lua_State *L)
3712{
3713 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003714 struct filter *filter;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003715 const char *str;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003716 size_t sz, input, output;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003717 int ret, offset;
3718
3719 if (lua_gettop(L) < 2 || lua_gettop(L) > 3)
3720 WILL_LJMP(luaL_error(L, "'insert' expects at least 1 argument and at most 2 arguments"));
3721 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3722 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003723
3724 output = co_data(chn);
3725 input = ci_data(chn);
3726
3727 filter = hlua_channel_filter(L, 1, chn, &output, &input);
3728 if (filter && !hlua_filter_from_payload(filter))
3729 WILL_LJMP(lua_error(L));
3730
Aurelien DARRAGONafb7daf2022-10-04 12:16:05 +02003731 offset = output;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003732 if (lua_gettop(L) > 2) {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003733 offset = MAY_LJMP(luaL_checkinteger(L, 3));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003734 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02003735 offset = MAX(0, (int)input + offset);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003736 offset += output;
Aurelien DARRAGONafb7daf2022-10-04 12:16:05 +02003737 if (offset > output + input) {
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003738 lua_pushfstring(L, "offset out of range.");
3739 WILL_LJMP(lua_error(L));
3740 }
3741 }
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003742 if (IS_HTX_STRM(chn_strm(chn))) {
3743 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3744 WILL_LJMP(lua_error(L));
3745 }
3746
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003747 ret = _hlua_channel_insert(chn, L, ist2(str, sz), offset);
3748 if (ret > 0 && filter) {
3749 struct hlua_flt_ctx *flt_ctx = filter->ctx;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003750
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003751 flt_update_offsets(filter, chn, ret);
3752 flt_ctx->cur_len[CHN_IDX(chn)] += ret;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003753 }
3754
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003755 lua_pushinteger(L, ret);
3756 return 1;
3757}
3758/* Replaces a given amount of input data at the given offset by a string
3759 * content. By default all remaining data are removed (offset = 0 and len =
3760 * -1). It returns the length of the written string, or -1 if the channel is
3761 * closed or if the buffer size is too little for the data.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003762 *
3763 * For a filter, the context is updated on success.
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003764 */
3765__LJMP static int hlua_channel_set_data(lua_State *L)
3766{
3767 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003768 struct filter *filter;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003769 const char *str;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003770 size_t sz, input, output;
3771 int ret, offset, len;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003772
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003773 if (lua_gettop(L) < 2 || lua_gettop(L) > 4)
3774 WILL_LJMP(luaL_error(L, "'set' expects at least 1 argument and at most 3 arguments"));
3775 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3776 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003777
Christopher Faulet1bb6afa2021-03-08 17:57:53 +01003778 if (IS_HTX_STRM(chn_strm(chn))) {
Thierry Fournier77016da2020-08-15 14:35:51 +02003779 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
Christopher Faulet3f829a42018-12-13 21:56:45 +01003780 WILL_LJMP(lua_error(L));
Thierry Fournier77016da2020-08-15 14:35:51 +02003781 }
Christopher Faulet3f829a42018-12-13 21:56:45 +01003782
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003783 output = co_data(chn);
3784 input = ci_data(chn);
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003785
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003786 filter = hlua_channel_filter(L, 1, chn, &output, &input);
3787 if (filter && !hlua_filter_from_payload(filter))
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003788 WILL_LJMP(lua_error(L));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003789
3790 offset = output;
3791 if (lua_gettop(L) > 2) {
3792 offset = MAY_LJMP(luaL_checkinteger(L, 3));
3793 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02003794 offset = MAX(0, (int)input + offset);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003795 offset += output;
3796 if (offset < output || offset > input + output) {
3797 lua_pushfstring(L, "offset out of range.");
3798 WILL_LJMP(lua_error(L));
3799 }
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003800 }
3801
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003802 len = output + input - offset;
3803 if (lua_gettop(L) == 4) {
3804 len = MAY_LJMP(luaL_checkinteger(L, 4));
3805 if (!len)
3806 goto set;
3807 if (len == -1)
3808 len = output + input - offset;
3809 if (len < 0 || offset + len > output + input) {
3810 lua_pushfstring(L, "length out of range.");
3811 WILL_LJMP(lua_error(L));
3812 }
3813 }
3814
3815 set:
Christopher Faulet23976d92021-08-06 09:59:49 +02003816 /* Be sure we can copied the string once input data will be removed. */
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003817 if (sz > c_room(chn) + len)
Christopher Faulet23976d92021-08-06 09:59:49 +02003818 lua_pushinteger(L, -1);
3819 else {
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003820 _hlua_channel_delete(chn, offset, len);
3821 ret = _hlua_channel_insert(chn, L, ist2(str, sz), offset);
3822 if (filter) {
3823 struct hlua_flt_ctx *flt_ctx = filter->ctx;
3824
3825 len -= (ret > 0 ? ret : 0);
3826 flt_update_offsets(filter, chn, -len);
3827 flt_ctx->cur_len[CHN_IDX(chn)] -= len;
3828 }
3829
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003830 lua_pushinteger(L, ret);
Christopher Faulet23976d92021-08-06 09:59:49 +02003831 }
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003832 return 1;
3833}
3834
3835/* Removes a given amount of input data at the given offset. By default all
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003836 * input data are removed (offset = 0 and len = -1). It returns the amount of
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003837 * the removed data.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003838 *
3839 * For a filter, the context is updated on success.
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003840 */
3841__LJMP static int hlua_channel_del_data(lua_State *L)
3842{
3843 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003844 struct filter *filter;
3845 size_t input, output;
3846 int offset, len;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003847
3848 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
3849 WILL_LJMP(luaL_error(L, "'remove' expects at most 2 arguments"));
3850 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003851
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003852 if (IS_HTX_STRM(chn_strm(chn))) {
3853 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3854 WILL_LJMP(lua_error(L));
3855 }
3856
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003857 output = co_data(chn);
3858 input = ci_data(chn);
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003859
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003860 filter = hlua_channel_filter(L, 1, chn, &output, &input);
3861 if (filter && !hlua_filter_from_payload(filter))
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003862 WILL_LJMP(lua_error(L));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003863
3864 offset = output;
Boyang Lie0c54352022-05-10 17:47:23 +00003865 if (lua_gettop(L) > 1) {
3866 offset = MAY_LJMP(luaL_checkinteger(L, 2));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003867 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02003868 offset = MAX(0, (int)input + offset);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003869 offset += output;
3870 if (offset < output || offset > input + output) {
3871 lua_pushfstring(L, "offset out of range.");
3872 WILL_LJMP(lua_error(L));
3873 }
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003874 }
3875
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003876 len = output + input - offset;
Boyang Lie0c54352022-05-10 17:47:23 +00003877 if (lua_gettop(L) == 3) {
3878 len = MAY_LJMP(luaL_checkinteger(L, 3));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003879 if (!len)
3880 goto end;
3881 if (len == -1)
3882 len = output + input - offset;
3883 if (len < 0 || offset + len > output + input) {
3884 lua_pushfstring(L, "length out of range.");
3885 WILL_LJMP(lua_error(L));
3886 }
3887 }
3888
3889 _hlua_channel_delete(chn, offset, len);
3890 if (filter) {
3891 struct hlua_flt_ctx *flt_ctx = filter->ctx;
3892
3893 flt_update_offsets(filter, chn, -len);
3894 flt_ctx->cur_len[CHN_IDX(chn)] -= len;
3895 }
3896
3897 end:
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003898 lua_pushinteger(L, len);
Christopher Faulet23976d92021-08-06 09:59:49 +02003899 return 1;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003900}
3901
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003902/* Append data in the output side of the buffer. This data is immediately
3903 * sent. The function returns the amount of data written. If the buffer
3904 * cannot contain the data, the function yields. The function returns -1
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003905 * if the channel is closed.
3906 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003907__LJMP static int hlua_channel_send_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003908{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003909 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003910 struct filter *filter;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003911 const char *str;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003912 size_t offset, len, sz;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003913 int l, ret;
Thierry Fournier4234dbd2020-11-28 13:18:23 +01003914 struct hlua *hlua;
3915
3916 /* Get hlua struct, or NULL if we execute from main lua state */
3917 hlua = hlua_gethlua(L);
3918 if (!hlua) {
3919 lua_pushnil(L);
3920 return 1;
3921 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003922
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003923 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3924 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
3925 l = MAY_LJMP(luaL_checkinteger(L, 3));
Christopher Faulet3f829a42018-12-13 21:56:45 +01003926
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003927 offset = co_data(chn);
3928 len = ci_data(chn);
3929
3930 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3931 if (filter && !hlua_filter_from_payload(filter))
3932 WILL_LJMP(lua_error(L));
3933
3934
Willy Tarreau47860ed2015-03-10 14:07:50 +01003935 if (unlikely(channel_output_closed(chn))) {
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003936 lua_pushinteger(L, -1);
3937 return 1;
3938 }
3939
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003940 len = c_room(chn);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003941 if (len > sz -l) {
3942 if (filter) {
3943 lua_pushinteger(L, -1);
3944 return 1;
3945 }
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003946 len = sz - l;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003947 }
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01003948
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003949 ret = _hlua_channel_insert(chn, L, ist2(str, len), offset);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003950 if (ret == -1) {
3951 lua_pop(L, 1);
3952 lua_pushinteger(L, -1);
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01003953 return 1;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003954 }
3955 if (ret) {
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003956 if (filter) {
3957 struct hlua_flt_ctx *flt_ctx = filter->ctx;
3958
3959
3960 flt_update_offsets(filter, chn, ret);
3961 FLT_OFF(filter, chn) += ret;
3962 flt_ctx->cur_off[CHN_IDX(chn)] += ret;
3963 }
3964 else
3965 c_adv(chn, ret);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003966
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003967 l += ret;
3968 lua_pop(L, 1);
3969 lua_pushinteger(L, l);
3970 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003971
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003972 if (l < sz) {
3973 /* Yield only if the channel's output is not empty.
3974 * Otherwise it means we cannot add more data. */
3975 if (co_data(chn) == 0 || HLUA_CANT_YIELD(hlua_gethlua(L)))
Christopher Faulet2e60aa42021-08-05 11:58:37 +02003976 return 1;
3977
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003978 /* If we are waiting for space in the response buffer, we
3979 * must set the flag WAKERESWR. This flag required the task
3980 * wake up if any activity is detected on the response buffer.
3981 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01003982 if (chn->flags & CF_ISRESP)
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003983 HLUA_SET_WAKERESWR(hlua);
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01003984 else
3985 HLUA_SET_WAKEREQWR(hlua);
Willy Tarreau9635e032018-10-16 17:52:55 +02003986 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003987 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003988
3989 return 1;
3990}
3991
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05003992/* Just a wrapper of "_hlua_channel_send". This wrapper permits
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003993 * yield the LUA process, and resume it without checking the
3994 * input arguments.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003995 *
3996 * This function cannot be called from a filter.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003997 */
3998__LJMP static int hlua_channel_send(lua_State *L)
3999{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02004000 struct channel *chn;
4001
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004002 MAY_LJMP(check_args(L, 2, "send"));
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02004003 chn = MAY_LJMP(hlua_checkchannel(L, 1));
4004 if (IS_HTX_STRM(chn_strm(chn))) {
4005 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
4006 WILL_LJMP(lua_error(L));
4007 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004008 lua_pushinteger(L, 0);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01004009 return MAY_LJMP(hlua_channel_send_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004010}
4011
4012/* This function forward and amount of butes. The data pass from
4013 * the input side of the buffer to the output side, and can be
4014 * forwarded. This function never fails.
4015 *
4016 * The Lua function takes an amount of bytes to be forwarded in
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05004017 * input. It returns the number of bytes forwarded.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004018 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01004019__LJMP static int hlua_channel_forward_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004020{
Willy Tarreau47860ed2015-03-10 14:07:50 +01004021 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004022 struct filter *filter;
4023 size_t offset, len, fwd;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02004024 int l, max;
Thierry Fournier4234dbd2020-11-28 13:18:23 +01004025 struct hlua *hlua;
4026
4027 /* Get hlua struct, or NULL if we execute from main lua state */
4028 hlua = hlua_gethlua(L);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02004029 if (!hlua) {
4030 lua_pushnil(L);
Thierry Fournier4234dbd2020-11-28 13:18:23 +01004031 return 1;
Thierry Fournier77016da2020-08-15 14:35:51 +02004032 }
Christopher Faulet3f829a42018-12-13 21:56:45 +01004033
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02004034 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004035 fwd = MAY_LJMP(luaL_checkinteger(L, 2));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004036 l = MAY_LJMP(luaL_checkinteger(L, -1));
4037
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004038 offset = co_data(chn);
4039 len = ci_data(chn);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02004040
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004041 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
4042 if (filter && !hlua_filter_from_payload(filter))
4043 WILL_LJMP(lua_error(L));
4044
4045 max = fwd - l;
4046 if (max > len)
4047 max = len;
4048
4049 if (filter) {
4050 struct hlua_flt_ctx *flt_ctx = filter->ctx;
4051
4052 FLT_OFF(filter, chn) += max;
4053 flt_ctx->cur_off[CHN_IDX(chn)] += max;
4054 flt_ctx->cur_len[CHN_IDX(chn)] -= max;
4055 }
4056 else
4057 channel_forward(chn, max);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004058
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02004059 l += max;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004060 lua_pop(L, 1);
4061 lua_pushinteger(L, l);
4062
4063 /* Check if it miss bytes to forward. */
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004064 if (l < fwd) {
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004065 /* The the input channel or the output channel are closed, we
4066 * must return the amount of data forwarded.
4067 */
Christopher Faulet2e60aa42021-08-05 11:58:37 +02004068 if (channel_input_closed(chn) || channel_output_closed(chn) || HLUA_CANT_YIELD(hlua_gethlua(L)))
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004069 return 1;
4070
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01004071 /* If we are waiting for space data in the response buffer, we
4072 * must set the flag WAKERESWR. This flag required the task
4073 * wake up if any activity is detected on the response buffer.
4074 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01004075 if (chn->flags & CF_ISRESP)
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01004076 HLUA_SET_WAKERESWR(hlua);
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01004077 else
4078 HLUA_SET_WAKEREQWR(hlua);
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01004079
Ilya Shipitsin4a689da2022-10-29 09:34:32 +05004080 /* Otherwise, we can yield waiting for new data in the input side. */
Willy Tarreau9635e032018-10-16 17:52:55 +02004081 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_forward_yield, TICK_ETERNITY, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004082 }
4083
4084 return 1;
4085}
4086
4087/* Just check the input and prepare the stack for the previous
4088 * function "hlua_channel_forward_yield"
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004089 *
4090 * This function cannot be called from a filter.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004091 */
4092__LJMP static int hlua_channel_forward(lua_State *L)
4093{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02004094 struct channel *chn;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004095
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02004096 MAY_LJMP(check_args(L, 2, "forward"));
4097 chn = MAY_LJMP(hlua_checkchannel(L, 1));
4098 if (IS_HTX_STRM(chn_strm(chn))) {
4099 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
4100 WILL_LJMP(lua_error(L));
4101 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004102 lua_pushinteger(L, 0);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01004103 return MAY_LJMP(hlua_channel_forward_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004104}
4105
4106/* Just returns the number of bytes available in the input
4107 * side of the buffer. This function never fails.
4108 */
4109__LJMP static int hlua_channel_get_in_len(lua_State *L)
4110{
Willy Tarreau47860ed2015-03-10 14:07:50 +01004111 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004112 struct filter *filter;
4113 size_t output, input;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004114
Christopher Faulet6a79fc12021-08-06 16:02:36 +02004115 MAY_LJMP(check_args(L, 1, "input"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004116 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004117
4118 output = co_data(chn);
4119 input = ci_data(chn);
4120 filter = hlua_channel_filter(L, 1, chn, &output, &input);
4121 if (filter || !IS_HTX_STRM(chn_strm(chn)))
4122 lua_pushinteger(L, input);
4123 else {
Christopher Fauleta3ceac12018-12-14 13:39:09 +01004124 struct htx *htx = htxbuf(&chn->buf);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004125
Christopher Fauleta3ceac12018-12-14 13:39:09 +01004126 lua_pushinteger(L, htx->data - co_data(chn));
4127 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004128 return 1;
4129}
4130
Thierry FOURNIER / OZON.IO65192f32016-11-07 15:28:40 +01004131/* Returns true if the channel is full. */
4132__LJMP static int hlua_channel_is_full(lua_State *L)
4133{
4134 struct channel *chn;
Thierry FOURNIER / OZON.IO65192f32016-11-07 15:28:40 +01004135
4136 MAY_LJMP(check_args(L, 1, "is_full"));
4137 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Faulet0ec740e2020-02-26 11:59:19 +01004138 /* ignore the reserve, we are not on a producer side (ie in an
4139 * applet).
4140 */
4141 lua_pushboolean(L, channel_full(chn, 0));
Thierry FOURNIER / OZON.IO65192f32016-11-07 15:28:40 +01004142 return 1;
4143}
4144
Christopher Faulet6a79fc12021-08-06 16:02:36 +02004145/* Returns true if the channel may still receive data. */
4146__LJMP static int hlua_channel_may_recv(lua_State *L)
4147{
4148 struct channel *chn;
4149
4150 MAY_LJMP(check_args(L, 1, "may_recv"));
4151 chn = MAY_LJMP(hlua_checkchannel(L, 1));
4152 lua_pushboolean(L, (!channel_input_closed(chn) && channel_may_recv(chn)));
4153 return 1;
4154}
4155
Christopher Faulet2ac9ba22020-02-25 10:15:50 +01004156/* Returns true if the channel is the response channel. */
4157__LJMP static int hlua_channel_is_resp(lua_State *L)
4158{
4159 struct channel *chn;
4160
4161 MAY_LJMP(check_args(L, 1, "is_resp"));
4162 chn = MAY_LJMP(hlua_checkchannel(L, 1));
4163
4164 lua_pushboolean(L, !!(chn->flags & CF_ISRESP));
4165 return 1;
4166}
4167
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004168/* Just returns the number of bytes available in the output
4169 * side of the buffer. This function never fails.
4170 */
4171__LJMP static int hlua_channel_get_out_len(lua_State *L)
4172{
Willy Tarreau47860ed2015-03-10 14:07:50 +01004173 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004174 size_t output, input;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004175
Christopher Faulet6a79fc12021-08-06 16:02:36 +02004176 MAY_LJMP(check_args(L, 1, "output"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004177 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004178
4179 output = co_data(chn);
4180 input = ci_data(chn);
4181 hlua_channel_filter(L, 1, chn, &output, &input);
4182
4183 lua_pushinteger(L, output);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004184 return 1;
4185}
4186
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004187/*
4188 *
4189 *
4190 * Class Fetches
4191 *
4192 *
4193 */
4194
4195/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02004196 * a class stream, otherwise it throws an error.
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004197 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004198__LJMP static struct hlua_smp *hlua_checkfetches(lua_State *L, int ud)
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004199{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004200 return MAY_LJMP(hlua_checkudata(L, ud, class_fetches_ref));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004201}
4202
4203/* This function creates and push in the stack a fetch object according
4204 * with a current TXN.
4205 */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004206static int hlua_fetches_new(lua_State *L, struct hlua_txn *txn, unsigned int flags)
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004207{
Willy Tarreau7073c472015-04-06 11:15:40 +02004208 struct hlua_smp *hsmp;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004209
4210 /* Check stack size. */
4211 if (!lua_checkstack(L, 3))
4212 return 0;
4213
4214 /* Create the object: obj[0] = userdata.
4215 * Note that the base of the Fetches object is the
4216 * transaction object.
4217 */
4218 lua_newtable(L);
Willy Tarreau7073c472015-04-06 11:15:40 +02004219 hsmp = lua_newuserdata(L, sizeof(*hsmp));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004220 lua_rawseti(L, -2, 0);
4221
Willy Tarreau7073c472015-04-06 11:15:40 +02004222 hsmp->s = txn->s;
4223 hsmp->p = txn->p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01004224 hsmp->dir = txn->dir;
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004225 hsmp->flags = flags;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004226
4227 /* Pop a class sesison metatable and affect it to the userdata. */
4228 lua_rawgeti(L, LUA_REGISTRYINDEX, class_fetches_ref);
4229 lua_setmetatable(L, -2);
4230
4231 return 1;
4232}
4233
4234/* This function is an LUA binding. It is called with each sample-fetch.
4235 * It uses closure argument to store the associated sample-fetch. It
4236 * returns only one argument or throws an error. An error is thrown
4237 * only if an error is encountered during the argument parsing. If
4238 * the "sample-fetch" function fails, nil is returned.
4239 */
4240__LJMP static int hlua_run_sample_fetch(lua_State *L)
4241{
Willy Tarreaub2ccb562015-04-06 11:11:15 +02004242 struct hlua_smp *hsmp;
Willy Tarreau2ec22742015-03-10 14:27:20 +01004243 struct sample_fetch *f;
Frédéric Lécaillef874a832018-06-15 13:56:04 +02004244 struct arg args[ARGM_NBARGS + 1] = {{0}};
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004245 int i;
4246 struct sample smp;
4247
4248 /* Get closure arguments. */
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004249 f = lua_touserdata(L, lua_upvalueindex(1));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004250
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004251 /* Get traditional arguments. */
Willy Tarreaub2ccb562015-04-06 11:11:15 +02004252 hsmp = MAY_LJMP(hlua_checkfetches(L, 1));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004253
Thierry FOURNIERca988662015-12-20 18:43:03 +01004254 /* Check execution authorization. */
4255 if (f->use & SMP_USE_HTTP_ANY &&
4256 !(hsmp->flags & HLUA_F_MAY_USE_HTTP)) {
4257 lua_pushfstring(L, "the sample-fetch '%s' needs an HTTP parser which "
4258 "is not available in Lua services", f->kw);
4259 WILL_LJMP(lua_error(L));
4260 }
4261
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004262 /* Get extra arguments. */
4263 for (i = 0; i < lua_gettop(L) - 1; i++) {
4264 if (i >= ARGM_NBARGS)
4265 break;
4266 hlua_lua2arg(L, i + 2, &args[i]);
4267 }
4268 args[i].type = ARGT_STOP;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004269 args[i].data.str.area = NULL;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004270
4271 /* Check arguments. */
Willy Tarreaub2ccb562015-04-06 11:11:15 +02004272 MAY_LJMP(hlua_lua2arg_check(L, 2, args, f->arg_mask, hsmp->p));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004273
4274 /* Run the special args checker. */
Willy Tarreau2ec22742015-03-10 14:27:20 +01004275 if (f->val_args && !f->val_args(args, NULL)) {
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004276 lua_pushfstring(L, "error in arguments");
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004277 goto error;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004278 }
4279
4280 /* Initialise the sample. */
4281 memset(&smp, 0, sizeof(smp));
4282
4283 /* Run the sample fetch process. */
Willy Tarreau1777ea62016-03-10 16:15:46 +01004284 smp_set_owner(&smp, hsmp->p, hsmp->s->sess, hsmp->s, hsmp->dir & SMP_OPT_DIR);
Thierry FOURNIER0786d052015-05-11 15:42:45 +02004285 if (!f->process(args, &smp, f->kw, f->private)) {
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004286 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004287 lua_pushstring(L, "");
4288 else
4289 lua_pushnil(L);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004290 goto end;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004291 }
4292
4293 /* Convert the returned sample in lua value. */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004294 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004295 hlua_smp2lua_str(L, &smp);
4296 else
4297 hlua_smp2lua(L, &smp);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004298
4299 end:
Willy Tarreauee0d7272021-07-16 10:26:56 +02004300 free_args(args);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004301 return 1;
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004302
4303 error:
Willy Tarreauee0d7272021-07-16 10:26:56 +02004304 free_args(args);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004305 WILL_LJMP(lua_error(L));
4306 return 0; /* Never reached */
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004307}
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004308
4309/*
4310 *
4311 *
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004312 * Class Converters
4313 *
4314 *
4315 */
4316
4317/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02004318 * a class stream, otherwise it throws an error.
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004319 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004320__LJMP static struct hlua_smp *hlua_checkconverters(lua_State *L, int ud)
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004321{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004322 return MAY_LJMP(hlua_checkudata(L, ud, class_converters_ref));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004323}
4324
4325/* This function creates and push in the stack a Converters object
4326 * according with a current TXN.
4327 */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004328static int hlua_converters_new(lua_State *L, struct hlua_txn *txn, unsigned int flags)
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004329{
Willy Tarreau7073c472015-04-06 11:15:40 +02004330 struct hlua_smp *hsmp;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004331
4332 /* Check stack size. */
4333 if (!lua_checkstack(L, 3))
4334 return 0;
4335
4336 /* Create the object: obj[0] = userdata.
4337 * Note that the base of the Converters object is the
4338 * same than the TXN object.
4339 */
4340 lua_newtable(L);
Willy Tarreau7073c472015-04-06 11:15:40 +02004341 hsmp = lua_newuserdata(L, sizeof(*hsmp));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004342 lua_rawseti(L, -2, 0);
4343
Willy Tarreau7073c472015-04-06 11:15:40 +02004344 hsmp->s = txn->s;
4345 hsmp->p = txn->p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01004346 hsmp->dir = txn->dir;
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004347 hsmp->flags = flags;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004348
Willy Tarreau87b09662015-04-03 00:22:06 +02004349 /* Pop a class stream metatable and affect it to the table. */
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004350 lua_rawgeti(L, LUA_REGISTRYINDEX, class_converters_ref);
4351 lua_setmetatable(L, -2);
4352
4353 return 1;
4354}
4355
4356/* This function is an LUA binding. It is called with each converter.
4357 * It uses closure argument to store the associated converter. It
4358 * returns only one argument or throws an error. An error is thrown
4359 * only if an error is encountered during the argument parsing. If
4360 * the converter function function fails, nil is returned.
4361 */
4362__LJMP static int hlua_run_sample_conv(lua_State *L)
4363{
Willy Tarreauda5f1082015-04-06 11:17:13 +02004364 struct hlua_smp *hsmp;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004365 struct sample_conv *conv;
Frédéric Lécaillef874a832018-06-15 13:56:04 +02004366 struct arg args[ARGM_NBARGS + 1] = {{0}};
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004367 int i;
4368 struct sample smp;
4369
4370 /* Get closure arguments. */
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004371 conv = lua_touserdata(L, lua_upvalueindex(1));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004372
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004373 /* Get traditional arguments. */
Willy Tarreauda5f1082015-04-06 11:17:13 +02004374 hsmp = MAY_LJMP(hlua_checkconverters(L, 1));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004375
4376 /* Get extra arguments. */
4377 for (i = 0; i < lua_gettop(L) - 2; i++) {
4378 if (i >= ARGM_NBARGS)
4379 break;
4380 hlua_lua2arg(L, i + 3, &args[i]);
4381 }
4382 args[i].type = ARGT_STOP;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004383 args[i].data.str.area = NULL;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004384
4385 /* Check arguments. */
Willy Tarreauda5f1082015-04-06 11:17:13 +02004386 MAY_LJMP(hlua_lua2arg_check(L, 3, args, conv->arg_mask, hsmp->p));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004387
4388 /* Run the special args checker. */
4389 if (conv->val_args && !conv->val_args(args, conv, "", 0, NULL)) {
4390 hlua_pusherror(L, "error in arguments");
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004391 goto error;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004392 }
4393
4394 /* Initialise the sample. */
Amaury Denoyellebc0af6a2020-10-29 17:21:20 +01004395 memset(&smp, 0, sizeof(smp));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004396 if (!hlua_lua2smp(L, 2, &smp)) {
4397 hlua_pusherror(L, "error in the input argument");
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004398 goto error;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004399 }
4400
Willy Tarreau1777ea62016-03-10 16:15:46 +01004401 smp_set_owner(&smp, hsmp->p, hsmp->s->sess, hsmp->s, hsmp->dir & SMP_OPT_DIR);
4402
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004403 /* Apply expected cast. */
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02004404 if (!sample_casts[smp.data.type][conv->in_type]) {
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004405 hlua_pusherror(L, "invalid input argument: cannot cast '%s' to '%s'",
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02004406 smp_to_type[smp.data.type], smp_to_type[conv->in_type]);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004407 goto error;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004408 }
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02004409 if (sample_casts[smp.data.type][conv->in_type] != c_none &&
4410 !sample_casts[smp.data.type][conv->in_type](&smp)) {
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004411 hlua_pusherror(L, "error during the input argument casting");
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004412 goto error;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004413 }
4414
4415 /* Run the sample conversion process. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02004416 if (!conv->process(args, &smp, conv->private)) {
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004417 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004418 lua_pushstring(L, "");
4419 else
Willy Tarreaua678b432015-08-28 10:14:59 +02004420 lua_pushnil(L);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004421 goto end;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004422 }
4423
4424 /* Convert the returned sample in lua value. */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004425 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004426 hlua_smp2lua_str(L, &smp);
4427 else
4428 hlua_smp2lua(L, &smp);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004429 end:
Willy Tarreauee0d7272021-07-16 10:26:56 +02004430 free_args(args);
Willy Tarreaua678b432015-08-28 10:14:59 +02004431 return 1;
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004432
4433 error:
Willy Tarreauee0d7272021-07-16 10:26:56 +02004434 free_args(args);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004435 WILL_LJMP(lua_error(L));
4436 return 0; /* Never reached */
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004437}
4438
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004439/*
4440 *
4441 *
4442 * Class AppletTCP
4443 *
4444 *
4445 */
4446
4447/* Returns a struct hlua_txn if the stack entry "ud" is
4448 * a class stream, otherwise it throws an error.
4449 */
4450__LJMP static struct hlua_appctx *hlua_checkapplet_tcp(lua_State *L, int ud)
4451{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004452 return MAY_LJMP(hlua_checkudata(L, ud, class_applet_tcp_ref));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004453}
4454
4455/* This function creates and push in the stack an Applet object
4456 * according with a current TXN.
4457 */
4458static int hlua_applet_tcp_new(lua_State *L, struct appctx *ctx)
4459{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004460 struct hlua_appctx *luactx;
Willy Tarreau0698c802022-05-11 14:09:57 +02004461 struct stream *s = appctx_strm(ctx);
Christopher Faulet2da02ae2022-02-24 13:45:27 +01004462 struct proxy *p;
4463
4464 ALREADY_CHECKED(s);
4465 p = s->be;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004466
4467 /* Check stack size. */
4468 if (!lua_checkstack(L, 3))
4469 return 0;
4470
4471 /* Create the object: obj[0] = userdata.
4472 * Note that the base of the Converters object is the
4473 * same than the TXN object.
4474 */
4475 lua_newtable(L);
Willy Tarreau7e702d12021-04-28 17:59:21 +02004476 luactx = lua_newuserdata(L, sizeof(*luactx));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004477 lua_rawseti(L, -2, 0);
Willy Tarreau7e702d12021-04-28 17:59:21 +02004478 luactx->appctx = ctx;
4479 luactx->htxn.s = s;
4480 luactx->htxn.p = p;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004481
4482 /* Create the "f" field that contains a list of fetches. */
4483 lua_pushstring(L, "f");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004484 if (!hlua_fetches_new(L, &luactx->htxn, 0))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004485 return 0;
4486 lua_settable(L, -3);
4487
4488 /* Create the "sf" field that contains a list of stringsafe fetches. */
4489 lua_pushstring(L, "sf");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004490 if (!hlua_fetches_new(L, &luactx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004491 return 0;
4492 lua_settable(L, -3);
4493
4494 /* Create the "c" field that contains a list of converters. */
4495 lua_pushstring(L, "c");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004496 if (!hlua_converters_new(L, &luactx->htxn, 0))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004497 return 0;
4498 lua_settable(L, -3);
4499
4500 /* Create the "sc" field that contains a list of stringsafe converters. */
4501 lua_pushstring(L, "sc");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004502 if (!hlua_converters_new(L, &luactx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004503 return 0;
4504 lua_settable(L, -3);
4505
4506 /* Pop a class stream metatable and affect it to the table. */
4507 lua_rawgeti(L, LUA_REGISTRYINDEX, class_applet_tcp_ref);
4508 lua_setmetatable(L, -2);
4509
4510 return 1;
4511}
4512
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004513__LJMP static int hlua_applet_tcp_set_var(lua_State *L)
4514{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004515 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004516 struct stream *s;
4517 const char *name;
4518 size_t len;
4519 struct sample smp;
4520
Tim Duesterhus4e172c92020-05-19 13:49:42 +02004521 if (lua_gettop(L) < 3 || lua_gettop(L) > 4)
4522 WILL_LJMP(luaL_error(L, "'set_var' needs between 3 and 4 arguments"));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004523
4524 /* It is useles to retrieve the stream, but this function
4525 * runs only in a stream context.
4526 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004527 luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004528 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02004529 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004530
4531 /* Converts the third argument in a sample. */
Amaury Denoyellebc0af6a2020-10-29 17:21:20 +01004532 memset(&smp, 0, sizeof(smp));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004533 hlua_lua2smp(L, 3, &smp);
4534
4535 /* Store the sample in a variable. */
4536 smp_set_owner(&smp, s->be, s->sess, s, 0);
Tim Duesterhus4e172c92020-05-19 13:49:42 +02004537
4538 if (lua_gettop(L) == 4 && lua_toboolean(L, 4))
4539 lua_pushboolean(L, vars_set_by_name_ifexist(name, len, &smp) != 0);
4540 else
4541 lua_pushboolean(L, vars_set_by_name(name, len, &smp) != 0);
4542
Tim Duesterhus84ebc132020-05-19 13:49:41 +02004543 return 1;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004544}
4545
4546__LJMP static int hlua_applet_tcp_unset_var(lua_State *L)
4547{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004548 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004549 struct stream *s;
4550 const char *name;
4551 size_t len;
4552 struct sample smp;
4553
4554 MAY_LJMP(check_args(L, 2, "unset_var"));
4555
4556 /* It is useles to retrieve the stream, but this function
4557 * runs only in a stream context.
4558 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004559 luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004560 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02004561 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004562
4563 /* Unset the variable. */
4564 smp_set_owner(&smp, s->be, s->sess, s, 0);
Tim Duesterhus84ebc132020-05-19 13:49:41 +02004565 lua_pushboolean(L, vars_unset_by_name_ifexist(name, len, &smp) != 0);
4566 return 1;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004567}
4568
4569__LJMP static int hlua_applet_tcp_get_var(lua_State *L)
4570{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004571 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004572 struct stream *s;
4573 const char *name;
4574 size_t len;
4575 struct sample smp;
4576
4577 MAY_LJMP(check_args(L, 2, "get_var"));
4578
4579 /* It is useles to retrieve the stream, but this function
4580 * runs only in a stream context.
4581 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004582 luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004583 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02004584 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004585
4586 smp_set_owner(&smp, s->be, s->sess, s, 0);
Willy Tarreaue352b9d2021-09-03 11:52:38 +02004587 if (!vars_get_by_name(name, len, &smp, NULL)) {
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004588 lua_pushnil(L);
4589 return 1;
4590 }
4591
4592 return hlua_smp2lua(L, &smp);
4593}
4594
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004595__LJMP static int hlua_applet_tcp_set_priv(lua_State *L)
4596{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004597 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
4598 struct stream *s = luactx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01004599 struct hlua *hlua;
4600
4601 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01004602 if (!s->hlua)
4603 return 0;
4604 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004605
4606 MAY_LJMP(check_args(L, 2, "set_priv"));
4607
4608 /* Remove previous value. */
Thierry FOURNIERe068b602017-04-26 13:27:05 +02004609 luaL_unref(L, LUA_REGISTRYINDEX, hlua->Mref);
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004610
4611 /* Get and store new value. */
4612 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
4613 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
4614
4615 return 0;
4616}
4617
4618__LJMP static int hlua_applet_tcp_get_priv(lua_State *L)
4619{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004620 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
4621 struct stream *s = luactx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01004622 struct hlua *hlua;
4623
4624 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01004625 if (!s->hlua) {
4626 lua_pushnil(L);
4627 return 1;
4628 }
4629 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004630
4631 /* Push configuration index in the stack. */
4632 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
4633
4634 return 1;
4635}
4636
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004637/* If expected data not yet available, it returns a yield. This function
4638 * consumes the data in the buffer. It returns a string containing the
4639 * data. This string can be empty.
4640 */
4641__LJMP static int hlua_applet_tcp_getline_yield(lua_State *L, int status, lua_KContext ctx)
4642{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004643 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Willy Tarreauc12b3212022-05-27 11:08:15 +02004644 struct stconn *sc = appctx_sc(luactx->appctx);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004645 int ret;
Willy Tarreau206ba832018-06-14 15:27:31 +02004646 const char *blk1;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004647 size_t len1;
Willy Tarreau206ba832018-06-14 15:27:31 +02004648 const char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004649 size_t len2;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004650
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004651 /* Read the maximum amount of data available. */
Willy Tarreau3e7be362022-05-27 10:35:27 +02004652 ret = co_getline_nc(sc_oc(sc), &blk1, &len1, &blk2, &len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004653
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004654 /* Data not yet available. return yield. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004655 if (ret == 0) {
Willy Tarreau90e8b452022-05-25 18:21:43 +02004656 applet_need_more_data(luactx->appctx);
Willy Tarreau9635e032018-10-16 17:52:55 +02004657 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_getline_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004658 }
4659
4660 /* End of data: commit the total strings and return. */
4661 if (ret < 0) {
Willy Tarreau7e702d12021-04-28 17:59:21 +02004662 luaL_pushresult(&luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004663 return 1;
4664 }
4665
4666 /* Ensure that the block 2 length is usable. */
4667 if (ret == 1)
4668 len2 = 0;
4669
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -07004670 /* don't check the max length read and don't check. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004671 luaL_addlstring(&luactx->b, blk1, len1);
4672 luaL_addlstring(&luactx->b, blk2, len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004673
4674 /* Consume input channel output buffer data. */
Willy Tarreau3e7be362022-05-27 10:35:27 +02004675 co_skip(sc_oc(sc), len1 + len2);
Willy Tarreau7e702d12021-04-28 17:59:21 +02004676 luaL_pushresult(&luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004677 return 1;
4678}
4679
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004680/* Check arguments for the function "hlua_channel_get_yield". */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004681__LJMP static int hlua_applet_tcp_getline(lua_State *L)
4682{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004683 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004684
4685 /* Initialise the string catenation. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004686 luaL_buffinit(L, &luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004687
4688 return MAY_LJMP(hlua_applet_tcp_getline_yield(L, 0, 0));
4689}
4690
4691/* If expected data not yet available, it returns a yield. This function
4692 * consumes the data in the buffer. It returns a string containing the
4693 * data. This string can be empty.
4694 */
4695__LJMP static int hlua_applet_tcp_recv_yield(lua_State *L, int status, lua_KContext ctx)
4696{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004697 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Willy Tarreauc12b3212022-05-27 11:08:15 +02004698 struct stconn *sc = appctx_sc(luactx->appctx);
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004699 size_t len = MAY_LJMP(luaL_checkinteger(L, 2));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004700 int ret;
Willy Tarreau206ba832018-06-14 15:27:31 +02004701 const char *blk1;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004702 size_t len1;
Willy Tarreau206ba832018-06-14 15:27:31 +02004703 const char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004704 size_t len2;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004705
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004706 /* Read the maximum amount of data available. */
Willy Tarreau3e7be362022-05-27 10:35:27 +02004707 ret = co_getblk_nc(sc_oc(sc), &blk1, &len1, &blk2, &len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004708
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004709 /* Data not yet available. return yield. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004710 if (ret == 0) {
Willy Tarreau90e8b452022-05-25 18:21:43 +02004711 applet_need_more_data(luactx->appctx);
Willy Tarreau9635e032018-10-16 17:52:55 +02004712 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004713 }
4714
4715 /* End of data: commit the total strings and return. */
4716 if (ret < 0) {
Willy Tarreau7e702d12021-04-28 17:59:21 +02004717 luaL_pushresult(&luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004718 return 1;
4719 }
4720
4721 /* Ensure that the block 2 length is usable. */
4722 if (ret == 1)
4723 len2 = 0;
4724
4725 if (len == -1) {
4726
4727 /* If len == -1, catenate all the data avalaile and
4728 * yield because we want to get all the data until
4729 * the end of data stream.
4730 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004731 luaL_addlstring(&luactx->b, blk1, len1);
4732 luaL_addlstring(&luactx->b, blk2, len2);
Willy Tarreau3e7be362022-05-27 10:35:27 +02004733 co_skip(sc_oc(sc), len1 + len2);
Willy Tarreau90e8b452022-05-25 18:21:43 +02004734 applet_need_more_data(luactx->appctx);
Willy Tarreau9635e032018-10-16 17:52:55 +02004735 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004736
4737 } else {
4738
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05004739 /* Copy the first block caping to the length required. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004740 if (len1 > len)
4741 len1 = len;
Willy Tarreau7e702d12021-04-28 17:59:21 +02004742 luaL_addlstring(&luactx->b, blk1, len1);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004743 len -= len1;
4744
4745 /* Copy the second block. */
4746 if (len2 > len)
4747 len2 = len;
Willy Tarreau7e702d12021-04-28 17:59:21 +02004748 luaL_addlstring(&luactx->b, blk2, len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004749 len -= len2;
4750
4751 /* Consume input channel output buffer data. */
Willy Tarreau3e7be362022-05-27 10:35:27 +02004752 co_skip(sc_oc(sc), len1 + len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004753
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004754 /* If there is no other data available, yield waiting for new data. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004755 if (len > 0) {
4756 lua_pushinteger(L, len);
4757 lua_replace(L, 2);
Willy Tarreau90e8b452022-05-25 18:21:43 +02004758 applet_need_more_data(luactx->appctx);
Willy Tarreau9635e032018-10-16 17:52:55 +02004759 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004760 }
4761
4762 /* return the result. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004763 luaL_pushresult(&luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004764 return 1;
4765 }
4766
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004767 /* we never execute this */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004768 hlua_pusherror(L, "Lua: internal error");
4769 WILL_LJMP(lua_error(L));
4770 return 0;
4771}
4772
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004773/* Check arguments for the function "hlua_channel_get_yield". */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004774__LJMP static int hlua_applet_tcp_recv(lua_State *L)
4775{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004776 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004777 int len = -1;
4778
4779 if (lua_gettop(L) > 2)
4780 WILL_LJMP(luaL_error(L, "The 'recv' function requires between 1 and 2 arguments."));
4781 if (lua_gettop(L) >= 2) {
4782 len = MAY_LJMP(luaL_checkinteger(L, 2));
4783 lua_pop(L, 1);
4784 }
4785
4786 /* Confirm or set the required length */
4787 lua_pushinteger(L, len);
4788
4789 /* Initialise the string catenation. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004790 luaL_buffinit(L, &luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004791
4792 return MAY_LJMP(hlua_applet_tcp_recv_yield(L, 0, 0));
4793}
4794
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004795/* Append data in the output side of the buffer. This data is immediately
4796 * sent. The function returns the amount of data written. If the buffer
4797 * cannot contain the data, the function yields. The function returns -1
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004798 * if the channel is closed.
4799 */
4800__LJMP static int hlua_applet_tcp_send_yield(lua_State *L, int status, lua_KContext ctx)
4801{
4802 size_t len;
Willy Tarreau7e702d12021-04-28 17:59:21 +02004803 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004804 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
4805 int l = MAY_LJMP(luaL_checkinteger(L, 3));
Willy Tarreauc12b3212022-05-27 11:08:15 +02004806 struct stconn *sc = appctx_sc(luactx->appctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02004807 struct channel *chn = sc_ic(sc);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004808 int max;
4809
4810 /* Get the max amount of data which can write as input in the channel. */
4811 max = channel_recv_max(chn);
4812 if (max > (len - l))
4813 max = len - l;
4814
4815 /* Copy data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02004816 ci_putblk(chn, str + l, max);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004817
4818 /* update counters. */
4819 l += max;
4820 lua_pop(L, 1);
4821 lua_pushinteger(L, l);
4822
4823 /* If some data is not send, declares the situation to the
4824 * applet, and returns a yield.
4825 */
4826 if (l < len) {
Willy Tarreau3e7be362022-05-27 10:35:27 +02004827 sc_need_room(sc);
Willy Tarreau9635e032018-10-16 17:52:55 +02004828 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004829 }
4830
4831 return 1;
4832}
4833
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05004834/* Just a wrapper of "hlua_applet_tcp_send_yield". This wrapper permits
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004835 * yield the LUA process, and resume it without checking the
4836 * input arguments.
4837 */
4838__LJMP static int hlua_applet_tcp_send(lua_State *L)
4839{
4840 MAY_LJMP(check_args(L, 2, "send"));
4841 lua_pushinteger(L, 0);
4842
4843 return MAY_LJMP(hlua_applet_tcp_send_yield(L, 0, 0));
4844}
4845
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004846/*
4847 *
4848 *
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004849 * Class AppletHTTP
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004850 *
4851 *
4852 */
4853
4854/* Returns a struct hlua_txn if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02004855 * a class stream, otherwise it throws an error.
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004856 */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004857__LJMP static struct hlua_appctx *hlua_checkapplet_http(lua_State *L, int ud)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004858{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004859 return MAY_LJMP(hlua_checkudata(L, ud, class_applet_http_ref));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004860}
4861
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004862/* This function creates and push in the stack an Applet object
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004863 * according with a current TXN.
Willy Tarreauaa229cc2022-05-06 14:26:10 +02004864 * It relies on the caller to have already reserved the room in ctx->svcctx
4865 * for the local storage of hlua_http_ctx.
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004866 */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004867static int hlua_applet_http_new(lua_State *L, struct appctx *ctx)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004868{
Willy Tarreauaa229cc2022-05-06 14:26:10 +02004869 struct hlua_http_ctx *http_ctx = ctx->svcctx;
Willy Tarreau7e702d12021-04-28 17:59:21 +02004870 struct hlua_appctx *luactx;
Thierry FOURNIER841475e2015-12-11 17:10:09 +01004871 struct hlua_txn htxn;
Willy Tarreau0698c802022-05-11 14:09:57 +02004872 struct stream *s = appctx_strm(ctx);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004873 struct proxy *px = s->be;
Christopher Fauleta2097962019-07-15 16:25:33 +02004874 struct htx *htx;
4875 struct htx_blk *blk;
4876 struct htx_sl *sl;
4877 struct ist path;
4878 unsigned long long len = 0;
4879 int32_t pos;
Amaury Denoyellec453f952021-07-06 11:40:12 +02004880 struct http_uri_parser parser;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004881
4882 /* Check stack size. */
4883 if (!lua_checkstack(L, 3))
4884 return 0;
4885
4886 /* Create the object: obj[0] = userdata.
4887 * Note that the base of the Converters object is the
4888 * same than the TXN object.
4889 */
4890 lua_newtable(L);
Willy Tarreau7e702d12021-04-28 17:59:21 +02004891 luactx = lua_newuserdata(L, sizeof(*luactx));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004892 lua_rawseti(L, -2, 0);
Willy Tarreau7e702d12021-04-28 17:59:21 +02004893 luactx->appctx = ctx;
Willy Tarreauaa229cc2022-05-06 14:26:10 +02004894 http_ctx->status = 200; /* Default status code returned. */
4895 http_ctx->reason = NULL; /* Use default reason based on status */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004896 luactx->htxn.s = s;
4897 luactx->htxn.p = px;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004898
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004899 /* Create the "f" field that contains a list of fetches. */
4900 lua_pushstring(L, "f");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004901 if (!hlua_fetches_new(L, &luactx->htxn, 0))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004902 return 0;
4903 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004904
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004905 /* Create the "sf" field that contains a list of stringsafe fetches. */
4906 lua_pushstring(L, "sf");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004907 if (!hlua_fetches_new(L, &luactx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004908 return 0;
4909 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004910
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004911 /* Create the "c" field that contains a list of converters. */
4912 lua_pushstring(L, "c");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004913 if (!hlua_converters_new(L, &luactx->htxn, 0))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004914 return 0;
4915 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004916
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004917 /* Create the "sc" field that contains a list of stringsafe converters. */
4918 lua_pushstring(L, "sc");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004919 if (!hlua_converters_new(L, &luactx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004920 return 0;
4921 lua_settable(L, -3);
Willy Tarreaueee5b512015-04-03 23:46:31 +02004922
Christopher Fauleta2097962019-07-15 16:25:33 +02004923 htx = htxbuf(&s->req.buf);
4924 blk = htx_get_first_blk(htx);
Christopher Fauletea009732019-11-18 15:50:25 +01004925 BUG_ON(!blk || htx_get_blk_type(blk) != HTX_BLK_REQ_SL);
Christopher Fauleta2097962019-07-15 16:25:33 +02004926 sl = htx_get_blk_ptr(htx, blk);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004927
Christopher Fauleta2097962019-07-15 16:25:33 +02004928 /* Stores the request method. */
4929 lua_pushstring(L, "method");
4930 lua_pushlstring(L, HTX_SL_REQ_MPTR(sl), HTX_SL_REQ_MLEN(sl));
4931 lua_settable(L, -3);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004932
Christopher Fauleta2097962019-07-15 16:25:33 +02004933 /* Stores the http version. */
4934 lua_pushstring(L, "version");
4935 lua_pushlstring(L, HTX_SL_REQ_VPTR(sl), HTX_SL_REQ_VLEN(sl));
4936 lua_settable(L, -3);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004937
Christopher Fauleta2097962019-07-15 16:25:33 +02004938 /* creates an array of headers. hlua_http_get_headers() crates and push
4939 * the array on the top of the stack.
4940 */
4941 lua_pushstring(L, "headers");
4942 htxn.s = s;
4943 htxn.p = px;
4944 htxn.dir = SMP_OPT_DIR_REQ;
Christopher Faulet9d1332b2020-02-24 16:46:16 +01004945 if (!hlua_http_get_headers(L, &htxn.s->txn->req))
Christopher Fauleta2097962019-07-15 16:25:33 +02004946 return 0;
4947 lua_settable(L, -3);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004948
Amaury Denoyellec453f952021-07-06 11:40:12 +02004949 parser = http_uri_parser_init(htx_sl_req_uri(sl));
4950 path = http_parse_path(&parser);
Tim Duesterhused526372020-03-05 17:56:33 +01004951 if (isttest(path)) {
Christopher Fauleta2097962019-07-15 16:25:33 +02004952 char *p, *q, *end;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004953
Christopher Fauleta2097962019-07-15 16:25:33 +02004954 p = path.ptr;
Tim Duesterhus4c8f75f2021-11-06 15:14:44 +01004955 end = istend(path);
Christopher Fauleta2097962019-07-15 16:25:33 +02004956 q = p;
4957 while (q < end && *q != '?')
4958 q++;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004959
Thierry FOURNIER7d388632017-02-22 02:06:16 +01004960 /* Stores the request path. */
Christopher Fauleta2097962019-07-15 16:25:33 +02004961 lua_pushstring(L, "path");
4962 lua_pushlstring(L, p, q - p);
Thierry FOURNIER7d388632017-02-22 02:06:16 +01004963 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01004964
Christopher Fauleta2097962019-07-15 16:25:33 +02004965 /* Stores the query string. */
4966 lua_pushstring(L, "qs");
4967 if (*q == '?')
4968 q++;
4969 lua_pushlstring(L, q, end - q);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004970 lua_settable(L, -3);
Christopher Fauleta2097962019-07-15 16:25:33 +02004971 }
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004972
Christopher Fauleta2097962019-07-15 16:25:33 +02004973 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
4974 struct htx_blk *blk = htx_get_blk(htx, pos);
4975 enum htx_blk_type type = htx_get_blk_type(blk);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004976
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01004977 if (type == HTX_BLK_TLR || type == HTX_BLK_EOT)
Christopher Fauleta2097962019-07-15 16:25:33 +02004978 break;
4979 if (type == HTX_BLK_DATA)
4980 len += htx_get_blksz(blk);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004981 }
Christopher Faulet2e47e3a2023-01-13 11:40:24 +01004982 if (htx->extra != HTX_UNKOWN_PAYLOAD_LENGTH)
Christopher Fauleta2097962019-07-15 16:25:33 +02004983 len += htx->extra;
4984
4985 /* Stores the request path. */
4986 lua_pushstring(L, "length");
4987 lua_pushinteger(L, len);
4988 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01004989
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004990 /* Create an empty array of HTTP request headers. */
4991 lua_pushstring(L, "response");
4992 lua_newtable(L);
4993 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01004994
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004995 /* Pop a class stream metatable and affect it to the table. */
4996 lua_rawgeti(L, LUA_REGISTRYINDEX, class_applet_http_ref);
4997 lua_setmetatable(L, -2);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004998
4999 return 1;
5000}
5001
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01005002__LJMP static int hlua_applet_http_set_var(lua_State *L)
5003{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005004 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01005005 struct stream *s;
5006 const char *name;
5007 size_t len;
5008 struct sample smp;
5009
Tim Duesterhus4e172c92020-05-19 13:49:42 +02005010 if (lua_gettop(L) < 3 || lua_gettop(L) > 4)
5011 WILL_LJMP(luaL_error(L, "'set_var' needs between 3 and 4 arguments"));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01005012
5013 /* It is useles to retrieve the stream, but this function
5014 * runs only in a stream context.
5015 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005016 luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01005017 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02005018 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01005019
5020 /* Converts the third argument in a sample. */
Amaury Denoyellebc0af6a2020-10-29 17:21:20 +01005021 memset(&smp, 0, sizeof(smp));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01005022 hlua_lua2smp(L, 3, &smp);
5023
5024 /* Store the sample in a variable. */
5025 smp_set_owner(&smp, s->be, s->sess, s, 0);
Tim Duesterhus4e172c92020-05-19 13:49:42 +02005026
5027 if (lua_gettop(L) == 4 && lua_toboolean(L, 4))
5028 lua_pushboolean(L, vars_set_by_name_ifexist(name, len, &smp) != 0);
5029 else
5030 lua_pushboolean(L, vars_set_by_name(name, len, &smp) != 0);
5031
Tim Duesterhus84ebc132020-05-19 13:49:41 +02005032 return 1;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01005033}
5034
5035__LJMP static int hlua_applet_http_unset_var(lua_State *L)
5036{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005037 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01005038 struct stream *s;
5039 const char *name;
5040 size_t len;
5041 struct sample smp;
5042
5043 MAY_LJMP(check_args(L, 2, "unset_var"));
5044
5045 /* It is useles to retrieve the stream, but this function
5046 * runs only in a stream context.
5047 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005048 luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01005049 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02005050 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01005051
5052 /* Unset the variable. */
5053 smp_set_owner(&smp, s->be, s->sess, s, 0);
Tim Duesterhus84ebc132020-05-19 13:49:41 +02005054 lua_pushboolean(L, vars_unset_by_name_ifexist(name, len, &smp) != 0);
5055 return 1;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01005056}
5057
5058__LJMP static int hlua_applet_http_get_var(lua_State *L)
5059{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005060 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01005061 struct stream *s;
5062 const char *name;
5063 size_t len;
5064 struct sample smp;
5065
5066 MAY_LJMP(check_args(L, 2, "get_var"));
5067
5068 /* It is useles to retrieve the stream, but this function
5069 * runs only in a stream context.
5070 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005071 luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01005072 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02005073 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01005074
5075 smp_set_owner(&smp, s->be, s->sess, s, 0);
Willy Tarreaue352b9d2021-09-03 11:52:38 +02005076 if (!vars_get_by_name(name, len, &smp, NULL)) {
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01005077 lua_pushnil(L);
5078 return 1;
5079 }
5080
5081 return hlua_smp2lua(L, &smp);
5082}
5083
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01005084__LJMP static int hlua_applet_http_set_priv(lua_State *L)
5085{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005086 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
5087 struct stream *s = luactx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01005088 struct hlua *hlua;
5089
5090 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005091 if (!s->hlua)
5092 return 0;
5093 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01005094
5095 MAY_LJMP(check_args(L, 2, "set_priv"));
5096
5097 /* Remove previous value. */
Thierry FOURNIERe068b602017-04-26 13:27:05 +02005098 luaL_unref(L, LUA_REGISTRYINDEX, hlua->Mref);
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01005099
5100 /* Get and store new value. */
5101 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
5102 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
5103
5104 return 0;
5105}
5106
5107__LJMP static int hlua_applet_http_get_priv(lua_State *L)
5108{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005109 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
5110 struct stream *s = luactx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01005111 struct hlua *hlua;
5112
5113 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005114 if (!s->hlua) {
5115 lua_pushnil(L);
5116 return 1;
5117 }
5118 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01005119
5120 /* Push configuration index in the stack. */
5121 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
5122
5123 return 1;
5124}
5125
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005126/* If expected data not yet available, it returns a yield. This function
5127 * consumes the data in the buffer. It returns a string containing the
5128 * data. This string can be empty.
5129 */
Christopher Fauleta2097962019-07-15 16:25:33 +02005130__LJMP static int hlua_applet_http_getline_yield(lua_State *L, int status, lua_KContext ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005131{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005132 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Willy Tarreauc12b3212022-05-27 11:08:15 +02005133 struct stconn *sc = appctx_sc(luactx->appctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02005134 struct channel *req = sc_oc(sc);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005135 struct htx *htx;
5136 struct htx_blk *blk;
5137 size_t count;
5138 int stop = 0;
5139
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005140 htx = htx_from_buf(&req->buf);
5141 count = co_data(req);
Christopher Fauleta3f15502019-05-13 15:27:23 +02005142 blk = htx_get_first_blk(htx);
Christopher Fauletcc26b132018-12-18 21:20:57 +01005143
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005144 while (count && !stop && blk) {
5145 enum htx_blk_type type = htx_get_blk_type(blk);
5146 uint32_t sz = htx_get_blksz(blk);
5147 struct ist v;
5148 uint32_t vlen;
5149 char *nl;
5150
5151 vlen = sz;
5152 if (vlen > count) {
5153 if (type != HTX_BLK_DATA)
5154 break;
5155 vlen = count;
5156 }
5157
5158 switch (type) {
5159 case HTX_BLK_UNUSED:
5160 break;
5161
5162 case HTX_BLK_DATA:
5163 v = htx_get_blk_value(htx, blk);
5164 v.len = vlen;
5165 nl = istchr(v, '\n');
5166 if (nl != NULL) {
5167 stop = 1;
5168 vlen = nl - v.ptr + 1;
5169 }
Willy Tarreau7e702d12021-04-28 17:59:21 +02005170 luaL_addlstring(&luactx->b, v.ptr, vlen);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005171 break;
5172
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005173 case HTX_BLK_TLR:
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01005174 case HTX_BLK_EOT:
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005175 stop = 1;
5176 break;
5177
5178 default:
5179 break;
5180 }
5181
Willy Tarreau84240042022-02-28 16:51:23 +01005182 c_rew(req, vlen);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005183 count -= vlen;
5184 if (sz == vlen)
5185 blk = htx_remove_blk(htx, blk);
5186 else {
5187 htx_cut_data_blk(htx, blk, vlen);
5188 break;
5189 }
5190 }
5191
Christopher Fauleteccb31c2021-04-02 14:24:56 +02005192 /* The message was fully consumed and no more data are expected
5193 * (EOM flag set).
5194 */
Christopher Faulet904763f2023-03-22 14:53:11 +01005195 if (htx_is_empty(htx) && (sc->flags & SC_FL_EOI))
Christopher Fauleteccb31c2021-04-02 14:24:56 +02005196 stop = 1;
5197
Christopher Faulet0ae79d02019-02-27 21:36:59 +01005198 htx_to_buf(htx, &req->buf);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005199 if (!stop) {
Willy Tarreau90e8b452022-05-25 18:21:43 +02005200 applet_need_more_data(luactx->appctx);
Christopher Fauleta2097962019-07-15 16:25:33 +02005201 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_getline_yield, TICK_ETERNITY, 0));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005202 }
5203
5204 /* return the result. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005205 luaL_pushresult(&luactx->b);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005206 return 1;
5207}
5208
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005209
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08005210/* Check arguments for the function "hlua_channel_get_yield". */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005211__LJMP static int hlua_applet_http_getline(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005212{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005213 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005214
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005215 /* Initialise the string catenation. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005216 luaL_buffinit(L, &luactx->b);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005217
Christopher Fauleta2097962019-07-15 16:25:33 +02005218 return MAY_LJMP(hlua_applet_http_getline_yield(L, 0, 0));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005219}
5220
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005221/* If expected data not yet available, it returns a yield. This function
5222 * consumes the data in the buffer. It returns a string containing the
5223 * data. This string can be empty.
5224 */
Christopher Fauleta2097962019-07-15 16:25:33 +02005225__LJMP static int hlua_applet_http_recv_yield(lua_State *L, int status, lua_KContext ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005226{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005227 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Willy Tarreauc12b3212022-05-27 11:08:15 +02005228 struct stconn *sc = appctx_sc(luactx->appctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02005229 struct channel *req = sc_oc(sc);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005230 struct htx *htx;
5231 struct htx_blk *blk;
5232 size_t count;
5233 int len;
5234
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005235 htx = htx_from_buf(&req->buf);
5236 len = MAY_LJMP(luaL_checkinteger(L, 2));
5237 count = co_data(req);
Christopher Faulet29f17582019-05-23 11:03:26 +02005238 blk = htx_get_head_blk(htx);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005239 while (count && len && blk) {
5240 enum htx_blk_type type = htx_get_blk_type(blk);
5241 uint32_t sz = htx_get_blksz(blk);
5242 struct ist v;
5243 uint32_t vlen;
5244
5245 vlen = sz;
5246 if (len > 0 && vlen > len)
5247 vlen = len;
5248 if (vlen > count) {
5249 if (type != HTX_BLK_DATA)
5250 break;
5251 vlen = count;
5252 }
5253
5254 switch (type) {
5255 case HTX_BLK_UNUSED:
5256 break;
5257
5258 case HTX_BLK_DATA:
5259 v = htx_get_blk_value(htx, blk);
Willy Tarreau7e702d12021-04-28 17:59:21 +02005260 luaL_addlstring(&luactx->b, v.ptr, vlen);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005261 break;
5262
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005263 case HTX_BLK_TLR:
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01005264 case HTX_BLK_EOT:
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005265 len = 0;
5266 break;
5267
5268 default:
5269 break;
5270 }
5271
Willy Tarreau84240042022-02-28 16:51:23 +01005272 c_rew(req, vlen);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005273 count -= vlen;
5274 if (len > 0)
5275 len -= vlen;
5276 if (sz == vlen)
5277 blk = htx_remove_blk(htx, blk);
5278 else {
5279 htx_cut_data_blk(htx, blk, vlen);
5280 break;
5281 }
5282 }
5283
Christopher Fauleteccb31c2021-04-02 14:24:56 +02005284 /* The message was fully consumed and no more data are expected
5285 * (EOM flag set).
5286 */
Christopher Faulet904763f2023-03-22 14:53:11 +01005287 if (htx_is_empty(htx) && (sc->flags & SC_FL_EOI))
Christopher Fauleteccb31c2021-04-02 14:24:56 +02005288 len = 0;
5289
Christopher Faulet0ae79d02019-02-27 21:36:59 +01005290 htx_to_buf(htx, &req->buf);
5291
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005292 /* If we are no other data available, yield waiting for new data. */
5293 if (len) {
5294 if (len > 0) {
5295 lua_pushinteger(L, len);
5296 lua_replace(L, 2);
5297 }
Willy Tarreau90e8b452022-05-25 18:21:43 +02005298 applet_need_more_data(luactx->appctx);
Willy Tarreau9635e032018-10-16 17:52:55 +02005299 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005300 }
5301
5302 /* return the result. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005303 luaL_pushresult(&luactx->b);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005304 return 1;
5305}
5306
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08005307/* Check arguments for the function "hlua_channel_get_yield". */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005308__LJMP static int hlua_applet_http_recv(lua_State *L)
5309{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005310 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005311 int len = -1;
5312
5313 /* Check arguments. */
5314 if (lua_gettop(L) > 2)
5315 WILL_LJMP(luaL_error(L, "The 'recv' function requires between 1 and 2 arguments."));
5316 if (lua_gettop(L) >= 2) {
5317 len = MAY_LJMP(luaL_checkinteger(L, 2));
5318 lua_pop(L, 1);
5319 }
5320
Christopher Fauleta2097962019-07-15 16:25:33 +02005321 lua_pushinteger(L, len);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005322
Christopher Fauleta2097962019-07-15 16:25:33 +02005323 /* Initialise the string catenation. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005324 luaL_buffinit(L, &luactx->b);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005325
Christopher Fauleta2097962019-07-15 16:25:33 +02005326 return MAY_LJMP(hlua_applet_http_recv_yield(L, 0, 0));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005327}
5328
5329/* Append data in the output side of the buffer. This data is immediately
5330 * sent. The function returns the amount of data written. If the buffer
5331 * cannot contain the data, the function yields. The function returns -1
5332 * if the channel is closed.
5333 */
Christopher Fauleta2097962019-07-15 16:25:33 +02005334__LJMP static int hlua_applet_http_send_yield(lua_State *L, int status, lua_KContext ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005335{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005336 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Willy Tarreauc12b3212022-05-27 11:08:15 +02005337 struct stconn *sc = appctx_sc(luactx->appctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02005338 struct channel *res = sc_ic(sc);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005339 struct htx *htx = htx_from_buf(&res->buf);
5340 const char *data;
5341 size_t len;
5342 int l = MAY_LJMP(luaL_checkinteger(L, 3));
5343 int max;
5344
Christopher Faulet9060fc02019-07-03 11:39:30 +02005345 max = htx_get_max_blksz(htx, channel_htx_recv_max(res, htx));
Christopher Faulet4b0e9b22019-01-09 12:16:58 +01005346 if (!max)
5347 goto snd_yield;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005348
5349 data = MAY_LJMP(luaL_checklstring(L, 2, &len));
5350
5351 /* Get the max amount of data which can write as input in the channel. */
5352 if (max > (len - l))
5353 max = len - l;
5354
5355 /* Copy data. */
Willy Tarreau0a7ef022019-05-28 10:30:11 +02005356 max = htx_add_data(htx, ist2(data + l, max));
Christopher Fauletf6cce3f2019-02-27 21:20:09 +01005357 channel_add_input(res, max);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005358
5359 /* update counters. */
5360 l += max;
5361 lua_pop(L, 1);
5362 lua_pushinteger(L, l);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005363
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005364 /* If some data is not send, declares the situation to the
5365 * applet, and returns a yield.
5366 */
5367 if (l < len) {
Christopher Faulet4b0e9b22019-01-09 12:16:58 +01005368 snd_yield:
Christopher Faulet0ae79d02019-02-27 21:36:59 +01005369 htx_to_buf(htx, &res->buf);
Willy Tarreau3e7be362022-05-27 10:35:27 +02005370 sc_need_room(sc);
Willy Tarreau9635e032018-10-16 17:52:55 +02005371 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005372 }
5373
Christopher Fauleta2097962019-07-15 16:25:33 +02005374 htx_to_buf(htx, &res->buf);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005375 return 1;
5376}
5377
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05005378/* Just a wrapper of "hlua_applet_send_yield". This wrapper permits
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005379 * yield the LUA process, and resume it without checking the
5380 * input arguments.
5381 */
5382__LJMP static int hlua_applet_http_send(lua_State *L)
5383{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005384 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005385 struct hlua_http_ctx *http_ctx = luactx->appctx->svcctx;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005386
5387 /* We want to send some data. Headers must be sent. */
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005388 if (!(http_ctx->flags & APPLET_HDR_SENT)) {
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005389 hlua_pusherror(L, "Lua: 'send' you must call start_response() before sending data.");
5390 WILL_LJMP(lua_error(L));
5391 }
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005392
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05005393 /* This integer is used for followinf the amount of data sent. */
Christopher Fauleta2097962019-07-15 16:25:33 +02005394 lua_pushinteger(L, 0);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005395
Christopher Fauleta2097962019-07-15 16:25:33 +02005396 return MAY_LJMP(hlua_applet_http_send_yield(L, 0, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005397}
5398
5399__LJMP static int hlua_applet_http_addheader(lua_State *L)
5400{
5401 const char *name;
5402 int ret;
5403
5404 MAY_LJMP(hlua_checkapplet_http(L, 1));
5405 name = MAY_LJMP(luaL_checkstring(L, 2));
5406 MAY_LJMP(luaL_checkstring(L, 3));
5407
5408 /* Push in the stack the "response" entry. */
5409 ret = lua_getfield(L, 1, "response");
5410 if (ret != LUA_TTABLE) {
5411 hlua_pusherror(L, "Lua: 'add_header' internal error: AppletHTTP['response'] "
5412 "is expected as an array. %s found", lua_typename(L, ret));
5413 WILL_LJMP(lua_error(L));
5414 }
5415
5416 /* check if the header is already registered if it is not
5417 * the case, register it.
5418 */
5419 ret = lua_getfield(L, -1, name);
5420 if (ret == LUA_TNIL) {
5421
5422 /* Entry not found. */
5423 lua_pop(L, 1); /* remove the nil. The "response" table is the top of the stack. */
5424
5425 /* Insert the new header name in the array in the top of the stack.
5426 * It left the new array in the top of the stack.
5427 */
5428 lua_newtable(L);
5429 lua_pushvalue(L, 2);
5430 lua_pushvalue(L, -2);
5431 lua_settable(L, -4);
5432
5433 } else if (ret != LUA_TTABLE) {
5434
5435 /* corruption error. */
5436 hlua_pusherror(L, "Lua: 'add_header' internal error: AppletHTTP['response']['%s'] "
5437 "is expected as an array. %s found", name, lua_typename(L, ret));
5438 WILL_LJMP(lua_error(L));
5439 }
5440
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -07005441 /* Now the top of thestack is an array of values. We push
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005442 * the header value as new entry.
5443 */
5444 lua_pushvalue(L, 3);
5445 ret = lua_rawlen(L, -2);
5446 lua_rawseti(L, -2, ret + 1);
5447 lua_pushboolean(L, 1);
5448 return 1;
5449}
5450
5451__LJMP static int hlua_applet_http_status(lua_State *L)
5452{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005453 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005454 int status = MAY_LJMP(luaL_checkinteger(L, 2));
Robin H. Johnson52f5db22017-01-01 13:10:52 -08005455 const char *reason = MAY_LJMP(luaL_optlstring(L, 3, NULL, NULL));
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005456 struct hlua_http_ctx *http_ctx = luactx->appctx->svcctx;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005457
5458 if (status < 100 || status > 599) {
5459 lua_pushboolean(L, 0);
5460 return 1;
5461 }
5462
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005463 http_ctx->status = status;
5464 http_ctx->reason = reason;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005465 lua_pushboolean(L, 1);
5466 return 1;
5467}
5468
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005469
Christopher Fauleta2097962019-07-15 16:25:33 +02005470__LJMP static int hlua_applet_http_send_response(lua_State *L)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005471{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005472 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005473 struct hlua_http_ctx *http_ctx = luactx->appctx->svcctx;
Willy Tarreauc12b3212022-05-27 11:08:15 +02005474 struct stconn *sc = appctx_sc(luactx->appctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02005475 struct channel *res = sc_ic(sc);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005476 struct htx *htx;
5477 struct htx_sl *sl;
5478 struct h1m h1m;
5479 const char *status, *reason;
5480 const char *name, *value;
5481 size_t nlen, vlen;
5482 unsigned int flags;
5483
5484 /* Send the message at once. */
5485 htx = htx_from_buf(&res->buf);
5486 h1m_init_res(&h1m);
5487
5488 /* Use the same http version than the request. */
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005489 status = ultoa_r(http_ctx->status, trash.area, trash.size);
5490 reason = http_ctx->reason;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005491 if (reason == NULL)
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005492 reason = http_get_reason(http_ctx->status);
5493 if (http_ctx->flags & APPLET_HTTP11) {
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005494 flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11);
5495 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.1"), ist(status), ist(reason));
5496 }
5497 else {
5498 flags = HTX_SL_F_IS_RESP;
5499 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.0"), ist(status), ist(reason));
5500 }
5501 if (!sl) {
5502 hlua_pusherror(L, "Lua applet http '%s': Failed to create response.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005503 luactx->appctx->rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005504 WILL_LJMP(lua_error(L));
5505 }
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005506 sl->info.res.status = http_ctx->status;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005507
5508 /* Get the array associated to the field "response" in the object AppletHTTP. */
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005509 if (lua_getfield(L, 1, "response") != LUA_TTABLE) {
5510 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response'] missing.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005511 luactx->appctx->rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005512 WILL_LJMP(lua_error(L));
5513 }
5514
5515 /* Browse the list of headers. */
5516 lua_pushnil(L);
5517 while(lua_next(L, -2) != 0) {
5518 /* We expect a string as -2. */
5519 if (lua_type(L, -2) != LUA_TSTRING) {
5520 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response'][] element must be a string. got %s.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005521 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005522 lua_typename(L, lua_type(L, -2)));
5523 WILL_LJMP(lua_error(L));
5524 }
5525 name = lua_tolstring(L, -2, &nlen);
5526
5527 /* We expect an array as -1. */
5528 if (lua_type(L, -1) != LUA_TTABLE) {
5529 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 +02005530 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005531 name,
5532 lua_typename(L, lua_type(L, -1)));
5533 WILL_LJMP(lua_error(L));
5534 }
5535
5536 /* Browse the table who is on the top of the stack. */
5537 lua_pushnil(L);
5538 while(lua_next(L, -2) != 0) {
5539 int id;
5540
5541 /* We expect a number as -2. */
5542 if (lua_type(L, -2) != LUA_TNUMBER) {
5543 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 +02005544 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005545 name,
5546 lua_typename(L, lua_type(L, -2)));
5547 WILL_LJMP(lua_error(L));
5548 }
5549 id = lua_tointeger(L, -2);
5550
5551 /* We expect a string as -2. */
5552 if (lua_type(L, -1) != LUA_TSTRING) {
5553 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 +02005554 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005555 name, id,
5556 lua_typename(L, lua_type(L, -1)));
5557 WILL_LJMP(lua_error(L));
5558 }
5559 value = lua_tolstring(L, -1, &vlen);
5560
5561 /* Simple Protocol checks. */
Christopher Faulet545fbba2021-09-28 09:36:25 +02005562 if (isteqi(ist2(name, nlen), ist("transfer-encoding"))) {
5563 int ret;
5564
5565 ret = h1_parse_xfer_enc_header(&h1m, ist2(value, vlen));
5566 if (ret < 0) {
5567 hlua_pusherror(L, "Lua applet http '%s': Invalid '%s' header.\n",
5568 luactx->appctx->rule->arg.hlua_rule->fcn->name,
5569 name);
5570 WILL_LJMP(lua_error(L));
5571 }
5572 else if (ret == 0)
5573 goto next; /* Skip it */
5574 }
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005575 else if (isteqi(ist2(name, nlen), ist("content-length"))) {
5576 struct ist v = ist2(value, vlen);
5577 int ret;
5578
5579 ret = h1_parse_cont_len_header(&h1m, &v);
5580 if (ret < 0) {
5581 hlua_pusherror(L, "Lua applet http '%s': Invalid '%s' header.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005582 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005583 name);
5584 WILL_LJMP(lua_error(L));
5585 }
5586 else if (ret == 0)
5587 goto next; /* Skip it */
5588 }
5589
5590 /* Add a new header */
5591 if (!htx_add_header(htx, ist2(name, nlen), ist2(value, vlen))) {
5592 hlua_pusherror(L, "Lua applet http '%s': Failed to add header '%s' in the response.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005593 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005594 name);
5595 WILL_LJMP(lua_error(L));
5596 }
5597 next:
5598 /* Remove the array from the stack, and get next element with a remaining string. */
5599 lua_pop(L, 1);
5600 }
5601
5602 /* Remove the array from the stack, and get next element with a remaining string. */
5603 lua_pop(L, 1);
5604 }
5605
5606 if (h1m.flags & H1_MF_CHNK)
5607 h1m.flags &= ~H1_MF_CLEN;
5608 if (h1m.flags & (H1_MF_CLEN|H1_MF_CHNK))
5609 h1m.flags |= H1_MF_XFER_LEN;
5610
5611 /* Uset HTX start-line flags */
5612 if (h1m.flags & H1_MF_XFER_ENC)
5613 flags |= HTX_SL_F_XFER_ENC;
5614 if (h1m.flags & H1_MF_XFER_LEN) {
5615 flags |= HTX_SL_F_XFER_LEN;
5616 if (h1m.flags & H1_MF_CHNK)
5617 flags |= HTX_SL_F_CHNK;
5618 else if (h1m.flags & H1_MF_CLEN)
5619 flags |= HTX_SL_F_CLEN;
5620 if (h1m.body_len == 0)
5621 flags |= HTX_SL_F_BODYLESS;
5622 }
5623 sl->flags |= flags;
5624
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -07005625 /* If we don't have a content-length set, and the HTTP version is 1.1
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005626 * and the status code implies the presence of a message body, we must
5627 * announce a transfer encoding chunked. This is required by haproxy
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05005628 * for the keepalive compliance. If the applet announces a transfer-encoding
5629 * chunked itself, don't do anything.
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005630 */
5631 if ((flags & (HTX_SL_F_VER_11|HTX_SL_F_XFER_LEN)) == HTX_SL_F_VER_11 &&
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005632 http_ctx->status >= 200 && http_ctx->status != 204 && http_ctx->status != 304) {
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005633 /* Add a new header */
5634 sl->flags |= (HTX_SL_F_XFER_ENC|H1_MF_CHNK|H1_MF_XFER_LEN);
5635 if (!htx_add_header(htx, ist("transfer-encoding"), ist("chunked"))) {
5636 hlua_pusherror(L, "Lua applet http '%s': Failed to add header 'transfer-encoding' in the response.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005637 luactx->appctx->rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005638 WILL_LJMP(lua_error(L));
5639 }
5640 }
5641
5642 /* Finalize headers. */
5643 if (!htx_add_endof(htx, HTX_BLK_EOH)) {
5644 hlua_pusherror(L, "Lua applet http '%s': Failed create the response.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005645 luactx->appctx->rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005646 WILL_LJMP(lua_error(L));
5647 }
5648
5649 if (htx_used_space(htx) > b_size(&res->buf) - global.tune.maxrewrite) {
5650 b_reset(&res->buf);
5651 hlua_pusherror(L, "Lua: 'start_response': response header block too big");
5652 WILL_LJMP(lua_error(L));
5653 }
5654
5655 htx_to_buf(htx, &res->buf);
Christopher Fauletf6cce3f2019-02-27 21:20:09 +01005656 channel_add_input(res, htx->data);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005657
5658 /* Headers sent, set the flag. */
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005659 http_ctx->flags |= APPLET_HDR_SENT;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005660 return 0;
5661
5662}
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005663/* We will build the status line and the headers of the HTTP response.
5664 * We will try send at once if its not possible, we give back the hand
5665 * waiting for more room.
5666 */
Christopher Fauleta2097962019-07-15 16:25:33 +02005667__LJMP static int hlua_applet_http_start_response_yield(lua_State *L, int status, lua_KContext ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005668{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005669 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Willy Tarreauc12b3212022-05-27 11:08:15 +02005670 struct stconn *sc = appctx_sc(luactx->appctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02005671 struct channel *res = sc_ic(sc);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005672
5673 if (co_data(res)) {
Willy Tarreau3e7be362022-05-27 10:35:27 +02005674 sc_need_room(sc);
Christopher Fauleta2097962019-07-15 16:25:33 +02005675 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_start_response_yield, TICK_ETERNITY, 0));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005676 }
Christopher Fauleta2097962019-07-15 16:25:33 +02005677 return MAY_LJMP(hlua_applet_http_send_response(L));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005678}
5679
5680
Christopher Fauleta2097962019-07-15 16:25:33 +02005681__LJMP static int hlua_applet_http_start_response(lua_State *L)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005682{
Christopher Fauleta2097962019-07-15 16:25:33 +02005683 return MAY_LJMP(hlua_applet_http_start_response_yield(L, 0, 0));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005684}
5685
Christopher Fauleta2097962019-07-15 16:25:33 +02005686/*
5687 *
5688 *
5689 * Class HTTP
5690 *
5691 *
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005692 */
Christopher Fauleta2097962019-07-15 16:25:33 +02005693
5694/* Returns a struct hlua_txn if the stack entry "ud" is
5695 * a class stream, otherwise it throws an error.
5696 */
5697__LJMP static struct hlua_txn *hlua_checkhttp(lua_State *L, int ud)
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005698{
Christopher Fauleta2097962019-07-15 16:25:33 +02005699 return MAY_LJMP(hlua_checkudata(L, ud, class_http_ref));
5700}
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005701
Christopher Fauleta2097962019-07-15 16:25:33 +02005702/* This function creates and push in the stack a HTTP object
5703 * according with a current TXN.
5704 */
5705static int hlua_http_new(lua_State *L, struct hlua_txn *txn)
5706{
5707 struct hlua_txn *htxn;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005708
Christopher Fauleta2097962019-07-15 16:25:33 +02005709 /* Check stack size. */
5710 if (!lua_checkstack(L, 3))
5711 return 0;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005712
Christopher Fauleta2097962019-07-15 16:25:33 +02005713 /* Create the object: obj[0] = userdata.
5714 * Note that the base of the Converters object is the
5715 * same than the TXN object.
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005716 */
Christopher Fauleta2097962019-07-15 16:25:33 +02005717 lua_newtable(L);
5718 htxn = lua_newuserdata(L, sizeof(*htxn));
5719 lua_rawseti(L, -2, 0);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005720
5721 htxn->s = txn->s;
5722 htxn->p = txn->p;
Christopher Faulet256b69a2019-05-23 11:14:21 +02005723 htxn->dir = txn->dir;
5724 htxn->flags = txn->flags;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005725
5726 /* Pop a class stream metatable and affect it to the table. */
5727 lua_rawgeti(L, LUA_REGISTRYINDEX, class_http_ref);
5728 lua_setmetatable(L, -2);
5729
5730 return 1;
5731}
5732
Christopher Fauletdf97ac42020-02-26 16:57:19 +01005733/* This function creates and returns an array containing the status-line
5734 * elements. This function does not fails.
5735 */
5736__LJMP static int hlua_http_get_stline(lua_State *L, struct htx_sl *sl)
5737{
5738 /* Create the table. */
5739 lua_newtable(L);
5740
5741 if (sl->flags & HTX_SL_F_IS_RESP) {
5742 lua_pushstring(L, "version");
5743 lua_pushlstring(L, HTX_SL_RES_VPTR(sl), HTX_SL_RES_VLEN(sl));
5744 lua_settable(L, -3);
5745 lua_pushstring(L, "code");
5746 lua_pushlstring(L, HTX_SL_RES_CPTR(sl), HTX_SL_RES_CLEN(sl));
5747 lua_settable(L, -3);
5748 lua_pushstring(L, "reason");
5749 lua_pushlstring(L, HTX_SL_RES_RPTR(sl), HTX_SL_RES_RLEN(sl));
5750 lua_settable(L, -3);
5751 }
5752 else {
5753 lua_pushstring(L, "method");
5754 lua_pushlstring(L, HTX_SL_REQ_MPTR(sl), HTX_SL_REQ_MLEN(sl));
5755 lua_settable(L, -3);
5756 lua_pushstring(L, "uri");
5757 lua_pushlstring(L, HTX_SL_REQ_UPTR(sl), HTX_SL_REQ_ULEN(sl));
5758 lua_settable(L, -3);
5759 lua_pushstring(L, "version");
5760 lua_pushlstring(L, HTX_SL_REQ_VPTR(sl), HTX_SL_REQ_VLEN(sl));
5761 lua_settable(L, -3);
5762 }
5763 return 1;
5764}
5765
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005766/* This function creates ans returns an array of HTTP headers.
5767 * This function does not fails. It is used as wrapper with the
5768 * 2 following functions.
5769 */
Christopher Faulet9d1332b2020-02-24 16:46:16 +01005770__LJMP static int hlua_http_get_headers(lua_State *L, struct http_msg *msg)
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005771{
Christopher Fauleta2097962019-07-15 16:25:33 +02005772 struct htx *htx;
5773 int32_t pos;
5774
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005775 /* Create the table. */
5776 lua_newtable(L);
5777
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005778
Christopher Fauleta2097962019-07-15 16:25:33 +02005779 htx = htxbuf(&msg->chn->buf);
5780 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
5781 struct htx_blk *blk = htx_get_blk(htx, pos);
5782 enum htx_blk_type type = htx_get_blk_type(blk);
5783 struct ist n, v;
5784 int len;
Christopher Faulet724a12c2018-12-13 22:12:15 +01005785
Christopher Fauleta2097962019-07-15 16:25:33 +02005786 if (type == HTX_BLK_HDR) {
5787 n = htx_get_blk_name(htx,blk);
5788 v = htx_get_blk_value(htx, blk);
Christopher Faulet724a12c2018-12-13 22:12:15 +01005789 }
Christopher Fauleta2097962019-07-15 16:25:33 +02005790 else if (type == HTX_BLK_EOH)
5791 break;
5792 else
5793 continue;
Christopher Faulet724a12c2018-12-13 22:12:15 +01005794
Christopher Fauleta2097962019-07-15 16:25:33 +02005795 /* Check for existing entry:
5796 * assume that the table is on the top of the stack, and
5797 * push the key in the stack, the function lua_gettable()
5798 * perform the lookup.
5799 */
5800 lua_pushlstring(L, n.ptr, n.len);
5801 lua_gettable(L, -2);
Christopher Faulet724a12c2018-12-13 22:12:15 +01005802
Christopher Fauleta2097962019-07-15 16:25:33 +02005803 switch (lua_type(L, -1)) {
5804 case LUA_TNIL:
5805 /* Table not found, create it. */
5806 lua_pop(L, 1); /* remove the nil value. */
5807 lua_pushlstring(L, n.ptr, n.len); /* push the header name as key. */
5808 lua_newtable(L); /* create and push empty table. */
5809 lua_pushlstring(L, v.ptr, v.len); /* push header value. */
5810 lua_rawseti(L, -2, 0); /* index header value (pop it). */
5811 lua_rawset(L, -3); /* index new table with header name (pop the values). */
Christopher Faulet724a12c2018-12-13 22:12:15 +01005812 break;
Christopher Faulet724a12c2018-12-13 22:12:15 +01005813
Christopher Fauleta2097962019-07-15 16:25:33 +02005814 case LUA_TTABLE:
5815 /* Entry found: push the value in the table. */
5816 len = lua_rawlen(L, -1);
5817 lua_pushlstring(L, v.ptr, v.len); /* push header value. */
5818 lua_rawseti(L, -2, len+1); /* index header value (pop it). */
5819 lua_pop(L, 1); /* remove the table (it is stored in the main table). */
5820 break;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005821
Christopher Fauleta2097962019-07-15 16:25:33 +02005822 default:
5823 /* Other cases are errors. */
5824 hlua_pusherror(L, "internal error during the parsing of headers.");
5825 WILL_LJMP(lua_error(L));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005826 }
5827 }
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005828 return 1;
5829}
5830
5831__LJMP static int hlua_http_req_get_headers(lua_State *L)
5832{
5833 struct hlua_txn *htxn;
5834
5835 MAY_LJMP(check_args(L, 1, "req_get_headers"));
5836 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5837
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005838 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005839 WILL_LJMP(lua_error(L));
5840
Christopher Faulet9d1332b2020-02-24 16:46:16 +01005841 return hlua_http_get_headers(L, &htxn->s->txn->req);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005842}
5843
5844__LJMP static int hlua_http_res_get_headers(lua_State *L)
5845{
5846 struct hlua_txn *htxn;
5847
5848 MAY_LJMP(check_args(L, 1, "res_get_headers"));
5849 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5850
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005851 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005852 WILL_LJMP(lua_error(L));
5853
Christopher Faulet9d1332b2020-02-24 16:46:16 +01005854 return hlua_http_get_headers(L, &htxn->s->txn->rsp);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005855}
5856
5857/* This function replace full header, or just a value in
5858 * the request or in the response. It is a wrapper fir the
5859 * 4 following functions.
5860 */
Christopher Fauletd1914aa2020-02-24 16:52:46 +01005861__LJMP static inline int hlua_http_rep_hdr(lua_State *L, struct http_msg *msg, int full)
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005862{
5863 size_t name_len;
5864 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
5865 const char *reg = MAY_LJMP(luaL_checkstring(L, 3));
5866 const char *value = MAY_LJMP(luaL_checkstring(L, 4));
Christopher Fauleta2097962019-07-15 16:25:33 +02005867 struct htx *htx;
Dragan Dosen26743032019-04-30 15:54:36 +02005868 struct my_regex *re;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005869
Dragan Dosen26743032019-04-30 15:54:36 +02005870 if (!(re = regex_comp(reg, 1, 1, NULL)))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005871 WILL_LJMP(luaL_argerror(L, 3, "invalid regex"));
5872
Christopher Fauleta2097962019-07-15 16:25:33 +02005873 htx = htxbuf(&msg->chn->buf);
Christopher Fauletd1914aa2020-02-24 16:52:46 +01005874 http_replace_hdrs(chn_strm(msg->chn), htx, ist2(name, name_len), value, re, full);
Dragan Dosen26743032019-04-30 15:54:36 +02005875 regex_free(re);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005876 return 0;
5877}
5878
5879__LJMP static int hlua_http_req_rep_hdr(lua_State *L)
5880{
5881 struct hlua_txn *htxn;
5882
5883 MAY_LJMP(check_args(L, 4, "req_rep_hdr"));
5884 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5885
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005886 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005887 WILL_LJMP(lua_error(L));
5888
Christopher Fauletd1914aa2020-02-24 16:52:46 +01005889 return MAY_LJMP(hlua_http_rep_hdr(L, &htxn->s->txn->req, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005890}
5891
5892__LJMP static int hlua_http_res_rep_hdr(lua_State *L)
5893{
5894 struct hlua_txn *htxn;
5895
5896 MAY_LJMP(check_args(L, 4, "res_rep_hdr"));
5897 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5898
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005899 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005900 WILL_LJMP(lua_error(L));
5901
Christopher Fauletd1914aa2020-02-24 16:52:46 +01005902 return MAY_LJMP(hlua_http_rep_hdr(L, &htxn->s->txn->rsp, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005903}
5904
5905__LJMP static int hlua_http_req_rep_val(lua_State *L)
5906{
5907 struct hlua_txn *htxn;
5908
5909 MAY_LJMP(check_args(L, 4, "req_rep_hdr"));
5910 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5911
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005912 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005913 WILL_LJMP(lua_error(L));
5914
Christopher Fauletd1914aa2020-02-24 16:52:46 +01005915 return MAY_LJMP(hlua_http_rep_hdr(L, &htxn->s->txn->req, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005916}
5917
5918__LJMP static int hlua_http_res_rep_val(lua_State *L)
5919{
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005920 struct hlua_txn *htxn;
5921
5922 MAY_LJMP(check_args(L, 4, "res_rep_val"));
5923 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5924
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005925 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005926 WILL_LJMP(lua_error(L));
5927
Christopher Fauletd1914aa2020-02-24 16:52:46 +01005928 return MAY_LJMP(hlua_http_rep_hdr(L, &htxn->s->txn->rsp, 0));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005929}
5930
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08005931/* This function deletes all the occurrences of an header.
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005932 * It is a wrapper for the 2 following functions.
5933 */
Christopher Fauletd31c7b32020-02-25 09:37:57 +01005934__LJMP static inline int hlua_http_del_hdr(lua_State *L, struct http_msg *msg)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005935{
5936 size_t len;
5937 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Christopher Fauleta2097962019-07-15 16:25:33 +02005938 struct htx *htx = htxbuf(&msg->chn->buf);
5939 struct http_hdr_ctx ctx;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005940
Christopher Fauleta2097962019-07-15 16:25:33 +02005941 ctx.blk = NULL;
5942 while (http_find_header(htx, ist2(name, len), &ctx, 1))
5943 http_remove_header(htx, &ctx);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005944 return 0;
5945}
5946
5947__LJMP static int hlua_http_req_del_hdr(lua_State *L)
5948{
5949 struct hlua_txn *htxn;
5950
5951 MAY_LJMP(check_args(L, 2, "req_del_hdr"));
5952 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5953
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005954 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005955 WILL_LJMP(lua_error(L));
5956
Christopher Fauletd31c7b32020-02-25 09:37:57 +01005957 return hlua_http_del_hdr(L, &htxn->s->txn->req);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005958}
5959
5960__LJMP static int hlua_http_res_del_hdr(lua_State *L)
5961{
5962 struct hlua_txn *htxn;
5963
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005964 MAY_LJMP(check_args(L, 2, "res_del_hdr"));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005965 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5966
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005967 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005968 WILL_LJMP(lua_error(L));
5969
Christopher Fauletd31c7b32020-02-25 09:37:57 +01005970 return hlua_http_del_hdr(L, &htxn->s->txn->rsp);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005971}
5972
5973/* This function adds an header. It is a wrapper used by
5974 * the 2 following functions.
5975 */
Christopher Fauletd31c7b32020-02-25 09:37:57 +01005976__LJMP static inline int hlua_http_add_hdr(lua_State *L, struct http_msg *msg)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005977{
5978 size_t name_len;
5979 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
5980 size_t value_len;
5981 const char *value = MAY_LJMP(luaL_checklstring(L, 3, &value_len));
Christopher Fauleta2097962019-07-15 16:25:33 +02005982 struct htx *htx = htxbuf(&msg->chn->buf);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005983
Christopher Fauleta2097962019-07-15 16:25:33 +02005984 lua_pushboolean(L, http_add_header(htx, ist2(name, name_len),
5985 ist2(value, value_len)));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005986 return 0;
5987}
5988
Christopher Fauletdf97ac42020-02-26 16:57:19 +01005989__LJMP static int hlua_http_req_add_hdr(lua_State *L)
5990{
5991 struct hlua_txn *htxn;
5992
5993 MAY_LJMP(check_args(L, 3, "req_add_hdr"));
5994 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5995
5996 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
5997 WILL_LJMP(lua_error(L));
5998
5999 return hlua_http_add_hdr(L, &htxn->s->txn->req);
6000}
6001
6002__LJMP static int hlua_http_res_add_hdr(lua_State *L)
6003{
6004 struct hlua_txn *htxn;
6005
6006 MAY_LJMP(check_args(L, 3, "res_add_hdr"));
6007 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
6008
6009 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
6010 WILL_LJMP(lua_error(L));
6011
6012 return hlua_http_add_hdr(L, &htxn->s->txn->rsp);
6013}
6014
6015static int hlua_http_req_set_hdr(lua_State *L)
6016{
6017 struct hlua_txn *htxn;
6018
6019 MAY_LJMP(check_args(L, 3, "req_set_hdr"));
6020 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
6021
6022 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
6023 WILL_LJMP(lua_error(L));
6024
6025 hlua_http_del_hdr(L, &htxn->s->txn->req);
6026 return hlua_http_add_hdr(L, &htxn->s->txn->req);
6027}
6028
6029static int hlua_http_res_set_hdr(lua_State *L)
6030{
6031 struct hlua_txn *htxn;
6032
6033 MAY_LJMP(check_args(L, 3, "res_set_hdr"));
6034 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
6035
6036 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
6037 WILL_LJMP(lua_error(L));
6038
6039 hlua_http_del_hdr(L, &htxn->s->txn->rsp);
6040 return hlua_http_add_hdr(L, &htxn->s->txn->rsp);
6041}
6042
6043/* This function set the method. */
6044static int hlua_http_req_set_meth(lua_State *L)
6045{
6046 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
6047 size_t name_len;
6048 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
6049
6050 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
6051 WILL_LJMP(lua_error(L));
6052
6053 lua_pushboolean(L, http_req_replace_stline(0, name, name_len, htxn->p, htxn->s) != -1);
6054 return 1;
6055}
6056
6057/* This function set the method. */
6058static int hlua_http_req_set_path(lua_State *L)
6059{
6060 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
6061 size_t name_len;
6062 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
6063
6064 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
6065 WILL_LJMP(lua_error(L));
6066
6067 lua_pushboolean(L, http_req_replace_stline(1, name, name_len, htxn->p, htxn->s) != -1);
6068 return 1;
6069}
6070
6071/* This function set the query-string. */
6072static int hlua_http_req_set_query(lua_State *L)
6073{
6074 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
6075 size_t name_len;
6076 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
6077
6078 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
6079 WILL_LJMP(lua_error(L));
6080
6081 /* Check length. */
6082 if (name_len > trash.size - 1) {
6083 lua_pushboolean(L, 0);
6084 return 1;
6085 }
6086
6087 /* Add the mark question as prefix. */
6088 chunk_reset(&trash);
6089 trash.area[trash.data++] = '?';
6090 memcpy(trash.area + trash.data, name, name_len);
6091 trash.data += name_len;
6092
6093 lua_pushboolean(L,
6094 http_req_replace_stline(2, trash.area, trash.data, htxn->p, htxn->s) != -1);
6095 return 1;
6096}
6097
6098/* This function set the uri. */
6099static int hlua_http_req_set_uri(lua_State *L)
6100{
6101 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
6102 size_t name_len;
6103 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
6104
6105 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
6106 WILL_LJMP(lua_error(L));
6107
6108 lua_pushboolean(L, http_req_replace_stline(3, name, name_len, htxn->p, htxn->s) != -1);
6109 return 1;
6110}
6111
6112/* This function set the response code & optionally reason. */
6113static int hlua_http_res_set_status(lua_State *L)
6114{
6115 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
6116 unsigned int code = MAY_LJMP(luaL_checkinteger(L, 2));
6117 const char *str = MAY_LJMP(luaL_optlstring(L, 3, NULL, NULL));
6118 const struct ist reason = ist2(str, (str ? strlen(str) : 0));
6119
6120 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
6121 WILL_LJMP(lua_error(L));
6122
6123 http_res_set_status(code, reason, htxn->s);
6124 return 0;
6125}
6126
6127/*
6128 *
6129 *
6130 * Class HTTPMessage
6131 *
6132 *
6133 */
6134
6135/* Returns a struct http_msg if the stack entry "ud" is a class HTTPMessage,
6136 * otherwise it throws an error.
6137 */
6138__LJMP static struct http_msg *hlua_checkhttpmsg(lua_State *L, int ud)
6139{
6140 return MAY_LJMP(hlua_checkudata(L, ud, class_http_msg_ref));
6141}
6142
6143/* Creates and pushes on the stack a HTTP object according with a current TXN.
6144 */
Christopher Faulet78c35472020-02-26 17:14:08 +01006145static int hlua_http_msg_new(lua_State *L, struct http_msg *msg)
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006146{
6147 /* Check stack size. */
6148 if (!lua_checkstack(L, 3))
6149 return 0;
6150
6151 lua_newtable(L);
6152 lua_pushlightuserdata(L, msg);
6153 lua_rawseti(L, -2, 0);
6154
6155 /* Create the "channel" field that contains the request channel object. */
6156 lua_pushstring(L, "channel");
6157 if (!hlua_channel_new(L, msg->chn))
6158 return 0;
6159 lua_rawset(L, -3);
6160
6161 /* Pop a class stream metatable and affect it to the table. */
6162 lua_rawgeti(L, LUA_REGISTRYINDEX, class_http_msg_ref);
6163 lua_setmetatable(L, -2);
6164
6165 return 1;
6166}
6167
6168/* Helper function returning a filter attached to the HTTP message at the
6169 * position <ud> in the stack, filling the current offset and length of the
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006170 * filter. If no filter is attached, NULL is returned and <offset> and <len> are
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006171 * filled with output and input length respectively.
6172 */
6173static struct filter *hlua_http_msg_filter(lua_State *L, int ud, struct http_msg *msg, size_t *offset, size_t *len)
6174{
6175 struct channel *chn = msg->chn;
6176 struct htx *htx = htxbuf(&chn->buf);
6177 struct filter *filter = NULL;
6178
6179 *offset = co_data(msg->chn);
6180 *len = htx->data - co_data(msg->chn);
6181
6182 if (lua_getfield(L, ud, "__filter") == LUA_TLIGHTUSERDATA) {
6183 filter = lua_touserdata (L, -1);
6184 if (msg->msg_state >= HTTP_MSG_DATA) {
6185 struct hlua_flt_ctx *flt_ctx = filter->ctx;
6186
6187 *offset = flt_ctx->cur_off[CHN_IDX(chn)];
6188 *len = flt_ctx->cur_len[CHN_IDX(chn)];
6189 }
6190 }
6191
6192 lua_pop(L, 1);
6193 return filter;
6194}
6195
6196/* Returns true if the channel attached to the HTTP message is the response
6197 * channel.
6198 */
6199__LJMP static int hlua_http_msg_is_resp(lua_State *L)
6200{
6201 struct http_msg *msg;
6202
6203 MAY_LJMP(check_args(L, 1, "is_resp"));
6204 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6205
6206 lua_pushboolean(L, !!(msg->chn->flags & CF_ISRESP));
6207 return 1;
6208}
6209
6210/* Returns an array containing the elements status-line of the HTTP message. It relies
6211 * on hlua_http_get_stline().
6212 */
6213__LJMP static int hlua_http_msg_get_stline(lua_State *L)
6214{
6215 struct http_msg *msg;
6216 struct htx *htx;
6217 struct htx_sl *sl;
6218
6219 MAY_LJMP(check_args(L, 1, "get_stline"));
6220 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6221
6222 if (msg->msg_state > HTTP_MSG_BODY)
6223 WILL_LJMP(lua_error(L));
6224
6225 htx = htxbuf(&msg->chn->buf);
6226 sl = http_get_stline(htx);
6227 if (!sl)
6228 return 0;
6229 return hlua_http_get_stline(L, sl);
6230}
6231
6232/* Returns an array containing all headers of the HTTP message. it relies on
6233 * hlua_http_get_headers().
6234 */
6235__LJMP static int hlua_http_msg_get_headers(lua_State *L)
6236{
6237 struct http_msg *msg;
6238
6239 MAY_LJMP(check_args(L, 1, "get_headers"));
6240 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6241
6242 if (msg->msg_state > HTTP_MSG_BODY)
6243 WILL_LJMP(lua_error(L));
6244
6245 return hlua_http_get_headers(L, msg);
6246}
6247
6248/* Deletes all occurrences of an header in the HTTP message matching on its
6249 * name. It relies on hlua_http_del_hdr().
6250 */
6251__LJMP static int hlua_http_msg_del_hdr(lua_State *L)
6252{
6253 struct http_msg *msg;
6254
6255 MAY_LJMP(check_args(L, 2, "del_header"));
6256 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6257
6258 if (msg->msg_state > HTTP_MSG_BODY)
6259 WILL_LJMP(lua_error(L));
6260
6261 return hlua_http_del_hdr(L, msg);
6262}
6263
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006264/* Matches the full value line of all occurrences of an header in the HTTP
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006265 * message given its name against a regex and replaces it if it matches. It
6266 * relies on hlua_http_rep_hdr().
6267 */
6268__LJMP static int hlua_http_msg_rep_hdr(lua_State *L)
6269{
6270 struct http_msg *msg;
6271
6272 MAY_LJMP(check_args(L, 4, "rep_header"));
6273 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6274
6275 if (msg->msg_state > HTTP_MSG_BODY)
6276 WILL_LJMP(lua_error(L));
6277
6278 return hlua_http_rep_hdr(L, msg, 1);
6279}
6280
Ilya Shipitsinbd6b4be2021-10-15 16:18:21 +05006281/* Matches all comma-separated values of all occurrences of an header in the HTTP
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006282 * message given its name against a regex and replaces it if it matches. It
6283 * relies on hlua_http_rep_hdr().
6284 */
6285__LJMP static int hlua_http_msg_rep_val(lua_State *L)
6286{
6287 struct http_msg *msg;
6288
6289 MAY_LJMP(check_args(L, 4, "rep_value"));
6290 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6291
6292 if (msg->msg_state > HTTP_MSG_BODY)
6293 WILL_LJMP(lua_error(L));
6294
6295 return hlua_http_rep_hdr(L, msg, 0);
6296}
6297
6298/* Add an header in the HTTP message. It relies on hlua_http_add_hdr() */
6299__LJMP static int hlua_http_msg_add_hdr(lua_State *L)
6300{
6301 struct http_msg *msg;
6302
6303 MAY_LJMP(check_args(L, 3, "add_header"));
6304 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6305
6306 if (msg->msg_state > HTTP_MSG_BODY)
6307 WILL_LJMP(lua_error(L));
6308
6309 return hlua_http_add_hdr(L, msg);
6310}
6311
6312/* Add an header in the HTTP message removing existing headers with the same
6313 * name. It relies on hlua_http_del_hdr() and hlua_http_add_hdr().
6314 */
6315__LJMP static int hlua_http_msg_set_hdr(lua_State *L)
6316{
6317 struct http_msg *msg;
6318
6319 MAY_LJMP(check_args(L, 3, "set_header"));
6320 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6321
6322 if (msg->msg_state > HTTP_MSG_BODY)
6323 WILL_LJMP(lua_error(L));
6324
6325 hlua_http_del_hdr(L, msg);
6326 return hlua_http_add_hdr(L, msg);
6327}
6328
6329/* Rewrites the request method. It relies on http_req_replace_stline(). */
6330__LJMP static int hlua_http_msg_set_meth(lua_State *L)
6331{
6332 struct stream *s;
6333 struct http_msg *msg;
6334 const char *name;
6335 size_t name_len;
6336
6337 MAY_LJMP(check_args(L, 2, "set_method"));
6338 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6339 name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
6340
6341 if ((msg->chn->flags & CF_ISRESP) || msg->msg_state > HTTP_MSG_BODY)
6342 WILL_LJMP(lua_error(L));
6343
6344 s = chn_strm(msg->chn);
6345 lua_pushboolean(L, http_req_replace_stline(0, name, name_len, s->be, s) != -1);
6346 return 1;
6347}
6348
6349/* Rewrites the request path. It relies on http_req_replace_stline(). */
6350__LJMP static int hlua_http_msg_set_path(lua_State *L)
6351{
6352 struct stream *s;
6353 struct http_msg *msg;
6354 const char *name;
6355 size_t name_len;
6356
6357 MAY_LJMP(check_args(L, 2, "set_path"));
6358 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6359 name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
6360
6361 if ((msg->chn->flags & CF_ISRESP) || msg->msg_state > HTTP_MSG_BODY)
6362 WILL_LJMP(lua_error(L));
6363
6364 s = chn_strm(msg->chn);
6365 lua_pushboolean(L, http_req_replace_stline(1, name, name_len, s->be, s) != -1);
6366 return 1;
6367}
6368
6369/* Rewrites the request query-string. It relies on http_req_replace_stline(). */
6370__LJMP static int hlua_http_msg_set_query(lua_State *L)
6371{
6372 struct stream *s;
6373 struct http_msg *msg;
6374 const char *name;
6375 size_t name_len;
6376
6377 MAY_LJMP(check_args(L, 2, "set_query"));
6378 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6379 name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
6380
6381 if ((msg->chn->flags & CF_ISRESP) || msg->msg_state > HTTP_MSG_BODY)
6382 WILL_LJMP(lua_error(L));
6383
6384 /* Check length. */
6385 if (name_len > trash.size - 1) {
6386 lua_pushboolean(L, 0);
6387 return 1;
6388 }
6389
6390 /* Add the mark question as prefix. */
6391 chunk_reset(&trash);
6392 trash.area[trash.data++] = '?';
6393 memcpy(trash.area + trash.data, name, name_len);
6394 trash.data += name_len;
6395
6396 s = chn_strm(msg->chn);
6397 lua_pushboolean(L, http_req_replace_stline(2, trash.area, trash.data, s->be, s) != -1);
6398 return 1;
6399}
6400
6401/* Rewrites the request URI. It relies on http_req_replace_stline(). */
6402__LJMP static int hlua_http_msg_set_uri(lua_State *L)
6403{
6404 struct stream *s;
6405 struct http_msg *msg;
6406 const char *name;
6407 size_t name_len;
6408
6409 MAY_LJMP(check_args(L, 2, "set_uri"));
6410 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6411 name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
6412
6413 if ((msg->chn->flags & CF_ISRESP) || msg->msg_state > HTTP_MSG_BODY)
6414 WILL_LJMP(lua_error(L));
6415
6416 s = chn_strm(msg->chn);
6417 lua_pushboolean(L, http_req_replace_stline(3, name, name_len, s->be, s) != -1);
6418 return 1;
6419}
6420
6421/* Rewrites the response status code. It relies on http_res_set_status(). */
6422__LJMP static int hlua_http_msg_set_status(lua_State *L)
6423{
6424 struct http_msg *msg;
6425 unsigned int code;
6426 const char *reason;
6427 size_t reason_len;
6428
6429 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6430 code = MAY_LJMP(luaL_checkinteger(L, 2));
6431 reason = MAY_LJMP(luaL_optlstring(L, 3, NULL, &reason_len));
6432
6433 if (!(msg->chn->flags & CF_ISRESP) || msg->msg_state > HTTP_MSG_BODY)
6434 WILL_LJMP(lua_error(L));
6435
6436 lua_pushboolean(L, http_res_set_status(code, ist2(reason, reason_len), chn_strm(msg->chn)) != -1);
6437 return 1;
6438}
6439
6440/* Returns true if the HTTP message is full. */
6441__LJMP static int hlua_http_msg_is_full(lua_State *L)
6442{
6443 struct http_msg *msg;
6444
6445 MAY_LJMP(check_args(L, 1, "is_full"));
6446 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6447 lua_pushboolean(L, channel_full(msg->chn, 0));
6448 return 1;
6449}
6450
6451/* Returns true if the HTTP message may still receive data. */
6452__LJMP static int hlua_http_msg_may_recv(lua_State *L)
6453{
6454 struct http_msg *msg;
6455 struct htx *htx;
6456
6457 MAY_LJMP(check_args(L, 1, "may_recv"));
6458 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6459 htx = htxbuf(&msg->chn->buf);
6460 lua_pushboolean(L, (htx_expect_more(htx) && !channel_input_closed(msg->chn) && channel_may_recv(msg->chn)));
6461 return 1;
6462}
6463
6464/* Returns true if the HTTP message EOM was received */
6465__LJMP static int hlua_http_msg_is_eom(lua_State *L)
6466{
6467 struct http_msg *msg;
6468 struct htx *htx;
6469
6470 MAY_LJMP(check_args(L, 1, "may_recv"));
6471 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6472 htx = htxbuf(&msg->chn->buf);
6473 lua_pushboolean(L, !htx_expect_more(htx));
6474 return 1;
6475}
6476
6477/* Returns the number of bytes available in the input side of the HTTP
6478 * message. This function never fails.
6479 */
6480__LJMP static int hlua_http_msg_get_in_len(lua_State *L)
6481{
6482 struct http_msg *msg;
Christopher Fauleteae8afa2020-02-26 17:15:48 +01006483 size_t output, input;
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006484
6485 MAY_LJMP(check_args(L, 1, "input"));
6486 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
Christopher Fauleteae8afa2020-02-26 17:15:48 +01006487 hlua_http_msg_filter(L, 1, msg, &output, &input);
6488 lua_pushinteger(L, input);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006489 return 1;
6490}
6491
6492/* Returns the number of bytes available in the output side of the HTTP
6493 * message. This function never fails.
6494 */
6495__LJMP static int hlua_http_msg_get_out_len(lua_State *L)
6496{
6497 struct http_msg *msg;
Christopher Fauleteae8afa2020-02-26 17:15:48 +01006498 size_t output, input;
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006499
6500 MAY_LJMP(check_args(L, 1, "output"));
6501 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
Christopher Fauleteae8afa2020-02-26 17:15:48 +01006502 hlua_http_msg_filter(L, 1, msg, &output, &input);
6503 lua_pushinteger(L, output);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006504 return 1;
6505}
6506
6507/* Copies at most <len> bytes of DATA blocks from the HTTP message <msg>
6508 * starting at the offset <offset> and put it in a string LUA variables. It
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006509 * returns the built string length. It stops on the first non-DATA HTX
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006510 * block. This function is called during the payload filtering, so the headers
6511 * are already scheduled for output (from the filter point of view).
6512 */
6513static int _hlua_http_msg_dup(struct http_msg *msg, lua_State *L, size_t offset, size_t len)
6514{
6515 struct htx *htx = htxbuf(&msg->chn->buf);
6516 struct htx_blk *blk;
6517 struct htx_ret htxret;
6518 luaL_Buffer b;
6519 int ret = 0;
6520
6521 luaL_buffinit(L, &b);
6522 htxret = htx_find_offset(htx, offset);
6523 for (blk = htxret.blk, offset = htxret.ret; blk && len; blk = htx_get_next_blk(htx, blk)) {
6524 enum htx_blk_type type = htx_get_blk_type(blk);
6525 struct ist v;
6526
6527 switch (type) {
6528 case HTX_BLK_UNUSED:
6529 break;
6530
6531 case HTX_BLK_DATA:
6532 v = htx_get_blk_value(htx, blk);
Tim Duesterhusb113b5c2021-09-15 13:58:44 +02006533 v = istadv(v, offset);
Tim Duesterhus2471f5c2021-11-08 09:05:01 +01006534 v = isttrim(v, len);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006535
6536 luaL_addlstring(&b, v.ptr, v.len);
6537 ret += v.len;
6538 break;
6539
6540 default:
vishnu0af4bd72021-10-24 06:46:24 +05306541 if (!ret)
6542 goto no_data;
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006543 goto end;
6544 }
6545 offset = 0;
6546 }
6547
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006548end:
vishnu0af4bd72021-10-24 06:46:24 +05306549 if (!ret && (htx->flags & HTX_FL_EOM))
6550 goto no_data;
6551 luaL_pushresult(&b);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006552 return ret;
vishnu0af4bd72021-10-24 06:46:24 +05306553
6554 no_data:
6555 /* Remove the empty string and push nil on the stack */
6556 lua_pop(L, 1);
6557 lua_pushnil(L);
6558 return 0;
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006559}
6560
6561/* Copies the string <str> to the HTTP message <msg> at the offset
6562 * <offset>. This function returns -1 if data cannot be copied. Otherwise, it
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006563 * returns the amount of data written. This function is responsible to update
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006564 * the filter context.
6565 */
6566static int _hlua_http_msg_insert(struct http_msg *msg, struct filter *filter, struct ist str, size_t offset)
6567{
6568 struct htx *htx = htx_from_buf(&msg->chn->buf);
6569 struct htx_ret htxret;
6570 int /*max, */ret = 0;
6571
6572 /* Nothing to do, just return */
6573 if (unlikely(istlen(str) == 0))
6574 goto end;
6575
6576 if (istlen(str) > htx_free_data_space(htx)) {
6577 ret = -1;
6578 goto end;
6579 }
6580
6581 htxret = htx_find_offset(htx, offset);
6582 if (!htxret.blk || htx_get_blk_type(htxret.blk) != HTX_BLK_DATA) {
6583 if (!htx_add_last_data(htx, str))
6584 goto end;
6585 }
6586 else {
6587 struct ist v = htx_get_blk_value(htx, htxret.blk);
6588 v.ptr += htxret.ret;
6589 v.len = 0;
6590 if (!htx_replace_blk_value(htx, htxret.blk, v, str))
6591 goto end;
6592 }
6593 ret = str.len;
6594 if (ret) {
6595 struct hlua_flt_ctx *flt_ctx = filter->ctx;
6596 flt_update_offsets(filter, msg->chn, ret);
6597 flt_ctx->cur_len[CHN_IDX(msg->chn)] += ret;
6598 }
6599
6600 end:
6601 htx_to_buf(htx, &msg->chn->buf);
6602 return ret;
6603}
6604
6605/* Helper function removing at most <len> bytes of DATA blocks at the absolute
6606 * position <offset>. It stops on the first non-DATA HTX block. This function is
6607 * called during the payload filtering, so the headers are already scheduled for
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006608 * output (from the filter point of view). This function is responsible to
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006609 * update the filter context.
6610 */
6611static void _hlua_http_msg_delete(struct http_msg *msg, struct filter *filter, size_t offset, size_t len)
6612{
6613 struct hlua_flt_ctx *flt_ctx = filter->ctx;
6614 struct htx *htx = htx_from_buf(&msg->chn->buf);
6615 struct htx_blk *blk;
6616 struct htx_ret htxret;
6617 size_t ret = 0;
6618
6619 /* Be sure <len> is always the amount of DATA to remove */
6620 if (htx->data == offset+len && htx_get_tail_type(htx) == HTX_BLK_DATA) {
Aurelien DARRAGONbcbcf982022-09-28 19:08:15 +02006621 /* When htx tail type == HTX_BLK_DATA, no need to take care
6622 * of special blocks like HTX_BLK_EOT.
6623 * We simply truncate after offset
6624 * (truncate targeted blk and discard the following ones)
6625 */
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006626 htx_truncate(htx, offset);
6627 ret = len;
6628 goto end;
6629 }
6630
6631 htxret = htx_find_offset(htx, offset);
6632 blk = htxret.blk;
6633 if (htxret.ret) {
Aurelien DARRAGONbcbcf982022-09-28 19:08:15 +02006634 /* dealing with offset: we need to trim targeted blk */
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006635 struct ist v;
6636
6637 if (htx_get_blk_type(blk) != HTX_BLK_DATA)
6638 goto end;
Aurelien DARRAGONbcbcf982022-09-28 19:08:15 +02006639
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006640 v = htx_get_blk_value(htx, blk);
Tim Duesterhusa029d782022-10-08 12:33:18 +02006641 v = istadv(v, htxret.ret);
Aurelien DARRAGONbcbcf982022-09-28 19:08:15 +02006642
Tim Duesterhus2471f5c2021-11-08 09:05:01 +01006643 v = isttrim(v, len);
Aurelien DARRAGONbcbcf982022-09-28 19:08:15 +02006644 /* trimming data in blk: discard everything after the offset
6645 * (replace 'v' with 'IST_NULL')
6646 */
Tim Duesterhusb113b5c2021-09-15 13:58:44 +02006647 blk = htx_replace_blk_value(htx, blk, v, IST_NULL);
Aurelien DARRAGONbcbcf982022-09-28 19:08:15 +02006648 if (blk && v.len < len) {
6649 /* In this case, caller wants to keep removing data,
6650 * but we need to spare current blk
6651 * because it was already trimmed
6652 */
6653 blk = htx_get_next_blk(htx, blk);
6654 }
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006655 len -= v.len;
6656 ret += v.len;
6657 }
6658
6659
6660 while (blk && len) {
Aurelien DARRAGONbcbcf982022-09-28 19:08:15 +02006661 /* there is more data that needs to be discarded */
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006662 enum htx_blk_type type = htx_get_blk_type(blk);
6663 uint32_t sz = htx_get_blksz(blk);
6664
6665 switch (type) {
6666 case HTX_BLK_UNUSED:
6667 break;
6668
6669 case HTX_BLK_DATA:
6670 if (len < sz) {
Aurelien DARRAGONbcbcf982022-09-28 19:08:15 +02006671 /* don't discard whole blk, only part of it
6672 * (from the beginning)
6673 */
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006674 htx_cut_data_blk(htx, blk, len);
6675 ret += len;
6676 goto end;
6677 }
6678 break;
6679
6680 default:
Aurelien DARRAGONbcbcf982022-09-28 19:08:15 +02006681 /* HTX_BLK_EOT blk won't be removed */
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006682 goto end;
6683 }
6684
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006685 /* Remove all the data block */
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006686 len -= sz;
6687 ret += sz;
6688 blk = htx_remove_blk(htx, blk);
6689 }
6690
6691end:
6692 flt_update_offsets(filter, msg->chn, -ret);
6693 flt_ctx->cur_len[CHN_IDX(msg->chn)] -= ret;
6694 /* WARNING: we don't call htx_to_buf() on purpose, because we don't want
6695 * to loose the EOM flag if the message is empty.
6696 */
6697}
6698
6699/* Copies input data found in an HTTP message. Unlike the channel function used
6700 * to duplicate raw data, this one can only be called inside a filter, from
6701 * http_payload callback. So it cannot yield. An exception is returned if it is
6702 * called from another callback. If nothing was copied, a nil value is pushed on
6703 * the stack.
6704 */
6705__LJMP static int hlua_http_msg_get_body(lua_State *L)
6706{
6707 struct http_msg *msg;
6708 struct filter *filter;
6709 size_t output, input;
6710 int offset, len;
6711
6712 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
6713 WILL_LJMP(luaL_error(L, "'data' expects at most 2 arguments"));
6714 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6715
6716 if (msg->msg_state < HTTP_MSG_DATA)
6717 WILL_LJMP(lua_error(L));
6718
6719 filter = hlua_http_msg_filter(L, 1, msg, &output, &input);
6720 if (!filter || !hlua_filter_from_payload(filter))
6721 WILL_LJMP(lua_error(L));
6722
6723 if (!ci_data(msg->chn) && channel_input_closed(msg->chn)) {
6724 lua_pushnil(L);
6725 return 1;
6726 }
6727
6728 offset = output;
6729 if (lua_gettop(L) > 1) {
6730 offset = MAY_LJMP(luaL_checkinteger(L, 2));
6731 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02006732 offset = MAX(0, (int)input + offset);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006733 offset += output;
6734 if (offset < output || offset > input + output) {
6735 lua_pushfstring(L, "offset out of range.");
6736 WILL_LJMP(lua_error(L));
6737 }
6738 }
6739 len = output + input - offset;
6740 if (lua_gettop(L) == 3) {
6741 len = MAY_LJMP(luaL_checkinteger(L, 3));
6742 if (!len)
6743 goto dup;
6744 if (len == -1)
6745 len = global.tune.bufsize;
6746 if (len < 0) {
6747 lua_pushfstring(L, "length out of range.");
6748 WILL_LJMP(lua_error(L));
6749 }
6750 }
6751
6752 dup:
6753 _hlua_http_msg_dup(msg, L, offset, len);
6754 return 1;
6755}
6756
6757/* Appends a string to the HTTP message, after all existing DATA blocks but
6758 * before the trailers, if any. It returns the amount of data written or -1 if
6759 * nothing was copied. Unlike the channel function used to append data, this one
6760 * can only be called inside a filter, from http_payload callback. So it cannot
6761 * yield. An exception is returned if it is called from another callback.
6762 */
6763__LJMP static int hlua_http_msg_append(lua_State *L)
6764{
6765 struct http_msg *msg;
6766 struct filter *filter;
6767 const char *str;
6768 size_t offset, len, sz;
6769 int ret;
6770
6771 MAY_LJMP(check_args(L, 2, "append"));
6772 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6773
6774 if (msg->msg_state < HTTP_MSG_DATA)
6775 WILL_LJMP(lua_error(L));
6776
6777 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
6778 filter = hlua_http_msg_filter(L, 1, msg, &offset, &len);
6779 if (!filter || !hlua_filter_from_payload(filter))
6780 WILL_LJMP(lua_error(L));
6781
6782 ret = _hlua_http_msg_insert(msg, filter, ist2(str, sz), offset+len);
6783 lua_pushinteger(L, ret);
6784 return 1;
6785}
6786
6787/* Prepends a string to the HTTP message, before all existing DATA blocks. It
6788 * returns the amount of data written or -1 if nothing was copied. Unlike the
6789 * channel function used to prepend data, this one can only be called inside a
6790 * filter, from http_payload callback. So it cannot yield. An exception is
6791 * returned if it is called from another callback.
6792 */
6793__LJMP static int hlua_http_msg_prepend(lua_State *L)
6794{
6795 struct http_msg *msg;
6796 struct filter *filter;
6797 const char *str;
6798 size_t offset, len, sz;
6799 int ret;
6800
6801 MAY_LJMP(check_args(L, 2, "prepend"));
6802 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006803
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006804 if (msg->msg_state < HTTP_MSG_DATA)
6805 WILL_LJMP(lua_error(L));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006806
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006807 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
6808 filter = hlua_http_msg_filter(L, 1, msg, &offset, &len);
6809 if (!filter || !hlua_filter_from_payload(filter))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006810 WILL_LJMP(lua_error(L));
6811
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006812 ret = _hlua_http_msg_insert(msg, filter, ist2(str, sz), offset);
6813 lua_pushinteger(L, ret);
6814 return 1;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006815}
6816
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006817/* Inserts a string to the HTTP message at a given offset. By default the string
6818 * is appended at the end of DATA blocks. It returns the amount of data written
6819 * or -1 if nothing was copied. Unlike the channel function used to insert data,
6820 * this one can only be called inside a filter, from http_payload callback. So
6821 * it cannot yield. An exception is returned if it is called from another
6822 * callback.
6823 */
6824__LJMP static int hlua_http_msg_insert_data(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006825{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006826 struct http_msg *msg;
6827 struct filter *filter;
6828 const char *str;
6829 size_t input, output, sz;
6830 int offset;
6831 int ret;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006832
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006833 if (lua_gettop(L) < 2 || lua_gettop(L) > 3)
6834 WILL_LJMP(luaL_error(L, "'insert' expects at least 1 argument and at most 2 arguments"));
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006835 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006836
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006837 if (msg->msg_state < HTTP_MSG_DATA)
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006838 WILL_LJMP(lua_error(L));
6839
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006840 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
Aurelien DARRAGON7fdba0a2022-09-28 16:03:45 +02006841 filter = hlua_http_msg_filter(L, 1, msg, &output, &input);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006842 if (!filter || !hlua_filter_from_payload(filter))
6843 WILL_LJMP(lua_error(L));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006844
Aurelien DARRAGON7fdba0a2022-09-28 16:03:45 +02006845 offset = output;
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006846 if (lua_gettop(L) > 2) {
6847 offset = MAY_LJMP(luaL_checkinteger(L, 3));
6848 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02006849 offset = MAX(0, (int)input + offset);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006850 offset += output;
Aurelien DARRAGON7fdba0a2022-09-28 16:03:45 +02006851 if (offset > output + input) {
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006852 lua_pushfstring(L, "offset out of range.");
6853 WILL_LJMP(lua_error(L));
6854 }
6855 }
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006856
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006857 ret = _hlua_http_msg_insert(msg, filter, ist2(str, sz), offset);
6858 lua_pushinteger(L, ret);
6859 return 1;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006860}
6861
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006862/* Removes a given amount of data from the HTTP message at a given offset. By
6863 * default all DATA blocks are removed. It returns the amount of data
6864 * removed. Unlike the channel function used to remove data, this one can only
6865 * be called inside a filter, from http_payload callback. So it cannot yield. An
6866 * exception is returned if it is called from another callback.
6867 */
6868__LJMP static int hlua_http_msg_del_data(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006869{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006870 struct http_msg *msg;
6871 struct filter *filter;
6872 size_t input, output;
6873 int offset, len;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006874
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006875 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
Boyang Lie0c54352022-05-10 17:47:23 +00006876 WILL_LJMP(luaL_error(L, "'remove' expects at most 2 arguments"));
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006877 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006878
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006879 if (msg->msg_state < HTTP_MSG_DATA)
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006880 WILL_LJMP(lua_error(L));
6881
Aurelien DARRAGONd7c71b02022-09-28 15:52:18 +02006882 filter = hlua_http_msg_filter(L, 1, msg, &output, &input);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006883 if (!filter || !hlua_filter_from_payload(filter))
6884 WILL_LJMP(lua_error(L));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006885
Aurelien DARRAGONd7c71b02022-09-28 15:52:18 +02006886 offset = output;
Boyang Lie0c54352022-05-10 17:47:23 +00006887 if (lua_gettop(L) > 1) {
6888 offset = MAY_LJMP(luaL_checkinteger(L, 2));
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006889 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02006890 offset = MAX(0, (int)input + offset);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006891 offset += output;
Aurelien DARRAGONd7c71b02022-09-28 15:52:18 +02006892 if (offset > output + input) {
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006893 lua_pushfstring(L, "offset out of range.");
6894 WILL_LJMP(lua_error(L));
6895 }
6896 }
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006897
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006898 len = output + input - offset;
Boyang Lie0c54352022-05-10 17:47:23 +00006899 if (lua_gettop(L) == 3) {
6900 len = MAY_LJMP(luaL_checkinteger(L, 3));
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006901 if (!len)
6902 goto end;
6903 if (len == -1)
6904 len = output + input - offset;
6905 if (len < 0 || offset + len > output + input) {
6906 lua_pushfstring(L, "length out of range.");
6907 WILL_LJMP(lua_error(L));
6908 }
6909 }
6910
6911 _hlua_http_msg_delete(msg, filter, offset, len);
6912
6913 end:
6914 lua_pushinteger(L, len);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006915 return 1;
6916}
6917
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006918/* Replaces a given amount of data at the given offset by a string. By default,
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006919 * all remaining data are removed, accordingly to the filter context. It returns
6920 * the amount of data written or -1 if nothing was copied. Unlike the channel
6921 * function used to replace data, this one can only be called inside a filter,
6922 * from http_payload callback. So it cannot yield. An exception is returned if
6923 * it is called from another callback.
6924 */
6925__LJMP static int hlua_http_msg_set_data(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006926{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006927 struct http_msg *msg;
6928 struct filter *filter;
6929 struct htx *htx;
6930 const char *str;
6931 size_t input, output, sz;
6932 int offset, len;
6933 int ret;
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02006934
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006935 if (lua_gettop(L) < 2 || lua_gettop(L) > 4)
6936 WILL_LJMP(luaL_error(L, "'set' expects at least 1 argument and at most 3 arguments"));
6937 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6938
6939 if (msg->msg_state < HTTP_MSG_DATA)
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006940 WILL_LJMP(lua_error(L));
6941
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006942 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
6943 filter = hlua_http_msg_filter(L, 1, msg, &output, &input);
6944 if (!filter || !hlua_filter_from_payload(filter))
6945 WILL_LJMP(lua_error(L));
6946
6947 offset = output;
6948 if (lua_gettop(L) > 2) {
6949 offset = MAY_LJMP(luaL_checkinteger(L, 3));
6950 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02006951 offset = MAX(0, (int)input + offset);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006952 offset += output;
6953 if (offset < output || offset > input + output) {
6954 lua_pushfstring(L, "offset out of range.");
6955 WILL_LJMP(lua_error(L));
6956 }
6957 }
6958
6959 len = output + input - offset;
6960 if (lua_gettop(L) == 4) {
6961 len = MAY_LJMP(luaL_checkinteger(L, 4));
6962 if (!len)
6963 goto set;
6964 if (len == -1)
6965 len = output + input - offset;
6966 if (len < 0 || offset + len > output + input) {
6967 lua_pushfstring(L, "length out of range.");
6968 WILL_LJMP(lua_error(L));
6969 }
6970 }
6971
6972 set:
6973 /* Be sure we can copied the string once input data will be removed. */
6974 htx = htx_from_buf(&msg->chn->buf);
6975 if (sz > htx_free_data_space(htx) + len)
6976 lua_pushinteger(L, -1);
6977 else {
6978 _hlua_http_msg_delete(msg, filter, offset, len);
6979 ret = _hlua_http_msg_insert(msg, filter, ist2(str, sz), offset);
6980 lua_pushinteger(L, ret);
6981 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006982 return 1;
6983}
6984
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006985/* Prepends data into an HTTP message and forward it, from the filter point of
6986 * view. It returns the amount of data written or -1 if nothing was sent. Unlike
6987 * the channel function used to send data, this one can only be called inside a
6988 * filter, from http_payload callback. So it cannot yield. An exception is
6989 * returned if it is called from another callback.
6990 */
6991__LJMP static int hlua_http_msg_send(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006992{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006993 struct http_msg *msg;
6994 struct filter *filter;
6995 struct htx *htx;
6996 const char *str;
6997 size_t offset, len, sz;
6998 int ret;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006999
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007000 MAY_LJMP(check_args(L, 2, "send"));
7001 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
7002
7003 if (msg->msg_state < HTTP_MSG_DATA)
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02007004 WILL_LJMP(lua_error(L));
7005
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007006 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
7007 filter = hlua_http_msg_filter(L, 1, msg, &offset, &len);
7008 if (!filter || !hlua_filter_from_payload(filter))
7009 WILL_LJMP(lua_error(L));
7010
7011 /* Return an error if the channel's output is closed */
7012 if (unlikely(channel_output_closed(msg->chn))) {
7013 lua_pushinteger(L, -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007014 return 1;
7015 }
7016
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007017 htx = htx_from_buf(&msg->chn->buf);
7018 if (sz > htx_free_data_space(htx)) {
7019 lua_pushinteger(L, -1);
7020 return 1;
7021 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007022
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007023 ret = _hlua_http_msg_insert(msg, filter, ist2(str, sz), offset);
7024 if (ret > 0) {
7025 struct hlua_flt_ctx *flt_ctx = filter->ctx;
7026
7027 FLT_OFF(filter, msg->chn) += ret;
7028 flt_ctx->cur_len[CHN_IDX(msg->chn)] -= ret;
7029 flt_ctx->cur_off[CHN_IDX(msg->chn)] += ret;
7030 }
7031
7032 lua_pushinteger(L, ret);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007033 return 1;
7034}
7035
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007036/* Forwards a given amount of bytes. It return -1 if the channel's output is
7037 * closed. Otherwise, it returns the number of bytes forwarded. Unlike the
7038 * channel function used to forward data, this one can only be called inside a
7039 * filter, from http_payload callback. So it cannot yield. An exception is
7040 * returned if it is called from another callback. All other functions deal with
7041 * DATA block, this one not.
7042*/
7043__LJMP static int hlua_http_msg_forward(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007044{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007045 struct http_msg *msg;
7046 struct filter *filter;
7047 size_t offset, len;
7048 int fwd, ret = 0;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007049
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007050 MAY_LJMP(check_args(L, 2, "forward"));
7051 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
7052
7053 if (msg->msg_state < HTTP_MSG_DATA)
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02007054 WILL_LJMP(lua_error(L));
7055
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007056 fwd = MAY_LJMP(luaL_checkinteger(L, 2));
7057 filter = hlua_http_msg_filter(L, 1, msg, &offset, &len);
7058 if (!filter || !hlua_filter_from_payload(filter))
7059 WILL_LJMP(lua_error(L));
7060
7061 /* Nothing to do, just return */
7062 if (!fwd)
7063 goto end;
7064
7065 /* Return an error if the channel's output is closed */
7066 if (unlikely(channel_output_closed(msg->chn))) {
7067 ret = -1;
7068 goto end;
7069 }
7070
7071 ret = fwd;
7072 if (ret > len)
7073 ret = len;
7074
7075 if (ret) {
7076 struct hlua_flt_ctx *flt_ctx = filter->ctx;
7077
7078 FLT_OFF(filter, msg->chn) += ret;
7079 flt_ctx->cur_off[CHN_IDX(msg->chn)] += ret;
7080 flt_ctx->cur_len[CHN_IDX(msg->chn)] -= ret;
7081 }
7082
7083 end:
7084 lua_pushinteger(L, ret);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007085 return 1;
7086}
7087
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007088/* Set EOM flag on the HTX message.
7089 *
7090 * NOTE: Not sure it is a good idea to manipulate this flag but for now I don't
7091 * really know how to do without this feature.
7092 */
7093__LJMP static int hlua_http_msg_set_eom(lua_State *L)
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02007094{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007095 struct http_msg *msg;
7096 struct htx *htx;
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02007097
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007098 MAY_LJMP(check_args(L, 1, "set_eom"));
7099 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
7100 htx = htxbuf(&msg->chn->buf);
7101 htx->flags |= HTX_FL_EOM;
7102 return 0;
7103}
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02007104
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007105/* Unset EOM flag on the HTX message.
7106 *
7107 * NOTE: Not sure it is a good idea to manipulate this flag but for now I don't
7108 * really know how to do without this feature.
7109 */
7110__LJMP static int hlua_http_msg_unset_eom(lua_State *L)
7111{
7112 struct http_msg *msg;
7113 struct htx *htx;
7114
7115 MAY_LJMP(check_args(L, 1, "set_eom"));
7116 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
7117 htx = htxbuf(&msg->chn->buf);
7118 htx->flags &= ~HTX_FL_EOM;
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02007119 return 0;
7120}
7121
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007122/*
7123 *
7124 *
William Lallemand3956c4e2021-09-21 16:25:15 +02007125 * Class HTTPClient
7126 *
7127 *
7128 */
7129__LJMP static struct hlua_httpclient *hlua_checkhttpclient(lua_State *L, int ud)
7130{
7131 return MAY_LJMP(hlua_checkudata(L, ud, class_httpclient_ref));
7132}
7133
William Lallemandf77f1de2021-09-28 19:10:38 +02007134
7135/* stops the httpclient and ask it to kill itself */
7136__LJMP static int hlua_httpclient_gc(lua_State *L)
7137{
7138 struct hlua_httpclient *hlua_hc;
7139
7140 MAY_LJMP(check_args(L, 1, "__gc"));
7141
7142 hlua_hc = MAY_LJMP(hlua_checkhttpclient(L, 1));
7143
Aurelien DARRAGON3ffbf382023-02-09 17:02:57 +01007144 if (MT_LIST_DELETE(&hlua_hc->by_hlua)) {
7145 /* we won the race against hlua_httpclient_destroy_all() */
William Lallemandbb581422022-10-20 10:57:28 +02007146 httpclient_stop_and_destroy(hlua_hc->hc);
Aurelien DARRAGON3ffbf382023-02-09 17:02:57 +01007147 hlua_hc->hc = NULL;
7148 }
William Lallemandf77f1de2021-09-28 19:10:38 +02007149
7150 return 0;
7151}
7152
7153
William Lallemand3956c4e2021-09-21 16:25:15 +02007154__LJMP static int hlua_httpclient_new(lua_State *L)
7155{
7156 struct hlua_httpclient *hlua_hc;
7157 struct hlua *hlua;
7158
7159 /* Get hlua struct, or NULL if we execute from main lua state */
7160 hlua = hlua_gethlua(L);
7161 if (!hlua)
7162 return 0;
7163
7164 /* Check stack size. */
7165 if (!lua_checkstack(L, 3)) {
7166 hlua_pusherror(L, "httpclient: full stack");
7167 goto err;
7168 }
7169 /* Create the object: obj[0] = userdata. */
7170 lua_newtable(L);
7171 hlua_hc = MAY_LJMP(lua_newuserdata(L, sizeof(*hlua_hc)));
7172 lua_rawseti(L, -2, 0);
7173 memset(hlua_hc, 0, sizeof(*hlua_hc));
7174
7175 hlua_hc->hc = httpclient_new(hlua, 0, IST_NULL);
7176 if (!hlua_hc->hc)
7177 goto err;
7178
Aurelien DARRAGON3ffbf382023-02-09 17:02:57 +01007179 MT_LIST_APPEND(&hlua->hc_list, &hlua_hc->by_hlua);
William Lallemandbb581422022-10-20 10:57:28 +02007180
William Lallemand3956c4e2021-09-21 16:25:15 +02007181 /* Pop a class stream metatable and affect it to the userdata. */
7182 lua_rawgeti(L, LUA_REGISTRYINDEX, class_httpclient_ref);
7183 lua_setmetatable(L, -2);
7184
7185 return 1;
7186
7187 err:
7188 WILL_LJMP(lua_error(L));
7189 return 0;
7190}
7191
7192
7193/*
7194 * Callback of the httpclient, this callback wakes the lua task up, once the
7195 * httpclient receives some data
7196 *
7197 */
7198
William Lallemandbd5739e2021-10-28 15:41:38 +02007199static void hlua_httpclient_cb(struct httpclient *hc)
William Lallemand3956c4e2021-09-21 16:25:15 +02007200{
7201 struct hlua *hlua = hc->caller;
7202
7203 if (!hlua || !hlua->task)
7204 return;
7205
7206 task_wakeup(hlua->task, TASK_WOKEN_MSG);
7207}
7208
7209/*
William Lallemandd7df73a2021-09-23 17:54:00 +02007210 * Fill the lua stack with headers from the httpclient response
7211 * This works the same way as the hlua_http_get_headers() function
7212 */
7213__LJMP static int hlua_httpclient_get_headers(lua_State *L, struct hlua_httpclient *hlua_hc)
7214{
7215 struct http_hdr *hdr;
7216
7217 lua_newtable(L);
7218
William Lallemandef574b22021-10-05 16:19:31 +02007219 for (hdr = hlua_hc->hc->res.hdrs; hdr && isttest(hdr->n); hdr++) {
William Lallemandd7df73a2021-09-23 17:54:00 +02007220 struct ist n, v;
7221 int len;
7222
7223 n = hdr->n;
7224 v = hdr->v;
7225
7226 /* Check for existing entry:
7227 * assume that the table is on the top of the stack, and
7228 * push the key in the stack, the function lua_gettable()
7229 * perform the lookup.
7230 */
7231
7232 lua_pushlstring(L, n.ptr, n.len);
7233 lua_gettable(L, -2);
7234
7235 switch (lua_type(L, -1)) {
7236 case LUA_TNIL:
7237 /* Table not found, create it. */
7238 lua_pop(L, 1); /* remove the nil value. */
7239 lua_pushlstring(L, n.ptr, n.len); /* push the header name as key. */
7240 lua_newtable(L); /* create and push empty table. */
7241 lua_pushlstring(L, v.ptr, v.len); /* push header value. */
7242 lua_rawseti(L, -2, 0); /* index header value (pop it). */
7243 lua_rawset(L, -3); /* index new table with header name (pop the values). */
7244 break;
7245
7246 case LUA_TTABLE:
7247 /* Entry found: push the value in the table. */
7248 len = lua_rawlen(L, -1);
7249 lua_pushlstring(L, v.ptr, v.len); /* push header value. */
7250 lua_rawseti(L, -2, len+1); /* index header value (pop it). */
7251 lua_pop(L, 1); /* remove the table (it is stored in the main table). */
7252 break;
7253
7254 default:
7255 /* Other cases are errors. */
7256 hlua_pusherror(L, "internal error during the parsing of headers.");
7257 WILL_LJMP(lua_error(L));
7258 }
7259 }
7260 return 1;
7261}
7262
7263/*
William Lallemand746e6f32021-10-06 10:57:44 +02007264 * Allocate and return an array of http_hdr ist extracted from the <headers> lua table
7265 *
7266 * Caller must free the result
7267 */
7268struct http_hdr *hlua_httpclient_table_to_hdrs(lua_State *L)
7269{
7270 struct http_hdr hdrs[global.tune.max_http_hdr];
7271 struct http_hdr *result = NULL;
7272 uint32_t hdr_num = 0;
7273
7274 lua_pushnil(L);
7275 while (lua_next(L, -2) != 0) {
7276 struct ist name, value;
7277 const char *n, *v;
7278 size_t nlen, vlen;
7279
7280 if (!lua_isstring(L, -2) || !lua_istable(L, -1)) {
7281 /* Skip element if the key is not a string or if the value is not a table */
7282 goto next_hdr;
7283 }
7284
7285 n = lua_tolstring(L, -2, &nlen);
7286 name = ist2(n, nlen);
7287
7288 /* Loop on header's values */
7289 lua_pushnil(L);
7290 while (lua_next(L, -2)) {
7291 if (!lua_isstring(L, -1)) {
7292 /* Skip the value if it is not a string */
7293 goto next_value;
7294 }
7295
7296 v = lua_tolstring(L, -1, &vlen);
7297 value = ist2(v, vlen);
7298 name = ist2(n, nlen);
7299
7300 hdrs[hdr_num].n = istdup(name);
7301 hdrs[hdr_num].v = istdup(value);
7302
7303 hdr_num++;
7304
7305 next_value:
7306 lua_pop(L, 1);
7307 }
7308
7309 next_hdr:
7310 lua_pop(L, 1);
7311
7312 }
7313
7314 if (hdr_num) {
7315 /* alloc and copy the headers in the httpclient struct */
Tim Duesterhus16cc16d2021-11-06 15:14:45 +01007316 result = calloc((hdr_num + 1), sizeof(*result));
William Lallemand746e6f32021-10-06 10:57:44 +02007317 if (!result)
7318 goto skip_headers;
7319 memcpy(result, hdrs, sizeof(struct http_hdr) * (hdr_num + 1));
7320
7321 result[hdr_num].n = IST_NULL;
7322 result[hdr_num].v = IST_NULL;
7323 }
7324
7325skip_headers:
William Lallemand746e6f32021-10-06 10:57:44 +02007326
7327 return result;
7328}
7329
7330
William Lallemandbd5739e2021-10-28 15:41:38 +02007331/*
7332 * For each yield, checks if there is some data in the httpclient and push them
7333 * in the lua buffer, once the httpclient finished its job, push the result on
7334 * the stack
7335 */
7336__LJMP static int hlua_httpclient_rcv_yield(lua_State *L, int status, lua_KContext ctx)
7337{
7338 struct buffer *tr;
7339 int res;
7340 struct hlua *hlua = hlua_gethlua(L);
7341 struct hlua_httpclient *hlua_hc = hlua_checkhttpclient(L, 1);
7342
7343
7344 tr = get_trash_chunk();
7345
7346 res = httpclient_res_xfer(hlua_hc->hc, tr);
7347 luaL_addlstring(&hlua_hc->b, b_orig(tr), res);
7348
7349 if (!httpclient_data(hlua_hc->hc) && httpclient_ended(hlua_hc->hc)) {
7350
7351 luaL_pushresult(&hlua_hc->b);
7352 lua_settable(L, -3);
7353
7354 lua_pushstring(L, "status");
7355 lua_pushinteger(L, hlua_hc->hc->res.status);
7356 lua_settable(L, -3);
7357
7358
7359 lua_pushstring(L, "reason");
7360 lua_pushlstring(L, hlua_hc->hc->res.reason.ptr, hlua_hc->hc->res.reason.len);
7361 lua_settable(L, -3);
7362
7363 lua_pushstring(L, "headers");
7364 hlua_httpclient_get_headers(L, hlua_hc);
7365 lua_settable(L, -3);
7366
7367 return 1;
7368 }
7369
7370 if (httpclient_data(hlua_hc->hc))
7371 task_wakeup(hlua->task, TASK_WOKEN_MSG);
7372
7373 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_httpclient_rcv_yield, TICK_ETERNITY, 0));
7374
7375 return 0;
7376}
7377
7378/*
7379 * Call this when trying to stream a body during a request
7380 */
7381__LJMP static int hlua_httpclient_snd_yield(lua_State *L, int status, lua_KContext ctx)
7382{
7383 struct hlua *hlua;
7384 struct hlua_httpclient *hlua_hc = hlua_checkhttpclient(L, 1);
7385 const char *body_str = NULL;
7386 int ret;
7387 int end = 0;
7388 size_t buf_len;
7389 size_t to_send = 0;
7390
7391 hlua = hlua_gethlua(L);
7392
7393 if (!hlua || !hlua->task)
7394 WILL_LJMP(luaL_error(L, "The 'get' function is only allowed in "
7395 "'frontend', 'backend' or 'task'"));
7396
7397 ret = lua_getfield(L, -1, "body");
7398 if (ret != LUA_TSTRING)
7399 goto rcv;
7400
7401 body_str = lua_tolstring(L, -1, &buf_len);
7402 lua_pop(L, 1);
7403
Christopher Fauletfc591292022-01-12 14:46:03 +01007404 to_send = buf_len - hlua_hc->sent;
William Lallemandbd5739e2021-10-28 15:41:38 +02007405
7406 if ((hlua_hc->sent + to_send) >= buf_len)
7407 end = 1;
7408
7409 /* the end flag is always set since we are using the whole remaining size */
7410 hlua_hc->sent += httpclient_req_xfer(hlua_hc->hc, ist2(body_str + hlua_hc->sent, to_send), end);
7411
7412 if (buf_len > hlua_hc->sent) {
7413 /* still need to process the buffer */
7414 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_httpclient_snd_yield, TICK_ETERNITY, 0));
7415 } else {
7416 goto rcv;
7417 /* we sent the whole request buffer we can recv */
7418 }
7419 return 0;
7420
7421rcv:
7422
7423 /* we return a "res" object */
7424 lua_newtable(L);
7425
William Lallemandbd5739e2021-10-28 15:41:38 +02007426 lua_pushstring(L, "body");
William Lallemandd1187eb2021-11-02 10:40:06 +01007427 luaL_buffinit(L, &hlua_hc->b);
William Lallemandbd5739e2021-10-28 15:41:38 +02007428
William Lallemand933fe392021-11-04 09:45:58 +01007429 task_wakeup(hlua->task, TASK_WOKEN_MSG);
William Lallemandbd5739e2021-10-28 15:41:38 +02007430 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_httpclient_rcv_yield, TICK_ETERNITY, 0));
7431
7432 return 1;
7433}
William Lallemand746e6f32021-10-06 10:57:44 +02007434
William Lallemand3956c4e2021-09-21 16:25:15 +02007435/*
William Lallemanddc2cc902021-10-26 11:43:26 +02007436 * Send an HTTP request and wait for a response
William Lallemand3956c4e2021-09-21 16:25:15 +02007437 */
7438
William Lallemanddc2cc902021-10-26 11:43:26 +02007439__LJMP static int hlua_httpclient_send(lua_State *L, enum http_meth_t meth)
William Lallemand3956c4e2021-09-21 16:25:15 +02007440{
7441 struct hlua_httpclient *hlua_hc;
William Lallemand746e6f32021-10-06 10:57:44 +02007442 struct http_hdr *hdrs = NULL;
7443 struct http_hdr *hdrs_i = NULL;
William Lallemand3956c4e2021-09-21 16:25:15 +02007444 struct hlua *hlua;
William Lallemand746e6f32021-10-06 10:57:44 +02007445 const char *url_str = NULL;
William Lallemanddec25c32021-10-25 19:48:37 +02007446 const char *body_str = NULL;
Christopher Faulet380ae9c2022-10-14 14:57:04 +02007447 size_t buf_len = 0;
William Lallemand746e6f32021-10-06 10:57:44 +02007448 int ret;
William Lallemand3956c4e2021-09-21 16:25:15 +02007449
7450 hlua = hlua_gethlua(L);
7451
7452 if (!hlua || !hlua->task)
7453 WILL_LJMP(luaL_error(L, "The 'get' function is only allowed in "
7454 "'frontend', 'backend' or 'task'"));
7455
William Lallemand746e6f32021-10-06 10:57:44 +02007456 if (lua_gettop(L) != 2 || lua_type(L, -1) != LUA_TTABLE)
7457 WILL_LJMP(luaL_error(L, "'get' needs a table as argument"));
7458
William Lallemand4f4f2b72022-02-17 20:00:23 +01007459 hlua_hc = hlua_checkhttpclient(L, 1);
7460
William Lallemand7177a952022-03-03 15:33:12 +01007461 lua_pushnil(L); /* first key */
7462 while (lua_next(L, 2)) {
7463 if (strcmp(lua_tostring(L, -2), "dst") == 0) {
7464 if (httpclient_set_dst(hlua_hc->hc, lua_tostring(L, -1)) < 0)
7465 WILL_LJMP(luaL_error(L, "Can't use the 'dst' argument"));
William Lallemand4f4f2b72022-02-17 20:00:23 +01007466
William Lallemand7177a952022-03-03 15:33:12 +01007467 } else if (strcmp(lua_tostring(L, -2), "url") == 0) {
7468 if (lua_type(L, -1) != LUA_TSTRING)
7469 WILL_LJMP(luaL_error(L, "invalid parameter in 'url', must be a string"));
7470 url_str = lua_tostring(L, -1);
William Lallemand3956c4e2021-09-21 16:25:15 +02007471
William Lallemand7177a952022-03-03 15:33:12 +01007472 } else if (strcmp(lua_tostring(L, -2), "timeout") == 0) {
7473 if (lua_type(L, -1) != LUA_TNUMBER)
7474 WILL_LJMP(luaL_error(L, "invalid parameter in 'timeout', must be a number"));
7475 httpclient_set_timeout(hlua_hc->hc, lua_tointeger(L, -1));
William Lallemandb4a4ef62022-02-23 14:18:16 +01007476
William Lallemand7177a952022-03-03 15:33:12 +01007477 } else if (strcmp(lua_tostring(L, -2), "headers") == 0) {
7478 if (lua_type(L, -1) != LUA_TTABLE)
7479 WILL_LJMP(luaL_error(L, "invalid parameter in 'headers', must be a table"));
7480 hdrs = hlua_httpclient_table_to_hdrs(L);
William Lallemand79416cb2021-09-24 14:51:44 +02007481
William Lallemand7177a952022-03-03 15:33:12 +01007482 } else if (strcmp(lua_tostring(L, -2), "body") == 0) {
7483 if (lua_type(L, -1) != LUA_TSTRING)
7484 WILL_LJMP(luaL_error(L, "invalid parameter in 'body', must be a string"));
7485 body_str = lua_tolstring(L, -1, &buf_len);
William Lallemandbd5739e2021-10-28 15:41:38 +02007486
William Lallemand7177a952022-03-03 15:33:12 +01007487 } else {
7488 WILL_LJMP(luaL_error(L, "'%s' invalid parameter name", lua_tostring(L, -2)));
7489 }
7490 /* removes 'value'; keeps 'key' for next iteration */
7491 lua_pop(L, 1);
7492 }
William Lallemanddec25c32021-10-25 19:48:37 +02007493
William Lallemand746e6f32021-10-06 10:57:44 +02007494 if (!url_str) {
7495 WILL_LJMP(luaL_error(L, "'get' need a 'url' argument"));
7496 return 0;
7497 }
William Lallemand3956c4e2021-09-21 16:25:15 +02007498
William Lallemand10a37362022-03-02 16:18:26 +01007499 hlua_hc->sent = 0;
William Lallemand3956c4e2021-09-21 16:25:15 +02007500
Aurelien DARRAGON03564072023-02-09 15:26:25 +01007501 istfree(&hlua_hc->hc->req.url);
William Lallemand3956c4e2021-09-21 16:25:15 +02007502 hlua_hc->hc->req.url = istdup(ist(url_str));
William Lallemanddc2cc902021-10-26 11:43:26 +02007503 hlua_hc->hc->req.meth = meth;
William Lallemand3956c4e2021-09-21 16:25:15 +02007504
7505 /* update the httpclient callbacks */
William Lallemandbd5739e2021-10-28 15:41:38 +02007506 hlua_hc->hc->ops.res_stline = hlua_httpclient_cb;
7507 hlua_hc->hc->ops.res_headers = hlua_httpclient_cb;
7508 hlua_hc->hc->ops.res_payload = hlua_httpclient_cb;
William Lallemand8f170c72022-03-15 10:52:07 +01007509 hlua_hc->hc->ops.res_end = hlua_httpclient_cb;
William Lallemand3956c4e2021-09-21 16:25:15 +02007510
William Lallemandbd5739e2021-10-28 15:41:38 +02007511 /* a body is available, it will use the request callback */
Christopher Faulet380ae9c2022-10-14 14:57:04 +02007512 if (body_str && buf_len) {
William Lallemandbd5739e2021-10-28 15:41:38 +02007513 hlua_hc->hc->ops.req_payload = hlua_httpclient_cb;
7514 }
William Lallemand3956c4e2021-09-21 16:25:15 +02007515
William Lallemandbd5739e2021-10-28 15:41:38 +02007516 ret = httpclient_req_gen(hlua_hc->hc, hlua_hc->hc->req.url, meth, hdrs, IST_NULL);
William Lallemand3956c4e2021-09-21 16:25:15 +02007517
William Lallemand746e6f32021-10-06 10:57:44 +02007518 /* free the temporary headers array */
7519 hdrs_i = hdrs;
7520 while (hdrs_i && isttest(hdrs_i->n)) {
7521 istfree(&hdrs_i->n);
7522 istfree(&hdrs_i->v);
7523 hdrs_i++;
7524 }
7525 ha_free(&hdrs);
7526
7527
William Lallemand6137a9e2021-10-26 15:01:53 +02007528 if (ret != ERR_NONE) {
7529 WILL_LJMP(luaL_error(L, "Can't generate the HTTP request"));
7530 return 0;
7531 }
7532
William Lallemandc2d3db42022-04-26 11:46:13 +02007533 if (!httpclient_start(hlua_hc->hc))
7534 WILL_LJMP(luaL_error(L, "couldn't start the httpclient"));
William Lallemand6137a9e2021-10-26 15:01:53 +02007535
William Lallemandbd5739e2021-10-28 15:41:38 +02007536 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_httpclient_snd_yield, TICK_ETERNITY, 0));
William Lallemand3956c4e2021-09-21 16:25:15 +02007537
William Lallemand3956c4e2021-09-21 16:25:15 +02007538 return 0;
7539}
7540
7541/*
William Lallemanddc2cc902021-10-26 11:43:26 +02007542 * Sends an HTTP HEAD request and wait for a response
7543 *
7544 * httpclient:head(url, headers, payload)
7545 */
7546__LJMP static int hlua_httpclient_head(lua_State *L)
7547{
7548 return hlua_httpclient_send(L, HTTP_METH_HEAD);
7549}
7550
7551/*
7552 * Send an HTTP GET request and wait for a response
7553 *
7554 * httpclient:get(url, headers, payload)
7555 */
7556__LJMP static int hlua_httpclient_get(lua_State *L)
7557{
7558 return hlua_httpclient_send(L, HTTP_METH_GET);
7559
7560}
7561
7562/*
7563 * Sends an HTTP PUT request and wait for a response
7564 *
7565 * httpclient:put(url, headers, payload)
7566 */
7567__LJMP static int hlua_httpclient_put(lua_State *L)
7568{
7569 return hlua_httpclient_send(L, HTTP_METH_PUT);
7570}
7571
7572/*
7573 * Send an HTTP POST request and wait for a response
7574 *
7575 * httpclient:post(url, headers, payload)
7576 */
7577__LJMP static int hlua_httpclient_post(lua_State *L)
7578{
7579 return hlua_httpclient_send(L, HTTP_METH_POST);
7580}
7581
7582
7583/*
7584 * Sends an HTTP DELETE request and wait for a response
7585 *
7586 * httpclient:delete(url, headers, payload)
7587 */
7588__LJMP static int hlua_httpclient_delete(lua_State *L)
7589{
7590 return hlua_httpclient_send(L, HTTP_METH_DELETE);
7591}
7592
7593/*
William Lallemand3956c4e2021-09-21 16:25:15 +02007594 *
7595 *
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007596 * Class TXN
7597 *
7598 *
7599 */
7600
7601/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02007602 * a class stream, otherwise it throws an error.
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007603 */
7604__LJMP static struct hlua_txn *hlua_checktxn(lua_State *L, int ud)
7605{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02007606 return MAY_LJMP(hlua_checkudata(L, ud, class_txn_ref));
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007607}
7608
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007609__LJMP static int hlua_set_var(lua_State *L)
7610{
7611 struct hlua_txn *htxn;
7612 const char *name;
7613 size_t len;
7614 struct sample smp;
7615
Tim Duesterhus4e172c92020-05-19 13:49:42 +02007616 if (lua_gettop(L) < 3 || lua_gettop(L) > 4)
7617 WILL_LJMP(luaL_error(L, "'set_var' needs between 3 and 4 arguments"));
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007618
7619 /* It is useles to retrieve the stream, but this function
7620 * runs only in a stream context.
7621 */
7622 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7623 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
7624
7625 /* Converts the third argument in a sample. */
Amaury Denoyellebc0af6a2020-10-29 17:21:20 +01007626 memset(&smp, 0, sizeof(smp));
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007627 hlua_lua2smp(L, 3, &smp);
7628
7629 /* Store the sample in a variable. */
Willy Tarreau7560dd42016-03-10 16:28:58 +01007630 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
Tim Duesterhus4e172c92020-05-19 13:49:42 +02007631
7632 if (lua_gettop(L) == 4 && lua_toboolean(L, 4))
7633 lua_pushboolean(L, vars_set_by_name_ifexist(name, len, &smp) != 0);
7634 else
7635 lua_pushboolean(L, vars_set_by_name(name, len, &smp) != 0);
7636
Tim Duesterhus84ebc132020-05-19 13:49:41 +02007637 return 1;
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007638}
7639
Christopher Faulet85d79c92016-11-09 16:54:56 +01007640__LJMP static int hlua_unset_var(lua_State *L)
7641{
7642 struct hlua_txn *htxn;
7643 const char *name;
7644 size_t len;
7645 struct sample smp;
7646
7647 MAY_LJMP(check_args(L, 2, "unset_var"));
7648
7649 /* It is useles to retrieve the stream, but this function
7650 * runs only in a stream context.
7651 */
7652 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7653 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
7654
7655 /* Unset the variable. */
7656 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
Tim Duesterhus84ebc132020-05-19 13:49:41 +02007657 lua_pushboolean(L, vars_unset_by_name_ifexist(name, len, &smp) != 0);
7658 return 1;
Christopher Faulet85d79c92016-11-09 16:54:56 +01007659}
7660
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007661__LJMP static int hlua_get_var(lua_State *L)
7662{
7663 struct hlua_txn *htxn;
7664 const char *name;
7665 size_t len;
7666 struct sample smp;
7667
7668 MAY_LJMP(check_args(L, 2, "get_var"));
7669
7670 /* It is useles to retrieve the stream, but this function
7671 * runs only in a stream context.
7672 */
7673 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7674 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
7675
Willy Tarreau7560dd42016-03-10 16:28:58 +01007676 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
Willy Tarreaue352b9d2021-09-03 11:52:38 +02007677 if (!vars_get_by_name(name, len, &smp, NULL)) {
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007678 lua_pushnil(L);
7679 return 1;
7680 }
7681
7682 return hlua_smp2lua(L, &smp);
7683}
7684
Willy Tarreau59551662015-03-10 14:23:13 +01007685__LJMP static int hlua_set_priv(lua_State *L)
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007686{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007687 struct hlua *hlua;
7688
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007689 MAY_LJMP(check_args(L, 2, "set_priv"));
7690
Willy Tarreau87b09662015-04-03 00:22:06 +02007691 /* It is useles to retrieve the stream, but this function
7692 * runs only in a stream context.
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007693 */
7694 MAY_LJMP(hlua_checktxn(L, 1));
Thierry Fournier4234dbd2020-11-28 13:18:23 +01007695
7696 /* Get hlua struct, or NULL if we execute from main lua state */
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007697 hlua = hlua_gethlua(L);
Thierry Fournier4234dbd2020-11-28 13:18:23 +01007698 if (!hlua)
7699 return 0;
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007700
7701 /* Remove previous value. */
Thierry FOURNIERe068b602017-04-26 13:27:05 +02007702 luaL_unref(L, LUA_REGISTRYINDEX, hlua->Mref);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007703
7704 /* Get and store new value. */
7705 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
7706 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
7707
7708 return 0;
7709}
7710
Willy Tarreau59551662015-03-10 14:23:13 +01007711__LJMP static int hlua_get_priv(lua_State *L)
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007712{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007713 struct hlua *hlua;
7714
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007715 MAY_LJMP(check_args(L, 1, "get_priv"));
7716
Willy Tarreau87b09662015-04-03 00:22:06 +02007717 /* It is useles to retrieve the stream, but this function
7718 * runs only in a stream context.
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007719 */
7720 MAY_LJMP(hlua_checktxn(L, 1));
Thierry Fournier4234dbd2020-11-28 13:18:23 +01007721
7722 /* Get hlua struct, or NULL if we execute from main lua state */
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007723 hlua = hlua_gethlua(L);
Thierry Fournier4234dbd2020-11-28 13:18:23 +01007724 if (!hlua) {
7725 lua_pushnil(L);
7726 return 1;
7727 }
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007728
7729 /* Push configuration index in the stack. */
7730 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
7731
7732 return 1;
7733}
7734
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007735/* Create stack entry containing a class TXN. This function
7736 * return 0 if the stack does not contains free slots,
7737 * otherwise it returns 1.
7738 */
Thierry FOURNIERab00df62016-07-14 11:42:37 +02007739static int hlua_txn_new(lua_State *L, struct stream *s, struct proxy *p, int dir, int flags)
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007740{
Willy Tarreaude491382015-04-06 11:04:28 +02007741 struct hlua_txn *htxn;
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007742
7743 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01007744 if (!lua_checkstack(L, 3))
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007745 return 0;
7746
7747 /* NOTE: The allocation never fails. The failure
7748 * throw an error, and the function never returns.
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08007749 * if the throw is not available, the process is aborted.
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007750 */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01007751 /* Create the object: obj[0] = userdata. */
7752 lua_newtable(L);
Willy Tarreaude491382015-04-06 11:04:28 +02007753 htxn = lua_newuserdata(L, sizeof(*htxn));
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01007754 lua_rawseti(L, -2, 0);
7755
Willy Tarreaude491382015-04-06 11:04:28 +02007756 htxn->s = s;
7757 htxn->p = p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01007758 htxn->dir = dir;
Thierry FOURNIERab00df62016-07-14 11:42:37 +02007759 htxn->flags = flags;
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007760
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01007761 /* Create the "f" field that contains a list of fetches. */
7762 lua_pushstring(L, "f");
Thierry FOURNIERca988662015-12-20 18:43:03 +01007763 if (!hlua_fetches_new(L, htxn, HLUA_F_MAY_USE_HTTP))
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01007764 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007765 lua_rawset(L, -3);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01007766
7767 /* Create the "sf" field that contains a list of stringsafe fetches. */
7768 lua_pushstring(L, "sf");
Thierry FOURNIERca988662015-12-20 18:43:03 +01007769 if (!hlua_fetches_new(L, htxn, HLUA_F_MAY_USE_HTTP | HLUA_F_AS_STRING))
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01007770 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007771 lua_rawset(L, -3);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01007772
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007773 /* Create the "c" field that contains a list of converters. */
7774 lua_pushstring(L, "c");
Willy Tarreaude491382015-04-06 11:04:28 +02007775 if (!hlua_converters_new(L, htxn, 0))
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01007776 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007777 lua_rawset(L, -3);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01007778
7779 /* Create the "sc" field that contains a list of stringsafe converters. */
7780 lua_pushstring(L, "sc");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01007781 if (!hlua_converters_new(L, htxn, HLUA_F_AS_STRING))
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007782 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007783 lua_rawset(L, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007784
Thierry FOURNIER397826a2015-03-11 19:39:09 +01007785 /* Create the "req" field that contains the request channel object. */
7786 lua_pushstring(L, "req");
Willy Tarreau2a71af42015-03-10 13:51:50 +01007787 if (!hlua_channel_new(L, &s->req))
Thierry FOURNIER397826a2015-03-11 19:39:09 +01007788 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007789 lua_rawset(L, -3);
Thierry FOURNIER397826a2015-03-11 19:39:09 +01007790
7791 /* Create the "res" field that contains the response channel object. */
7792 lua_pushstring(L, "res");
Willy Tarreau2a71af42015-03-10 13:51:50 +01007793 if (!hlua_channel_new(L, &s->res))
Thierry FOURNIER397826a2015-03-11 19:39:09 +01007794 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007795 lua_rawset(L, -3);
Thierry FOURNIER397826a2015-03-11 19:39:09 +01007796
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007797 /* Creates the HTTP object is the current proxy allows http. */
7798 lua_pushstring(L, "http");
Christopher Faulet1bb6afa2021-03-08 17:57:53 +01007799 if (IS_HTX_STRM(s)) {
Willy Tarreaude491382015-04-06 11:04:28 +02007800 if (!hlua_http_new(L, htxn))
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007801 return 0;
7802 }
7803 else
7804 lua_pushnil(L);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007805 lua_rawset(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007806
Christopher Faulet78c35472020-02-26 17:14:08 +01007807 if ((htxn->flags & HLUA_TXN_CTX_MASK) == HLUA_TXN_FLT_CTX) {
7808 /* HTTPMessage object are created when a lua TXN is created from
7809 * a filter context only
7810 */
7811
7812 /* Creates the HTTP-Request object is the current proxy allows http. */
7813 lua_pushstring(L, "http_req");
7814 if (p->mode == PR_MODE_HTTP) {
7815 if (!hlua_http_msg_new(L, &s->txn->req))
7816 return 0;
7817 }
7818 else
7819 lua_pushnil(L);
7820 lua_rawset(L, -3);
7821
7822 /* Creates the HTTP-Response object is the current proxy allows http. */
7823 lua_pushstring(L, "http_res");
7824 if (p->mode == PR_MODE_HTTP) {
7825 if (!hlua_http_msg_new(L, &s->txn->rsp))
7826 return 0;
7827 }
7828 else
7829 lua_pushnil(L);
7830 lua_rawset(L, -3);
7831 }
7832
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007833 /* Pop a class sesison metatable and affect it to the userdata. */
7834 lua_rawgeti(L, LUA_REGISTRYINDEX, class_txn_ref);
7835 lua_setmetatable(L, -2);
7836
7837 return 1;
7838}
7839
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01007840__LJMP static int hlua_txn_deflog(lua_State *L)
7841{
7842 const char *msg;
7843 struct hlua_txn *htxn;
7844
7845 MAY_LJMP(check_args(L, 2, "deflog"));
7846 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7847 msg = MAY_LJMP(luaL_checkstring(L, 2));
7848
7849 hlua_sendlog(htxn->s->be, htxn->s->logs.level, msg);
7850 return 0;
7851}
7852
7853__LJMP static int hlua_txn_log(lua_State *L)
7854{
7855 int level;
7856 const char *msg;
7857 struct hlua_txn *htxn;
7858
7859 MAY_LJMP(check_args(L, 3, "log"));
7860 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7861 level = MAY_LJMP(luaL_checkinteger(L, 2));
7862 msg = MAY_LJMP(luaL_checkstring(L, 3));
7863
7864 if (level < 0 || level >= NB_LOG_LEVELS)
7865 WILL_LJMP(luaL_argerror(L, 1, "Invalid loglevel."));
7866
7867 hlua_sendlog(htxn->s->be, level, msg);
7868 return 0;
7869}
7870
7871__LJMP static int hlua_txn_log_debug(lua_State *L)
7872{
7873 const char *msg;
7874 struct hlua_txn *htxn;
7875
7876 MAY_LJMP(check_args(L, 2, "Debug"));
7877 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7878 msg = MAY_LJMP(luaL_checkstring(L, 2));
7879 hlua_sendlog(htxn->s->be, LOG_DEBUG, msg);
7880 return 0;
7881}
7882
7883__LJMP static int hlua_txn_log_info(lua_State *L)
7884{
7885 const char *msg;
7886 struct hlua_txn *htxn;
7887
7888 MAY_LJMP(check_args(L, 2, "Info"));
7889 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7890 msg = MAY_LJMP(luaL_checkstring(L, 2));
7891 hlua_sendlog(htxn->s->be, LOG_INFO, msg);
7892 return 0;
7893}
7894
7895__LJMP static int hlua_txn_log_warning(lua_State *L)
7896{
7897 const char *msg;
7898 struct hlua_txn *htxn;
7899
7900 MAY_LJMP(check_args(L, 2, "Warning"));
7901 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7902 msg = MAY_LJMP(luaL_checkstring(L, 2));
7903 hlua_sendlog(htxn->s->be, LOG_WARNING, msg);
7904 return 0;
7905}
7906
7907__LJMP static int hlua_txn_log_alert(lua_State *L)
7908{
7909 const char *msg;
7910 struct hlua_txn *htxn;
7911
7912 MAY_LJMP(check_args(L, 2, "Alert"));
7913 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7914 msg = MAY_LJMP(luaL_checkstring(L, 2));
7915 hlua_sendlog(htxn->s->be, LOG_ALERT, msg);
7916 return 0;
7917}
7918
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01007919__LJMP static int hlua_txn_set_loglevel(lua_State *L)
7920{
7921 struct hlua_txn *htxn;
7922 int ll;
7923
7924 MAY_LJMP(check_args(L, 2, "set_loglevel"));
7925 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7926 ll = MAY_LJMP(luaL_checkinteger(L, 2));
7927
7928 if (ll < 0 || ll > 7)
7929 WILL_LJMP(luaL_argerror(L, 2, "Bad log level. It must be between 0 and 7"));
7930
7931 htxn->s->logs.level = ll;
7932 return 0;
7933}
7934
7935__LJMP static int hlua_txn_set_tos(lua_State *L)
7936{
7937 struct hlua_txn *htxn;
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01007938 int tos;
7939
7940 MAY_LJMP(check_args(L, 2, "set_tos"));
7941 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7942 tos = MAY_LJMP(luaL_checkinteger(L, 2));
7943
Willy Tarreau1a18b542018-12-11 16:37:42 +01007944 conn_set_tos(objt_conn(htxn->s->sess->origin), tos);
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01007945 return 0;
7946}
7947
7948__LJMP static int hlua_txn_set_mark(lua_State *L)
7949{
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01007950 struct hlua_txn *htxn;
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01007951 int mark;
7952
7953 MAY_LJMP(check_args(L, 2, "set_mark"));
7954 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7955 mark = MAY_LJMP(luaL_checkinteger(L, 2));
7956
Lukas Tribus579e3e32019-08-11 18:03:45 +02007957 conn_set_mark(objt_conn(htxn->s->sess->origin), mark);
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01007958 return 0;
7959}
7960
Patrick Hemmer268a7072018-05-11 12:52:31 -04007961__LJMP static int hlua_txn_set_priority_class(lua_State *L)
7962{
7963 struct hlua_txn *htxn;
7964
7965 MAY_LJMP(check_args(L, 2, "set_priority_class"));
7966 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7967 htxn->s->priority_class = queue_limit_class(MAY_LJMP(luaL_checkinteger(L, 2)));
7968 return 0;
7969}
7970
7971__LJMP static int hlua_txn_set_priority_offset(lua_State *L)
7972{
7973 struct hlua_txn *htxn;
7974
7975 MAY_LJMP(check_args(L, 2, "set_priority_offset"));
7976 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7977 htxn->s->priority_offset = queue_limit_offset(MAY_LJMP(luaL_checkinteger(L, 2)));
7978 return 0;
7979}
7980
Christopher Faulet700d9e82020-01-31 12:21:52 +01007981/* Forward the Reply object to the client. This function converts the reply in
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05007982 * HTX an push it to into the response channel. It is response to forward the
Christopher Faulet700d9e82020-01-31 12:21:52 +01007983 * message and terminate the transaction. It returns 1 on success and 0 on
7984 * error. The Reply must be on top of the stack.
7985 */
7986__LJMP static int hlua_txn_forward_reply(lua_State *L, struct stream *s)
7987{
7988 struct htx *htx;
7989 struct htx_sl *sl;
7990 struct h1m h1m;
7991 const char *status, *reason, *body;
7992 size_t status_len, reason_len, body_len;
7993 int ret, code, flags;
7994
7995 code = 200;
7996 status = "200";
7997 status_len = 3;
7998 ret = lua_getfield(L, -1, "status");
7999 if (ret == LUA_TNUMBER) {
8000 code = lua_tointeger(L, -1);
8001 status = lua_tolstring(L, -1, &status_len);
8002 }
8003 lua_pop(L, 1);
8004
8005 reason = http_get_reason(code);
8006 reason_len = strlen(reason);
8007 ret = lua_getfield(L, -1, "reason");
8008 if (ret == LUA_TSTRING)
8009 reason = lua_tolstring(L, -1, &reason_len);
8010 lua_pop(L, 1);
8011
8012 body = NULL;
8013 body_len = 0;
8014 ret = lua_getfield(L, -1, "body");
8015 if (ret == LUA_TSTRING)
8016 body = lua_tolstring(L, -1, &body_len);
8017 lua_pop(L, 1);
8018
8019 /* Prepare the response before inserting the headers */
8020 h1m_init_res(&h1m);
8021 htx = htx_from_buf(&s->res.buf);
8022 channel_htx_truncate(&s->res, htx);
8023 if (s->txn->req.flags & HTTP_MSGF_VER_11) {
8024 flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11);
8025 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.1"),
8026 ist2(status, status_len), ist2(reason, reason_len));
8027 }
8028 else {
8029 flags = HTX_SL_F_IS_RESP;
8030 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.0"),
8031 ist2(status, status_len), ist2(reason, reason_len));
8032 }
8033 if (!sl)
8034 goto fail;
8035 sl->info.res.status = code;
8036
8037 /* Push in the stack the "headers" entry. */
8038 ret = lua_getfield(L, -1, "headers");
8039 if (ret != LUA_TTABLE)
8040 goto skip_headers;
8041
8042 lua_pushnil(L);
8043 while (lua_next(L, -2) != 0) {
8044 struct ist name, value;
8045 const char *n, *v;
8046 size_t nlen, vlen;
8047
8048 if (!lua_isstring(L, -2) || !lua_istable(L, -1)) {
8049 /* Skip element if the key is not a string or if the value is not a table */
8050 goto next_hdr;
8051 }
8052
8053 n = lua_tolstring(L, -2, &nlen);
8054 name = ist2(n, nlen);
8055 if (isteqi(name, ist("content-length"))) {
8056 /* Always skip content-length header. It will be added
8057 * later with the correct len
8058 */
8059 goto next_hdr;
8060 }
8061
8062 /* Loop on header's values */
8063 lua_pushnil(L);
8064 while (lua_next(L, -2)) {
8065 if (!lua_isstring(L, -1)) {
8066 /* Skip the value if it is not a string */
8067 goto next_value;
8068 }
8069
8070 v = lua_tolstring(L, -1, &vlen);
8071 value = ist2(v, vlen);
8072
8073 if (isteqi(name, ist("transfer-encoding")))
8074 h1_parse_xfer_enc_header(&h1m, value);
8075 if (!htx_add_header(htx, ist2(n, nlen), ist2(v, vlen)))
8076 goto fail;
8077
8078 next_value:
8079 lua_pop(L, 1);
8080 }
8081
8082 next_hdr:
8083 lua_pop(L, 1);
8084 }
8085 skip_headers:
8086 lua_pop(L, 1);
8087
8088 /* Update h1m flags: CLEN is set if CHNK is not present */
8089 if (!(h1m.flags & H1_MF_CHNK)) {
8090 const char *clen = ultoa(body_len);
8091
8092 h1m.flags |= H1_MF_CLEN;
8093 if (!htx_add_header(htx, ist("content-length"), ist(clen)))
8094 goto fail;
8095 }
8096 if (h1m.flags & (H1_MF_CLEN|H1_MF_CHNK))
8097 h1m.flags |= H1_MF_XFER_LEN;
8098
8099 /* Update HTX start-line flags */
8100 if (h1m.flags & H1_MF_XFER_ENC)
8101 flags |= HTX_SL_F_XFER_ENC;
8102 if (h1m.flags & H1_MF_XFER_LEN) {
8103 flags |= HTX_SL_F_XFER_LEN;
8104 if (h1m.flags & H1_MF_CHNK)
8105 flags |= HTX_SL_F_CHNK;
8106 else if (h1m.flags & H1_MF_CLEN)
8107 flags |= HTX_SL_F_CLEN;
8108 if (h1m.body_len == 0)
8109 flags |= HTX_SL_F_BODYLESS;
8110 }
8111 sl->flags |= flags;
8112
8113
8114 if (!htx_add_endof(htx, HTX_BLK_EOH) ||
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01008115 (body_len && !htx_add_data_atonce(htx, ist2(body, body_len))))
Christopher Faulet700d9e82020-01-31 12:21:52 +01008116 goto fail;
8117
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01008118 htx->flags |= HTX_FL_EOM;
8119
Christopher Faulet700d9e82020-01-31 12:21:52 +01008120 /* Now, forward the response and terminate the transaction */
8121 s->txn->status = code;
8122 htx_to_buf(htx, &s->res.buf);
8123 if (!http_forward_proxy_resp(s, 1))
8124 goto fail;
8125
8126 return 1;
8127
8128 fail:
8129 channel_htx_truncate(&s->res, htx);
8130 return 0;
8131}
8132
8133/* Terminate a transaction if called from a lua action. For TCP streams,
8134 * processing is just aborted. Nothing is returned to the client and all
8135 * arguments are ignored. For HTTP streams, if a reply is passed as argument, it
8136 * is forwarded to the client before terminating the transaction. On success,
8137 * the function exits with ACT_RET_DONE code. If an error occurred, it exits
8138 * with ACT_RET_ERR code. If this function is not called from a lua action, it
8139 * just exits without any processing.
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01008140 */
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02008141__LJMP static int hlua_txn_done(lua_State *L)
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01008142{
Willy Tarreaub2ccb562015-04-06 11:11:15 +02008143 struct hlua_txn *htxn;
Christopher Faulet700d9e82020-01-31 12:21:52 +01008144 struct stream *s;
8145 int finst;
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01008146
Willy Tarreaub2ccb562015-04-06 11:11:15 +02008147 htxn = MAY_LJMP(hlua_checktxn(L, 1));
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01008148
Christopher Faulet700d9e82020-01-31 12:21:52 +01008149 /* If the flags NOTERM is set, we cannot terminate the session, so we
8150 * just end the execution of the current lua code. */
8151 if (htxn->flags & HLUA_TXN_NOTERM)
Thierry FOURNIERab00df62016-07-14 11:42:37 +02008152 WILL_LJMP(hlua_done(L));
Thierry FOURNIERab00df62016-07-14 11:42:37 +02008153
Christopher Faulet700d9e82020-01-31 12:21:52 +01008154 s = htxn->s;
Christopher Fauletd8f0e072020-02-25 09:45:51 +01008155 if (!IS_HTX_STRM(htxn->s)) {
Christopher Faulet700d9e82020-01-31 12:21:52 +01008156 struct channel *req = &s->req;
8157 struct channel *res = &s->res;
Willy Tarreau81389672015-03-10 12:03:52 +01008158
Christopher Faulet700d9e82020-01-31 12:21:52 +01008159 channel_auto_read(req);
8160 channel_abort(req);
8161 channel_auto_close(req);
8162 channel_erase(req);
8163
Christopher Faulet700d9e82020-01-31 12:21:52 +01008164 channel_auto_read(res);
8165 channel_auto_close(res);
8166 channel_shutr_now(res);
8167
8168 finst = ((htxn->dir == SMP_OPT_DIR_REQ) ? SF_FINST_R : SF_FINST_D);
8169 goto done;
Christopher Fauletfe6a71b2019-07-26 16:40:24 +02008170 }
Thierry FOURNIER10ec2142015-08-24 17:23:45 +02008171
Christopher Faulet700d9e82020-01-31 12:21:52 +01008172 if (lua_gettop(L) == 1 || !lua_istable(L, 2)) {
8173 /* No reply or invalid reply */
8174 s->txn->status = 0;
8175 http_reply_and_close(s, 0, NULL);
8176 }
8177 else {
8178 /* Remove extra args to have the reply on top of the stack */
8179 if (lua_gettop(L) > 2)
8180 lua_pop(L, lua_gettop(L) - 2);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01008181
Christopher Faulet700d9e82020-01-31 12:21:52 +01008182 if (!hlua_txn_forward_reply(L, s)) {
8183 if (!(s->flags & SF_ERR_MASK))
8184 s->flags |= SF_ERR_PRXCOND;
8185 lua_pushinteger(L, ACT_RET_ERR);
8186 WILL_LJMP(hlua_done(L));
8187 return 0; /* Never reached */
8188 }
Christopher Faulet4d0e2632019-07-16 10:52:40 +02008189 }
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02008190
Christopher Faulet700d9e82020-01-31 12:21:52 +01008191 finst = ((htxn->dir == SMP_OPT_DIR_REQ) ? SF_FINST_R : SF_FINST_H);
8192 if (htxn->dir == SMP_OPT_DIR_REQ) {
8193 /* let's log the request time */
8194 s->logs.tv_request = now;
8195 if (s->sess->fe == s->be) /* report it if the request was intercepted by the frontend */
Willy Tarreau4781b152021-04-06 13:53:36 +02008196 _HA_ATOMIC_INC(&s->sess->fe->fe_counters.intercepted_req);
Christopher Faulet700d9e82020-01-31 12:21:52 +01008197 }
Christopher Fauletfe6a71b2019-07-26 16:40:24 +02008198
Christopher Faulet700d9e82020-01-31 12:21:52 +01008199 done:
8200 if (!(s->flags & SF_ERR_MASK))
8201 s->flags |= SF_ERR_LOCAL;
8202 if (!(s->flags & SF_FINST_MASK))
8203 s->flags |= finst;
Christopher Fauletfe6a71b2019-07-26 16:40:24 +02008204
Christopher Faulete48d1dc2021-08-13 14:11:17 +02008205 if ((htxn->flags & HLUA_TXN_CTX_MASK) == HLUA_TXN_FLT_CTX)
8206 lua_pushinteger(L, -1);
8207 else
8208 lua_pushinteger(L, ACT_RET_ABRT);
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02008209 WILL_LJMP(hlua_done(L));
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01008210 return 0;
8211}
8212
Christopher Faulet700d9e82020-01-31 12:21:52 +01008213/*
8214 *
8215 *
8216 * Class REPLY
8217 *
8218 *
8219 */
8220
8221/* Pushes the TXN reply onto the top of the stack. If the stask does not have a
8222 * free slots, the function fails and returns 0;
8223 */
8224static int hlua_txn_reply_new(lua_State *L)
8225{
8226 struct hlua_txn *htxn;
8227 const char *reason, *body = NULL;
8228 int ret, status;
8229
8230 htxn = MAY_LJMP(hlua_checktxn(L, 1));
Christopher Fauletd8f0e072020-02-25 09:45:51 +01008231 if (!IS_HTX_STRM(htxn->s)) {
Christopher Faulet700d9e82020-01-31 12:21:52 +01008232 hlua_pusherror(L, "txn object is not an HTTP transaction.");
8233 WILL_LJMP(lua_error(L));
8234 }
8235
8236 /* Default value */
8237 status = 200;
8238 reason = http_get_reason(status);
8239
8240 if (lua_istable(L, 2)) {
8241 /* load status and reason from the table argument at index 2 */
8242 ret = lua_getfield(L, 2, "status");
8243 if (ret == LUA_TNIL)
8244 goto reason;
8245 else if (ret != LUA_TNUMBER) {
8246 /* invalid status: ignore the reason */
8247 goto body;
8248 }
8249 status = lua_tointeger(L, -1);
8250
8251 reason:
8252 lua_pop(L, 1); /* restore the stack: remove status */
8253 ret = lua_getfield(L, 2, "reason");
8254 if (ret == LUA_TSTRING)
8255 reason = lua_tostring(L, -1);
8256
8257 body:
8258 lua_pop(L, 1); /* restore the stack: remove invalid status or reason */
8259 ret = lua_getfield(L, 2, "body");
8260 if (ret == LUA_TSTRING)
8261 body = lua_tostring(L, -1);
8262 lua_pop(L, 1); /* restore the stack: remove body */
8263 }
8264
8265 /* Create the Reply table */
8266 lua_newtable(L);
8267
8268 /* Add status element */
8269 lua_pushstring(L, "status");
8270 lua_pushinteger(L, status);
8271 lua_settable(L, -3);
8272
8273 /* Add reason element */
8274 reason = http_get_reason(status);
8275 lua_pushstring(L, "reason");
8276 lua_pushstring(L, reason);
8277 lua_settable(L, -3);
8278
8279 /* Add body element, nil if undefined */
8280 lua_pushstring(L, "body");
8281 if (body)
8282 lua_pushstring(L, body);
8283 else
8284 lua_pushnil(L);
8285 lua_settable(L, -3);
8286
8287 /* Add headers element */
8288 lua_pushstring(L, "headers");
8289 lua_newtable(L);
8290
8291 /* stack: [ txn, <Arg:table>, <Reply:table>, "headers", <headers:table> ] */
8292 if (lua_istable(L, 2)) {
8293 /* load headers from the table argument at index 2. If it is a table, copy it. */
8294 ret = lua_getfield(L, 2, "headers");
8295 if (ret == LUA_TTABLE) {
8296 /* stack: [ ... <headers:table>, <table> ] */
8297 lua_pushnil(L);
8298 while (lua_next(L, -2) != 0) {
8299 /* stack: [ ... <headers:table>, <table>, k, v] */
8300 if (!lua_isstring(L, -1) && !lua_istable(L, -1)) {
8301 /* invalid value type, skip it */
8302 lua_pop(L, 1);
8303 continue;
8304 }
8305
8306
8307 /* Duplicate the key and swap it with the value. */
8308 lua_pushvalue(L, -2);
8309 lua_insert(L, -2);
8310 /* stack: [ ... <headers:table>, <table>, k, k, v ] */
8311
8312 lua_newtable(L);
8313 lua_insert(L, -2);
8314 /* stack: [ ... <headers:table>, <table>, k, k, <inner:table>, v ] */
8315
8316 if (lua_isstring(L, -1)) {
8317 /* push the value in the inner table */
8318 lua_rawseti(L, -2, 1);
8319 }
8320 else { /* table */
8321 lua_pushnil(L);
8322 while (lua_next(L, -2) != 0) {
8323 /* stack: [ ... <headers:table>, <table>, k, k, <inner:table>, <v:table>, k2, v2 ] */
8324 if (!lua_isstring(L, -1)) {
8325 /* invalid value type, skip it*/
8326 lua_pop(L, 1);
8327 continue;
8328 }
8329 /* push the value in the inner table */
8330 lua_rawseti(L, -4, lua_rawlen(L, -4) + 1);
8331 /* stack: [ ... <headers:table>, <table>, k, k, <inner:table>, <v:table>, k2 ] */
8332 }
8333 lua_pop(L, 1);
8334 /* stack: [ ... <headers:table>, <table>, k, k, <inner:table> ] */
8335 }
8336
8337 /* push (k,v) on the stack in the headers table:
8338 * stack: [ ... <headers:table>, <table>, k, k, v ]
8339 */
8340 lua_settable(L, -5);
8341 /* stack: [ ... <headers:table>, <table>, k ] */
8342 }
8343 }
8344 lua_pop(L, 1);
8345 }
8346 /* stack: [ txn, <Arg:table>, <Reply:table>, "headers", <headers:table> ] */
8347 lua_settable(L, -3);
8348 /* stack: [ txn, <Arg:table>, <Reply:table> ] */
8349
8350 /* Pop a class sesison metatable and affect it to the userdata. */
8351 lua_rawgeti(L, LUA_REGISTRYINDEX, class_txn_reply_ref);
8352 lua_setmetatable(L, -2);
8353 return 1;
8354}
8355
8356/* Set the reply status code, and optionally the reason. If no reason is
8357 * provided, the default one corresponding to the status code is used.
8358 */
8359__LJMP static int hlua_txn_reply_set_status(lua_State *L)
8360{
8361 int status = MAY_LJMP(luaL_checkinteger(L, 2));
8362 const char *reason = MAY_LJMP(luaL_optlstring(L, 3, NULL, NULL));
8363
8364 /* First argument (self) must be a table */
Aurelien DARRAGONd83d0452022-10-05 11:46:45 +02008365 MAY_LJMP(luaL_checktype(L, 1, LUA_TTABLE));
Christopher Faulet700d9e82020-01-31 12:21:52 +01008366
8367 if (status < 100 || status > 599) {
8368 lua_pushboolean(L, 0);
8369 return 1;
8370 }
8371 if (!reason)
8372 reason = http_get_reason(status);
8373
8374 lua_pushinteger(L, status);
8375 lua_setfield(L, 1, "status");
8376
8377 lua_pushstring(L, reason);
8378 lua_setfield(L, 1, "reason");
8379
8380 lua_pushboolean(L, 1);
8381 return 1;
8382}
8383
8384/* Add a header into the reply object. Each header name is associated to an
8385 * array of values in the "headers" table. If the header name is not found, a
8386 * new entry is created.
8387 */
8388__LJMP static int hlua_txn_reply_add_header(lua_State *L)
8389{
8390 const char *name = MAY_LJMP(luaL_checkstring(L, 2));
8391 const char *value = MAY_LJMP(luaL_checkstring(L, 3));
8392 int ret;
8393
8394 /* First argument (self) must be a table */
Aurelien DARRAGONd83d0452022-10-05 11:46:45 +02008395 MAY_LJMP(luaL_checktype(L, 1, LUA_TTABLE));
Christopher Faulet700d9e82020-01-31 12:21:52 +01008396
8397 /* Push in the stack the "headers" entry. */
8398 ret = lua_getfield(L, 1, "headers");
8399 if (ret != LUA_TTABLE) {
8400 hlua_pusherror(L, "Reply['headers'] is expected to a an array. %s found", lua_typename(L, ret));
8401 WILL_LJMP(lua_error(L));
8402 }
8403
8404 /* check if the header is already registered. If not, register it. */
8405 ret = lua_getfield(L, -1, name);
8406 if (ret == LUA_TNIL) {
8407 /* Entry not found. */
8408 lua_pop(L, 1); /* remove the nil. The "headers" table is the top of the stack. */
8409
8410 /* Insert the new header name in the array in the top of the stack.
8411 * It left the new array in the top of the stack.
8412 */
8413 lua_newtable(L);
8414 lua_pushstring(L, name);
8415 lua_pushvalue(L, -2);
8416 lua_settable(L, -4);
8417 }
8418 else if (ret != LUA_TTABLE) {
8419 hlua_pusherror(L, "Reply['headers']['%s'] is expected to be an array. %s found", name, lua_typename(L, ret));
8420 WILL_LJMP(lua_error(L));
8421 }
8422
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -07008423 /* Now the top of thestack is an array of values. We push
Christopher Faulet700d9e82020-01-31 12:21:52 +01008424 * the header value as new entry.
8425 */
8426 lua_pushstring(L, value);
8427 ret = lua_rawlen(L, -2);
8428 lua_rawseti(L, -2, ret + 1);
8429
8430 lua_pushboolean(L, 1);
8431 return 1;
8432}
8433
8434/* Remove all occurrences of a given header name. */
8435__LJMP static int hlua_txn_reply_del_header(lua_State *L)
8436{
8437 const char *name = MAY_LJMP(luaL_checkstring(L, 2));
8438 int ret;
8439
8440 /* First argument (self) must be a table */
Aurelien DARRAGONd83d0452022-10-05 11:46:45 +02008441 MAY_LJMP(luaL_checktype(L, 1, LUA_TTABLE));
Christopher Faulet700d9e82020-01-31 12:21:52 +01008442
8443 /* Push in the stack the "headers" entry. */
8444 ret = lua_getfield(L, 1, "headers");
8445 if (ret != LUA_TTABLE) {
8446 hlua_pusherror(L, "Reply['headers'] is expected to be an array. %s found", lua_typename(L, ret));
8447 WILL_LJMP(lua_error(L));
8448 }
8449
8450 lua_pushstring(L, name);
8451 lua_pushnil(L);
8452 lua_settable(L, -3);
8453
8454 lua_pushboolean(L, 1);
8455 return 1;
8456}
8457
8458/* Set the reply's body. Overwrite any existing entry. */
8459__LJMP static int hlua_txn_reply_set_body(lua_State *L)
8460{
8461 const char *payload = MAY_LJMP(luaL_checkstring(L, 2));
8462
8463 /* First argument (self) must be a table */
Aurelien DARRAGONd83d0452022-10-05 11:46:45 +02008464 MAY_LJMP(luaL_checktype(L, 1, LUA_TTABLE));
Christopher Faulet700d9e82020-01-31 12:21:52 +01008465
8466 lua_pushstring(L, payload);
8467 lua_setfield(L, 1, "body");
8468
8469 lua_pushboolean(L, 1);
8470 return 1;
8471}
8472
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01008473__LJMP static int hlua_log(lua_State *L)
8474{
8475 int level;
8476 const char *msg;
8477
8478 MAY_LJMP(check_args(L, 2, "log"));
8479 level = MAY_LJMP(luaL_checkinteger(L, 1));
8480 msg = MAY_LJMP(luaL_checkstring(L, 2));
8481
8482 if (level < 0 || level >= NB_LOG_LEVELS)
8483 WILL_LJMP(luaL_argerror(L, 1, "Invalid loglevel."));
8484
8485 hlua_sendlog(NULL, level, msg);
8486 return 0;
8487}
8488
8489__LJMP static int hlua_log_debug(lua_State *L)
8490{
8491 const char *msg;
8492
8493 MAY_LJMP(check_args(L, 1, "debug"));
8494 msg = MAY_LJMP(luaL_checkstring(L, 1));
8495 hlua_sendlog(NULL, LOG_DEBUG, msg);
8496 return 0;
8497}
8498
8499__LJMP static int hlua_log_info(lua_State *L)
8500{
8501 const char *msg;
8502
8503 MAY_LJMP(check_args(L, 1, "info"));
8504 msg = MAY_LJMP(luaL_checkstring(L, 1));
8505 hlua_sendlog(NULL, LOG_INFO, msg);
8506 return 0;
8507}
8508
8509__LJMP static int hlua_log_warning(lua_State *L)
8510{
8511 const char *msg;
8512
8513 MAY_LJMP(check_args(L, 1, "warning"));
8514 msg = MAY_LJMP(luaL_checkstring(L, 1));
8515 hlua_sendlog(NULL, LOG_WARNING, msg);
8516 return 0;
8517}
8518
8519__LJMP static int hlua_log_alert(lua_State *L)
8520{
8521 const char *msg;
8522
8523 MAY_LJMP(check_args(L, 1, "alert"));
8524 msg = MAY_LJMP(luaL_checkstring(L, 1));
8525 hlua_sendlog(NULL, LOG_ALERT, msg);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01008526 return 0;
8527}
8528
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01008529__LJMP static int hlua_sleep_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008530{
8531 int wakeup_ms = lua_tointeger(L, -1);
Willy Tarreau12c02702021-09-30 16:12:31 +02008532 if (!tick_is_expired(wakeup_ms, now_ms))
Willy Tarreau9635e032018-10-16 17:52:55 +02008533 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008534 return 0;
8535}
8536
8537__LJMP static int hlua_sleep(lua_State *L)
8538{
8539 unsigned int delay;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008540 unsigned int wakeup_ms;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008541
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008542 MAY_LJMP(check_args(L, 1, "sleep"));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008543
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01008544 delay = MAY_LJMP(luaL_checkinteger(L, 1)) * 1000;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008545 wakeup_ms = tick_add(now_ms, delay);
8546 lua_pushinteger(L, wakeup_ms);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008547
Willy Tarreau9635e032018-10-16 17:52:55 +02008548 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008549 return 0;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008550}
8551
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008552__LJMP static int hlua_msleep(lua_State *L)
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008553{
8554 unsigned int delay;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008555 unsigned int wakeup_ms;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008556
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008557 MAY_LJMP(check_args(L, 1, "msleep"));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008558
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01008559 delay = MAY_LJMP(luaL_checkinteger(L, 1));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008560 wakeup_ms = tick_add(now_ms, delay);
8561 lua_pushinteger(L, wakeup_ms);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008562
Willy Tarreau9635e032018-10-16 17:52:55 +02008563 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008564 return 0;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008565}
8566
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01008567/* This functionis an LUA binding. it permits to give back
8568 * the hand at the HAProxy scheduler. It is used when the
8569 * LUA processing consumes a lot of time.
8570 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01008571__LJMP static int hlua_yield_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008572{
8573 return 0;
8574}
8575
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01008576__LJMP static int hlua_yield(lua_State *L)
8577{
Willy Tarreau9635e032018-10-16 17:52:55 +02008578 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_yield_yield, TICK_ETERNITY, HLUA_CTRLYIELD));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008579 return 0;
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01008580}
8581
Thierry FOURNIER37196f42015-02-16 19:34:56 +01008582/* This function change the nice of the currently executed
8583 * task. It is used set low or high priority at the current
8584 * task.
8585 */
Willy Tarreau59551662015-03-10 14:23:13 +01008586__LJMP static int hlua_set_nice(lua_State *L)
Thierry FOURNIER37196f42015-02-16 19:34:56 +01008587{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01008588 struct hlua *hlua;
8589 int nice;
Thierry FOURNIER37196f42015-02-16 19:34:56 +01008590
Willy Tarreau80f5fae2015-02-27 16:38:20 +01008591 MAY_LJMP(check_args(L, 1, "set_nice"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01008592 nice = MAY_LJMP(luaL_checkinteger(L, 1));
Thierry FOURNIER37196f42015-02-16 19:34:56 +01008593
Thierry Fournier4234dbd2020-11-28 13:18:23 +01008594 /* Get hlua struct, or NULL if we execute from main lua state */
8595 hlua = hlua_gethlua(L);
8596
8597 /* If the task is not set, I'm in a start mode. */
Thierry FOURNIER37196f42015-02-16 19:34:56 +01008598 if (!hlua || !hlua->task)
8599 return 0;
8600
8601 if (nice < -1024)
8602 nice = -1024;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01008603 else if (nice > 1024)
Thierry FOURNIER37196f42015-02-16 19:34:56 +01008604 nice = 1024;
8605
8606 hlua->task->nice = nice;
8607 return 0;
8608}
8609
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08008610/* This function is used as a callback of a task. It is called by the
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008611 * HAProxy task subsystem when the task is awaked. The LUA runtime can
8612 * return an E_AGAIN signal, the emmiter of this signal must set a
8613 * signal to wake the task.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008614 *
8615 * Task wrapper are longjmp safe because the only one Lua code
8616 * executed is the safe hlua_ctx_resume();
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008617 */
Willy Tarreau144f84a2021-03-02 16:09:26 +01008618struct task *hlua_process_task(struct task *task, void *context, unsigned int state)
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008619{
Olivier Houchard9f6af332018-05-25 14:04:04 +02008620 struct hlua *hlua = context;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008621 enum hlua_exec status;
8622
Willy Tarreau6ef52f42022-06-15 14:19:48 +02008623 if (task->tid < 0)
8624 task->tid = tid;
8625
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008626 /* If it is the first call to the task, we must initialize the
8627 * execution timeouts.
8628 */
8629 if (!HLUA_IS_RUNNING(hlua))
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02008630 hlua->max_time = hlua_timeout_task;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008631
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008632 /* Execute the Lua code. */
8633 status = hlua_ctx_resume(hlua, 1);
8634
8635 switch (status) {
8636 /* finished or yield */
8637 case HLUA_E_OK:
8638 hlua_ctx_destroy(hlua);
Olivier Houchard3f795f72019-04-17 22:51:06 +02008639 task_destroy(task);
Tim Duesterhuscd235c62018-04-24 13:56:01 +02008640 task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008641 break;
8642
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01008643 case HLUA_E_AGAIN: /* co process or timeout wake me later. */
Thierry FOURNIERcb146882017-12-10 17:10:57 +01008644 notification_gc(&hlua->com);
PiBa-NLfe971b32018-05-02 22:27:14 +02008645 task->expire = hlua->wake_time;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008646 break;
8647
8648 /* finished with error. */
Aurelien DARRAGON79544102022-11-24 14:27:15 +01008649 case HLUA_E_ETMOUT:
8650 SEND_ERR(NULL, "Lua task: execution timeout.\n");
8651 goto err_task_abort;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008652 case HLUA_E_ERRMSG:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008653 SEND_ERR(NULL, "Lua task: %s.\n", lua_tostring(hlua->T, -1));
Aurelien DARRAGON79544102022-11-24 14:27:15 +01008654 goto err_task_abort;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008655 case HLUA_E_ERR:
8656 default:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008657 SEND_ERR(NULL, "Lua task: unknown error.\n");
Aurelien DARRAGON79544102022-11-24 14:27:15 +01008658 err_task_abort:
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008659 hlua_ctx_destroy(hlua);
Olivier Houchard3f795f72019-04-17 22:51:06 +02008660 task_destroy(task);
Emeric Brun253e53e2017-10-17 18:58:40 +02008661 task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008662 break;
8663 }
Emeric Brun253e53e2017-10-17 18:58:40 +02008664 return task;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008665}
8666
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008667/* This function is an LUA binding that register LUA function to be
8668 * executed after the HAProxy configuration parsing and before the
8669 * HAProxy scheduler starts. This function expect only one LUA
8670 * argument that is a function. This function returns nothing, but
8671 * throws if an error is encountered.
8672 */
8673__LJMP static int hlua_register_init(lua_State *L)
8674{
8675 struct hlua_init_function *init;
8676 int ref;
8677
8678 MAY_LJMP(check_args(L, 1, "register_init"));
8679
Aurelien DARRAGON87f52972023-02-24 09:43:54 +01008680 if (hlua_gethlua(L)) {
8681 /* runtime processing */
8682 WILL_LJMP(luaL_error(L, "register_init: not available outside of body context"));
8683 }
8684
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008685 ref = MAY_LJMP(hlua_checkfunction(L, 1));
8686
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02008687 init = calloc(1, sizeof(*init));
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +01008688 if (!init) {
8689 hlua_unref(L, ref);
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01008690 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +01008691 }
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008692
8693 init->function_ref = ref;
Willy Tarreau2b718102021-04-21 07:32:39 +02008694 LIST_APPEND(&hlua_init_functions[hlua_state_id], &init->l);
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008695 return 0;
8696}
8697
Ilya Shipitsin6f86eaa2022-11-30 16:22:42 +05008698/* This function is an LUA binding. It permits to register a task
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008699 * executed in parallel of the main HAroxy activity. The task is
8700 * created and it is set in the HAProxy scheduler. It can be called
8701 * from the "init" section, "post init" or during the runtime.
8702 *
8703 * Lua prototype:
8704 *
Aurelien DARRAGONb8038992023-03-09 16:48:30 +01008705 * <none> core.register_task(<function>[, <arg1>[, <arg2>[, ...[, <arg4>]]]])
8706 *
8707 * <arg1..4> are optional arguments that will be provided to <function>
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008708 */
8709static int hlua_register_task(lua_State *L)
8710{
Christopher Faulet5294ec02021-04-12 12:24:47 +02008711 struct hlua *hlua = NULL;
8712 struct task *task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008713 int ref;
Aurelien DARRAGONb8038992023-03-09 16:48:30 +01008714 int nb_arg;
8715 int it;
8716 int arg_ref[4]; /* optional arguments */
Thierry Fournier021d9862020-11-28 23:42:03 +01008717 int state_id;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008718
Aurelien DARRAGONb8038992023-03-09 16:48:30 +01008719 nb_arg = lua_gettop(L);
8720 if (nb_arg < 1)
8721 WILL_LJMP(luaL_error(L, "register_task: <func> argument is required"));
8722 else if (nb_arg > 5)
8723 WILL_LJMP(luaL_error(L, "register_task: no more that 4 optional arguments may be provided"));
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008724
Aurelien DARRAGONb8038992023-03-09 16:48:30 +01008725 /* first arg: function ref */
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008726 ref = MAY_LJMP(hlua_checkfunction(L, 1));
8727
Aurelien DARRAGONb8038992023-03-09 16:48:30 +01008728 /* extract optional args (if any) */
8729 it = 0;
8730 while (--nb_arg) {
8731 lua_pushvalue(L, 2 + it);
8732 arg_ref[it] = hlua_ref(L); /* get arg reference */
8733 it += 1;
8734 }
8735 nb_arg = it;
8736
Thierry Fournier75fc0292020-11-28 13:18:56 +01008737 /* Get the reference state. If the reference is NULL, L is the master
8738 * state, otherwise hlua->T is.
8739 */
8740 hlua = hlua_gethlua(L);
8741 if (hlua)
Thierry Fournier021d9862020-11-28 23:42:03 +01008742 /* we are in runtime processing */
8743 state_id = hlua->state_id;
Thierry Fournier75fc0292020-11-28 13:18:56 +01008744 else
Thierry Fournier021d9862020-11-28 23:42:03 +01008745 /* we are in initialization mode */
Thierry Fournierc7492592020-11-28 23:57:24 +01008746 state_id = hlua_state_id;
Thierry Fournier75fc0292020-11-28 13:18:56 +01008747
Willy Tarreaubafbe012017-11-24 17:34:44 +01008748 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008749 if (!hlua)
Christopher Faulet5294ec02021-04-12 12:24:47 +02008750 goto alloc_error;
Christopher Faulet1e8433f2021-03-24 15:03:01 +01008751 HLUA_INIT(hlua);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008752
Thierry Fournier59f11be2020-11-29 00:37:41 +01008753 /* We are in the common lua state, execute the task anywhere,
8754 * otherwise, inherit the current thread identifier
8755 */
8756 if (state_id == 0)
Willy Tarreaubeeabf52021-10-01 18:23:30 +02008757 task = task_new_anywhere();
Thierry Fournier59f11be2020-11-29 00:37:41 +01008758 else
Willy Tarreaubeeabf52021-10-01 18:23:30 +02008759 task = task_new_here();
Willy Tarreaue09101e2018-10-16 17:37:12 +02008760 if (!task)
Christopher Faulet5294ec02021-04-12 12:24:47 +02008761 goto alloc_error;
Willy Tarreaue09101e2018-10-16 17:37:12 +02008762
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008763 task->context = hlua;
8764 task->process = hlua_process_task;
8765
Aurelien DARRAGON6b0b9bd2023-03-21 14:02:16 +01008766 if (!hlua_ctx_init(hlua, state_id, task))
Christopher Faulet5294ec02021-04-12 12:24:47 +02008767 goto alloc_error;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008768
Aurelien DARRAGONb8038992023-03-09 16:48:30 +01008769 /* Ensure there is enough space on the stack for the function
8770 * plus optional arguments
8771 */
8772 if (!lua_checkstack(hlua->T, (1 + nb_arg)))
8773 goto alloc_error;
8774
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008775 /* Restore the function in the stack. */
Aurelien DARRAGON4fdf8b52023-03-20 17:22:37 +01008776 hlua_pushref(hlua->T, ref);
Aurelien DARRAGONbe58d662023-03-13 14:09:21 +01008777 /* function ref not needed anymore since it was pushed to the substack */
8778 hlua_unref(L, ref);
8779
Aurelien DARRAGONb8038992023-03-09 16:48:30 +01008780 hlua->nargs = nb_arg;
8781
8782 /* push optional arguments to the function */
8783 for (it = 0; it < nb_arg; it++) {
8784 /* push arg to the stack */
8785 hlua_pushref(hlua->T, arg_ref[it]);
8786 /* arg ref not needed anymore since it was pushed to the substack */
8787 hlua_unref(L, arg_ref[it]);
8788 }
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008789
8790 /* Schedule task. */
Willy Tarreaue3957f82021-09-30 16:17:37 +02008791 task_wakeup(task, TASK_WOKEN_INIT);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008792
8793 return 0;
Christopher Faulet5294ec02021-04-12 12:24:47 +02008794
8795 alloc_error:
8796 task_destroy(task);
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +01008797 hlua_unref(L, ref);
Aurelien DARRAGONb8038992023-03-09 16:48:30 +01008798 for (it = 0; it < nb_arg; it++) {
8799 hlua_unref(L, arg_ref[it]);
8800 }
Christopher Faulet5294ec02021-04-12 12:24:47 +02008801 hlua_ctx_destroy(hlua);
8802 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
8803 return 0; /* Never reached */
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008804}
8805
Aurelien DARRAGONc84899c2023-02-20 18:18:59 +01008806/* called from unsafe location */
8807static void hlua_event_subscription_destroy(struct hlua_event_sub *hlua_sub)
8808{
8809 /* hlua cleanup */
8810
8811 hlua_lock(hlua_sub->hlua);
8812 /* registry is shared between coroutines */
8813 hlua_unref(hlua_sub->hlua->T, hlua_sub->fcn_ref);
8814 hlua_unlock(hlua_sub->hlua);
8815
8816 hlua_ctx_destroy(hlua_sub->hlua);
8817
8818 /* free */
8819 pool_free(pool_head_hlua_event_sub, hlua_sub);
8820}
8821
8822/* single event handler: hlua ctx is shared between multiple events handlers
8823 * issued from the same subscription. Thus, it is not destroyed when the event
8824 * is processed: it is destroyed when no more events are expected for the
8825 * subscription (ie: when the subscription ends).
8826 *
8827 * Moreover, events are processed sequentially within the subscription:
8828 * one event must be fully processed before another one may be processed.
8829 * This ensures proper consistency for lua event handling from an ordering
8830 * point of view. This is especially useful with server events for example
8831 * where ADD/DEL/UP/DOWN events ordering really matters to trigger specific
8832 * actions from lua (e.g.: sending emails or making API calls).
8833 *
8834 * Due to this design, each lua event handler is pleased to process the event
8835 * as fast as possible to prevent the event queue from growing up.
8836 * Strictly speaking, there is no runtime limit for the callback function
8837 * (timeout set to default task timeout), but if the event queue goes past
8838 * the limit of unconsumed events an error will be reported and the
8839 * susbscription will pause itself for as long as it takes for the handler to
8840 * catch up (events will be lost as a result).
8841 * If the event handler does not need the sequential ordering and wants to
8842 * process multiple events at a time, it may spawn a new side-task using
8843 * 'core.register_task' to delegate the event handling and make parallel event
8844 * processing within the same subscription set.
8845 */
8846static void hlua_event_handler(struct hlua *hlua)
8847{
8848 enum hlua_exec status;
8849
8850 /* If it is the first call to the task, we must initialize the
8851 * execution timeouts.
8852 */
8853 if (!HLUA_IS_RUNNING(hlua)) {
8854 hlua->max_time = hlua_timeout_task;
8855 }
8856
8857 /* make sure to reset the task expiry before each hlua_ctx_resume()
8858 * since the task is re-used for multiple cb function calls
8859 * We couldn't risk to have t->expire pointing to a past date because
8860 * it was set during last function invocation but was never reset since
8861 * (ie: E_AGAIN)
8862 */
8863 hlua->task->expire = TICK_ETERNITY;
8864
8865 /* Execute the Lua code. */
8866 status = hlua_ctx_resume(hlua, 1);
8867
8868 switch (status) {
8869 /* finished or yield */
8870 case HLUA_E_OK:
8871 break;
8872
8873 case HLUA_E_AGAIN: /* co process or timeout wake me later. */
8874 notification_gc(&hlua->com);
8875 hlua->task->expire = hlua->wake_time;
8876 break;
8877
8878 /* finished with error. */
8879 case HLUA_E_ETMOUT:
8880 SEND_ERR(NULL, "Lua event_hdl: execution timeout.\n");
8881 break;
8882
8883 case HLUA_E_ERRMSG:
8884 SEND_ERR(NULL, "Lua event_hdl: %s.\n", lua_tostring(hlua->T, -1));
8885 break;
8886
8887 case HLUA_E_ERR:
8888 default:
8889 SEND_ERR(NULL, "Lua event_hdl: unknown error.\n");
8890 break;
8891 }
8892}
8893
8894__LJMP static int hlua_event_hdl_cb_data_push_args(struct hlua_event_sub *hlua_sub,
8895 struct event_hdl_sub_type event, void *data)
8896{
8897 struct hlua *hlua = hlua_sub->hlua;
8898
8899 hlua->nargs = 1;
8900 lua_pushstring(hlua->T, event_hdl_sub_type_to_string(event));
8901 if (event_hdl_sub_family_equal(EVENT_HDL_SUB_SERVER, event)) {
8902 struct event_hdl_cb_data_server *e_server = data;
8903 struct proxy *px;
8904 struct server *server;
8905
8906 hlua->nargs += 1;
8907 lua_newtable(hlua->T);
8908 /* Add server name */
8909 lua_pushstring(hlua->T, "name");
8910 lua_pushstring(hlua->T, e_server->safe.name);
8911 lua_settable(hlua->T, -3);
8912 /* Add server puid */
8913 lua_pushstring(hlua->T, "puid");
8914 lua_pushinteger(hlua->T, e_server->safe.puid);
8915 lua_settable(hlua->T, -3);
8916 /* Add server rid */
8917 lua_pushstring(hlua->T, "rid");
8918 lua_pushinteger(hlua->T, e_server->safe.rid);
8919 lua_settable(hlua->T, -3);
8920 /* Add server proxy name */
8921 lua_pushstring(hlua->T, "proxy_name");
8922 lua_pushstring(hlua->T, e_server->safe.proxy_name);
8923 lua_settable(hlua->T, -3);
8924
8925 /* attempt to provide reference server object
8926 * (if it wasn't removed yet, SERVER_DEL will never succeed here)
8927 */
8928 px = proxy_find_by_name(e_server->safe.proxy_name, PR_CAP_BE, 0);
8929 BUG_ON(!px);
8930 server = findserver_unique_id(px, e_server->safe.puid, e_server->safe.rid);
8931 if (server) {
8932 lua_pushstring(hlua->T, "reference");
8933 hlua_fcn_new_server(hlua->T, server);
8934 lua_settable(hlua->T, -3);
8935 }
8936 }
8937 /* sub mgmt */
8938 hlua->nargs += 1;
8939 hlua_fcn_new_event_sub(hlua->T, hlua_sub->sub);
8940
8941 return 1;
8942}
8943
8944/* events runner: if there's an ongoing hlua event handling process, finish it
8945 * then, check if there are new events waiting to be processed
8946 * (events are processed sequentially)
8947 *
8948 * We have a safety measure to warn/guard if the event queue is growing up
8949 * too much due to many events being generated and lua handler is unable to
8950 * keep up the pace (e.g.: when the event queue grows past 100 unconsumed events).
8951 * TODO: make it tunable
8952 */
8953static struct task *hlua_event_runner(struct task *task, void *context, unsigned int state)
8954{
8955 struct hlua_event_sub *hlua_sub = context;
8956 struct event_hdl_async_event *event;
8957 const char *error = NULL;
8958
8959 if (!hlua_sub->paused && event_hdl_async_equeue_size(&hlua_sub->equeue) > 100) {
8960 const char *trace;
8961
8962 /* We reached the limit of pending events in the queue: we should
8963 * warn the user, and temporarily pause the subscription to give a chance
8964 * to the handler to catch up? (it also prevents ressource shortage since
8965 * the queue could grow indefinitely otherwise)
8966 * TODO: find a way to inform the handler that it missed some events
8967 * (example: stats within the subscription in event_hdl api exposed via lua api?)
8968 *
8969 * Nonetheless, reaching this limit means that the handler is not fast enough
8970 * and/or that it subscribed to events that happen too frequently and did not
8971 * expect it. This could come from an inadequate design in the user's script.
8972 */
8973 event_hdl_pause(hlua_sub->sub);
8974 hlua_sub->paused = 1;
8975
8976 /* The following Lua calls can fail. */
8977 if (!SET_SAFE_LJMP(hlua_sub->hlua))
8978 trace = NULL;
8979 trace = hlua_traceback(hlua_sub->hlua->T, ", ");
8980 /* At this point the execution is safe. */
8981 RESET_SAFE_LJMP(hlua_sub->hlua);
8982
8983 ha_warning("Lua event_hdl: pausing the subscription because the function fails to keep up the pace (%u unconsumed events): %s\n", event_hdl_async_equeue_size(&hlua_sub->equeue), ((trace) ? trace : ""));
8984 }
8985
8986 if (HLUA_IS_RUNNING(hlua_sub->hlua)) {
8987 /* ongoing hlua event handler, resume it */
8988 hlua_event_handler(hlua_sub->hlua);
8989 } else if ((event = event_hdl_async_equeue_pop(&hlua_sub->equeue))) { /* check for new events */
8990 if (event_hdl_sub_type_equal(event->type, EVENT_HDL_SUB_END)) {
8991 /* ending event: no more events to come */
8992 event_hdl_async_free_event(event);
8993 task_destroy(task);
8994 hlua_event_subscription_destroy(hlua_sub);
8995 return NULL;
8996 }
8997 /* new event: start processing it */
8998
8999 /* The following Lua calls can fail. */
9000 if (!SET_SAFE_LJMP(hlua_sub->hlua)) {
9001 if (lua_type(hlua_sub->hlua->T, -1) == LUA_TSTRING)
9002 error = lua_tostring(hlua_sub->hlua->T, -1);
9003 else
9004 error = "critical error";
9005 ha_alert("Lua event_hdl: %s.\n", error);
9006 goto skip_event;
9007 }
9008
9009 /* Check stack available size. */
9010 if (!lua_checkstack(hlua_sub->hlua->T, 5)) {
9011 ha_alert("Lua event_hdl: full stack.\n");
9012 RESET_SAFE_LJMP(hlua_sub->hlua);
9013 goto skip_event;
9014 }
9015
9016 /* Restore the function in the stack. */
9017 hlua_pushref(hlua_sub->hlua->T, hlua_sub->fcn_ref);
9018
9019 /* push args */
9020 hlua_sub->hlua->nargs = 0;
9021 if (!hlua_event_hdl_cb_data_push_args(hlua_sub, event->type, event->data)) {
9022 RESET_SAFE_LJMP(hlua_sub->hlua);
9023 goto skip_event;
9024 }
9025
9026 /* At this point the execution is safe. */
9027 RESET_SAFE_LJMP(hlua_sub->hlua);
9028
9029 /* At this point the event was successfully translated into hlua ctx,
9030 * or hlua error occured, so we can safely discard it
9031 */
9032 event_hdl_async_free_event(event);
9033 event = NULL;
9034
9035 hlua_event_handler(hlua_sub->hlua);
9036 skip_event:
9037 if (event)
9038 event_hdl_async_free_event(event);
9039
9040 }
9041
9042 if (!HLUA_IS_RUNNING(hlua_sub->hlua)) {
9043 /* we just finished the processing of one event..
9044 * check for new events before becoming idle
9045 */
9046 if (!event_hdl_async_equeue_isempty(&hlua_sub->equeue)) {
9047 /* more events to process, make sure the task
9048 * will be resumed ASAP to process pending events
9049 */
9050 task_wakeup(task, TASK_WOKEN_OTHER);
9051 }
9052 else if (hlua_sub->paused) {
9053 /* empty queue, the handler catched up: resume the subscription */
9054 event_hdl_resume(hlua_sub->sub);
9055 hlua_sub->paused = 0;
9056 }
9057 }
9058
9059 return task;
9060}
9061
9062/* Must be called directly under lua protected/safe environment
9063 * (not from external callback)
9064 * <fcn_ref> should NOT be dropped after the function successfully returns:
9065 * it will be done automatically in hlua_event_subscription_destroy() when the
9066 * subscription ends.
9067 *
9068 * Returns the new subscription on success and NULL on failure (memory error)
9069 */
9070static struct event_hdl_sub *hlua_event_subscribe(event_hdl_sub_list *list, struct event_hdl_sub_type e_type,
9071 int state_id, int fcn_ref)
9072{
9073 struct hlua_event_sub *hlua_sub;
9074 struct task *task = NULL;
9075
9076 hlua_sub = pool_alloc(pool_head_hlua_event_sub);
9077 if (!hlua_sub)
9078 goto mem_error;
9079 hlua_sub->task = NULL;
9080 hlua_sub->hlua = NULL;
9081 hlua_sub->paused = 0;
9082 if ((task = task_new_here()) == NULL) {
9083 ha_alert("out of memory while allocating hlua event task");
9084 goto mem_error;
9085 }
9086 task->process = hlua_event_runner;
9087 task->context = hlua_sub;
9088 event_hdl_async_equeue_init(&hlua_sub->equeue);
9089 hlua_sub->task = task;
9090 hlua_sub->fcn_ref = fcn_ref;
9091 hlua_sub->state_id = state_id;
9092 hlua_sub->hlua = pool_alloc(pool_head_hlua);
9093 if (!hlua_sub->hlua)
9094 goto mem_error;
9095 HLUA_INIT(hlua_sub->hlua);
9096 if (!hlua_ctx_init(hlua_sub->hlua, hlua_sub->state_id, task))
9097 goto mem_error;
9098
9099 hlua_sub->sub = event_hdl_subscribe_ptr(list, e_type,
9100 EVENT_HDL_ASYNC_TASK(&hlua_sub->equeue,
9101 task,
9102 hlua_sub,
9103 NULL));
9104 if (!hlua_sub->sub)
9105 goto mem_error;
9106
9107 return hlua_sub->sub; /* returns pointer to event_hdl_sub struct */
9108
9109 mem_error:
9110 if (hlua_sub) {
9111 if (hlua_sub->task)
9112 task_destroy(hlua_sub->task);
9113 if (hlua_sub->hlua)
9114 hlua_ctx_destroy(hlua_sub->hlua);
9115 pool_free(pool_head_hlua_event_sub, hlua_sub);
9116 }
9117
9118 return NULL;
9119}
9120
9121/* looks for an array of strings referring to a composition of event_hdl subscription
9122 * types at <index> in <L> stack
9123 */
9124__LJMP static struct event_hdl_sub_type hlua_check_event_sub_types(lua_State *L, int index)
9125{
9126 struct event_hdl_sub_type subscriptions;
9127 const char *msg;
9128
9129 if (lua_type(L, index) != LUA_TTABLE) {
9130 msg = lua_pushfstring(L, "table of strings expected, got %s", luaL_typename(L, index));
9131 luaL_argerror(L, index, msg);
9132 }
9133
9134 subscriptions = EVENT_HDL_SUB_NONE;
9135
9136 /* browse the argument as an array. */
9137 lua_pushnil(L);
9138 while (lua_next(L, index) != 0) {
9139 if (lua_type(L, -1) != LUA_TSTRING) {
9140 msg = lua_pushfstring(L, "table of strings expected, got %s", luaL_typename(L, index));
9141 luaL_argerror(L, index, msg);
9142 }
9143
9144 if (event_hdl_sub_type_equal(EVENT_HDL_SUB_NONE, event_hdl_string_to_sub_type(lua_tostring(L, -1)))) {
9145 msg = lua_pushfstring(L, "'%s' event type is unknown", lua_tostring(L, -1));
9146 luaL_argerror(L, index, msg);
9147 }
9148
9149 /* perform subscriptions |= current sub */
9150 subscriptions = event_hdl_sub_type_add(subscriptions, event_hdl_string_to_sub_type(lua_tostring(L, -1)));
9151
9152 /* pop the current value. */
9153 lua_pop(L, 1);
9154 }
9155
9156 return subscriptions;
9157}
9158
9159/* Wrapper for hlua_fcn_new_event_sub(): catch errors raised by
9160 * the function to prevent LJMP
9161 *
9162 * If no error occured, the function returns 1, else it returns 0 and
9163 * the error message is pushed at the top of the stack
9164 */
9165__LJMP static int _hlua_new_event_sub_safe(lua_State *L)
9166{
9167 struct event_hdl_sub *sub = lua_touserdata(L, 1);
9168
9169 /* this function may raise errors */
9170 return MAY_LJMP(hlua_fcn_new_event_sub(L, sub));
9171}
9172static int hlua_new_event_sub_safe(lua_State *L, struct event_hdl_sub *sub)
9173{
9174 if (!lua_checkstack(L, 2))
9175 return 0;
9176 lua_pushcfunction(L, _hlua_new_event_sub_safe);
9177 lua_pushlightuserdata(L, sub);
9178 switch (lua_pcall(L, 1, 1, 0)) {
9179 case LUA_OK:
9180 return 1;
9181 default:
9182 /* error was catched */
9183 return 0;
9184 }
9185}
9186
9187/* This function is a LUA helper used for registering lua event callbacks.
9188 * It expects an event subscription array and the function to be executed
9189 * when subscribed events occur (stack arguments).
9190 * It can be called from the "init" section, "post init" or during the runtime.
9191 *
9192 * <sub_list> is the subscription list where the subscription will be attempted
9193 *
9194 * Pushes the newly allocated subscription on the stack on success
9195 */
9196__LJMP int hlua_event_sub(lua_State *L, event_hdl_sub_list *sub_list)
9197{
9198 struct hlua *hlua;
9199 struct event_hdl_sub *sub;
9200 struct event_hdl_sub_type subscriptions;
9201 int fcn_ref;
9202 int state_id;
9203
9204 MAY_LJMP(check_args(L, 2, "event_sub"));
9205
9206 /* Get the reference state */
9207 hlua = hlua_gethlua(L);
9208 if (hlua)
9209 /* we are in runtime processing, any thread may subscribe to events:
9210 * subscription events will be handled by the thread who performed
9211 * the registration.
9212 */
9213 state_id = hlua->state_id;
9214 else {
9215 /* we are in initialization mode, only thread 0 (actual calling thread)
9216 * may subscribe to events to prevent the same handler (from different lua
9217 * stacks) from being registered multiple times
9218 *
9219 * hlua_state_id == 0: monostack (lua-load)
9220 * hlua_state_id > 0: hlua_state_id=tid+1, multi-stack (lua-load-per-thread)
9221 * (thus if hlua_state_id > 1, it means we are not in primary thread ctx)
9222 */
9223 if (hlua_state_id > 1)
9224 return 0; /* skip registration */
9225 state_id = hlua_state_id;
9226 }
9227
9228 /* First argument : event subscriptions. */
9229 subscriptions = MAY_LJMP(hlua_check_event_sub_types(L, 1));
9230
9231 if (event_hdl_sub_type_equal(subscriptions, EVENT_HDL_SUB_NONE)) {
9232 WILL_LJMP(luaL_error(L, "event_sub: no valid event types were provided"));
9233 return 0; /* Never reached */
9234 }
9235
9236 /* Second argument : lua function. */
9237 fcn_ref = MAY_LJMP(hlua_checkfunction(L, 2));
9238
9239 /* try to subscribe */
9240 sub = hlua_event_subscribe(sub_list, subscriptions, state_id, fcn_ref);
9241 if (!sub) {
9242 hlua_unref(L, fcn_ref);
9243 WILL_LJMP(luaL_error(L, "event_sub: lua out of memory error"));
9244 return 0; /* Never reached */
9245 }
9246
9247 /* push the subscription to the stack
9248 *
9249 * Here we use the safe function so that lua errors will be
9250 * handled explicitly to prevent 'sub' from being lost
9251 */
9252 if (!hlua_new_event_sub_safe(L, sub)) {
9253 /* Some events could already be pending in the handler's queue.
9254 * However it is wiser to cancel the subscription since we are unable to
9255 * provide a valid reference to it.
9256 * Pending events will be delivered (unless lua keeps raising errors).
9257 */
9258 event_hdl_unsubscribe(sub); /* cancel the subscription */
9259 WILL_LJMP(luaL_error(L, "event_sub: cannot push the subscription (%s)", lua_tostring(L, -1)));
9260 return 0; /* Never reached */
9261 }
9262 event_hdl_drop(sub); /* sub has been duplicated, discard old ref */
9263
9264 return 1;
9265}
9266
9267/* This function is a LUA wrapper used for registering global lua event callbacks
9268 * The new subscription is pushed onto the stack on success
9269 * Returns the number of arguments pushed to the stack (1 for success)
9270 */
9271__LJMP static int hlua_event_global_sub(lua_State *L)
9272{
9273 /* NULL <sub_list> = global subscription list */
9274 return MAY_LJMP(hlua_event_sub(L, NULL));
9275}
9276
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009277/* Wrapper called by HAProxy to execute an LUA converter. This wrapper
9278 * doesn't allow "yield" functions because the HAProxy engine cannot
9279 * resume converters.
9280 */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02009281static int hlua_sample_conv_wrapper(const struct arg *arg_p, struct sample *smp, void *private)
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009282{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02009283 struct hlua_function *fcn = private;
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02009284 struct stream *stream = smp->strm;
Thierry Fournierfd107a22016-02-19 19:57:23 +01009285 const char *error;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009286
Willy Tarreaube508f12016-03-10 11:47:01 +01009287 if (!stream)
9288 return 0;
9289
Willy Tarreau87b09662015-04-03 00:22:06 +02009290 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01009291 * Lua context can be not initialized. This behavior
9292 * permits to save performances because a systematic
9293 * Lua initialization cause 5% performances loss.
9294 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009295 if (!stream->hlua) {
Christopher Faulet1e8433f2021-03-24 15:03:01 +01009296 struct hlua *hlua;
9297
9298 hlua = pool_alloc(pool_head_hlua);
9299 if (!hlua) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009300 SEND_ERR(stream->be, "Lua converter '%s': can't initialize Lua context.\n", fcn->name);
9301 return 0;
9302 }
Christopher Faulet1e8433f2021-03-24 15:03:01 +01009303 HLUA_INIT(hlua);
9304 stream->hlua = hlua;
Aurelien DARRAGON6b0b9bd2023-03-21 14:02:16 +01009305 if (!hlua_ctx_init(stream->hlua, fcn_ref_to_stack_id(fcn), stream->task)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009306 SEND_ERR(stream->be, "Lua converter '%s': can't initialize Lua context.\n", fcn->name);
9307 return 0;
9308 }
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01009309 }
9310
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009311 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009312 if (!HLUA_IS_RUNNING(stream->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02009313
9314 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009315 if (!SET_SAFE_LJMP(stream->hlua)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009316 if (lua_type(stream->hlua->T, -1) == LUA_TSTRING)
9317 error = lua_tostring(stream->hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +01009318 else
9319 error = "critical error";
9320 SEND_ERR(stream->be, "Lua converter '%s': %s.\n", fcn->name, error);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02009321 return 0;
9322 }
9323
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009324 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009325 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009326 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009327 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009328 return 0;
9329 }
9330
9331 /* Restore the function in the stack. */
Aurelien DARRAGON4fdf8b52023-03-20 17:22:37 +01009332 hlua_pushref(stream->hlua->T, fcn->function_ref[stream->hlua->state_id]);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009333
9334 /* convert input sample and pust-it in the stack. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009335 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009336 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009337 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009338 return 0;
9339 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009340 hlua_smp2lua(stream->hlua->T, smp);
9341 stream->hlua->nargs = 1;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009342
9343 /* push keywords in the stack. */
9344 if (arg_p) {
9345 for (; arg_p->type != ARGT_STOP; arg_p++) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009346 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009347 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009348 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009349 return 0;
9350 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009351 hlua_arg2lua(stream->hlua->T, arg_p);
9352 stream->hlua->nargs++;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009353 }
9354 }
9355
Thierry FOURNIERbd413492015-03-03 16:52:26 +01009356 /* We must initialize the execution timeouts. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009357 stream->hlua->max_time = hlua_timeout_session;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01009358
Thierry FOURNIERbabae282015-09-17 11:36:37 +02009359 /* At this point the execution is safe. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009360 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009361 }
9362
9363 /* Execute the function. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009364 switch (hlua_ctx_resume(stream->hlua, 0)) {
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009365 /* finished. */
9366 case HLUA_E_OK:
Thierry FOURNIERfd80df12017-05-12 16:32:20 +02009367 /* If the stack is empty, the function fails. */
9368 if (lua_gettop(stream->hlua->T) <= 0)
9369 return 0;
9370
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009371 /* Convert the returned value in sample. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009372 hlua_lua2smp(stream->hlua->T, -1, smp);
9373 lua_pop(stream->hlua->T, 1);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009374 return 1;
9375
9376 /* yield. */
9377 case HLUA_E_AGAIN:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009378 SEND_ERR(stream->be, "Lua converter '%s': cannot use yielded functions.\n", fcn->name);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009379 return 0;
9380
9381 /* finished with error. */
9382 case HLUA_E_ERRMSG:
9383 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009384 SEND_ERR(stream->be, "Lua converter '%s': %s.\n",
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009385 fcn->name, lua_tostring(stream->hlua->T, -1));
9386 lua_pop(stream->hlua->T, 1);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009387 return 0;
9388
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009389 case HLUA_E_ETMOUT:
9390 SEND_ERR(stream->be, "Lua converter '%s': execution timeout.\n", fcn->name);
9391 return 0;
9392
9393 case HLUA_E_NOMEM:
9394 SEND_ERR(stream->be, "Lua converter '%s': out of memory error.\n", fcn->name);
9395 return 0;
9396
9397 case HLUA_E_YIELD:
9398 SEND_ERR(stream->be, "Lua converter '%s': yield functions like core.tcp() or core.sleep() are not allowed.\n", fcn->name);
9399 return 0;
9400
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009401 case HLUA_E_ERR:
9402 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009403 SEND_ERR(stream->be, "Lua converter '%s' returns an unknown error.\n", fcn->name);
Willy Tarreau14de3952022-11-14 07:08:28 +01009404 __fallthrough;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009405
9406 default:
9407 return 0;
9408 }
9409}
9410
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009411/* Wrapper called by HAProxy to execute a sample-fetch. this wrapper
9412 * doesn't allow "yield" functions because the HAProxy engine cannot
Willy Tarreaube508f12016-03-10 11:47:01 +01009413 * resume sample-fetches. This function will be called by the sample
9414 * fetch engine to call lua-based fetch operations.
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009415 */
Thierry FOURNIER0786d052015-05-11 15:42:45 +02009416static int hlua_sample_fetch_wrapper(const struct arg *arg_p, struct sample *smp,
9417 const char *kw, void *private)
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009418{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02009419 struct hlua_function *fcn = private;
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02009420 struct stream *stream = smp->strm;
Thierry Fournierfd107a22016-02-19 19:57:23 +01009421 const char *error;
Christopher Faulet8c9e6bb2021-08-06 16:29:41 +02009422 unsigned int hflags = HLUA_TXN_NOTERM | HLUA_TXN_SMP_CTX;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009423
Willy Tarreaube508f12016-03-10 11:47:01 +01009424 if (!stream)
9425 return 0;
Christopher Fauletafd8f102018-11-08 11:34:21 +01009426
Willy Tarreau87b09662015-04-03 00:22:06 +02009427 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01009428 * Lua context can be not initialized. This behavior
9429 * permits to save performances because a systematic
9430 * Lua initialization cause 5% performances loss.
9431 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009432 if (!stream->hlua) {
Christopher Faulet1e8433f2021-03-24 15:03:01 +01009433 struct hlua *hlua;
9434
9435 hlua = pool_alloc(pool_head_hlua);
9436 if (!hlua) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009437 SEND_ERR(stream->be, "Lua sample-fetch '%s': can't initialize Lua context.\n", fcn->name);
9438 return 0;
9439 }
Christopher Faulet1e8433f2021-03-24 15:03:01 +01009440 hlua->T = NULL;
9441 stream->hlua = hlua;
Aurelien DARRAGON6b0b9bd2023-03-21 14:02:16 +01009442 if (!hlua_ctx_init(stream->hlua, fcn_ref_to_stack_id(fcn), stream->task)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009443 SEND_ERR(stream->be, "Lua sample-fetch '%s': can't initialize Lua context.\n", fcn->name);
9444 return 0;
9445 }
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01009446 }
9447
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009448 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009449 if (!HLUA_IS_RUNNING(stream->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02009450
9451 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009452 if (!SET_SAFE_LJMP(stream->hlua)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009453 if (lua_type(stream->hlua->T, -1) == LUA_TSTRING)
9454 error = lua_tostring(stream->hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +01009455 else
9456 error = "critical error";
9457 SEND_ERR(smp->px, "Lua sample-fetch '%s': %s.\n", fcn->name, error);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02009458 return 0;
9459 }
9460
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009461 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009462 if (!lua_checkstack(stream->hlua->T, 2)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009463 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009464 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009465 return 0;
9466 }
9467
9468 /* Restore the function in the stack. */
Aurelien DARRAGON4fdf8b52023-03-20 17:22:37 +01009469 hlua_pushref(stream->hlua->T, fcn->function_ref[stream->hlua->state_id]);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009470
9471 /* push arguments in the stack. */
Christopher Fauletbfab2dd2019-07-26 15:09:53 +02009472 if (!hlua_txn_new(stream->hlua->T, stream, smp->px, smp->opt & SMP_OPT_DIR, hflags)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009473 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009474 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009475 return 0;
9476 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009477 stream->hlua->nargs = 1;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009478
9479 /* push keywords in the stack. */
9480 for (; arg_p && arg_p->type != ARGT_STOP; arg_p++) {
9481 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009482 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009483 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009484 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009485 return 0;
9486 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009487 hlua_arg2lua(stream->hlua->T, arg_p);
9488 stream->hlua->nargs++;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009489 }
9490
Thierry FOURNIERbd413492015-03-03 16:52:26 +01009491 /* We must initialize the execution timeouts. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009492 stream->hlua->max_time = hlua_timeout_session;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01009493
Thierry FOURNIERbabae282015-09-17 11:36:37 +02009494 /* At this point the execution is safe. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009495 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009496 }
9497
9498 /* Execute the function. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009499 switch (hlua_ctx_resume(stream->hlua, 0)) {
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009500 /* finished. */
9501 case HLUA_E_OK:
Thierry FOURNIERfd80df12017-05-12 16:32:20 +02009502 /* If the stack is empty, the function fails. */
9503 if (lua_gettop(stream->hlua->T) <= 0)
9504 return 0;
9505
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009506 /* Convert the returned value in sample. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009507 hlua_lua2smp(stream->hlua->T, -1, smp);
9508 lua_pop(stream->hlua->T, 1);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009509
9510 /* Set the end of execution flag. */
9511 smp->flags &= ~SMP_F_MAY_CHANGE;
9512 return 1;
9513
9514 /* yield. */
9515 case HLUA_E_AGAIN:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009516 SEND_ERR(smp->px, "Lua sample-fetch '%s': cannot use yielded functions.\n", fcn->name);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009517 return 0;
9518
9519 /* finished with error. */
9520 case HLUA_E_ERRMSG:
9521 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009522 SEND_ERR(smp->px, "Lua sample-fetch '%s': %s.\n",
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009523 fcn->name, lua_tostring(stream->hlua->T, -1));
9524 lua_pop(stream->hlua->T, 1);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009525 return 0;
9526
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009527 case HLUA_E_ETMOUT:
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009528 SEND_ERR(smp->px, "Lua sample-fetch '%s': execution timeout.\n", fcn->name);
9529 return 0;
9530
9531 case HLUA_E_NOMEM:
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009532 SEND_ERR(smp->px, "Lua sample-fetch '%s': out of memory error.\n", fcn->name);
9533 return 0;
9534
9535 case HLUA_E_YIELD:
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009536 SEND_ERR(smp->px, "Lua sample-fetch '%s': yield not allowed.\n", fcn->name);
9537 return 0;
9538
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009539 case HLUA_E_ERR:
9540 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009541 SEND_ERR(smp->px, "Lua sample-fetch '%s' returns an unknown error.\n", fcn->name);
Willy Tarreau14de3952022-11-14 07:08:28 +01009542 __fallthrough;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009543
9544 default:
9545 return 0;
9546 }
9547}
9548
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009549/* This function is an LUA binding used for registering
9550 * "sample-conv" functions. It expects a converter name used
9551 * in the haproxy configuration file, and an LUA function.
9552 */
9553__LJMP static int hlua_register_converters(lua_State *L)
9554{
9555 struct sample_conv_kw_list *sck;
9556 const char *name;
9557 int ref;
9558 int len;
Christopher Fauletaa224302021-04-12 14:08:21 +02009559 struct hlua_function *fcn = NULL;
Thierry Fournierf67442e2020-11-28 20:41:07 +01009560 struct sample_conv *sc;
9561 struct buffer *trash;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009562
9563 MAY_LJMP(check_args(L, 2, "register_converters"));
9564
Aurelien DARRAGON87f52972023-02-24 09:43:54 +01009565 if (hlua_gethlua(L)) {
9566 /* runtime processing */
9567 WILL_LJMP(luaL_error(L, "register_converters: not available outside of body context"));
9568 }
9569
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009570 /* First argument : converter name. */
9571 name = MAY_LJMP(luaL_checkstring(L, 1));
9572
9573 /* Second argument : lua function. */
9574 ref = MAY_LJMP(hlua_checkfunction(L, 2));
9575
Thierry Fournierf67442e2020-11-28 20:41:07 +01009576 /* Check if the converter is already registered */
9577 trash = get_trash_chunk();
9578 chunk_printf(trash, "lua.%s", name);
9579 sc = find_sample_conv(trash->area, trash->data);
9580 if (sc != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +01009581 fcn = sc->private;
9582 if (fcn->function_ref[hlua_state_id] != -1) {
9583 ha_warning("Trying to register converter 'lua.%s' more than once. "
9584 "This will become a hard error in version 2.5.\n", name);
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +01009585 hlua_unref(L, fcn->function_ref[hlua_state_id]);
Thierry Fournier59f11be2020-11-29 00:37:41 +01009586 }
9587 fcn->function_ref[hlua_state_id] = ref;
9588 return 0;
Thierry Fournierf67442e2020-11-28 20:41:07 +01009589 }
9590
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009591 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02009592 sck = calloc(1, sizeof(*sck) + sizeof(struct sample_conv) * 2);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009593 if (!sck)
Christopher Fauletaa224302021-04-12 14:08:21 +02009594 goto alloc_error;
Thierry Fournier62a22aa2020-11-28 21:06:35 +01009595 fcn = new_hlua_function();
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009596 if (!fcn)
Christopher Fauletaa224302021-04-12 14:08:21 +02009597 goto alloc_error;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009598
9599 /* Fill fcn. */
9600 fcn->name = strdup(name);
9601 if (!fcn->name)
Christopher Fauletaa224302021-04-12 14:08:21 +02009602 goto alloc_error;
Thierry Fournierc7492592020-11-28 23:57:24 +01009603 fcn->function_ref[hlua_state_id] = ref;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009604
9605 /* List head */
9606 sck->list.n = sck->list.p = NULL;
9607
9608 /* converter keyword. */
9609 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02009610 sck->kw[0].kw = calloc(1, len);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009611 if (!sck->kw[0].kw)
Christopher Fauletaa224302021-04-12 14:08:21 +02009612 goto alloc_error;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009613
9614 snprintf((char *)sck->kw[0].kw, len, "lua.%s", name);
9615 sck->kw[0].process = hlua_sample_conv_wrapper;
David Carlier0c437f42016-04-27 16:21:56 +01009616 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 +01009617 sck->kw[0].val_args = NULL;
9618 sck->kw[0].in_type = SMP_T_STR;
9619 sck->kw[0].out_type = SMP_T_STR;
9620 sck->kw[0].private = fcn;
9621
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009622 /* Register this new converter */
9623 sample_register_convs(sck);
9624
9625 return 0;
Christopher Fauletaa224302021-04-12 14:08:21 +02009626
9627 alloc_error:
9628 release_hlua_function(fcn);
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +01009629 hlua_unref(L, ref);
Christopher Fauletaa224302021-04-12 14:08:21 +02009630 ha_free(&sck);
9631 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
9632 return 0; /* Never reached */
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009633}
9634
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08009635/* This function is an LUA binding used for registering
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009636 * "sample-fetch" functions. It expects a converter name used
9637 * in the haproxy configuration file, and an LUA function.
9638 */
9639__LJMP static int hlua_register_fetches(lua_State *L)
9640{
9641 const char *name;
9642 int ref;
9643 int len;
9644 struct sample_fetch_kw_list *sfk;
Christopher Faulet2567f182021-04-12 14:11:50 +02009645 struct hlua_function *fcn = NULL;
Thierry Fournierf67442e2020-11-28 20:41:07 +01009646 struct sample_fetch *sf;
9647 struct buffer *trash;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009648
9649 MAY_LJMP(check_args(L, 2, "register_fetches"));
9650
Aurelien DARRAGON87f52972023-02-24 09:43:54 +01009651 if (hlua_gethlua(L)) {
9652 /* runtime processing */
9653 WILL_LJMP(luaL_error(L, "register_fetches: not available outside of body context"));
9654 }
9655
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009656 /* First argument : sample-fetch name. */
9657 name = MAY_LJMP(luaL_checkstring(L, 1));
9658
9659 /* Second argument : lua function. */
9660 ref = MAY_LJMP(hlua_checkfunction(L, 2));
9661
Thierry Fournierf67442e2020-11-28 20:41:07 +01009662 /* Check if the sample-fetch is already registered */
9663 trash = get_trash_chunk();
9664 chunk_printf(trash, "lua.%s", name);
9665 sf = find_sample_fetch(trash->area, trash->data);
9666 if (sf != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +01009667 fcn = sf->private;
9668 if (fcn->function_ref[hlua_state_id] != -1) {
9669 ha_warning("Trying to register sample-fetch 'lua.%s' more than once. "
9670 "This will become a hard error in version 2.5.\n", name);
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +01009671 hlua_unref(L, fcn->function_ref[hlua_state_id]);
Thierry Fournier59f11be2020-11-29 00:37:41 +01009672 }
9673 fcn->function_ref[hlua_state_id] = ref;
9674 return 0;
Thierry Fournierf67442e2020-11-28 20:41:07 +01009675 }
9676
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009677 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02009678 sfk = calloc(1, sizeof(*sfk) + sizeof(struct sample_fetch) * 2);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009679 if (!sfk)
Christopher Faulet2567f182021-04-12 14:11:50 +02009680 goto alloc_error;
Thierry Fournier62a22aa2020-11-28 21:06:35 +01009681 fcn = new_hlua_function();
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009682 if (!fcn)
Christopher Faulet2567f182021-04-12 14:11:50 +02009683 goto alloc_error;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009684
9685 /* Fill fcn. */
9686 fcn->name = strdup(name);
9687 if (!fcn->name)
Christopher Faulet2567f182021-04-12 14:11:50 +02009688 goto alloc_error;
Thierry Fournierc7492592020-11-28 23:57:24 +01009689 fcn->function_ref[hlua_state_id] = ref;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009690
9691 /* List head */
9692 sfk->list.n = sfk->list.p = NULL;
9693
9694 /* sample-fetch keyword. */
9695 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02009696 sfk->kw[0].kw = calloc(1, len);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009697 if (!sfk->kw[0].kw)
Christopher Faulet2567f182021-04-12 14:11:50 +02009698 goto alloc_error;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009699
9700 snprintf((char *)sfk->kw[0].kw, len, "lua.%s", name);
9701 sfk->kw[0].process = hlua_sample_fetch_wrapper;
David Carlier0c437f42016-04-27 16:21:56 +01009702 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 +01009703 sfk->kw[0].val_args = NULL;
9704 sfk->kw[0].out_type = SMP_T_STR;
9705 sfk->kw[0].use = SMP_USE_HTTP_ANY;
9706 sfk->kw[0].val = 0;
9707 sfk->kw[0].private = fcn;
9708
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009709 /* Register this new fetch. */
9710 sample_register_fetches(sfk);
9711
9712 return 0;
Christopher Faulet2567f182021-04-12 14:11:50 +02009713
9714 alloc_error:
9715 release_hlua_function(fcn);
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +01009716 hlua_unref(L, ref);
Christopher Faulet2567f182021-04-12 14:11:50 +02009717 ha_free(&sfk);
9718 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
9719 return 0; /* Never reached */
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009720}
9721
Christopher Faulet501465d2020-02-26 14:54:16 +01009722/* This function is a lua binding to set the wake_time.
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01009723 */
Christopher Faulet501465d2020-02-26 14:54:16 +01009724__LJMP static int hlua_set_wake_time(lua_State *L)
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01009725{
Thierry Fournier4234dbd2020-11-28 13:18:23 +01009726 struct hlua *hlua;
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01009727 unsigned int delay;
9728 unsigned int wakeup_ms;
9729
Thierry Fournier4234dbd2020-11-28 13:18:23 +01009730 /* Get hlua struct, or NULL if we execute from main lua state */
9731 hlua = hlua_gethlua(L);
9732 if (!hlua) {
9733 return 0;
9734 }
9735
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01009736 MAY_LJMP(check_args(L, 1, "wake_time"));
9737
9738 delay = MAY_LJMP(luaL_checkinteger(L, 1));
9739 wakeup_ms = tick_add(now_ms, delay);
9740 hlua->wake_time = wakeup_ms;
9741 return 0;
9742}
9743
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009744/* This function is a wrapper to execute each LUA function declared as an action
9745 * wrapper during the initialisation period. This function may return any
9746 * ACT_RET_* value. On error ACT_RET_CONT is returned and the action is
9747 * ignored. If the lua action yields, ACT_RET_YIELD is returned. On success, the
9748 * return value is the first element on the stack.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009749 */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009750static enum act_return hlua_action(struct act_rule *rule, struct proxy *px,
Willy Tarreau658b85b2015-09-27 10:00:49 +02009751 struct session *sess, struct stream *s, int flags)
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009752{
9753 char **arg;
Christopher Faulet8c9e6bb2021-08-06 16:29:41 +02009754 unsigned int hflags = HLUA_TXN_ACT_CTX;
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009755 int dir, act_ret = ACT_RET_CONT;
Thierry Fournierfd107a22016-02-19 19:57:23 +01009756 const char *error;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009757
9758 switch (rule->from) {
Christopher Fauletd8f0e072020-02-25 09:45:51 +01009759 case ACT_F_TCP_REQ_CNT: dir = SMP_OPT_DIR_REQ; break;
9760 case ACT_F_TCP_RES_CNT: dir = SMP_OPT_DIR_RES; break;
9761 case ACT_F_HTTP_REQ: dir = SMP_OPT_DIR_REQ; break;
9762 case ACT_F_HTTP_RES: dir = SMP_OPT_DIR_RES; break;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009763 default:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009764 SEND_ERR(px, "Lua: internal error while execute action.\n");
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009765 goto end;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009766 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009767
Willy Tarreau87b09662015-04-03 00:22:06 +02009768 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01009769 * Lua context can be not initialized. This behavior
9770 * permits to save performances because a systematic
9771 * Lua initialization cause 5% performances loss.
9772 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009773 if (!s->hlua) {
Christopher Faulet1e8433f2021-03-24 15:03:01 +01009774 struct hlua *hlua;
9775
9776 hlua = pool_alloc(pool_head_hlua);
9777 if (!hlua) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009778 SEND_ERR(px, "Lua action '%s': can't initialize Lua context.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009779 rule->arg.hlua_rule->fcn->name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009780 goto end;
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009781 }
Christopher Faulet1e8433f2021-03-24 15:03:01 +01009782 HLUA_INIT(hlua);
9783 s->hlua = hlua;
Aurelien DARRAGON6b0b9bd2023-03-21 14:02:16 +01009784 if (!hlua_ctx_init(s->hlua, fcn_ref_to_stack_id(rule->arg.hlua_rule->fcn), s->task)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009785 SEND_ERR(px, "Lua action '%s': can't initialize Lua context.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009786 rule->arg.hlua_rule->fcn->name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009787 goto end;
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009788 }
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01009789 }
9790
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009791 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009792 if (!HLUA_IS_RUNNING(s->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02009793
9794 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009795 if (!SET_SAFE_LJMP(s->hlua)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009796 if (lua_type(s->hlua->T, -1) == LUA_TSTRING)
9797 error = lua_tostring(s->hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +01009798 else
9799 error = "critical error";
9800 SEND_ERR(px, "Lua function '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009801 rule->arg.hlua_rule->fcn->name, error);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009802 goto end;
Thierry FOURNIERbabae282015-09-17 11:36:37 +02009803 }
9804
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009805 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009806 if (!lua_checkstack(s->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009807 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009808 rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009809 RESET_SAFE_LJMP(s->hlua);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009810 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009811 }
9812
9813 /* Restore the function in the stack. */
Aurelien DARRAGON4fdf8b52023-03-20 17:22:37 +01009814 hlua_pushref(s->hlua->T, rule->arg.hlua_rule->fcn->function_ref[s->hlua->state_id]);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009815
Willy Tarreau87b09662015-04-03 00:22:06 +02009816 /* Create and and push object stream in the stack. */
Christopher Fauletbfab2dd2019-07-26 15:09:53 +02009817 if (!hlua_txn_new(s->hlua->T, s, px, dir, hflags)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009818 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009819 rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009820 RESET_SAFE_LJMP(s->hlua);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009821 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009822 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009823 s->hlua->nargs = 1;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009824
9825 /* push keywords in the stack. */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009826 for (arg = rule->arg.hlua_rule->args; arg && *arg; arg++) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009827 if (!lua_checkstack(s->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009828 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009829 rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009830 RESET_SAFE_LJMP(s->hlua);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009831 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009832 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009833 lua_pushstring(s->hlua->T, *arg);
9834 s->hlua->nargs++;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009835 }
9836
Thierry FOURNIERbabae282015-09-17 11:36:37 +02009837 /* Now the execution is safe. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009838 RESET_SAFE_LJMP(s->hlua);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02009839
Thierry FOURNIERbd413492015-03-03 16:52:26 +01009840 /* We must initialize the execution timeouts. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009841 s->hlua->max_time = hlua_timeout_session;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009842 }
9843
9844 /* Execute the function. */
Christopher Faulet105ba6c2019-12-18 14:41:51 +01009845 switch (hlua_ctx_resume(s->hlua, !(flags & ACT_OPT_FINAL))) {
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009846 /* finished. */
9847 case HLUA_E_OK:
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009848 /* Catch the return value */
9849 if (lua_gettop(s->hlua->T) > 0)
9850 act_ret = lua_tointeger(s->hlua->T, -1);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009851
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01009852 /* Set timeout in the required channel. */
Christopher Faulet498c4832020-07-28 11:59:58 +02009853 if (act_ret == ACT_RET_YIELD) {
9854 if (flags & ACT_OPT_FINAL)
9855 goto err_yield;
9856
Christopher Faulet8f587ea2020-07-28 12:01:55 +02009857 if (dir == SMP_OPT_DIR_REQ)
9858 s->req.analyse_exp = tick_first((tick_is_expired(s->req.analyse_exp, now_ms) ? 0 : s->req.analyse_exp),
9859 s->hlua->wake_time);
9860 else
9861 s->res.analyse_exp = tick_first((tick_is_expired(s->res.analyse_exp, now_ms) ? 0 : s->res.analyse_exp),
9862 s->hlua->wake_time);
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01009863 }
9864 goto end;
9865
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009866 /* yield. */
9867 case HLUA_E_AGAIN:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01009868 /* Set timeout in the required channel. */
Christopher Faulet8f587ea2020-07-28 12:01:55 +02009869 if (dir == SMP_OPT_DIR_REQ)
9870 s->req.analyse_exp = tick_first((tick_is_expired(s->req.analyse_exp, now_ms) ? 0 : s->req.analyse_exp),
9871 s->hlua->wake_time);
9872 else
9873 s->res.analyse_exp = tick_first((tick_is_expired(s->res.analyse_exp, now_ms) ? 0 : s->res.analyse_exp),
9874 s->hlua->wake_time);
9875
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009876 /* Some actions can be wake up when a "write" event
9877 * is detected on a response channel. This is useful
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08009878 * only for actions targeted on the requests.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009879 */
Christopher Faulet51fa3582019-07-26 14:54:52 +02009880 if (HLUA_IS_WAKERESWR(s->hlua))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01009881 s->res.flags |= CF_WAKE_WRITE;
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009882 if (HLUA_IS_WAKEREQWR(s->hlua))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01009883 s->req.flags |= CF_WAKE_WRITE;
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009884 act_ret = ACT_RET_YIELD;
9885 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009886
9887 /* finished with error. */
9888 case HLUA_E_ERRMSG:
9889 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009890 SEND_ERR(px, "Lua function '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009891 rule->arg.hlua_rule->fcn->name, lua_tostring(s->hlua->T, -1));
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009892 lua_pop(s->hlua->T, 1);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009893 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009894
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009895 case HLUA_E_ETMOUT:
Thierry Fournierad5345f2020-11-29 02:05:57 +01009896 SEND_ERR(px, "Lua function '%s': execution timeout.\n", rule->arg.hlua_rule->fcn->name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009897 goto end;
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009898
9899 case HLUA_E_NOMEM:
Thierry Fournierad5345f2020-11-29 02:05:57 +01009900 SEND_ERR(px, "Lua function '%s': out of memory error.\n", rule->arg.hlua_rule->fcn->name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009901 goto end;
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009902
9903 case HLUA_E_YIELD:
Christopher Faulet498c4832020-07-28 11:59:58 +02009904 err_yield:
9905 act_ret = ACT_RET_CONT;
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009906 SEND_ERR(px, "Lua function '%s': aborting Lua processing on expired timeout.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009907 rule->arg.hlua_rule->fcn->name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009908 goto end;
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009909
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009910 case HLUA_E_ERR:
9911 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009912 SEND_ERR(px, "Lua function '%s' return an unknown error.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009913 rule->arg.hlua_rule->fcn->name);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009914
9915 default:
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009916 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009917 }
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009918
9919 end:
Christopher Faulet2361fd92020-07-30 10:40:58 +02009920 if (act_ret != ACT_RET_YIELD && s->hlua)
Christopher Faulet8f587ea2020-07-28 12:01:55 +02009921 s->hlua->wake_time = TICK_ETERNITY;
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009922 return act_ret;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009923}
9924
Willy Tarreau144f84a2021-03-02 16:09:26 +01009925struct task *hlua_applet_wakeup(struct task *t, void *context, unsigned int state)
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009926{
Olivier Houchard9f6af332018-05-25 14:04:04 +02009927 struct appctx *ctx = context;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009928
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009929 appctx_wakeup(ctx);
Willy Tarreaud9587412017-08-23 16:07:33 +02009930 t->expire = TICK_ETERNITY;
Willy Tarreaud1aa41f2017-07-21 16:41:56 +02009931 return t;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009932}
9933
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009934static int hlua_applet_tcp_init(struct appctx *ctx)
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009935{
Willy Tarreaue23f33b2022-05-06 14:07:13 +02009936 struct hlua_tcp_ctx *tcp_ctx = applet_reserve_svcctx(ctx, sizeof(*tcp_ctx));
Willy Tarreauc12b3212022-05-27 11:08:15 +02009937 struct stconn *sc = appctx_sc(ctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02009938 struct stream *strm = __sc_strm(sc);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009939 struct hlua *hlua;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009940 struct task *task;
9941 char **arg;
Thierry Fournierfd107a22016-02-19 19:57:23 +01009942 const char *error;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009943
Willy Tarreaubafbe012017-11-24 17:34:44 +01009944 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009945 if (!hlua) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009946 SEND_ERR(strm->be, "Lua applet tcp '%s': out of memory.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009947 ctx->rule->arg.hlua_rule->fcn->name);
Christopher Fauletc9929382022-05-12 11:52:27 +02009948 return -1;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009949 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009950 HLUA_INIT(hlua);
Willy Tarreaue23f33b2022-05-06 14:07:13 +02009951 tcp_ctx->hlua = hlua;
9952 tcp_ctx->flags = 0;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009953
9954 /* Create task used by signal to wakeup applets. */
Willy Tarreaubeeabf52021-10-01 18:23:30 +02009955 task = task_new_here();
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009956 if (!task) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009957 SEND_ERR(strm->be, "Lua applet tcp '%s': out of memory.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009958 ctx->rule->arg.hlua_rule->fcn->name);
Christopher Fauletc9929382022-05-12 11:52:27 +02009959 return -1;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009960 }
9961 task->nice = 0;
9962 task->context = ctx;
9963 task->process = hlua_applet_wakeup;
Willy Tarreaue23f33b2022-05-06 14:07:13 +02009964 tcp_ctx->task = task;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009965
9966 /* In the execution wrappers linked with a stream, the
9967 * Lua context can be not initialized. This behavior
9968 * permits to save performances because a systematic
9969 * Lua initialization cause 5% performances loss.
9970 */
Aurelien DARRAGON6b0b9bd2023-03-21 14:02:16 +01009971 if (!hlua_ctx_init(hlua, fcn_ref_to_stack_id(ctx->rule->arg.hlua_rule->fcn), task)) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009972 SEND_ERR(strm->be, "Lua applet tcp '%s': can't initialize Lua context.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009973 ctx->rule->arg.hlua_rule->fcn->name);
Christopher Fauletc9929382022-05-12 11:52:27 +02009974 return -1;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009975 }
9976
9977 /* Set timeout according with the applet configuration. */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02009978 hlua->max_time = ctx->applet->timeout;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009979
9980 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009981 if (!SET_SAFE_LJMP(hlua)) {
Thierry Fournierfd107a22016-02-19 19:57:23 +01009982 if (lua_type(hlua->T, -1) == LUA_TSTRING)
9983 error = lua_tostring(hlua->T, -1);
9984 else
9985 error = "critical error";
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009986 SEND_ERR(strm->be, "Lua applet tcp '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009987 ctx->rule->arg.hlua_rule->fcn->name, error);
Christopher Fauletc9929382022-05-12 11:52:27 +02009988 return -1;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009989 }
9990
9991 /* Check stack available size. */
9992 if (!lua_checkstack(hlua->T, 1)) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009993 SEND_ERR(strm->be, "Lua applet tcp '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009994 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009995 RESET_SAFE_LJMP(hlua);
Christopher Fauletc9929382022-05-12 11:52:27 +02009996 return -1;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009997 }
9998
9999 /* Restore the function in the stack. */
Aurelien DARRAGON4fdf8b52023-03-20 17:22:37 +010010000 hlua_pushref(hlua->T, ctx->rule->arg.hlua_rule->fcn->function_ref[hlua->state_id]);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010001
10002 /* Create and and push object stream in the stack. */
10003 if (!hlua_applet_tcp_new(hlua->T, ctx)) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +010010004 SEND_ERR(strm->be, "Lua applet tcp '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010005 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010006 RESET_SAFE_LJMP(hlua);
Christopher Fauletc9929382022-05-12 11:52:27 +020010007 return -1;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010008 }
10009 hlua->nargs = 1;
10010
10011 /* push keywords in the stack. */
10012 for (arg = ctx->rule->arg.hlua_rule->args; arg && *arg; arg++) {
10013 if (!lua_checkstack(hlua->T, 1)) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +010010014 SEND_ERR(strm->be, "Lua applet tcp '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010015 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010016 RESET_SAFE_LJMP(hlua);
Christopher Fauletc9929382022-05-12 11:52:27 +020010017 return -1;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010018 }
10019 lua_pushstring(hlua->T, *arg);
10020 hlua->nargs++;
10021 }
10022
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010023 RESET_SAFE_LJMP(hlua);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010024
10025 /* Wakeup the applet ASAP. */
Willy Tarreau90e8b452022-05-25 18:21:43 +020010026 applet_need_more_data(ctx);
Willy Tarreau4164eb92022-05-25 15:42:03 +020010027 applet_have_more_data(ctx);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010028
Christopher Fauletc9929382022-05-12 11:52:27 +020010029 return 0;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010030}
10031
Willy Tarreau60409db2019-08-21 14:14:50 +020010032void hlua_applet_tcp_fct(struct appctx *ctx)
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010033{
Willy Tarreaue23f33b2022-05-06 14:07:13 +020010034 struct hlua_tcp_ctx *tcp_ctx = ctx->svcctx;
Willy Tarreauc12b3212022-05-27 11:08:15 +020010035 struct stconn *sc = appctx_sc(ctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +020010036 struct stream *strm = __sc_strm(sc);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010037 struct act_rule *rule = ctx->rule;
10038 struct proxy *px = strm->be;
Willy Tarreaue23f33b2022-05-06 14:07:13 +020010039 struct hlua *hlua = tcp_ctx->hlua;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010040
Christopher Faulet31572222023-03-31 11:13:48 +020010041 if (unlikely(se_fl_test(ctx->sedesc, (SE_FL_EOS|SE_FL_ERROR|SE_FL_SHR|SE_FL_SHW))))
10042 goto out;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010043
Christopher Faulet31572222023-03-31 11:13:48 +020010044 /* The applet execution is already done. */
10045 if (tcp_ctx->flags & APPLET_DONE)
10046 goto out;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010047
10048 /* Execute the function. */
10049 switch (hlua_ctx_resume(hlua, 1)) {
10050 /* finished. */
10051 case HLUA_E_OK:
Willy Tarreaue23f33b2022-05-06 14:07:13 +020010052 tcp_ctx->flags |= APPLET_DONE;
Christopher Faulet31572222023-03-31 11:13:48 +020010053 se_fl_set(ctx->sedesc, SE_FL_EOI|SE_FL_EOS);
10054 break;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010055
10056 /* yield. */
10057 case HLUA_E_AGAIN:
Thierry Fournier0164f202016-02-20 17:47:43 +010010058 if (hlua->wake_time != TICK_ETERNITY)
Willy Tarreaue23f33b2022-05-06 14:07:13 +020010059 task_schedule(tcp_ctx->task, hlua->wake_time);
Christopher Faulet31572222023-03-31 11:13:48 +020010060 break;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010061
10062 /* finished with error. */
10063 case HLUA_E_ERRMSG:
10064 /* Display log. */
10065 SEND_ERR(px, "Lua applet tcp '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010066 rule->arg.hlua_rule->fcn->name, lua_tostring(hlua->T, -1));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010067 lua_pop(hlua->T, 1);
10068 goto error;
10069
Thierry Fournierd5b073c2018-05-21 19:42:47 +020010070 case HLUA_E_ETMOUT:
10071 SEND_ERR(px, "Lua applet tcp '%s': execution timeout.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010072 rule->arg.hlua_rule->fcn->name);
Thierry Fournierd5b073c2018-05-21 19:42:47 +020010073 goto error;
10074
10075 case HLUA_E_NOMEM:
10076 SEND_ERR(px, "Lua applet tcp '%s': out of memory error.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010077 rule->arg.hlua_rule->fcn->name);
Thierry Fournierd5b073c2018-05-21 19:42:47 +020010078 goto error;
10079
10080 case HLUA_E_YIELD: /* unexpected */
10081 SEND_ERR(px, "Lua applet tcp '%s': yield not allowed.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010082 rule->arg.hlua_rule->fcn->name);
Thierry Fournierd5b073c2018-05-21 19:42:47 +020010083 goto error;
10084
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010085 case HLUA_E_ERR:
10086 /* Display log. */
10087 SEND_ERR(px, "Lua applet tcp '%s' return an unknown error.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010088 rule->arg.hlua_rule->fcn->name);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010089 goto error;
10090
10091 default:
10092 goto error;
10093 }
10094
Christopher Faulet31572222023-03-31 11:13:48 +020010095out:
10096 /* eat the whole request */
10097 co_skip(sc_oc(sc), co_data(sc_oc(sc)));
10098 return;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010099
Christopher Faulet31572222023-03-31 11:13:48 +020010100error:
10101 se_fl_set(ctx->sedesc, SE_FL_ERROR);
Willy Tarreaue23f33b2022-05-06 14:07:13 +020010102 tcp_ctx->flags |= APPLET_DONE;
Christopher Faulet31572222023-03-31 11:13:48 +020010103 goto out;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010104}
10105
10106static void hlua_applet_tcp_release(struct appctx *ctx)
10107{
Willy Tarreaue23f33b2022-05-06 14:07:13 +020010108 struct hlua_tcp_ctx *tcp_ctx = ctx->svcctx;
10109
10110 task_destroy(tcp_ctx->task);
10111 tcp_ctx->task = NULL;
10112 hlua_ctx_destroy(tcp_ctx->hlua);
10113 tcp_ctx->hlua = NULL;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010114}
10115
Christopher Fauletc9929382022-05-12 11:52:27 +020010116/* The function returns 0 if the initialisation is complete or -1 if
10117 * an errors occurs. It also reserves the appctx for an hlua_http_ctx.
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010118 */
Christopher Faulet4aa1d282022-01-13 16:01:35 +010010119static int hlua_applet_http_init(struct appctx *ctx)
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010120{
Willy Tarreauaa229cc2022-05-06 14:26:10 +020010121 struct hlua_http_ctx *http_ctx = applet_reserve_svcctx(ctx, sizeof(*http_ctx));
Willy Tarreauc12b3212022-05-27 11:08:15 +020010122 struct stconn *sc = appctx_sc(ctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +020010123 struct stream *strm = __sc_strm(sc);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010124 struct http_txn *txn;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +010010125 struct hlua *hlua;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010126 char **arg;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010127 struct task *task;
Thierry Fournierfd107a22016-02-19 19:57:23 +010010128 const char *error;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010129
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010130 txn = strm->txn;
Willy Tarreaubafbe012017-11-24 17:34:44 +010010131 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +010010132 if (!hlua) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +010010133 SEND_ERR(strm->be, "Lua applet http '%s': out of memory.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010134 ctx->rule->arg.hlua_rule->fcn->name);
Christopher Fauletc9929382022-05-12 11:52:27 +020010135 return -1;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +010010136 }
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010137 HLUA_INIT(hlua);
Willy Tarreauaa229cc2022-05-06 14:26:10 +020010138 http_ctx->hlua = hlua;
10139 http_ctx->left_bytes = -1;
10140 http_ctx->flags = 0;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010141
Thierry FOURNIERd93ea2b2015-12-20 19:14:52 +010010142 if (txn->req.flags & HTTP_MSGF_VER_11)
Willy Tarreauaa229cc2022-05-06 14:26:10 +020010143 http_ctx->flags |= APPLET_HTTP11;
Thierry FOURNIERd93ea2b2015-12-20 19:14:52 +010010144
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010145 /* Create task used by signal to wakeup applets. */
Willy Tarreaubeeabf52021-10-01 18:23:30 +020010146 task = task_new_here();
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010147 if (!task) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +010010148 SEND_ERR(strm->be, "Lua applet http '%s': out of memory.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010149 ctx->rule->arg.hlua_rule->fcn->name);
Christopher Fauletc9929382022-05-12 11:52:27 +020010150 return -1;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010151 }
10152 task->nice = 0;
10153 task->context = ctx;
10154 task->process = hlua_applet_wakeup;
Willy Tarreauaa229cc2022-05-06 14:26:10 +020010155 http_ctx->task = task;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010156
10157 /* In the execution wrappers linked with a stream, the
10158 * Lua context can be not initialized. This behavior
10159 * permits to save performances because a systematic
10160 * Lua initialization cause 5% performances loss.
10161 */
Aurelien DARRAGON6b0b9bd2023-03-21 14:02:16 +010010162 if (!hlua_ctx_init(hlua, fcn_ref_to_stack_id(ctx->rule->arg.hlua_rule->fcn), task)) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +010010163 SEND_ERR(strm->be, "Lua applet http '%s': can't initialize Lua context.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010164 ctx->rule->arg.hlua_rule->fcn->name);
Christopher Fauletc9929382022-05-12 11:52:27 +020010165 return -1;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010166 }
10167
10168 /* Set timeout according with the applet configuration. */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +020010169 hlua->max_time = ctx->applet->timeout;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010170
10171 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010172 if (!SET_SAFE_LJMP(hlua)) {
Thierry Fournierfd107a22016-02-19 19:57:23 +010010173 if (lua_type(hlua->T, -1) == LUA_TSTRING)
10174 error = lua_tostring(hlua->T, -1);
10175 else
10176 error = "critical error";
Christopher Faulet4aa1d282022-01-13 16:01:35 +010010177 SEND_ERR(strm->be, "Lua applet http '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010178 ctx->rule->arg.hlua_rule->fcn->name, error);
Christopher Fauletc9929382022-05-12 11:52:27 +020010179 return -1;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010180 }
10181
10182 /* Check stack available size. */
10183 if (!lua_checkstack(hlua->T, 1)) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +010010184 SEND_ERR(strm->be, "Lua applet http '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010185 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010186 RESET_SAFE_LJMP(hlua);
Christopher Fauletc9929382022-05-12 11:52:27 +020010187 return -1;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010188 }
10189
10190 /* Restore the function in the stack. */
Aurelien DARRAGON4fdf8b52023-03-20 17:22:37 +010010191 hlua_pushref(hlua->T, ctx->rule->arg.hlua_rule->fcn->function_ref[hlua->state_id]);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010192
10193 /* Create and and push object stream in the stack. */
10194 if (!hlua_applet_http_new(hlua->T, ctx)) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +010010195 SEND_ERR(strm->be, "Lua applet http '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010196 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010197 RESET_SAFE_LJMP(hlua);
Christopher Fauletc9929382022-05-12 11:52:27 +020010198 return -1;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010199 }
10200 hlua->nargs = 1;
10201
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010202 /* push keywords in the stack. */
10203 for (arg = ctx->rule->arg.hlua_rule->args; arg && *arg; arg++) {
10204 if (!lua_checkstack(hlua->T, 1)) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +010010205 SEND_ERR(strm->be, "Lua applet http '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010206 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010207 RESET_SAFE_LJMP(hlua);
Christopher Fauletc9929382022-05-12 11:52:27 +020010208 return -1;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010209 }
10210 lua_pushstring(hlua->T, *arg);
10211 hlua->nargs++;
10212 }
10213
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010214 RESET_SAFE_LJMP(hlua);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010215
10216 /* Wakeup the applet when data is ready for read. */
Willy Tarreau90e8b452022-05-25 18:21:43 +020010217 applet_need_more_data(ctx);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010218
Christopher Fauletc9929382022-05-12 11:52:27 +020010219 return 0;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010220}
10221
Willy Tarreau60409db2019-08-21 14:14:50 +020010222void hlua_applet_http_fct(struct appctx *ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010223{
Willy Tarreauaa229cc2022-05-06 14:26:10 +020010224 struct hlua_http_ctx *http_ctx = ctx->svcctx;
Willy Tarreauc12b3212022-05-27 11:08:15 +020010225 struct stconn *sc = appctx_sc(ctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +020010226 struct stream *strm = __sc_strm(sc);
10227 struct channel *req = sc_oc(sc);
10228 struct channel *res = sc_ic(sc);
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010229 struct act_rule *rule = ctx->rule;
10230 struct proxy *px = strm->be;
Willy Tarreauaa229cc2022-05-06 14:26:10 +020010231 struct hlua *hlua = http_ctx->hlua;
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010232 struct htx *req_htx, *res_htx;
10233
10234 res_htx = htx_from_buf(&res->buf);
10235
Christopher Faulet31572222023-03-31 11:13:48 +020010236 if (unlikely(se_fl_test(ctx->sedesc, (SE_FL_EOS|SE_FL_ERROR|SE_FL_SHR|SE_FL_SHW))))
10237 goto out;
10238
10239 /* The applet execution is already done. */
10240 if (http_ctx->flags & APPLET_DONE)
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010241 goto out;
10242
Ilya Shipitsin856aabc2020-04-16 23:51:34 +050010243 /* Check if the input buffer is available. */
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010244 if (!b_size(&res->buf)) {
Willy Tarreau3e7be362022-05-27 10:35:27 +020010245 sc_need_room(sc);
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010246 goto out;
10247 }
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010248
10249 /* Set the currently running flag. */
10250 if (!HLUA_IS_RUNNING(hlua) &&
Willy Tarreauaa229cc2022-05-06 14:26:10 +020010251 !(http_ctx->flags & APPLET_DONE)) {
Christopher Fauletbd878d22021-04-28 10:50:21 +020010252 if (!co_data(req)) {
Willy Tarreau90e8b452022-05-25 18:21:43 +020010253 applet_need_more_data(ctx);
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010254 goto out;
10255 }
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010256 }
10257
Christopher Faulet31572222023-03-31 11:13:48 +020010258 /* Execute the function. */
10259 switch (hlua_ctx_resume(hlua, 1)) {
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010260 /* finished. */
10261 case HLUA_E_OK:
Willy Tarreauaa229cc2022-05-06 14:26:10 +020010262 http_ctx->flags |= APPLET_DONE;
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010263 break;
10264
10265 /* yield. */
10266 case HLUA_E_AGAIN:
10267 if (hlua->wake_time != TICK_ETERNITY)
Willy Tarreauaa229cc2022-05-06 14:26:10 +020010268 task_schedule(http_ctx->task, hlua->wake_time);
Christopher Faulet56a3d6e2019-02-27 22:06:23 +010010269 goto out;
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010270
10271 /* finished with error. */
10272 case HLUA_E_ERRMSG:
10273 /* Display log. */
10274 SEND_ERR(px, "Lua applet http '%s': %s.\n",
Christopher Faulet31572222023-03-31 11:13:48 +020010275 rule->arg.hlua_rule->fcn->name, lua_tostring(hlua->T, -1));
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010276 lua_pop(hlua->T, 1);
10277 goto error;
10278
10279 case HLUA_E_ETMOUT:
10280 SEND_ERR(px, "Lua applet http '%s': execution timeout.\n",
Christopher Faulet31572222023-03-31 11:13:48 +020010281 rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010282 goto error;
10283
10284 case HLUA_E_NOMEM:
10285 SEND_ERR(px, "Lua applet http '%s': out of memory error.\n",
Christopher Faulet31572222023-03-31 11:13:48 +020010286 rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010287 goto error;
10288
10289 case HLUA_E_YIELD: /* unexpected */
10290 SEND_ERR(px, "Lua applet http '%s': yield not allowed.\n",
Christopher Faulet31572222023-03-31 11:13:48 +020010291 rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010292 goto error;
10293
10294 case HLUA_E_ERR:
10295 /* Display log. */
10296 SEND_ERR(px, "Lua applet http '%s' return an unknown error.\n",
Christopher Faulet31572222023-03-31 11:13:48 +020010297 rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010298 goto error;
10299
10300 default:
10301 goto error;
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010302 }
10303
Willy Tarreauaa229cc2022-05-06 14:26:10 +020010304 if (http_ctx->flags & APPLET_DONE) {
10305 if (http_ctx->flags & APPLET_RSP_SENT)
Christopher Faulet31572222023-03-31 11:13:48 +020010306 goto out;
Christopher Faulet56a3d6e2019-02-27 22:06:23 +010010307
Willy Tarreauaa229cc2022-05-06 14:26:10 +020010308 if (!(http_ctx->flags & APPLET_HDR_SENT))
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010309 goto error;
10310
Christopher Fauletf89af9c2022-04-07 10:07:18 +020010311 /* no more data are expected. If the response buffer is empty
10312 * for a chunked message, be sure to add something (EOT block in
10313 * this case) to have something to send. It is important to be
10314 * sure the EOM flags will be handled by the endpoint.
10315 */
10316 if (htx_is_empty(res_htx) && (strm->txn->rsp.flags & (HTTP_MSGF_XFER_LEN|HTTP_MSGF_CNT_LEN)) == HTTP_MSGF_XFER_LEN) {
10317 if (!htx_add_endof(res_htx, HTX_BLK_EOT)) {
Willy Tarreau3e7be362022-05-27 10:35:27 +020010318 sc_need_room(sc);
Christopher Fauletf89af9c2022-04-07 10:07:18 +020010319 goto out;
10320 }
10321 channel_add_input(res, 1);
10322 }
10323
Christopher Fauletd1ac2b92020-12-02 19:12:22 +010010324 res_htx->flags |= HTX_FL_EOM;
Christopher Faulet31572222023-03-31 11:13:48 +020010325 se_fl_set(ctx->sedesc, SE_FL_EOI|SE_FL_EOS);
Willy Tarreauaa229cc2022-05-06 14:26:10 +020010326 strm->txn->status = http_ctx->status;
10327 http_ctx->flags |= APPLET_RSP_SENT;
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010328 }
10329
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010330 out:
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010331 htx_to_buf(res_htx, &res->buf);
Christopher Faulet31572222023-03-31 11:13:48 +020010332 /* eat the whole request */
10333 if (co_data(req)) {
10334 req_htx = htx_from_buf(&req->buf);
10335 co_htx_skip(req, req_htx, co_data(req));
10336 htx_to_buf(req_htx, &req->buf);
10337 }
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010338 return;
10339
10340 error:
10341
10342 /* If we are in HTTP mode, and we are not send any
10343 * data, return a 500 server error in best effort:
10344 * if there is no room available in the buffer,
10345 * just close the connection.
10346 */
Willy Tarreauaa229cc2022-05-06 14:26:10 +020010347 if (!(http_ctx->flags & APPLET_HDR_SENT)) {
Christopher Fauletf7346382019-07-17 22:02:08 +020010348 struct buffer *err = &http_err_chunks[HTTP_ERR_500];
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010349
10350 channel_erase(res);
10351 res->buf.data = b_data(err);
10352 memcpy(res->buf.area, b_head(err), b_data(err));
10353 res_htx = htx_from_buf(&res->buf);
Christopher Fauletf6cce3f2019-02-27 21:20:09 +010010354 channel_add_input(res, res_htx->data);
Christopher Faulet31572222023-03-31 11:13:48 +020010355 se_fl_set(ctx->sedesc, SE_FL_EOI|SE_FL_EOS);
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010356 }
Christopher Faulet31572222023-03-31 11:13:48 +020010357 else
10358 se_fl_set(ctx->sedesc, SE_FL_ERROR);
10359
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010360 if (!(strm->flags & SF_ERR_MASK))
10361 strm->flags |= SF_ERR_RESOURCE;
Willy Tarreauaa229cc2022-05-06 14:26:10 +020010362 http_ctx->flags |= APPLET_DONE;
Christopher Faulet31572222023-03-31 11:13:48 +020010363 goto out;
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010364}
10365
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010366static void hlua_applet_http_release(struct appctx *ctx)
10367{
Willy Tarreauaa229cc2022-05-06 14:26:10 +020010368 struct hlua_http_ctx *http_ctx = ctx->svcctx;
10369
10370 task_destroy(http_ctx->task);
10371 http_ctx->task = NULL;
10372 hlua_ctx_destroy(http_ctx->hlua);
10373 http_ctx->hlua = NULL;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010374}
10375
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +020010376/* global {tcp|http}-request parser. Return ACT_RET_PRS_OK in
Ilya Shipitsin856aabc2020-04-16 23:51:34 +050010377 * success case, else return ACT_RET_PRS_ERR.
Thierry FOURNIERbabae282015-09-17 11:36:37 +020010378 *
10379 * This function can fail with an abort() due to an Lua critical error.
10380 * We are in the configuration parsing process of HAProxy, this abort() is
10381 * tolerated.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +010010382 */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +020010383static enum act_parse_ret action_register_lua(const char **args, int *cur_arg, struct proxy *px,
10384 struct act_rule *rule, char **err)
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +010010385{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +020010386 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +010010387 int i;
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010388
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +020010389 /* Memory for the rule. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +020010390 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +020010391 if (!rule->arg.hlua_rule) {
10392 memprintf(err, "out of memory error");
Christopher Faulet528526f2021-04-12 14:37:32 +020010393 goto error;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +020010394 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +010010395
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +010010396 /* Memory for arguments. */
Tim Duesterhuse52b6e52020-09-12 20:26:43 +020010397 rule->arg.hlua_rule->args = calloc(fcn->nargs + 1,
10398 sizeof(*rule->arg.hlua_rule->args));
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +010010399 if (!rule->arg.hlua_rule->args) {
10400 memprintf(err, "out of memory error");
Christopher Faulet528526f2021-04-12 14:37:32 +020010401 goto error;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +010010402 }
10403
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +020010404 /* Reference the Lua function and store the reference. */
Thierry Fournierad5345f2020-11-29 02:05:57 +010010405 rule->arg.hlua_rule->fcn = fcn;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +020010406
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +010010407 /* Expect some arguments */
10408 for (i = 0; i < fcn->nargs; i++) {
Thierry FOURNIER1725c2e2019-01-06 19:38:49 +010010409 if (*args[*cur_arg] == '\0') {
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +010010410 memprintf(err, "expect %d arguments", fcn->nargs);
Christopher Faulet528526f2021-04-12 14:37:32 +020010411 goto error;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +010010412 }
Thierry FOURNIER1725c2e2019-01-06 19:38:49 +010010413 rule->arg.hlua_rule->args[i] = strdup(args[*cur_arg]);
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +010010414 if (!rule->arg.hlua_rule->args[i]) {
10415 memprintf(err, "out of memory error");
Christopher Faulet528526f2021-04-12 14:37:32 +020010416 goto error;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +010010417 }
10418 (*cur_arg)++;
10419 }
10420 rule->arg.hlua_rule->args[i] = NULL;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +020010421
Thierry FOURNIER42148732015-09-02 17:17:33 +020010422 rule->action = ACT_CUSTOM;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +020010423 rule->action_ptr = hlua_action;
Thierry FOURNIERafa80492015-08-19 09:04:15 +020010424 return ACT_RET_PRS_OK;
Christopher Faulet528526f2021-04-12 14:37:32 +020010425
10426 error:
10427 if (rule->arg.hlua_rule) {
10428 if (rule->arg.hlua_rule->args) {
10429 for (i = 0; i < fcn->nargs; i++)
10430 ha_free(&rule->arg.hlua_rule->args[i]);
10431 ha_free(&rule->arg.hlua_rule->args);
10432 }
10433 ha_free(&rule->arg.hlua_rule);
10434 }
10435 return ACT_RET_PRS_ERR;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +010010436}
10437
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010438static enum act_parse_ret action_register_service_http(const char **args, int *cur_arg, struct proxy *px,
10439 struct act_rule *rule, char **err)
10440{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +020010441 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010442
Thierry FOURNIER718e2a72015-12-20 20:13:14 +010010443 /* HTTP applets are forbidden in tcp-request rules.
Ilya Shipitsin856aabc2020-04-16 23:51:34 +050010444 * HTTP applet request requires everything initialized by
Thierry FOURNIER718e2a72015-12-20 20:13:14 +010010445 * "http_process_request" (analyzer flag AN_REQ_HTTP_INNER).
Ilya Shipitsin856aabc2020-04-16 23:51:34 +050010446 * The applet will be immediately initialized, but its before
Thierry FOURNIER718e2a72015-12-20 20:13:14 +010010447 * the call of this analyzer.
10448 */
10449 if (rule->from != ACT_F_HTTP_REQ) {
10450 memprintf(err, "HTTP applets are forbidden from 'tcp-request' rulesets");
10451 return ACT_RET_PRS_ERR;
10452 }
10453
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010454 /* Memory for the rule. */
10455 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
10456 if (!rule->arg.hlua_rule) {
10457 memprintf(err, "out of memory error");
10458 return ACT_RET_PRS_ERR;
10459 }
10460
10461 /* Reference the Lua function and store the reference. */
Thierry Fournierad5345f2020-11-29 02:05:57 +010010462 rule->arg.hlua_rule->fcn = fcn;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010463
10464 /* TODO: later accept arguments. */
10465 rule->arg.hlua_rule->args = NULL;
10466
10467 /* Add applet pointer in the rule. */
10468 rule->applet.obj_type = OBJ_TYPE_APPLET;
10469 rule->applet.name = fcn->name;
10470 rule->applet.init = hlua_applet_http_init;
10471 rule->applet.fct = hlua_applet_http_fct;
10472 rule->applet.release = hlua_applet_http_release;
10473 rule->applet.timeout = hlua_timeout_applet;
10474
10475 return ACT_RET_PRS_OK;
10476}
10477
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010478/* This function is an LUA binding used for registering
10479 * "sample-conv" functions. It expects a converter name used
10480 * in the haproxy configuration file, and an LUA function.
10481 */
10482__LJMP static int hlua_register_action(lua_State *L)
10483{
Christopher Faulet4fc9da02021-04-12 15:08:12 +020010484 struct action_kw_list *akl = NULL;
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010485 const char *name;
10486 int ref;
10487 int len;
Christopher Faulet4fc9da02021-04-12 15:08:12 +020010488 struct hlua_function *fcn = NULL;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +010010489 int nargs;
Thierry Fournierf67442e2020-11-28 20:41:07 +010010490 struct buffer *trash;
10491 struct action_kw *akw;
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010492
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +010010493 /* Initialise the number of expected arguments at 0. */
10494 nargs = 0;
10495
10496 if (lua_gettop(L) < 3 || lua_gettop(L) > 4)
10497 WILL_LJMP(luaL_error(L, "'register_action' needs between 3 and 4 arguments"));
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010498
Aurelien DARRAGON87f52972023-02-24 09:43:54 +010010499 if (hlua_gethlua(L)) {
10500 /* runtime processing */
10501 WILL_LJMP(luaL_error(L, "register_action: not available outside of body context"));
10502 }
10503
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010504 /* First argument : converter name. */
10505 name = MAY_LJMP(luaL_checkstring(L, 1));
10506
10507 /* Second argument : environment. */
10508 if (lua_type(L, 2) != LUA_TTABLE)
10509 WILL_LJMP(luaL_error(L, "register_action: second argument must be a table of strings"));
10510
10511 /* Third argument : lua function. */
10512 ref = MAY_LJMP(hlua_checkfunction(L, 3));
10513
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -080010514 /* Fourth argument : number of mandatory arguments expected on the configuration line. */
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +010010515 if (lua_gettop(L) >= 4)
10516 nargs = MAY_LJMP(luaL_checkinteger(L, 4));
10517
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -080010518 /* browse the second argument as an array. */
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010519 lua_pushnil(L);
10520 while (lua_next(L, 2) != 0) {
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +010010521 if (lua_type(L, -1) != LUA_TSTRING) {
10522 hlua_unref(L, ref);
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010523 WILL_LJMP(luaL_error(L, "register_action: second argument must be a table of strings"));
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +010010524 }
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010525
Thierry Fournierf67442e2020-11-28 20:41:07 +010010526 /* Check if action exists */
10527 trash = get_trash_chunk();
10528 chunk_printf(trash, "lua.%s", name);
10529 if (strcmp(lua_tostring(L, -1), "tcp-req") == 0) {
10530 akw = tcp_req_cont_action(trash->area);
10531 } else if (strcmp(lua_tostring(L, -1), "tcp-res") == 0) {
10532 akw = tcp_res_cont_action(trash->area);
10533 } else if (strcmp(lua_tostring(L, -1), "http-req") == 0) {
10534 akw = action_http_req_custom(trash->area);
10535 } else if (strcmp(lua_tostring(L, -1), "http-res") == 0) {
10536 akw = action_http_res_custom(trash->area);
10537 } else {
10538 akw = NULL;
10539 }
10540 if (akw != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +010010541 fcn = akw->private;
10542 if (fcn->function_ref[hlua_state_id] != -1) {
10543 ha_warning("Trying to register action 'lua.%s' more than once. "
10544 "This will become a hard error in version 2.5.\n", name);
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +010010545 hlua_unref(L, fcn->function_ref[hlua_state_id]);
Thierry Fournier59f11be2020-11-29 00:37:41 +010010546 }
10547 fcn->function_ref[hlua_state_id] = ref;
10548
10549 /* pop the environment string. */
10550 lua_pop(L, 1);
10551 continue;
Thierry Fournierf67442e2020-11-28 20:41:07 +010010552 }
10553
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010554 /* Check required environment. Only accepted "http" or "tcp". */
10555 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +020010556 akl = calloc(1, sizeof(*akl) + sizeof(struct action_kw) * 2);
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010557 if (!akl)
Christopher Faulet4fc9da02021-04-12 15:08:12 +020010558 goto alloc_error;;
Thierry Fournier62a22aa2020-11-28 21:06:35 +010010559 fcn = new_hlua_function();
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010560 if (!fcn)
Christopher Faulet4fc9da02021-04-12 15:08:12 +020010561 goto alloc_error;
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010562
10563 /* Fill fcn. */
10564 fcn->name = strdup(name);
10565 if (!fcn->name)
Christopher Faulet4fc9da02021-04-12 15:08:12 +020010566 goto alloc_error;
Thierry Fournierc7492592020-11-28 23:57:24 +010010567 fcn->function_ref[hlua_state_id] = ref;
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010568
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -070010569 /* Set the expected number of arguments. */
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +010010570 fcn->nargs = nargs;
10571
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010572 /* List head */
10573 akl->list.n = akl->list.p = NULL;
10574
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010575 /* action keyword. */
10576 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +020010577 akl->kw[0].kw = calloc(1, len);
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010578 if (!akl->kw[0].kw)
Christopher Faulet4fc9da02021-04-12 15:08:12 +020010579 goto alloc_error;
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010580
10581 snprintf((char *)akl->kw[0].kw, len, "lua.%s", name);
10582
Amaury Denoyellee4a617c2021-05-06 15:33:09 +020010583 akl->kw[0].flags = 0;
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010584 akl->kw[0].private = fcn;
10585 akl->kw[0].parse = action_register_lua;
10586
10587 /* select the action registering point. */
10588 if (strcmp(lua_tostring(L, -1), "tcp-req") == 0)
10589 tcp_req_cont_keywords_register(akl);
10590 else if (strcmp(lua_tostring(L, -1), "tcp-res") == 0)
10591 tcp_res_cont_keywords_register(akl);
10592 else if (strcmp(lua_tostring(L, -1), "http-req") == 0)
10593 http_req_keywords_register(akl);
10594 else if (strcmp(lua_tostring(L, -1), "http-res") == 0)
10595 http_res_keywords_register(akl);
Christopher Faulet4fc9da02021-04-12 15:08:12 +020010596 else {
10597 release_hlua_function(fcn);
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +010010598 hlua_unref(L, ref);
Christopher Faulet4fc9da02021-04-12 15:08:12 +020010599 if (akl)
10600 ha_free((char **)&(akl->kw[0].kw));
10601 ha_free(&akl);
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +010010602 WILL_LJMP(luaL_error(L, "Lua action environment '%s' is unknown. "
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010603 "'tcp-req', 'tcp-res', 'http-req' or 'http-res' "
10604 "are expected.", lua_tostring(L, -1)));
Christopher Faulet4fc9da02021-04-12 15:08:12 +020010605 }
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010606
10607 /* pop the environment string. */
10608 lua_pop(L, 1);
Christopher Faulet4fc9da02021-04-12 15:08:12 +020010609
10610 /* reset for next loop */
10611 akl = NULL;
10612 fcn = NULL;
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010613 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010614 return ACT_RET_PRS_OK;
Christopher Faulet4fc9da02021-04-12 15:08:12 +020010615
10616 alloc_error:
10617 release_hlua_function(fcn);
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +010010618 hlua_unref(L, ref);
Christopher Faulet4fc9da02021-04-12 15:08:12 +020010619 ha_free(&akl);
10620 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
10621 return 0; /* Never reached */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010622}
10623
10624static enum act_parse_ret action_register_service_tcp(const char **args, int *cur_arg, struct proxy *px,
10625 struct act_rule *rule, char **err)
10626{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +020010627 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010628
Christopher Faulet280f85b2019-07-15 15:02:04 +020010629 if (px->mode == PR_MODE_HTTP) {
10630 memprintf(err, "Lua TCP services cannot be used on HTTP proxies");
Christopher Fauletafd8f102018-11-08 11:34:21 +010010631 return ACT_RET_PRS_ERR;
10632 }
10633
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010634 /* Memory for the rule. */
10635 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
10636 if (!rule->arg.hlua_rule) {
10637 memprintf(err, "out of memory error");
10638 return ACT_RET_PRS_ERR;
10639 }
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010640
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010641 /* Reference the Lua function and store the reference. */
Thierry Fournierad5345f2020-11-29 02:05:57 +010010642 rule->arg.hlua_rule->fcn = fcn;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010643
10644 /* TODO: later accept arguments. */
10645 rule->arg.hlua_rule->args = NULL;
10646
10647 /* Add applet pointer in the rule. */
10648 rule->applet.obj_type = OBJ_TYPE_APPLET;
10649 rule->applet.name = fcn->name;
10650 rule->applet.init = hlua_applet_tcp_init;
10651 rule->applet.fct = hlua_applet_tcp_fct;
10652 rule->applet.release = hlua_applet_tcp_release;
10653 rule->applet.timeout = hlua_timeout_applet;
10654
10655 return 0;
10656}
10657
10658/* This function is an LUA binding used for registering
10659 * "sample-conv" functions. It expects a converter name used
10660 * in the haproxy configuration file, and an LUA function.
10661 */
10662__LJMP static int hlua_register_service(lua_State *L)
10663{
10664 struct action_kw_list *akl;
10665 const char *name;
10666 const char *env;
10667 int ref;
10668 int len;
Christopher Faulet5c028d72021-04-12 15:11:44 +020010669 struct hlua_function *fcn = NULL;
Thierry Fournierf67442e2020-11-28 20:41:07 +010010670 struct buffer *trash;
10671 struct action_kw *akw;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010672
10673 MAY_LJMP(check_args(L, 3, "register_service"));
10674
Aurelien DARRAGON87f52972023-02-24 09:43:54 +010010675 if (hlua_gethlua(L)) {
10676 /* runtime processing */
10677 WILL_LJMP(luaL_error(L, "register_service: not available outside of body context"));
10678 }
10679
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010680 /* First argument : converter name. */
10681 name = MAY_LJMP(luaL_checkstring(L, 1));
10682
10683 /* Second argument : environment. */
10684 env = MAY_LJMP(luaL_checkstring(L, 2));
10685
10686 /* Third argument : lua function. */
10687 ref = MAY_LJMP(hlua_checkfunction(L, 3));
10688
Thierry Fournierf67442e2020-11-28 20:41:07 +010010689 /* Check for service already registered */
10690 trash = get_trash_chunk();
10691 chunk_printf(trash, "lua.%s", name);
10692 akw = service_find(trash->area);
10693 if (akw != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +010010694 fcn = akw->private;
10695 if (fcn->function_ref[hlua_state_id] != -1) {
10696 ha_warning("Trying to register service 'lua.%s' more than once. "
10697 "This will become a hard error in version 2.5.\n", name);
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +010010698 hlua_unref(L, fcn->function_ref[hlua_state_id]);
Thierry Fournier59f11be2020-11-29 00:37:41 +010010699 }
10700 fcn->function_ref[hlua_state_id] = ref;
10701 return 0;
Thierry Fournierf67442e2020-11-28 20:41:07 +010010702 }
10703
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010704 /* Allocate and fill the sample fetch keyword struct. */
10705 akl = calloc(1, sizeof(*akl) + sizeof(struct action_kw) * 2);
10706 if (!akl)
Christopher Faulet5c028d72021-04-12 15:11:44 +020010707 goto alloc_error;
Thierry Fournier62a22aa2020-11-28 21:06:35 +010010708 fcn = new_hlua_function();
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010709 if (!fcn)
Christopher Faulet5c028d72021-04-12 15:11:44 +020010710 goto alloc_error;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010711
10712 /* Fill fcn. */
10713 len = strlen("<lua.>") + strlen(name) + 1;
10714 fcn->name = calloc(1, len);
10715 if (!fcn->name)
Christopher Faulet5c028d72021-04-12 15:11:44 +020010716 goto alloc_error;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010717 snprintf((char *)fcn->name, len, "<lua.%s>", name);
Thierry Fournierc7492592020-11-28 23:57:24 +010010718 fcn->function_ref[hlua_state_id] = ref;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010719
10720 /* List head */
10721 akl->list.n = akl->list.p = NULL;
10722
10723 /* converter keyword. */
10724 len = strlen("lua.") + strlen(name) + 1;
10725 akl->kw[0].kw = calloc(1, len);
10726 if (!akl->kw[0].kw)
Christopher Faulet5c028d72021-04-12 15:11:44 +020010727 goto alloc_error;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010728
10729 snprintf((char *)akl->kw[0].kw, len, "lua.%s", name);
10730
Thierry FOURNIER / OZON.IO02564fd2016-11-12 11:07:05 +010010731 /* Check required environment. Only accepted "http" or "tcp". */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010732 if (strcmp(env, "tcp") == 0)
10733 akl->kw[0].parse = action_register_service_tcp;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010734 else if (strcmp(env, "http") == 0)
10735 akl->kw[0].parse = action_register_service_http;
Christopher Faulet5c028d72021-04-12 15:11:44 +020010736 else {
10737 release_hlua_function(fcn);
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +010010738 hlua_unref(L, ref);
Christopher Faulet5c028d72021-04-12 15:11:44 +020010739 if (akl)
10740 ha_free((char **)&(akl->kw[0].kw));
10741 ha_free(&akl);
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +010010742 WILL_LJMP(luaL_error(L, "Lua service environment '%s' is unknown. "
Eric Salamafe7456f2017-12-21 14:30:07 +010010743 "'tcp' or 'http' are expected.", env));
Christopher Faulet5c028d72021-04-12 15:11:44 +020010744 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010745
Amaury Denoyellee4a617c2021-05-06 15:33:09 +020010746 akl->kw[0].flags = 0;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010747 akl->kw[0].private = fcn;
10748
10749 /* End of array. */
10750 memset(&akl->kw[1], 0, sizeof(*akl->kw));
10751
10752 /* Register this new converter */
10753 service_keywords_register(akl);
10754
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010755 return 0;
Christopher Faulet5c028d72021-04-12 15:11:44 +020010756
10757 alloc_error:
10758 release_hlua_function(fcn);
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +010010759 hlua_unref(L, ref);
Christopher Faulet5c028d72021-04-12 15:11:44 +020010760 ha_free(&akl);
10761 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
10762 return 0; /* Never reached */
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010763}
10764
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010765/* This function initialises Lua cli handler. It copies the
10766 * arguments in the Lua stack and create channel IO objects.
10767 */
Aurélien Nephtaliabbf6072018-04-18 13:26:46 +020010768static int hlua_cli_parse_fct(char **args, char *payload, struct appctx *appctx, void *private)
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010769{
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010770 struct hlua_cli_ctx *ctx = applet_reserve_svcctx(appctx, sizeof(*ctx));
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010771 struct hlua *hlua;
10772 struct hlua_function *fcn;
10773 int i;
10774 const char *error;
10775
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010776 fcn = private;
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010777 ctx->fcn = private;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +010010778
Willy Tarreaubafbe012017-11-24 17:34:44 +010010779 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +010010780 if (!hlua) {
10781 SEND_ERR(NULL, "Lua cli '%s': out of memory.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +010010782 return 1;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +010010783 }
10784 HLUA_INIT(hlua);
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010785 ctx->hlua = hlua;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010786
10787 /* Create task used by signal to wakeup applets.
Ilya Shipitsind4259502020-04-08 01:07:56 +050010788 * We use the same wakeup function than the Lua applet_tcp and
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010789 * applet_http. It is absolutely compatible.
10790 */
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010791 ctx->task = task_new_here();
10792 if (!ctx->task) {
Thierry FOURNIERffbf5692016-12-16 11:14:06 +010010793 SEND_ERR(NULL, "Lua cli '%s': out of memory.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +010010794 goto error;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010795 }
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010796 ctx->task->nice = 0;
10797 ctx->task->context = appctx;
10798 ctx->task->process = hlua_applet_wakeup;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010799
10800 /* Initialises the Lua context */
Aurelien DARRAGON6b0b9bd2023-03-21 14:02:16 +010010801 if (!hlua_ctx_init(hlua, fcn_ref_to_stack_id(fcn), ctx->task)) {
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010802 SEND_ERR(NULL, "Lua cli '%s': can't initialize Lua context.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +010010803 goto error;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010804 }
10805
10806 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010807 if (!SET_SAFE_LJMP(hlua)) {
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010808 if (lua_type(hlua->T, -1) == LUA_TSTRING)
10809 error = lua_tostring(hlua->T, -1);
10810 else
10811 error = "critical error";
10812 SEND_ERR(NULL, "Lua cli '%s': %s.\n", fcn->name, error);
10813 goto error;
10814 }
10815
10816 /* Check stack available size. */
10817 if (!lua_checkstack(hlua->T, 2)) {
10818 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
10819 goto error;
10820 }
10821
10822 /* Restore the function in the stack. */
Aurelien DARRAGON4fdf8b52023-03-20 17:22:37 +010010823 hlua_pushref(hlua->T, fcn->function_ref[hlua->state_id]);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010824
10825 /* Once the arguments parsed, the CLI is like an AppletTCP,
10826 * so push AppletTCP in the stack.
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010827 */
10828 if (!hlua_applet_tcp_new(hlua->T, appctx)) {
10829 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
10830 goto error;
10831 }
10832 hlua->nargs = 1;
10833
10834 /* push keywords in the stack. */
10835 for (i = 0; *args[i]; i++) {
10836 /* Check stack available size. */
10837 if (!lua_checkstack(hlua->T, 1)) {
10838 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
10839 goto error;
10840 }
10841 lua_pushstring(hlua->T, args[i]);
10842 hlua->nargs++;
10843 }
10844
10845 /* We must initialize the execution timeouts. */
10846 hlua->max_time = hlua_timeout_session;
10847
10848 /* At this point the execution is safe. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010849 RESET_SAFE_LJMP(hlua);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010850
10851 /* It's ok */
10852 return 0;
10853
10854 /* It's not ok. */
10855error:
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010856 RESET_SAFE_LJMP(hlua);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010857 hlua_ctx_destroy(hlua);
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010858 ctx->hlua = NULL;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010859 return 1;
10860}
10861
10862static int hlua_cli_io_handler_fct(struct appctx *appctx)
10863{
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010864 struct hlua_cli_ctx *ctx = appctx->svcctx;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010865 struct hlua *hlua;
Willy Tarreau475e4632022-05-27 10:26:46 +020010866 struct stconn *sc;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010867 struct hlua_function *fcn;
10868
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010869 hlua = ctx->hlua;
Willy Tarreauc12b3212022-05-27 11:08:15 +020010870 sc = appctx_sc(appctx);
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010871 fcn = ctx->fcn;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010872
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010873 /* Execute the function. */
10874 switch (hlua_ctx_resume(hlua, 1)) {
10875
10876 /* finished. */
10877 case HLUA_E_OK:
10878 return 1;
10879
10880 /* yield. */
10881 case HLUA_E_AGAIN:
10882 /* We want write. */
10883 if (HLUA_IS_WAKERESWR(hlua))
Willy Tarreau475e4632022-05-27 10:26:46 +020010884 sc_need_room(sc);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010885 /* Set the timeout. */
10886 if (hlua->wake_time != TICK_ETERNITY)
10887 task_schedule(hlua->task, hlua->wake_time);
10888 return 0;
10889
10890 /* finished with error. */
10891 case HLUA_E_ERRMSG:
10892 /* Display log. */
10893 SEND_ERR(NULL, "Lua cli '%s': %s.\n",
10894 fcn->name, lua_tostring(hlua->T, -1));
10895 lua_pop(hlua->T, 1);
10896 return 1;
10897
Thierry Fournierd5b073c2018-05-21 19:42:47 +020010898 case HLUA_E_ETMOUT:
10899 SEND_ERR(NULL, "Lua converter '%s': execution timeout.\n",
10900 fcn->name);
10901 return 1;
10902
10903 case HLUA_E_NOMEM:
10904 SEND_ERR(NULL, "Lua converter '%s': out of memory error.\n",
10905 fcn->name);
10906 return 1;
10907
10908 case HLUA_E_YIELD: /* unexpected */
10909 SEND_ERR(NULL, "Lua converter '%s': yield not allowed.\n",
10910 fcn->name);
10911 return 1;
10912
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010913 case HLUA_E_ERR:
10914 /* Display log. */
10915 SEND_ERR(NULL, "Lua cli '%s' return an unknown error.\n",
10916 fcn->name);
10917 return 1;
10918
10919 default:
10920 return 1;
10921 }
10922
10923 return 1;
10924}
10925
10926static void hlua_cli_io_release_fct(struct appctx *appctx)
10927{
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010928 struct hlua_cli_ctx *ctx = appctx->svcctx;
10929
10930 hlua_ctx_destroy(ctx->hlua);
10931 ctx->hlua = NULL;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010932}
10933
10934/* This function is an LUA binding used for registering
10935 * new keywords in the cli. It expects a list of keywords
10936 * which are the "path". It is limited to 5 keywords. A
10937 * description of the command, a function to be executed
10938 * for the parsing and a function for io handlers.
10939 */
10940__LJMP static int hlua_register_cli(lua_State *L)
10941{
10942 struct cli_kw_list *cli_kws;
10943 const char *message;
10944 int ref_io;
10945 int len;
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010946 struct hlua_function *fcn = NULL;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010947 int index;
10948 int i;
Thierry Fournierf67442e2020-11-28 20:41:07 +010010949 struct buffer *trash;
10950 const char *kw[5];
10951 struct cli_kw *cli_kw;
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010952 const char *errmsg;
Willy Tarreau22450af2023-04-07 15:27:55 +020010953 char *end;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010954
10955 MAY_LJMP(check_args(L, 3, "register_cli"));
10956
Aurelien DARRAGON87f52972023-02-24 09:43:54 +010010957 if (hlua_gethlua(L)) {
10958 /* runtime processing */
10959 WILL_LJMP(luaL_error(L, "register_cli: not available outside of body context"));
10960 }
10961
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010962 /* First argument : an array of maximum 5 keywords. */
10963 if (!lua_istable(L, 1))
10964 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table"));
10965
10966 /* Second argument : string with contextual message. */
10967 message = MAY_LJMP(luaL_checkstring(L, 2));
10968
10969 /* Third and fourth argument : lua function. */
10970 ref_io = MAY_LJMP(hlua_checkfunction(L, 3));
10971
Thierry Fournierf67442e2020-11-28 20:41:07 +010010972 /* Check for CLI service already registered */
10973 trash = get_trash_chunk();
10974 index = 0;
10975 lua_pushnil(L);
10976 memset(kw, 0, sizeof(kw));
10977 while (lua_next(L, 1) != 0) {
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +010010978 if (index >= CLI_PREFIX_KW_NB) {
10979 hlua_unref(L, ref_io);
Thierry Fournierf67442e2020-11-28 20:41:07 +010010980 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table with a maximum of 5 entries"));
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +010010981 }
10982 if (lua_type(L, -1) != LUA_TSTRING) {
10983 hlua_unref(L, ref_io);
Thierry Fournierf67442e2020-11-28 20:41:07 +010010984 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table filled with strings"));
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +010010985 }
Thierry Fournierf67442e2020-11-28 20:41:07 +010010986 kw[index] = lua_tostring(L, -1);
10987 if (index == 0)
10988 chunk_printf(trash, "%s", kw[index]);
10989 else
10990 chunk_appendf(trash, " %s", kw[index]);
10991 index++;
10992 lua_pop(L, 1);
10993 }
10994 cli_kw = cli_find_kw_exact((char **)kw);
10995 if (cli_kw != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +010010996 fcn = cli_kw->private;
10997 if (fcn->function_ref[hlua_state_id] != -1) {
10998 ha_warning("Trying to register CLI keyword 'lua.%s' more than once. "
10999 "This will become a hard error in version 2.5.\n", trash->area);
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +010011000 hlua_unref(L, fcn->function_ref[hlua_state_id]);
Thierry Fournier59f11be2020-11-29 00:37:41 +010011001 }
11002 fcn->function_ref[hlua_state_id] = ref_io;
11003 return 0;
Thierry Fournierf67442e2020-11-28 20:41:07 +010011004 }
11005
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011006 /* Allocate and fill the sample fetch keyword struct. */
11007 cli_kws = calloc(1, sizeof(*cli_kws) + sizeof(struct cli_kw) * 2);
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020011008 if (!cli_kws) {
11009 errmsg = "Lua out of memory error.";
11010 goto error;
11011 }
Thierry Fournier62a22aa2020-11-28 21:06:35 +010011012 fcn = new_hlua_function();
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020011013 if (!fcn) {
11014 errmsg = "Lua out of memory error.";
11015 goto error;
11016 }
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011017
11018 /* Fill path. */
11019 index = 0;
11020 lua_pushnil(L);
11021 while(lua_next(L, 1) != 0) {
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020011022 if (index >= 5) {
11023 errmsg = "1st argument must be a table with a maximum of 5 entries";
11024 goto error;
11025 }
11026 if (lua_type(L, -1) != LUA_TSTRING) {
11027 errmsg = "1st argument must be a table filled with strings";
11028 goto error;
11029 }
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011030 cli_kws->kw[0].str_kw[index] = strdup(lua_tostring(L, -1));
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020011031 if (!cli_kws->kw[0].str_kw[index]) {
11032 errmsg = "Lua out of memory error.";
11033 goto error;
11034 }
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011035 index++;
11036 lua_pop(L, 1);
11037 }
11038
11039 /* Copy help message. */
11040 cli_kws->kw[0].usage = strdup(message);
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020011041 if (!cli_kws->kw[0].usage) {
11042 errmsg = "Lua out of memory error.";
11043 goto error;
11044 }
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011045
11046 /* Fill fcn io handler. */
11047 len = strlen("<lua.cli>") + 1;
11048 for (i = 0; i < index; i++)
11049 len += strlen(cli_kws->kw[0].str_kw[i]) + 1;
11050 fcn->name = calloc(1, len);
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020011051 if (!fcn->name) {
11052 errmsg = "Lua out of memory error.";
11053 goto error;
11054 }
Willy Tarreau22450af2023-04-07 15:27:55 +020011055
11056 end = fcn->name;
11057 len = 8;
11058 memcpy(end, "<lua.cli", len);
11059 end += len;
11060
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011061 for (i = 0; i < index; i++) {
Willy Tarreau22450af2023-04-07 15:27:55 +020011062 *(end++) = '.';
11063 len = strlen(cli_kws->kw[0].str_kw[i]);
11064 memcpy(end, cli_kws->kw[0].str_kw[i], len);
11065 end += len;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011066 }
Willy Tarreau22450af2023-04-07 15:27:55 +020011067 *(end++) = '>';
11068 *(end++) = 0;
11069
Thierry Fournierc7492592020-11-28 23:57:24 +010011070 fcn->function_ref[hlua_state_id] = ref_io;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011071
11072 /* Fill last entries. */
11073 cli_kws->kw[0].private = fcn;
11074 cli_kws->kw[0].parse = hlua_cli_parse_fct;
11075 cli_kws->kw[0].io_handler = hlua_cli_io_handler_fct;
11076 cli_kws->kw[0].io_release = hlua_cli_io_release_fct;
11077
11078 /* Register this new converter */
11079 cli_register_kw(cli_kws);
11080
11081 return 0;
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020011082
11083 error:
11084 release_hlua_function(fcn);
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +010011085 hlua_unref(L, ref_io);
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020011086 if (cli_kws) {
11087 for (i = 0; i < index; i++)
11088 ha_free((char **)&(cli_kws->kw[0].str_kw[i]));
11089 ha_free((char **)&(cli_kws->kw[0].usage));
11090 }
11091 ha_free(&cli_kws);
11092 WILL_LJMP(luaL_error(L, errmsg));
11093 return 0; /* Never reached */
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011094}
11095
Christopher Faulet69c581a2021-05-31 08:54:04 +020011096static int hlua_filter_init_per_thread(struct proxy *px, struct flt_conf *fconf)
11097{
11098 struct hlua_flt_config *conf = fconf->conf;
11099 lua_State *L;
11100 int error, pos, state_id, flt_ref;
11101
11102 state_id = reg_flt_to_stack_id(conf->reg);
11103 L = hlua_states[state_id];
11104 pos = lua_gettop(L);
11105
11106 /* The filter parsing function */
Aurelien DARRAGON4fdf8b52023-03-20 17:22:37 +010011107 hlua_pushref(L, conf->reg->fun_ref[state_id]);
Christopher Faulet69c581a2021-05-31 08:54:04 +020011108
11109 /* Push the filter class on the stack and resolve all callbacks */
Aurelien DARRAGON4fdf8b52023-03-20 17:22:37 +010011110 hlua_pushref(L, conf->reg->flt_ref[state_id]);
Christopher Faulet69c581a2021-05-31 08:54:04 +020011111
11112 /* Duplicate the filter class so each filter will have its own copy */
11113 lua_newtable(L);
11114 lua_pushnil(L);
11115
11116 while (lua_next(L, pos+2)) {
11117 lua_pushvalue(L, -2);
11118 lua_insert(L, -2);
11119 lua_settable(L, -4);
11120 }
Aurelien DARRAGON73d1a982023-03-20 17:42:08 +010011121 flt_ref = hlua_ref(L);
Christopher Faulet69c581a2021-05-31 08:54:04 +020011122
11123 /* Remove the original lua filter class from the stack */
11124 lua_pop(L, 1);
11125
11126 /* Push the copy on the stack */
Aurelien DARRAGON4fdf8b52023-03-20 17:22:37 +010011127 hlua_pushref(L, flt_ref);
Christopher Faulet69c581a2021-05-31 08:54:04 +020011128
11129 /* extra args are pushed in a table */
11130 lua_newtable(L);
11131 for (pos = 0; conf->args[pos]; pos++) {
11132 /* Check stack available size. */
11133 if (!lua_checkstack(L, 1)) {
11134 ha_alert("Lua filter '%s' : Lua error : full stack.", conf->reg->name);
11135 goto error;
11136 }
11137 lua_pushstring(L, conf->args[pos]);
11138 lua_rawseti(L, -2, lua_rawlen(L, -2) + 1);
11139 }
11140
11141 error = lua_pcall(L, 2, LUA_MULTRET, 0);
11142 switch (error) {
11143 case LUA_OK:
11144 /* replace the filter ref */
11145 conf->ref[state_id] = flt_ref;
11146 break;
11147 case LUA_ERRRUN:
11148 ha_alert("Lua filter '%s' : runtime error : %s", conf->reg->name, lua_tostring(L, -1));
11149 goto error;
11150 case LUA_ERRMEM:
11151 ha_alert("Lua filter '%s' : out of memory error", conf->reg->name);
11152 goto error;
11153 case LUA_ERRERR:
11154 ha_alert("Lua filter '%s' : message handler error : %s", conf->reg->name, lua_tostring(L, -1));
11155 goto error;
11156#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM <= 503
11157 case LUA_ERRGCMM:
11158 ha_alert("Lua filter '%s' : garbage collector error : %s", conf->reg->name, lua_tostring(L, -1));
11159 goto error;
11160#endif
11161 default:
Ilya Shipitsinff0f2782021-08-22 22:18:07 +050011162 ha_alert("Lua filter '%s' : unknown error : %s", conf->reg->name, lua_tostring(L, -1));
Christopher Faulet69c581a2021-05-31 08:54:04 +020011163 goto error;
11164 }
11165
11166 lua_settop(L, 0);
11167 return 0;
11168
11169 error:
11170 lua_settop(L, 0);
11171 return -1;
11172}
11173
11174static void hlua_filter_deinit_per_thread(struct proxy *px, struct flt_conf *fconf)
11175{
11176 struct hlua_flt_config *conf = fconf->conf;
11177 lua_State *L;
11178 int state_id;
11179
11180 if (!conf)
11181 return;
11182
11183 state_id = reg_flt_to_stack_id(conf->reg);
11184 L = hlua_states[state_id];
Aurelien DARRAGONfde199d2023-03-20 15:09:33 +010011185 hlua_unref(L, conf->ref[state_id]);
Christopher Faulet69c581a2021-05-31 08:54:04 +020011186}
11187
11188static int hlua_filter_init(struct proxy *px, struct flt_conf *fconf)
11189{
11190 struct hlua_flt_config *conf = fconf->conf;
11191 int state_id = reg_flt_to_stack_id(conf->reg);
11192
11193 /* Rely on per-thread init for global scripts */
11194 if (!state_id)
11195 return hlua_filter_init_per_thread(px, fconf);
11196 return 0;
11197}
11198
11199static void hlua_filter_deinit(struct proxy *px, struct flt_conf *fconf)
11200{
11201
11202 if (fconf->conf) {
11203 struct hlua_flt_config *conf = fconf->conf;
11204 int state_id = reg_flt_to_stack_id(conf->reg);
11205 int pos;
11206
11207 /* Rely on per-thread deinit for global scripts */
11208 if (!state_id)
11209 hlua_filter_deinit_per_thread(px, fconf);
11210
11211 for (pos = 0; conf->args[pos]; pos++)
11212 free(conf->args[pos]);
11213 free(conf->args);
11214 }
11215 ha_free(&fconf->conf);
11216 ha_free((char **)&fconf->id);
11217 ha_free(&fconf->ops);
11218}
11219
11220static int hlua_filter_new(struct stream *s, struct filter *filter)
11221{
11222 struct hlua_flt_config *conf = FLT_CONF(filter);
11223 struct hlua_flt_ctx *flt_ctx = NULL;
11224 int ret = 1;
11225
11226 /* In the execution wrappers linked with a stream, the
11227 * Lua context can be not initialized. This behavior
11228 * permits to save performances because a systematic
11229 * Lua initialization cause 5% performances loss.
11230 */
11231 if (!s->hlua) {
11232 struct hlua *hlua;
11233
11234 hlua = pool_alloc(pool_head_hlua);
11235 if (!hlua) {
11236 SEND_ERR(s->be, "Lua filter '%s': can't initialize Lua context.\n",
11237 conf->reg->name);
11238 ret = 0;
11239 goto end;
11240 }
11241 HLUA_INIT(hlua);
11242 s->hlua = hlua;
Aurelien DARRAGON6b0b9bd2023-03-21 14:02:16 +010011243 if (!hlua_ctx_init(s->hlua, reg_flt_to_stack_id(conf->reg), s->task)) {
Christopher Faulet69c581a2021-05-31 08:54:04 +020011244 SEND_ERR(s->be, "Lua filter '%s': can't initialize Lua context.\n",
11245 conf->reg->name);
11246 ret = 0;
11247 goto end;
11248 }
11249 }
11250
11251 flt_ctx = pool_zalloc(pool_head_hlua_flt_ctx);
11252 if (!flt_ctx) {
11253 SEND_ERR(s->be, "Lua filter '%s': can't initialize filter Lua context.\n",
11254 conf->reg->name);
11255 ret = 0;
11256 goto end;
11257 }
11258 flt_ctx->hlua[0] = pool_alloc(pool_head_hlua);
11259 flt_ctx->hlua[1] = pool_alloc(pool_head_hlua);
11260 if (!flt_ctx->hlua[0] || !flt_ctx->hlua[1]) {
11261 SEND_ERR(s->be, "Lua filter '%s': can't initialize filter Lua context.\n",
11262 conf->reg->name);
11263 ret = 0;
11264 goto end;
11265 }
11266 HLUA_INIT(flt_ctx->hlua[0]);
11267 HLUA_INIT(flt_ctx->hlua[1]);
Aurelien DARRAGON6b0b9bd2023-03-21 14:02:16 +010011268 if (!hlua_ctx_init(flt_ctx->hlua[0], reg_flt_to_stack_id(conf->reg), s->task) ||
11269 !hlua_ctx_init(flt_ctx->hlua[1], reg_flt_to_stack_id(conf->reg), s->task)) {
Christopher Faulet69c581a2021-05-31 08:54:04 +020011270 SEND_ERR(s->be, "Lua filter '%s': can't initialize filter Lua context.\n",
11271 conf->reg->name);
11272 ret = 0;
11273 goto end;
11274 }
11275
11276 if (!HLUA_IS_RUNNING(s->hlua)) {
11277 /* The following Lua calls can fail. */
11278 if (!SET_SAFE_LJMP(s->hlua)) {
11279 const char *error;
11280
11281 if (lua_type(s->hlua->T, -1) == LUA_TSTRING)
11282 error = lua_tostring(s->hlua->T, -1);
11283 else
11284 error = "critical error";
11285 SEND_ERR(s->be, "Lua filter '%s': %s.\n", conf->reg->name, error);
11286 ret = 0;
11287 goto end;
11288 }
11289
11290 /* Check stack size. */
11291 if (!lua_checkstack(s->hlua->T, 1)) {
11292 SEND_ERR(s->be, "Lua filter '%s': full stack.\n", conf->reg->name);
Tim Duesterhus22817382021-09-11 23:17:25 +020011293 RESET_SAFE_LJMP(s->hlua);
Christopher Faulet69c581a2021-05-31 08:54:04 +020011294 ret = 0;
11295 goto end;
11296 }
11297
Aurelien DARRAGON4fdf8b52023-03-20 17:22:37 +010011298 hlua_pushref(s->hlua->T, conf->ref[s->hlua->state_id]);
Christopher Faulet69c581a2021-05-31 08:54:04 +020011299 if (lua_getfield(s->hlua->T, -1, "new") != LUA_TFUNCTION) {
11300 SEND_ERR(s->be, "Lua filter '%s': 'new' field is not a function.\n",
11301 conf->reg->name);
11302 RESET_SAFE_LJMP(s->hlua);
11303 ret = 0;
11304 goto end;
11305 }
11306 lua_insert(s->hlua->T, -2);
11307
11308 /* Push the copy on the stack */
11309 s->hlua->nargs = 1;
11310
11311 /* We must initialize the execution timeouts. */
11312 s->hlua->max_time = hlua_timeout_session;
11313
11314 /* At this point the execution is safe. */
11315 RESET_SAFE_LJMP(s->hlua);
11316 }
11317
11318 switch (hlua_ctx_resume(s->hlua, 0)) {
11319 case HLUA_E_OK:
11320 /* Nothing returned or not a table, ignore the filter for current stream */
11321 if (!lua_gettop(s->hlua->T) || !lua_istable(s->hlua->T, 1)) {
11322 ret = 0;
11323 goto end;
11324 }
11325
11326 /* Attached the filter pointer to the ctx */
11327 lua_pushstring(s->hlua->T, "__filter");
11328 lua_pushlightuserdata(s->hlua->T, filter);
11329 lua_settable(s->hlua->T, -3);
11330
11331 /* Save a ref on the filter ctx */
11332 lua_pushvalue(s->hlua->T, 1);
Aurelien DARRAGON73d1a982023-03-20 17:42:08 +010011333 flt_ctx->ref = hlua_ref(s->hlua->T);
Christopher Faulet69c581a2021-05-31 08:54:04 +020011334 filter->ctx = flt_ctx;
11335 break;
11336 case HLUA_E_ERRMSG:
11337 SEND_ERR(s->be, "Lua filter '%s' : %s.\n", conf->reg->name, lua_tostring(s->hlua->T, -1));
11338 ret = -1;
11339 goto end;
11340 case HLUA_E_ETMOUT:
11341 SEND_ERR(s->be, "Lua filter '%s' : 'new' execution timeout.\n", conf->reg->name);
11342 ret = 0;
11343 goto end;
11344 case HLUA_E_NOMEM:
11345 SEND_ERR(s->be, "Lua filter '%s' : out of memory error.\n", conf->reg->name);
11346 ret = 0;
11347 goto end;
11348 case HLUA_E_AGAIN:
11349 case HLUA_E_YIELD:
11350 SEND_ERR(s->be, "Lua filter '%s': yield functions like core.tcp() or core.sleep()"
11351 " are not allowed from 'new' function.\n", conf->reg->name);
11352 ret = 0;
11353 goto end;
11354 case HLUA_E_ERR:
11355 SEND_ERR(s->be, "Lua filter '%s': 'new' returns an unknown error.\n", conf->reg->name);
11356 ret = 0;
11357 goto end;
11358 default:
11359 ret = 0;
11360 goto end;
11361 }
11362
11363 end:
11364 if (s->hlua)
11365 lua_settop(s->hlua->T, 0);
11366 if (ret <= 0) {
11367 if (flt_ctx) {
11368 hlua_ctx_destroy(flt_ctx->hlua[0]);
11369 hlua_ctx_destroy(flt_ctx->hlua[1]);
11370 pool_free(pool_head_hlua_flt_ctx, flt_ctx);
11371 }
11372 }
11373 return ret;
11374}
11375
11376static void hlua_filter_delete(struct stream *s, struct filter *filter)
11377{
11378 struct hlua_flt_ctx *flt_ctx = filter->ctx;
11379
Aurelien DARRAGONfde199d2023-03-20 15:09:33 +010011380 hlua_unref(s->hlua->T, flt_ctx->ref);
Christopher Faulet69c581a2021-05-31 08:54:04 +020011381 hlua_ctx_destroy(flt_ctx->hlua[0]);
11382 hlua_ctx_destroy(flt_ctx->hlua[1]);
11383 pool_free(pool_head_hlua_flt_ctx, flt_ctx);
11384 filter->ctx = NULL;
11385}
11386
Christopher Faulet9f55a502020-02-25 15:21:02 +010011387static int hlua_filter_from_payload(struct filter *filter)
11388{
11389 struct hlua_flt_ctx *flt_ctx = filter->ctx;
11390
11391 return (flt_ctx && !!(flt_ctx->flags & HLUA_FLT_CTX_FL_PAYLOAD));
11392}
11393
Christopher Fauletc404f112020-02-26 15:03:09 +010011394static int hlua_filter_callback(struct stream *s, struct filter *filter, const char *fun,
11395 int dir, unsigned int flags)
11396{
11397 struct hlua *flt_hlua;
11398 struct hlua_flt_config *conf = FLT_CONF(filter);
11399 struct hlua_flt_ctx *flt_ctx = filter->ctx;
11400 unsigned int hflags = HLUA_TXN_FLT_CTX;
11401 int ret = 1;
11402
11403 flt_hlua = flt_ctx->hlua[(dir == SMP_OPT_DIR_REQ ? 0 : 1)];
11404 if (!flt_hlua)
11405 goto end;
11406
11407 if (!HLUA_IS_RUNNING(flt_hlua)) {
11408 int extra_idx = lua_gettop(flt_hlua->T);
11409
11410 /* The following Lua calls can fail. */
11411 if (!SET_SAFE_LJMP(flt_hlua)) {
11412 const char *error;
11413
11414 if (lua_type(flt_hlua->T, -1) == LUA_TSTRING)
11415 error = lua_tostring(flt_hlua->T, -1);
11416 else
11417 error = "critical error";
11418 SEND_ERR(s->be, "Lua filter '%s': %s.\n", conf->reg->name, error);
11419 goto end;
11420 }
11421
11422 /* Check stack size. */
11423 if (!lua_checkstack(flt_hlua->T, 3)) {
11424 SEND_ERR(s->be, "Lua filter '%s': full stack.\n", conf->reg->name);
11425 RESET_SAFE_LJMP(flt_hlua);
11426 goto end;
11427 }
11428
Aurelien DARRAGON4fdf8b52023-03-20 17:22:37 +010011429 hlua_pushref(flt_hlua->T, flt_ctx->ref);
Christopher Fauletc404f112020-02-26 15:03:09 +010011430 if (lua_getfield(flt_hlua->T, -1, fun) != LUA_TFUNCTION) {
11431 RESET_SAFE_LJMP(flt_hlua);
11432 goto end;
11433 }
11434 lua_insert(flt_hlua->T, -2);
11435
11436 if (!hlua_txn_new(flt_hlua->T, s, s->be, dir, hflags)) {
11437 SEND_ERR(s->be, "Lua filter '%s': full stack.\n", conf->reg->name);
11438 RESET_SAFE_LJMP(flt_hlua);
11439 goto end;
11440 }
11441 flt_hlua->nargs = 2;
11442
11443 if (flags & HLUA_FLT_CB_ARG_CHN) {
11444 if (dir == SMP_OPT_DIR_REQ)
11445 lua_getfield(flt_hlua->T, -1, "req");
11446 else
11447 lua_getfield(flt_hlua->T, -1, "res");
11448 if (lua_type(flt_hlua->T, -1) == LUA_TTABLE) {
11449 lua_pushstring(flt_hlua->T, "__filter");
11450 lua_pushlightuserdata(flt_hlua->T, filter);
11451 lua_settable(flt_hlua->T, -3);
11452 }
11453 flt_hlua->nargs++;
11454 }
11455 else if (flags & HLUA_FLT_CB_ARG_HTTP_MSG) {
Christopher Fauleteae8afa2020-02-26 17:15:48 +010011456 if (dir == SMP_OPT_DIR_REQ)
11457 lua_getfield(flt_hlua->T, -1, "http_req");
11458 else
11459 lua_getfield(flt_hlua->T, -1, "http_res");
11460 if (lua_type(flt_hlua->T, -1) == LUA_TTABLE) {
11461 lua_pushstring(flt_hlua->T, "__filter");
11462 lua_pushlightuserdata(flt_hlua->T, filter);
11463 lua_settable(flt_hlua->T, -3);
11464 }
11465 flt_hlua->nargs++;
Christopher Fauletc404f112020-02-26 15:03:09 +010011466 }
11467
11468 /* Check stack size. */
11469 if (!lua_checkstack(flt_hlua->T, 1)) {
11470 SEND_ERR(s->be, "Lua filter '%s': full stack.\n", conf->reg->name);
11471 RESET_SAFE_LJMP(flt_hlua);
11472 goto end;
11473 }
11474
11475 while (extra_idx--) {
11476 lua_pushvalue(flt_hlua->T, 1);
11477 lua_remove(flt_hlua->T, 1);
11478 flt_hlua->nargs++;
11479 }
11480
11481 /* We must initialize the execution timeouts. */
11482 flt_hlua->max_time = hlua_timeout_session;
11483
11484 /* At this point the execution is safe. */
11485 RESET_SAFE_LJMP(flt_hlua);
11486 }
11487
11488 switch (hlua_ctx_resume(flt_hlua, !(flags & HLUA_FLT_CB_FINAL))) {
11489 case HLUA_E_OK:
11490 /* Catch the return value if it required */
11491 if ((flags & HLUA_FLT_CB_RETVAL) && lua_gettop(flt_hlua->T) > 0) {
11492 ret = lua_tointeger(flt_hlua->T, -1);
11493 lua_settop(flt_hlua->T, 0); /* Empty the stack. */
11494 }
11495
11496 /* Set timeout in the required channel. */
11497 if (flt_hlua->wake_time != TICK_ETERNITY) {
11498 if (dir == SMP_OPT_DIR_REQ)
11499 s->req.analyse_exp = flt_hlua->wake_time;
11500 else
11501 s->res.analyse_exp = flt_hlua->wake_time;
11502 }
11503 break;
11504 case HLUA_E_AGAIN:
11505 /* Set timeout in the required channel. */
11506 if (flt_hlua->wake_time != TICK_ETERNITY) {
11507 if (dir == SMP_OPT_DIR_REQ)
11508 s->req.analyse_exp = flt_hlua->wake_time;
11509 else
11510 s->res.analyse_exp = flt_hlua->wake_time;
11511 }
11512 /* Some actions can be wake up when a "write" event
11513 * is detected on a response channel. This is useful
11514 * only for actions targeted on the requests.
11515 */
11516 if (HLUA_IS_WAKERESWR(flt_hlua))
11517 s->res.flags |= CF_WAKE_WRITE;
11518 if (HLUA_IS_WAKEREQWR(flt_hlua))
11519 s->req.flags |= CF_WAKE_WRITE;
11520 ret = 0;
11521 goto end;
11522 case HLUA_E_ERRMSG:
11523 SEND_ERR(s->be, "Lua filter '%s' : %s.\n", conf->reg->name, lua_tostring(flt_hlua->T, -1));
11524 ret = -1;
11525 goto end;
11526 case HLUA_E_ETMOUT:
11527 SEND_ERR(s->be, "Lua filter '%s' : '%s' callback execution timeout.\n", conf->reg->name, fun);
11528 goto end;
11529 case HLUA_E_NOMEM:
11530 SEND_ERR(s->be, "Lua filter '%s' : out of memory error.\n", conf->reg->name);
11531 goto end;
11532 case HLUA_E_YIELD:
11533 SEND_ERR(s->be, "Lua filter '%s': yield functions like core.tcp() or core.sleep()"
11534 " are not allowed from '%s' callback.\n", conf->reg->name, fun);
11535 goto end;
11536 case HLUA_E_ERR:
11537 SEND_ERR(s->be, "Lua filter '%s': '%s' returns an unknown error.\n", conf->reg->name, fun);
11538 goto end;
11539 default:
11540 goto end;
11541 }
11542
11543
11544 end:
11545 return ret;
11546}
11547
11548static int hlua_filter_start_analyze(struct stream *s, struct filter *filter, struct channel *chn)
11549{
11550 struct hlua_flt_ctx *flt_ctx = filter->ctx;
11551
11552 flt_ctx->flags = 0;
11553 return hlua_filter_callback(s, filter, "start_analyze",
11554 (!(chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES),
11555 (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_RETVAL | HLUA_FLT_CB_ARG_CHN));
11556}
11557
11558static int hlua_filter_end_analyze(struct stream *s, struct filter *filter, struct channel *chn)
11559{
11560 struct hlua_flt_ctx *flt_ctx = filter->ctx;
11561
11562 flt_ctx->flags &= ~HLUA_FLT_CTX_FL_PAYLOAD;
11563 return hlua_filter_callback(s, filter, "end_analyze",
11564 (!(chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES),
11565 (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_RETVAL | HLUA_FLT_CB_ARG_CHN));
11566}
11567
Christopher Fauleteae8afa2020-02-26 17:15:48 +010011568static int hlua_filter_http_headers(struct stream *s, struct filter *filter, struct http_msg *msg)
11569{
11570 struct hlua_flt_ctx *flt_ctx = filter->ctx;
11571
11572 flt_ctx->flags &= ~HLUA_FLT_CTX_FL_PAYLOAD;
11573 return hlua_filter_callback(s, filter, "http_headers",
11574 (!(msg->chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES),
11575 (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_RETVAL | HLUA_FLT_CB_ARG_HTTP_MSG));
11576}
11577
11578static int hlua_filter_http_payload(struct stream *s, struct filter *filter, struct http_msg *msg,
11579 unsigned int offset, unsigned int len)
11580{
11581 struct hlua_flt_ctx *flt_ctx = filter->ctx;
11582 struct hlua *flt_hlua;
11583 int dir = (!(msg->chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES);
11584 int idx = (dir == SMP_OPT_DIR_REQ ? 0 : 1);
11585 int ret;
11586
11587 flt_hlua = flt_ctx->hlua[idx];
11588 flt_ctx->cur_off[idx] = offset;
11589 flt_ctx->cur_len[idx] = len;
11590 flt_ctx->flags |= HLUA_FLT_CTX_FL_PAYLOAD;
11591 ret = hlua_filter_callback(s, filter, "http_payload", dir, (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_ARG_HTTP_MSG));
11592 if (ret != -1) {
11593 ret = flt_ctx->cur_len[idx];
11594 if (lua_gettop(flt_hlua->T) > 0) {
11595 ret = lua_tointeger(flt_hlua->T, -1);
11596 if (ret > flt_ctx->cur_len[idx])
11597 ret = flt_ctx->cur_len[idx];
11598 lua_settop(flt_hlua->T, 0); /* Empty the stack. */
11599 }
11600 }
11601 return ret;
11602}
11603
11604static int hlua_filter_http_end(struct stream *s, struct filter *filter, struct http_msg *msg)
11605{
11606 struct hlua_flt_ctx *flt_ctx = filter->ctx;
11607
11608 flt_ctx->flags &= ~HLUA_FLT_CTX_FL_PAYLOAD;
11609 return hlua_filter_callback(s, filter, "http_end",
11610 (!(msg->chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES),
11611 (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_RETVAL | HLUA_FLT_CB_ARG_HTTP_MSG));
11612}
11613
Christopher Fauletc404f112020-02-26 15:03:09 +010011614static int hlua_filter_tcp_payload(struct stream *s, struct filter *filter, struct channel *chn,
11615 unsigned int offset, unsigned int len)
11616{
11617 struct hlua_flt_ctx *flt_ctx = filter->ctx;
11618 struct hlua *flt_hlua;
11619 int dir = (!(chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES);
11620 int idx = (dir == SMP_OPT_DIR_REQ ? 0 : 1);
11621 int ret;
11622
11623 flt_hlua = flt_ctx->hlua[idx];
11624 flt_ctx->cur_off[idx] = offset;
11625 flt_ctx->cur_len[idx] = len;
11626 flt_ctx->flags |= HLUA_FLT_CTX_FL_PAYLOAD;
11627 ret = hlua_filter_callback(s, filter, "tcp_payload", dir, (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_ARG_CHN));
11628 if (ret != -1) {
11629 ret = flt_ctx->cur_len[idx];
11630 if (lua_gettop(flt_hlua->T) > 0) {
11631 ret = lua_tointeger(flt_hlua->T, -1);
11632 if (ret > flt_ctx->cur_len[idx])
11633 ret = flt_ctx->cur_len[idx];
11634 lua_settop(flt_hlua->T, 0); /* Empty the stack. */
11635 }
11636 }
11637 return ret;
11638}
11639
Christopher Faulet69c581a2021-05-31 08:54:04 +020011640static int hlua_filter_parse_fct(char **args, int *cur_arg, struct proxy *px,
11641 struct flt_conf *fconf, char **err, void *private)
11642{
11643 struct hlua_reg_filter *reg_flt = private;
11644 lua_State *L;
11645 struct hlua_flt_config *conf = NULL;
11646 const char *flt_id = NULL;
11647 int state_id, pos, flt_flags = 0;
11648 struct flt_ops *hlua_flt_ops = NULL;
11649
11650 state_id = reg_flt_to_stack_id(reg_flt);
11651 L = hlua_states[state_id];
11652
11653 /* Initialize the filter ops with default callbacks */
11654 hlua_flt_ops = calloc(1, sizeof(*hlua_flt_ops));
Christopher Fauletc86bb872021-08-13 08:33:57 +020011655 if (!hlua_flt_ops)
11656 goto error;
Christopher Faulet69c581a2021-05-31 08:54:04 +020011657 hlua_flt_ops->init = hlua_filter_init;
11658 hlua_flt_ops->deinit = hlua_filter_deinit;
11659 if (state_id) {
11660 /* Set per-thread callback if script is loaded per-thread */
11661 hlua_flt_ops->init_per_thread = hlua_filter_init_per_thread;
11662 hlua_flt_ops->deinit_per_thread = hlua_filter_deinit_per_thread;
11663 }
11664 hlua_flt_ops->attach = hlua_filter_new;
11665 hlua_flt_ops->detach = hlua_filter_delete;
11666
11667 /* Push the filter class on the stack and resolve all callbacks */
Aurelien DARRAGON4fdf8b52023-03-20 17:22:37 +010011668 hlua_pushref(L, reg_flt->flt_ref[state_id]);
Christopher Faulet69c581a2021-05-31 08:54:04 +020011669
Christopher Fauletc404f112020-02-26 15:03:09 +010011670 if (lua_getfield(L, -1, "start_analyze") == LUA_TFUNCTION)
11671 hlua_flt_ops->channel_start_analyze = hlua_filter_start_analyze;
11672 lua_pop(L, 1);
11673 if (lua_getfield(L, -1, "end_analyze") == LUA_TFUNCTION)
11674 hlua_flt_ops->channel_end_analyze = hlua_filter_end_analyze;
11675 lua_pop(L, 1);
Christopher Fauleteae8afa2020-02-26 17:15:48 +010011676 if (lua_getfield(L, -1, "http_headers") == LUA_TFUNCTION)
11677 hlua_flt_ops->http_headers = hlua_filter_http_headers;
11678 lua_pop(L, 1);
11679 if (lua_getfield(L, -1, "http_payload") == LUA_TFUNCTION)
11680 hlua_flt_ops->http_payload = hlua_filter_http_payload;
11681 lua_pop(L, 1);
11682 if (lua_getfield(L, -1, "http_end") == LUA_TFUNCTION)
11683 hlua_flt_ops->http_end = hlua_filter_http_end;
11684 lua_pop(L, 1);
Christopher Fauletc404f112020-02-26 15:03:09 +010011685 if (lua_getfield(L, -1, "tcp_payload") == LUA_TFUNCTION)
11686 hlua_flt_ops->tcp_payload = hlua_filter_tcp_payload;
11687 lua_pop(L, 1);
Christopher Faulet69c581a2021-05-31 08:54:04 +020011688
11689 /* Get id and flags of the filter class */
11690 if (lua_getfield(L, -1, "id") == LUA_TSTRING)
11691 flt_id = lua_tostring(L, -1);
11692 lua_pop(L, 1);
11693 if (lua_getfield(L, -1, "flags") == LUA_TNUMBER)
11694 flt_flags = lua_tointeger(L, -1);
11695 lua_pop(L, 1);
11696
11697 /* Create the filter config */
11698 conf = calloc(1, sizeof(*conf));
Christopher Fauletc86bb872021-08-13 08:33:57 +020011699 if (!conf)
Christopher Faulet69c581a2021-05-31 08:54:04 +020011700 goto error;
Christopher Faulet69c581a2021-05-31 08:54:04 +020011701 conf->reg = reg_flt;
11702
11703 /* duplicate args */
11704 for (pos = 0; *args[*cur_arg + 1 + pos]; pos++);
11705 conf->args = calloc(pos + 1, sizeof(*conf->args));
Christopher Fauletc86bb872021-08-13 08:33:57 +020011706 if (!conf->args)
11707 goto error;
11708 for (pos = 0; *args[*cur_arg + 1 + pos]; pos++) {
Christopher Faulet69c581a2021-05-31 08:54:04 +020011709 conf->args[pos] = strdup(args[*cur_arg + 1 + pos]);
Christopher Fauletc86bb872021-08-13 08:33:57 +020011710 if (!conf->args[pos])
11711 goto error;
11712 }
Christopher Faulet69c581a2021-05-31 08:54:04 +020011713 conf->args[pos] = NULL;
11714 *cur_arg += pos + 1;
11715
Christopher Fauletc86bb872021-08-13 08:33:57 +020011716 if (flt_id) {
11717 fconf->id = strdup(flt_id);
11718 if (!fconf->id)
11719 goto error;
11720 }
Christopher Faulet69c581a2021-05-31 08:54:04 +020011721 fconf->flags = flt_flags;
11722 fconf->conf = conf;
11723 fconf->ops = hlua_flt_ops;
11724
11725 lua_settop(L, 0);
11726 return 0;
11727
11728 error:
Christopher Fauletc86bb872021-08-13 08:33:57 +020011729 memprintf(err, "Lua filter '%s' : Lua out of memory error", reg_flt->name);
Christopher Faulet69c581a2021-05-31 08:54:04 +020011730 free(hlua_flt_ops);
Christopher Fauletc86bb872021-08-13 08:33:57 +020011731 if (conf && conf->args) {
11732 for (pos = 0; conf->args[pos]; pos++)
11733 free(conf->args[pos]);
11734 free(conf->args);
11735 }
Christopher Faulet69c581a2021-05-31 08:54:04 +020011736 free(conf);
Christopher Fauletc86bb872021-08-13 08:33:57 +020011737 free((char *)fconf->id);
Christopher Faulet69c581a2021-05-31 08:54:04 +020011738 lua_settop(L, 0);
11739 return -1;
11740}
11741
Christopher Fauletc404f112020-02-26 15:03:09 +010011742__LJMP static int hlua_register_data_filter(lua_State *L)
11743{
11744 struct filter *filter;
11745 struct channel *chn;
11746
11747 MAY_LJMP(check_args(L, 2, "register_data_filter"));
11748 MAY_LJMP(luaL_checktype(L, 1, LUA_TTABLE));
11749 chn = MAY_LJMP(hlua_checkchannel(L, 2));
11750
11751 lua_getfield(L, 1, "__filter");
11752 MAY_LJMP(luaL_checktype(L, -1, LUA_TLIGHTUSERDATA));
11753 filter = lua_touserdata (L, -1);
11754 lua_pop(L, 1);
11755
11756 register_data_filter(chn_strm(chn), chn, filter);
11757 return 1;
11758}
11759
11760__LJMP static int hlua_unregister_data_filter(lua_State *L)
11761{
11762 struct filter *filter;
11763 struct channel *chn;
11764
11765 MAY_LJMP(check_args(L, 2, "unregister_data_filter"));
11766 MAY_LJMP(luaL_checktype(L, 1, LUA_TTABLE));
11767 chn = MAY_LJMP(hlua_checkchannel(L, 2));
11768
11769 lua_getfield(L, 1, "__filter");
11770 MAY_LJMP(luaL_checktype(L, -1, LUA_TLIGHTUSERDATA));
11771 filter = lua_touserdata (L, -1);
11772 lua_pop(L, 1);
11773
11774 unregister_data_filter(chn_strm(chn), chn, filter);
11775 return 1;
11776}
11777
Christopher Faulet69c581a2021-05-31 08:54:04 +020011778/* This function is an LUA binding used for registering a filter. It expects a
Ilya Shipitsinff0f2782021-08-22 22:18:07 +050011779 * filter name used in the haproxy configuration file and a LUA function to
Christopher Faulet69c581a2021-05-31 08:54:04 +020011780 * parse configuration arguments.
11781 */
11782__LJMP static int hlua_register_filter(lua_State *L)
11783{
11784 struct buffer *trash;
11785 struct flt_kw_list *fkl;
11786 struct flt_kw *fkw;
11787 const char *name;
11788 struct hlua_reg_filter *reg_flt= NULL;
11789 int flt_ref, fun_ref;
11790 int len;
11791
11792 MAY_LJMP(check_args(L, 3, "register_filter"));
11793
Aurelien DARRAGON87f52972023-02-24 09:43:54 +010011794 if (hlua_gethlua(L)) {
11795 /* runtime processing */
11796 WILL_LJMP(luaL_error(L, "register_filter: not available outside of body context"));
11797 }
11798
Christopher Faulet69c581a2021-05-31 08:54:04 +020011799 /* First argument : filter name. */
11800 name = MAY_LJMP(luaL_checkstring(L, 1));
11801
11802 /* Second argument : The filter class */
11803 flt_ref = MAY_LJMP(hlua_checktable(L, 2));
11804
11805 /* Third argument : lua function. */
11806 fun_ref = MAY_LJMP(hlua_checkfunction(L, 3));
11807
11808 trash = get_trash_chunk();
11809 chunk_printf(trash, "lua.%s", name);
11810 fkw = flt_find_kw(trash->area);
11811 if (fkw != NULL) {
11812 reg_flt = fkw->private;
11813 if (reg_flt->flt_ref[hlua_state_id] != -1 || reg_flt->fun_ref[hlua_state_id] != -1) {
11814 ha_warning("Trying to register filter 'lua.%s' more than once. "
11815 "This will become a hard error in version 2.5.\n", name);
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +010011816 if (reg_flt->flt_ref[hlua_state_id] != -1)
11817 hlua_unref(L, reg_flt->flt_ref[hlua_state_id]);
11818 if (reg_flt->fun_ref[hlua_state_id] != -1)
11819 hlua_unref(L, reg_flt->fun_ref[hlua_state_id]);
Christopher Faulet69c581a2021-05-31 08:54:04 +020011820 }
11821 reg_flt->flt_ref[hlua_state_id] = flt_ref;
11822 reg_flt->fun_ref[hlua_state_id] = fun_ref;
11823 return 0;
11824 }
11825
11826 fkl = calloc(1, sizeof(*fkl) + sizeof(struct flt_kw) * 2);
11827 if (!fkl)
11828 goto alloc_error;
11829 fkl->scope = "HLUA";
11830
11831 reg_flt = new_hlua_reg_filter(name);
11832 if (!reg_flt)
11833 goto alloc_error;
11834
11835 reg_flt->flt_ref[hlua_state_id] = flt_ref;
11836 reg_flt->fun_ref[hlua_state_id] = fun_ref;
11837
11838 /* The filter keyword */
11839 len = strlen("lua.") + strlen(name) + 1;
11840 fkl->kw[0].kw = calloc(1, len);
11841 if (!fkl->kw[0].kw)
11842 goto alloc_error;
11843
11844 snprintf((char *)fkl->kw[0].kw, len, "lua.%s", name);
11845
11846 fkl->kw[0].parse = hlua_filter_parse_fct;
11847 fkl->kw[0].private = reg_flt;
11848 memset(&fkl->kw[1], 0, sizeof(*fkl->kw));
11849
11850 /* Register this new filter */
11851 flt_register_keywords(fkl);
11852
11853 return 0;
11854
11855 alloc_error:
11856 release_hlua_reg_filter(reg_flt);
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +010011857 hlua_unref(L, flt_ref);
11858 hlua_unref(L, fun_ref);
Christopher Faulet69c581a2021-05-31 08:54:04 +020011859 ha_free(&fkl);
11860 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
11861 return 0; /* Never reached */
11862}
11863
Thierry FOURNIERbd413492015-03-03 16:52:26 +010011864static int hlua_read_timeout(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011865 const struct proxy *defpx, const char *file, int line,
Thierry FOURNIERbd413492015-03-03 16:52:26 +010011866 char **err, unsigned int *timeout)
11867{
11868 const char *error;
11869
11870 error = parse_time_err(args[1], timeout, TIME_UNIT_MS);
Willy Tarreau9faebe32019-06-07 19:00:37 +020011871 if (error == PARSE_TIME_OVER) {
11872 memprintf(err, "timer overflow in argument <%s> to <%s> (maximum value is 2147483647 ms or ~24.8 days)",
11873 args[1], args[0]);
11874 return -1;
11875 }
11876 else if (error == PARSE_TIME_UNDER) {
11877 memprintf(err, "timer underflow in argument <%s> to <%s> (minimum non-null value is 1 ms)",
11878 args[1], args[0]);
11879 return -1;
11880 }
11881 else if (error) {
Thierry FOURNIERbd413492015-03-03 16:52:26 +010011882 memprintf(err, "%s: invalid timeout", args[0]);
11883 return -1;
11884 }
11885 return 0;
11886}
11887
11888static int hlua_session_timeout(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011889 const struct proxy *defpx, const char *file, int line,
Thierry FOURNIERbd413492015-03-03 16:52:26 +010011890 char **err)
11891{
11892 return hlua_read_timeout(args, section_type, curpx, defpx,
11893 file, line, err, &hlua_timeout_session);
11894}
11895
11896static int hlua_task_timeout(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011897 const struct proxy *defpx, const char *file, int line,
Thierry FOURNIERbd413492015-03-03 16:52:26 +010011898 char **err)
11899{
11900 return hlua_read_timeout(args, section_type, curpx, defpx,
11901 file, line, err, &hlua_timeout_task);
11902}
11903
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020011904static int hlua_applet_timeout(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011905 const struct proxy *defpx, const char *file, int line,
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020011906 char **err)
11907{
11908 return hlua_read_timeout(args, section_type, curpx, defpx,
11909 file, line, err, &hlua_timeout_applet);
11910}
11911
Thierry FOURNIERee9f8022015-03-03 17:37:37 +010011912static int hlua_forced_yield(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011913 const struct proxy *defpx, const char *file, int line,
Thierry FOURNIERee9f8022015-03-03 17:37:37 +010011914 char **err)
11915{
11916 char *error;
11917
11918 hlua_nb_instruction = strtoll(args[1], &error, 10);
11919 if (*error != '\0') {
11920 memprintf(err, "%s: invalid number", args[0]);
11921 return -1;
11922 }
11923 return 0;
11924}
11925
Willy Tarreau32f61e22015-03-18 17:54:59 +010011926static int hlua_parse_maxmem(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011927 const struct proxy *defpx, const char *file, int line,
Willy Tarreau32f61e22015-03-18 17:54:59 +010011928 char **err)
11929{
11930 char *error;
11931
11932 if (*(args[1]) == 0) {
Thierry Fournier70e38e92022-09-19 09:01:53 +020011933 memprintf(err, "'%s' expects an integer argument (Lua memory size in MB).", args[0]);
Willy Tarreau32f61e22015-03-18 17:54:59 +010011934 return -1;
11935 }
11936 hlua_global_allocator.limit = strtoll(args[1], &error, 10) * 1024L * 1024L;
11937 if (*error != '\0') {
11938 memprintf(err, "%s: invalid number %s (error at '%c')", args[0], args[1], *error);
11939 return -1;
11940 }
11941 return 0;
11942}
11943
11944
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011945/* This function is called by the main configuration key "lua-load". It loads and
11946 * execute an lua file during the parsing of the HAProxy configuration file. It is
11947 * the main lua entry point.
11948 *
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -080011949 * This function runs with the HAProxy keywords API. It returns -1 if an error
11950 * occurs, otherwise it returns 0.
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011951 *
11952 * In some error case, LUA set an error message in top of the stack. This function
11953 * returns this error message in the HAProxy logs and pop it from the stack.
Thierry FOURNIERbabae282015-09-17 11:36:37 +020011954 *
11955 * This function can fail with an abort() due to an Lua critical error.
11956 * We are in the configuration parsing process of HAProxy, this abort() is
11957 * tolerated.
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011958 */
Thierry Fournierae6b5682022-09-19 09:04:16 +020011959static int hlua_load_state(char **args, lua_State *L, char **err)
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011960{
11961 int error;
Thierry Fournierae6b5682022-09-19 09:04:16 +020011962 int nargs;
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011963
11964 /* Just load and compile the file. */
Thierry Fournierae6b5682022-09-19 09:04:16 +020011965 error = luaL_loadfile(L, args[0]);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011966 if (error) {
Thierry Fournierae6b5682022-09-19 09:04:16 +020011967 memprintf(err, "error in Lua file '%s': %s", args[0], lua_tostring(L, -1));
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011968 lua_pop(L, 1);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011969 return -1;
11970 }
Thierry Fournierae6b5682022-09-19 09:04:16 +020011971
11972 /* Push args in the Lua stack, except the first one which is the filename */
11973 for (nargs = 1; *(args[nargs]) != 0; nargs++) {
Aurelien DARRAGON4d7aefe2022-09-23 10:22:14 +020011974 /* Check stack size. */
11975 if (!lua_checkstack(L, 1)) {
11976 memprintf(err, "Lua runtime error while loading arguments: stack is full.");
11977 return -1;
11978 }
Thierry Fournierae6b5682022-09-19 09:04:16 +020011979 lua_pushstring(L, args[nargs]);
11980 }
11981 nargs--;
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011982
11983 /* If no syntax error where detected, execute the code. */
Thierry Fournierae6b5682022-09-19 09:04:16 +020011984 error = lua_pcall(L, nargs, LUA_MULTRET, 0);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011985 switch (error) {
11986 case LUA_OK:
11987 break;
11988 case LUA_ERRRUN:
Thierry Fournier70e38e92022-09-19 09:01:53 +020011989 memprintf(err, "Lua runtime error: %s", lua_tostring(L, -1));
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011990 lua_pop(L, 1);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011991 return -1;
11992 case LUA_ERRMEM:
Thierry Fournier70e38e92022-09-19 09:01:53 +020011993 memprintf(err, "Lua out of memory error");
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011994 return -1;
11995 case LUA_ERRERR:
Thierry Fournier70e38e92022-09-19 09:01:53 +020011996 memprintf(err, "Lua message handler error: %s", lua_tostring(L, -1));
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011997 lua_pop(L, 1);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011998 return -1;
Christopher Faulet08ed98f2020-07-28 10:33:25 +020011999#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM <= 503
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010012000 case LUA_ERRGCMM:
Thierry Fournier70e38e92022-09-19 09:01:53 +020012001 memprintf(err, "Lua garbage collector error: %s", lua_tostring(L, -1));
Thierry Fournierc93c15c2020-11-28 15:02:13 +010012002 lua_pop(L, 1);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010012003 return -1;
Christopher Faulet08ed98f2020-07-28 10:33:25 +020012004#endif
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010012005 default:
Thierry Fournier70e38e92022-09-19 09:01:53 +020012006 memprintf(err, "Lua unknown error: %s", lua_tostring(L, -1));
Thierry Fournierc93c15c2020-11-28 15:02:13 +010012007 lua_pop(L, 1);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010012008 return -1;
12009 }
12010
12011 return 0;
12012}
12013
Thierry Fournierc93c15c2020-11-28 15:02:13 +010012014static int hlua_load(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010012015 const struct proxy *defpx, const char *file, int line,
Thierry Fournierc93c15c2020-11-28 15:02:13 +010012016 char **err)
12017{
12018 if (*(args[1]) == 0) {
Thierry Fournier70e38e92022-09-19 09:01:53 +020012019 memprintf(err, "'%s' expects a file name as parameter.", args[0]);
Thierry Fournierc93c15c2020-11-28 15:02:13 +010012020 return -1;
12021 }
12022
Thierry Fournier59f11be2020-11-29 00:37:41 +010012023 /* loading for global state */
Thierry Fournierc7492592020-11-28 23:57:24 +010012024 hlua_state_id = 0;
Willy Tarreau43ab05b2021-09-28 09:43:11 +020012025 ha_set_thread(NULL);
Thierry Fournierae6b5682022-09-19 09:04:16 +020012026 return hlua_load_state(&args[1], hlua_states[0], err);
Thierry Fournierc93c15c2020-11-28 15:02:13 +010012027}
12028
Thierry Fournier59f11be2020-11-29 00:37:41 +010012029static int hlua_load_per_thread(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010012030 const struct proxy *defpx, const char *file, int line,
Thierry Fournier59f11be2020-11-29 00:37:41 +010012031 char **err)
12032{
12033 int len;
Thierry Fournierae6b5682022-09-19 09:04:16 +020012034 int i;
Thierry Fournier59f11be2020-11-29 00:37:41 +010012035
12036 if (*(args[1]) == 0) {
Thierry Fournier70e38e92022-09-19 09:01:53 +020012037 memprintf(err, "'%s' expects a file as parameter.", args[0]);
Thierry Fournier59f11be2020-11-29 00:37:41 +010012038 return -1;
12039 }
12040
12041 if (per_thread_load == NULL) {
12042 /* allocate the first entry large enough to store the final NULL */
12043 per_thread_load = calloc(1, sizeof(*per_thread_load));
12044 if (per_thread_load == NULL) {
12045 memprintf(err, "out of memory error");
12046 return -1;
12047 }
12048 }
12049
12050 /* count used entries */
12051 for (len = 0; per_thread_load[len] != NULL; len++)
12052 ;
12053
12054 per_thread_load = realloc(per_thread_load, (len + 2) * sizeof(*per_thread_load));
12055 if (per_thread_load == NULL) {
12056 memprintf(err, "out of memory error");
12057 return -1;
12058 }
Thierry Fournier59f11be2020-11-29 00:37:41 +010012059 per_thread_load[len + 1] = NULL;
12060
Thierry Fournierae6b5682022-09-19 09:04:16 +020012061 /* count args excepting the first, allocate array and copy args */
12062 for (i = 0; *(args[i + 1]) != 0; i++);
Aurelien DARRAGONb12d1692022-09-23 08:48:34 +020012063 per_thread_load[len] = calloc(i + 1, sizeof(*per_thread_load[len]));
Thierry Fournier59f11be2020-11-29 00:37:41 +010012064 if (per_thread_load[len] == NULL) {
12065 memprintf(err, "out of memory error");
12066 return -1;
12067 }
Thierry Fournierae6b5682022-09-19 09:04:16 +020012068 for (i = 1; *(args[i]) != 0; i++) {
12069 per_thread_load[len][i - 1] = strdup(args[i]);
12070 if (per_thread_load[len][i - 1] == NULL) {
12071 memprintf(err, "out of memory error");
12072 return -1;
12073 }
12074 }
12075 per_thread_load[len][i - 1] = strdup("");
12076 if (per_thread_load[len][i - 1] == NULL) {
12077 memprintf(err, "out of memory error");
12078 return -1;
12079 }
Thierry Fournier59f11be2020-11-29 00:37:41 +010012080
12081 /* loading for thread 1 only */
12082 hlua_state_id = 1;
Willy Tarreau43ab05b2021-09-28 09:43:11 +020012083 ha_set_thread(NULL);
Thierry Fournierae6b5682022-09-19 09:04:16 +020012084 return hlua_load_state(per_thread_load[len], hlua_states[1], err);
Thierry Fournier59f11be2020-11-29 00:37:41 +010012085}
12086
Tim Duesterhusc9fc9f22020-01-12 13:55:39 +010012087/* Prepend the given <path> followed by a semicolon to the `package.<type>` variable
12088 * in the given <ctx>.
12089 */
Thierry Fournier3fb9e512020-11-28 10:13:12 +010012090static int hlua_prepend_path(lua_State *L, char *type, char *path)
Tim Duesterhusc9fc9f22020-01-12 13:55:39 +010012091{
Thierry Fournier3fb9e512020-11-28 10:13:12 +010012092 lua_getglobal(L, "package"); /* push package variable */
12093 lua_pushstring(L, path); /* push given path */
12094 lua_pushstring(L, ";"); /* push semicolon */
12095 lua_getfield(L, -3, type); /* push old path */
12096 lua_concat(L, 3); /* concatenate to new path */
12097 lua_setfield(L, -2, type); /* store new path */
12098 lua_pop(L, 1); /* pop package variable */
Tim Duesterhusc9fc9f22020-01-12 13:55:39 +010012099
12100 return 0;
12101}
12102
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010012103static int hlua_config_prepend_path(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010012104 const struct proxy *defpx, const char *file, int line,
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010012105 char **err)
12106{
12107 char *path;
12108 char *type = "path";
Tim Duesterhus621e74a2021-01-03 20:04:36 +010012109 struct prepend_path *p = NULL;
Bertrand Jacquin7fbc7702021-11-24 21:16:06 +000012110 size_t i;
Thierry Fournier59f11be2020-11-29 00:37:41 +010012111
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010012112 if (too_many_args(2, args, err, NULL)) {
Tim Duesterhus621e74a2021-01-03 20:04:36 +010012113 goto err;
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010012114 }
12115
12116 if (!(*args[1])) {
12117 memprintf(err, "'%s' expects to receive a <path> as argument", args[0]);
Tim Duesterhus621e74a2021-01-03 20:04:36 +010012118 goto err;
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010012119 }
12120 path = args[1];
12121
12122 if (*args[2]) {
12123 if (strcmp(args[2], "path") != 0 && strcmp(args[2], "cpath") != 0) {
12124 memprintf(err, "'%s' expects <type> to either be 'path' or 'cpath'", args[0]);
Tim Duesterhus621e74a2021-01-03 20:04:36 +010012125 goto err;
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010012126 }
12127 type = args[2];
12128 }
12129
Thierry Fournier59f11be2020-11-29 00:37:41 +010012130 p = calloc(1, sizeof(*p));
12131 if (p == NULL) {
Tim Duesterhusf89d43a2021-01-03 20:04:37 +010012132 memprintf(err, "memory allocation failed");
Tim Duesterhus621e74a2021-01-03 20:04:36 +010012133 goto err;
Thierry Fournier59f11be2020-11-29 00:37:41 +010012134 }
12135 p->path = strdup(path);
12136 if (p->path == NULL) {
Tim Duesterhusf89d43a2021-01-03 20:04:37 +010012137 memprintf(err, "memory allocation failed");
Tim Duesterhus621e74a2021-01-03 20:04:36 +010012138 goto err2;
Thierry Fournier59f11be2020-11-29 00:37:41 +010012139 }
12140 p->type = strdup(type);
12141 if (p->type == NULL) {
Tim Duesterhusf89d43a2021-01-03 20:04:37 +010012142 memprintf(err, "memory allocation failed");
Tim Duesterhus621e74a2021-01-03 20:04:36 +010012143 goto err2;
Thierry Fournier59f11be2020-11-29 00:37:41 +010012144 }
Willy Tarreau2b718102021-04-21 07:32:39 +020012145 LIST_APPEND(&prepend_path_list, &p->l);
Thierry Fournier59f11be2020-11-29 00:37:41 +010012146
Tim Duesterhus9e5e5862021-10-11 18:51:08 +020012147 /* Handle the global state and the per-thread state for the first
12148 * thread. The remaining threads will be initialized based on
12149 * prepend_path_list.
12150 */
Bertrand Jacquin7fbc7702021-11-24 21:16:06 +000012151 for (i = 0; i < 2; i++) {
Tim Duesterhus9e5e5862021-10-11 18:51:08 +020012152 lua_State *L = hlua_states[i];
12153 const char *error;
12154
12155 if (setjmp(safe_ljmp_env) != 0) {
12156 lua_atpanic(L, hlua_panic_safe);
12157 if (lua_type(L, -1) == LUA_TSTRING)
12158 error = lua_tostring(L, -1);
12159 else
12160 error = "critical error";
12161 fprintf(stderr, "lua-prepend-path: %s.\n", error);
12162 exit(1);
12163 } else {
12164 lua_atpanic(L, hlua_panic_ljmp);
12165 }
12166
12167 hlua_prepend_path(L, type, path);
12168
12169 lua_atpanic(L, hlua_panic_safe);
12170 }
12171
Thierry Fournier59f11be2020-11-29 00:37:41 +010012172 return 0;
Tim Duesterhus621e74a2021-01-03 20:04:36 +010012173
12174err2:
12175 free(p->type);
12176 free(p->path);
12177err:
12178 free(p);
12179 return -1;
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010012180}
12181
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010012182/* configuration keywords declaration */
12183static struct cfg_kw_list cfg_kws = {{ },{
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010012184 { CFG_GLOBAL, "lua-prepend-path", hlua_config_prepend_path },
Thierry FOURNIERbd413492015-03-03 16:52:26 +010012185 { CFG_GLOBAL, "lua-load", hlua_load },
Thierry Fournier59f11be2020-11-29 00:37:41 +010012186 { CFG_GLOBAL, "lua-load-per-thread", hlua_load_per_thread },
Thierry FOURNIERbd413492015-03-03 16:52:26 +010012187 { CFG_GLOBAL, "tune.lua.session-timeout", hlua_session_timeout },
12188 { CFG_GLOBAL, "tune.lua.task-timeout", hlua_task_timeout },
Thierry FOURNIER56da1012015-10-01 08:42:31 +020012189 { CFG_GLOBAL, "tune.lua.service-timeout", hlua_applet_timeout },
Thierry FOURNIERee9f8022015-03-03 17:37:37 +010012190 { CFG_GLOBAL, "tune.lua.forced-yield", hlua_forced_yield },
Willy Tarreau32f61e22015-03-18 17:54:59 +010012191 { CFG_GLOBAL, "tune.lua.maxmem", hlua_parse_maxmem },
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010012192 { 0, NULL, NULL },
12193}};
12194
Willy Tarreau0108d902018-11-25 19:14:37 +010012195INITCALL1(STG_REGISTER, cfg_register_keywords, &cfg_kws);
12196
William Lallemand52139182022-03-30 15:05:42 +020012197#ifdef USE_OPENSSL
Christopher Fauletafd8f102018-11-08 11:34:21 +010012198
William Lallemand30fcca12022-03-30 12:03:12 +020012199/*
12200 * This function replace a ckch_store by another one, and rebuild the ckch_inst and all its dependencies.
12201 * It does the sam as "cli_io_handler_commit_cert" but for lua, the major
12202 * difference is that the yield in lua and for the CLI is not handled the same
12203 * way.
12204 */
12205__LJMP static int hlua_ckch_commit_yield(lua_State *L, int status, lua_KContext ctx)
12206{
12207 struct ckch_inst **lua_ckchi = lua_touserdata(L, -1);
12208 struct ckch_store **lua_ckchs = lua_touserdata(L, -2);
12209 struct ckch_inst *ckchi = *lua_ckchi;
12210 struct ckch_store *old_ckchs = lua_ckchs[0];
12211 struct ckch_store *new_ckchs = lua_ckchs[1];
12212 struct hlua *hlua;
12213 char *err = NULL;
12214 int y = 1;
12215
12216 hlua = hlua_gethlua(L);
12217
12218 /* get the first ckchi to copy */
12219 if (ckchi == NULL)
12220 ckchi = LIST_ELEM(old_ckchs->ckch_inst.n, typeof(ckchi), by_ckchs);
12221
12222 /* walk through the old ckch_inst and creates new ckch_inst using the updated ckchs */
12223 list_for_each_entry_from(ckchi, &old_ckchs->ckch_inst, by_ckchs) {
12224 struct ckch_inst *new_inst;
12225
12226 /* it takes a lot of CPU to creates SSL_CTXs, so we yield every 10 CKCH instances */
12227 if (y % 10 == 0) {
12228
12229 *lua_ckchi = ckchi;
12230
12231 task_wakeup(hlua->task, TASK_WOKEN_MSG);
12232 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_ckch_commit_yield, TICK_ETERNITY, 0));
12233 }
12234
12235 if (ckch_inst_rebuild(new_ckchs, ckchi, &new_inst, &err))
12236 goto error;
12237
12238 /* link the new ckch_inst to the duplicate */
12239 LIST_APPEND(&new_ckchs->ckch_inst, &new_inst->by_ckchs);
12240 y++;
12241 }
12242
12243 /* The generation is finished, we can insert everything */
12244 ckch_store_replace(old_ckchs, new_ckchs);
12245
12246 lua_pop(L, 2); /* pop the lua_ckchs and ckchi */
12247
12248 HA_SPIN_UNLOCK(CKCH_LOCK, &ckch_lock);
12249
12250 return 0;
12251
12252error:
12253 ckch_store_free(new_ckchs);
12254 HA_SPIN_UNLOCK(CKCH_LOCK, &ckch_lock);
12255 WILL_LJMP(luaL_error(L, "%s", err));
12256 free(err);
12257
12258 return 0;
12259}
12260
12261/*
12262 * Replace a ckch_store <filename> in the ckchs_tree with a ckch_store created
12263 * from the table in parameter.
12264 *
12265 * This is equivalent to "set ssl cert" + "commit ssl cert" over the CLI, which
12266 * means it does not need to have a transaction since everything is done in the
12267 * same function.
12268 *
12269 * CertCache.set{filename="", crt="", key="", sctl="", ocsp="", issuer=""}
12270 *
12271 */
12272__LJMP static int hlua_ckch_set(lua_State *L)
12273{
12274 struct hlua *hlua;
12275 struct ckch_inst **lua_ckchi;
12276 struct ckch_store **lua_ckchs;
12277 struct ckch_store *old_ckchs = NULL;
12278 struct ckch_store *new_ckchs = NULL;
12279 int errcode = 0;
12280 char *err = NULL;
12281 struct cert_exts *cert_ext = NULL;
12282 char *filename;
William Lallemand52ddd992022-11-22 11:51:53 +010012283 struct ckch_data *data;
William Lallemand30fcca12022-03-30 12:03:12 +020012284 int ret;
12285
12286 if (lua_type(L, -1) != LUA_TTABLE)
12287 WILL_LJMP(luaL_error(L, "'CertCache.set' needs a table as argument"));
12288
12289 hlua = hlua_gethlua(L);
12290
12291 /* FIXME: this should not return an error but should come back later */
12292 if (HA_SPIN_TRYLOCK(CKCH_LOCK, &ckch_lock))
12293 WILL_LJMP(luaL_error(L, "CertCache already under lock"));
12294
12295 ret = lua_getfield(L, -1, "filename");
12296 if (ret != LUA_TSTRING) {
Thierry Fournier70e38e92022-09-19 09:01:53 +020012297 memprintf(&err, "%sNo filename specified!", err ? err : "");
William Lallemand30fcca12022-03-30 12:03:12 +020012298 errcode |= ERR_ALERT | ERR_FATAL;
12299 goto end;
12300 }
12301 filename = (char *)lua_tostring(L, -1);
12302
12303
12304 /* look for the filename in the tree */
12305 old_ckchs = ckchs_lookup(filename);
12306 if (!old_ckchs) {
Thierry Fournier70e38e92022-09-19 09:01:53 +020012307 memprintf(&err, "%sCan't replace a certificate which is not referenced by the configuration!", err ? err : "");
William Lallemand30fcca12022-03-30 12:03:12 +020012308 errcode |= ERR_ALERT | ERR_FATAL;
12309 goto end;
12310 }
12311 /* TODO: handle extra_files_noext */
12312
12313 new_ckchs = ckchs_dup(old_ckchs);
12314 if (!new_ckchs) {
Thierry Fournier70e38e92022-09-19 09:01:53 +020012315 memprintf(&err, "%sCannot allocate memory!", err ? err : "");
William Lallemand30fcca12022-03-30 12:03:12 +020012316 errcode |= ERR_ALERT | ERR_FATAL;
12317 goto end;
12318 }
12319
William Lallemand52ddd992022-11-22 11:51:53 +010012320 data = new_ckchs->data;
William Lallemand30fcca12022-03-30 12:03:12 +020012321
12322 /* loop on the field in the table, which have the same name as the
12323 * possible extensions of files */
12324 lua_pushnil(L);
12325 while (lua_next(L, 1)) {
12326 int i;
12327 const char *field = lua_tostring(L, -2);
12328 char *payload = (char *)lua_tostring(L, -1);
12329
12330 if (!field || strcmp(field, "filename") == 0) {
12331 lua_pop(L, 1);
12332 continue;
12333 }
12334
12335 for (i = 0; field && cert_exts[i].ext != NULL; i++) {
12336 if (strcmp(field, cert_exts[i].ext) == 0) {
12337 cert_ext = &cert_exts[i];
12338 break;
12339 }
12340 }
12341
12342 /* this is the default type, the field is not supported */
12343 if (cert_ext == NULL) {
Thierry Fournier70e38e92022-09-19 09:01:53 +020012344 memprintf(&err, "%sUnsupported field '%s'", err ? err : "", field);
William Lallemand30fcca12022-03-30 12:03:12 +020012345 errcode |= ERR_ALERT | ERR_FATAL;
12346 goto end;
12347 }
12348
12349 /* appply the change on the duplicate */
William Lallemand52ddd992022-11-22 11:51:53 +010012350 if (cert_ext->load(filename, payload, data, &err) != 0) {
Thierry Fournier70e38e92022-09-19 09:01:53 +020012351 memprintf(&err, "%sCan't load the payload for '%s'", err ? err : "", cert_ext->ext);
William Lallemand30fcca12022-03-30 12:03:12 +020012352 errcode |= ERR_ALERT | ERR_FATAL;
12353 goto end;
12354 }
12355 lua_pop(L, 1);
12356 }
12357
12358 /* store the pointers on the lua stack */
12359 lua_ckchs = lua_newuserdata(L, sizeof(struct ckch_store *) * 2);
12360 lua_ckchs[0] = old_ckchs;
12361 lua_ckchs[1] = new_ckchs;
12362 lua_ckchi = lua_newuserdata(L, sizeof(struct ckch_inst *));
12363 *lua_ckchi = NULL;
12364
12365 task_wakeup(hlua->task, TASK_WOKEN_MSG);
12366 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_ckch_commit_yield, TICK_ETERNITY, 0));
12367
12368end:
12369 HA_SPIN_UNLOCK(CKCH_LOCK, &ckch_lock);
12370
12371 if (errcode & ERR_CODE) {
12372 ckch_store_free(new_ckchs);
12373 WILL_LJMP(luaL_error(L, "%s", err));
12374 }
12375 free(err);
12376
12377 return 0;
12378}
12379
William Lallemand52139182022-03-30 15:05:42 +020012380#else
12381
12382__LJMP static int hlua_ckch_set(lua_State *L)
12383{
12384 WILL_LJMP(luaL_error(L, "'CertCache.set' needs an HAProxy built with OpenSSL"));
12385
12386 return 0;
12387}
12388#endif /* ! USE_OPENSSL */
12389
12390
12391
Thierry FOURNIERbabae282015-09-17 11:36:37 +020012392/* This function can fail with an abort() due to an Lua critical error.
12393 * We are in the initialisation process of HAProxy, this abort() is
12394 * tolerated.
12395 */
Thierry Fournierb8cef172020-11-28 15:37:17 +010012396int hlua_post_init_state(lua_State *L)
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010012397{
12398 struct hlua_init_function *init;
12399 const char *msg;
12400 enum hlua_exec ret;
Thierry Fournierfd107a22016-02-19 19:57:23 +010012401 const char *error;
Thierry Fournier670db242020-11-28 10:49:59 +010012402 const char *kind;
12403 const char *trace;
12404 int return_status = 1;
12405#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM >= 504
12406 int nres;
12407#endif
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010012408
Willy Tarreaucdb53462020-12-02 12:12:00 +010012409 /* disable memory limit checks if limit is not set */
12410 if (!hlua_global_allocator.limit)
12411 hlua_global_allocator.limit = ~hlua_global_allocator.limit;
12412
Ilya Shipitsin856aabc2020-04-16 23:51:34 +050012413 /* Call post initialisation function in safe environment. */
Thierry Fournier3c539322020-11-28 16:05:05 +010012414 if (setjmp(safe_ljmp_env) != 0) {
12415 lua_atpanic(L, hlua_panic_safe);
Thierry Fournierb8cef172020-11-28 15:37:17 +010012416 if (lua_type(L, -1) == LUA_TSTRING)
12417 error = lua_tostring(L, -1);
Thierry Fournier3d4a6752016-02-19 20:53:30 +010012418 else
12419 error = "critical error";
12420 fprintf(stderr, "Lua post-init: %s.\n", error);
12421 exit(1);
Thierry Fournier3c539322020-11-28 16:05:05 +010012422 } else {
12423 lua_atpanic(L, hlua_panic_ljmp);
Thierry Fournier3d4a6752016-02-19 20:53:30 +010012424 }
Frédéric Lécaille54f2bcf2018-08-29 13:46:24 +020012425
Thierry Fournierc7492592020-11-28 23:57:24 +010012426 list_for_each_entry(init, &hlua_init_functions[hlua_state_id], l) {
Aurelien DARRAGON4fdf8b52023-03-20 17:22:37 +010012427 hlua_pushref(L, init->function_ref);
Aurelien DARRAGON16d047b2023-03-20 16:29:55 +010012428 /* function ref should be released right away since it was pushed
12429 * on the stack and will not be used anymore
12430 */
12431 hlua_unref(L, init->function_ref);
Thierry Fournier670db242020-11-28 10:49:59 +010012432
12433#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM >= 504
Thierry Fournierb8cef172020-11-28 15:37:17 +010012434 ret = lua_resume(L, L, 0, &nres);
Thierry Fournier670db242020-11-28 10:49:59 +010012435#else
Thierry Fournierb8cef172020-11-28 15:37:17 +010012436 ret = lua_resume(L, L, 0);
Thierry Fournier670db242020-11-28 10:49:59 +010012437#endif
12438 kind = NULL;
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010012439 switch (ret) {
Thierry Fournier670db242020-11-28 10:49:59 +010012440
12441 case LUA_OK:
Thierry Fournierb8cef172020-11-28 15:37:17 +010012442 lua_pop(L, -1);
Thierry Fournier13d08b72020-11-28 11:02:58 +010012443 break;
Thierry Fournier670db242020-11-28 10:49:59 +010012444
12445 case LUA_ERRERR:
12446 kind = "message handler error";
Willy Tarreau14de3952022-11-14 07:08:28 +010012447 __fallthrough;
Thierry Fournier670db242020-11-28 10:49:59 +010012448 case LUA_ERRRUN:
12449 if (!kind)
12450 kind = "runtime error";
Thierry Fournierb8cef172020-11-28 15:37:17 +010012451 msg = lua_tostring(L, -1);
12452 lua_settop(L, 0); /* Empty the stack. */
12453 lua_pop(L, 1);
Christopher Fauletd09cc512021-03-24 14:48:45 +010012454 trace = hlua_traceback(L, ", ");
Thierry Fournier670db242020-11-28 10:49:59 +010012455 if (msg)
12456 ha_alert("Lua init: %s: '%s' from %s\n", kind, msg, trace);
12457 else
12458 ha_alert("Lua init: unknown %s from %s\n", kind, trace);
12459 return_status = 0;
12460 break;
12461
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010012462 default:
Thierry Fournier670db242020-11-28 10:49:59 +010012463 /* Unknown error */
12464 kind = "Unknown error";
Willy Tarreau14de3952022-11-14 07:08:28 +010012465 __fallthrough;
Thierry Fournier670db242020-11-28 10:49:59 +010012466 case LUA_YIELD:
12467 /* yield is not configured at this step, this state doesn't happen */
12468 if (!kind)
12469 kind = "yield not allowed";
Willy Tarreau14de3952022-11-14 07:08:28 +010012470 __fallthrough;
Thierry Fournier670db242020-11-28 10:49:59 +010012471 case LUA_ERRMEM:
12472 if (!kind)
12473 kind = "out of memory error";
Thierry Fournierb8cef172020-11-28 15:37:17 +010012474 lua_settop(L, 0);
12475 lua_pop(L, 1);
Christopher Fauletd09cc512021-03-24 14:48:45 +010012476 trace = hlua_traceback(L, ", ");
Thierry Fournier670db242020-11-28 10:49:59 +010012477 ha_alert("Lua init: %s: %s\n", kind, trace);
12478 return_status = 0;
12479 break;
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010012480 }
Thierry Fournier670db242020-11-28 10:49:59 +010012481 if (!return_status)
12482 break;
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010012483 }
Thierry Fournier3c539322020-11-28 16:05:05 +010012484
12485 lua_atpanic(L, hlua_panic_safe);
Thierry Fournier670db242020-11-28 10:49:59 +010012486 return return_status;
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010012487}
12488
Thierry Fournierb8cef172020-11-28 15:37:17 +010012489int hlua_post_init()
12490{
Thierry Fournier59f11be2020-11-29 00:37:41 +010012491 int ret;
12492 int i;
12493 int errors;
12494 char *err = NULL;
12495 struct hlua_function *fcn;
Christopher Faulet69c581a2021-05-31 08:54:04 +020012496 struct hlua_reg_filter *reg_flt;
Thierry Fournier59f11be2020-11-29 00:37:41 +010012497
Willy Tarreaub1310492021-08-30 09:35:18 +020012498#if defined(USE_OPENSSL)
Thierry Fournierb8cef172020-11-28 15:37:17 +010012499 /* Initialize SSL server. */
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010012500 if (socket_ssl->xprt->prepare_srv) {
Thierry Fournierb8cef172020-11-28 15:37:17 +010012501 int saved_used_backed = global.ssl_used_backend;
12502 // don't affect maxconn automatic computation
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010012503 socket_ssl->xprt->prepare_srv(socket_ssl);
Thierry Fournierb8cef172020-11-28 15:37:17 +010012504 global.ssl_used_backend = saved_used_backed;
12505 }
12506#endif
12507
Thierry Fournierc7492592020-11-28 23:57:24 +010012508 /* Perform post init of common thread */
12509 hlua_state_id = 0;
Willy Tarreau43ab05b2021-09-28 09:43:11 +020012510 ha_set_thread(&ha_thread_info[0]);
Thierry Fournier59f11be2020-11-29 00:37:41 +010012511 ret = hlua_post_init_state(hlua_states[hlua_state_id]);
12512 if (ret == 0)
12513 return 0;
12514
12515 /* init remaining lua states and load files */
12516 for (hlua_state_id = 2; hlua_state_id < global.nbthread + 1; hlua_state_id++) {
12517
12518 /* set thread context */
Willy Tarreau43ab05b2021-09-28 09:43:11 +020012519 ha_set_thread(&ha_thread_info[hlua_state_id - 1]);
Thierry Fournier59f11be2020-11-29 00:37:41 +010012520
12521 /* Init lua state */
12522 hlua_states[hlua_state_id] = hlua_init_state(hlua_state_id);
12523
12524 /* Load lua files */
12525 for (i = 0; per_thread_load && per_thread_load[i]; i++) {
12526 ret = hlua_load_state(per_thread_load[i], hlua_states[hlua_state_id], &err);
12527 if (ret != 0) {
12528 ha_alert("Lua init: %s\n", err);
12529 return 0;
12530 }
12531 }
12532 }
12533
12534 /* Reset thread context */
Willy Tarreau43ab05b2021-09-28 09:43:11 +020012535 ha_set_thread(NULL);
Thierry Fournier59f11be2020-11-29 00:37:41 +010012536
12537 /* Execute post init for all states */
12538 for (hlua_state_id = 1; hlua_state_id < global.nbthread + 1; hlua_state_id++) {
12539
12540 /* set thread context */
Willy Tarreau43ab05b2021-09-28 09:43:11 +020012541 ha_set_thread(&ha_thread_info[hlua_state_id - 1]);
Thierry Fournier59f11be2020-11-29 00:37:41 +010012542
12543 /* run post init */
12544 ret = hlua_post_init_state(hlua_states[hlua_state_id]);
12545 if (ret == 0)
12546 return 0;
12547 }
12548
12549 /* Reset thread context */
Willy Tarreau43ab05b2021-09-28 09:43:11 +020012550 ha_set_thread(NULL);
Thierry Fournier59f11be2020-11-29 00:37:41 +010012551
12552 /* control functions registering. Each function must have:
12553 * - only the function_ref[0] set positive and all other to -1
12554 * - only the function_ref[0] set to -1 and all other positive
12555 * This ensure a same reference is not used both in shared
12556 * lua state and thread dedicated lua state. Note: is the case
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +050012557 * reach, the shared state is priority, but the bug will be
Thierry Fournier59f11be2020-11-29 00:37:41 +010012558 * complicated to found for the end user.
12559 */
12560 errors = 0;
12561 list_for_each_entry(fcn, &referenced_functions, l) {
12562 ret = 0;
12563 for (i = 1; i < global.nbthread + 1; i++) {
12564 if (fcn->function_ref[i] == -1)
12565 ret--;
12566 else
12567 ret++;
12568 }
12569 if (abs(ret) != global.nbthread) {
12570 ha_alert("Lua function '%s' is not referenced in all thread. "
12571 "Expect function in all thread or in none thread.\n", fcn->name);
12572 errors++;
12573 continue;
12574 }
12575
12576 if ((fcn->function_ref[0] == -1) == (ret < 0)) {
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +050012577 ha_alert("Lua function '%s' is referenced both ins shared Lua context (through lua-load) "
12578 "and per-thread Lua context (through lua-load-per-thread). these two context "
Thierry Fournier59f11be2020-11-29 00:37:41 +010012579 "exclusive.\n", fcn->name);
12580 errors++;
12581 }
12582 }
12583
Christopher Faulet69c581a2021-05-31 08:54:04 +020012584 /* Do the same with registered filters */
12585 list_for_each_entry(reg_flt, &referenced_filters, l) {
12586 ret = 0;
12587 for (i = 1; i < global.nbthread + 1; i++) {
12588 if (reg_flt->flt_ref[i] == -1)
12589 ret--;
12590 else
12591 ret++;
12592 }
12593 if (abs(ret) != global.nbthread) {
12594 ha_alert("Lua filter '%s' is not referenced in all thread. "
12595 "Expect function in all thread or in none thread.\n", reg_flt->name);
12596 errors++;
12597 continue;
12598 }
12599
12600 if ((reg_flt->flt_ref[0] == -1) == (ret < 0)) {
12601 ha_alert("Lua filter '%s' is referenced both ins shared Lua context (through lua-load) "
12602 "and per-thread Lua context (through lua-load-per-thread). these two context "
12603 "exclusive.\n", fcn->name);
12604 errors++;
12605 }
12606 }
12607
12608
Thierry Fournier59f11be2020-11-29 00:37:41 +010012609 if (errors > 0)
12610 return 0;
12611
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +050012612 /* after this point, this global will no longer be used, so set to
Thierry Fournier59f11be2020-11-29 00:37:41 +010012613 * -1 in order to have probably a segfault if someone use it
12614 */
12615 hlua_state_id = -1;
12616
12617 return 1;
Thierry Fournierb8cef172020-11-28 15:37:17 +010012618}
12619
Willy Tarreau32f61e22015-03-18 17:54:59 +010012620/* The memory allocator used by the Lua stack. <ud> is a pointer to the
12621 * allocator's context. <ptr> is the pointer to alloc/free/realloc. <osize>
12622 * is the previously allocated size or the kind of object in case of a new
Willy Tarreaud36c7fa2020-12-02 12:26:29 +010012623 * allocation. <nsize> is the requested new size. A new allocation is
12624 * indicated by <ptr> being NULL. A free is indicated by <nsize> being
Willy Tarreaucdb53462020-12-02 12:12:00 +010012625 * zero. This one verifies that the limits are respected but is optimized
12626 * for the fast case where limits are not used, hence stats are not updated.
Willy Tarreaua5efdff2021-10-22 16:00:02 +020012627 *
12628 * Warning: while this API ressembles glibc's realloc() a lot, glibc surpasses
12629 * POSIX by making realloc(ptr,0) an effective free(), but others do not do
12630 * that and will simply allocate zero as if it were the result of malloc(0),
12631 * so mapping this onto realloc() will lead to memory leaks on non-glibc
12632 * systems.
Willy Tarreau32f61e22015-03-18 17:54:59 +010012633 */
12634static void *hlua_alloc(void *ud, void *ptr, size_t osize, size_t nsize)
12635{
12636 struct hlua_mem_allocator *zone = ud;
Willy Tarreaucdb53462020-12-02 12:12:00 +010012637 size_t limit, old, new;
12638
12639 /* a limit of ~0 means unlimited and boot complete, so there's no need
12640 * for accounting anymore.
12641 */
Willy Tarreaua5efdff2021-10-22 16:00:02 +020012642 if (likely(~zone->limit == 0)) {
12643 if (!nsize)
12644 ha_free(&ptr);
12645 else
12646 ptr = realloc(ptr, nsize);
12647 return ptr;
12648 }
Willy Tarreau32f61e22015-03-18 17:54:59 +010012649
Willy Tarreaud36c7fa2020-12-02 12:26:29 +010012650 if (!ptr)
12651 osize = 0;
Willy Tarreau32f61e22015-03-18 17:54:59 +010012652
Willy Tarreaucdb53462020-12-02 12:12:00 +010012653 /* enforce strict limits across all threads */
12654 limit = zone->limit;
12655 old = _HA_ATOMIC_LOAD(&zone->allocated);
12656 do {
12657 new = old + nsize - osize;
12658 if (unlikely(nsize && limit && new > limit))
12659 return NULL;
12660 } while (!_HA_ATOMIC_CAS(&zone->allocated, &old, new));
Willy Tarreau32f61e22015-03-18 17:54:59 +010012661
Willy Tarreaua5efdff2021-10-22 16:00:02 +020012662 if (!nsize)
12663 ha_free(&ptr);
12664 else
12665 ptr = realloc(ptr, nsize);
Willy Tarreaucdb53462020-12-02 12:12:00 +010012666
12667 if (unlikely(!ptr && nsize)) // failed
12668 _HA_ATOMIC_SUB(&zone->allocated, nsize - osize);
12669
12670 __ha_barrier_atomic_store();
Willy Tarreau32f61e22015-03-18 17:54:59 +010012671 return ptr;
12672}
12673
Thierry Fournierecb83c22020-11-28 15:49:44 +010012674/* This function can fail with an abort() due to a Lua critical error.
Thierry FOURNIERbabae282015-09-17 11:36:37 +020012675 * We are in the initialisation process of HAProxy, this abort() is
12676 * tolerated.
12677 */
Thierry Fournierecb83c22020-11-28 15:49:44 +010012678lua_State *hlua_init_state(int thread_num)
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +010012679{
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010012680 int i;
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010012681 int idx;
12682 struct sample_fetch *sf;
Thierry FOURNIER594afe72015-03-10 23:58:30 +010012683 struct sample_conv *sc;
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010012684 char *p;
Thierry Fournierfd107a22016-02-19 19:57:23 +010012685 const char *error_msg;
Thierry Fournier4234dbd2020-11-28 13:18:23 +010012686 void **context;
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012687 lua_State *L;
Thierry Fournier59f11be2020-11-29 00:37:41 +010012688 struct prepend_path *pp;
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010012689
Thierry FOURNIER380d0932015-01-23 14:27:52 +010012690 /* Init main lua stack. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012691 L = lua_newstate(hlua_alloc, &hlua_global_allocator);
Thierry FOURNIER380d0932015-01-23 14:27:52 +010012692
Thierry Fournier4234dbd2020-11-28 13:18:23 +010012693 /* Initialise Lua context to NULL */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012694 context = lua_getextraspace(L);
Thierry Fournier4234dbd2020-11-28 13:18:23 +010012695 *context = NULL;
12696
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -080012697 /* From this point, until the end of the initialisation function,
Thierry FOURNIERbabae282015-09-17 11:36:37 +020012698 * the Lua function can fail with an abort. We are in the initialisation
12699 * process of HAProxy, this abort() is tolerated.
12700 */
12701
Thierry Fournier3c539322020-11-28 16:05:05 +010012702 /* Call post initialisation function in safe environment. */
12703 if (setjmp(safe_ljmp_env) != 0) {
12704 lua_atpanic(L, hlua_panic_safe);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012705 if (lua_type(L, -1) == LUA_TSTRING)
12706 error_msg = lua_tostring(L, -1);
Thierry Fournier2f05cc62020-11-28 16:08:02 +010012707 else
12708 error_msg = "critical error";
12709 fprintf(stderr, "Lua init: %s.\n", error_msg);
12710 exit(1);
Thierry Fournier3c539322020-11-28 16:05:05 +010012711 } else {
12712 lua_atpanic(L, hlua_panic_ljmp);
Thierry Fournier2f05cc62020-11-28 16:08:02 +010012713 }
12714
Thierry FOURNIER380d0932015-01-23 14:27:52 +010012715 /* Initialise lua. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012716 luaL_openlibs(L);
Tim Duesterhus541fe1e2020-01-12 13:55:41 +010012717#define HLUA_PREPEND_PATH_TOSTRING1(x) #x
12718#define HLUA_PREPEND_PATH_TOSTRING(x) HLUA_PREPEND_PATH_TOSTRING1(x)
12719#ifdef HLUA_PREPEND_PATH
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012720 hlua_prepend_path(L, "path", HLUA_PREPEND_PATH_TOSTRING(HLUA_PREPEND_PATH));
Tim Duesterhus541fe1e2020-01-12 13:55:41 +010012721#endif
12722#ifdef HLUA_PREPEND_CPATH
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012723 hlua_prepend_path(L, "cpath", HLUA_PREPEND_PATH_TOSTRING(HLUA_PREPEND_CPATH));
Tim Duesterhus541fe1e2020-01-12 13:55:41 +010012724#endif
12725#undef HLUA_PREPEND_PATH_TOSTRING
12726#undef HLUA_PREPEND_PATH_TOSTRING1
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010012727
Thierry Fournier59f11be2020-11-29 00:37:41 +010012728 /* Apply configured prepend path */
12729 list_for_each_entry(pp, &prepend_path_list, l)
12730 hlua_prepend_path(L, pp->type, pp->path);
12731
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010012732 /*
12733 *
12734 * Create "core" object.
12735 *
12736 */
12737
Thierry FOURNIERa2d8c652015-03-11 17:29:39 +010012738 /* This table entry is the object "core" base. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012739 lua_newtable(L);
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010012740
Thierry Fournierecb83c22020-11-28 15:49:44 +010012741 /* set the thread id */
12742 hlua_class_const_int(L, "thread", thread_num);
12743
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010012744 /* Push the loglevel constants. */
Willy Tarreau80f5fae2015-02-27 16:38:20 +010012745 for (i = 0; i < NB_LOG_LEVELS; i++)
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012746 hlua_class_const_int(L, log_levels[i], i);
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010012747
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010012748 /* Register special functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012749 hlua_class_function(L, "register_init", hlua_register_init);
12750 hlua_class_function(L, "register_task", hlua_register_task);
12751 hlua_class_function(L, "register_fetches", hlua_register_fetches);
12752 hlua_class_function(L, "register_converters", hlua_register_converters);
12753 hlua_class_function(L, "register_action", hlua_register_action);
12754 hlua_class_function(L, "register_service", hlua_register_service);
12755 hlua_class_function(L, "register_cli", hlua_register_cli);
Christopher Faulet69c581a2021-05-31 08:54:04 +020012756 hlua_class_function(L, "register_filter", hlua_register_filter);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012757 hlua_class_function(L, "yield", hlua_yield);
12758 hlua_class_function(L, "set_nice", hlua_set_nice);
12759 hlua_class_function(L, "sleep", hlua_sleep);
12760 hlua_class_function(L, "msleep", hlua_msleep);
12761 hlua_class_function(L, "add_acl", hlua_add_acl);
12762 hlua_class_function(L, "del_acl", hlua_del_acl);
12763 hlua_class_function(L, "set_map", hlua_set_map);
12764 hlua_class_function(L, "del_map", hlua_del_map);
12765 hlua_class_function(L, "tcp", hlua_socket_new);
William Lallemand3956c4e2021-09-21 16:25:15 +020012766 hlua_class_function(L, "httpclient", hlua_httpclient_new);
Aurelien DARRAGONc84899c2023-02-20 18:18:59 +010012767 hlua_class_function(L, "event_sub", hlua_event_global_sub);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012768 hlua_class_function(L, "log", hlua_log);
12769 hlua_class_function(L, "Debug", hlua_log_debug);
12770 hlua_class_function(L, "Info", hlua_log_info);
12771 hlua_class_function(L, "Warning", hlua_log_warning);
12772 hlua_class_function(L, "Alert", hlua_log_alert);
12773 hlua_class_function(L, "done", hlua_done);
12774 hlua_fcn_reg_core_fcn(L);
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010012775
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012776 lua_setglobal(L, "core");
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010012777
12778 /*
12779 *
Christopher Faulet0f3c8902020-01-31 18:57:12 +010012780 * Create "act" object.
12781 *
12782 */
12783
12784 /* This table entry is the object "act" base. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012785 lua_newtable(L);
Christopher Faulet0f3c8902020-01-31 18:57:12 +010012786
12787 /* push action return constants */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012788 hlua_class_const_int(L, "CONTINUE", ACT_RET_CONT);
12789 hlua_class_const_int(L, "STOP", ACT_RET_STOP);
12790 hlua_class_const_int(L, "YIELD", ACT_RET_YIELD);
12791 hlua_class_const_int(L, "ERROR", ACT_RET_ERR);
12792 hlua_class_const_int(L, "DONE", ACT_RET_DONE);
12793 hlua_class_const_int(L, "DENY", ACT_RET_DENY);
12794 hlua_class_const_int(L, "ABORT", ACT_RET_ABRT);
12795 hlua_class_const_int(L, "INVALID", ACT_RET_INV);
Christopher Faulet0f3c8902020-01-31 18:57:12 +010012796
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012797 hlua_class_function(L, "wake_time", hlua_set_wake_time);
Christopher Faulet2c2c2e32020-01-31 19:07:52 +010012798
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012799 lua_setglobal(L, "act");
Christopher Faulet0f3c8902020-01-31 18:57:12 +010012800
12801 /*
12802 *
Christopher Faulet69c581a2021-05-31 08:54:04 +020012803 * Create "Filter" object.
12804 *
12805 */
12806
12807 /* This table entry is the object "filter" base. */
12808 lua_newtable(L);
12809
12810 /* push flags and constants */
12811 hlua_class_const_int(L, "CONTINUE", 1);
12812 hlua_class_const_int(L, "WAIT", 0);
12813 hlua_class_const_int(L, "ERROR", -1);
12814
12815 hlua_class_const_int(L, "FLT_CFG_FL_HTX", FLT_CFG_FL_HTX);
12816
Christopher Fauletc404f112020-02-26 15:03:09 +010012817 hlua_class_function(L, "wake_time", hlua_set_wake_time);
12818 hlua_class_function(L, "register_data_filter", hlua_register_data_filter);
12819 hlua_class_function(L, "unregister_data_filter", hlua_unregister_data_filter);
12820
Christopher Faulet69c581a2021-05-31 08:54:04 +020012821 lua_setglobal(L, "filter");
12822
12823 /*
12824 *
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012825 * Register class Map
12826 *
12827 */
12828
12829 /* This table entry is the object "Map" base. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012830 lua_newtable(L);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012831
12832 /* register pattern types. */
12833 for (i=0; i<PAT_MATCH_NUM; i++)
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012834 hlua_class_const_int(L, pat_match_names[i], i);
Thierry FOURNIER4dc71972017-01-28 08:33:08 +010012835 for (i=0; i<PAT_MATCH_NUM; i++) {
Willy Tarreau843b7cb2018-07-13 10:54:26 +020012836 snprintf(trash.area, trash.size, "_%s", pat_match_names[i]);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012837 hlua_class_const_int(L, trash.area, i);
Thierry FOURNIER4dc71972017-01-28 08:33:08 +010012838 }
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012839
12840 /* register constructor. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012841 hlua_class_function(L, "new", hlua_map_new);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012842
12843 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012844 lua_newtable(L);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012845
Ilya Shipitsind4259502020-04-08 01:07:56 +050012846 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012847 lua_pushstring(L, "__index");
12848 lua_newtable(L);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012849
12850 /* Register . */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012851 hlua_class_function(L, "lookup", hlua_map_lookup);
12852 hlua_class_function(L, "slookup", hlua_map_slookup);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012853
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012854 lua_rawset(L, -3);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012855
Thierry Fournier45e78d72016-02-19 18:34:46 +010012856 /* Register previous table in the registry with reference and named entry.
12857 * The function hlua_register_metatable() pops the stack, so we
12858 * previously create a copy of the table.
12859 */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012860 lua_pushvalue(L, -1); /* Copy the -1 entry and push it on the stack. */
12861 class_map_ref = hlua_register_metatable(L, CLASS_MAP);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012862
12863 /* Assign the metatable to the mai Map object. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012864 lua_setmetatable(L, -2);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012865
12866 /* Set a name to the table. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012867 lua_setglobal(L, "Map");
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012868
12869 /*
12870 *
William Lallemand30fcca12022-03-30 12:03:12 +020012871 * Register "CertCache" class
12872 *
12873 */
12874
12875 /* Create and fill the metatable. */
12876 lua_newtable(L);
12877 /* Register */
12878 hlua_class_function(L, "set", hlua_ckch_set);
12879 lua_setglobal(L, CLASS_CERTCACHE); /* Create global object called Regex */
12880
12881 /*
12882 *
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010012883 * Register class Channel
12884 *
12885 */
12886
12887 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012888 lua_newtable(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010012889
Ilya Shipitsind4259502020-04-08 01:07:56 +050012890 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012891 lua_pushstring(L, "__index");
12892 lua_newtable(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010012893
12894 /* Register . */
Christopher Faulet6a79fc12021-08-06 16:02:36 +020012895 hlua_class_function(L, "data", hlua_channel_get_data);
12896 hlua_class_function(L, "line", hlua_channel_get_line);
12897 hlua_class_function(L, "set", hlua_channel_set_data);
12898 hlua_class_function(L, "remove", hlua_channel_del_data);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012899 hlua_class_function(L, "append", hlua_channel_append);
Christopher Faulet6a79fc12021-08-06 16:02:36 +020012900 hlua_class_function(L, "prepend", hlua_channel_prepend);
12901 hlua_class_function(L, "insert", hlua_channel_insert_data);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012902 hlua_class_function(L, "send", hlua_channel_send);
12903 hlua_class_function(L, "forward", hlua_channel_forward);
Christopher Faulet6a79fc12021-08-06 16:02:36 +020012904 hlua_class_function(L, "input", hlua_channel_get_in_len);
12905 hlua_class_function(L, "output", hlua_channel_get_out_len);
12906 hlua_class_function(L, "may_recv", hlua_channel_may_recv);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012907 hlua_class_function(L, "is_full", hlua_channel_is_full);
12908 hlua_class_function(L, "is_resp", hlua_channel_is_resp);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010012909
Christopher Faulet6a79fc12021-08-06 16:02:36 +020012910 /* Deprecated API */
12911 hlua_class_function(L, "get", hlua_channel_get);
12912 hlua_class_function(L, "dup", hlua_channel_dup);
12913 hlua_class_function(L, "getline", hlua_channel_getline);
12914 hlua_class_function(L, "get_in_len", hlua_channel_get_in_len);
12915 hlua_class_function(L, "get_out_len", hlua_channel_get_out_len);
12916
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012917 lua_rawset(L, -3);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010012918
12919 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012920 class_channel_ref = hlua_register_metatable(L, CLASS_CHANNEL);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010012921
12922 /*
12923 *
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010012924 * Register class Fetches
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010012925 *
12926 */
12927
12928 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012929 lua_newtable(L);
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010012930
Ilya Shipitsind4259502020-04-08 01:07:56 +050012931 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012932 lua_pushstring(L, "__index");
12933 lua_newtable(L);
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010012934
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010012935 /* Browse existing fetches and create the associated
12936 * object method.
12937 */
12938 sf = NULL;
12939 while ((sf = sample_fetch_getnext(sf, &idx)) != NULL) {
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010012940 /* gL.Tua doesn't support '.' and '-' in the function names, replace it
12941 * by an underscore.
12942 */
Willy Tarreau5ef96562021-08-26 16:48:53 +020012943 strlcpy2(trash.area, sf->kw, trash.size);
Willy Tarreau843b7cb2018-07-13 10:54:26 +020012944 for (p = trash.area; *p; p++)
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010012945 if (*p == '.' || *p == '-' || *p == '+')
12946 *p = '_';
12947
12948 /* Register the function. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012949 lua_pushstring(L, trash.area);
12950 lua_pushlightuserdata(L, sf);
12951 lua_pushcclosure(L, hlua_run_sample_fetch, 1);
12952 lua_rawset(L, -3);
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010012953 }
12954
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012955 lua_rawset(L, -3);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010012956
12957 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012958 class_fetches_ref = hlua_register_metatable(L, CLASS_FETCHES);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010012959
12960 /*
12961 *
Thierry FOURNIER594afe72015-03-10 23:58:30 +010012962 * Register class Converters
12963 *
12964 */
12965
12966 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012967 lua_newtable(L);
Thierry FOURNIER594afe72015-03-10 23:58:30 +010012968
12969 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012970 lua_pushstring(L, "__index");
12971 lua_newtable(L);
Thierry FOURNIER594afe72015-03-10 23:58:30 +010012972
12973 /* Browse existing converters and create the associated
12974 * object method.
12975 */
12976 sc = NULL;
12977 while ((sc = sample_conv_getnext(sc, &idx)) != NULL) {
Thierry FOURNIER594afe72015-03-10 23:58:30 +010012978 /* gL.Tua doesn't support '.' and '-' in the function names, replace it
12979 * by an underscore.
12980 */
Willy Tarreau5ef96562021-08-26 16:48:53 +020012981 strlcpy2(trash.area, sc->kw, trash.size);
Willy Tarreau843b7cb2018-07-13 10:54:26 +020012982 for (p = trash.area; *p; p++)
Thierry FOURNIER594afe72015-03-10 23:58:30 +010012983 if (*p == '.' || *p == '-' || *p == '+')
12984 *p = '_';
12985
12986 /* Register the function. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012987 lua_pushstring(L, trash.area);
12988 lua_pushlightuserdata(L, sc);
12989 lua_pushcclosure(L, hlua_run_sample_conv, 1);
12990 lua_rawset(L, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +010012991 }
12992
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012993 lua_rawset(L, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +010012994
12995 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012996 class_converters_ref = hlua_register_metatable(L, CLASS_CONVERTERS);
Thierry FOURNIER594afe72015-03-10 23:58:30 +010012997
12998 /*
12999 *
Thierry FOURNIER08504f42015-03-16 14:17:08 +010013000 * Register class HTTP
13001 *
13002 */
13003
13004 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013005 lua_newtable(L);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010013006
Ilya Shipitsind4259502020-04-08 01:07:56 +050013007 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013008 lua_pushstring(L, "__index");
13009 lua_newtable(L);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010013010
13011 /* Register Lua functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013012 hlua_class_function(L, "req_get_headers",hlua_http_req_get_headers);
13013 hlua_class_function(L, "req_del_header", hlua_http_req_del_hdr);
13014 hlua_class_function(L, "req_rep_header", hlua_http_req_rep_hdr);
13015 hlua_class_function(L, "req_rep_value", hlua_http_req_rep_val);
13016 hlua_class_function(L, "req_add_header", hlua_http_req_add_hdr);
13017 hlua_class_function(L, "req_set_header", hlua_http_req_set_hdr);
13018 hlua_class_function(L, "req_set_method", hlua_http_req_set_meth);
13019 hlua_class_function(L, "req_set_path", hlua_http_req_set_path);
13020 hlua_class_function(L, "req_set_query", hlua_http_req_set_query);
13021 hlua_class_function(L, "req_set_uri", hlua_http_req_set_uri);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010013022
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013023 hlua_class_function(L, "res_get_headers",hlua_http_res_get_headers);
13024 hlua_class_function(L, "res_del_header", hlua_http_res_del_hdr);
13025 hlua_class_function(L, "res_rep_header", hlua_http_res_rep_hdr);
13026 hlua_class_function(L, "res_rep_value", hlua_http_res_rep_val);
13027 hlua_class_function(L, "res_add_header", hlua_http_res_add_hdr);
13028 hlua_class_function(L, "res_set_header", hlua_http_res_set_hdr);
13029 hlua_class_function(L, "res_set_status", hlua_http_res_set_status);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010013030
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013031 lua_rawset(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010013032
13033 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013034 class_http_ref = hlua_register_metatable(L, CLASS_HTTP);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010013035
Christopher Fauletdf97ac42020-02-26 16:57:19 +010013036 /*
13037 *
13038 * Register class HTTPMessage
13039 *
13040 */
13041
13042 /* Create and fill the metatable. */
13043 lua_newtable(L);
13044
Ilya Shipitsinff0f2782021-08-22 22:18:07 +050013045 /* Create and fill the __index entry. */
Christopher Fauletdf97ac42020-02-26 16:57:19 +010013046 lua_pushstring(L, "__index");
13047 lua_newtable(L);
13048
13049 /* Register Lua functions. */
13050 hlua_class_function(L, "is_resp", hlua_http_msg_is_resp);
13051 hlua_class_function(L, "get_stline", hlua_http_msg_get_stline);
13052 hlua_class_function(L, "get_headers", hlua_http_msg_get_headers);
13053 hlua_class_function(L, "del_header", hlua_http_msg_del_hdr);
13054 hlua_class_function(L, "rep_header", hlua_http_msg_rep_hdr);
13055 hlua_class_function(L, "rep_value", hlua_http_msg_rep_val);
13056 hlua_class_function(L, "add_header", hlua_http_msg_add_hdr);
13057 hlua_class_function(L, "set_header", hlua_http_msg_set_hdr);
13058 hlua_class_function(L, "set_method", hlua_http_msg_set_meth);
13059 hlua_class_function(L, "set_path", hlua_http_msg_set_path);
13060 hlua_class_function(L, "set_query", hlua_http_msg_set_query);
13061 hlua_class_function(L, "set_uri", hlua_http_msg_set_uri);
13062 hlua_class_function(L, "set_status", hlua_http_msg_set_status);
13063 hlua_class_function(L, "is_full", hlua_http_msg_is_full);
13064 hlua_class_function(L, "may_recv", hlua_http_msg_may_recv);
13065 hlua_class_function(L, "eom", hlua_http_msg_is_eom);
13066 hlua_class_function(L, "input", hlua_http_msg_get_in_len);
13067 hlua_class_function(L, "output", hlua_http_msg_get_out_len);
13068
13069 hlua_class_function(L, "body", hlua_http_msg_get_body);
13070 hlua_class_function(L, "set", hlua_http_msg_set_data);
13071 hlua_class_function(L, "remove", hlua_http_msg_del_data);
13072 hlua_class_function(L, "append", hlua_http_msg_append);
13073 hlua_class_function(L, "prepend", hlua_http_msg_prepend);
13074 hlua_class_function(L, "insert", hlua_http_msg_insert_data);
13075 hlua_class_function(L, "set_eom", hlua_http_msg_set_eom);
13076 hlua_class_function(L, "unset_eom", hlua_http_msg_unset_eom);
13077
13078 hlua_class_function(L, "send", hlua_http_msg_send);
13079 hlua_class_function(L, "forward", hlua_http_msg_forward);
13080
13081 lua_rawset(L, -3);
13082
13083 /* Register previous table in the registry with reference and named entry. */
13084 class_http_msg_ref = hlua_register_metatable(L, CLASS_HTTP_MSG);
William Lallemand3956c4e2021-09-21 16:25:15 +020013085
13086 /*
13087 *
13088 * Register class HTTPClient
13089 *
13090 */
13091
13092 /* Create and fill the metatable. */
13093 lua_newtable(L);
13094 lua_pushstring(L, "__index");
13095 lua_newtable(L);
13096 hlua_class_function(L, "get", hlua_httpclient_get);
William Lallemanddc2cc902021-10-26 11:43:26 +020013097 hlua_class_function(L, "head", hlua_httpclient_head);
13098 hlua_class_function(L, "put", hlua_httpclient_put);
13099 hlua_class_function(L, "post", hlua_httpclient_post);
13100 hlua_class_function(L, "delete", hlua_httpclient_delete);
William Lallemand3956c4e2021-09-21 16:25:15 +020013101 lua_settable(L, -3); /* Sets the __index entry. */
William Lallemandf77f1de2021-09-28 19:10:38 +020013102 /* Register the garbage collector entry. */
13103 lua_pushstring(L, "__gc");
13104 lua_pushcclosure(L, hlua_httpclient_gc, 0);
13105 lua_settable(L, -3); /* Push the last 2 entries in the table at index -3 */
13106
William Lallemand3956c4e2021-09-21 16:25:15 +020013107
13108
13109 class_httpclient_ref = hlua_register_metatable(L, CLASS_HTTPCLIENT);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010013110 /*
13111 *
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020013112 * Register class AppletTCP
13113 *
13114 */
13115
13116 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013117 lua_newtable(L);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020013118
Ilya Shipitsind4259502020-04-08 01:07:56 +050013119 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013120 lua_pushstring(L, "__index");
13121 lua_newtable(L);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020013122
13123 /* Register Lua functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013124 hlua_class_function(L, "getline", hlua_applet_tcp_getline);
13125 hlua_class_function(L, "receive", hlua_applet_tcp_recv);
13126 hlua_class_function(L, "send", hlua_applet_tcp_send);
13127 hlua_class_function(L, "set_priv", hlua_applet_tcp_set_priv);
13128 hlua_class_function(L, "get_priv", hlua_applet_tcp_get_priv);
13129 hlua_class_function(L, "set_var", hlua_applet_tcp_set_var);
13130 hlua_class_function(L, "unset_var", hlua_applet_tcp_unset_var);
13131 hlua_class_function(L, "get_var", hlua_applet_tcp_get_var);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020013132
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013133 lua_settable(L, -3);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020013134
13135 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013136 class_applet_tcp_ref = hlua_register_metatable(L, CLASS_APPLET_TCP);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020013137
13138 /*
13139 *
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020013140 * Register class AppletHTTP
13141 *
13142 */
13143
13144 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013145 lua_newtable(L);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020013146
Ilya Shipitsind4259502020-04-08 01:07:56 +050013147 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013148 lua_pushstring(L, "__index");
13149 lua_newtable(L);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020013150
13151 /* Register Lua functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013152 hlua_class_function(L, "set_priv", hlua_applet_http_set_priv);
13153 hlua_class_function(L, "get_priv", hlua_applet_http_get_priv);
13154 hlua_class_function(L, "set_var", hlua_applet_http_set_var);
13155 hlua_class_function(L, "unset_var", hlua_applet_http_unset_var);
13156 hlua_class_function(L, "get_var", hlua_applet_http_get_var);
13157 hlua_class_function(L, "getline", hlua_applet_http_getline);
13158 hlua_class_function(L, "receive", hlua_applet_http_recv);
13159 hlua_class_function(L, "send", hlua_applet_http_send);
13160 hlua_class_function(L, "add_header", hlua_applet_http_addheader);
13161 hlua_class_function(L, "set_status", hlua_applet_http_status);
13162 hlua_class_function(L, "start_response", hlua_applet_http_start_response);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020013163
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013164 lua_settable(L, -3);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020013165
13166 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013167 class_applet_http_ref = hlua_register_metatable(L, CLASS_APPLET_HTTP);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020013168
13169 /*
13170 *
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010013171 * Register class TXN
13172 *
13173 */
13174
13175 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013176 lua_newtable(L);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010013177
Ilya Shipitsind4259502020-04-08 01:07:56 +050013178 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013179 lua_pushstring(L, "__index");
13180 lua_newtable(L);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010013181
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +010013182 /* Register Lua functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013183 hlua_class_function(L, "set_priv", hlua_set_priv);
13184 hlua_class_function(L, "get_priv", hlua_get_priv);
13185 hlua_class_function(L, "set_var", hlua_set_var);
13186 hlua_class_function(L, "unset_var", hlua_unset_var);
13187 hlua_class_function(L, "get_var", hlua_get_var);
13188 hlua_class_function(L, "done", hlua_txn_done);
13189 hlua_class_function(L, "reply", hlua_txn_reply_new);
13190 hlua_class_function(L, "set_loglevel", hlua_txn_set_loglevel);
13191 hlua_class_function(L, "set_tos", hlua_txn_set_tos);
13192 hlua_class_function(L, "set_mark", hlua_txn_set_mark);
13193 hlua_class_function(L, "set_priority_class", hlua_txn_set_priority_class);
13194 hlua_class_function(L, "set_priority_offset", hlua_txn_set_priority_offset);
13195 hlua_class_function(L, "deflog", hlua_txn_deflog);
13196 hlua_class_function(L, "log", hlua_txn_log);
13197 hlua_class_function(L, "Debug", hlua_txn_log_debug);
13198 hlua_class_function(L, "Info", hlua_txn_log_info);
13199 hlua_class_function(L, "Warning", hlua_txn_log_warning);
13200 hlua_class_function(L, "Alert", hlua_txn_log_alert);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +010013201
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013202 lua_rawset(L, -3);
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010013203
13204 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013205 class_txn_ref = hlua_register_metatable(L, CLASS_TXN);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010013206
13207 /*
13208 *
Christopher Faulet700d9e82020-01-31 12:21:52 +010013209 * Register class reply
13210 *
13211 */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013212 lua_newtable(L);
13213 lua_pushstring(L, "__index");
13214 lua_newtable(L);
13215 hlua_class_function(L, "set_status", hlua_txn_reply_set_status);
13216 hlua_class_function(L, "add_header", hlua_txn_reply_add_header);
13217 hlua_class_function(L, "del_header", hlua_txn_reply_del_header);
13218 hlua_class_function(L, "set_body", hlua_txn_reply_set_body);
13219 lua_settable(L, -3); /* Sets the __index entry. */
13220 class_txn_reply_ref = luaL_ref(L, LUA_REGISTRYINDEX);
Christopher Faulet700d9e82020-01-31 12:21:52 +010013221
13222
13223 /*
13224 *
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010013225 * Register class Socket
13226 *
13227 */
13228
13229 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013230 lua_newtable(L);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010013231
Ilya Shipitsind4259502020-04-08 01:07:56 +050013232 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013233 lua_pushstring(L, "__index");
13234 lua_newtable(L);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010013235
Baptiste Assmann84bb4932015-03-02 21:40:06 +010013236#ifdef USE_OPENSSL
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013237 hlua_class_function(L, "connect_ssl", hlua_socket_connect_ssl);
Baptiste Assmann84bb4932015-03-02 21:40:06 +010013238#endif
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013239 hlua_class_function(L, "connect", hlua_socket_connect);
13240 hlua_class_function(L, "send", hlua_socket_send);
13241 hlua_class_function(L, "receive", hlua_socket_receive);
13242 hlua_class_function(L, "close", hlua_socket_close);
13243 hlua_class_function(L, "getpeername", hlua_socket_getpeername);
13244 hlua_class_function(L, "getsockname", hlua_socket_getsockname);
13245 hlua_class_function(L, "setoption", hlua_socket_setoption);
13246 hlua_class_function(L, "settimeout", hlua_socket_settimeout);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010013247
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013248 lua_rawset(L, -3); /* Push the last 2 entries in the table at index -3 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010013249
13250 /* Register the garbage collector entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013251 lua_pushstring(L, "__gc");
13252 lua_pushcclosure(L, hlua_socket_gc, 0);
13253 lua_rawset(L, -3); /* Push the last 2 entries in the table at index -3 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010013254
13255 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013256 class_socket_ref = hlua_register_metatable(L, CLASS_SOCKET);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010013257
Thierry Fournieraafc7772020-12-04 11:47:47 +010013258 lua_atpanic(L, hlua_panic_safe);
13259
13260 return L;
13261}
13262
13263void hlua_init(void) {
13264 int i;
Amaury Denoyelle239fdbf2021-03-24 10:22:03 +010013265 char *errmsg;
Thierry Fournieraafc7772020-12-04 11:47:47 +010013266#ifdef USE_OPENSSL
13267 struct srv_kw *kw;
13268 int tmp_error;
13269 char *error;
13270 char *args[] = { /* SSL client configuration. */
13271 "ssl",
13272 "verify",
13273 "none",
13274 NULL
13275 };
13276#endif
13277
13278 /* Init post init function list head */
13279 for (i = 0; i < MAX_THREADS + 1; i++)
13280 LIST_INIT(&hlua_init_functions[i]);
13281
13282 /* Init state for common/shared lua parts */
13283 hlua_state_id = 0;
Willy Tarreau43ab05b2021-09-28 09:43:11 +020013284 ha_set_thread(NULL);
Thierry Fournieraafc7772020-12-04 11:47:47 +010013285 hlua_states[0] = hlua_init_state(0);
13286
13287 /* Init state 1 for thread 0. We have at least one thread. */
13288 hlua_state_id = 1;
Willy Tarreau43ab05b2021-09-28 09:43:11 +020013289 ha_set_thread(NULL);
Thierry Fournieraafc7772020-12-04 11:47:47 +010013290 hlua_states[1] = hlua_init_state(1);
13291
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010013292 /* Proxy and server configuration initialisation. */
William Lallemand6bb77b92021-07-28 15:48:16 +020013293 socket_proxy = alloc_new_proxy("LUA-SOCKET", PR_CAP_FE|PR_CAP_BE|PR_CAP_INT, &errmsg);
Amaury Denoyelle239fdbf2021-03-24 10:22:03 +010013294 if (!socket_proxy) {
13295 fprintf(stderr, "Lua init: %s\n", errmsg);
13296 exit(1);
13297 }
13298 proxy_preset_defaults(socket_proxy);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010013299
13300 /* Init TCP server: unchanged parameters */
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010013301 socket_tcp = new_server(socket_proxy);
13302 if (!socket_tcp) {
13303 fprintf(stderr, "Lua init: failed to allocate tcp server socket\n");
13304 exit(1);
13305 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010013306
13307#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010013308 /* Init TCP server: unchanged parameters */
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010013309 socket_ssl = new_server(socket_proxy);
13310 if (!socket_ssl) {
13311 fprintf(stderr, "Lua init: failed to allocate ssl server socket\n");
13312 exit(1);
13313 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010013314
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010013315 socket_ssl->use_ssl = 1;
13316 socket_ssl->xprt = xprt_get(XPRT_SSL);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010013317
Bertrand Jacquin80839ff2021-01-21 19:14:46 +000013318 for (i = 0; args[i] != NULL; i++) {
13319 if ((kw = srv_find_kw(args[i])) != NULL) { /* Maybe it's registered server keyword */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010013320 /*
13321 *
13322 * If the keyword is not known, we can search in the registered
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -080013323 * server keywords. This is useful to configure special SSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010013324 * features like client certificates and ssl_verify.
13325 *
13326 */
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010013327 tmp_error = kw->parse(args, &i, socket_proxy, socket_ssl, &error);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010013328 if (tmp_error != 0) {
13329 fprintf(stderr, "INTERNAL ERROR: %s\n", error);
13330 abort(); /* This must be never arrives because the command line
13331 not editable by the user. */
13332 }
Bertrand Jacquin80839ff2021-01-21 19:14:46 +000013333 i += kw->skip;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010013334 }
13335 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010013336#endif
Thierry Fournier75933d42016-01-21 09:30:18 +010013337
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +010013338}
Willy Tarreaubb57d942016-12-21 19:04:56 +010013339
Tim Duesterhusd0c0ca22020-07-04 11:53:26 +020013340static void hlua_deinit()
13341{
Willy Tarreau186f3762020-12-04 11:48:12 +010013342 int thr;
Christopher Faulet69c581a2021-05-31 08:54:04 +020013343 struct hlua_reg_filter *reg_flt, *reg_flt_bck;
13344
13345 list_for_each_entry_safe(reg_flt, reg_flt_bck, &referenced_filters, l)
13346 release_hlua_reg_filter(reg_flt);
Willy Tarreau186f3762020-12-04 11:48:12 +010013347
13348 for (thr = 0; thr < MAX_THREADS+1; thr++) {
13349 if (hlua_states[thr])
13350 lua_close(hlua_states[thr]);
13351 }
Willy Tarreau430bf4a2021-03-04 09:45:32 +010013352
Amaury Denoyellebc2ebfa2021-08-25 15:34:53 +020013353 srv_drop(socket_tcp);
Willy Tarreau430bf4a2021-03-04 09:45:32 +010013354
Willy Tarreau0f143af2021-03-05 10:41:48 +010013355#ifdef USE_OPENSSL
Amaury Denoyellebc2ebfa2021-08-25 15:34:53 +020013356 srv_drop(socket_ssl);
Willy Tarreau0f143af2021-03-05 10:41:48 +010013357#endif
Amaury Denoyelle239fdbf2021-03-24 10:22:03 +010013358
13359 free_proxy(socket_proxy);
Tim Duesterhusd0c0ca22020-07-04 11:53:26 +020013360}
13361
13362REGISTER_POST_DEINIT(hlua_deinit);
13363
Willy Tarreau80713382018-11-26 10:19:54 +010013364static void hlua_register_build_options(void)
13365{
Willy Tarreaubb57d942016-12-21 19:04:56 +010013366 char *ptr = NULL;
Willy Tarreau80713382018-11-26 10:19:54 +010013367
Willy Tarreaubb57d942016-12-21 19:04:56 +010013368 memprintf(&ptr, "Built with Lua version : %s", LUA_RELEASE);
13369 hap_register_build_opts(ptr, 1);
13370}
Willy Tarreau80713382018-11-26 10:19:54 +010013371
13372INITCALL0(STG_REGISTER, hlua_register_build_options);