blob: a00a114165093948bf1e7740f97694250b260023 [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);
Christopher Faulet700d9e82020-01-31 12:21:52 +01008161 channel_erase(req);
8162
Christopher Faulet700d9e82020-01-31 12:21:52 +01008163 channel_auto_read(res);
8164 channel_auto_close(res);
Christopher Faulet12762f02023-04-13 15:40:10 +02008165 sc_schedule_abort(s->scb);
Christopher Faulet700d9e82020-01-31 12:21:52 +01008166
8167 finst = ((htxn->dir == SMP_OPT_DIR_REQ) ? SF_FINST_R : SF_FINST_D);
8168 goto done;
Christopher Fauletfe6a71b2019-07-26 16:40:24 +02008169 }
Thierry FOURNIER10ec2142015-08-24 17:23:45 +02008170
Christopher Faulet700d9e82020-01-31 12:21:52 +01008171 if (lua_gettop(L) == 1 || !lua_istable(L, 2)) {
8172 /* No reply or invalid reply */
8173 s->txn->status = 0;
8174 http_reply_and_close(s, 0, NULL);
8175 }
8176 else {
8177 /* Remove extra args to have the reply on top of the stack */
8178 if (lua_gettop(L) > 2)
8179 lua_pop(L, lua_gettop(L) - 2);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01008180
Christopher Faulet700d9e82020-01-31 12:21:52 +01008181 if (!hlua_txn_forward_reply(L, s)) {
8182 if (!(s->flags & SF_ERR_MASK))
8183 s->flags |= SF_ERR_PRXCOND;
8184 lua_pushinteger(L, ACT_RET_ERR);
8185 WILL_LJMP(hlua_done(L));
8186 return 0; /* Never reached */
8187 }
Christopher Faulet4d0e2632019-07-16 10:52:40 +02008188 }
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02008189
Christopher Faulet700d9e82020-01-31 12:21:52 +01008190 finst = ((htxn->dir == SMP_OPT_DIR_REQ) ? SF_FINST_R : SF_FINST_H);
8191 if (htxn->dir == SMP_OPT_DIR_REQ) {
8192 /* let's log the request time */
8193 s->logs.tv_request = now;
8194 if (s->sess->fe == s->be) /* report it if the request was intercepted by the frontend */
Willy Tarreau4781b152021-04-06 13:53:36 +02008195 _HA_ATOMIC_INC(&s->sess->fe->fe_counters.intercepted_req);
Christopher Faulet700d9e82020-01-31 12:21:52 +01008196 }
Christopher Fauletfe6a71b2019-07-26 16:40:24 +02008197
Christopher Faulet700d9e82020-01-31 12:21:52 +01008198 done:
8199 if (!(s->flags & SF_ERR_MASK))
8200 s->flags |= SF_ERR_LOCAL;
8201 if (!(s->flags & SF_FINST_MASK))
8202 s->flags |= finst;
Christopher Fauletfe6a71b2019-07-26 16:40:24 +02008203
Christopher Faulete48d1dc2021-08-13 14:11:17 +02008204 if ((htxn->flags & HLUA_TXN_CTX_MASK) == HLUA_TXN_FLT_CTX)
8205 lua_pushinteger(L, -1);
8206 else
8207 lua_pushinteger(L, ACT_RET_ABRT);
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02008208 WILL_LJMP(hlua_done(L));
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01008209 return 0;
8210}
8211
Christopher Faulet700d9e82020-01-31 12:21:52 +01008212/*
8213 *
8214 *
8215 * Class REPLY
8216 *
8217 *
8218 */
8219
8220/* Pushes the TXN reply onto the top of the stack. If the stask does not have a
8221 * free slots, the function fails and returns 0;
8222 */
8223static int hlua_txn_reply_new(lua_State *L)
8224{
8225 struct hlua_txn *htxn;
8226 const char *reason, *body = NULL;
8227 int ret, status;
8228
8229 htxn = MAY_LJMP(hlua_checktxn(L, 1));
Christopher Fauletd8f0e072020-02-25 09:45:51 +01008230 if (!IS_HTX_STRM(htxn->s)) {
Christopher Faulet700d9e82020-01-31 12:21:52 +01008231 hlua_pusherror(L, "txn object is not an HTTP transaction.");
8232 WILL_LJMP(lua_error(L));
8233 }
8234
8235 /* Default value */
8236 status = 200;
8237 reason = http_get_reason(status);
8238
8239 if (lua_istable(L, 2)) {
8240 /* load status and reason from the table argument at index 2 */
8241 ret = lua_getfield(L, 2, "status");
8242 if (ret == LUA_TNIL)
8243 goto reason;
8244 else if (ret != LUA_TNUMBER) {
8245 /* invalid status: ignore the reason */
8246 goto body;
8247 }
8248 status = lua_tointeger(L, -1);
8249
8250 reason:
8251 lua_pop(L, 1); /* restore the stack: remove status */
8252 ret = lua_getfield(L, 2, "reason");
8253 if (ret == LUA_TSTRING)
8254 reason = lua_tostring(L, -1);
8255
8256 body:
8257 lua_pop(L, 1); /* restore the stack: remove invalid status or reason */
8258 ret = lua_getfield(L, 2, "body");
8259 if (ret == LUA_TSTRING)
8260 body = lua_tostring(L, -1);
8261 lua_pop(L, 1); /* restore the stack: remove body */
8262 }
8263
8264 /* Create the Reply table */
8265 lua_newtable(L);
8266
8267 /* Add status element */
8268 lua_pushstring(L, "status");
8269 lua_pushinteger(L, status);
8270 lua_settable(L, -3);
8271
8272 /* Add reason element */
8273 reason = http_get_reason(status);
8274 lua_pushstring(L, "reason");
8275 lua_pushstring(L, reason);
8276 lua_settable(L, -3);
8277
8278 /* Add body element, nil if undefined */
8279 lua_pushstring(L, "body");
8280 if (body)
8281 lua_pushstring(L, body);
8282 else
8283 lua_pushnil(L);
8284 lua_settable(L, -3);
8285
8286 /* Add headers element */
8287 lua_pushstring(L, "headers");
8288 lua_newtable(L);
8289
8290 /* stack: [ txn, <Arg:table>, <Reply:table>, "headers", <headers:table> ] */
8291 if (lua_istable(L, 2)) {
8292 /* load headers from the table argument at index 2. If it is a table, copy it. */
8293 ret = lua_getfield(L, 2, "headers");
8294 if (ret == LUA_TTABLE) {
8295 /* stack: [ ... <headers:table>, <table> ] */
8296 lua_pushnil(L);
8297 while (lua_next(L, -2) != 0) {
8298 /* stack: [ ... <headers:table>, <table>, k, v] */
8299 if (!lua_isstring(L, -1) && !lua_istable(L, -1)) {
8300 /* invalid value type, skip it */
8301 lua_pop(L, 1);
8302 continue;
8303 }
8304
8305
8306 /* Duplicate the key and swap it with the value. */
8307 lua_pushvalue(L, -2);
8308 lua_insert(L, -2);
8309 /* stack: [ ... <headers:table>, <table>, k, k, v ] */
8310
8311 lua_newtable(L);
8312 lua_insert(L, -2);
8313 /* stack: [ ... <headers:table>, <table>, k, k, <inner:table>, v ] */
8314
8315 if (lua_isstring(L, -1)) {
8316 /* push the value in the inner table */
8317 lua_rawseti(L, -2, 1);
8318 }
8319 else { /* table */
8320 lua_pushnil(L);
8321 while (lua_next(L, -2) != 0) {
8322 /* stack: [ ... <headers:table>, <table>, k, k, <inner:table>, <v:table>, k2, v2 ] */
8323 if (!lua_isstring(L, -1)) {
8324 /* invalid value type, skip it*/
8325 lua_pop(L, 1);
8326 continue;
8327 }
8328 /* push the value in the inner table */
8329 lua_rawseti(L, -4, lua_rawlen(L, -4) + 1);
8330 /* stack: [ ... <headers:table>, <table>, k, k, <inner:table>, <v:table>, k2 ] */
8331 }
8332 lua_pop(L, 1);
8333 /* stack: [ ... <headers:table>, <table>, k, k, <inner:table> ] */
8334 }
8335
8336 /* push (k,v) on the stack in the headers table:
8337 * stack: [ ... <headers:table>, <table>, k, k, v ]
8338 */
8339 lua_settable(L, -5);
8340 /* stack: [ ... <headers:table>, <table>, k ] */
8341 }
8342 }
8343 lua_pop(L, 1);
8344 }
8345 /* stack: [ txn, <Arg:table>, <Reply:table>, "headers", <headers:table> ] */
8346 lua_settable(L, -3);
8347 /* stack: [ txn, <Arg:table>, <Reply:table> ] */
8348
8349 /* Pop a class sesison metatable and affect it to the userdata. */
8350 lua_rawgeti(L, LUA_REGISTRYINDEX, class_txn_reply_ref);
8351 lua_setmetatable(L, -2);
8352 return 1;
8353}
8354
8355/* Set the reply status code, and optionally the reason. If no reason is
8356 * provided, the default one corresponding to the status code is used.
8357 */
8358__LJMP static int hlua_txn_reply_set_status(lua_State *L)
8359{
8360 int status = MAY_LJMP(luaL_checkinteger(L, 2));
8361 const char *reason = MAY_LJMP(luaL_optlstring(L, 3, NULL, NULL));
8362
8363 /* First argument (self) must be a table */
Aurelien DARRAGONd83d0452022-10-05 11:46:45 +02008364 MAY_LJMP(luaL_checktype(L, 1, LUA_TTABLE));
Christopher Faulet700d9e82020-01-31 12:21:52 +01008365
8366 if (status < 100 || status > 599) {
8367 lua_pushboolean(L, 0);
8368 return 1;
8369 }
8370 if (!reason)
8371 reason = http_get_reason(status);
8372
8373 lua_pushinteger(L, status);
8374 lua_setfield(L, 1, "status");
8375
8376 lua_pushstring(L, reason);
8377 lua_setfield(L, 1, "reason");
8378
8379 lua_pushboolean(L, 1);
8380 return 1;
8381}
8382
8383/* Add a header into the reply object. Each header name is associated to an
8384 * array of values in the "headers" table. If the header name is not found, a
8385 * new entry is created.
8386 */
8387__LJMP static int hlua_txn_reply_add_header(lua_State *L)
8388{
8389 const char *name = MAY_LJMP(luaL_checkstring(L, 2));
8390 const char *value = MAY_LJMP(luaL_checkstring(L, 3));
8391 int ret;
8392
8393 /* First argument (self) must be a table */
Aurelien DARRAGONd83d0452022-10-05 11:46:45 +02008394 MAY_LJMP(luaL_checktype(L, 1, LUA_TTABLE));
Christopher Faulet700d9e82020-01-31 12:21:52 +01008395
8396 /* Push in the stack the "headers" entry. */
8397 ret = lua_getfield(L, 1, "headers");
8398 if (ret != LUA_TTABLE) {
8399 hlua_pusherror(L, "Reply['headers'] is expected to a an array. %s found", lua_typename(L, ret));
8400 WILL_LJMP(lua_error(L));
8401 }
8402
8403 /* check if the header is already registered. If not, register it. */
8404 ret = lua_getfield(L, -1, name);
8405 if (ret == LUA_TNIL) {
8406 /* Entry not found. */
8407 lua_pop(L, 1); /* remove the nil. The "headers" table is the top of the stack. */
8408
8409 /* Insert the new header name in the array in the top of the stack.
8410 * It left the new array in the top of the stack.
8411 */
8412 lua_newtable(L);
8413 lua_pushstring(L, name);
8414 lua_pushvalue(L, -2);
8415 lua_settable(L, -4);
8416 }
8417 else if (ret != LUA_TTABLE) {
8418 hlua_pusherror(L, "Reply['headers']['%s'] is expected to be an array. %s found", name, lua_typename(L, ret));
8419 WILL_LJMP(lua_error(L));
8420 }
8421
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -07008422 /* Now the top of thestack is an array of values. We push
Christopher Faulet700d9e82020-01-31 12:21:52 +01008423 * the header value as new entry.
8424 */
8425 lua_pushstring(L, value);
8426 ret = lua_rawlen(L, -2);
8427 lua_rawseti(L, -2, ret + 1);
8428
8429 lua_pushboolean(L, 1);
8430 return 1;
8431}
8432
8433/* Remove all occurrences of a given header name. */
8434__LJMP static int hlua_txn_reply_del_header(lua_State *L)
8435{
8436 const char *name = MAY_LJMP(luaL_checkstring(L, 2));
8437 int ret;
8438
8439 /* First argument (self) must be a table */
Aurelien DARRAGONd83d0452022-10-05 11:46:45 +02008440 MAY_LJMP(luaL_checktype(L, 1, LUA_TTABLE));
Christopher Faulet700d9e82020-01-31 12:21:52 +01008441
8442 /* Push in the stack the "headers" entry. */
8443 ret = lua_getfield(L, 1, "headers");
8444 if (ret != LUA_TTABLE) {
8445 hlua_pusherror(L, "Reply['headers'] is expected to be an array. %s found", lua_typename(L, ret));
8446 WILL_LJMP(lua_error(L));
8447 }
8448
8449 lua_pushstring(L, name);
8450 lua_pushnil(L);
8451 lua_settable(L, -3);
8452
8453 lua_pushboolean(L, 1);
8454 return 1;
8455}
8456
8457/* Set the reply's body. Overwrite any existing entry. */
8458__LJMP static int hlua_txn_reply_set_body(lua_State *L)
8459{
8460 const char *payload = MAY_LJMP(luaL_checkstring(L, 2));
8461
8462 /* First argument (self) must be a table */
Aurelien DARRAGONd83d0452022-10-05 11:46:45 +02008463 MAY_LJMP(luaL_checktype(L, 1, LUA_TTABLE));
Christopher Faulet700d9e82020-01-31 12:21:52 +01008464
8465 lua_pushstring(L, payload);
8466 lua_setfield(L, 1, "body");
8467
8468 lua_pushboolean(L, 1);
8469 return 1;
8470}
8471
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01008472__LJMP static int hlua_log(lua_State *L)
8473{
8474 int level;
8475 const char *msg;
8476
8477 MAY_LJMP(check_args(L, 2, "log"));
8478 level = MAY_LJMP(luaL_checkinteger(L, 1));
8479 msg = MAY_LJMP(luaL_checkstring(L, 2));
8480
8481 if (level < 0 || level >= NB_LOG_LEVELS)
8482 WILL_LJMP(luaL_argerror(L, 1, "Invalid loglevel."));
8483
8484 hlua_sendlog(NULL, level, msg);
8485 return 0;
8486}
8487
8488__LJMP static int hlua_log_debug(lua_State *L)
8489{
8490 const char *msg;
8491
8492 MAY_LJMP(check_args(L, 1, "debug"));
8493 msg = MAY_LJMP(luaL_checkstring(L, 1));
8494 hlua_sendlog(NULL, LOG_DEBUG, msg);
8495 return 0;
8496}
8497
8498__LJMP static int hlua_log_info(lua_State *L)
8499{
8500 const char *msg;
8501
8502 MAY_LJMP(check_args(L, 1, "info"));
8503 msg = MAY_LJMP(luaL_checkstring(L, 1));
8504 hlua_sendlog(NULL, LOG_INFO, msg);
8505 return 0;
8506}
8507
8508__LJMP static int hlua_log_warning(lua_State *L)
8509{
8510 const char *msg;
8511
8512 MAY_LJMP(check_args(L, 1, "warning"));
8513 msg = MAY_LJMP(luaL_checkstring(L, 1));
8514 hlua_sendlog(NULL, LOG_WARNING, msg);
8515 return 0;
8516}
8517
8518__LJMP static int hlua_log_alert(lua_State *L)
8519{
8520 const char *msg;
8521
8522 MAY_LJMP(check_args(L, 1, "alert"));
8523 msg = MAY_LJMP(luaL_checkstring(L, 1));
8524 hlua_sendlog(NULL, LOG_ALERT, msg);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01008525 return 0;
8526}
8527
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01008528__LJMP static int hlua_sleep_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008529{
8530 int wakeup_ms = lua_tointeger(L, -1);
Willy Tarreau12c02702021-09-30 16:12:31 +02008531 if (!tick_is_expired(wakeup_ms, now_ms))
Willy Tarreau9635e032018-10-16 17:52:55 +02008532 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008533 return 0;
8534}
8535
8536__LJMP static int hlua_sleep(lua_State *L)
8537{
8538 unsigned int delay;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008539 unsigned int wakeup_ms;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008540
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008541 MAY_LJMP(check_args(L, 1, "sleep"));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008542
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01008543 delay = MAY_LJMP(luaL_checkinteger(L, 1)) * 1000;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008544 wakeup_ms = tick_add(now_ms, delay);
8545 lua_pushinteger(L, wakeup_ms);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008546
Willy Tarreau9635e032018-10-16 17:52:55 +02008547 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008548 return 0;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008549}
8550
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008551__LJMP static int hlua_msleep(lua_State *L)
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008552{
8553 unsigned int delay;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008554 unsigned int wakeup_ms;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008555
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008556 MAY_LJMP(check_args(L, 1, "msleep"));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008557
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01008558 delay = MAY_LJMP(luaL_checkinteger(L, 1));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008559 wakeup_ms = tick_add(now_ms, delay);
8560 lua_pushinteger(L, wakeup_ms);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008561
Willy Tarreau9635e032018-10-16 17:52:55 +02008562 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008563 return 0;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008564}
8565
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01008566/* This functionis an LUA binding. it permits to give back
8567 * the hand at the HAProxy scheduler. It is used when the
8568 * LUA processing consumes a lot of time.
8569 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01008570__LJMP static int hlua_yield_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008571{
8572 return 0;
8573}
8574
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01008575__LJMP static int hlua_yield(lua_State *L)
8576{
Willy Tarreau9635e032018-10-16 17:52:55 +02008577 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_yield_yield, TICK_ETERNITY, HLUA_CTRLYIELD));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008578 return 0;
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01008579}
8580
Thierry FOURNIER37196f42015-02-16 19:34:56 +01008581/* This function change the nice of the currently executed
8582 * task. It is used set low or high priority at the current
8583 * task.
8584 */
Willy Tarreau59551662015-03-10 14:23:13 +01008585__LJMP static int hlua_set_nice(lua_State *L)
Thierry FOURNIER37196f42015-02-16 19:34:56 +01008586{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01008587 struct hlua *hlua;
8588 int nice;
Thierry FOURNIER37196f42015-02-16 19:34:56 +01008589
Willy Tarreau80f5fae2015-02-27 16:38:20 +01008590 MAY_LJMP(check_args(L, 1, "set_nice"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01008591 nice = MAY_LJMP(luaL_checkinteger(L, 1));
Thierry FOURNIER37196f42015-02-16 19:34:56 +01008592
Thierry Fournier4234dbd2020-11-28 13:18:23 +01008593 /* Get hlua struct, or NULL if we execute from main lua state */
8594 hlua = hlua_gethlua(L);
8595
8596 /* If the task is not set, I'm in a start mode. */
Thierry FOURNIER37196f42015-02-16 19:34:56 +01008597 if (!hlua || !hlua->task)
8598 return 0;
8599
8600 if (nice < -1024)
8601 nice = -1024;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01008602 else if (nice > 1024)
Thierry FOURNIER37196f42015-02-16 19:34:56 +01008603 nice = 1024;
8604
8605 hlua->task->nice = nice;
8606 return 0;
8607}
8608
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08008609/* This function is used as a callback of a task. It is called by the
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008610 * HAProxy task subsystem when the task is awaked. The LUA runtime can
8611 * return an E_AGAIN signal, the emmiter of this signal must set a
8612 * signal to wake the task.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008613 *
8614 * Task wrapper are longjmp safe because the only one Lua code
8615 * executed is the safe hlua_ctx_resume();
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008616 */
Willy Tarreau144f84a2021-03-02 16:09:26 +01008617struct task *hlua_process_task(struct task *task, void *context, unsigned int state)
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008618{
Olivier Houchard9f6af332018-05-25 14:04:04 +02008619 struct hlua *hlua = context;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008620 enum hlua_exec status;
8621
Willy Tarreau6ef52f42022-06-15 14:19:48 +02008622 if (task->tid < 0)
8623 task->tid = tid;
8624
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008625 /* If it is the first call to the task, we must initialize the
8626 * execution timeouts.
8627 */
8628 if (!HLUA_IS_RUNNING(hlua))
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02008629 hlua->max_time = hlua_timeout_task;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008630
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008631 /* Execute the Lua code. */
8632 status = hlua_ctx_resume(hlua, 1);
8633
8634 switch (status) {
8635 /* finished or yield */
8636 case HLUA_E_OK:
8637 hlua_ctx_destroy(hlua);
Olivier Houchard3f795f72019-04-17 22:51:06 +02008638 task_destroy(task);
Tim Duesterhuscd235c62018-04-24 13:56:01 +02008639 task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008640 break;
8641
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01008642 case HLUA_E_AGAIN: /* co process or timeout wake me later. */
Thierry FOURNIERcb146882017-12-10 17:10:57 +01008643 notification_gc(&hlua->com);
PiBa-NLfe971b32018-05-02 22:27:14 +02008644 task->expire = hlua->wake_time;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008645 break;
8646
8647 /* finished with error. */
Aurelien DARRAGON79544102022-11-24 14:27:15 +01008648 case HLUA_E_ETMOUT:
8649 SEND_ERR(NULL, "Lua task: execution timeout.\n");
8650 goto err_task_abort;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008651 case HLUA_E_ERRMSG:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008652 SEND_ERR(NULL, "Lua task: %s.\n", lua_tostring(hlua->T, -1));
Aurelien DARRAGON79544102022-11-24 14:27:15 +01008653 goto err_task_abort;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008654 case HLUA_E_ERR:
8655 default:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008656 SEND_ERR(NULL, "Lua task: unknown error.\n");
Aurelien DARRAGON79544102022-11-24 14:27:15 +01008657 err_task_abort:
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008658 hlua_ctx_destroy(hlua);
Olivier Houchard3f795f72019-04-17 22:51:06 +02008659 task_destroy(task);
Emeric Brun253e53e2017-10-17 18:58:40 +02008660 task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008661 break;
8662 }
Emeric Brun253e53e2017-10-17 18:58:40 +02008663 return task;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008664}
8665
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008666/* This function is an LUA binding that register LUA function to be
8667 * executed after the HAProxy configuration parsing and before the
8668 * HAProxy scheduler starts. This function expect only one LUA
8669 * argument that is a function. This function returns nothing, but
8670 * throws if an error is encountered.
8671 */
8672__LJMP static int hlua_register_init(lua_State *L)
8673{
8674 struct hlua_init_function *init;
8675 int ref;
8676
8677 MAY_LJMP(check_args(L, 1, "register_init"));
8678
Aurelien DARRAGON87f52972023-02-24 09:43:54 +01008679 if (hlua_gethlua(L)) {
8680 /* runtime processing */
8681 WILL_LJMP(luaL_error(L, "register_init: not available outside of body context"));
8682 }
8683
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008684 ref = MAY_LJMP(hlua_checkfunction(L, 1));
8685
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02008686 init = calloc(1, sizeof(*init));
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +01008687 if (!init) {
8688 hlua_unref(L, ref);
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01008689 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +01008690 }
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008691
8692 init->function_ref = ref;
Willy Tarreau2b718102021-04-21 07:32:39 +02008693 LIST_APPEND(&hlua_init_functions[hlua_state_id], &init->l);
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008694 return 0;
8695}
8696
Ilya Shipitsin6f86eaa2022-11-30 16:22:42 +05008697/* This function is an LUA binding. It permits to register a task
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008698 * executed in parallel of the main HAroxy activity. The task is
8699 * created and it is set in the HAProxy scheduler. It can be called
8700 * from the "init" section, "post init" or during the runtime.
8701 *
8702 * Lua prototype:
8703 *
Aurelien DARRAGONb8038992023-03-09 16:48:30 +01008704 * <none> core.register_task(<function>[, <arg1>[, <arg2>[, ...[, <arg4>]]]])
8705 *
8706 * <arg1..4> are optional arguments that will be provided to <function>
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008707 */
8708static int hlua_register_task(lua_State *L)
8709{
Christopher Faulet5294ec02021-04-12 12:24:47 +02008710 struct hlua *hlua = NULL;
8711 struct task *task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008712 int ref;
Aurelien DARRAGONb8038992023-03-09 16:48:30 +01008713 int nb_arg;
8714 int it;
8715 int arg_ref[4]; /* optional arguments */
Thierry Fournier021d9862020-11-28 23:42:03 +01008716 int state_id;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008717
Aurelien DARRAGONb8038992023-03-09 16:48:30 +01008718 nb_arg = lua_gettop(L);
8719 if (nb_arg < 1)
8720 WILL_LJMP(luaL_error(L, "register_task: <func> argument is required"));
8721 else if (nb_arg > 5)
8722 WILL_LJMP(luaL_error(L, "register_task: no more that 4 optional arguments may be provided"));
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008723
Aurelien DARRAGONb8038992023-03-09 16:48:30 +01008724 /* first arg: function ref */
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008725 ref = MAY_LJMP(hlua_checkfunction(L, 1));
8726
Aurelien DARRAGONb8038992023-03-09 16:48:30 +01008727 /* extract optional args (if any) */
8728 it = 0;
8729 while (--nb_arg) {
8730 lua_pushvalue(L, 2 + it);
8731 arg_ref[it] = hlua_ref(L); /* get arg reference */
8732 it += 1;
8733 }
8734 nb_arg = it;
8735
Thierry Fournier75fc0292020-11-28 13:18:56 +01008736 /* Get the reference state. If the reference is NULL, L is the master
8737 * state, otherwise hlua->T is.
8738 */
8739 hlua = hlua_gethlua(L);
8740 if (hlua)
Thierry Fournier021d9862020-11-28 23:42:03 +01008741 /* we are in runtime processing */
8742 state_id = hlua->state_id;
Thierry Fournier75fc0292020-11-28 13:18:56 +01008743 else
Thierry Fournier021d9862020-11-28 23:42:03 +01008744 /* we are in initialization mode */
Thierry Fournierc7492592020-11-28 23:57:24 +01008745 state_id = hlua_state_id;
Thierry Fournier75fc0292020-11-28 13:18:56 +01008746
Willy Tarreaubafbe012017-11-24 17:34:44 +01008747 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008748 if (!hlua)
Christopher Faulet5294ec02021-04-12 12:24:47 +02008749 goto alloc_error;
Christopher Faulet1e8433f2021-03-24 15:03:01 +01008750 HLUA_INIT(hlua);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008751
Thierry Fournier59f11be2020-11-29 00:37:41 +01008752 /* We are in the common lua state, execute the task anywhere,
8753 * otherwise, inherit the current thread identifier
8754 */
8755 if (state_id == 0)
Willy Tarreaubeeabf52021-10-01 18:23:30 +02008756 task = task_new_anywhere();
Thierry Fournier59f11be2020-11-29 00:37:41 +01008757 else
Willy Tarreaubeeabf52021-10-01 18:23:30 +02008758 task = task_new_here();
Willy Tarreaue09101e2018-10-16 17:37:12 +02008759 if (!task)
Christopher Faulet5294ec02021-04-12 12:24:47 +02008760 goto alloc_error;
Willy Tarreaue09101e2018-10-16 17:37:12 +02008761
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008762 task->context = hlua;
8763 task->process = hlua_process_task;
8764
Aurelien DARRAGON6b0b9bd2023-03-21 14:02:16 +01008765 if (!hlua_ctx_init(hlua, state_id, task))
Christopher Faulet5294ec02021-04-12 12:24:47 +02008766 goto alloc_error;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008767
Aurelien DARRAGONb8038992023-03-09 16:48:30 +01008768 /* Ensure there is enough space on the stack for the function
8769 * plus optional arguments
8770 */
8771 if (!lua_checkstack(hlua->T, (1 + nb_arg)))
8772 goto alloc_error;
8773
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008774 /* Restore the function in the stack. */
Aurelien DARRAGON4fdf8b52023-03-20 17:22:37 +01008775 hlua_pushref(hlua->T, ref);
Aurelien DARRAGONbe58d662023-03-13 14:09:21 +01008776 /* function ref not needed anymore since it was pushed to the substack */
8777 hlua_unref(L, ref);
8778
Aurelien DARRAGONb8038992023-03-09 16:48:30 +01008779 hlua->nargs = nb_arg;
8780
8781 /* push optional arguments to the function */
8782 for (it = 0; it < nb_arg; it++) {
8783 /* push arg to the stack */
8784 hlua_pushref(hlua->T, arg_ref[it]);
8785 /* arg ref not needed anymore since it was pushed to the substack */
8786 hlua_unref(L, arg_ref[it]);
8787 }
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008788
8789 /* Schedule task. */
Willy Tarreaue3957f82021-09-30 16:17:37 +02008790 task_wakeup(task, TASK_WOKEN_INIT);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008791
8792 return 0;
Christopher Faulet5294ec02021-04-12 12:24:47 +02008793
8794 alloc_error:
8795 task_destroy(task);
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +01008796 hlua_unref(L, ref);
Aurelien DARRAGONb8038992023-03-09 16:48:30 +01008797 for (it = 0; it < nb_arg; it++) {
8798 hlua_unref(L, arg_ref[it]);
8799 }
Christopher Faulet5294ec02021-04-12 12:24:47 +02008800 hlua_ctx_destroy(hlua);
8801 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
8802 return 0; /* Never reached */
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008803}
8804
Aurelien DARRAGONc84899c2023-02-20 18:18:59 +01008805/* called from unsafe location */
8806static void hlua_event_subscription_destroy(struct hlua_event_sub *hlua_sub)
8807{
8808 /* hlua cleanup */
8809
8810 hlua_lock(hlua_sub->hlua);
8811 /* registry is shared between coroutines */
8812 hlua_unref(hlua_sub->hlua->T, hlua_sub->fcn_ref);
8813 hlua_unlock(hlua_sub->hlua);
8814
8815 hlua_ctx_destroy(hlua_sub->hlua);
8816
8817 /* free */
8818 pool_free(pool_head_hlua_event_sub, hlua_sub);
8819}
8820
8821/* single event handler: hlua ctx is shared between multiple events handlers
8822 * issued from the same subscription. Thus, it is not destroyed when the event
8823 * is processed: it is destroyed when no more events are expected for the
8824 * subscription (ie: when the subscription ends).
8825 *
8826 * Moreover, events are processed sequentially within the subscription:
8827 * one event must be fully processed before another one may be processed.
8828 * This ensures proper consistency for lua event handling from an ordering
8829 * point of view. This is especially useful with server events for example
8830 * where ADD/DEL/UP/DOWN events ordering really matters to trigger specific
8831 * actions from lua (e.g.: sending emails or making API calls).
8832 *
8833 * Due to this design, each lua event handler is pleased to process the event
8834 * as fast as possible to prevent the event queue from growing up.
8835 * Strictly speaking, there is no runtime limit for the callback function
8836 * (timeout set to default task timeout), but if the event queue goes past
8837 * the limit of unconsumed events an error will be reported and the
8838 * susbscription will pause itself for as long as it takes for the handler to
8839 * catch up (events will be lost as a result).
8840 * If the event handler does not need the sequential ordering and wants to
8841 * process multiple events at a time, it may spawn a new side-task using
8842 * 'core.register_task' to delegate the event handling and make parallel event
8843 * processing within the same subscription set.
8844 */
8845static void hlua_event_handler(struct hlua *hlua)
8846{
8847 enum hlua_exec status;
8848
8849 /* If it is the first call to the task, we must initialize the
8850 * execution timeouts.
8851 */
8852 if (!HLUA_IS_RUNNING(hlua)) {
8853 hlua->max_time = hlua_timeout_task;
8854 }
8855
8856 /* make sure to reset the task expiry before each hlua_ctx_resume()
8857 * since the task is re-used for multiple cb function calls
8858 * We couldn't risk to have t->expire pointing to a past date because
8859 * it was set during last function invocation but was never reset since
8860 * (ie: E_AGAIN)
8861 */
8862 hlua->task->expire = TICK_ETERNITY;
8863
8864 /* Execute the Lua code. */
8865 status = hlua_ctx_resume(hlua, 1);
8866
8867 switch (status) {
8868 /* finished or yield */
8869 case HLUA_E_OK:
8870 break;
8871
8872 case HLUA_E_AGAIN: /* co process or timeout wake me later. */
8873 notification_gc(&hlua->com);
8874 hlua->task->expire = hlua->wake_time;
8875 break;
8876
8877 /* finished with error. */
8878 case HLUA_E_ETMOUT:
8879 SEND_ERR(NULL, "Lua event_hdl: execution timeout.\n");
8880 break;
8881
8882 case HLUA_E_ERRMSG:
8883 SEND_ERR(NULL, "Lua event_hdl: %s.\n", lua_tostring(hlua->T, -1));
8884 break;
8885
8886 case HLUA_E_ERR:
8887 default:
8888 SEND_ERR(NULL, "Lua event_hdl: unknown error.\n");
8889 break;
8890 }
8891}
8892
8893__LJMP static int hlua_event_hdl_cb_data_push_args(struct hlua_event_sub *hlua_sub,
8894 struct event_hdl_sub_type event, void *data)
8895{
8896 struct hlua *hlua = hlua_sub->hlua;
8897
8898 hlua->nargs = 1;
8899 lua_pushstring(hlua->T, event_hdl_sub_type_to_string(event));
8900 if (event_hdl_sub_family_equal(EVENT_HDL_SUB_SERVER, event)) {
8901 struct event_hdl_cb_data_server *e_server = data;
8902 struct proxy *px;
8903 struct server *server;
8904
8905 hlua->nargs += 1;
8906 lua_newtable(hlua->T);
8907 /* Add server name */
8908 lua_pushstring(hlua->T, "name");
8909 lua_pushstring(hlua->T, e_server->safe.name);
8910 lua_settable(hlua->T, -3);
8911 /* Add server puid */
8912 lua_pushstring(hlua->T, "puid");
8913 lua_pushinteger(hlua->T, e_server->safe.puid);
8914 lua_settable(hlua->T, -3);
8915 /* Add server rid */
8916 lua_pushstring(hlua->T, "rid");
8917 lua_pushinteger(hlua->T, e_server->safe.rid);
8918 lua_settable(hlua->T, -3);
8919 /* Add server proxy name */
8920 lua_pushstring(hlua->T, "proxy_name");
8921 lua_pushstring(hlua->T, e_server->safe.proxy_name);
8922 lua_settable(hlua->T, -3);
8923
8924 /* attempt to provide reference server object
8925 * (if it wasn't removed yet, SERVER_DEL will never succeed here)
8926 */
8927 px = proxy_find_by_name(e_server->safe.proxy_name, PR_CAP_BE, 0);
8928 BUG_ON(!px);
8929 server = findserver_unique_id(px, e_server->safe.puid, e_server->safe.rid);
8930 if (server) {
8931 lua_pushstring(hlua->T, "reference");
8932 hlua_fcn_new_server(hlua->T, server);
8933 lua_settable(hlua->T, -3);
8934 }
8935 }
8936 /* sub mgmt */
8937 hlua->nargs += 1;
8938 hlua_fcn_new_event_sub(hlua->T, hlua_sub->sub);
8939
8940 return 1;
8941}
8942
8943/* events runner: if there's an ongoing hlua event handling process, finish it
8944 * then, check if there are new events waiting to be processed
8945 * (events are processed sequentially)
8946 *
8947 * We have a safety measure to warn/guard if the event queue is growing up
8948 * too much due to many events being generated and lua handler is unable to
8949 * keep up the pace (e.g.: when the event queue grows past 100 unconsumed events).
8950 * TODO: make it tunable
8951 */
8952static struct task *hlua_event_runner(struct task *task, void *context, unsigned int state)
8953{
8954 struct hlua_event_sub *hlua_sub = context;
8955 struct event_hdl_async_event *event;
8956 const char *error = NULL;
8957
8958 if (!hlua_sub->paused && event_hdl_async_equeue_size(&hlua_sub->equeue) > 100) {
8959 const char *trace;
8960
8961 /* We reached the limit of pending events in the queue: we should
8962 * warn the user, and temporarily pause the subscription to give a chance
8963 * to the handler to catch up? (it also prevents ressource shortage since
8964 * the queue could grow indefinitely otherwise)
8965 * TODO: find a way to inform the handler that it missed some events
8966 * (example: stats within the subscription in event_hdl api exposed via lua api?)
8967 *
8968 * Nonetheless, reaching this limit means that the handler is not fast enough
8969 * and/or that it subscribed to events that happen too frequently and did not
8970 * expect it. This could come from an inadequate design in the user's script.
8971 */
8972 event_hdl_pause(hlua_sub->sub);
8973 hlua_sub->paused = 1;
8974
8975 /* The following Lua calls can fail. */
8976 if (!SET_SAFE_LJMP(hlua_sub->hlua))
8977 trace = NULL;
8978 trace = hlua_traceback(hlua_sub->hlua->T, ", ");
8979 /* At this point the execution is safe. */
8980 RESET_SAFE_LJMP(hlua_sub->hlua);
8981
8982 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 : ""));
8983 }
8984
8985 if (HLUA_IS_RUNNING(hlua_sub->hlua)) {
8986 /* ongoing hlua event handler, resume it */
8987 hlua_event_handler(hlua_sub->hlua);
8988 } else if ((event = event_hdl_async_equeue_pop(&hlua_sub->equeue))) { /* check for new events */
8989 if (event_hdl_sub_type_equal(event->type, EVENT_HDL_SUB_END)) {
8990 /* ending event: no more events to come */
8991 event_hdl_async_free_event(event);
8992 task_destroy(task);
8993 hlua_event_subscription_destroy(hlua_sub);
8994 return NULL;
8995 }
8996 /* new event: start processing it */
8997
8998 /* The following Lua calls can fail. */
8999 if (!SET_SAFE_LJMP(hlua_sub->hlua)) {
9000 if (lua_type(hlua_sub->hlua->T, -1) == LUA_TSTRING)
9001 error = lua_tostring(hlua_sub->hlua->T, -1);
9002 else
9003 error = "critical error";
9004 ha_alert("Lua event_hdl: %s.\n", error);
9005 goto skip_event;
9006 }
9007
9008 /* Check stack available size. */
9009 if (!lua_checkstack(hlua_sub->hlua->T, 5)) {
9010 ha_alert("Lua event_hdl: full stack.\n");
9011 RESET_SAFE_LJMP(hlua_sub->hlua);
9012 goto skip_event;
9013 }
9014
9015 /* Restore the function in the stack. */
9016 hlua_pushref(hlua_sub->hlua->T, hlua_sub->fcn_ref);
9017
9018 /* push args */
9019 hlua_sub->hlua->nargs = 0;
9020 if (!hlua_event_hdl_cb_data_push_args(hlua_sub, event->type, event->data)) {
9021 RESET_SAFE_LJMP(hlua_sub->hlua);
9022 goto skip_event;
9023 }
9024
9025 /* At this point the execution is safe. */
9026 RESET_SAFE_LJMP(hlua_sub->hlua);
9027
9028 /* At this point the event was successfully translated into hlua ctx,
9029 * or hlua error occured, so we can safely discard it
9030 */
9031 event_hdl_async_free_event(event);
9032 event = NULL;
9033
9034 hlua_event_handler(hlua_sub->hlua);
9035 skip_event:
9036 if (event)
9037 event_hdl_async_free_event(event);
9038
9039 }
9040
9041 if (!HLUA_IS_RUNNING(hlua_sub->hlua)) {
9042 /* we just finished the processing of one event..
9043 * check for new events before becoming idle
9044 */
9045 if (!event_hdl_async_equeue_isempty(&hlua_sub->equeue)) {
9046 /* more events to process, make sure the task
9047 * will be resumed ASAP to process pending events
9048 */
9049 task_wakeup(task, TASK_WOKEN_OTHER);
9050 }
9051 else if (hlua_sub->paused) {
9052 /* empty queue, the handler catched up: resume the subscription */
9053 event_hdl_resume(hlua_sub->sub);
9054 hlua_sub->paused = 0;
9055 }
9056 }
9057
9058 return task;
9059}
9060
9061/* Must be called directly under lua protected/safe environment
9062 * (not from external callback)
9063 * <fcn_ref> should NOT be dropped after the function successfully returns:
9064 * it will be done automatically in hlua_event_subscription_destroy() when the
9065 * subscription ends.
9066 *
9067 * Returns the new subscription on success and NULL on failure (memory error)
9068 */
9069static struct event_hdl_sub *hlua_event_subscribe(event_hdl_sub_list *list, struct event_hdl_sub_type e_type,
9070 int state_id, int fcn_ref)
9071{
9072 struct hlua_event_sub *hlua_sub;
9073 struct task *task = NULL;
9074
9075 hlua_sub = pool_alloc(pool_head_hlua_event_sub);
9076 if (!hlua_sub)
9077 goto mem_error;
9078 hlua_sub->task = NULL;
9079 hlua_sub->hlua = NULL;
9080 hlua_sub->paused = 0;
9081 if ((task = task_new_here()) == NULL) {
9082 ha_alert("out of memory while allocating hlua event task");
9083 goto mem_error;
9084 }
9085 task->process = hlua_event_runner;
9086 task->context = hlua_sub;
9087 event_hdl_async_equeue_init(&hlua_sub->equeue);
9088 hlua_sub->task = task;
9089 hlua_sub->fcn_ref = fcn_ref;
9090 hlua_sub->state_id = state_id;
9091 hlua_sub->hlua = pool_alloc(pool_head_hlua);
9092 if (!hlua_sub->hlua)
9093 goto mem_error;
9094 HLUA_INIT(hlua_sub->hlua);
9095 if (!hlua_ctx_init(hlua_sub->hlua, hlua_sub->state_id, task))
9096 goto mem_error;
9097
9098 hlua_sub->sub = event_hdl_subscribe_ptr(list, e_type,
9099 EVENT_HDL_ASYNC_TASK(&hlua_sub->equeue,
9100 task,
9101 hlua_sub,
9102 NULL));
9103 if (!hlua_sub->sub)
9104 goto mem_error;
9105
9106 return hlua_sub->sub; /* returns pointer to event_hdl_sub struct */
9107
9108 mem_error:
9109 if (hlua_sub) {
9110 if (hlua_sub->task)
9111 task_destroy(hlua_sub->task);
9112 if (hlua_sub->hlua)
9113 hlua_ctx_destroy(hlua_sub->hlua);
9114 pool_free(pool_head_hlua_event_sub, hlua_sub);
9115 }
9116
9117 return NULL;
9118}
9119
9120/* looks for an array of strings referring to a composition of event_hdl subscription
9121 * types at <index> in <L> stack
9122 */
9123__LJMP static struct event_hdl_sub_type hlua_check_event_sub_types(lua_State *L, int index)
9124{
9125 struct event_hdl_sub_type subscriptions;
9126 const char *msg;
9127
9128 if (lua_type(L, index) != LUA_TTABLE) {
9129 msg = lua_pushfstring(L, "table of strings expected, got %s", luaL_typename(L, index));
9130 luaL_argerror(L, index, msg);
9131 }
9132
9133 subscriptions = EVENT_HDL_SUB_NONE;
9134
9135 /* browse the argument as an array. */
9136 lua_pushnil(L);
9137 while (lua_next(L, index) != 0) {
9138 if (lua_type(L, -1) != LUA_TSTRING) {
9139 msg = lua_pushfstring(L, "table of strings expected, got %s", luaL_typename(L, index));
9140 luaL_argerror(L, index, msg);
9141 }
9142
9143 if (event_hdl_sub_type_equal(EVENT_HDL_SUB_NONE, event_hdl_string_to_sub_type(lua_tostring(L, -1)))) {
9144 msg = lua_pushfstring(L, "'%s' event type is unknown", lua_tostring(L, -1));
9145 luaL_argerror(L, index, msg);
9146 }
9147
9148 /* perform subscriptions |= current sub */
9149 subscriptions = event_hdl_sub_type_add(subscriptions, event_hdl_string_to_sub_type(lua_tostring(L, -1)));
9150
9151 /* pop the current value. */
9152 lua_pop(L, 1);
9153 }
9154
9155 return subscriptions;
9156}
9157
9158/* Wrapper for hlua_fcn_new_event_sub(): catch errors raised by
9159 * the function to prevent LJMP
9160 *
9161 * If no error occured, the function returns 1, else it returns 0 and
9162 * the error message is pushed at the top of the stack
9163 */
9164__LJMP static int _hlua_new_event_sub_safe(lua_State *L)
9165{
9166 struct event_hdl_sub *sub = lua_touserdata(L, 1);
9167
9168 /* this function may raise errors */
9169 return MAY_LJMP(hlua_fcn_new_event_sub(L, sub));
9170}
9171static int hlua_new_event_sub_safe(lua_State *L, struct event_hdl_sub *sub)
9172{
9173 if (!lua_checkstack(L, 2))
9174 return 0;
9175 lua_pushcfunction(L, _hlua_new_event_sub_safe);
9176 lua_pushlightuserdata(L, sub);
9177 switch (lua_pcall(L, 1, 1, 0)) {
9178 case LUA_OK:
9179 return 1;
9180 default:
9181 /* error was catched */
9182 return 0;
9183 }
9184}
9185
9186/* This function is a LUA helper used for registering lua event callbacks.
9187 * It expects an event subscription array and the function to be executed
9188 * when subscribed events occur (stack arguments).
9189 * It can be called from the "init" section, "post init" or during the runtime.
9190 *
9191 * <sub_list> is the subscription list where the subscription will be attempted
9192 *
9193 * Pushes the newly allocated subscription on the stack on success
9194 */
9195__LJMP int hlua_event_sub(lua_State *L, event_hdl_sub_list *sub_list)
9196{
9197 struct hlua *hlua;
9198 struct event_hdl_sub *sub;
9199 struct event_hdl_sub_type subscriptions;
9200 int fcn_ref;
9201 int state_id;
9202
9203 MAY_LJMP(check_args(L, 2, "event_sub"));
9204
9205 /* Get the reference state */
9206 hlua = hlua_gethlua(L);
9207 if (hlua)
9208 /* we are in runtime processing, any thread may subscribe to events:
9209 * subscription events will be handled by the thread who performed
9210 * the registration.
9211 */
9212 state_id = hlua->state_id;
9213 else {
9214 /* we are in initialization mode, only thread 0 (actual calling thread)
9215 * may subscribe to events to prevent the same handler (from different lua
9216 * stacks) from being registered multiple times
9217 *
9218 * hlua_state_id == 0: monostack (lua-load)
9219 * hlua_state_id > 0: hlua_state_id=tid+1, multi-stack (lua-load-per-thread)
9220 * (thus if hlua_state_id > 1, it means we are not in primary thread ctx)
9221 */
9222 if (hlua_state_id > 1)
9223 return 0; /* skip registration */
9224 state_id = hlua_state_id;
9225 }
9226
9227 /* First argument : event subscriptions. */
9228 subscriptions = MAY_LJMP(hlua_check_event_sub_types(L, 1));
9229
9230 if (event_hdl_sub_type_equal(subscriptions, EVENT_HDL_SUB_NONE)) {
9231 WILL_LJMP(luaL_error(L, "event_sub: no valid event types were provided"));
9232 return 0; /* Never reached */
9233 }
9234
9235 /* Second argument : lua function. */
9236 fcn_ref = MAY_LJMP(hlua_checkfunction(L, 2));
9237
9238 /* try to subscribe */
9239 sub = hlua_event_subscribe(sub_list, subscriptions, state_id, fcn_ref);
9240 if (!sub) {
9241 hlua_unref(L, fcn_ref);
9242 WILL_LJMP(luaL_error(L, "event_sub: lua out of memory error"));
9243 return 0; /* Never reached */
9244 }
9245
9246 /* push the subscription to the stack
9247 *
9248 * Here we use the safe function so that lua errors will be
9249 * handled explicitly to prevent 'sub' from being lost
9250 */
9251 if (!hlua_new_event_sub_safe(L, sub)) {
9252 /* Some events could already be pending in the handler's queue.
9253 * However it is wiser to cancel the subscription since we are unable to
9254 * provide a valid reference to it.
9255 * Pending events will be delivered (unless lua keeps raising errors).
9256 */
9257 event_hdl_unsubscribe(sub); /* cancel the subscription */
9258 WILL_LJMP(luaL_error(L, "event_sub: cannot push the subscription (%s)", lua_tostring(L, -1)));
9259 return 0; /* Never reached */
9260 }
9261 event_hdl_drop(sub); /* sub has been duplicated, discard old ref */
9262
9263 return 1;
9264}
9265
9266/* This function is a LUA wrapper used for registering global lua event callbacks
9267 * The new subscription is pushed onto the stack on success
9268 * Returns the number of arguments pushed to the stack (1 for success)
9269 */
9270__LJMP static int hlua_event_global_sub(lua_State *L)
9271{
9272 /* NULL <sub_list> = global subscription list */
9273 return MAY_LJMP(hlua_event_sub(L, NULL));
9274}
9275
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009276/* Wrapper called by HAProxy to execute an LUA converter. This wrapper
9277 * doesn't allow "yield" functions because the HAProxy engine cannot
9278 * resume converters.
9279 */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02009280static int hlua_sample_conv_wrapper(const struct arg *arg_p, struct sample *smp, void *private)
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009281{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02009282 struct hlua_function *fcn = private;
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02009283 struct stream *stream = smp->strm;
Thierry Fournierfd107a22016-02-19 19:57:23 +01009284 const char *error;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009285
Willy Tarreaube508f12016-03-10 11:47:01 +01009286 if (!stream)
9287 return 0;
9288
Willy Tarreau87b09662015-04-03 00:22:06 +02009289 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01009290 * Lua context can be not initialized. This behavior
9291 * permits to save performances because a systematic
9292 * Lua initialization cause 5% performances loss.
9293 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009294 if (!stream->hlua) {
Christopher Faulet1e8433f2021-03-24 15:03:01 +01009295 struct hlua *hlua;
9296
9297 hlua = pool_alloc(pool_head_hlua);
9298 if (!hlua) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009299 SEND_ERR(stream->be, "Lua converter '%s': can't initialize Lua context.\n", fcn->name);
9300 return 0;
9301 }
Christopher Faulet1e8433f2021-03-24 15:03:01 +01009302 HLUA_INIT(hlua);
9303 stream->hlua = hlua;
Aurelien DARRAGON6b0b9bd2023-03-21 14:02:16 +01009304 if (!hlua_ctx_init(stream->hlua, fcn_ref_to_stack_id(fcn), stream->task)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009305 SEND_ERR(stream->be, "Lua converter '%s': can't initialize Lua context.\n", fcn->name);
9306 return 0;
9307 }
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01009308 }
9309
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009310 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009311 if (!HLUA_IS_RUNNING(stream->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02009312
9313 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009314 if (!SET_SAFE_LJMP(stream->hlua)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009315 if (lua_type(stream->hlua->T, -1) == LUA_TSTRING)
9316 error = lua_tostring(stream->hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +01009317 else
9318 error = "critical error";
9319 SEND_ERR(stream->be, "Lua converter '%s': %s.\n", fcn->name, error);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02009320 return 0;
9321 }
9322
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009323 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009324 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009325 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009326 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009327 return 0;
9328 }
9329
9330 /* Restore the function in the stack. */
Aurelien DARRAGON4fdf8b52023-03-20 17:22:37 +01009331 hlua_pushref(stream->hlua->T, fcn->function_ref[stream->hlua->state_id]);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009332
9333 /* convert input sample and pust-it in the stack. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009334 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009335 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009336 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009337 return 0;
9338 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009339 hlua_smp2lua(stream->hlua->T, smp);
9340 stream->hlua->nargs = 1;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009341
9342 /* push keywords in the stack. */
9343 if (arg_p) {
9344 for (; arg_p->type != ARGT_STOP; arg_p++) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009345 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009346 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009347 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009348 return 0;
9349 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009350 hlua_arg2lua(stream->hlua->T, arg_p);
9351 stream->hlua->nargs++;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009352 }
9353 }
9354
Thierry FOURNIERbd413492015-03-03 16:52:26 +01009355 /* We must initialize the execution timeouts. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009356 stream->hlua->max_time = hlua_timeout_session;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01009357
Thierry FOURNIERbabae282015-09-17 11:36:37 +02009358 /* At this point the execution is safe. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009359 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009360 }
9361
9362 /* Execute the function. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009363 switch (hlua_ctx_resume(stream->hlua, 0)) {
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009364 /* finished. */
9365 case HLUA_E_OK:
Thierry FOURNIERfd80df12017-05-12 16:32:20 +02009366 /* If the stack is empty, the function fails. */
9367 if (lua_gettop(stream->hlua->T) <= 0)
9368 return 0;
9369
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009370 /* Convert the returned value in sample. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009371 hlua_lua2smp(stream->hlua->T, -1, smp);
9372 lua_pop(stream->hlua->T, 1);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009373 return 1;
9374
9375 /* yield. */
9376 case HLUA_E_AGAIN:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009377 SEND_ERR(stream->be, "Lua converter '%s': cannot use yielded functions.\n", fcn->name);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009378 return 0;
9379
9380 /* finished with error. */
9381 case HLUA_E_ERRMSG:
9382 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009383 SEND_ERR(stream->be, "Lua converter '%s': %s.\n",
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009384 fcn->name, lua_tostring(stream->hlua->T, -1));
9385 lua_pop(stream->hlua->T, 1);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009386 return 0;
9387
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009388 case HLUA_E_ETMOUT:
9389 SEND_ERR(stream->be, "Lua converter '%s': execution timeout.\n", fcn->name);
9390 return 0;
9391
9392 case HLUA_E_NOMEM:
9393 SEND_ERR(stream->be, "Lua converter '%s': out of memory error.\n", fcn->name);
9394 return 0;
9395
9396 case HLUA_E_YIELD:
9397 SEND_ERR(stream->be, "Lua converter '%s': yield functions like core.tcp() or core.sleep() are not allowed.\n", fcn->name);
9398 return 0;
9399
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009400 case HLUA_E_ERR:
9401 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009402 SEND_ERR(stream->be, "Lua converter '%s' returns an unknown error.\n", fcn->name);
Willy Tarreau14de3952022-11-14 07:08:28 +01009403 __fallthrough;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009404
9405 default:
9406 return 0;
9407 }
9408}
9409
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009410/* Wrapper called by HAProxy to execute a sample-fetch. this wrapper
9411 * doesn't allow "yield" functions because the HAProxy engine cannot
Willy Tarreaube508f12016-03-10 11:47:01 +01009412 * resume sample-fetches. This function will be called by the sample
9413 * fetch engine to call lua-based fetch operations.
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009414 */
Thierry FOURNIER0786d052015-05-11 15:42:45 +02009415static int hlua_sample_fetch_wrapper(const struct arg *arg_p, struct sample *smp,
9416 const char *kw, void *private)
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009417{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02009418 struct hlua_function *fcn = private;
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02009419 struct stream *stream = smp->strm;
Thierry Fournierfd107a22016-02-19 19:57:23 +01009420 const char *error;
Christopher Faulet8c9e6bb2021-08-06 16:29:41 +02009421 unsigned int hflags = HLUA_TXN_NOTERM | HLUA_TXN_SMP_CTX;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009422
Willy Tarreaube508f12016-03-10 11:47:01 +01009423 if (!stream)
9424 return 0;
Christopher Fauletafd8f102018-11-08 11:34:21 +01009425
Willy Tarreau87b09662015-04-03 00:22:06 +02009426 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01009427 * Lua context can be not initialized. This behavior
9428 * permits to save performances because a systematic
9429 * Lua initialization cause 5% performances loss.
9430 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009431 if (!stream->hlua) {
Christopher Faulet1e8433f2021-03-24 15:03:01 +01009432 struct hlua *hlua;
9433
9434 hlua = pool_alloc(pool_head_hlua);
9435 if (!hlua) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009436 SEND_ERR(stream->be, "Lua sample-fetch '%s': can't initialize Lua context.\n", fcn->name);
9437 return 0;
9438 }
Christopher Faulet1e8433f2021-03-24 15:03:01 +01009439 hlua->T = NULL;
9440 stream->hlua = hlua;
Aurelien DARRAGON6b0b9bd2023-03-21 14:02:16 +01009441 if (!hlua_ctx_init(stream->hlua, fcn_ref_to_stack_id(fcn), stream->task)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009442 SEND_ERR(stream->be, "Lua sample-fetch '%s': can't initialize Lua context.\n", fcn->name);
9443 return 0;
9444 }
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01009445 }
9446
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009447 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009448 if (!HLUA_IS_RUNNING(stream->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02009449
9450 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009451 if (!SET_SAFE_LJMP(stream->hlua)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009452 if (lua_type(stream->hlua->T, -1) == LUA_TSTRING)
9453 error = lua_tostring(stream->hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +01009454 else
9455 error = "critical error";
9456 SEND_ERR(smp->px, "Lua sample-fetch '%s': %s.\n", fcn->name, error);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02009457 return 0;
9458 }
9459
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009460 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009461 if (!lua_checkstack(stream->hlua->T, 2)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009462 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009463 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009464 return 0;
9465 }
9466
9467 /* Restore the function in the stack. */
Aurelien DARRAGON4fdf8b52023-03-20 17:22:37 +01009468 hlua_pushref(stream->hlua->T, fcn->function_ref[stream->hlua->state_id]);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009469
9470 /* push arguments in the stack. */
Christopher Fauletbfab2dd2019-07-26 15:09:53 +02009471 if (!hlua_txn_new(stream->hlua->T, stream, smp->px, smp->opt & SMP_OPT_DIR, hflags)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009472 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009473 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009474 return 0;
9475 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009476 stream->hlua->nargs = 1;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009477
9478 /* push keywords in the stack. */
9479 for (; arg_p && arg_p->type != ARGT_STOP; arg_p++) {
9480 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009481 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009482 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009483 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009484 return 0;
9485 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009486 hlua_arg2lua(stream->hlua->T, arg_p);
9487 stream->hlua->nargs++;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009488 }
9489
Thierry FOURNIERbd413492015-03-03 16:52:26 +01009490 /* We must initialize the execution timeouts. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009491 stream->hlua->max_time = hlua_timeout_session;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01009492
Thierry FOURNIERbabae282015-09-17 11:36:37 +02009493 /* At this point the execution is safe. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009494 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009495 }
9496
9497 /* Execute the function. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009498 switch (hlua_ctx_resume(stream->hlua, 0)) {
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009499 /* finished. */
9500 case HLUA_E_OK:
Thierry FOURNIERfd80df12017-05-12 16:32:20 +02009501 /* If the stack is empty, the function fails. */
9502 if (lua_gettop(stream->hlua->T) <= 0)
9503 return 0;
9504
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009505 /* Convert the returned value in sample. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009506 hlua_lua2smp(stream->hlua->T, -1, smp);
9507 lua_pop(stream->hlua->T, 1);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009508
9509 /* Set the end of execution flag. */
9510 smp->flags &= ~SMP_F_MAY_CHANGE;
9511 return 1;
9512
9513 /* yield. */
9514 case HLUA_E_AGAIN:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009515 SEND_ERR(smp->px, "Lua sample-fetch '%s': cannot use yielded functions.\n", fcn->name);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009516 return 0;
9517
9518 /* finished with error. */
9519 case HLUA_E_ERRMSG:
9520 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009521 SEND_ERR(smp->px, "Lua sample-fetch '%s': %s.\n",
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009522 fcn->name, lua_tostring(stream->hlua->T, -1));
9523 lua_pop(stream->hlua->T, 1);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009524 return 0;
9525
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009526 case HLUA_E_ETMOUT:
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009527 SEND_ERR(smp->px, "Lua sample-fetch '%s': execution timeout.\n", fcn->name);
9528 return 0;
9529
9530 case HLUA_E_NOMEM:
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009531 SEND_ERR(smp->px, "Lua sample-fetch '%s': out of memory error.\n", fcn->name);
9532 return 0;
9533
9534 case HLUA_E_YIELD:
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009535 SEND_ERR(smp->px, "Lua sample-fetch '%s': yield not allowed.\n", fcn->name);
9536 return 0;
9537
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009538 case HLUA_E_ERR:
9539 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009540 SEND_ERR(smp->px, "Lua sample-fetch '%s' returns an unknown error.\n", fcn->name);
Willy Tarreau14de3952022-11-14 07:08:28 +01009541 __fallthrough;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009542
9543 default:
9544 return 0;
9545 }
9546}
9547
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009548/* This function is an LUA binding used for registering
9549 * "sample-conv" functions. It expects a converter name used
9550 * in the haproxy configuration file, and an LUA function.
9551 */
9552__LJMP static int hlua_register_converters(lua_State *L)
9553{
9554 struct sample_conv_kw_list *sck;
9555 const char *name;
9556 int ref;
9557 int len;
Christopher Fauletaa224302021-04-12 14:08:21 +02009558 struct hlua_function *fcn = NULL;
Thierry Fournierf67442e2020-11-28 20:41:07 +01009559 struct sample_conv *sc;
9560 struct buffer *trash;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009561
9562 MAY_LJMP(check_args(L, 2, "register_converters"));
9563
Aurelien DARRAGON87f52972023-02-24 09:43:54 +01009564 if (hlua_gethlua(L)) {
9565 /* runtime processing */
9566 WILL_LJMP(luaL_error(L, "register_converters: not available outside of body context"));
9567 }
9568
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009569 /* First argument : converter name. */
9570 name = MAY_LJMP(luaL_checkstring(L, 1));
9571
9572 /* Second argument : lua function. */
9573 ref = MAY_LJMP(hlua_checkfunction(L, 2));
9574
Thierry Fournierf67442e2020-11-28 20:41:07 +01009575 /* Check if the converter is already registered */
9576 trash = get_trash_chunk();
9577 chunk_printf(trash, "lua.%s", name);
9578 sc = find_sample_conv(trash->area, trash->data);
9579 if (sc != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +01009580 fcn = sc->private;
9581 if (fcn->function_ref[hlua_state_id] != -1) {
9582 ha_warning("Trying to register converter 'lua.%s' more than once. "
9583 "This will become a hard error in version 2.5.\n", name);
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +01009584 hlua_unref(L, fcn->function_ref[hlua_state_id]);
Thierry Fournier59f11be2020-11-29 00:37:41 +01009585 }
9586 fcn->function_ref[hlua_state_id] = ref;
9587 return 0;
Thierry Fournierf67442e2020-11-28 20:41:07 +01009588 }
9589
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009590 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02009591 sck = calloc(1, sizeof(*sck) + sizeof(struct sample_conv) * 2);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009592 if (!sck)
Christopher Fauletaa224302021-04-12 14:08:21 +02009593 goto alloc_error;
Thierry Fournier62a22aa2020-11-28 21:06:35 +01009594 fcn = new_hlua_function();
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009595 if (!fcn)
Christopher Fauletaa224302021-04-12 14:08:21 +02009596 goto alloc_error;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009597
9598 /* Fill fcn. */
9599 fcn->name = strdup(name);
9600 if (!fcn->name)
Christopher Fauletaa224302021-04-12 14:08:21 +02009601 goto alloc_error;
Thierry Fournierc7492592020-11-28 23:57:24 +01009602 fcn->function_ref[hlua_state_id] = ref;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009603
9604 /* List head */
9605 sck->list.n = sck->list.p = NULL;
9606
9607 /* converter keyword. */
9608 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02009609 sck->kw[0].kw = calloc(1, len);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009610 if (!sck->kw[0].kw)
Christopher Fauletaa224302021-04-12 14:08:21 +02009611 goto alloc_error;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009612
9613 snprintf((char *)sck->kw[0].kw, len, "lua.%s", name);
9614 sck->kw[0].process = hlua_sample_conv_wrapper;
David Carlier0c437f42016-04-27 16:21:56 +01009615 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 +01009616 sck->kw[0].val_args = NULL;
9617 sck->kw[0].in_type = SMP_T_STR;
9618 sck->kw[0].out_type = SMP_T_STR;
9619 sck->kw[0].private = fcn;
9620
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009621 /* Register this new converter */
9622 sample_register_convs(sck);
9623
9624 return 0;
Christopher Fauletaa224302021-04-12 14:08:21 +02009625
9626 alloc_error:
9627 release_hlua_function(fcn);
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +01009628 hlua_unref(L, ref);
Christopher Fauletaa224302021-04-12 14:08:21 +02009629 ha_free(&sck);
9630 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
9631 return 0; /* Never reached */
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009632}
9633
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08009634/* This function is an LUA binding used for registering
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009635 * "sample-fetch" functions. It expects a converter name used
9636 * in the haproxy configuration file, and an LUA function.
9637 */
9638__LJMP static int hlua_register_fetches(lua_State *L)
9639{
9640 const char *name;
9641 int ref;
9642 int len;
9643 struct sample_fetch_kw_list *sfk;
Christopher Faulet2567f182021-04-12 14:11:50 +02009644 struct hlua_function *fcn = NULL;
Thierry Fournierf67442e2020-11-28 20:41:07 +01009645 struct sample_fetch *sf;
9646 struct buffer *trash;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009647
9648 MAY_LJMP(check_args(L, 2, "register_fetches"));
9649
Aurelien DARRAGON87f52972023-02-24 09:43:54 +01009650 if (hlua_gethlua(L)) {
9651 /* runtime processing */
9652 WILL_LJMP(luaL_error(L, "register_fetches: not available outside of body context"));
9653 }
9654
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009655 /* First argument : sample-fetch name. */
9656 name = MAY_LJMP(luaL_checkstring(L, 1));
9657
9658 /* Second argument : lua function. */
9659 ref = MAY_LJMP(hlua_checkfunction(L, 2));
9660
Thierry Fournierf67442e2020-11-28 20:41:07 +01009661 /* Check if the sample-fetch is already registered */
9662 trash = get_trash_chunk();
9663 chunk_printf(trash, "lua.%s", name);
9664 sf = find_sample_fetch(trash->area, trash->data);
9665 if (sf != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +01009666 fcn = sf->private;
9667 if (fcn->function_ref[hlua_state_id] != -1) {
9668 ha_warning("Trying to register sample-fetch 'lua.%s' more than once. "
9669 "This will become a hard error in version 2.5.\n", name);
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +01009670 hlua_unref(L, fcn->function_ref[hlua_state_id]);
Thierry Fournier59f11be2020-11-29 00:37:41 +01009671 }
9672 fcn->function_ref[hlua_state_id] = ref;
9673 return 0;
Thierry Fournierf67442e2020-11-28 20:41:07 +01009674 }
9675
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009676 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02009677 sfk = calloc(1, sizeof(*sfk) + sizeof(struct sample_fetch) * 2);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009678 if (!sfk)
Christopher Faulet2567f182021-04-12 14:11:50 +02009679 goto alloc_error;
Thierry Fournier62a22aa2020-11-28 21:06:35 +01009680 fcn = new_hlua_function();
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009681 if (!fcn)
Christopher Faulet2567f182021-04-12 14:11:50 +02009682 goto alloc_error;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009683
9684 /* Fill fcn. */
9685 fcn->name = strdup(name);
9686 if (!fcn->name)
Christopher Faulet2567f182021-04-12 14:11:50 +02009687 goto alloc_error;
Thierry Fournierc7492592020-11-28 23:57:24 +01009688 fcn->function_ref[hlua_state_id] = ref;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009689
9690 /* List head */
9691 sfk->list.n = sfk->list.p = NULL;
9692
9693 /* sample-fetch keyword. */
9694 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02009695 sfk->kw[0].kw = calloc(1, len);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009696 if (!sfk->kw[0].kw)
Christopher Faulet2567f182021-04-12 14:11:50 +02009697 goto alloc_error;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009698
9699 snprintf((char *)sfk->kw[0].kw, len, "lua.%s", name);
9700 sfk->kw[0].process = hlua_sample_fetch_wrapper;
David Carlier0c437f42016-04-27 16:21:56 +01009701 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 +01009702 sfk->kw[0].val_args = NULL;
9703 sfk->kw[0].out_type = SMP_T_STR;
9704 sfk->kw[0].use = SMP_USE_HTTP_ANY;
9705 sfk->kw[0].val = 0;
9706 sfk->kw[0].private = fcn;
9707
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009708 /* Register this new fetch. */
9709 sample_register_fetches(sfk);
9710
9711 return 0;
Christopher Faulet2567f182021-04-12 14:11:50 +02009712
9713 alloc_error:
9714 release_hlua_function(fcn);
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +01009715 hlua_unref(L, ref);
Christopher Faulet2567f182021-04-12 14:11:50 +02009716 ha_free(&sfk);
9717 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
9718 return 0; /* Never reached */
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009719}
9720
Christopher Faulet501465d2020-02-26 14:54:16 +01009721/* This function is a lua binding to set the wake_time.
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01009722 */
Christopher Faulet501465d2020-02-26 14:54:16 +01009723__LJMP static int hlua_set_wake_time(lua_State *L)
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01009724{
Thierry Fournier4234dbd2020-11-28 13:18:23 +01009725 struct hlua *hlua;
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01009726 unsigned int delay;
9727 unsigned int wakeup_ms;
9728
Thierry Fournier4234dbd2020-11-28 13:18:23 +01009729 /* Get hlua struct, or NULL if we execute from main lua state */
9730 hlua = hlua_gethlua(L);
9731 if (!hlua) {
9732 return 0;
9733 }
9734
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01009735 MAY_LJMP(check_args(L, 1, "wake_time"));
9736
9737 delay = MAY_LJMP(luaL_checkinteger(L, 1));
9738 wakeup_ms = tick_add(now_ms, delay);
9739 hlua->wake_time = wakeup_ms;
9740 return 0;
9741}
9742
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009743/* This function is a wrapper to execute each LUA function declared as an action
9744 * wrapper during the initialisation period. This function may return any
9745 * ACT_RET_* value. On error ACT_RET_CONT is returned and the action is
9746 * ignored. If the lua action yields, ACT_RET_YIELD is returned. On success, the
9747 * return value is the first element on the stack.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009748 */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009749static enum act_return hlua_action(struct act_rule *rule, struct proxy *px,
Willy Tarreau658b85b2015-09-27 10:00:49 +02009750 struct session *sess, struct stream *s, int flags)
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009751{
9752 char **arg;
Christopher Faulet8c9e6bb2021-08-06 16:29:41 +02009753 unsigned int hflags = HLUA_TXN_ACT_CTX;
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009754 int dir, act_ret = ACT_RET_CONT;
Thierry Fournierfd107a22016-02-19 19:57:23 +01009755 const char *error;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009756
9757 switch (rule->from) {
Christopher Fauletd8f0e072020-02-25 09:45:51 +01009758 case ACT_F_TCP_REQ_CNT: dir = SMP_OPT_DIR_REQ; break;
9759 case ACT_F_TCP_RES_CNT: dir = SMP_OPT_DIR_RES; break;
9760 case ACT_F_HTTP_REQ: dir = SMP_OPT_DIR_REQ; break;
9761 case ACT_F_HTTP_RES: dir = SMP_OPT_DIR_RES; break;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009762 default:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009763 SEND_ERR(px, "Lua: internal error while execute action.\n");
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009764 goto end;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009765 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009766
Willy Tarreau87b09662015-04-03 00:22:06 +02009767 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01009768 * Lua context can be not initialized. This behavior
9769 * permits to save performances because a systematic
9770 * Lua initialization cause 5% performances loss.
9771 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009772 if (!s->hlua) {
Christopher Faulet1e8433f2021-03-24 15:03:01 +01009773 struct hlua *hlua;
9774
9775 hlua = pool_alloc(pool_head_hlua);
9776 if (!hlua) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009777 SEND_ERR(px, "Lua action '%s': can't initialize Lua context.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009778 rule->arg.hlua_rule->fcn->name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009779 goto end;
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009780 }
Christopher Faulet1e8433f2021-03-24 15:03:01 +01009781 HLUA_INIT(hlua);
9782 s->hlua = hlua;
Aurelien DARRAGON6b0b9bd2023-03-21 14:02:16 +01009783 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 +01009784 SEND_ERR(px, "Lua action '%s': can't initialize Lua context.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009785 rule->arg.hlua_rule->fcn->name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009786 goto end;
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009787 }
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01009788 }
9789
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009790 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009791 if (!HLUA_IS_RUNNING(s->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02009792
9793 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009794 if (!SET_SAFE_LJMP(s->hlua)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009795 if (lua_type(s->hlua->T, -1) == LUA_TSTRING)
9796 error = lua_tostring(s->hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +01009797 else
9798 error = "critical error";
9799 SEND_ERR(px, "Lua function '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009800 rule->arg.hlua_rule->fcn->name, error);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009801 goto end;
Thierry FOURNIERbabae282015-09-17 11:36:37 +02009802 }
9803
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009804 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009805 if (!lua_checkstack(s->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009806 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009807 rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009808 RESET_SAFE_LJMP(s->hlua);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009809 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009810 }
9811
9812 /* Restore the function in the stack. */
Aurelien DARRAGON4fdf8b52023-03-20 17:22:37 +01009813 hlua_pushref(s->hlua->T, rule->arg.hlua_rule->fcn->function_ref[s->hlua->state_id]);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009814
Willy Tarreau87b09662015-04-03 00:22:06 +02009815 /* Create and and push object stream in the stack. */
Christopher Fauletbfab2dd2019-07-26 15:09:53 +02009816 if (!hlua_txn_new(s->hlua->T, s, px, dir, hflags)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009817 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009818 rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009819 RESET_SAFE_LJMP(s->hlua);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009820 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009821 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009822 s->hlua->nargs = 1;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009823
9824 /* push keywords in the stack. */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009825 for (arg = rule->arg.hlua_rule->args; arg && *arg; arg++) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009826 if (!lua_checkstack(s->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009827 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009828 rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009829 RESET_SAFE_LJMP(s->hlua);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009830 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009831 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009832 lua_pushstring(s->hlua->T, *arg);
9833 s->hlua->nargs++;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009834 }
9835
Thierry FOURNIERbabae282015-09-17 11:36:37 +02009836 /* Now the execution is safe. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009837 RESET_SAFE_LJMP(s->hlua);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02009838
Thierry FOURNIERbd413492015-03-03 16:52:26 +01009839 /* We must initialize the execution timeouts. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009840 s->hlua->max_time = hlua_timeout_session;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009841 }
9842
9843 /* Execute the function. */
Christopher Faulet105ba6c2019-12-18 14:41:51 +01009844 switch (hlua_ctx_resume(s->hlua, !(flags & ACT_OPT_FINAL))) {
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009845 /* finished. */
9846 case HLUA_E_OK:
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009847 /* Catch the return value */
9848 if (lua_gettop(s->hlua->T) > 0)
9849 act_ret = lua_tointeger(s->hlua->T, -1);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009850
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01009851 /* Set timeout in the required channel. */
Christopher Faulet498c4832020-07-28 11:59:58 +02009852 if (act_ret == ACT_RET_YIELD) {
9853 if (flags & ACT_OPT_FINAL)
9854 goto err_yield;
9855
Christopher Faulet8f587ea2020-07-28 12:01:55 +02009856 if (dir == SMP_OPT_DIR_REQ)
9857 s->req.analyse_exp = tick_first((tick_is_expired(s->req.analyse_exp, now_ms) ? 0 : s->req.analyse_exp),
9858 s->hlua->wake_time);
9859 else
9860 s->res.analyse_exp = tick_first((tick_is_expired(s->res.analyse_exp, now_ms) ? 0 : s->res.analyse_exp),
9861 s->hlua->wake_time);
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01009862 }
9863 goto end;
9864
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009865 /* yield. */
9866 case HLUA_E_AGAIN:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01009867 /* Set timeout in the required channel. */
Christopher Faulet8f587ea2020-07-28 12:01:55 +02009868 if (dir == SMP_OPT_DIR_REQ)
9869 s->req.analyse_exp = tick_first((tick_is_expired(s->req.analyse_exp, now_ms) ? 0 : s->req.analyse_exp),
9870 s->hlua->wake_time);
9871 else
9872 s->res.analyse_exp = tick_first((tick_is_expired(s->res.analyse_exp, now_ms) ? 0 : s->res.analyse_exp),
9873 s->hlua->wake_time);
9874
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009875 /* Some actions can be wake up when a "write" event
9876 * is detected on a response channel. This is useful
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08009877 * only for actions targeted on the requests.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009878 */
Christopher Faulet51fa3582019-07-26 14:54:52 +02009879 if (HLUA_IS_WAKERESWR(s->hlua))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01009880 s->res.flags |= CF_WAKE_WRITE;
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009881 if (HLUA_IS_WAKEREQWR(s->hlua))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01009882 s->req.flags |= CF_WAKE_WRITE;
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009883 act_ret = ACT_RET_YIELD;
9884 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009885
9886 /* finished with error. */
9887 case HLUA_E_ERRMSG:
9888 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009889 SEND_ERR(px, "Lua function '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009890 rule->arg.hlua_rule->fcn->name, lua_tostring(s->hlua->T, -1));
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009891 lua_pop(s->hlua->T, 1);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009892 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009893
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009894 case HLUA_E_ETMOUT:
Thierry Fournierad5345f2020-11-29 02:05:57 +01009895 SEND_ERR(px, "Lua function '%s': execution timeout.\n", rule->arg.hlua_rule->fcn->name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009896 goto end;
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009897
9898 case HLUA_E_NOMEM:
Thierry Fournierad5345f2020-11-29 02:05:57 +01009899 SEND_ERR(px, "Lua function '%s': out of memory error.\n", rule->arg.hlua_rule->fcn->name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009900 goto end;
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009901
9902 case HLUA_E_YIELD:
Christopher Faulet498c4832020-07-28 11:59:58 +02009903 err_yield:
9904 act_ret = ACT_RET_CONT;
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009905 SEND_ERR(px, "Lua function '%s': aborting Lua processing on expired timeout.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009906 rule->arg.hlua_rule->fcn->name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009907 goto end;
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009908
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009909 case HLUA_E_ERR:
9910 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009911 SEND_ERR(px, "Lua function '%s' return an unknown error.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009912 rule->arg.hlua_rule->fcn->name);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009913
9914 default:
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009915 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009916 }
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009917
9918 end:
Christopher Faulet2361fd92020-07-30 10:40:58 +02009919 if (act_ret != ACT_RET_YIELD && s->hlua)
Christopher Faulet8f587ea2020-07-28 12:01:55 +02009920 s->hlua->wake_time = TICK_ETERNITY;
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009921 return act_ret;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009922}
9923
Willy Tarreau144f84a2021-03-02 16:09:26 +01009924struct task *hlua_applet_wakeup(struct task *t, void *context, unsigned int state)
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009925{
Olivier Houchard9f6af332018-05-25 14:04:04 +02009926 struct appctx *ctx = context;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009927
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009928 appctx_wakeup(ctx);
Willy Tarreaud9587412017-08-23 16:07:33 +02009929 t->expire = TICK_ETERNITY;
Willy Tarreaud1aa41f2017-07-21 16:41:56 +02009930 return t;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009931}
9932
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009933static int hlua_applet_tcp_init(struct appctx *ctx)
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009934{
Willy Tarreaue23f33b2022-05-06 14:07:13 +02009935 struct hlua_tcp_ctx *tcp_ctx = applet_reserve_svcctx(ctx, sizeof(*tcp_ctx));
Willy Tarreauc12b3212022-05-27 11:08:15 +02009936 struct stconn *sc = appctx_sc(ctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02009937 struct stream *strm = __sc_strm(sc);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009938 struct hlua *hlua;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009939 struct task *task;
9940 char **arg;
Thierry Fournierfd107a22016-02-19 19:57:23 +01009941 const char *error;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009942
Willy Tarreaubafbe012017-11-24 17:34:44 +01009943 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009944 if (!hlua) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009945 SEND_ERR(strm->be, "Lua applet tcp '%s': out of memory.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009946 ctx->rule->arg.hlua_rule->fcn->name);
Christopher Fauletc9929382022-05-12 11:52:27 +02009947 return -1;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009948 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009949 HLUA_INIT(hlua);
Willy Tarreaue23f33b2022-05-06 14:07:13 +02009950 tcp_ctx->hlua = hlua;
9951 tcp_ctx->flags = 0;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009952
9953 /* Create task used by signal to wakeup applets. */
Willy Tarreaubeeabf52021-10-01 18:23:30 +02009954 task = task_new_here();
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009955 if (!task) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009956 SEND_ERR(strm->be, "Lua applet tcp '%s': out of memory.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009957 ctx->rule->arg.hlua_rule->fcn->name);
Christopher Fauletc9929382022-05-12 11:52:27 +02009958 return -1;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009959 }
9960 task->nice = 0;
9961 task->context = ctx;
9962 task->process = hlua_applet_wakeup;
Willy Tarreaue23f33b2022-05-06 14:07:13 +02009963 tcp_ctx->task = task;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009964
9965 /* In the execution wrappers linked with a stream, the
9966 * Lua context can be not initialized. This behavior
9967 * permits to save performances because a systematic
9968 * Lua initialization cause 5% performances loss.
9969 */
Aurelien DARRAGON6b0b9bd2023-03-21 14:02:16 +01009970 if (!hlua_ctx_init(hlua, fcn_ref_to_stack_id(ctx->rule->arg.hlua_rule->fcn), task)) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009971 SEND_ERR(strm->be, "Lua applet tcp '%s': can't initialize Lua context.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009972 ctx->rule->arg.hlua_rule->fcn->name);
Christopher Fauletc9929382022-05-12 11:52:27 +02009973 return -1;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009974 }
9975
9976 /* Set timeout according with the applet configuration. */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02009977 hlua->max_time = ctx->applet->timeout;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009978
9979 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009980 if (!SET_SAFE_LJMP(hlua)) {
Thierry Fournierfd107a22016-02-19 19:57:23 +01009981 if (lua_type(hlua->T, -1) == LUA_TSTRING)
9982 error = lua_tostring(hlua->T, -1);
9983 else
9984 error = "critical error";
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009985 SEND_ERR(strm->be, "Lua applet tcp '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009986 ctx->rule->arg.hlua_rule->fcn->name, error);
Christopher Fauletc9929382022-05-12 11:52:27 +02009987 return -1;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009988 }
9989
9990 /* Check stack available size. */
9991 if (!lua_checkstack(hlua->T, 1)) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009992 SEND_ERR(strm->be, "Lua applet tcp '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009993 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009994 RESET_SAFE_LJMP(hlua);
Christopher Fauletc9929382022-05-12 11:52:27 +02009995 return -1;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009996 }
9997
9998 /* Restore the function in the stack. */
Aurelien DARRAGON4fdf8b52023-03-20 17:22:37 +01009999 hlua_pushref(hlua->T, ctx->rule->arg.hlua_rule->fcn->function_ref[hlua->state_id]);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010000
10001 /* Create and and push object stream in the stack. */
10002 if (!hlua_applet_tcp_new(hlua->T, ctx)) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +010010003 SEND_ERR(strm->be, "Lua applet tcp '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010004 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010005 RESET_SAFE_LJMP(hlua);
Christopher Fauletc9929382022-05-12 11:52:27 +020010006 return -1;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010007 }
10008 hlua->nargs = 1;
10009
10010 /* push keywords in the stack. */
10011 for (arg = ctx->rule->arg.hlua_rule->args; arg && *arg; arg++) {
10012 if (!lua_checkstack(hlua->T, 1)) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +010010013 SEND_ERR(strm->be, "Lua applet tcp '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010014 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010015 RESET_SAFE_LJMP(hlua);
Christopher Fauletc9929382022-05-12 11:52:27 +020010016 return -1;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010017 }
10018 lua_pushstring(hlua->T, *arg);
10019 hlua->nargs++;
10020 }
10021
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010022 RESET_SAFE_LJMP(hlua);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010023
10024 /* Wakeup the applet ASAP. */
Willy Tarreau90e8b452022-05-25 18:21:43 +020010025 applet_need_more_data(ctx);
Willy Tarreau4164eb92022-05-25 15:42:03 +020010026 applet_have_more_data(ctx);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010027
Christopher Fauletc9929382022-05-12 11:52:27 +020010028 return 0;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010029}
10030
Willy Tarreau60409db2019-08-21 14:14:50 +020010031void hlua_applet_tcp_fct(struct appctx *ctx)
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010032{
Willy Tarreaue23f33b2022-05-06 14:07:13 +020010033 struct hlua_tcp_ctx *tcp_ctx = ctx->svcctx;
Willy Tarreauc12b3212022-05-27 11:08:15 +020010034 struct stconn *sc = appctx_sc(ctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +020010035 struct stream *strm = __sc_strm(sc);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010036 struct act_rule *rule = ctx->rule;
10037 struct proxy *px = strm->be;
Willy Tarreaue23f33b2022-05-06 14:07:13 +020010038 struct hlua *hlua = tcp_ctx->hlua;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010039
Christopher Faulet31572222023-03-31 11:13:48 +020010040 if (unlikely(se_fl_test(ctx->sedesc, (SE_FL_EOS|SE_FL_ERROR|SE_FL_SHR|SE_FL_SHW))))
10041 goto out;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010042
Christopher Faulet31572222023-03-31 11:13:48 +020010043 /* The applet execution is already done. */
10044 if (tcp_ctx->flags & APPLET_DONE)
10045 goto out;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010046
10047 /* Execute the function. */
10048 switch (hlua_ctx_resume(hlua, 1)) {
10049 /* finished. */
10050 case HLUA_E_OK:
Willy Tarreaue23f33b2022-05-06 14:07:13 +020010051 tcp_ctx->flags |= APPLET_DONE;
Christopher Faulet31572222023-03-31 11:13:48 +020010052 se_fl_set(ctx->sedesc, SE_FL_EOI|SE_FL_EOS);
10053 break;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010054
10055 /* yield. */
10056 case HLUA_E_AGAIN:
Thierry Fournier0164f202016-02-20 17:47:43 +010010057 if (hlua->wake_time != TICK_ETERNITY)
Willy Tarreaue23f33b2022-05-06 14:07:13 +020010058 task_schedule(tcp_ctx->task, hlua->wake_time);
Christopher Faulet31572222023-03-31 11:13:48 +020010059 break;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010060
10061 /* finished with error. */
10062 case HLUA_E_ERRMSG:
10063 /* Display log. */
10064 SEND_ERR(px, "Lua applet tcp '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010065 rule->arg.hlua_rule->fcn->name, lua_tostring(hlua->T, -1));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010066 lua_pop(hlua->T, 1);
10067 goto error;
10068
Thierry Fournierd5b073c2018-05-21 19:42:47 +020010069 case HLUA_E_ETMOUT:
10070 SEND_ERR(px, "Lua applet tcp '%s': execution timeout.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010071 rule->arg.hlua_rule->fcn->name);
Thierry Fournierd5b073c2018-05-21 19:42:47 +020010072 goto error;
10073
10074 case HLUA_E_NOMEM:
10075 SEND_ERR(px, "Lua applet tcp '%s': out of memory error.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010076 rule->arg.hlua_rule->fcn->name);
Thierry Fournierd5b073c2018-05-21 19:42:47 +020010077 goto error;
10078
10079 case HLUA_E_YIELD: /* unexpected */
10080 SEND_ERR(px, "Lua applet tcp '%s': yield not allowed.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010081 rule->arg.hlua_rule->fcn->name);
Thierry Fournierd5b073c2018-05-21 19:42:47 +020010082 goto error;
10083
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010084 case HLUA_E_ERR:
10085 /* Display log. */
10086 SEND_ERR(px, "Lua applet tcp '%s' return an unknown error.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010087 rule->arg.hlua_rule->fcn->name);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010088 goto error;
10089
10090 default:
10091 goto error;
10092 }
10093
Christopher Faulet31572222023-03-31 11:13:48 +020010094out:
10095 /* eat the whole request */
10096 co_skip(sc_oc(sc), co_data(sc_oc(sc)));
10097 return;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010098
Christopher Faulet31572222023-03-31 11:13:48 +020010099error:
10100 se_fl_set(ctx->sedesc, SE_FL_ERROR);
Willy Tarreaue23f33b2022-05-06 14:07:13 +020010101 tcp_ctx->flags |= APPLET_DONE;
Christopher Faulet31572222023-03-31 11:13:48 +020010102 goto out;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010103}
10104
10105static void hlua_applet_tcp_release(struct appctx *ctx)
10106{
Willy Tarreaue23f33b2022-05-06 14:07:13 +020010107 struct hlua_tcp_ctx *tcp_ctx = ctx->svcctx;
10108
10109 task_destroy(tcp_ctx->task);
10110 tcp_ctx->task = NULL;
10111 hlua_ctx_destroy(tcp_ctx->hlua);
10112 tcp_ctx->hlua = NULL;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010113}
10114
Christopher Fauletc9929382022-05-12 11:52:27 +020010115/* The function returns 0 if the initialisation is complete or -1 if
10116 * an errors occurs. It also reserves the appctx for an hlua_http_ctx.
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010117 */
Christopher Faulet4aa1d282022-01-13 16:01:35 +010010118static int hlua_applet_http_init(struct appctx *ctx)
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010119{
Willy Tarreauaa229cc2022-05-06 14:26:10 +020010120 struct hlua_http_ctx *http_ctx = applet_reserve_svcctx(ctx, sizeof(*http_ctx));
Willy Tarreauc12b3212022-05-27 11:08:15 +020010121 struct stconn *sc = appctx_sc(ctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +020010122 struct stream *strm = __sc_strm(sc);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010123 struct http_txn *txn;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +010010124 struct hlua *hlua;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010125 char **arg;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010126 struct task *task;
Thierry Fournierfd107a22016-02-19 19:57:23 +010010127 const char *error;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010128
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010129 txn = strm->txn;
Willy Tarreaubafbe012017-11-24 17:34:44 +010010130 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +010010131 if (!hlua) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +010010132 SEND_ERR(strm->be, "Lua applet http '%s': out of memory.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010133 ctx->rule->arg.hlua_rule->fcn->name);
Christopher Fauletc9929382022-05-12 11:52:27 +020010134 return -1;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +010010135 }
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010136 HLUA_INIT(hlua);
Willy Tarreauaa229cc2022-05-06 14:26:10 +020010137 http_ctx->hlua = hlua;
10138 http_ctx->left_bytes = -1;
10139 http_ctx->flags = 0;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010140
Thierry FOURNIERd93ea2b2015-12-20 19:14:52 +010010141 if (txn->req.flags & HTTP_MSGF_VER_11)
Willy Tarreauaa229cc2022-05-06 14:26:10 +020010142 http_ctx->flags |= APPLET_HTTP11;
Thierry FOURNIERd93ea2b2015-12-20 19:14:52 +010010143
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010144 /* Create task used by signal to wakeup applets. */
Willy Tarreaubeeabf52021-10-01 18:23:30 +020010145 task = task_new_here();
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010146 if (!task) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +010010147 SEND_ERR(strm->be, "Lua applet http '%s': out of memory.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010148 ctx->rule->arg.hlua_rule->fcn->name);
Christopher Fauletc9929382022-05-12 11:52:27 +020010149 return -1;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010150 }
10151 task->nice = 0;
10152 task->context = ctx;
10153 task->process = hlua_applet_wakeup;
Willy Tarreauaa229cc2022-05-06 14:26:10 +020010154 http_ctx->task = task;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010155
10156 /* In the execution wrappers linked with a stream, the
10157 * Lua context can be not initialized. This behavior
10158 * permits to save performances because a systematic
10159 * Lua initialization cause 5% performances loss.
10160 */
Aurelien DARRAGON6b0b9bd2023-03-21 14:02:16 +010010161 if (!hlua_ctx_init(hlua, fcn_ref_to_stack_id(ctx->rule->arg.hlua_rule->fcn), task)) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +010010162 SEND_ERR(strm->be, "Lua applet http '%s': can't initialize Lua context.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010163 ctx->rule->arg.hlua_rule->fcn->name);
Christopher Fauletc9929382022-05-12 11:52:27 +020010164 return -1;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010165 }
10166
10167 /* Set timeout according with the applet configuration. */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +020010168 hlua->max_time = ctx->applet->timeout;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010169
10170 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010171 if (!SET_SAFE_LJMP(hlua)) {
Thierry Fournierfd107a22016-02-19 19:57:23 +010010172 if (lua_type(hlua->T, -1) == LUA_TSTRING)
10173 error = lua_tostring(hlua->T, -1);
10174 else
10175 error = "critical error";
Christopher Faulet4aa1d282022-01-13 16:01:35 +010010176 SEND_ERR(strm->be, "Lua applet http '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010177 ctx->rule->arg.hlua_rule->fcn->name, error);
Christopher Fauletc9929382022-05-12 11:52:27 +020010178 return -1;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010179 }
10180
10181 /* Check stack available size. */
10182 if (!lua_checkstack(hlua->T, 1)) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +010010183 SEND_ERR(strm->be, "Lua applet http '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010184 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010185 RESET_SAFE_LJMP(hlua);
Christopher Fauletc9929382022-05-12 11:52:27 +020010186 return -1;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010187 }
10188
10189 /* Restore the function in the stack. */
Aurelien DARRAGON4fdf8b52023-03-20 17:22:37 +010010190 hlua_pushref(hlua->T, ctx->rule->arg.hlua_rule->fcn->function_ref[hlua->state_id]);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010191
10192 /* Create and and push object stream in the stack. */
10193 if (!hlua_applet_http_new(hlua->T, ctx)) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +010010194 SEND_ERR(strm->be, "Lua applet http '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010195 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010196 RESET_SAFE_LJMP(hlua);
Christopher Fauletc9929382022-05-12 11:52:27 +020010197 return -1;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010198 }
10199 hlua->nargs = 1;
10200
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010201 /* push keywords in the stack. */
10202 for (arg = ctx->rule->arg.hlua_rule->args; arg && *arg; arg++) {
10203 if (!lua_checkstack(hlua->T, 1)) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +010010204 SEND_ERR(strm->be, "Lua applet http '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010205 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010206 RESET_SAFE_LJMP(hlua);
Christopher Fauletc9929382022-05-12 11:52:27 +020010207 return -1;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010208 }
10209 lua_pushstring(hlua->T, *arg);
10210 hlua->nargs++;
10211 }
10212
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010213 RESET_SAFE_LJMP(hlua);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010214
10215 /* Wakeup the applet when data is ready for read. */
Willy Tarreau90e8b452022-05-25 18:21:43 +020010216 applet_need_more_data(ctx);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010217
Christopher Fauletc9929382022-05-12 11:52:27 +020010218 return 0;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010219}
10220
Willy Tarreau60409db2019-08-21 14:14:50 +020010221void hlua_applet_http_fct(struct appctx *ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010222{
Willy Tarreauaa229cc2022-05-06 14:26:10 +020010223 struct hlua_http_ctx *http_ctx = ctx->svcctx;
Willy Tarreauc12b3212022-05-27 11:08:15 +020010224 struct stconn *sc = appctx_sc(ctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +020010225 struct stream *strm = __sc_strm(sc);
10226 struct channel *req = sc_oc(sc);
10227 struct channel *res = sc_ic(sc);
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010228 struct act_rule *rule = ctx->rule;
10229 struct proxy *px = strm->be;
Willy Tarreauaa229cc2022-05-06 14:26:10 +020010230 struct hlua *hlua = http_ctx->hlua;
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010231 struct htx *req_htx, *res_htx;
10232
10233 res_htx = htx_from_buf(&res->buf);
10234
Christopher Faulet31572222023-03-31 11:13:48 +020010235 if (unlikely(se_fl_test(ctx->sedesc, (SE_FL_EOS|SE_FL_ERROR|SE_FL_SHR|SE_FL_SHW))))
10236 goto out;
10237
10238 /* The applet execution is already done. */
10239 if (http_ctx->flags & APPLET_DONE)
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010240 goto out;
10241
Ilya Shipitsin856aabc2020-04-16 23:51:34 +050010242 /* Check if the input buffer is available. */
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010243 if (!b_size(&res->buf)) {
Willy Tarreau3e7be362022-05-27 10:35:27 +020010244 sc_need_room(sc);
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010245 goto out;
10246 }
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010247
10248 /* Set the currently running flag. */
10249 if (!HLUA_IS_RUNNING(hlua) &&
Willy Tarreauaa229cc2022-05-06 14:26:10 +020010250 !(http_ctx->flags & APPLET_DONE)) {
Christopher Fauletbd878d22021-04-28 10:50:21 +020010251 if (!co_data(req)) {
Willy Tarreau90e8b452022-05-25 18:21:43 +020010252 applet_need_more_data(ctx);
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010253 goto out;
10254 }
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010255 }
10256
Christopher Faulet31572222023-03-31 11:13:48 +020010257 /* Execute the function. */
10258 switch (hlua_ctx_resume(hlua, 1)) {
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010259 /* finished. */
10260 case HLUA_E_OK:
Willy Tarreauaa229cc2022-05-06 14:26:10 +020010261 http_ctx->flags |= APPLET_DONE;
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010262 break;
10263
10264 /* yield. */
10265 case HLUA_E_AGAIN:
10266 if (hlua->wake_time != TICK_ETERNITY)
Willy Tarreauaa229cc2022-05-06 14:26:10 +020010267 task_schedule(http_ctx->task, hlua->wake_time);
Christopher Faulet56a3d6e2019-02-27 22:06:23 +010010268 goto out;
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010269
10270 /* finished with error. */
10271 case HLUA_E_ERRMSG:
10272 /* Display log. */
10273 SEND_ERR(px, "Lua applet http '%s': %s.\n",
Christopher Faulet31572222023-03-31 11:13:48 +020010274 rule->arg.hlua_rule->fcn->name, lua_tostring(hlua->T, -1));
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010275 lua_pop(hlua->T, 1);
10276 goto error;
10277
10278 case HLUA_E_ETMOUT:
10279 SEND_ERR(px, "Lua applet http '%s': execution timeout.\n",
Christopher Faulet31572222023-03-31 11:13:48 +020010280 rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010281 goto error;
10282
10283 case HLUA_E_NOMEM:
10284 SEND_ERR(px, "Lua applet http '%s': out of memory error.\n",
Christopher Faulet31572222023-03-31 11:13:48 +020010285 rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010286 goto error;
10287
10288 case HLUA_E_YIELD: /* unexpected */
10289 SEND_ERR(px, "Lua applet http '%s': yield not allowed.\n",
Christopher Faulet31572222023-03-31 11:13:48 +020010290 rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010291 goto error;
10292
10293 case HLUA_E_ERR:
10294 /* Display log. */
10295 SEND_ERR(px, "Lua applet http '%s' return an unknown error.\n",
Christopher Faulet31572222023-03-31 11:13:48 +020010296 rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010297 goto error;
10298
10299 default:
10300 goto error;
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010301 }
10302
Willy Tarreauaa229cc2022-05-06 14:26:10 +020010303 if (http_ctx->flags & APPLET_DONE) {
10304 if (http_ctx->flags & APPLET_RSP_SENT)
Christopher Faulet31572222023-03-31 11:13:48 +020010305 goto out;
Christopher Faulet56a3d6e2019-02-27 22:06:23 +010010306
Willy Tarreauaa229cc2022-05-06 14:26:10 +020010307 if (!(http_ctx->flags & APPLET_HDR_SENT))
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010308 goto error;
10309
Christopher Fauletf89af9c2022-04-07 10:07:18 +020010310 /* no more data are expected. If the response buffer is empty
10311 * for a chunked message, be sure to add something (EOT block in
10312 * this case) to have something to send. It is important to be
10313 * sure the EOM flags will be handled by the endpoint.
10314 */
10315 if (htx_is_empty(res_htx) && (strm->txn->rsp.flags & (HTTP_MSGF_XFER_LEN|HTTP_MSGF_CNT_LEN)) == HTTP_MSGF_XFER_LEN) {
10316 if (!htx_add_endof(res_htx, HTX_BLK_EOT)) {
Willy Tarreau3e7be362022-05-27 10:35:27 +020010317 sc_need_room(sc);
Christopher Fauletf89af9c2022-04-07 10:07:18 +020010318 goto out;
10319 }
10320 channel_add_input(res, 1);
10321 }
10322
Christopher Fauletd1ac2b92020-12-02 19:12:22 +010010323 res_htx->flags |= HTX_FL_EOM;
Christopher Faulet31572222023-03-31 11:13:48 +020010324 se_fl_set(ctx->sedesc, SE_FL_EOI|SE_FL_EOS);
Willy Tarreauaa229cc2022-05-06 14:26:10 +020010325 strm->txn->status = http_ctx->status;
10326 http_ctx->flags |= APPLET_RSP_SENT;
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010327 }
10328
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010329 out:
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010330 htx_to_buf(res_htx, &res->buf);
Christopher Faulet31572222023-03-31 11:13:48 +020010331 /* eat the whole request */
10332 if (co_data(req)) {
10333 req_htx = htx_from_buf(&req->buf);
10334 co_htx_skip(req, req_htx, co_data(req));
10335 htx_to_buf(req_htx, &req->buf);
10336 }
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010337 return;
10338
10339 error:
10340
10341 /* If we are in HTTP mode, and we are not send any
10342 * data, return a 500 server error in best effort:
10343 * if there is no room available in the buffer,
10344 * just close the connection.
10345 */
Willy Tarreauaa229cc2022-05-06 14:26:10 +020010346 if (!(http_ctx->flags & APPLET_HDR_SENT)) {
Christopher Fauletf7346382019-07-17 22:02:08 +020010347 struct buffer *err = &http_err_chunks[HTTP_ERR_500];
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010348
10349 channel_erase(res);
10350 res->buf.data = b_data(err);
10351 memcpy(res->buf.area, b_head(err), b_data(err));
10352 res_htx = htx_from_buf(&res->buf);
Christopher Fauletf6cce3f2019-02-27 21:20:09 +010010353 channel_add_input(res, res_htx->data);
Christopher Faulet31572222023-03-31 11:13:48 +020010354 se_fl_set(ctx->sedesc, SE_FL_EOI|SE_FL_EOS);
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010355 }
Christopher Faulet31572222023-03-31 11:13:48 +020010356 else
10357 se_fl_set(ctx->sedesc, SE_FL_ERROR);
10358
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010359 if (!(strm->flags & SF_ERR_MASK))
10360 strm->flags |= SF_ERR_RESOURCE;
Willy Tarreauaa229cc2022-05-06 14:26:10 +020010361 http_ctx->flags |= APPLET_DONE;
Christopher Faulet31572222023-03-31 11:13:48 +020010362 goto out;
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010363}
10364
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010365static void hlua_applet_http_release(struct appctx *ctx)
10366{
Willy Tarreauaa229cc2022-05-06 14:26:10 +020010367 struct hlua_http_ctx *http_ctx = ctx->svcctx;
10368
10369 task_destroy(http_ctx->task);
10370 http_ctx->task = NULL;
10371 hlua_ctx_destroy(http_ctx->hlua);
10372 http_ctx->hlua = NULL;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010373}
10374
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +020010375/* global {tcp|http}-request parser. Return ACT_RET_PRS_OK in
Ilya Shipitsin856aabc2020-04-16 23:51:34 +050010376 * success case, else return ACT_RET_PRS_ERR.
Thierry FOURNIERbabae282015-09-17 11:36:37 +020010377 *
10378 * This function can fail with an abort() due to an Lua critical error.
10379 * We are in the configuration parsing process of HAProxy, this abort() is
10380 * tolerated.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +010010381 */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +020010382static enum act_parse_ret action_register_lua(const char **args, int *cur_arg, struct proxy *px,
10383 struct act_rule *rule, char **err)
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +010010384{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +020010385 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +010010386 int i;
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010387
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +020010388 /* Memory for the rule. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +020010389 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +020010390 if (!rule->arg.hlua_rule) {
10391 memprintf(err, "out of memory error");
Christopher Faulet528526f2021-04-12 14:37:32 +020010392 goto error;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +020010393 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +010010394
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +010010395 /* Memory for arguments. */
Tim Duesterhuse52b6e52020-09-12 20:26:43 +020010396 rule->arg.hlua_rule->args = calloc(fcn->nargs + 1,
10397 sizeof(*rule->arg.hlua_rule->args));
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +010010398 if (!rule->arg.hlua_rule->args) {
10399 memprintf(err, "out of memory error");
Christopher Faulet528526f2021-04-12 14:37:32 +020010400 goto error;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +010010401 }
10402
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +020010403 /* Reference the Lua function and store the reference. */
Thierry Fournierad5345f2020-11-29 02:05:57 +010010404 rule->arg.hlua_rule->fcn = fcn;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +020010405
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +010010406 /* Expect some arguments */
10407 for (i = 0; i < fcn->nargs; i++) {
Thierry FOURNIER1725c2e2019-01-06 19:38:49 +010010408 if (*args[*cur_arg] == '\0') {
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +010010409 memprintf(err, "expect %d arguments", fcn->nargs);
Christopher Faulet528526f2021-04-12 14:37:32 +020010410 goto error;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +010010411 }
Thierry FOURNIER1725c2e2019-01-06 19:38:49 +010010412 rule->arg.hlua_rule->args[i] = strdup(args[*cur_arg]);
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +010010413 if (!rule->arg.hlua_rule->args[i]) {
10414 memprintf(err, "out of memory error");
Christopher Faulet528526f2021-04-12 14:37:32 +020010415 goto error;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +010010416 }
10417 (*cur_arg)++;
10418 }
10419 rule->arg.hlua_rule->args[i] = NULL;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +020010420
Thierry FOURNIER42148732015-09-02 17:17:33 +020010421 rule->action = ACT_CUSTOM;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +020010422 rule->action_ptr = hlua_action;
Thierry FOURNIERafa80492015-08-19 09:04:15 +020010423 return ACT_RET_PRS_OK;
Christopher Faulet528526f2021-04-12 14:37:32 +020010424
10425 error:
10426 if (rule->arg.hlua_rule) {
10427 if (rule->arg.hlua_rule->args) {
10428 for (i = 0; i < fcn->nargs; i++)
10429 ha_free(&rule->arg.hlua_rule->args[i]);
10430 ha_free(&rule->arg.hlua_rule->args);
10431 }
10432 ha_free(&rule->arg.hlua_rule);
10433 }
10434 return ACT_RET_PRS_ERR;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +010010435}
10436
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010437static enum act_parse_ret action_register_service_http(const char **args, int *cur_arg, struct proxy *px,
10438 struct act_rule *rule, char **err)
10439{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +020010440 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010441
Thierry FOURNIER718e2a72015-12-20 20:13:14 +010010442 /* HTTP applets are forbidden in tcp-request rules.
Ilya Shipitsin856aabc2020-04-16 23:51:34 +050010443 * HTTP applet request requires everything initialized by
Thierry FOURNIER718e2a72015-12-20 20:13:14 +010010444 * "http_process_request" (analyzer flag AN_REQ_HTTP_INNER).
Ilya Shipitsin856aabc2020-04-16 23:51:34 +050010445 * The applet will be immediately initialized, but its before
Thierry FOURNIER718e2a72015-12-20 20:13:14 +010010446 * the call of this analyzer.
10447 */
10448 if (rule->from != ACT_F_HTTP_REQ) {
10449 memprintf(err, "HTTP applets are forbidden from 'tcp-request' rulesets");
10450 return ACT_RET_PRS_ERR;
10451 }
10452
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010453 /* Memory for the rule. */
10454 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
10455 if (!rule->arg.hlua_rule) {
10456 memprintf(err, "out of memory error");
10457 return ACT_RET_PRS_ERR;
10458 }
10459
10460 /* Reference the Lua function and store the reference. */
Thierry Fournierad5345f2020-11-29 02:05:57 +010010461 rule->arg.hlua_rule->fcn = fcn;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010462
10463 /* TODO: later accept arguments. */
10464 rule->arg.hlua_rule->args = NULL;
10465
10466 /* Add applet pointer in the rule. */
10467 rule->applet.obj_type = OBJ_TYPE_APPLET;
10468 rule->applet.name = fcn->name;
10469 rule->applet.init = hlua_applet_http_init;
10470 rule->applet.fct = hlua_applet_http_fct;
10471 rule->applet.release = hlua_applet_http_release;
10472 rule->applet.timeout = hlua_timeout_applet;
10473
10474 return ACT_RET_PRS_OK;
10475}
10476
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010477/* This function is an LUA binding used for registering
10478 * "sample-conv" functions. It expects a converter name used
10479 * in the haproxy configuration file, and an LUA function.
10480 */
10481__LJMP static int hlua_register_action(lua_State *L)
10482{
Christopher Faulet4fc9da02021-04-12 15:08:12 +020010483 struct action_kw_list *akl = NULL;
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010484 const char *name;
10485 int ref;
10486 int len;
Christopher Faulet4fc9da02021-04-12 15:08:12 +020010487 struct hlua_function *fcn = NULL;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +010010488 int nargs;
Thierry Fournierf67442e2020-11-28 20:41:07 +010010489 struct buffer *trash;
10490 struct action_kw *akw;
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010491
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +010010492 /* Initialise the number of expected arguments at 0. */
10493 nargs = 0;
10494
10495 if (lua_gettop(L) < 3 || lua_gettop(L) > 4)
10496 WILL_LJMP(luaL_error(L, "'register_action' needs between 3 and 4 arguments"));
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010497
Aurelien DARRAGON87f52972023-02-24 09:43:54 +010010498 if (hlua_gethlua(L)) {
10499 /* runtime processing */
10500 WILL_LJMP(luaL_error(L, "register_action: not available outside of body context"));
10501 }
10502
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010503 /* First argument : converter name. */
10504 name = MAY_LJMP(luaL_checkstring(L, 1));
10505
10506 /* Second argument : environment. */
10507 if (lua_type(L, 2) != LUA_TTABLE)
10508 WILL_LJMP(luaL_error(L, "register_action: second argument must be a table of strings"));
10509
10510 /* Third argument : lua function. */
10511 ref = MAY_LJMP(hlua_checkfunction(L, 3));
10512
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -080010513 /* Fourth argument : number of mandatory arguments expected on the configuration line. */
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +010010514 if (lua_gettop(L) >= 4)
10515 nargs = MAY_LJMP(luaL_checkinteger(L, 4));
10516
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -080010517 /* browse the second argument as an array. */
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010518 lua_pushnil(L);
10519 while (lua_next(L, 2) != 0) {
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +010010520 if (lua_type(L, -1) != LUA_TSTRING) {
10521 hlua_unref(L, ref);
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010522 WILL_LJMP(luaL_error(L, "register_action: second argument must be a table of strings"));
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +010010523 }
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010524
Thierry Fournierf67442e2020-11-28 20:41:07 +010010525 /* Check if action exists */
10526 trash = get_trash_chunk();
10527 chunk_printf(trash, "lua.%s", name);
10528 if (strcmp(lua_tostring(L, -1), "tcp-req") == 0) {
10529 akw = tcp_req_cont_action(trash->area);
10530 } else if (strcmp(lua_tostring(L, -1), "tcp-res") == 0) {
10531 akw = tcp_res_cont_action(trash->area);
10532 } else if (strcmp(lua_tostring(L, -1), "http-req") == 0) {
10533 akw = action_http_req_custom(trash->area);
10534 } else if (strcmp(lua_tostring(L, -1), "http-res") == 0) {
10535 akw = action_http_res_custom(trash->area);
10536 } else {
10537 akw = NULL;
10538 }
10539 if (akw != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +010010540 fcn = akw->private;
10541 if (fcn->function_ref[hlua_state_id] != -1) {
10542 ha_warning("Trying to register action 'lua.%s' more than once. "
10543 "This will become a hard error in version 2.5.\n", name);
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +010010544 hlua_unref(L, fcn->function_ref[hlua_state_id]);
Thierry Fournier59f11be2020-11-29 00:37:41 +010010545 }
10546 fcn->function_ref[hlua_state_id] = ref;
10547
10548 /* pop the environment string. */
10549 lua_pop(L, 1);
10550 continue;
Thierry Fournierf67442e2020-11-28 20:41:07 +010010551 }
10552
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010553 /* Check required environment. Only accepted "http" or "tcp". */
10554 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +020010555 akl = calloc(1, sizeof(*akl) + sizeof(struct action_kw) * 2);
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010556 if (!akl)
Christopher Faulet4fc9da02021-04-12 15:08:12 +020010557 goto alloc_error;;
Thierry Fournier62a22aa2020-11-28 21:06:35 +010010558 fcn = new_hlua_function();
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010559 if (!fcn)
Christopher Faulet4fc9da02021-04-12 15:08:12 +020010560 goto alloc_error;
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010561
10562 /* Fill fcn. */
10563 fcn->name = strdup(name);
10564 if (!fcn->name)
Christopher Faulet4fc9da02021-04-12 15:08:12 +020010565 goto alloc_error;
Thierry Fournierc7492592020-11-28 23:57:24 +010010566 fcn->function_ref[hlua_state_id] = ref;
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010567
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -070010568 /* Set the expected number of arguments. */
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +010010569 fcn->nargs = nargs;
10570
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010571 /* List head */
10572 akl->list.n = akl->list.p = NULL;
10573
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010574 /* action keyword. */
10575 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +020010576 akl->kw[0].kw = calloc(1, len);
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010577 if (!akl->kw[0].kw)
Christopher Faulet4fc9da02021-04-12 15:08:12 +020010578 goto alloc_error;
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010579
10580 snprintf((char *)akl->kw[0].kw, len, "lua.%s", name);
10581
Amaury Denoyellee4a617c2021-05-06 15:33:09 +020010582 akl->kw[0].flags = 0;
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010583 akl->kw[0].private = fcn;
10584 akl->kw[0].parse = action_register_lua;
10585
10586 /* select the action registering point. */
10587 if (strcmp(lua_tostring(L, -1), "tcp-req") == 0)
10588 tcp_req_cont_keywords_register(akl);
10589 else if (strcmp(lua_tostring(L, -1), "tcp-res") == 0)
10590 tcp_res_cont_keywords_register(akl);
10591 else if (strcmp(lua_tostring(L, -1), "http-req") == 0)
10592 http_req_keywords_register(akl);
10593 else if (strcmp(lua_tostring(L, -1), "http-res") == 0)
10594 http_res_keywords_register(akl);
Christopher Faulet4fc9da02021-04-12 15:08:12 +020010595 else {
10596 release_hlua_function(fcn);
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +010010597 hlua_unref(L, ref);
Christopher Faulet4fc9da02021-04-12 15:08:12 +020010598 if (akl)
10599 ha_free((char **)&(akl->kw[0].kw));
10600 ha_free(&akl);
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +010010601 WILL_LJMP(luaL_error(L, "Lua action environment '%s' is unknown. "
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010602 "'tcp-req', 'tcp-res', 'http-req' or 'http-res' "
10603 "are expected.", lua_tostring(L, -1)));
Christopher Faulet4fc9da02021-04-12 15:08:12 +020010604 }
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010605
10606 /* pop the environment string. */
10607 lua_pop(L, 1);
Christopher Faulet4fc9da02021-04-12 15:08:12 +020010608
10609 /* reset for next loop */
10610 akl = NULL;
10611 fcn = NULL;
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010612 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010613 return ACT_RET_PRS_OK;
Christopher Faulet4fc9da02021-04-12 15:08:12 +020010614
10615 alloc_error:
10616 release_hlua_function(fcn);
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +010010617 hlua_unref(L, ref);
Christopher Faulet4fc9da02021-04-12 15:08:12 +020010618 ha_free(&akl);
10619 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
10620 return 0; /* Never reached */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010621}
10622
10623static enum act_parse_ret action_register_service_tcp(const char **args, int *cur_arg, struct proxy *px,
10624 struct act_rule *rule, char **err)
10625{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +020010626 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010627
Christopher Faulet280f85b2019-07-15 15:02:04 +020010628 if (px->mode == PR_MODE_HTTP) {
10629 memprintf(err, "Lua TCP services cannot be used on HTTP proxies");
Christopher Fauletafd8f102018-11-08 11:34:21 +010010630 return ACT_RET_PRS_ERR;
10631 }
10632
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010633 /* Memory for the rule. */
10634 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
10635 if (!rule->arg.hlua_rule) {
10636 memprintf(err, "out of memory error");
10637 return ACT_RET_PRS_ERR;
10638 }
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010639
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010640 /* Reference the Lua function and store the reference. */
Thierry Fournierad5345f2020-11-29 02:05:57 +010010641 rule->arg.hlua_rule->fcn = fcn;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010642
10643 /* TODO: later accept arguments. */
10644 rule->arg.hlua_rule->args = NULL;
10645
10646 /* Add applet pointer in the rule. */
10647 rule->applet.obj_type = OBJ_TYPE_APPLET;
10648 rule->applet.name = fcn->name;
10649 rule->applet.init = hlua_applet_tcp_init;
10650 rule->applet.fct = hlua_applet_tcp_fct;
10651 rule->applet.release = hlua_applet_tcp_release;
10652 rule->applet.timeout = hlua_timeout_applet;
10653
10654 return 0;
10655}
10656
10657/* This function is an LUA binding used for registering
10658 * "sample-conv" functions. It expects a converter name used
10659 * in the haproxy configuration file, and an LUA function.
10660 */
10661__LJMP static int hlua_register_service(lua_State *L)
10662{
10663 struct action_kw_list *akl;
10664 const char *name;
10665 const char *env;
10666 int ref;
10667 int len;
Christopher Faulet5c028d72021-04-12 15:11:44 +020010668 struct hlua_function *fcn = NULL;
Thierry Fournierf67442e2020-11-28 20:41:07 +010010669 struct buffer *trash;
10670 struct action_kw *akw;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010671
10672 MAY_LJMP(check_args(L, 3, "register_service"));
10673
Aurelien DARRAGON87f52972023-02-24 09:43:54 +010010674 if (hlua_gethlua(L)) {
10675 /* runtime processing */
10676 WILL_LJMP(luaL_error(L, "register_service: not available outside of body context"));
10677 }
10678
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010679 /* First argument : converter name. */
10680 name = MAY_LJMP(luaL_checkstring(L, 1));
10681
10682 /* Second argument : environment. */
10683 env = MAY_LJMP(luaL_checkstring(L, 2));
10684
10685 /* Third argument : lua function. */
10686 ref = MAY_LJMP(hlua_checkfunction(L, 3));
10687
Thierry Fournierf67442e2020-11-28 20:41:07 +010010688 /* Check for service already registered */
10689 trash = get_trash_chunk();
10690 chunk_printf(trash, "lua.%s", name);
10691 akw = service_find(trash->area);
10692 if (akw != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +010010693 fcn = akw->private;
10694 if (fcn->function_ref[hlua_state_id] != -1) {
10695 ha_warning("Trying to register service 'lua.%s' more than once. "
10696 "This will become a hard error in version 2.5.\n", name);
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +010010697 hlua_unref(L, fcn->function_ref[hlua_state_id]);
Thierry Fournier59f11be2020-11-29 00:37:41 +010010698 }
10699 fcn->function_ref[hlua_state_id] = ref;
10700 return 0;
Thierry Fournierf67442e2020-11-28 20:41:07 +010010701 }
10702
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010703 /* Allocate and fill the sample fetch keyword struct. */
10704 akl = calloc(1, sizeof(*akl) + sizeof(struct action_kw) * 2);
10705 if (!akl)
Christopher Faulet5c028d72021-04-12 15:11:44 +020010706 goto alloc_error;
Thierry Fournier62a22aa2020-11-28 21:06:35 +010010707 fcn = new_hlua_function();
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010708 if (!fcn)
Christopher Faulet5c028d72021-04-12 15:11:44 +020010709 goto alloc_error;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010710
10711 /* Fill fcn. */
10712 len = strlen("<lua.>") + strlen(name) + 1;
10713 fcn->name = calloc(1, len);
10714 if (!fcn->name)
Christopher Faulet5c028d72021-04-12 15:11:44 +020010715 goto alloc_error;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010716 snprintf((char *)fcn->name, len, "<lua.%s>", name);
Thierry Fournierc7492592020-11-28 23:57:24 +010010717 fcn->function_ref[hlua_state_id] = ref;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010718
10719 /* List head */
10720 akl->list.n = akl->list.p = NULL;
10721
10722 /* converter keyword. */
10723 len = strlen("lua.") + strlen(name) + 1;
10724 akl->kw[0].kw = calloc(1, len);
10725 if (!akl->kw[0].kw)
Christopher Faulet5c028d72021-04-12 15:11:44 +020010726 goto alloc_error;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010727
10728 snprintf((char *)akl->kw[0].kw, len, "lua.%s", name);
10729
Thierry FOURNIER / OZON.IO02564fd2016-11-12 11:07:05 +010010730 /* Check required environment. Only accepted "http" or "tcp". */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010731 if (strcmp(env, "tcp") == 0)
10732 akl->kw[0].parse = action_register_service_tcp;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010733 else if (strcmp(env, "http") == 0)
10734 akl->kw[0].parse = action_register_service_http;
Christopher Faulet5c028d72021-04-12 15:11:44 +020010735 else {
10736 release_hlua_function(fcn);
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +010010737 hlua_unref(L, ref);
Christopher Faulet5c028d72021-04-12 15:11:44 +020010738 if (akl)
10739 ha_free((char **)&(akl->kw[0].kw));
10740 ha_free(&akl);
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +010010741 WILL_LJMP(luaL_error(L, "Lua service environment '%s' is unknown. "
Eric Salamafe7456f2017-12-21 14:30:07 +010010742 "'tcp' or 'http' are expected.", env));
Christopher Faulet5c028d72021-04-12 15:11:44 +020010743 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010744
Amaury Denoyellee4a617c2021-05-06 15:33:09 +020010745 akl->kw[0].flags = 0;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010746 akl->kw[0].private = fcn;
10747
10748 /* End of array. */
10749 memset(&akl->kw[1], 0, sizeof(*akl->kw));
10750
10751 /* Register this new converter */
10752 service_keywords_register(akl);
10753
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010754 return 0;
Christopher Faulet5c028d72021-04-12 15:11:44 +020010755
10756 alloc_error:
10757 release_hlua_function(fcn);
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +010010758 hlua_unref(L, ref);
Christopher Faulet5c028d72021-04-12 15:11:44 +020010759 ha_free(&akl);
10760 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
10761 return 0; /* Never reached */
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010762}
10763
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010764/* This function initialises Lua cli handler. It copies the
10765 * arguments in the Lua stack and create channel IO objects.
10766 */
Aurélien Nephtaliabbf6072018-04-18 13:26:46 +020010767static int hlua_cli_parse_fct(char **args, char *payload, struct appctx *appctx, void *private)
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010768{
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010769 struct hlua_cli_ctx *ctx = applet_reserve_svcctx(appctx, sizeof(*ctx));
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010770 struct hlua *hlua;
10771 struct hlua_function *fcn;
10772 int i;
10773 const char *error;
10774
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010775 fcn = private;
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010776 ctx->fcn = private;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +010010777
Willy Tarreaubafbe012017-11-24 17:34:44 +010010778 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +010010779 if (!hlua) {
10780 SEND_ERR(NULL, "Lua cli '%s': out of memory.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +010010781 return 1;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +010010782 }
10783 HLUA_INIT(hlua);
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010784 ctx->hlua = hlua;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010785
10786 /* Create task used by signal to wakeup applets.
Ilya Shipitsind4259502020-04-08 01:07:56 +050010787 * We use the same wakeup function than the Lua applet_tcp and
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010788 * applet_http. It is absolutely compatible.
10789 */
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010790 ctx->task = task_new_here();
10791 if (!ctx->task) {
Thierry FOURNIERffbf5692016-12-16 11:14:06 +010010792 SEND_ERR(NULL, "Lua cli '%s': out of memory.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +010010793 goto error;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010794 }
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010795 ctx->task->nice = 0;
10796 ctx->task->context = appctx;
10797 ctx->task->process = hlua_applet_wakeup;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010798
10799 /* Initialises the Lua context */
Aurelien DARRAGON6b0b9bd2023-03-21 14:02:16 +010010800 if (!hlua_ctx_init(hlua, fcn_ref_to_stack_id(fcn), ctx->task)) {
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010801 SEND_ERR(NULL, "Lua cli '%s': can't initialize Lua context.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +010010802 goto error;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010803 }
10804
10805 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010806 if (!SET_SAFE_LJMP(hlua)) {
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010807 if (lua_type(hlua->T, -1) == LUA_TSTRING)
10808 error = lua_tostring(hlua->T, -1);
10809 else
10810 error = "critical error";
10811 SEND_ERR(NULL, "Lua cli '%s': %s.\n", fcn->name, error);
10812 goto error;
10813 }
10814
10815 /* Check stack available size. */
10816 if (!lua_checkstack(hlua->T, 2)) {
10817 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
10818 goto error;
10819 }
10820
10821 /* Restore the function in the stack. */
Aurelien DARRAGON4fdf8b52023-03-20 17:22:37 +010010822 hlua_pushref(hlua->T, fcn->function_ref[hlua->state_id]);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010823
10824 /* Once the arguments parsed, the CLI is like an AppletTCP,
10825 * so push AppletTCP in the stack.
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010826 */
10827 if (!hlua_applet_tcp_new(hlua->T, appctx)) {
10828 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
10829 goto error;
10830 }
10831 hlua->nargs = 1;
10832
10833 /* push keywords in the stack. */
10834 for (i = 0; *args[i]; i++) {
10835 /* Check stack available size. */
10836 if (!lua_checkstack(hlua->T, 1)) {
10837 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
10838 goto error;
10839 }
10840 lua_pushstring(hlua->T, args[i]);
10841 hlua->nargs++;
10842 }
10843
10844 /* We must initialize the execution timeouts. */
10845 hlua->max_time = hlua_timeout_session;
10846
10847 /* At this point the execution is safe. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010848 RESET_SAFE_LJMP(hlua);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010849
10850 /* It's ok */
10851 return 0;
10852
10853 /* It's not ok. */
10854error:
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010855 RESET_SAFE_LJMP(hlua);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010856 hlua_ctx_destroy(hlua);
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010857 ctx->hlua = NULL;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010858 return 1;
10859}
10860
10861static int hlua_cli_io_handler_fct(struct appctx *appctx)
10862{
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010863 struct hlua_cli_ctx *ctx = appctx->svcctx;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010864 struct hlua *hlua;
Willy Tarreau475e4632022-05-27 10:26:46 +020010865 struct stconn *sc;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010866 struct hlua_function *fcn;
10867
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010868 hlua = ctx->hlua;
Willy Tarreauc12b3212022-05-27 11:08:15 +020010869 sc = appctx_sc(appctx);
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010870 fcn = ctx->fcn;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010871
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010872 /* Execute the function. */
10873 switch (hlua_ctx_resume(hlua, 1)) {
10874
10875 /* finished. */
10876 case HLUA_E_OK:
10877 return 1;
10878
10879 /* yield. */
10880 case HLUA_E_AGAIN:
10881 /* We want write. */
10882 if (HLUA_IS_WAKERESWR(hlua))
Willy Tarreau475e4632022-05-27 10:26:46 +020010883 sc_need_room(sc);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010884 /* Set the timeout. */
10885 if (hlua->wake_time != TICK_ETERNITY)
10886 task_schedule(hlua->task, hlua->wake_time);
10887 return 0;
10888
10889 /* finished with error. */
10890 case HLUA_E_ERRMSG:
10891 /* Display log. */
10892 SEND_ERR(NULL, "Lua cli '%s': %s.\n",
10893 fcn->name, lua_tostring(hlua->T, -1));
10894 lua_pop(hlua->T, 1);
10895 return 1;
10896
Thierry Fournierd5b073c2018-05-21 19:42:47 +020010897 case HLUA_E_ETMOUT:
10898 SEND_ERR(NULL, "Lua converter '%s': execution timeout.\n",
10899 fcn->name);
10900 return 1;
10901
10902 case HLUA_E_NOMEM:
10903 SEND_ERR(NULL, "Lua converter '%s': out of memory error.\n",
10904 fcn->name);
10905 return 1;
10906
10907 case HLUA_E_YIELD: /* unexpected */
10908 SEND_ERR(NULL, "Lua converter '%s': yield not allowed.\n",
10909 fcn->name);
10910 return 1;
10911
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010912 case HLUA_E_ERR:
10913 /* Display log. */
10914 SEND_ERR(NULL, "Lua cli '%s' return an unknown error.\n",
10915 fcn->name);
10916 return 1;
10917
10918 default:
10919 return 1;
10920 }
10921
10922 return 1;
10923}
10924
10925static void hlua_cli_io_release_fct(struct appctx *appctx)
10926{
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010927 struct hlua_cli_ctx *ctx = appctx->svcctx;
10928
10929 hlua_ctx_destroy(ctx->hlua);
10930 ctx->hlua = NULL;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010931}
10932
10933/* This function is an LUA binding used for registering
10934 * new keywords in the cli. It expects a list of keywords
10935 * which are the "path". It is limited to 5 keywords. A
10936 * description of the command, a function to be executed
10937 * for the parsing and a function for io handlers.
10938 */
10939__LJMP static int hlua_register_cli(lua_State *L)
10940{
10941 struct cli_kw_list *cli_kws;
10942 const char *message;
10943 int ref_io;
10944 int len;
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010945 struct hlua_function *fcn = NULL;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010946 int index;
10947 int i;
Thierry Fournierf67442e2020-11-28 20:41:07 +010010948 struct buffer *trash;
10949 const char *kw[5];
10950 struct cli_kw *cli_kw;
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010951 const char *errmsg;
Willy Tarreau22450af2023-04-07 15:27:55 +020010952 char *end;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010953
10954 MAY_LJMP(check_args(L, 3, "register_cli"));
10955
Aurelien DARRAGON87f52972023-02-24 09:43:54 +010010956 if (hlua_gethlua(L)) {
10957 /* runtime processing */
10958 WILL_LJMP(luaL_error(L, "register_cli: not available outside of body context"));
10959 }
10960
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010961 /* First argument : an array of maximum 5 keywords. */
10962 if (!lua_istable(L, 1))
10963 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table"));
10964
10965 /* Second argument : string with contextual message. */
10966 message = MAY_LJMP(luaL_checkstring(L, 2));
10967
10968 /* Third and fourth argument : lua function. */
10969 ref_io = MAY_LJMP(hlua_checkfunction(L, 3));
10970
Thierry Fournierf67442e2020-11-28 20:41:07 +010010971 /* Check for CLI service already registered */
10972 trash = get_trash_chunk();
10973 index = 0;
10974 lua_pushnil(L);
10975 memset(kw, 0, sizeof(kw));
10976 while (lua_next(L, 1) != 0) {
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +010010977 if (index >= CLI_PREFIX_KW_NB) {
10978 hlua_unref(L, ref_io);
Thierry Fournierf67442e2020-11-28 20:41:07 +010010979 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 +010010980 }
10981 if (lua_type(L, -1) != LUA_TSTRING) {
10982 hlua_unref(L, ref_io);
Thierry Fournierf67442e2020-11-28 20:41:07 +010010983 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table filled with strings"));
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +010010984 }
Thierry Fournierf67442e2020-11-28 20:41:07 +010010985 kw[index] = lua_tostring(L, -1);
10986 if (index == 0)
10987 chunk_printf(trash, "%s", kw[index]);
10988 else
10989 chunk_appendf(trash, " %s", kw[index]);
10990 index++;
10991 lua_pop(L, 1);
10992 }
10993 cli_kw = cli_find_kw_exact((char **)kw);
10994 if (cli_kw != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +010010995 fcn = cli_kw->private;
10996 if (fcn->function_ref[hlua_state_id] != -1) {
10997 ha_warning("Trying to register CLI keyword 'lua.%s' more than once. "
10998 "This will become a hard error in version 2.5.\n", trash->area);
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +010010999 hlua_unref(L, fcn->function_ref[hlua_state_id]);
Thierry Fournier59f11be2020-11-29 00:37:41 +010011000 }
11001 fcn->function_ref[hlua_state_id] = ref_io;
11002 return 0;
Thierry Fournierf67442e2020-11-28 20:41:07 +010011003 }
11004
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011005 /* Allocate and fill the sample fetch keyword struct. */
11006 cli_kws = calloc(1, sizeof(*cli_kws) + sizeof(struct cli_kw) * 2);
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020011007 if (!cli_kws) {
11008 errmsg = "Lua out of memory error.";
11009 goto error;
11010 }
Thierry Fournier62a22aa2020-11-28 21:06:35 +010011011 fcn = new_hlua_function();
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020011012 if (!fcn) {
11013 errmsg = "Lua out of memory error.";
11014 goto error;
11015 }
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011016
11017 /* Fill path. */
11018 index = 0;
11019 lua_pushnil(L);
11020 while(lua_next(L, 1) != 0) {
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020011021 if (index >= 5) {
11022 errmsg = "1st argument must be a table with a maximum of 5 entries";
11023 goto error;
11024 }
11025 if (lua_type(L, -1) != LUA_TSTRING) {
11026 errmsg = "1st argument must be a table filled with strings";
11027 goto error;
11028 }
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011029 cli_kws->kw[0].str_kw[index] = strdup(lua_tostring(L, -1));
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020011030 if (!cli_kws->kw[0].str_kw[index]) {
11031 errmsg = "Lua out of memory error.";
11032 goto error;
11033 }
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011034 index++;
11035 lua_pop(L, 1);
11036 }
11037
11038 /* Copy help message. */
11039 cli_kws->kw[0].usage = strdup(message);
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020011040 if (!cli_kws->kw[0].usage) {
11041 errmsg = "Lua out of memory error.";
11042 goto error;
11043 }
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011044
11045 /* Fill fcn io handler. */
11046 len = strlen("<lua.cli>") + 1;
11047 for (i = 0; i < index; i++)
11048 len += strlen(cli_kws->kw[0].str_kw[i]) + 1;
11049 fcn->name = calloc(1, len);
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020011050 if (!fcn->name) {
11051 errmsg = "Lua out of memory error.";
11052 goto error;
11053 }
Willy Tarreau22450af2023-04-07 15:27:55 +020011054
11055 end = fcn->name;
11056 len = 8;
11057 memcpy(end, "<lua.cli", len);
11058 end += len;
11059
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011060 for (i = 0; i < index; i++) {
Willy Tarreau22450af2023-04-07 15:27:55 +020011061 *(end++) = '.';
11062 len = strlen(cli_kws->kw[0].str_kw[i]);
11063 memcpy(end, cli_kws->kw[0].str_kw[i], len);
11064 end += len;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011065 }
Willy Tarreau22450af2023-04-07 15:27:55 +020011066 *(end++) = '>';
11067 *(end++) = 0;
11068
Thierry Fournierc7492592020-11-28 23:57:24 +010011069 fcn->function_ref[hlua_state_id] = ref_io;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011070
11071 /* Fill last entries. */
11072 cli_kws->kw[0].private = fcn;
11073 cli_kws->kw[0].parse = hlua_cli_parse_fct;
11074 cli_kws->kw[0].io_handler = hlua_cli_io_handler_fct;
11075 cli_kws->kw[0].io_release = hlua_cli_io_release_fct;
11076
11077 /* Register this new converter */
11078 cli_register_kw(cli_kws);
11079
11080 return 0;
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020011081
11082 error:
11083 release_hlua_function(fcn);
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +010011084 hlua_unref(L, ref_io);
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020011085 if (cli_kws) {
11086 for (i = 0; i < index; i++)
11087 ha_free((char **)&(cli_kws->kw[0].str_kw[i]));
11088 ha_free((char **)&(cli_kws->kw[0].usage));
11089 }
11090 ha_free(&cli_kws);
11091 WILL_LJMP(luaL_error(L, errmsg));
11092 return 0; /* Never reached */
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011093}
11094
Christopher Faulet69c581a2021-05-31 08:54:04 +020011095static int hlua_filter_init_per_thread(struct proxy *px, struct flt_conf *fconf)
11096{
11097 struct hlua_flt_config *conf = fconf->conf;
11098 lua_State *L;
11099 int error, pos, state_id, flt_ref;
11100
11101 state_id = reg_flt_to_stack_id(conf->reg);
11102 L = hlua_states[state_id];
11103 pos = lua_gettop(L);
11104
11105 /* The filter parsing function */
Aurelien DARRAGON4fdf8b52023-03-20 17:22:37 +010011106 hlua_pushref(L, conf->reg->fun_ref[state_id]);
Christopher Faulet69c581a2021-05-31 08:54:04 +020011107
11108 /* Push the filter class on the stack and resolve all callbacks */
Aurelien DARRAGON4fdf8b52023-03-20 17:22:37 +010011109 hlua_pushref(L, conf->reg->flt_ref[state_id]);
Christopher Faulet69c581a2021-05-31 08:54:04 +020011110
11111 /* Duplicate the filter class so each filter will have its own copy */
11112 lua_newtable(L);
11113 lua_pushnil(L);
11114
11115 while (lua_next(L, pos+2)) {
11116 lua_pushvalue(L, -2);
11117 lua_insert(L, -2);
11118 lua_settable(L, -4);
11119 }
Aurelien DARRAGON73d1a982023-03-20 17:42:08 +010011120 flt_ref = hlua_ref(L);
Christopher Faulet69c581a2021-05-31 08:54:04 +020011121
11122 /* Remove the original lua filter class from the stack */
11123 lua_pop(L, 1);
11124
11125 /* Push the copy on the stack */
Aurelien DARRAGON4fdf8b52023-03-20 17:22:37 +010011126 hlua_pushref(L, flt_ref);
Christopher Faulet69c581a2021-05-31 08:54:04 +020011127
11128 /* extra args are pushed in a table */
11129 lua_newtable(L);
11130 for (pos = 0; conf->args[pos]; pos++) {
11131 /* Check stack available size. */
11132 if (!lua_checkstack(L, 1)) {
11133 ha_alert("Lua filter '%s' : Lua error : full stack.", conf->reg->name);
11134 goto error;
11135 }
11136 lua_pushstring(L, conf->args[pos]);
11137 lua_rawseti(L, -2, lua_rawlen(L, -2) + 1);
11138 }
11139
11140 error = lua_pcall(L, 2, LUA_MULTRET, 0);
11141 switch (error) {
11142 case LUA_OK:
11143 /* replace the filter ref */
11144 conf->ref[state_id] = flt_ref;
11145 break;
11146 case LUA_ERRRUN:
11147 ha_alert("Lua filter '%s' : runtime error : %s", conf->reg->name, lua_tostring(L, -1));
11148 goto error;
11149 case LUA_ERRMEM:
11150 ha_alert("Lua filter '%s' : out of memory error", conf->reg->name);
11151 goto error;
11152 case LUA_ERRERR:
11153 ha_alert("Lua filter '%s' : message handler error : %s", conf->reg->name, lua_tostring(L, -1));
11154 goto error;
11155#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM <= 503
11156 case LUA_ERRGCMM:
11157 ha_alert("Lua filter '%s' : garbage collector error : %s", conf->reg->name, lua_tostring(L, -1));
11158 goto error;
11159#endif
11160 default:
Ilya Shipitsinff0f2782021-08-22 22:18:07 +050011161 ha_alert("Lua filter '%s' : unknown error : %s", conf->reg->name, lua_tostring(L, -1));
Christopher Faulet69c581a2021-05-31 08:54:04 +020011162 goto error;
11163 }
11164
11165 lua_settop(L, 0);
11166 return 0;
11167
11168 error:
11169 lua_settop(L, 0);
11170 return -1;
11171}
11172
11173static void hlua_filter_deinit_per_thread(struct proxy *px, struct flt_conf *fconf)
11174{
11175 struct hlua_flt_config *conf = fconf->conf;
11176 lua_State *L;
11177 int state_id;
11178
11179 if (!conf)
11180 return;
11181
11182 state_id = reg_flt_to_stack_id(conf->reg);
11183 L = hlua_states[state_id];
Aurelien DARRAGONfde199d2023-03-20 15:09:33 +010011184 hlua_unref(L, conf->ref[state_id]);
Christopher Faulet69c581a2021-05-31 08:54:04 +020011185}
11186
11187static int hlua_filter_init(struct proxy *px, struct flt_conf *fconf)
11188{
11189 struct hlua_flt_config *conf = fconf->conf;
11190 int state_id = reg_flt_to_stack_id(conf->reg);
11191
11192 /* Rely on per-thread init for global scripts */
11193 if (!state_id)
11194 return hlua_filter_init_per_thread(px, fconf);
11195 return 0;
11196}
11197
11198static void hlua_filter_deinit(struct proxy *px, struct flt_conf *fconf)
11199{
11200
11201 if (fconf->conf) {
11202 struct hlua_flt_config *conf = fconf->conf;
11203 int state_id = reg_flt_to_stack_id(conf->reg);
11204 int pos;
11205
11206 /* Rely on per-thread deinit for global scripts */
11207 if (!state_id)
11208 hlua_filter_deinit_per_thread(px, fconf);
11209
11210 for (pos = 0; conf->args[pos]; pos++)
11211 free(conf->args[pos]);
11212 free(conf->args);
11213 }
11214 ha_free(&fconf->conf);
11215 ha_free((char **)&fconf->id);
11216 ha_free(&fconf->ops);
11217}
11218
11219static int hlua_filter_new(struct stream *s, struct filter *filter)
11220{
11221 struct hlua_flt_config *conf = FLT_CONF(filter);
11222 struct hlua_flt_ctx *flt_ctx = NULL;
11223 int ret = 1;
11224
11225 /* In the execution wrappers linked with a stream, the
11226 * Lua context can be not initialized. This behavior
11227 * permits to save performances because a systematic
11228 * Lua initialization cause 5% performances loss.
11229 */
11230 if (!s->hlua) {
11231 struct hlua *hlua;
11232
11233 hlua = pool_alloc(pool_head_hlua);
11234 if (!hlua) {
11235 SEND_ERR(s->be, "Lua filter '%s': can't initialize Lua context.\n",
11236 conf->reg->name);
11237 ret = 0;
11238 goto end;
11239 }
11240 HLUA_INIT(hlua);
11241 s->hlua = hlua;
Aurelien DARRAGON6b0b9bd2023-03-21 14:02:16 +010011242 if (!hlua_ctx_init(s->hlua, reg_flt_to_stack_id(conf->reg), s->task)) {
Christopher Faulet69c581a2021-05-31 08:54:04 +020011243 SEND_ERR(s->be, "Lua filter '%s': can't initialize Lua context.\n",
11244 conf->reg->name);
11245 ret = 0;
11246 goto end;
11247 }
11248 }
11249
11250 flt_ctx = pool_zalloc(pool_head_hlua_flt_ctx);
11251 if (!flt_ctx) {
11252 SEND_ERR(s->be, "Lua filter '%s': can't initialize filter Lua context.\n",
11253 conf->reg->name);
11254 ret = 0;
11255 goto end;
11256 }
11257 flt_ctx->hlua[0] = pool_alloc(pool_head_hlua);
11258 flt_ctx->hlua[1] = pool_alloc(pool_head_hlua);
11259 if (!flt_ctx->hlua[0] || !flt_ctx->hlua[1]) {
11260 SEND_ERR(s->be, "Lua filter '%s': can't initialize filter Lua context.\n",
11261 conf->reg->name);
11262 ret = 0;
11263 goto end;
11264 }
11265 HLUA_INIT(flt_ctx->hlua[0]);
11266 HLUA_INIT(flt_ctx->hlua[1]);
Aurelien DARRAGON6b0b9bd2023-03-21 14:02:16 +010011267 if (!hlua_ctx_init(flt_ctx->hlua[0], reg_flt_to_stack_id(conf->reg), s->task) ||
11268 !hlua_ctx_init(flt_ctx->hlua[1], reg_flt_to_stack_id(conf->reg), s->task)) {
Christopher Faulet69c581a2021-05-31 08:54:04 +020011269 SEND_ERR(s->be, "Lua filter '%s': can't initialize filter Lua context.\n",
11270 conf->reg->name);
11271 ret = 0;
11272 goto end;
11273 }
11274
11275 if (!HLUA_IS_RUNNING(s->hlua)) {
11276 /* The following Lua calls can fail. */
11277 if (!SET_SAFE_LJMP(s->hlua)) {
11278 const char *error;
11279
11280 if (lua_type(s->hlua->T, -1) == LUA_TSTRING)
11281 error = lua_tostring(s->hlua->T, -1);
11282 else
11283 error = "critical error";
11284 SEND_ERR(s->be, "Lua filter '%s': %s.\n", conf->reg->name, error);
11285 ret = 0;
11286 goto end;
11287 }
11288
11289 /* Check stack size. */
11290 if (!lua_checkstack(s->hlua->T, 1)) {
11291 SEND_ERR(s->be, "Lua filter '%s': full stack.\n", conf->reg->name);
Tim Duesterhus22817382021-09-11 23:17:25 +020011292 RESET_SAFE_LJMP(s->hlua);
Christopher Faulet69c581a2021-05-31 08:54:04 +020011293 ret = 0;
11294 goto end;
11295 }
11296
Aurelien DARRAGON4fdf8b52023-03-20 17:22:37 +010011297 hlua_pushref(s->hlua->T, conf->ref[s->hlua->state_id]);
Christopher Faulet69c581a2021-05-31 08:54:04 +020011298 if (lua_getfield(s->hlua->T, -1, "new") != LUA_TFUNCTION) {
11299 SEND_ERR(s->be, "Lua filter '%s': 'new' field is not a function.\n",
11300 conf->reg->name);
11301 RESET_SAFE_LJMP(s->hlua);
11302 ret = 0;
11303 goto end;
11304 }
11305 lua_insert(s->hlua->T, -2);
11306
11307 /* Push the copy on the stack */
11308 s->hlua->nargs = 1;
11309
11310 /* We must initialize the execution timeouts. */
11311 s->hlua->max_time = hlua_timeout_session;
11312
11313 /* At this point the execution is safe. */
11314 RESET_SAFE_LJMP(s->hlua);
11315 }
11316
11317 switch (hlua_ctx_resume(s->hlua, 0)) {
11318 case HLUA_E_OK:
11319 /* Nothing returned or not a table, ignore the filter for current stream */
11320 if (!lua_gettop(s->hlua->T) || !lua_istable(s->hlua->T, 1)) {
11321 ret = 0;
11322 goto end;
11323 }
11324
11325 /* Attached the filter pointer to the ctx */
11326 lua_pushstring(s->hlua->T, "__filter");
11327 lua_pushlightuserdata(s->hlua->T, filter);
11328 lua_settable(s->hlua->T, -3);
11329
11330 /* Save a ref on the filter ctx */
11331 lua_pushvalue(s->hlua->T, 1);
Aurelien DARRAGON73d1a982023-03-20 17:42:08 +010011332 flt_ctx->ref = hlua_ref(s->hlua->T);
Christopher Faulet69c581a2021-05-31 08:54:04 +020011333 filter->ctx = flt_ctx;
11334 break;
11335 case HLUA_E_ERRMSG:
11336 SEND_ERR(s->be, "Lua filter '%s' : %s.\n", conf->reg->name, lua_tostring(s->hlua->T, -1));
11337 ret = -1;
11338 goto end;
11339 case HLUA_E_ETMOUT:
11340 SEND_ERR(s->be, "Lua filter '%s' : 'new' execution timeout.\n", conf->reg->name);
11341 ret = 0;
11342 goto end;
11343 case HLUA_E_NOMEM:
11344 SEND_ERR(s->be, "Lua filter '%s' : out of memory error.\n", conf->reg->name);
11345 ret = 0;
11346 goto end;
11347 case HLUA_E_AGAIN:
11348 case HLUA_E_YIELD:
11349 SEND_ERR(s->be, "Lua filter '%s': yield functions like core.tcp() or core.sleep()"
11350 " are not allowed from 'new' function.\n", conf->reg->name);
11351 ret = 0;
11352 goto end;
11353 case HLUA_E_ERR:
11354 SEND_ERR(s->be, "Lua filter '%s': 'new' returns an unknown error.\n", conf->reg->name);
11355 ret = 0;
11356 goto end;
11357 default:
11358 ret = 0;
11359 goto end;
11360 }
11361
11362 end:
11363 if (s->hlua)
11364 lua_settop(s->hlua->T, 0);
11365 if (ret <= 0) {
11366 if (flt_ctx) {
11367 hlua_ctx_destroy(flt_ctx->hlua[0]);
11368 hlua_ctx_destroy(flt_ctx->hlua[1]);
11369 pool_free(pool_head_hlua_flt_ctx, flt_ctx);
11370 }
11371 }
11372 return ret;
11373}
11374
11375static void hlua_filter_delete(struct stream *s, struct filter *filter)
11376{
11377 struct hlua_flt_ctx *flt_ctx = filter->ctx;
11378
Aurelien DARRAGONfde199d2023-03-20 15:09:33 +010011379 hlua_unref(s->hlua->T, flt_ctx->ref);
Christopher Faulet69c581a2021-05-31 08:54:04 +020011380 hlua_ctx_destroy(flt_ctx->hlua[0]);
11381 hlua_ctx_destroy(flt_ctx->hlua[1]);
11382 pool_free(pool_head_hlua_flt_ctx, flt_ctx);
11383 filter->ctx = NULL;
11384}
11385
Christopher Faulet9f55a502020-02-25 15:21:02 +010011386static int hlua_filter_from_payload(struct filter *filter)
11387{
11388 struct hlua_flt_ctx *flt_ctx = filter->ctx;
11389
11390 return (flt_ctx && !!(flt_ctx->flags & HLUA_FLT_CTX_FL_PAYLOAD));
11391}
11392
Christopher Fauletc404f112020-02-26 15:03:09 +010011393static int hlua_filter_callback(struct stream *s, struct filter *filter, const char *fun,
11394 int dir, unsigned int flags)
11395{
11396 struct hlua *flt_hlua;
11397 struct hlua_flt_config *conf = FLT_CONF(filter);
11398 struct hlua_flt_ctx *flt_ctx = filter->ctx;
11399 unsigned int hflags = HLUA_TXN_FLT_CTX;
11400 int ret = 1;
11401
11402 flt_hlua = flt_ctx->hlua[(dir == SMP_OPT_DIR_REQ ? 0 : 1)];
11403 if (!flt_hlua)
11404 goto end;
11405
11406 if (!HLUA_IS_RUNNING(flt_hlua)) {
11407 int extra_idx = lua_gettop(flt_hlua->T);
11408
11409 /* The following Lua calls can fail. */
11410 if (!SET_SAFE_LJMP(flt_hlua)) {
11411 const char *error;
11412
11413 if (lua_type(flt_hlua->T, -1) == LUA_TSTRING)
11414 error = lua_tostring(flt_hlua->T, -1);
11415 else
11416 error = "critical error";
11417 SEND_ERR(s->be, "Lua filter '%s': %s.\n", conf->reg->name, error);
11418 goto end;
11419 }
11420
11421 /* Check stack size. */
11422 if (!lua_checkstack(flt_hlua->T, 3)) {
11423 SEND_ERR(s->be, "Lua filter '%s': full stack.\n", conf->reg->name);
11424 RESET_SAFE_LJMP(flt_hlua);
11425 goto end;
11426 }
11427
Aurelien DARRAGON4fdf8b52023-03-20 17:22:37 +010011428 hlua_pushref(flt_hlua->T, flt_ctx->ref);
Christopher Fauletc404f112020-02-26 15:03:09 +010011429 if (lua_getfield(flt_hlua->T, -1, fun) != LUA_TFUNCTION) {
11430 RESET_SAFE_LJMP(flt_hlua);
11431 goto end;
11432 }
11433 lua_insert(flt_hlua->T, -2);
11434
11435 if (!hlua_txn_new(flt_hlua->T, s, s->be, dir, hflags)) {
11436 SEND_ERR(s->be, "Lua filter '%s': full stack.\n", conf->reg->name);
11437 RESET_SAFE_LJMP(flt_hlua);
11438 goto end;
11439 }
11440 flt_hlua->nargs = 2;
11441
11442 if (flags & HLUA_FLT_CB_ARG_CHN) {
11443 if (dir == SMP_OPT_DIR_REQ)
11444 lua_getfield(flt_hlua->T, -1, "req");
11445 else
11446 lua_getfield(flt_hlua->T, -1, "res");
11447 if (lua_type(flt_hlua->T, -1) == LUA_TTABLE) {
11448 lua_pushstring(flt_hlua->T, "__filter");
11449 lua_pushlightuserdata(flt_hlua->T, filter);
11450 lua_settable(flt_hlua->T, -3);
11451 }
11452 flt_hlua->nargs++;
11453 }
11454 else if (flags & HLUA_FLT_CB_ARG_HTTP_MSG) {
Christopher Fauleteae8afa2020-02-26 17:15:48 +010011455 if (dir == SMP_OPT_DIR_REQ)
11456 lua_getfield(flt_hlua->T, -1, "http_req");
11457 else
11458 lua_getfield(flt_hlua->T, -1, "http_res");
11459 if (lua_type(flt_hlua->T, -1) == LUA_TTABLE) {
11460 lua_pushstring(flt_hlua->T, "__filter");
11461 lua_pushlightuserdata(flt_hlua->T, filter);
11462 lua_settable(flt_hlua->T, -3);
11463 }
11464 flt_hlua->nargs++;
Christopher Fauletc404f112020-02-26 15:03:09 +010011465 }
11466
11467 /* Check stack size. */
11468 if (!lua_checkstack(flt_hlua->T, 1)) {
11469 SEND_ERR(s->be, "Lua filter '%s': full stack.\n", conf->reg->name);
11470 RESET_SAFE_LJMP(flt_hlua);
11471 goto end;
11472 }
11473
11474 while (extra_idx--) {
11475 lua_pushvalue(flt_hlua->T, 1);
11476 lua_remove(flt_hlua->T, 1);
11477 flt_hlua->nargs++;
11478 }
11479
11480 /* We must initialize the execution timeouts. */
11481 flt_hlua->max_time = hlua_timeout_session;
11482
11483 /* At this point the execution is safe. */
11484 RESET_SAFE_LJMP(flt_hlua);
11485 }
11486
11487 switch (hlua_ctx_resume(flt_hlua, !(flags & HLUA_FLT_CB_FINAL))) {
11488 case HLUA_E_OK:
11489 /* Catch the return value if it required */
11490 if ((flags & HLUA_FLT_CB_RETVAL) && lua_gettop(flt_hlua->T) > 0) {
11491 ret = lua_tointeger(flt_hlua->T, -1);
11492 lua_settop(flt_hlua->T, 0); /* Empty the stack. */
11493 }
11494
11495 /* Set timeout in the required channel. */
11496 if (flt_hlua->wake_time != TICK_ETERNITY) {
11497 if (dir == SMP_OPT_DIR_REQ)
11498 s->req.analyse_exp = flt_hlua->wake_time;
11499 else
11500 s->res.analyse_exp = flt_hlua->wake_time;
11501 }
11502 break;
11503 case HLUA_E_AGAIN:
11504 /* Set timeout in the required channel. */
11505 if (flt_hlua->wake_time != TICK_ETERNITY) {
11506 if (dir == SMP_OPT_DIR_REQ)
11507 s->req.analyse_exp = flt_hlua->wake_time;
11508 else
11509 s->res.analyse_exp = flt_hlua->wake_time;
11510 }
11511 /* Some actions can be wake up when a "write" event
11512 * is detected on a response channel. This is useful
11513 * only for actions targeted on the requests.
11514 */
11515 if (HLUA_IS_WAKERESWR(flt_hlua))
11516 s->res.flags |= CF_WAKE_WRITE;
11517 if (HLUA_IS_WAKEREQWR(flt_hlua))
11518 s->req.flags |= CF_WAKE_WRITE;
11519 ret = 0;
11520 goto end;
11521 case HLUA_E_ERRMSG:
11522 SEND_ERR(s->be, "Lua filter '%s' : %s.\n", conf->reg->name, lua_tostring(flt_hlua->T, -1));
11523 ret = -1;
11524 goto end;
11525 case HLUA_E_ETMOUT:
11526 SEND_ERR(s->be, "Lua filter '%s' : '%s' callback execution timeout.\n", conf->reg->name, fun);
11527 goto end;
11528 case HLUA_E_NOMEM:
11529 SEND_ERR(s->be, "Lua filter '%s' : out of memory error.\n", conf->reg->name);
11530 goto end;
11531 case HLUA_E_YIELD:
11532 SEND_ERR(s->be, "Lua filter '%s': yield functions like core.tcp() or core.sleep()"
11533 " are not allowed from '%s' callback.\n", conf->reg->name, fun);
11534 goto end;
11535 case HLUA_E_ERR:
11536 SEND_ERR(s->be, "Lua filter '%s': '%s' returns an unknown error.\n", conf->reg->name, fun);
11537 goto end;
11538 default:
11539 goto end;
11540 }
11541
11542
11543 end:
11544 return ret;
11545}
11546
11547static int hlua_filter_start_analyze(struct stream *s, struct filter *filter, struct channel *chn)
11548{
11549 struct hlua_flt_ctx *flt_ctx = filter->ctx;
11550
11551 flt_ctx->flags = 0;
11552 return hlua_filter_callback(s, filter, "start_analyze",
11553 (!(chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES),
11554 (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_RETVAL | HLUA_FLT_CB_ARG_CHN));
11555}
11556
11557static int hlua_filter_end_analyze(struct stream *s, struct filter *filter, struct channel *chn)
11558{
11559 struct hlua_flt_ctx *flt_ctx = filter->ctx;
11560
11561 flt_ctx->flags &= ~HLUA_FLT_CTX_FL_PAYLOAD;
11562 return hlua_filter_callback(s, filter, "end_analyze",
11563 (!(chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES),
11564 (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_RETVAL | HLUA_FLT_CB_ARG_CHN));
11565}
11566
Christopher Fauleteae8afa2020-02-26 17:15:48 +010011567static int hlua_filter_http_headers(struct stream *s, struct filter *filter, struct http_msg *msg)
11568{
11569 struct hlua_flt_ctx *flt_ctx = filter->ctx;
11570
11571 flt_ctx->flags &= ~HLUA_FLT_CTX_FL_PAYLOAD;
11572 return hlua_filter_callback(s, filter, "http_headers",
11573 (!(msg->chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES),
11574 (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_RETVAL | HLUA_FLT_CB_ARG_HTTP_MSG));
11575}
11576
11577static int hlua_filter_http_payload(struct stream *s, struct filter *filter, struct http_msg *msg,
11578 unsigned int offset, unsigned int len)
11579{
11580 struct hlua_flt_ctx *flt_ctx = filter->ctx;
11581 struct hlua *flt_hlua;
11582 int dir = (!(msg->chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES);
11583 int idx = (dir == SMP_OPT_DIR_REQ ? 0 : 1);
11584 int ret;
11585
11586 flt_hlua = flt_ctx->hlua[idx];
11587 flt_ctx->cur_off[idx] = offset;
11588 flt_ctx->cur_len[idx] = len;
11589 flt_ctx->flags |= HLUA_FLT_CTX_FL_PAYLOAD;
11590 ret = hlua_filter_callback(s, filter, "http_payload", dir, (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_ARG_HTTP_MSG));
11591 if (ret != -1) {
11592 ret = flt_ctx->cur_len[idx];
11593 if (lua_gettop(flt_hlua->T) > 0) {
11594 ret = lua_tointeger(flt_hlua->T, -1);
11595 if (ret > flt_ctx->cur_len[idx])
11596 ret = flt_ctx->cur_len[idx];
11597 lua_settop(flt_hlua->T, 0); /* Empty the stack. */
11598 }
11599 }
11600 return ret;
11601}
11602
11603static int hlua_filter_http_end(struct stream *s, struct filter *filter, struct http_msg *msg)
11604{
11605 struct hlua_flt_ctx *flt_ctx = filter->ctx;
11606
11607 flt_ctx->flags &= ~HLUA_FLT_CTX_FL_PAYLOAD;
11608 return hlua_filter_callback(s, filter, "http_end",
11609 (!(msg->chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES),
11610 (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_RETVAL | HLUA_FLT_CB_ARG_HTTP_MSG));
11611}
11612
Christopher Fauletc404f112020-02-26 15:03:09 +010011613static int hlua_filter_tcp_payload(struct stream *s, struct filter *filter, struct channel *chn,
11614 unsigned int offset, unsigned int len)
11615{
11616 struct hlua_flt_ctx *flt_ctx = filter->ctx;
11617 struct hlua *flt_hlua;
11618 int dir = (!(chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES);
11619 int idx = (dir == SMP_OPT_DIR_REQ ? 0 : 1);
11620 int ret;
11621
11622 flt_hlua = flt_ctx->hlua[idx];
11623 flt_ctx->cur_off[idx] = offset;
11624 flt_ctx->cur_len[idx] = len;
11625 flt_ctx->flags |= HLUA_FLT_CTX_FL_PAYLOAD;
11626 ret = hlua_filter_callback(s, filter, "tcp_payload", dir, (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_ARG_CHN));
11627 if (ret != -1) {
11628 ret = flt_ctx->cur_len[idx];
11629 if (lua_gettop(flt_hlua->T) > 0) {
11630 ret = lua_tointeger(flt_hlua->T, -1);
11631 if (ret > flt_ctx->cur_len[idx])
11632 ret = flt_ctx->cur_len[idx];
11633 lua_settop(flt_hlua->T, 0); /* Empty the stack. */
11634 }
11635 }
11636 return ret;
11637}
11638
Christopher Faulet69c581a2021-05-31 08:54:04 +020011639static int hlua_filter_parse_fct(char **args, int *cur_arg, struct proxy *px,
11640 struct flt_conf *fconf, char **err, void *private)
11641{
11642 struct hlua_reg_filter *reg_flt = private;
11643 lua_State *L;
11644 struct hlua_flt_config *conf = NULL;
11645 const char *flt_id = NULL;
11646 int state_id, pos, flt_flags = 0;
11647 struct flt_ops *hlua_flt_ops = NULL;
11648
11649 state_id = reg_flt_to_stack_id(reg_flt);
11650 L = hlua_states[state_id];
11651
11652 /* Initialize the filter ops with default callbacks */
11653 hlua_flt_ops = calloc(1, sizeof(*hlua_flt_ops));
Christopher Fauletc86bb872021-08-13 08:33:57 +020011654 if (!hlua_flt_ops)
11655 goto error;
Christopher Faulet69c581a2021-05-31 08:54:04 +020011656 hlua_flt_ops->init = hlua_filter_init;
11657 hlua_flt_ops->deinit = hlua_filter_deinit;
11658 if (state_id) {
11659 /* Set per-thread callback if script is loaded per-thread */
11660 hlua_flt_ops->init_per_thread = hlua_filter_init_per_thread;
11661 hlua_flt_ops->deinit_per_thread = hlua_filter_deinit_per_thread;
11662 }
11663 hlua_flt_ops->attach = hlua_filter_new;
11664 hlua_flt_ops->detach = hlua_filter_delete;
11665
11666 /* Push the filter class on the stack and resolve all callbacks */
Aurelien DARRAGON4fdf8b52023-03-20 17:22:37 +010011667 hlua_pushref(L, reg_flt->flt_ref[state_id]);
Christopher Faulet69c581a2021-05-31 08:54:04 +020011668
Christopher Fauletc404f112020-02-26 15:03:09 +010011669 if (lua_getfield(L, -1, "start_analyze") == LUA_TFUNCTION)
11670 hlua_flt_ops->channel_start_analyze = hlua_filter_start_analyze;
11671 lua_pop(L, 1);
11672 if (lua_getfield(L, -1, "end_analyze") == LUA_TFUNCTION)
11673 hlua_flt_ops->channel_end_analyze = hlua_filter_end_analyze;
11674 lua_pop(L, 1);
Christopher Fauleteae8afa2020-02-26 17:15:48 +010011675 if (lua_getfield(L, -1, "http_headers") == LUA_TFUNCTION)
11676 hlua_flt_ops->http_headers = hlua_filter_http_headers;
11677 lua_pop(L, 1);
11678 if (lua_getfield(L, -1, "http_payload") == LUA_TFUNCTION)
11679 hlua_flt_ops->http_payload = hlua_filter_http_payload;
11680 lua_pop(L, 1);
11681 if (lua_getfield(L, -1, "http_end") == LUA_TFUNCTION)
11682 hlua_flt_ops->http_end = hlua_filter_http_end;
11683 lua_pop(L, 1);
Christopher Fauletc404f112020-02-26 15:03:09 +010011684 if (lua_getfield(L, -1, "tcp_payload") == LUA_TFUNCTION)
11685 hlua_flt_ops->tcp_payload = hlua_filter_tcp_payload;
11686 lua_pop(L, 1);
Christopher Faulet69c581a2021-05-31 08:54:04 +020011687
11688 /* Get id and flags of the filter class */
11689 if (lua_getfield(L, -1, "id") == LUA_TSTRING)
11690 flt_id = lua_tostring(L, -1);
11691 lua_pop(L, 1);
11692 if (lua_getfield(L, -1, "flags") == LUA_TNUMBER)
11693 flt_flags = lua_tointeger(L, -1);
11694 lua_pop(L, 1);
11695
11696 /* Create the filter config */
11697 conf = calloc(1, sizeof(*conf));
Christopher Fauletc86bb872021-08-13 08:33:57 +020011698 if (!conf)
Christopher Faulet69c581a2021-05-31 08:54:04 +020011699 goto error;
Christopher Faulet69c581a2021-05-31 08:54:04 +020011700 conf->reg = reg_flt;
11701
11702 /* duplicate args */
11703 for (pos = 0; *args[*cur_arg + 1 + pos]; pos++);
11704 conf->args = calloc(pos + 1, sizeof(*conf->args));
Christopher Fauletc86bb872021-08-13 08:33:57 +020011705 if (!conf->args)
11706 goto error;
11707 for (pos = 0; *args[*cur_arg + 1 + pos]; pos++) {
Christopher Faulet69c581a2021-05-31 08:54:04 +020011708 conf->args[pos] = strdup(args[*cur_arg + 1 + pos]);
Christopher Fauletc86bb872021-08-13 08:33:57 +020011709 if (!conf->args[pos])
11710 goto error;
11711 }
Christopher Faulet69c581a2021-05-31 08:54:04 +020011712 conf->args[pos] = NULL;
11713 *cur_arg += pos + 1;
11714
Christopher Fauletc86bb872021-08-13 08:33:57 +020011715 if (flt_id) {
11716 fconf->id = strdup(flt_id);
11717 if (!fconf->id)
11718 goto error;
11719 }
Christopher Faulet69c581a2021-05-31 08:54:04 +020011720 fconf->flags = flt_flags;
11721 fconf->conf = conf;
11722 fconf->ops = hlua_flt_ops;
11723
11724 lua_settop(L, 0);
11725 return 0;
11726
11727 error:
Christopher Fauletc86bb872021-08-13 08:33:57 +020011728 memprintf(err, "Lua filter '%s' : Lua out of memory error", reg_flt->name);
Christopher Faulet69c581a2021-05-31 08:54:04 +020011729 free(hlua_flt_ops);
Christopher Fauletc86bb872021-08-13 08:33:57 +020011730 if (conf && conf->args) {
11731 for (pos = 0; conf->args[pos]; pos++)
11732 free(conf->args[pos]);
11733 free(conf->args);
11734 }
Christopher Faulet69c581a2021-05-31 08:54:04 +020011735 free(conf);
Christopher Fauletc86bb872021-08-13 08:33:57 +020011736 free((char *)fconf->id);
Christopher Faulet69c581a2021-05-31 08:54:04 +020011737 lua_settop(L, 0);
11738 return -1;
11739}
11740
Christopher Fauletc404f112020-02-26 15:03:09 +010011741__LJMP static int hlua_register_data_filter(lua_State *L)
11742{
11743 struct filter *filter;
11744 struct channel *chn;
11745
11746 MAY_LJMP(check_args(L, 2, "register_data_filter"));
11747 MAY_LJMP(luaL_checktype(L, 1, LUA_TTABLE));
11748 chn = MAY_LJMP(hlua_checkchannel(L, 2));
11749
11750 lua_getfield(L, 1, "__filter");
11751 MAY_LJMP(luaL_checktype(L, -1, LUA_TLIGHTUSERDATA));
11752 filter = lua_touserdata (L, -1);
11753 lua_pop(L, 1);
11754
11755 register_data_filter(chn_strm(chn), chn, filter);
11756 return 1;
11757}
11758
11759__LJMP static int hlua_unregister_data_filter(lua_State *L)
11760{
11761 struct filter *filter;
11762 struct channel *chn;
11763
11764 MAY_LJMP(check_args(L, 2, "unregister_data_filter"));
11765 MAY_LJMP(luaL_checktype(L, 1, LUA_TTABLE));
11766 chn = MAY_LJMP(hlua_checkchannel(L, 2));
11767
11768 lua_getfield(L, 1, "__filter");
11769 MAY_LJMP(luaL_checktype(L, -1, LUA_TLIGHTUSERDATA));
11770 filter = lua_touserdata (L, -1);
11771 lua_pop(L, 1);
11772
11773 unregister_data_filter(chn_strm(chn), chn, filter);
11774 return 1;
11775}
11776
Christopher Faulet69c581a2021-05-31 08:54:04 +020011777/* This function is an LUA binding used for registering a filter. It expects a
Ilya Shipitsinff0f2782021-08-22 22:18:07 +050011778 * filter name used in the haproxy configuration file and a LUA function to
Christopher Faulet69c581a2021-05-31 08:54:04 +020011779 * parse configuration arguments.
11780 */
11781__LJMP static int hlua_register_filter(lua_State *L)
11782{
11783 struct buffer *trash;
11784 struct flt_kw_list *fkl;
11785 struct flt_kw *fkw;
11786 const char *name;
11787 struct hlua_reg_filter *reg_flt= NULL;
11788 int flt_ref, fun_ref;
11789 int len;
11790
11791 MAY_LJMP(check_args(L, 3, "register_filter"));
11792
Aurelien DARRAGON87f52972023-02-24 09:43:54 +010011793 if (hlua_gethlua(L)) {
11794 /* runtime processing */
11795 WILL_LJMP(luaL_error(L, "register_filter: not available outside of body context"));
11796 }
11797
Christopher Faulet69c581a2021-05-31 08:54:04 +020011798 /* First argument : filter name. */
11799 name = MAY_LJMP(luaL_checkstring(L, 1));
11800
11801 /* Second argument : The filter class */
11802 flt_ref = MAY_LJMP(hlua_checktable(L, 2));
11803
11804 /* Third argument : lua function. */
11805 fun_ref = MAY_LJMP(hlua_checkfunction(L, 3));
11806
11807 trash = get_trash_chunk();
11808 chunk_printf(trash, "lua.%s", name);
11809 fkw = flt_find_kw(trash->area);
11810 if (fkw != NULL) {
11811 reg_flt = fkw->private;
11812 if (reg_flt->flt_ref[hlua_state_id] != -1 || reg_flt->fun_ref[hlua_state_id] != -1) {
11813 ha_warning("Trying to register filter 'lua.%s' more than once. "
11814 "This will become a hard error in version 2.5.\n", name);
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +010011815 if (reg_flt->flt_ref[hlua_state_id] != -1)
11816 hlua_unref(L, reg_flt->flt_ref[hlua_state_id]);
11817 if (reg_flt->fun_ref[hlua_state_id] != -1)
11818 hlua_unref(L, reg_flt->fun_ref[hlua_state_id]);
Christopher Faulet69c581a2021-05-31 08:54:04 +020011819 }
11820 reg_flt->flt_ref[hlua_state_id] = flt_ref;
11821 reg_flt->fun_ref[hlua_state_id] = fun_ref;
11822 return 0;
11823 }
11824
11825 fkl = calloc(1, sizeof(*fkl) + sizeof(struct flt_kw) * 2);
11826 if (!fkl)
11827 goto alloc_error;
11828 fkl->scope = "HLUA";
11829
11830 reg_flt = new_hlua_reg_filter(name);
11831 if (!reg_flt)
11832 goto alloc_error;
11833
11834 reg_flt->flt_ref[hlua_state_id] = flt_ref;
11835 reg_flt->fun_ref[hlua_state_id] = fun_ref;
11836
11837 /* The filter keyword */
11838 len = strlen("lua.") + strlen(name) + 1;
11839 fkl->kw[0].kw = calloc(1, len);
11840 if (!fkl->kw[0].kw)
11841 goto alloc_error;
11842
11843 snprintf((char *)fkl->kw[0].kw, len, "lua.%s", name);
11844
11845 fkl->kw[0].parse = hlua_filter_parse_fct;
11846 fkl->kw[0].private = reg_flt;
11847 memset(&fkl->kw[1], 0, sizeof(*fkl->kw));
11848
11849 /* Register this new filter */
11850 flt_register_keywords(fkl);
11851
11852 return 0;
11853
11854 alloc_error:
11855 release_hlua_reg_filter(reg_flt);
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +010011856 hlua_unref(L, flt_ref);
11857 hlua_unref(L, fun_ref);
Christopher Faulet69c581a2021-05-31 08:54:04 +020011858 ha_free(&fkl);
11859 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
11860 return 0; /* Never reached */
11861}
11862
Thierry FOURNIERbd413492015-03-03 16:52:26 +010011863static int hlua_read_timeout(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011864 const struct proxy *defpx, const char *file, int line,
Thierry FOURNIERbd413492015-03-03 16:52:26 +010011865 char **err, unsigned int *timeout)
11866{
11867 const char *error;
11868
11869 error = parse_time_err(args[1], timeout, TIME_UNIT_MS);
Willy Tarreau9faebe32019-06-07 19:00:37 +020011870 if (error == PARSE_TIME_OVER) {
11871 memprintf(err, "timer overflow in argument <%s> to <%s> (maximum value is 2147483647 ms or ~24.8 days)",
11872 args[1], args[0]);
11873 return -1;
11874 }
11875 else if (error == PARSE_TIME_UNDER) {
11876 memprintf(err, "timer underflow in argument <%s> to <%s> (minimum non-null value is 1 ms)",
11877 args[1], args[0]);
11878 return -1;
11879 }
11880 else if (error) {
Thierry FOURNIERbd413492015-03-03 16:52:26 +010011881 memprintf(err, "%s: invalid timeout", args[0]);
11882 return -1;
11883 }
11884 return 0;
11885}
11886
11887static int hlua_session_timeout(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011888 const struct proxy *defpx, const char *file, int line,
Thierry FOURNIERbd413492015-03-03 16:52:26 +010011889 char **err)
11890{
11891 return hlua_read_timeout(args, section_type, curpx, defpx,
11892 file, line, err, &hlua_timeout_session);
11893}
11894
11895static int hlua_task_timeout(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011896 const struct proxy *defpx, const char *file, int line,
Thierry FOURNIERbd413492015-03-03 16:52:26 +010011897 char **err)
11898{
11899 return hlua_read_timeout(args, section_type, curpx, defpx,
11900 file, line, err, &hlua_timeout_task);
11901}
11902
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020011903static int hlua_applet_timeout(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011904 const struct proxy *defpx, const char *file, int line,
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020011905 char **err)
11906{
11907 return hlua_read_timeout(args, section_type, curpx, defpx,
11908 file, line, err, &hlua_timeout_applet);
11909}
11910
Thierry FOURNIERee9f8022015-03-03 17:37:37 +010011911static int hlua_forced_yield(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011912 const struct proxy *defpx, const char *file, int line,
Thierry FOURNIERee9f8022015-03-03 17:37:37 +010011913 char **err)
11914{
11915 char *error;
11916
11917 hlua_nb_instruction = strtoll(args[1], &error, 10);
11918 if (*error != '\0') {
11919 memprintf(err, "%s: invalid number", args[0]);
11920 return -1;
11921 }
11922 return 0;
11923}
11924
Willy Tarreau32f61e22015-03-18 17:54:59 +010011925static int hlua_parse_maxmem(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011926 const struct proxy *defpx, const char *file, int line,
Willy Tarreau32f61e22015-03-18 17:54:59 +010011927 char **err)
11928{
11929 char *error;
11930
11931 if (*(args[1]) == 0) {
Thierry Fournier70e38e92022-09-19 09:01:53 +020011932 memprintf(err, "'%s' expects an integer argument (Lua memory size in MB).", args[0]);
Willy Tarreau32f61e22015-03-18 17:54:59 +010011933 return -1;
11934 }
11935 hlua_global_allocator.limit = strtoll(args[1], &error, 10) * 1024L * 1024L;
11936 if (*error != '\0') {
11937 memprintf(err, "%s: invalid number %s (error at '%c')", args[0], args[1], *error);
11938 return -1;
11939 }
11940 return 0;
11941}
11942
11943
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011944/* This function is called by the main configuration key "lua-load". It loads and
11945 * execute an lua file during the parsing of the HAProxy configuration file. It is
11946 * the main lua entry point.
11947 *
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -080011948 * This function runs with the HAProxy keywords API. It returns -1 if an error
11949 * occurs, otherwise it returns 0.
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011950 *
11951 * In some error case, LUA set an error message in top of the stack. This function
11952 * returns this error message in the HAProxy logs and pop it from the stack.
Thierry FOURNIERbabae282015-09-17 11:36:37 +020011953 *
11954 * This function can fail with an abort() due to an Lua critical error.
11955 * We are in the configuration parsing process of HAProxy, this abort() is
11956 * tolerated.
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011957 */
Thierry Fournierae6b5682022-09-19 09:04:16 +020011958static int hlua_load_state(char **args, lua_State *L, char **err)
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011959{
11960 int error;
Thierry Fournierae6b5682022-09-19 09:04:16 +020011961 int nargs;
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011962
11963 /* Just load and compile the file. */
Thierry Fournierae6b5682022-09-19 09:04:16 +020011964 error = luaL_loadfile(L, args[0]);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011965 if (error) {
Thierry Fournierae6b5682022-09-19 09:04:16 +020011966 memprintf(err, "error in Lua file '%s': %s", args[0], lua_tostring(L, -1));
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011967 lua_pop(L, 1);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011968 return -1;
11969 }
Thierry Fournierae6b5682022-09-19 09:04:16 +020011970
11971 /* Push args in the Lua stack, except the first one which is the filename */
11972 for (nargs = 1; *(args[nargs]) != 0; nargs++) {
Aurelien DARRAGON4d7aefe2022-09-23 10:22:14 +020011973 /* Check stack size. */
11974 if (!lua_checkstack(L, 1)) {
11975 memprintf(err, "Lua runtime error while loading arguments: stack is full.");
11976 return -1;
11977 }
Thierry Fournierae6b5682022-09-19 09:04:16 +020011978 lua_pushstring(L, args[nargs]);
11979 }
11980 nargs--;
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011981
11982 /* If no syntax error where detected, execute the code. */
Thierry Fournierae6b5682022-09-19 09:04:16 +020011983 error = lua_pcall(L, nargs, LUA_MULTRET, 0);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011984 switch (error) {
11985 case LUA_OK:
11986 break;
11987 case LUA_ERRRUN:
Thierry Fournier70e38e92022-09-19 09:01:53 +020011988 memprintf(err, "Lua runtime error: %s", lua_tostring(L, -1));
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011989 lua_pop(L, 1);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011990 return -1;
11991 case LUA_ERRMEM:
Thierry Fournier70e38e92022-09-19 09:01:53 +020011992 memprintf(err, "Lua out of memory error");
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011993 return -1;
11994 case LUA_ERRERR:
Thierry Fournier70e38e92022-09-19 09:01:53 +020011995 memprintf(err, "Lua message handler error: %s", lua_tostring(L, -1));
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011996 lua_pop(L, 1);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011997 return -1;
Christopher Faulet08ed98f2020-07-28 10:33:25 +020011998#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM <= 503
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011999 case LUA_ERRGCMM:
Thierry Fournier70e38e92022-09-19 09:01:53 +020012000 memprintf(err, "Lua garbage collector error: %s", lua_tostring(L, -1));
Thierry Fournierc93c15c2020-11-28 15:02:13 +010012001 lua_pop(L, 1);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010012002 return -1;
Christopher Faulet08ed98f2020-07-28 10:33:25 +020012003#endif
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010012004 default:
Thierry Fournier70e38e92022-09-19 09:01:53 +020012005 memprintf(err, "Lua unknown error: %s", lua_tostring(L, -1));
Thierry Fournierc93c15c2020-11-28 15:02:13 +010012006 lua_pop(L, 1);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010012007 return -1;
12008 }
12009
12010 return 0;
12011}
12012
Thierry Fournierc93c15c2020-11-28 15:02:13 +010012013static int hlua_load(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010012014 const struct proxy *defpx, const char *file, int line,
Thierry Fournierc93c15c2020-11-28 15:02:13 +010012015 char **err)
12016{
12017 if (*(args[1]) == 0) {
Thierry Fournier70e38e92022-09-19 09:01:53 +020012018 memprintf(err, "'%s' expects a file name as parameter.", args[0]);
Thierry Fournierc93c15c2020-11-28 15:02:13 +010012019 return -1;
12020 }
12021
Thierry Fournier59f11be2020-11-29 00:37:41 +010012022 /* loading for global state */
Thierry Fournierc7492592020-11-28 23:57:24 +010012023 hlua_state_id = 0;
Willy Tarreau43ab05b2021-09-28 09:43:11 +020012024 ha_set_thread(NULL);
Thierry Fournierae6b5682022-09-19 09:04:16 +020012025 return hlua_load_state(&args[1], hlua_states[0], err);
Thierry Fournierc93c15c2020-11-28 15:02:13 +010012026}
12027
Thierry Fournier59f11be2020-11-29 00:37:41 +010012028static int hlua_load_per_thread(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010012029 const struct proxy *defpx, const char *file, int line,
Thierry Fournier59f11be2020-11-29 00:37:41 +010012030 char **err)
12031{
12032 int len;
Thierry Fournierae6b5682022-09-19 09:04:16 +020012033 int i;
Thierry Fournier59f11be2020-11-29 00:37:41 +010012034
12035 if (*(args[1]) == 0) {
Thierry Fournier70e38e92022-09-19 09:01:53 +020012036 memprintf(err, "'%s' expects a file as parameter.", args[0]);
Thierry Fournier59f11be2020-11-29 00:37:41 +010012037 return -1;
12038 }
12039
12040 if (per_thread_load == NULL) {
12041 /* allocate the first entry large enough to store the final NULL */
12042 per_thread_load = calloc(1, sizeof(*per_thread_load));
12043 if (per_thread_load == NULL) {
12044 memprintf(err, "out of memory error");
12045 return -1;
12046 }
12047 }
12048
12049 /* count used entries */
12050 for (len = 0; per_thread_load[len] != NULL; len++)
12051 ;
12052
12053 per_thread_load = realloc(per_thread_load, (len + 2) * sizeof(*per_thread_load));
12054 if (per_thread_load == NULL) {
12055 memprintf(err, "out of memory error");
12056 return -1;
12057 }
Thierry Fournier59f11be2020-11-29 00:37:41 +010012058 per_thread_load[len + 1] = NULL;
12059
Thierry Fournierae6b5682022-09-19 09:04:16 +020012060 /* count args excepting the first, allocate array and copy args */
12061 for (i = 0; *(args[i + 1]) != 0; i++);
Aurelien DARRAGONb12d1692022-09-23 08:48:34 +020012062 per_thread_load[len] = calloc(i + 1, sizeof(*per_thread_load[len]));
Thierry Fournier59f11be2020-11-29 00:37:41 +010012063 if (per_thread_load[len] == NULL) {
12064 memprintf(err, "out of memory error");
12065 return -1;
12066 }
Thierry Fournierae6b5682022-09-19 09:04:16 +020012067 for (i = 1; *(args[i]) != 0; i++) {
12068 per_thread_load[len][i - 1] = strdup(args[i]);
12069 if (per_thread_load[len][i - 1] == NULL) {
12070 memprintf(err, "out of memory error");
12071 return -1;
12072 }
12073 }
12074 per_thread_load[len][i - 1] = strdup("");
12075 if (per_thread_load[len][i - 1] == NULL) {
12076 memprintf(err, "out of memory error");
12077 return -1;
12078 }
Thierry Fournier59f11be2020-11-29 00:37:41 +010012079
12080 /* loading for thread 1 only */
12081 hlua_state_id = 1;
Willy Tarreau43ab05b2021-09-28 09:43:11 +020012082 ha_set_thread(NULL);
Thierry Fournierae6b5682022-09-19 09:04:16 +020012083 return hlua_load_state(per_thread_load[len], hlua_states[1], err);
Thierry Fournier59f11be2020-11-29 00:37:41 +010012084}
12085
Tim Duesterhusc9fc9f22020-01-12 13:55:39 +010012086/* Prepend the given <path> followed by a semicolon to the `package.<type>` variable
12087 * in the given <ctx>.
12088 */
Thierry Fournier3fb9e512020-11-28 10:13:12 +010012089static int hlua_prepend_path(lua_State *L, char *type, char *path)
Tim Duesterhusc9fc9f22020-01-12 13:55:39 +010012090{
Thierry Fournier3fb9e512020-11-28 10:13:12 +010012091 lua_getglobal(L, "package"); /* push package variable */
12092 lua_pushstring(L, path); /* push given path */
12093 lua_pushstring(L, ";"); /* push semicolon */
12094 lua_getfield(L, -3, type); /* push old path */
12095 lua_concat(L, 3); /* concatenate to new path */
12096 lua_setfield(L, -2, type); /* store new path */
12097 lua_pop(L, 1); /* pop package variable */
Tim Duesterhusc9fc9f22020-01-12 13:55:39 +010012098
12099 return 0;
12100}
12101
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010012102static int hlua_config_prepend_path(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010012103 const struct proxy *defpx, const char *file, int line,
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010012104 char **err)
12105{
12106 char *path;
12107 char *type = "path";
Tim Duesterhus621e74a2021-01-03 20:04:36 +010012108 struct prepend_path *p = NULL;
Bertrand Jacquin7fbc7702021-11-24 21:16:06 +000012109 size_t i;
Thierry Fournier59f11be2020-11-29 00:37:41 +010012110
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010012111 if (too_many_args(2, args, err, NULL)) {
Tim Duesterhus621e74a2021-01-03 20:04:36 +010012112 goto err;
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010012113 }
12114
12115 if (!(*args[1])) {
12116 memprintf(err, "'%s' expects to receive a <path> as argument", args[0]);
Tim Duesterhus621e74a2021-01-03 20:04:36 +010012117 goto err;
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010012118 }
12119 path = args[1];
12120
12121 if (*args[2]) {
12122 if (strcmp(args[2], "path") != 0 && strcmp(args[2], "cpath") != 0) {
12123 memprintf(err, "'%s' expects <type> to either be 'path' or 'cpath'", args[0]);
Tim Duesterhus621e74a2021-01-03 20:04:36 +010012124 goto err;
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010012125 }
12126 type = args[2];
12127 }
12128
Thierry Fournier59f11be2020-11-29 00:37:41 +010012129 p = calloc(1, sizeof(*p));
12130 if (p == NULL) {
Tim Duesterhusf89d43a2021-01-03 20:04:37 +010012131 memprintf(err, "memory allocation failed");
Tim Duesterhus621e74a2021-01-03 20:04:36 +010012132 goto err;
Thierry Fournier59f11be2020-11-29 00:37:41 +010012133 }
12134 p->path = strdup(path);
12135 if (p->path == NULL) {
Tim Duesterhusf89d43a2021-01-03 20:04:37 +010012136 memprintf(err, "memory allocation failed");
Tim Duesterhus621e74a2021-01-03 20:04:36 +010012137 goto err2;
Thierry Fournier59f11be2020-11-29 00:37:41 +010012138 }
12139 p->type = strdup(type);
12140 if (p->type == NULL) {
Tim Duesterhusf89d43a2021-01-03 20:04:37 +010012141 memprintf(err, "memory allocation failed");
Tim Duesterhus621e74a2021-01-03 20:04:36 +010012142 goto err2;
Thierry Fournier59f11be2020-11-29 00:37:41 +010012143 }
Willy Tarreau2b718102021-04-21 07:32:39 +020012144 LIST_APPEND(&prepend_path_list, &p->l);
Thierry Fournier59f11be2020-11-29 00:37:41 +010012145
Tim Duesterhus9e5e5862021-10-11 18:51:08 +020012146 /* Handle the global state and the per-thread state for the first
12147 * thread. The remaining threads will be initialized based on
12148 * prepend_path_list.
12149 */
Bertrand Jacquin7fbc7702021-11-24 21:16:06 +000012150 for (i = 0; i < 2; i++) {
Tim Duesterhus9e5e5862021-10-11 18:51:08 +020012151 lua_State *L = hlua_states[i];
12152 const char *error;
12153
12154 if (setjmp(safe_ljmp_env) != 0) {
12155 lua_atpanic(L, hlua_panic_safe);
12156 if (lua_type(L, -1) == LUA_TSTRING)
12157 error = lua_tostring(L, -1);
12158 else
12159 error = "critical error";
12160 fprintf(stderr, "lua-prepend-path: %s.\n", error);
12161 exit(1);
12162 } else {
12163 lua_atpanic(L, hlua_panic_ljmp);
12164 }
12165
12166 hlua_prepend_path(L, type, path);
12167
12168 lua_atpanic(L, hlua_panic_safe);
12169 }
12170
Thierry Fournier59f11be2020-11-29 00:37:41 +010012171 return 0;
Tim Duesterhus621e74a2021-01-03 20:04:36 +010012172
12173err2:
12174 free(p->type);
12175 free(p->path);
12176err:
12177 free(p);
12178 return -1;
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010012179}
12180
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010012181/* configuration keywords declaration */
12182static struct cfg_kw_list cfg_kws = {{ },{
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010012183 { CFG_GLOBAL, "lua-prepend-path", hlua_config_prepend_path },
Thierry FOURNIERbd413492015-03-03 16:52:26 +010012184 { CFG_GLOBAL, "lua-load", hlua_load },
Thierry Fournier59f11be2020-11-29 00:37:41 +010012185 { CFG_GLOBAL, "lua-load-per-thread", hlua_load_per_thread },
Thierry FOURNIERbd413492015-03-03 16:52:26 +010012186 { CFG_GLOBAL, "tune.lua.session-timeout", hlua_session_timeout },
12187 { CFG_GLOBAL, "tune.lua.task-timeout", hlua_task_timeout },
Thierry FOURNIER56da1012015-10-01 08:42:31 +020012188 { CFG_GLOBAL, "tune.lua.service-timeout", hlua_applet_timeout },
Thierry FOURNIERee9f8022015-03-03 17:37:37 +010012189 { CFG_GLOBAL, "tune.lua.forced-yield", hlua_forced_yield },
Willy Tarreau32f61e22015-03-18 17:54:59 +010012190 { CFG_GLOBAL, "tune.lua.maxmem", hlua_parse_maxmem },
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010012191 { 0, NULL, NULL },
12192}};
12193
Willy Tarreau0108d902018-11-25 19:14:37 +010012194INITCALL1(STG_REGISTER, cfg_register_keywords, &cfg_kws);
12195
William Lallemand52139182022-03-30 15:05:42 +020012196#ifdef USE_OPENSSL
Christopher Fauletafd8f102018-11-08 11:34:21 +010012197
William Lallemand30fcca12022-03-30 12:03:12 +020012198/*
12199 * This function replace a ckch_store by another one, and rebuild the ckch_inst and all its dependencies.
12200 * It does the sam as "cli_io_handler_commit_cert" but for lua, the major
12201 * difference is that the yield in lua and for the CLI is not handled the same
12202 * way.
12203 */
12204__LJMP static int hlua_ckch_commit_yield(lua_State *L, int status, lua_KContext ctx)
12205{
12206 struct ckch_inst **lua_ckchi = lua_touserdata(L, -1);
12207 struct ckch_store **lua_ckchs = lua_touserdata(L, -2);
12208 struct ckch_inst *ckchi = *lua_ckchi;
12209 struct ckch_store *old_ckchs = lua_ckchs[0];
12210 struct ckch_store *new_ckchs = lua_ckchs[1];
12211 struct hlua *hlua;
12212 char *err = NULL;
12213 int y = 1;
12214
12215 hlua = hlua_gethlua(L);
12216
12217 /* get the first ckchi to copy */
12218 if (ckchi == NULL)
12219 ckchi = LIST_ELEM(old_ckchs->ckch_inst.n, typeof(ckchi), by_ckchs);
12220
12221 /* walk through the old ckch_inst and creates new ckch_inst using the updated ckchs */
12222 list_for_each_entry_from(ckchi, &old_ckchs->ckch_inst, by_ckchs) {
12223 struct ckch_inst *new_inst;
12224
12225 /* it takes a lot of CPU to creates SSL_CTXs, so we yield every 10 CKCH instances */
12226 if (y % 10 == 0) {
12227
12228 *lua_ckchi = ckchi;
12229
12230 task_wakeup(hlua->task, TASK_WOKEN_MSG);
12231 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_ckch_commit_yield, TICK_ETERNITY, 0));
12232 }
12233
12234 if (ckch_inst_rebuild(new_ckchs, ckchi, &new_inst, &err))
12235 goto error;
12236
12237 /* link the new ckch_inst to the duplicate */
12238 LIST_APPEND(&new_ckchs->ckch_inst, &new_inst->by_ckchs);
12239 y++;
12240 }
12241
12242 /* The generation is finished, we can insert everything */
12243 ckch_store_replace(old_ckchs, new_ckchs);
12244
12245 lua_pop(L, 2); /* pop the lua_ckchs and ckchi */
12246
12247 HA_SPIN_UNLOCK(CKCH_LOCK, &ckch_lock);
12248
12249 return 0;
12250
12251error:
12252 ckch_store_free(new_ckchs);
12253 HA_SPIN_UNLOCK(CKCH_LOCK, &ckch_lock);
12254 WILL_LJMP(luaL_error(L, "%s", err));
12255 free(err);
12256
12257 return 0;
12258}
12259
12260/*
12261 * Replace a ckch_store <filename> in the ckchs_tree with a ckch_store created
12262 * from the table in parameter.
12263 *
12264 * This is equivalent to "set ssl cert" + "commit ssl cert" over the CLI, which
12265 * means it does not need to have a transaction since everything is done in the
12266 * same function.
12267 *
12268 * CertCache.set{filename="", crt="", key="", sctl="", ocsp="", issuer=""}
12269 *
12270 */
12271__LJMP static int hlua_ckch_set(lua_State *L)
12272{
12273 struct hlua *hlua;
12274 struct ckch_inst **lua_ckchi;
12275 struct ckch_store **lua_ckchs;
12276 struct ckch_store *old_ckchs = NULL;
12277 struct ckch_store *new_ckchs = NULL;
12278 int errcode = 0;
12279 char *err = NULL;
12280 struct cert_exts *cert_ext = NULL;
12281 char *filename;
William Lallemand52ddd992022-11-22 11:51:53 +010012282 struct ckch_data *data;
William Lallemand30fcca12022-03-30 12:03:12 +020012283 int ret;
12284
12285 if (lua_type(L, -1) != LUA_TTABLE)
12286 WILL_LJMP(luaL_error(L, "'CertCache.set' needs a table as argument"));
12287
12288 hlua = hlua_gethlua(L);
12289
12290 /* FIXME: this should not return an error but should come back later */
12291 if (HA_SPIN_TRYLOCK(CKCH_LOCK, &ckch_lock))
12292 WILL_LJMP(luaL_error(L, "CertCache already under lock"));
12293
12294 ret = lua_getfield(L, -1, "filename");
12295 if (ret != LUA_TSTRING) {
Thierry Fournier70e38e92022-09-19 09:01:53 +020012296 memprintf(&err, "%sNo filename specified!", err ? err : "");
William Lallemand30fcca12022-03-30 12:03:12 +020012297 errcode |= ERR_ALERT | ERR_FATAL;
12298 goto end;
12299 }
12300 filename = (char *)lua_tostring(L, -1);
12301
12302
12303 /* look for the filename in the tree */
12304 old_ckchs = ckchs_lookup(filename);
12305 if (!old_ckchs) {
Thierry Fournier70e38e92022-09-19 09:01:53 +020012306 memprintf(&err, "%sCan't replace a certificate which is not referenced by the configuration!", err ? err : "");
William Lallemand30fcca12022-03-30 12:03:12 +020012307 errcode |= ERR_ALERT | ERR_FATAL;
12308 goto end;
12309 }
12310 /* TODO: handle extra_files_noext */
12311
12312 new_ckchs = ckchs_dup(old_ckchs);
12313 if (!new_ckchs) {
Thierry Fournier70e38e92022-09-19 09:01:53 +020012314 memprintf(&err, "%sCannot allocate memory!", err ? err : "");
William Lallemand30fcca12022-03-30 12:03:12 +020012315 errcode |= ERR_ALERT | ERR_FATAL;
12316 goto end;
12317 }
12318
William Lallemand52ddd992022-11-22 11:51:53 +010012319 data = new_ckchs->data;
William Lallemand30fcca12022-03-30 12:03:12 +020012320
12321 /* loop on the field in the table, which have the same name as the
12322 * possible extensions of files */
12323 lua_pushnil(L);
12324 while (lua_next(L, 1)) {
12325 int i;
12326 const char *field = lua_tostring(L, -2);
12327 char *payload = (char *)lua_tostring(L, -1);
12328
12329 if (!field || strcmp(field, "filename") == 0) {
12330 lua_pop(L, 1);
12331 continue;
12332 }
12333
12334 for (i = 0; field && cert_exts[i].ext != NULL; i++) {
12335 if (strcmp(field, cert_exts[i].ext) == 0) {
12336 cert_ext = &cert_exts[i];
12337 break;
12338 }
12339 }
12340
12341 /* this is the default type, the field is not supported */
12342 if (cert_ext == NULL) {
Thierry Fournier70e38e92022-09-19 09:01:53 +020012343 memprintf(&err, "%sUnsupported field '%s'", err ? err : "", field);
William Lallemand30fcca12022-03-30 12:03:12 +020012344 errcode |= ERR_ALERT | ERR_FATAL;
12345 goto end;
12346 }
12347
12348 /* appply the change on the duplicate */
William Lallemand52ddd992022-11-22 11:51:53 +010012349 if (cert_ext->load(filename, payload, data, &err) != 0) {
Thierry Fournier70e38e92022-09-19 09:01:53 +020012350 memprintf(&err, "%sCan't load the payload for '%s'", err ? err : "", cert_ext->ext);
William Lallemand30fcca12022-03-30 12:03:12 +020012351 errcode |= ERR_ALERT | ERR_FATAL;
12352 goto end;
12353 }
12354 lua_pop(L, 1);
12355 }
12356
12357 /* store the pointers on the lua stack */
12358 lua_ckchs = lua_newuserdata(L, sizeof(struct ckch_store *) * 2);
12359 lua_ckchs[0] = old_ckchs;
12360 lua_ckchs[1] = new_ckchs;
12361 lua_ckchi = lua_newuserdata(L, sizeof(struct ckch_inst *));
12362 *lua_ckchi = NULL;
12363
12364 task_wakeup(hlua->task, TASK_WOKEN_MSG);
12365 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_ckch_commit_yield, TICK_ETERNITY, 0));
12366
12367end:
12368 HA_SPIN_UNLOCK(CKCH_LOCK, &ckch_lock);
12369
12370 if (errcode & ERR_CODE) {
12371 ckch_store_free(new_ckchs);
12372 WILL_LJMP(luaL_error(L, "%s", err));
12373 }
12374 free(err);
12375
12376 return 0;
12377}
12378
William Lallemand52139182022-03-30 15:05:42 +020012379#else
12380
12381__LJMP static int hlua_ckch_set(lua_State *L)
12382{
12383 WILL_LJMP(luaL_error(L, "'CertCache.set' needs an HAProxy built with OpenSSL"));
12384
12385 return 0;
12386}
12387#endif /* ! USE_OPENSSL */
12388
12389
12390
Thierry FOURNIERbabae282015-09-17 11:36:37 +020012391/* This function can fail with an abort() due to an Lua critical error.
12392 * We are in the initialisation process of HAProxy, this abort() is
12393 * tolerated.
12394 */
Thierry Fournierb8cef172020-11-28 15:37:17 +010012395int hlua_post_init_state(lua_State *L)
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010012396{
12397 struct hlua_init_function *init;
12398 const char *msg;
12399 enum hlua_exec ret;
Thierry Fournierfd107a22016-02-19 19:57:23 +010012400 const char *error;
Thierry Fournier670db242020-11-28 10:49:59 +010012401 const char *kind;
12402 const char *trace;
12403 int return_status = 1;
12404#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM >= 504
12405 int nres;
12406#endif
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010012407
Willy Tarreaucdb53462020-12-02 12:12:00 +010012408 /* disable memory limit checks if limit is not set */
12409 if (!hlua_global_allocator.limit)
12410 hlua_global_allocator.limit = ~hlua_global_allocator.limit;
12411
Ilya Shipitsin856aabc2020-04-16 23:51:34 +050012412 /* Call post initialisation function in safe environment. */
Thierry Fournier3c539322020-11-28 16:05:05 +010012413 if (setjmp(safe_ljmp_env) != 0) {
12414 lua_atpanic(L, hlua_panic_safe);
Thierry Fournierb8cef172020-11-28 15:37:17 +010012415 if (lua_type(L, -1) == LUA_TSTRING)
12416 error = lua_tostring(L, -1);
Thierry Fournier3d4a6752016-02-19 20:53:30 +010012417 else
12418 error = "critical error";
12419 fprintf(stderr, "Lua post-init: %s.\n", error);
12420 exit(1);
Thierry Fournier3c539322020-11-28 16:05:05 +010012421 } else {
12422 lua_atpanic(L, hlua_panic_ljmp);
Thierry Fournier3d4a6752016-02-19 20:53:30 +010012423 }
Frédéric Lécaille54f2bcf2018-08-29 13:46:24 +020012424
Thierry Fournierc7492592020-11-28 23:57:24 +010012425 list_for_each_entry(init, &hlua_init_functions[hlua_state_id], l) {
Aurelien DARRAGON4fdf8b52023-03-20 17:22:37 +010012426 hlua_pushref(L, init->function_ref);
Aurelien DARRAGON16d047b2023-03-20 16:29:55 +010012427 /* function ref should be released right away since it was pushed
12428 * on the stack and will not be used anymore
12429 */
12430 hlua_unref(L, init->function_ref);
Thierry Fournier670db242020-11-28 10:49:59 +010012431
12432#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM >= 504
Thierry Fournierb8cef172020-11-28 15:37:17 +010012433 ret = lua_resume(L, L, 0, &nres);
Thierry Fournier670db242020-11-28 10:49:59 +010012434#else
Thierry Fournierb8cef172020-11-28 15:37:17 +010012435 ret = lua_resume(L, L, 0);
Thierry Fournier670db242020-11-28 10:49:59 +010012436#endif
12437 kind = NULL;
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010012438 switch (ret) {
Thierry Fournier670db242020-11-28 10:49:59 +010012439
12440 case LUA_OK:
Thierry Fournierb8cef172020-11-28 15:37:17 +010012441 lua_pop(L, -1);
Thierry Fournier13d08b72020-11-28 11:02:58 +010012442 break;
Thierry Fournier670db242020-11-28 10:49:59 +010012443
12444 case LUA_ERRERR:
12445 kind = "message handler error";
Willy Tarreau14de3952022-11-14 07:08:28 +010012446 __fallthrough;
Thierry Fournier670db242020-11-28 10:49:59 +010012447 case LUA_ERRRUN:
12448 if (!kind)
12449 kind = "runtime error";
Thierry Fournierb8cef172020-11-28 15:37:17 +010012450 msg = lua_tostring(L, -1);
12451 lua_settop(L, 0); /* Empty the stack. */
12452 lua_pop(L, 1);
Christopher Fauletd09cc512021-03-24 14:48:45 +010012453 trace = hlua_traceback(L, ", ");
Thierry Fournier670db242020-11-28 10:49:59 +010012454 if (msg)
12455 ha_alert("Lua init: %s: '%s' from %s\n", kind, msg, trace);
12456 else
12457 ha_alert("Lua init: unknown %s from %s\n", kind, trace);
12458 return_status = 0;
12459 break;
12460
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010012461 default:
Thierry Fournier670db242020-11-28 10:49:59 +010012462 /* Unknown error */
12463 kind = "Unknown error";
Willy Tarreau14de3952022-11-14 07:08:28 +010012464 __fallthrough;
Thierry Fournier670db242020-11-28 10:49:59 +010012465 case LUA_YIELD:
12466 /* yield is not configured at this step, this state doesn't happen */
12467 if (!kind)
12468 kind = "yield not allowed";
Willy Tarreau14de3952022-11-14 07:08:28 +010012469 __fallthrough;
Thierry Fournier670db242020-11-28 10:49:59 +010012470 case LUA_ERRMEM:
12471 if (!kind)
12472 kind = "out of memory error";
Thierry Fournierb8cef172020-11-28 15:37:17 +010012473 lua_settop(L, 0);
12474 lua_pop(L, 1);
Christopher Fauletd09cc512021-03-24 14:48:45 +010012475 trace = hlua_traceback(L, ", ");
Thierry Fournier670db242020-11-28 10:49:59 +010012476 ha_alert("Lua init: %s: %s\n", kind, trace);
12477 return_status = 0;
12478 break;
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010012479 }
Thierry Fournier670db242020-11-28 10:49:59 +010012480 if (!return_status)
12481 break;
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010012482 }
Thierry Fournier3c539322020-11-28 16:05:05 +010012483
12484 lua_atpanic(L, hlua_panic_safe);
Thierry Fournier670db242020-11-28 10:49:59 +010012485 return return_status;
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010012486}
12487
Thierry Fournierb8cef172020-11-28 15:37:17 +010012488int hlua_post_init()
12489{
Thierry Fournier59f11be2020-11-29 00:37:41 +010012490 int ret;
12491 int i;
12492 int errors;
12493 char *err = NULL;
12494 struct hlua_function *fcn;
Christopher Faulet69c581a2021-05-31 08:54:04 +020012495 struct hlua_reg_filter *reg_flt;
Thierry Fournier59f11be2020-11-29 00:37:41 +010012496
Willy Tarreaub1310492021-08-30 09:35:18 +020012497#if defined(USE_OPENSSL)
Thierry Fournierb8cef172020-11-28 15:37:17 +010012498 /* Initialize SSL server. */
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010012499 if (socket_ssl->xprt->prepare_srv) {
Thierry Fournierb8cef172020-11-28 15:37:17 +010012500 int saved_used_backed = global.ssl_used_backend;
12501 // don't affect maxconn automatic computation
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010012502 socket_ssl->xprt->prepare_srv(socket_ssl);
Thierry Fournierb8cef172020-11-28 15:37:17 +010012503 global.ssl_used_backend = saved_used_backed;
12504 }
12505#endif
12506
Thierry Fournierc7492592020-11-28 23:57:24 +010012507 /* Perform post init of common thread */
12508 hlua_state_id = 0;
Willy Tarreau43ab05b2021-09-28 09:43:11 +020012509 ha_set_thread(&ha_thread_info[0]);
Thierry Fournier59f11be2020-11-29 00:37:41 +010012510 ret = hlua_post_init_state(hlua_states[hlua_state_id]);
12511 if (ret == 0)
12512 return 0;
12513
12514 /* init remaining lua states and load files */
12515 for (hlua_state_id = 2; hlua_state_id < global.nbthread + 1; hlua_state_id++) {
12516
12517 /* set thread context */
Willy Tarreau43ab05b2021-09-28 09:43:11 +020012518 ha_set_thread(&ha_thread_info[hlua_state_id - 1]);
Thierry Fournier59f11be2020-11-29 00:37:41 +010012519
12520 /* Init lua state */
12521 hlua_states[hlua_state_id] = hlua_init_state(hlua_state_id);
12522
12523 /* Load lua files */
12524 for (i = 0; per_thread_load && per_thread_load[i]; i++) {
12525 ret = hlua_load_state(per_thread_load[i], hlua_states[hlua_state_id], &err);
12526 if (ret != 0) {
12527 ha_alert("Lua init: %s\n", err);
12528 return 0;
12529 }
12530 }
12531 }
12532
12533 /* Reset thread context */
Willy Tarreau43ab05b2021-09-28 09:43:11 +020012534 ha_set_thread(NULL);
Thierry Fournier59f11be2020-11-29 00:37:41 +010012535
12536 /* Execute post init for all states */
12537 for (hlua_state_id = 1; hlua_state_id < global.nbthread + 1; hlua_state_id++) {
12538
12539 /* set thread context */
Willy Tarreau43ab05b2021-09-28 09:43:11 +020012540 ha_set_thread(&ha_thread_info[hlua_state_id - 1]);
Thierry Fournier59f11be2020-11-29 00:37:41 +010012541
12542 /* run post init */
12543 ret = hlua_post_init_state(hlua_states[hlua_state_id]);
12544 if (ret == 0)
12545 return 0;
12546 }
12547
12548 /* Reset thread context */
Willy Tarreau43ab05b2021-09-28 09:43:11 +020012549 ha_set_thread(NULL);
Thierry Fournier59f11be2020-11-29 00:37:41 +010012550
12551 /* control functions registering. Each function must have:
12552 * - only the function_ref[0] set positive and all other to -1
12553 * - only the function_ref[0] set to -1 and all other positive
12554 * This ensure a same reference is not used both in shared
12555 * lua state and thread dedicated lua state. Note: is the case
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +050012556 * reach, the shared state is priority, but the bug will be
Thierry Fournier59f11be2020-11-29 00:37:41 +010012557 * complicated to found for the end user.
12558 */
12559 errors = 0;
12560 list_for_each_entry(fcn, &referenced_functions, l) {
12561 ret = 0;
12562 for (i = 1; i < global.nbthread + 1; i++) {
12563 if (fcn->function_ref[i] == -1)
12564 ret--;
12565 else
12566 ret++;
12567 }
12568 if (abs(ret) != global.nbthread) {
12569 ha_alert("Lua function '%s' is not referenced in all thread. "
12570 "Expect function in all thread or in none thread.\n", fcn->name);
12571 errors++;
12572 continue;
12573 }
12574
12575 if ((fcn->function_ref[0] == -1) == (ret < 0)) {
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +050012576 ha_alert("Lua function '%s' is referenced both ins shared Lua context (through lua-load) "
12577 "and per-thread Lua context (through lua-load-per-thread). these two context "
Thierry Fournier59f11be2020-11-29 00:37:41 +010012578 "exclusive.\n", fcn->name);
12579 errors++;
12580 }
12581 }
12582
Christopher Faulet69c581a2021-05-31 08:54:04 +020012583 /* Do the same with registered filters */
12584 list_for_each_entry(reg_flt, &referenced_filters, l) {
12585 ret = 0;
12586 for (i = 1; i < global.nbthread + 1; i++) {
12587 if (reg_flt->flt_ref[i] == -1)
12588 ret--;
12589 else
12590 ret++;
12591 }
12592 if (abs(ret) != global.nbthread) {
12593 ha_alert("Lua filter '%s' is not referenced in all thread. "
12594 "Expect function in all thread or in none thread.\n", reg_flt->name);
12595 errors++;
12596 continue;
12597 }
12598
12599 if ((reg_flt->flt_ref[0] == -1) == (ret < 0)) {
12600 ha_alert("Lua filter '%s' is referenced both ins shared Lua context (through lua-load) "
12601 "and per-thread Lua context (through lua-load-per-thread). these two context "
12602 "exclusive.\n", fcn->name);
12603 errors++;
12604 }
12605 }
12606
12607
Thierry Fournier59f11be2020-11-29 00:37:41 +010012608 if (errors > 0)
12609 return 0;
12610
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +050012611 /* after this point, this global will no longer be used, so set to
Thierry Fournier59f11be2020-11-29 00:37:41 +010012612 * -1 in order to have probably a segfault if someone use it
12613 */
12614 hlua_state_id = -1;
12615
12616 return 1;
Thierry Fournierb8cef172020-11-28 15:37:17 +010012617}
12618
Willy Tarreau32f61e22015-03-18 17:54:59 +010012619/* The memory allocator used by the Lua stack. <ud> is a pointer to the
12620 * allocator's context. <ptr> is the pointer to alloc/free/realloc. <osize>
12621 * is the previously allocated size or the kind of object in case of a new
Willy Tarreaud36c7fa2020-12-02 12:26:29 +010012622 * allocation. <nsize> is the requested new size. A new allocation is
12623 * indicated by <ptr> being NULL. A free is indicated by <nsize> being
Willy Tarreaucdb53462020-12-02 12:12:00 +010012624 * zero. This one verifies that the limits are respected but is optimized
12625 * for the fast case where limits are not used, hence stats are not updated.
Willy Tarreaua5efdff2021-10-22 16:00:02 +020012626 *
12627 * Warning: while this API ressembles glibc's realloc() a lot, glibc surpasses
12628 * POSIX by making realloc(ptr,0) an effective free(), but others do not do
12629 * that and will simply allocate zero as if it were the result of malloc(0),
12630 * so mapping this onto realloc() will lead to memory leaks on non-glibc
12631 * systems.
Willy Tarreau32f61e22015-03-18 17:54:59 +010012632 */
12633static void *hlua_alloc(void *ud, void *ptr, size_t osize, size_t nsize)
12634{
12635 struct hlua_mem_allocator *zone = ud;
Willy Tarreaucdb53462020-12-02 12:12:00 +010012636 size_t limit, old, new;
12637
12638 /* a limit of ~0 means unlimited and boot complete, so there's no need
12639 * for accounting anymore.
12640 */
Willy Tarreaua5efdff2021-10-22 16:00:02 +020012641 if (likely(~zone->limit == 0)) {
12642 if (!nsize)
12643 ha_free(&ptr);
12644 else
12645 ptr = realloc(ptr, nsize);
12646 return ptr;
12647 }
Willy Tarreau32f61e22015-03-18 17:54:59 +010012648
Willy Tarreaud36c7fa2020-12-02 12:26:29 +010012649 if (!ptr)
12650 osize = 0;
Willy Tarreau32f61e22015-03-18 17:54:59 +010012651
Willy Tarreaucdb53462020-12-02 12:12:00 +010012652 /* enforce strict limits across all threads */
12653 limit = zone->limit;
12654 old = _HA_ATOMIC_LOAD(&zone->allocated);
12655 do {
12656 new = old + nsize - osize;
12657 if (unlikely(nsize && limit && new > limit))
12658 return NULL;
12659 } while (!_HA_ATOMIC_CAS(&zone->allocated, &old, new));
Willy Tarreau32f61e22015-03-18 17:54:59 +010012660
Willy Tarreaua5efdff2021-10-22 16:00:02 +020012661 if (!nsize)
12662 ha_free(&ptr);
12663 else
12664 ptr = realloc(ptr, nsize);
Willy Tarreaucdb53462020-12-02 12:12:00 +010012665
12666 if (unlikely(!ptr && nsize)) // failed
12667 _HA_ATOMIC_SUB(&zone->allocated, nsize - osize);
12668
12669 __ha_barrier_atomic_store();
Willy Tarreau32f61e22015-03-18 17:54:59 +010012670 return ptr;
12671}
12672
Thierry Fournierecb83c22020-11-28 15:49:44 +010012673/* This function can fail with an abort() due to a Lua critical error.
Thierry FOURNIERbabae282015-09-17 11:36:37 +020012674 * We are in the initialisation process of HAProxy, this abort() is
12675 * tolerated.
12676 */
Thierry Fournierecb83c22020-11-28 15:49:44 +010012677lua_State *hlua_init_state(int thread_num)
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +010012678{
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010012679 int i;
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010012680 int idx;
12681 struct sample_fetch *sf;
Thierry FOURNIER594afe72015-03-10 23:58:30 +010012682 struct sample_conv *sc;
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010012683 char *p;
Thierry Fournierfd107a22016-02-19 19:57:23 +010012684 const char *error_msg;
Thierry Fournier4234dbd2020-11-28 13:18:23 +010012685 void **context;
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012686 lua_State *L;
Thierry Fournier59f11be2020-11-29 00:37:41 +010012687 struct prepend_path *pp;
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010012688
Thierry FOURNIER380d0932015-01-23 14:27:52 +010012689 /* Init main lua stack. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012690 L = lua_newstate(hlua_alloc, &hlua_global_allocator);
Thierry FOURNIER380d0932015-01-23 14:27:52 +010012691
Thierry Fournier4234dbd2020-11-28 13:18:23 +010012692 /* Initialise Lua context to NULL */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012693 context = lua_getextraspace(L);
Thierry Fournier4234dbd2020-11-28 13:18:23 +010012694 *context = NULL;
12695
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -080012696 /* From this point, until the end of the initialisation function,
Thierry FOURNIERbabae282015-09-17 11:36:37 +020012697 * the Lua function can fail with an abort. We are in the initialisation
12698 * process of HAProxy, this abort() is tolerated.
12699 */
12700
Thierry Fournier3c539322020-11-28 16:05:05 +010012701 /* Call post initialisation function in safe environment. */
12702 if (setjmp(safe_ljmp_env) != 0) {
12703 lua_atpanic(L, hlua_panic_safe);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012704 if (lua_type(L, -1) == LUA_TSTRING)
12705 error_msg = lua_tostring(L, -1);
Thierry Fournier2f05cc62020-11-28 16:08:02 +010012706 else
12707 error_msg = "critical error";
12708 fprintf(stderr, "Lua init: %s.\n", error_msg);
12709 exit(1);
Thierry Fournier3c539322020-11-28 16:05:05 +010012710 } else {
12711 lua_atpanic(L, hlua_panic_ljmp);
Thierry Fournier2f05cc62020-11-28 16:08:02 +010012712 }
12713
Thierry FOURNIER380d0932015-01-23 14:27:52 +010012714 /* Initialise lua. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012715 luaL_openlibs(L);
Tim Duesterhus541fe1e2020-01-12 13:55:41 +010012716#define HLUA_PREPEND_PATH_TOSTRING1(x) #x
12717#define HLUA_PREPEND_PATH_TOSTRING(x) HLUA_PREPEND_PATH_TOSTRING1(x)
12718#ifdef HLUA_PREPEND_PATH
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012719 hlua_prepend_path(L, "path", HLUA_PREPEND_PATH_TOSTRING(HLUA_PREPEND_PATH));
Tim Duesterhus541fe1e2020-01-12 13:55:41 +010012720#endif
12721#ifdef HLUA_PREPEND_CPATH
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012722 hlua_prepend_path(L, "cpath", HLUA_PREPEND_PATH_TOSTRING(HLUA_PREPEND_CPATH));
Tim Duesterhus541fe1e2020-01-12 13:55:41 +010012723#endif
12724#undef HLUA_PREPEND_PATH_TOSTRING
12725#undef HLUA_PREPEND_PATH_TOSTRING1
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010012726
Thierry Fournier59f11be2020-11-29 00:37:41 +010012727 /* Apply configured prepend path */
12728 list_for_each_entry(pp, &prepend_path_list, l)
12729 hlua_prepend_path(L, pp->type, pp->path);
12730
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010012731 /*
12732 *
12733 * Create "core" object.
12734 *
12735 */
12736
Thierry FOURNIERa2d8c652015-03-11 17:29:39 +010012737 /* This table entry is the object "core" base. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012738 lua_newtable(L);
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010012739
Thierry Fournierecb83c22020-11-28 15:49:44 +010012740 /* set the thread id */
12741 hlua_class_const_int(L, "thread", thread_num);
12742
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010012743 /* Push the loglevel constants. */
Willy Tarreau80f5fae2015-02-27 16:38:20 +010012744 for (i = 0; i < NB_LOG_LEVELS; i++)
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012745 hlua_class_const_int(L, log_levels[i], i);
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010012746
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010012747 /* Register special functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012748 hlua_class_function(L, "register_init", hlua_register_init);
12749 hlua_class_function(L, "register_task", hlua_register_task);
12750 hlua_class_function(L, "register_fetches", hlua_register_fetches);
12751 hlua_class_function(L, "register_converters", hlua_register_converters);
12752 hlua_class_function(L, "register_action", hlua_register_action);
12753 hlua_class_function(L, "register_service", hlua_register_service);
12754 hlua_class_function(L, "register_cli", hlua_register_cli);
Christopher Faulet69c581a2021-05-31 08:54:04 +020012755 hlua_class_function(L, "register_filter", hlua_register_filter);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012756 hlua_class_function(L, "yield", hlua_yield);
12757 hlua_class_function(L, "set_nice", hlua_set_nice);
12758 hlua_class_function(L, "sleep", hlua_sleep);
12759 hlua_class_function(L, "msleep", hlua_msleep);
12760 hlua_class_function(L, "add_acl", hlua_add_acl);
12761 hlua_class_function(L, "del_acl", hlua_del_acl);
12762 hlua_class_function(L, "set_map", hlua_set_map);
12763 hlua_class_function(L, "del_map", hlua_del_map);
12764 hlua_class_function(L, "tcp", hlua_socket_new);
William Lallemand3956c4e2021-09-21 16:25:15 +020012765 hlua_class_function(L, "httpclient", hlua_httpclient_new);
Aurelien DARRAGONc84899c2023-02-20 18:18:59 +010012766 hlua_class_function(L, "event_sub", hlua_event_global_sub);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012767 hlua_class_function(L, "log", hlua_log);
12768 hlua_class_function(L, "Debug", hlua_log_debug);
12769 hlua_class_function(L, "Info", hlua_log_info);
12770 hlua_class_function(L, "Warning", hlua_log_warning);
12771 hlua_class_function(L, "Alert", hlua_log_alert);
12772 hlua_class_function(L, "done", hlua_done);
12773 hlua_fcn_reg_core_fcn(L);
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010012774
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012775 lua_setglobal(L, "core");
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010012776
12777 /*
12778 *
Christopher Faulet0f3c8902020-01-31 18:57:12 +010012779 * Create "act" object.
12780 *
12781 */
12782
12783 /* This table entry is the object "act" base. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012784 lua_newtable(L);
Christopher Faulet0f3c8902020-01-31 18:57:12 +010012785
12786 /* push action return constants */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012787 hlua_class_const_int(L, "CONTINUE", ACT_RET_CONT);
12788 hlua_class_const_int(L, "STOP", ACT_RET_STOP);
12789 hlua_class_const_int(L, "YIELD", ACT_RET_YIELD);
12790 hlua_class_const_int(L, "ERROR", ACT_RET_ERR);
12791 hlua_class_const_int(L, "DONE", ACT_RET_DONE);
12792 hlua_class_const_int(L, "DENY", ACT_RET_DENY);
12793 hlua_class_const_int(L, "ABORT", ACT_RET_ABRT);
12794 hlua_class_const_int(L, "INVALID", ACT_RET_INV);
Christopher Faulet0f3c8902020-01-31 18:57:12 +010012795
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012796 hlua_class_function(L, "wake_time", hlua_set_wake_time);
Christopher Faulet2c2c2e32020-01-31 19:07:52 +010012797
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012798 lua_setglobal(L, "act");
Christopher Faulet0f3c8902020-01-31 18:57:12 +010012799
12800 /*
12801 *
Christopher Faulet69c581a2021-05-31 08:54:04 +020012802 * Create "Filter" object.
12803 *
12804 */
12805
12806 /* This table entry is the object "filter" base. */
12807 lua_newtable(L);
12808
12809 /* push flags and constants */
12810 hlua_class_const_int(L, "CONTINUE", 1);
12811 hlua_class_const_int(L, "WAIT", 0);
12812 hlua_class_const_int(L, "ERROR", -1);
12813
12814 hlua_class_const_int(L, "FLT_CFG_FL_HTX", FLT_CFG_FL_HTX);
12815
Christopher Fauletc404f112020-02-26 15:03:09 +010012816 hlua_class_function(L, "wake_time", hlua_set_wake_time);
12817 hlua_class_function(L, "register_data_filter", hlua_register_data_filter);
12818 hlua_class_function(L, "unregister_data_filter", hlua_unregister_data_filter);
12819
Christopher Faulet69c581a2021-05-31 08:54:04 +020012820 lua_setglobal(L, "filter");
12821
12822 /*
12823 *
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012824 * Register class Map
12825 *
12826 */
12827
12828 /* This table entry is the object "Map" base. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012829 lua_newtable(L);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012830
12831 /* register pattern types. */
12832 for (i=0; i<PAT_MATCH_NUM; i++)
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012833 hlua_class_const_int(L, pat_match_names[i], i);
Thierry FOURNIER4dc71972017-01-28 08:33:08 +010012834 for (i=0; i<PAT_MATCH_NUM; i++) {
Willy Tarreau843b7cb2018-07-13 10:54:26 +020012835 snprintf(trash.area, trash.size, "_%s", pat_match_names[i]);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012836 hlua_class_const_int(L, trash.area, i);
Thierry FOURNIER4dc71972017-01-28 08:33:08 +010012837 }
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012838
12839 /* register constructor. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012840 hlua_class_function(L, "new", hlua_map_new);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012841
12842 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012843 lua_newtable(L);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012844
Ilya Shipitsind4259502020-04-08 01:07:56 +050012845 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012846 lua_pushstring(L, "__index");
12847 lua_newtable(L);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012848
12849 /* Register . */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012850 hlua_class_function(L, "lookup", hlua_map_lookup);
12851 hlua_class_function(L, "slookup", hlua_map_slookup);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012852
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012853 lua_rawset(L, -3);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012854
Thierry Fournier45e78d72016-02-19 18:34:46 +010012855 /* Register previous table in the registry with reference and named entry.
12856 * The function hlua_register_metatable() pops the stack, so we
12857 * previously create a copy of the table.
12858 */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012859 lua_pushvalue(L, -1); /* Copy the -1 entry and push it on the stack. */
12860 class_map_ref = hlua_register_metatable(L, CLASS_MAP);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012861
12862 /* Assign the metatable to the mai Map object. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012863 lua_setmetatable(L, -2);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012864
12865 /* Set a name to the table. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012866 lua_setglobal(L, "Map");
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012867
12868 /*
12869 *
William Lallemand30fcca12022-03-30 12:03:12 +020012870 * Register "CertCache" class
12871 *
12872 */
12873
12874 /* Create and fill the metatable. */
12875 lua_newtable(L);
12876 /* Register */
12877 hlua_class_function(L, "set", hlua_ckch_set);
12878 lua_setglobal(L, CLASS_CERTCACHE); /* Create global object called Regex */
12879
12880 /*
12881 *
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010012882 * Register class Channel
12883 *
12884 */
12885
12886 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012887 lua_newtable(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010012888
Ilya Shipitsind4259502020-04-08 01:07:56 +050012889 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012890 lua_pushstring(L, "__index");
12891 lua_newtable(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010012892
12893 /* Register . */
Christopher Faulet6a79fc12021-08-06 16:02:36 +020012894 hlua_class_function(L, "data", hlua_channel_get_data);
12895 hlua_class_function(L, "line", hlua_channel_get_line);
12896 hlua_class_function(L, "set", hlua_channel_set_data);
12897 hlua_class_function(L, "remove", hlua_channel_del_data);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012898 hlua_class_function(L, "append", hlua_channel_append);
Christopher Faulet6a79fc12021-08-06 16:02:36 +020012899 hlua_class_function(L, "prepend", hlua_channel_prepend);
12900 hlua_class_function(L, "insert", hlua_channel_insert_data);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012901 hlua_class_function(L, "send", hlua_channel_send);
12902 hlua_class_function(L, "forward", hlua_channel_forward);
Christopher Faulet6a79fc12021-08-06 16:02:36 +020012903 hlua_class_function(L, "input", hlua_channel_get_in_len);
12904 hlua_class_function(L, "output", hlua_channel_get_out_len);
12905 hlua_class_function(L, "may_recv", hlua_channel_may_recv);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012906 hlua_class_function(L, "is_full", hlua_channel_is_full);
12907 hlua_class_function(L, "is_resp", hlua_channel_is_resp);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010012908
Christopher Faulet6a79fc12021-08-06 16:02:36 +020012909 /* Deprecated API */
12910 hlua_class_function(L, "get", hlua_channel_get);
12911 hlua_class_function(L, "dup", hlua_channel_dup);
12912 hlua_class_function(L, "getline", hlua_channel_getline);
12913 hlua_class_function(L, "get_in_len", hlua_channel_get_in_len);
12914 hlua_class_function(L, "get_out_len", hlua_channel_get_out_len);
12915
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012916 lua_rawset(L, -3);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010012917
12918 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012919 class_channel_ref = hlua_register_metatable(L, CLASS_CHANNEL);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010012920
12921 /*
12922 *
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010012923 * Register class Fetches
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010012924 *
12925 */
12926
12927 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012928 lua_newtable(L);
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010012929
Ilya Shipitsind4259502020-04-08 01:07:56 +050012930 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012931 lua_pushstring(L, "__index");
12932 lua_newtable(L);
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010012933
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010012934 /* Browse existing fetches and create the associated
12935 * object method.
12936 */
12937 sf = NULL;
12938 while ((sf = sample_fetch_getnext(sf, &idx)) != NULL) {
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010012939 /* gL.Tua doesn't support '.' and '-' in the function names, replace it
12940 * by an underscore.
12941 */
Willy Tarreau5ef96562021-08-26 16:48:53 +020012942 strlcpy2(trash.area, sf->kw, trash.size);
Willy Tarreau843b7cb2018-07-13 10:54:26 +020012943 for (p = trash.area; *p; p++)
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010012944 if (*p == '.' || *p == '-' || *p == '+')
12945 *p = '_';
12946
12947 /* Register the function. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012948 lua_pushstring(L, trash.area);
12949 lua_pushlightuserdata(L, sf);
12950 lua_pushcclosure(L, hlua_run_sample_fetch, 1);
12951 lua_rawset(L, -3);
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010012952 }
12953
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012954 lua_rawset(L, -3);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010012955
12956 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012957 class_fetches_ref = hlua_register_metatable(L, CLASS_FETCHES);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010012958
12959 /*
12960 *
Thierry FOURNIER594afe72015-03-10 23:58:30 +010012961 * Register class Converters
12962 *
12963 */
12964
12965 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012966 lua_newtable(L);
Thierry FOURNIER594afe72015-03-10 23:58:30 +010012967
12968 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012969 lua_pushstring(L, "__index");
12970 lua_newtable(L);
Thierry FOURNIER594afe72015-03-10 23:58:30 +010012971
12972 /* Browse existing converters and create the associated
12973 * object method.
12974 */
12975 sc = NULL;
12976 while ((sc = sample_conv_getnext(sc, &idx)) != NULL) {
Thierry FOURNIER594afe72015-03-10 23:58:30 +010012977 /* gL.Tua doesn't support '.' and '-' in the function names, replace it
12978 * by an underscore.
12979 */
Willy Tarreau5ef96562021-08-26 16:48:53 +020012980 strlcpy2(trash.area, sc->kw, trash.size);
Willy Tarreau843b7cb2018-07-13 10:54:26 +020012981 for (p = trash.area; *p; p++)
Thierry FOURNIER594afe72015-03-10 23:58:30 +010012982 if (*p == '.' || *p == '-' || *p == '+')
12983 *p = '_';
12984
12985 /* Register the function. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012986 lua_pushstring(L, trash.area);
12987 lua_pushlightuserdata(L, sc);
12988 lua_pushcclosure(L, hlua_run_sample_conv, 1);
12989 lua_rawset(L, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +010012990 }
12991
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012992 lua_rawset(L, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +010012993
12994 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012995 class_converters_ref = hlua_register_metatable(L, CLASS_CONVERTERS);
Thierry FOURNIER594afe72015-03-10 23:58:30 +010012996
12997 /*
12998 *
Thierry FOURNIER08504f42015-03-16 14:17:08 +010012999 * Register class HTTP
13000 *
13001 */
13002
13003 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013004 lua_newtable(L);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010013005
Ilya Shipitsind4259502020-04-08 01:07:56 +050013006 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013007 lua_pushstring(L, "__index");
13008 lua_newtable(L);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010013009
13010 /* Register Lua functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013011 hlua_class_function(L, "req_get_headers",hlua_http_req_get_headers);
13012 hlua_class_function(L, "req_del_header", hlua_http_req_del_hdr);
13013 hlua_class_function(L, "req_rep_header", hlua_http_req_rep_hdr);
13014 hlua_class_function(L, "req_rep_value", hlua_http_req_rep_val);
13015 hlua_class_function(L, "req_add_header", hlua_http_req_add_hdr);
13016 hlua_class_function(L, "req_set_header", hlua_http_req_set_hdr);
13017 hlua_class_function(L, "req_set_method", hlua_http_req_set_meth);
13018 hlua_class_function(L, "req_set_path", hlua_http_req_set_path);
13019 hlua_class_function(L, "req_set_query", hlua_http_req_set_query);
13020 hlua_class_function(L, "req_set_uri", hlua_http_req_set_uri);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010013021
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013022 hlua_class_function(L, "res_get_headers",hlua_http_res_get_headers);
13023 hlua_class_function(L, "res_del_header", hlua_http_res_del_hdr);
13024 hlua_class_function(L, "res_rep_header", hlua_http_res_rep_hdr);
13025 hlua_class_function(L, "res_rep_value", hlua_http_res_rep_val);
13026 hlua_class_function(L, "res_add_header", hlua_http_res_add_hdr);
13027 hlua_class_function(L, "res_set_header", hlua_http_res_set_hdr);
13028 hlua_class_function(L, "res_set_status", hlua_http_res_set_status);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010013029
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013030 lua_rawset(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010013031
13032 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013033 class_http_ref = hlua_register_metatable(L, CLASS_HTTP);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010013034
Christopher Fauletdf97ac42020-02-26 16:57:19 +010013035 /*
13036 *
13037 * Register class HTTPMessage
13038 *
13039 */
13040
13041 /* Create and fill the metatable. */
13042 lua_newtable(L);
13043
Ilya Shipitsinff0f2782021-08-22 22:18:07 +050013044 /* Create and fill the __index entry. */
Christopher Fauletdf97ac42020-02-26 16:57:19 +010013045 lua_pushstring(L, "__index");
13046 lua_newtable(L);
13047
13048 /* Register Lua functions. */
13049 hlua_class_function(L, "is_resp", hlua_http_msg_is_resp);
13050 hlua_class_function(L, "get_stline", hlua_http_msg_get_stline);
13051 hlua_class_function(L, "get_headers", hlua_http_msg_get_headers);
13052 hlua_class_function(L, "del_header", hlua_http_msg_del_hdr);
13053 hlua_class_function(L, "rep_header", hlua_http_msg_rep_hdr);
13054 hlua_class_function(L, "rep_value", hlua_http_msg_rep_val);
13055 hlua_class_function(L, "add_header", hlua_http_msg_add_hdr);
13056 hlua_class_function(L, "set_header", hlua_http_msg_set_hdr);
13057 hlua_class_function(L, "set_method", hlua_http_msg_set_meth);
13058 hlua_class_function(L, "set_path", hlua_http_msg_set_path);
13059 hlua_class_function(L, "set_query", hlua_http_msg_set_query);
13060 hlua_class_function(L, "set_uri", hlua_http_msg_set_uri);
13061 hlua_class_function(L, "set_status", hlua_http_msg_set_status);
13062 hlua_class_function(L, "is_full", hlua_http_msg_is_full);
13063 hlua_class_function(L, "may_recv", hlua_http_msg_may_recv);
13064 hlua_class_function(L, "eom", hlua_http_msg_is_eom);
13065 hlua_class_function(L, "input", hlua_http_msg_get_in_len);
13066 hlua_class_function(L, "output", hlua_http_msg_get_out_len);
13067
13068 hlua_class_function(L, "body", hlua_http_msg_get_body);
13069 hlua_class_function(L, "set", hlua_http_msg_set_data);
13070 hlua_class_function(L, "remove", hlua_http_msg_del_data);
13071 hlua_class_function(L, "append", hlua_http_msg_append);
13072 hlua_class_function(L, "prepend", hlua_http_msg_prepend);
13073 hlua_class_function(L, "insert", hlua_http_msg_insert_data);
13074 hlua_class_function(L, "set_eom", hlua_http_msg_set_eom);
13075 hlua_class_function(L, "unset_eom", hlua_http_msg_unset_eom);
13076
13077 hlua_class_function(L, "send", hlua_http_msg_send);
13078 hlua_class_function(L, "forward", hlua_http_msg_forward);
13079
13080 lua_rawset(L, -3);
13081
13082 /* Register previous table in the registry with reference and named entry. */
13083 class_http_msg_ref = hlua_register_metatable(L, CLASS_HTTP_MSG);
William Lallemand3956c4e2021-09-21 16:25:15 +020013084
13085 /*
13086 *
13087 * Register class HTTPClient
13088 *
13089 */
13090
13091 /* Create and fill the metatable. */
13092 lua_newtable(L);
13093 lua_pushstring(L, "__index");
13094 lua_newtable(L);
13095 hlua_class_function(L, "get", hlua_httpclient_get);
William Lallemanddc2cc902021-10-26 11:43:26 +020013096 hlua_class_function(L, "head", hlua_httpclient_head);
13097 hlua_class_function(L, "put", hlua_httpclient_put);
13098 hlua_class_function(L, "post", hlua_httpclient_post);
13099 hlua_class_function(L, "delete", hlua_httpclient_delete);
William Lallemand3956c4e2021-09-21 16:25:15 +020013100 lua_settable(L, -3); /* Sets the __index entry. */
William Lallemandf77f1de2021-09-28 19:10:38 +020013101 /* Register the garbage collector entry. */
13102 lua_pushstring(L, "__gc");
13103 lua_pushcclosure(L, hlua_httpclient_gc, 0);
13104 lua_settable(L, -3); /* Push the last 2 entries in the table at index -3 */
13105
William Lallemand3956c4e2021-09-21 16:25:15 +020013106
13107
13108 class_httpclient_ref = hlua_register_metatable(L, CLASS_HTTPCLIENT);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010013109 /*
13110 *
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020013111 * Register class AppletTCP
13112 *
13113 */
13114
13115 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013116 lua_newtable(L);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020013117
Ilya Shipitsind4259502020-04-08 01:07:56 +050013118 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013119 lua_pushstring(L, "__index");
13120 lua_newtable(L);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020013121
13122 /* Register Lua functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013123 hlua_class_function(L, "getline", hlua_applet_tcp_getline);
13124 hlua_class_function(L, "receive", hlua_applet_tcp_recv);
13125 hlua_class_function(L, "send", hlua_applet_tcp_send);
13126 hlua_class_function(L, "set_priv", hlua_applet_tcp_set_priv);
13127 hlua_class_function(L, "get_priv", hlua_applet_tcp_get_priv);
13128 hlua_class_function(L, "set_var", hlua_applet_tcp_set_var);
13129 hlua_class_function(L, "unset_var", hlua_applet_tcp_unset_var);
13130 hlua_class_function(L, "get_var", hlua_applet_tcp_get_var);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020013131
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013132 lua_settable(L, -3);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020013133
13134 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013135 class_applet_tcp_ref = hlua_register_metatable(L, CLASS_APPLET_TCP);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020013136
13137 /*
13138 *
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020013139 * Register class AppletHTTP
13140 *
13141 */
13142
13143 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013144 lua_newtable(L);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020013145
Ilya Shipitsind4259502020-04-08 01:07:56 +050013146 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013147 lua_pushstring(L, "__index");
13148 lua_newtable(L);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020013149
13150 /* Register Lua functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013151 hlua_class_function(L, "set_priv", hlua_applet_http_set_priv);
13152 hlua_class_function(L, "get_priv", hlua_applet_http_get_priv);
13153 hlua_class_function(L, "set_var", hlua_applet_http_set_var);
13154 hlua_class_function(L, "unset_var", hlua_applet_http_unset_var);
13155 hlua_class_function(L, "get_var", hlua_applet_http_get_var);
13156 hlua_class_function(L, "getline", hlua_applet_http_getline);
13157 hlua_class_function(L, "receive", hlua_applet_http_recv);
13158 hlua_class_function(L, "send", hlua_applet_http_send);
13159 hlua_class_function(L, "add_header", hlua_applet_http_addheader);
13160 hlua_class_function(L, "set_status", hlua_applet_http_status);
13161 hlua_class_function(L, "start_response", hlua_applet_http_start_response);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020013162
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013163 lua_settable(L, -3);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020013164
13165 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013166 class_applet_http_ref = hlua_register_metatable(L, CLASS_APPLET_HTTP);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020013167
13168 /*
13169 *
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010013170 * Register class TXN
13171 *
13172 */
13173
13174 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013175 lua_newtable(L);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010013176
Ilya Shipitsind4259502020-04-08 01:07:56 +050013177 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013178 lua_pushstring(L, "__index");
13179 lua_newtable(L);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010013180
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +010013181 /* Register Lua functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013182 hlua_class_function(L, "set_priv", hlua_set_priv);
13183 hlua_class_function(L, "get_priv", hlua_get_priv);
13184 hlua_class_function(L, "set_var", hlua_set_var);
13185 hlua_class_function(L, "unset_var", hlua_unset_var);
13186 hlua_class_function(L, "get_var", hlua_get_var);
13187 hlua_class_function(L, "done", hlua_txn_done);
13188 hlua_class_function(L, "reply", hlua_txn_reply_new);
13189 hlua_class_function(L, "set_loglevel", hlua_txn_set_loglevel);
13190 hlua_class_function(L, "set_tos", hlua_txn_set_tos);
13191 hlua_class_function(L, "set_mark", hlua_txn_set_mark);
13192 hlua_class_function(L, "set_priority_class", hlua_txn_set_priority_class);
13193 hlua_class_function(L, "set_priority_offset", hlua_txn_set_priority_offset);
13194 hlua_class_function(L, "deflog", hlua_txn_deflog);
13195 hlua_class_function(L, "log", hlua_txn_log);
13196 hlua_class_function(L, "Debug", hlua_txn_log_debug);
13197 hlua_class_function(L, "Info", hlua_txn_log_info);
13198 hlua_class_function(L, "Warning", hlua_txn_log_warning);
13199 hlua_class_function(L, "Alert", hlua_txn_log_alert);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +010013200
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013201 lua_rawset(L, -3);
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010013202
13203 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013204 class_txn_ref = hlua_register_metatable(L, CLASS_TXN);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010013205
13206 /*
13207 *
Christopher Faulet700d9e82020-01-31 12:21:52 +010013208 * Register class reply
13209 *
13210 */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013211 lua_newtable(L);
13212 lua_pushstring(L, "__index");
13213 lua_newtable(L);
13214 hlua_class_function(L, "set_status", hlua_txn_reply_set_status);
13215 hlua_class_function(L, "add_header", hlua_txn_reply_add_header);
13216 hlua_class_function(L, "del_header", hlua_txn_reply_del_header);
13217 hlua_class_function(L, "set_body", hlua_txn_reply_set_body);
13218 lua_settable(L, -3); /* Sets the __index entry. */
13219 class_txn_reply_ref = luaL_ref(L, LUA_REGISTRYINDEX);
Christopher Faulet700d9e82020-01-31 12:21:52 +010013220
13221
13222 /*
13223 *
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010013224 * Register class Socket
13225 *
13226 */
13227
13228 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013229 lua_newtable(L);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010013230
Ilya Shipitsind4259502020-04-08 01:07:56 +050013231 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013232 lua_pushstring(L, "__index");
13233 lua_newtable(L);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010013234
Baptiste Assmann84bb4932015-03-02 21:40:06 +010013235#ifdef USE_OPENSSL
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013236 hlua_class_function(L, "connect_ssl", hlua_socket_connect_ssl);
Baptiste Assmann84bb4932015-03-02 21:40:06 +010013237#endif
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013238 hlua_class_function(L, "connect", hlua_socket_connect);
13239 hlua_class_function(L, "send", hlua_socket_send);
13240 hlua_class_function(L, "receive", hlua_socket_receive);
13241 hlua_class_function(L, "close", hlua_socket_close);
13242 hlua_class_function(L, "getpeername", hlua_socket_getpeername);
13243 hlua_class_function(L, "getsockname", hlua_socket_getsockname);
13244 hlua_class_function(L, "setoption", hlua_socket_setoption);
13245 hlua_class_function(L, "settimeout", hlua_socket_settimeout);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010013246
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013247 lua_rawset(L, -3); /* Push the last 2 entries in the table at index -3 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010013248
13249 /* Register the garbage collector entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013250 lua_pushstring(L, "__gc");
13251 lua_pushcclosure(L, hlua_socket_gc, 0);
13252 lua_rawset(L, -3); /* Push the last 2 entries in the table at index -3 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010013253
13254 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013255 class_socket_ref = hlua_register_metatable(L, CLASS_SOCKET);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010013256
Thierry Fournieraafc7772020-12-04 11:47:47 +010013257 lua_atpanic(L, hlua_panic_safe);
13258
13259 return L;
13260}
13261
13262void hlua_init(void) {
13263 int i;
Amaury Denoyelle239fdbf2021-03-24 10:22:03 +010013264 char *errmsg;
Thierry Fournieraafc7772020-12-04 11:47:47 +010013265#ifdef USE_OPENSSL
13266 struct srv_kw *kw;
13267 int tmp_error;
13268 char *error;
13269 char *args[] = { /* SSL client configuration. */
13270 "ssl",
13271 "verify",
13272 "none",
13273 NULL
13274 };
13275#endif
13276
13277 /* Init post init function list head */
13278 for (i = 0; i < MAX_THREADS + 1; i++)
13279 LIST_INIT(&hlua_init_functions[i]);
13280
13281 /* Init state for common/shared lua parts */
13282 hlua_state_id = 0;
Willy Tarreau43ab05b2021-09-28 09:43:11 +020013283 ha_set_thread(NULL);
Thierry Fournieraafc7772020-12-04 11:47:47 +010013284 hlua_states[0] = hlua_init_state(0);
13285
13286 /* Init state 1 for thread 0. We have at least one thread. */
13287 hlua_state_id = 1;
Willy Tarreau43ab05b2021-09-28 09:43:11 +020013288 ha_set_thread(NULL);
Thierry Fournieraafc7772020-12-04 11:47:47 +010013289 hlua_states[1] = hlua_init_state(1);
13290
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010013291 /* Proxy and server configuration initialisation. */
William Lallemand6bb77b92021-07-28 15:48:16 +020013292 socket_proxy = alloc_new_proxy("LUA-SOCKET", PR_CAP_FE|PR_CAP_BE|PR_CAP_INT, &errmsg);
Amaury Denoyelle239fdbf2021-03-24 10:22:03 +010013293 if (!socket_proxy) {
13294 fprintf(stderr, "Lua init: %s\n", errmsg);
13295 exit(1);
13296 }
13297 proxy_preset_defaults(socket_proxy);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010013298
13299 /* Init TCP server: unchanged parameters */
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010013300 socket_tcp = new_server(socket_proxy);
13301 if (!socket_tcp) {
13302 fprintf(stderr, "Lua init: failed to allocate tcp server socket\n");
13303 exit(1);
13304 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010013305
13306#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010013307 /* Init TCP server: unchanged parameters */
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010013308 socket_ssl = new_server(socket_proxy);
13309 if (!socket_ssl) {
13310 fprintf(stderr, "Lua init: failed to allocate ssl server socket\n");
13311 exit(1);
13312 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010013313
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010013314 socket_ssl->use_ssl = 1;
13315 socket_ssl->xprt = xprt_get(XPRT_SSL);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010013316
Bertrand Jacquin80839ff2021-01-21 19:14:46 +000013317 for (i = 0; args[i] != NULL; i++) {
13318 if ((kw = srv_find_kw(args[i])) != NULL) { /* Maybe it's registered server keyword */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010013319 /*
13320 *
13321 * If the keyword is not known, we can search in the registered
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -080013322 * server keywords. This is useful to configure special SSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010013323 * features like client certificates and ssl_verify.
13324 *
13325 */
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010013326 tmp_error = kw->parse(args, &i, socket_proxy, socket_ssl, &error);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010013327 if (tmp_error != 0) {
13328 fprintf(stderr, "INTERNAL ERROR: %s\n", error);
13329 abort(); /* This must be never arrives because the command line
13330 not editable by the user. */
13331 }
Bertrand Jacquin80839ff2021-01-21 19:14:46 +000013332 i += kw->skip;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010013333 }
13334 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010013335#endif
Thierry Fournier75933d42016-01-21 09:30:18 +010013336
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +010013337}
Willy Tarreaubb57d942016-12-21 19:04:56 +010013338
Tim Duesterhusd0c0ca22020-07-04 11:53:26 +020013339static void hlua_deinit()
13340{
Willy Tarreau186f3762020-12-04 11:48:12 +010013341 int thr;
Christopher Faulet69c581a2021-05-31 08:54:04 +020013342 struct hlua_reg_filter *reg_flt, *reg_flt_bck;
13343
13344 list_for_each_entry_safe(reg_flt, reg_flt_bck, &referenced_filters, l)
13345 release_hlua_reg_filter(reg_flt);
Willy Tarreau186f3762020-12-04 11:48:12 +010013346
13347 for (thr = 0; thr < MAX_THREADS+1; thr++) {
13348 if (hlua_states[thr])
13349 lua_close(hlua_states[thr]);
13350 }
Willy Tarreau430bf4a2021-03-04 09:45:32 +010013351
Amaury Denoyellebc2ebfa2021-08-25 15:34:53 +020013352 srv_drop(socket_tcp);
Willy Tarreau430bf4a2021-03-04 09:45:32 +010013353
Willy Tarreau0f143af2021-03-05 10:41:48 +010013354#ifdef USE_OPENSSL
Amaury Denoyellebc2ebfa2021-08-25 15:34:53 +020013355 srv_drop(socket_ssl);
Willy Tarreau0f143af2021-03-05 10:41:48 +010013356#endif
Amaury Denoyelle239fdbf2021-03-24 10:22:03 +010013357
13358 free_proxy(socket_proxy);
Tim Duesterhusd0c0ca22020-07-04 11:53:26 +020013359}
13360
13361REGISTER_POST_DEINIT(hlua_deinit);
13362
Willy Tarreau80713382018-11-26 10:19:54 +010013363static void hlua_register_build_options(void)
13364{
Willy Tarreaubb57d942016-12-21 19:04:56 +010013365 char *ptr = NULL;
Willy Tarreau80713382018-11-26 10:19:54 +010013366
Willy Tarreaubb57d942016-12-21 19:04:56 +010013367 memprintf(&ptr, "Built with Lua version : %s", LUA_RELEASE);
13368 hap_register_build_opts(ptr, 1);
13369}
Willy Tarreau80713382018-11-26 10:19:54 +010013370
13371INITCALL0(STG_REGISTER, hlua_register_build_options);