blob: bea0cf754a98d89cf74df7de19091df4c816689b [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
Aurelien DARRAGONda9503c2022-11-25 09:10:07 +0100348/* Lua max execution timeouts. By default, stream-related
349 * lua coroutines (e.g.: actions) have a short timeout.
350 * On the other hand tasks coroutines don't have a timeout because
351 * a task may remain alive during all the haproxy execution.
352 *
353 * Timeouts are expressed in milliseconds, they are meant to be used
354 * with hlua timer's API exclusively.
355 * 0 means no timeout
356 */
Aurelien DARRAGON58e36e52023-04-06 22:51:56 +0200357static uint32_t hlua_timeout_burst = 1000; /* burst timeout. */
Aurelien DARRAGONda9503c2022-11-25 09:10:07 +0100358static uint32_t hlua_timeout_session = 4000; /* session timeout. */
359static uint32_t hlua_timeout_task = 0; /* task timeout. */
360static uint32_t hlua_timeout_applet = 4000; /* applet timeout. */
361
362/* hlua multipurpose timer:
363 * used to compute burst lua time (within a single hlua_ctx_resume())
364 * and cumulative lua time for a given coroutine, and to check
365 * the lua coroutine against the configured timeouts
366 */
367
368/* fetch per-thread cpu_time with ms precision (may wrap) */
369static inline uint32_t _hlua_time_ms()
370{
371 /* We're interested in the current cpu time in ms, which will be returned
372 * as a uint32_t to save some space.
373 * We must take the following into account:
374 *
375 * - now_cpu_time_fast() which returns the time in nanoseconds as a uint64_t
376 * will wrap every 585 years.
377 * - uint32_t may only contain 4294967295ms (~=49.7 days), so _hlua_time_ms()
378 * itself will also wrap every 49.7 days.
379 *
380 * While we can safely ignore the now_cpu_time_fast() wrap, we must
381 * take care of the uint32_t wrap by making sure to exclusively
382 * manipulate the time using uint32_t everywhere _hlua_time_ms()
383 * is involved.
384 */
385 return (uint32_t)(now_cpu_time_fast() / 1000000ULL);
386}
387
388/* computes time spent in a single lua execution (in ms) */
389static inline uint32_t _hlua_time_burst(const struct hlua_timer *timer)
390{
391 uint32_t burst_ms;
392
393 /* wrapping is expected and properly
394 * handled thanks to _hlua_time_ms() and burst_ms
395 * being of the same type
396 */
397 burst_ms = _hlua_time_ms() - timer->start;
398 return burst_ms;
399}
400
401static inline void hlua_timer_init(struct hlua_timer *timer, unsigned int max)
402{
403 timer->cumulative = 0;
404 timer->burst = 0;
405 timer->max = max;
406}
407
408/* reset the timer ctx between 2 yields */
409static inline void hlua_timer_reset(struct hlua_timer *timer)
410{
411 timer->cumulative += timer->burst;
412 timer->burst = 0;
413}
414
415/* start the timer right before a new execution */
416static inline void hlua_timer_start(struct hlua_timer *timer)
417{
418 timer->start = _hlua_time_ms();
419}
420
421/* update hlua timer when finishing an execution */
422static inline void hlua_timer_stop(struct hlua_timer *timer)
423{
424 timer->burst += _hlua_time_burst(timer);
425}
426
Aurelien DARRAGON58e36e52023-04-06 22:51:56 +0200427/* check the timers for current hlua context:
428 * - first check for burst timeout (max execution time for the current
429 hlua resume, ie: time between effective yields)
430 * - then check for yield cumulative timeout
431 *
Aurelien DARRAGONda9503c2022-11-25 09:10:07 +0100432 * Returns 1 if the check succeeded and 0 if it failed
433 * (ie: timeout exceeded)
Thierry FOURNIERbd413492015-03-03 16:52:26 +0100434 */
Aurelien DARRAGONda9503c2022-11-25 09:10:07 +0100435static inline int hlua_timer_check(const struct hlua_timer *timer)
436{
437 uint32_t pburst = _hlua_time_burst(timer); /* pending burst time in ms */
438
Aurelien DARRAGON58e36e52023-04-06 22:51:56 +0200439 if (hlua_timeout_burst && (timer->burst + pburst) > hlua_timeout_burst)
440 return 0; /* burst timeout exceeded */
Aurelien DARRAGONda9503c2022-11-25 09:10:07 +0100441 if (timer->max && (timer->cumulative + timer->burst + pburst) > timer->max)
442 return 0; /* cumulative timeout exceeded */
443 return 1; /* ok */
444}
Thierry FOURNIERbd413492015-03-03 16:52:26 +0100445
Thierry FOURNIERee9f8022015-03-03 17:37:37 +0100446/* Interrupts the Lua processing each "hlua_nb_instruction" instructions.
447 * it is used for preventing infinite loops.
448 *
449 * I test the scheer with an infinite loop containing one incrementation
450 * and one test. I run this loop between 10 seconds, I raise a ceil of
451 * 710M loops from one interrupt each 9000 instructions, so I fix the value
452 * to one interrupt each 10 000 instructions.
453 *
454 * configured | Number of
455 * instructions | loops executed
456 * between two | in milions
457 * forced yields |
458 * ---------------+---------------
459 * 10 | 160
460 * 500 | 670
461 * 1000 | 680
462 * 5000 | 700
463 * 7000 | 700
464 * 8000 | 700
465 * 9000 | 710 <- ceil
466 * 10000 | 710
467 * 100000 | 710
468 * 1000000 | 710
469 *
470 */
471static unsigned int hlua_nb_instruction = 10000;
472
Willy Tarreaucdb53462020-12-02 12:12:00 +0100473/* Descriptor for the memory allocation state. The limit is pre-initialised to
474 * 0 until it is replaced by "tune.lua.maxmem" during the config parsing, or it
475 * is replaced with ~0 during post_init after everything was loaded. This way
476 * it is guaranteed that if limit is ~0 the boot is complete and that if it's
477 * zero it's not yet limited and proper accounting is required.
Willy Tarreau32f61e22015-03-18 17:54:59 +0100478 */
479struct hlua_mem_allocator {
480 size_t allocated;
481 size_t limit;
482};
483
Willy Tarreaucdb53462020-12-02 12:12:00 +0100484static struct hlua_mem_allocator hlua_global_allocator THREAD_ALIGNED(64);
Willy Tarreau32f61e22015-03-18 17:54:59 +0100485
Aurelien DARRAGONc84899c2023-02-20 18:18:59 +0100486/* hlua event subscription */
487struct hlua_event_sub {
488 int fcn_ref;
489 int state_id;
490 struct hlua *hlua;
491 struct task *task;
492 event_hdl_async_equeue equeue;
493 struct event_hdl_sub *sub;
494 uint8_t paused;
495};
496
497/* This is the memory pool containing struct hlua_event_sub
498 * for event subscriptions from lua
499 */
500DECLARE_STATIC_POOL(pool_head_hlua_event_sub, "hlua_esub", sizeof(struct hlua_event_sub));
501
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100502/* These functions converts types between HAProxy internal args or
503 * sample and LUA types. Another function permits to check if the
504 * LUA stack contains arguments according with an required ARG_T
505 * format.
506 */
507static int hlua_arg2lua(lua_State *L, const struct arg *arg);
508static int hlua_lua2arg(lua_State *L, int ud, struct arg *arg);
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100509__LJMP static int hlua_lua2arg_check(lua_State *L, int first, struct arg *argp,
David Carlier0c437f42016-04-27 16:21:56 +0100510 uint64_t mask, struct proxy *p);
Willy Tarreau5eadada2015-03-10 17:28:54 +0100511static int hlua_smp2lua(lua_State *L, struct sample *smp);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100512static int hlua_smp2lua_str(lua_State *L, struct sample *smp);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100513static int hlua_lua2smp(lua_State *L, int ud, struct sample *smp);
514
Christopher Faulet9d1332b2020-02-24 16:46:16 +0100515__LJMP static int hlua_http_get_headers(lua_State *L, struct http_msg *msg);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200516
Thierry Fournier59f11be2020-11-29 00:37:41 +0100517struct prepend_path {
518 struct list l;
519 char *type;
520 char *path;
521};
522
523static struct list prepend_path_list = LIST_HEAD_INIT(prepend_path_list);
524
Thierry FOURNIER23bc3752015-09-11 19:15:43 +0200525#define SEND_ERR(__be, __fmt, __args...) \
526 do { \
527 send_log(__be, LOG_ERR, __fmt, ## __args); \
528 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE)) \
Christopher Faulet767a84b2017-11-24 16:50:31 +0100529 ha_alert(__fmt, ## __args); \
Thierry FOURNIER23bc3752015-09-11 19:15:43 +0200530 } while (0)
531
Thierry Fournier62a22aa2020-11-28 21:06:35 +0100532static inline struct hlua_function *new_hlua_function()
533{
534 struct hlua_function *fcn;
Thierry Fournierc7492592020-11-28 23:57:24 +0100535 int i;
Thierry Fournier62a22aa2020-11-28 21:06:35 +0100536
537 fcn = calloc(1, sizeof(*fcn));
538 if (!fcn)
539 return NULL;
Willy Tarreau2b718102021-04-21 07:32:39 +0200540 LIST_APPEND(&referenced_functions, &fcn->l);
Thierry Fournierc7492592020-11-28 23:57:24 +0100541 for (i = 0; i < MAX_THREADS + 1; i++)
542 fcn->function_ref[i] = -1;
Thierry Fournier62a22aa2020-11-28 21:06:35 +0100543 return fcn;
544}
545
Christopher Fauletdda44442021-04-12 14:05:43 +0200546static inline void release_hlua_function(struct hlua_function *fcn)
547{
548 if (!fcn)
549 return;
550 if (fcn->name)
551 ha_free(&fcn->name);
Willy Tarreau2b718102021-04-21 07:32:39 +0200552 LIST_DELETE(&fcn->l);
Christopher Fauletdda44442021-04-12 14:05:43 +0200553 ha_free(&fcn);
554}
555
Thierry Fournierc7492592020-11-28 23:57:24 +0100556/* If the common state is set, the stack id is 0, otherwise it is the tid + 1 */
557static inline int fcn_ref_to_stack_id(struct hlua_function *fcn)
558{
559 if (fcn->function_ref[0] == -1)
560 return tid + 1;
561 return 0;
562}
563
Christopher Faulet69c581a2021-05-31 08:54:04 +0200564/* Create a new registered filter. Only its name is filled */
565static inline struct hlua_reg_filter *new_hlua_reg_filter(const char *name)
566{
567 struct hlua_reg_filter *reg_flt;
568 int i;
569
570 reg_flt = calloc(1, sizeof(*reg_flt));
571 if (!reg_flt)
572 return NULL;
573 reg_flt->name = strdup(name);
574 if (!reg_flt->name) {
575 free(reg_flt);
576 return NULL;
577 }
578 LIST_APPEND(&referenced_filters, &reg_flt->l);
579 for (i = 0; i < MAX_THREADS + 1; i++) {
580 reg_flt->flt_ref[i] = -1;
581 reg_flt->fun_ref[i] = -1;
582 }
583 return reg_flt;
584}
585
586/* Release a registered filter */
587static inline void release_hlua_reg_filter(struct hlua_reg_filter *reg_flt)
588{
589 if (!reg_flt)
590 return;
591 if (reg_flt->name)
592 ha_free(&reg_flt->name);
593 LIST_DELETE(&reg_flt->l);
594 ha_free(&reg_flt);
595}
596
597/* If the common state is set, the stack id is 0, otherwise it is the tid + 1 */
598static inline int reg_flt_to_stack_id(struct hlua_reg_filter *reg_flt)
599{
600 if (reg_flt->fun_ref[0] == -1)
601 return tid + 1;
602 return 0;
603}
604
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100605/* Used to check an Lua function type in the stack. It creates and
606 * returns a reference of the function. This function throws an
Aurelien DARRAGONf8f8a2b2023-03-02 17:50:49 +0100607 * error if the argument is not a "function".
608 * When no longer used, the ref must be released with hlua_unref()
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100609 */
Aurelien DARRAGON9ee0d042023-03-20 18:36:08 +0100610__LJMP int hlua_checkfunction(lua_State *L, int argno)
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100611{
612 if (!lua_isfunction(L, argno)) {
Thierry FOURNIERfd1e9552018-02-23 18:41:18 +0100613 const char *msg = lua_pushfstring(L, "function expected, got %s", luaL_typename(L, argno));
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100614 WILL_LJMP(luaL_argerror(L, argno, msg));
615 }
616 lua_pushvalue(L, argno);
617 return luaL_ref(L, LUA_REGISTRYINDEX);
618}
619
Christopher Fauletba9e21d2020-02-25 10:20:04 +0100620/* Used to check an Lua table type in the stack. It creates and
621 * returns a reference of the table. This function throws an
Aurelien DARRAGONf8f8a2b2023-03-02 17:50:49 +0100622 * error if the argument is not a "table".
623 * When no longer used, the ref must be released with hlua_unref()
Christopher Fauletba9e21d2020-02-25 10:20:04 +0100624 */
Aurelien DARRAGON9ee0d042023-03-20 18:36:08 +0100625__LJMP int hlua_checktable(lua_State *L, int argno)
Christopher Fauletba9e21d2020-02-25 10:20:04 +0100626{
627 if (!lua_istable(L, argno)) {
628 const char *msg = lua_pushfstring(L, "table expected, got %s", luaL_typename(L, argno));
629 WILL_LJMP(luaL_argerror(L, argno, msg));
630 }
631 lua_pushvalue(L, argno);
632 return luaL_ref(L, LUA_REGISTRYINDEX);
633}
634
Aurelien DARRAGONf8f8a2b2023-03-02 17:50:49 +0100635/* Get a reference to the object that is at the top of the stack
636 * The referenced object will be popped from the stack
637 *
638 * The function returns the reference to the object which must
639 * be cleared using hlua_unref() when no longer used
640 */
641__LJMP int hlua_ref(lua_State *L)
642{
643 return MAY_LJMP(luaL_ref(L, LUA_REGISTRYINDEX));
644}
645
646/* Pushes a reference previously created using luaL_ref(L, LUA_REGISTRYINDEX)
647 * on <L> stack
648 * (ie: hlua_checkfunction(), hlua_checktable() or hlua_ref())
649 *
650 * When the reference is no longer used, it should be released by calling
651 * hlua_unref()
652 *
653 * <L> can be from any co-routine as long as it belongs to the same lua
654 * parent state that the one used to get the reference.
655 */
656void hlua_pushref(lua_State *L, int ref)
657{
658 lua_rawgeti(L, LUA_REGISTRYINDEX, ref);
659}
660
661/* Releases a reference previously created using luaL_ref(L, LUA_REGISTRYINDEX)
662 * (ie: hlua_checkfunction(), hlua_checktable() or hlua_ref())
663 *
664 * This will allow the reference to be reused and the referred object
665 * to be garbage collected.
666 *
667 * <L> can be from any co-routine as long as it belongs to the same lua
668 * parent state that the one used to get the reference.
669 */
670void hlua_unref(lua_State *L, int ref)
671{
672 luaL_unref(L, LUA_REGISTRYINDEX, ref);
673}
674
Christopher Fauletd09cc512021-03-24 14:48:45 +0100675__LJMP const char *hlua_traceback(lua_State *L, const char* sep)
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200676{
677 lua_Debug ar;
678 int level = 0;
Willy Tarreau83061a82018-07-13 11:56:34 +0200679 struct buffer *msg = get_trash_chunk();
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200680
681 while (lua_getstack(L, level++, &ar)) {
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200682 /* Fill fields:
683 * 'S': fills in the fields source, short_src, linedefined, lastlinedefined, and what;
684 * 'l': fills in the field currentline;
685 * 'n': fills in the field name and namewhat;
686 * 't': fills in the field istailcall;
687 */
688 lua_getinfo(L, "Slnt", &ar);
689
Willy Tarreau5c143402022-06-19 17:35:53 +0200690 /* skip these empty entries, usually they come from deep C functions */
691 if (ar.currentline < 0 && *ar.what == 'C' && !*ar.namewhat && !ar.name)
692 continue;
693
694 /* Add separator */
695 if (b_data(msg))
696 chunk_appendf(msg, "%s", sep);
697
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200698 /* Append code localisation */
699 if (ar.currentline > 0)
Christopher Fauletd09cc512021-03-24 14:48:45 +0100700 chunk_appendf(msg, "%s:%d: ", ar.short_src, ar.currentline);
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200701 else
Christopher Fauletd09cc512021-03-24 14:48:45 +0100702 chunk_appendf(msg, "%s: ", ar.short_src);
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200703
704 /*
705 * Get function name
706 *
707 * if namewhat is no empty, name is defined.
708 * what contains "Lua" for Lua function, "C" for C function,
709 * or "main" for main code.
710 */
711 if (*ar.namewhat != '\0' && ar.name != NULL) /* is there a name from code? */
Christopher Fauletd09cc512021-03-24 14:48:45 +0100712 chunk_appendf(msg, "in %s '%s'", ar.namewhat, ar.name); /* use it */
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200713
714 else if (*ar.what == 'm') /* "main", the code is not executed in a function */
Christopher Fauletd09cc512021-03-24 14:48:45 +0100715 chunk_appendf(msg, "in main chunk");
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200716
717 else if (*ar.what != 'C') /* for Lua functions, use <file:line> */
Christopher Fauletd09cc512021-03-24 14:48:45 +0100718 chunk_appendf(msg, "in function line %d", ar.linedefined);
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200719
720 else /* nothing left... */
721 chunk_appendf(msg, "?");
722
723
724 /* Display tailed call */
725 if (ar.istailcall)
726 chunk_appendf(msg, " ...");
727 }
728
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200729 return msg->area;
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200730}
731
732
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100733/* This function check the number of arguments available in the
734 * stack. If the number of arguments available is not the same
Ilya Shipitsinc02a23f2020-05-06 00:53:22 +0500735 * then <nb> an error is thrown.
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100736 */
737__LJMP static inline void check_args(lua_State *L, int nb, char *fcn)
738{
739 if (lua_gettop(L) == nb)
740 return;
741 WILL_LJMP(luaL_error(L, "'%s' needs %d arguments", fcn, nb));
742}
743
Mark Lakes22154b42018-01-29 14:38:40 -0800744/* This function pushes an error string prefixed by the file name
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100745 * and the line number where the error is encountered.
746 */
747static int hlua_pusherror(lua_State *L, const char *fmt, ...)
748{
749 va_list argp;
750 va_start(argp, fmt);
751 luaL_where(L, 1);
752 lua_pushvfstring(L, fmt, argp);
753 va_end(argp);
754 lua_concat(L, 2);
755 return 1;
756}
757
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100758/* This functions is used with sample fetch and converters. It
759 * converts the HAProxy configuration argument in a lua stack
760 * values.
761 *
762 * It takes an array of "arg", and each entry of the array is
763 * converted and pushed in the LUA stack.
764 */
765static int hlua_arg2lua(lua_State *L, const struct arg *arg)
766{
767 switch (arg->type) {
768 case ARGT_SINT:
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100769 case ARGT_TIME:
770 case ARGT_SIZE:
Thierry FOURNIERf90838b2015-03-06 13:48:32 +0100771 lua_pushinteger(L, arg->data.sint);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100772 break;
773
774 case ARGT_STR:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200775 lua_pushlstring(L, arg->data.str.area, arg->data.str.data);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100776 break;
777
778 case ARGT_IPV4:
779 case ARGT_IPV6:
780 case ARGT_MSK4:
781 case ARGT_MSK6:
782 case ARGT_FE:
783 case ARGT_BE:
784 case ARGT_TAB:
785 case ARGT_SRV:
786 case ARGT_USR:
787 case ARGT_MAP:
788 default:
789 lua_pushnil(L);
790 break;
791 }
792 return 1;
793}
794
Ilya Shipitsinc02a23f2020-05-06 00:53:22 +0500795/* This function take one entry in an LUA stack at the index "ud",
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100796 * and try to convert it in an HAProxy argument entry. This is useful
Ilya Shipitsind4259502020-04-08 01:07:56 +0500797 * with sample fetch wrappers. The input arguments are given to the
798 * lua wrapper and converted as arg list by the function.
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100799 */
800static int hlua_lua2arg(lua_State *L, int ud, struct arg *arg)
801{
802 switch (lua_type(L, ud)) {
803
804 case LUA_TNUMBER:
805 case LUA_TBOOLEAN:
806 arg->type = ARGT_SINT;
807 arg->data.sint = lua_tointeger(L, ud);
808 break;
809
810 case LUA_TSTRING:
811 arg->type = ARGT_STR;
Tim Duesterhus2e89dec2019-09-29 23:03:08 +0200812 arg->data.str.area = (char *)lua_tolstring(L, ud, &arg->data.str.data);
Tim Duesterhus29d2e8a2019-09-29 23:03:07 +0200813 /* We don't know the actual size of the underlying allocation, so be conservative. */
Christopher Fauletfdea1b62020-08-06 08:29:18 +0200814 arg->data.str.size = arg->data.str.data+1; /* count the terminating null byte */
Tim Duesterhus29d2e8a2019-09-29 23:03:07 +0200815 arg->data.str.head = 0;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100816 break;
817
818 case LUA_TUSERDATA:
819 case LUA_TNIL:
820 case LUA_TTABLE:
821 case LUA_TFUNCTION:
822 case LUA_TTHREAD:
823 case LUA_TLIGHTUSERDATA:
824 arg->type = ARGT_SINT;
Thierry FOURNIERbf65cd42015-07-20 17:45:02 +0200825 arg->data.sint = 0;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100826 break;
827 }
828 return 1;
829}
830
831/* the following functions are used to convert a struct sample
832 * in Lua type. This useful to convert the return of the
Ilya Shipitsind4259502020-04-08 01:07:56 +0500833 * fetches or converters.
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100834 */
Willy Tarreau5eadada2015-03-10 17:28:54 +0100835static int hlua_smp2lua(lua_State *L, struct sample *smp)
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100836{
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200837 switch (smp->data.type) {
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100838 case SMP_T_SINT:
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100839 case SMP_T_BOOL:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200840 lua_pushinteger(L, smp->data.u.sint);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100841 break;
842
843 case SMP_T_BIN:
844 case SMP_T_STR:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200845 lua_pushlstring(L, smp->data.u.str.area, smp->data.u.str.data);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100846 break;
847
848 case SMP_T_METH:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200849 switch (smp->data.u.meth.meth) {
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100850 case HTTP_METH_OPTIONS: lua_pushstring(L, "OPTIONS"); break;
851 case HTTP_METH_GET: lua_pushstring(L, "GET"); break;
852 case HTTP_METH_HEAD: lua_pushstring(L, "HEAD"); break;
853 case HTTP_METH_POST: lua_pushstring(L, "POST"); break;
854 case HTTP_METH_PUT: lua_pushstring(L, "PUT"); break;
855 case HTTP_METH_DELETE: lua_pushstring(L, "DELETE"); break;
856 case HTTP_METH_TRACE: lua_pushstring(L, "TRACE"); break;
857 case HTTP_METH_CONNECT: lua_pushstring(L, "CONNECT"); break;
858 case HTTP_METH_OTHER:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200859 lua_pushlstring(L, smp->data.u.meth.str.area, smp->data.u.meth.str.data);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100860 break;
861 default:
862 lua_pushnil(L);
863 break;
864 }
865 break;
866
867 case SMP_T_IPV4:
868 case SMP_T_IPV6:
869 case SMP_T_ADDR: /* This type is never used to qualify a sample. */
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200870 if (sample_casts[smp->data.type][SMP_T_STR] &&
871 sample_casts[smp->data.type][SMP_T_STR](smp))
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200872 lua_pushlstring(L, smp->data.u.str.area, smp->data.u.str.data);
Willy Tarreau5eadada2015-03-10 17:28:54 +0100873 else
874 lua_pushnil(L);
875 break;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100876 default:
877 lua_pushnil(L);
878 break;
879 }
880 return 1;
881}
882
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100883/* the following functions are used to convert a struct sample
884 * in Lua strings. This is useful to convert the return of the
Ilya Shipitsind4259502020-04-08 01:07:56 +0500885 * fetches or converters.
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100886 */
887static int hlua_smp2lua_str(lua_State *L, struct sample *smp)
888{
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200889 switch (smp->data.type) {
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100890
891 case SMP_T_BIN:
892 case SMP_T_STR:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200893 lua_pushlstring(L, smp->data.u.str.area, smp->data.u.str.data);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100894 break;
895
896 case SMP_T_METH:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200897 switch (smp->data.u.meth.meth) {
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100898 case HTTP_METH_OPTIONS: lua_pushstring(L, "OPTIONS"); break;
899 case HTTP_METH_GET: lua_pushstring(L, "GET"); break;
900 case HTTP_METH_HEAD: lua_pushstring(L, "HEAD"); break;
901 case HTTP_METH_POST: lua_pushstring(L, "POST"); break;
902 case HTTP_METH_PUT: lua_pushstring(L, "PUT"); break;
903 case HTTP_METH_DELETE: lua_pushstring(L, "DELETE"); break;
904 case HTTP_METH_TRACE: lua_pushstring(L, "TRACE"); break;
905 case HTTP_METH_CONNECT: lua_pushstring(L, "CONNECT"); break;
906 case HTTP_METH_OTHER:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200907 lua_pushlstring(L, smp->data.u.meth.str.area, smp->data.u.meth.str.data);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100908 break;
909 default:
910 lua_pushstring(L, "");
911 break;
912 }
913 break;
914
915 case SMP_T_SINT:
916 case SMP_T_BOOL:
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100917 case SMP_T_IPV4:
918 case SMP_T_IPV6:
919 case SMP_T_ADDR: /* This type is never used to qualify a sample. */
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200920 if (sample_casts[smp->data.type][SMP_T_STR] &&
921 sample_casts[smp->data.type][SMP_T_STR](smp))
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200922 lua_pushlstring(L, smp->data.u.str.area, smp->data.u.str.data);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100923 else
924 lua_pushstring(L, "");
925 break;
926 default:
927 lua_pushstring(L, "");
928 break;
929 }
930 return 1;
931}
932
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100933/* the following functions are used to convert an Lua type in a
934 * struct sample. This is useful to provide data from a converter
935 * to the LUA code.
936 */
937static int hlua_lua2smp(lua_State *L, int ud, struct sample *smp)
938{
939 switch (lua_type(L, ud)) {
940
941 case LUA_TNUMBER:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200942 smp->data.type = SMP_T_SINT;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200943 smp->data.u.sint = lua_tointeger(L, ud);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100944 break;
945
946
947 case LUA_TBOOLEAN:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200948 smp->data.type = SMP_T_BOOL;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200949 smp->data.u.sint = lua_toboolean(L, ud);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100950 break;
951
952 case LUA_TSTRING:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200953 smp->data.type = SMP_T_STR;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100954 smp->flags |= SMP_F_CONST;
Tim Duesterhus2e89dec2019-09-29 23:03:08 +0200955 smp->data.u.str.area = (char *)lua_tolstring(L, ud, &smp->data.u.str.data);
Tim Duesterhus29d2e8a2019-09-29 23:03:07 +0200956 /* We don't know the actual size of the underlying allocation, so be conservative. */
Christopher Fauletfdea1b62020-08-06 08:29:18 +0200957 smp->data.u.str.size = smp->data.u.str.data+1; /* count the terminating null byte */
Tim Duesterhus29d2e8a2019-09-29 23:03:07 +0200958 smp->data.u.str.head = 0;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100959 break;
960
961 case LUA_TUSERDATA:
962 case LUA_TNIL:
963 case LUA_TTABLE:
964 case LUA_TFUNCTION:
965 case LUA_TTHREAD:
966 case LUA_TLIGHTUSERDATA:
Thierry FOURNIER93405e12015-08-26 14:19:03 +0200967 case LUA_TNONE:
968 default:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200969 smp->data.type = SMP_T_BOOL;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200970 smp->data.u.sint = 0;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100971 break;
972 }
973 return 1;
974}
975
Ilya Shipitsind4259502020-04-08 01:07:56 +0500976/* This function check the "argp" built by another conversion function
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -0800977 * is in accord with the expected argp defined by the "mask". The function
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100978 * returns true or false. It can be adjust the types if there compatibles.
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100979 *
Ilya Shipitsinc02a23f2020-05-06 00:53:22 +0500980 * This function assumes that the argp argument contains ARGM_NBARGS + 1
Willy Tarreauee0d7272021-07-16 10:26:56 +0200981 * entries and that there is at least one stop at the last position.
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100982 */
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100983__LJMP int hlua_lua2arg_check(lua_State *L, int first, struct arg *argp,
David Carlier0c437f42016-04-27 16:21:56 +0100984 uint64_t mask, struct proxy *p)
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100985{
986 int min_arg;
Willy Tarreauee0d7272021-07-16 10:26:56 +0200987 int idx;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100988 struct proxy *px;
Christopher Fauletd25d9262020-08-06 11:04:46 +0200989 struct userlist *ul;
Christopher Fauletfd2e9062020-08-06 11:10:57 +0200990 struct my_regex *reg;
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200991 const char *msg = NULL;
Christopher Fauletfd2e9062020-08-06 11:10:57 +0200992 char *sname, *pname, *err = NULL;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100993
994 idx = 0;
995 min_arg = ARGM(mask);
996 mask >>= ARGM_BITS;
997
998 while (1) {
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200999 struct buffer tmp = BUF_NULL;
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001000
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001001 /* Check for mandatory arguments. */
1002 if (argp[idx].type == ARGT_STOP) {
Thierry FOURNIER3caa0392015-03-13 13:38:17 +01001003 if (idx < min_arg) {
1004
1005 /* If miss other argument than the first one, we return an error. */
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001006 if (idx > 0) {
1007 msg = "Mandatory argument expected";
1008 goto error;
1009 }
Thierry FOURNIER3caa0392015-03-13 13:38:17 +01001010
1011 /* If first argument have a certain type, some default values
1012 * may be used. See the function smp_resolve_args().
1013 */
1014 switch (mask & ARGT_MASK) {
1015
1016 case ARGT_FE:
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001017 if (!(p->cap & PR_CAP_FE)) {
1018 msg = "Mandatory argument expected";
1019 goto error;
1020 }
Thierry FOURNIER3caa0392015-03-13 13:38:17 +01001021 argp[idx].data.prx = p;
1022 argp[idx].type = ARGT_FE;
1023 argp[idx+1].type = ARGT_STOP;
1024 break;
1025
1026 case ARGT_BE:
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001027 if (!(p->cap & PR_CAP_BE)) {
1028 msg = "Mandatory argument expected";
1029 goto error;
1030 }
Thierry FOURNIER3caa0392015-03-13 13:38:17 +01001031 argp[idx].data.prx = p;
1032 argp[idx].type = ARGT_BE;
1033 argp[idx+1].type = ARGT_STOP;
1034 break;
1035
1036 case ARGT_TAB:
Olivier Houchard14f62682022-09-13 00:35:53 +02001037 if (!p->table) {
1038 msg = "Mandatory argument expected";
1039 goto error;
1040 }
1041 argp[idx].data.t = p->table;
Thierry FOURNIER3caa0392015-03-13 13:38:17 +01001042 argp[idx].type = ARGT_TAB;
1043 argp[idx+1].type = ARGT_STOP;
1044 break;
1045
1046 default:
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001047 msg = "Mandatory argument expected";
1048 goto error;
Thierry FOURNIER3caa0392015-03-13 13:38:17 +01001049 break;
1050 }
1051 }
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001052 break;
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001053 }
1054
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001055 /* Check for exceed the number of required argument. */
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001056 if ((mask & ARGT_MASK) == ARGT_STOP &&
1057 argp[idx].type != ARGT_STOP) {
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001058 msg = "Last argument expected";
1059 goto error;
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001060 }
1061
1062 if ((mask & ARGT_MASK) == ARGT_STOP &&
1063 argp[idx].type == ARGT_STOP) {
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001064 break;
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001065 }
1066
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001067 /* Convert some argument types. All string in argp[] are for not
1068 * duplicated yet.
1069 */
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001070 switch (mask & ARGT_MASK) {
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001071 case ARGT_SINT:
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001072 if (argp[idx].type != ARGT_SINT) {
1073 msg = "integer expected";
1074 goto error;
1075 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001076 argp[idx].type = ARGT_SINT;
1077 break;
1078
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001079 case ARGT_TIME:
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001080 if (argp[idx].type != ARGT_SINT) {
1081 msg = "integer expected";
1082 goto error;
1083 }
Thierry FOURNIER29176f32015-07-07 00:41:29 +02001084 argp[idx].type = ARGT_TIME;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001085 break;
1086
1087 case ARGT_SIZE:
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001088 if (argp[idx].type != ARGT_SINT) {
1089 msg = "integer expected";
1090 goto error;
1091 }
Thierry FOURNIER29176f32015-07-07 00:41:29 +02001092 argp[idx].type = ARGT_SIZE;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001093 break;
1094
1095 case ARGT_FE:
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001096 if (argp[idx].type != ARGT_STR) {
1097 msg = "string expected";
1098 goto error;
1099 }
Christopher Fauletfdea1b62020-08-06 08:29:18 +02001100 argp[idx].data.prx = proxy_fe_by_name(argp[idx].data.str.area);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001101 if (!argp[idx].data.prx) {
1102 msg = "frontend doesn't exist";
1103 goto error;
1104 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001105 argp[idx].type = ARGT_FE;
1106 break;
1107
1108 case ARGT_BE:
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001109 if (argp[idx].type != ARGT_STR) {
1110 msg = "string expected";
1111 goto error;
1112 }
Christopher Fauletfdea1b62020-08-06 08:29:18 +02001113 argp[idx].data.prx = proxy_be_by_name(argp[idx].data.str.area);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001114 if (!argp[idx].data.prx) {
1115 msg = "backend doesn't exist";
1116 goto error;
1117 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001118 argp[idx].type = ARGT_BE;
1119 break;
1120
1121 case ARGT_TAB:
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001122 if (argp[idx].type != ARGT_STR) {
1123 msg = "string expected";
1124 goto error;
1125 }
Christopher Fauletfdea1b62020-08-06 08:29:18 +02001126 argp[idx].data.t = stktable_find_by_name(argp[idx].data.str.area);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001127 if (!argp[idx].data.t) {
1128 msg = "table doesn't exist";
1129 goto error;
1130 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001131 argp[idx].type = ARGT_TAB;
1132 break;
1133
1134 case ARGT_SRV:
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001135 if (argp[idx].type != ARGT_STR) {
1136 msg = "string expected";
1137 goto error;
1138 }
Christopher Fauletfdea1b62020-08-06 08:29:18 +02001139 sname = strrchr(argp[idx].data.str.area, '/');
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001140 if (sname) {
1141 *sname++ = '\0';
Christopher Fauletfdea1b62020-08-06 08:29:18 +02001142 pname = argp[idx].data.str.area;
Willy Tarreau9e0bb102015-05-26 11:24:42 +02001143 px = proxy_be_by_name(pname);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001144 if (!px) {
1145 msg = "backend doesn't exist";
1146 goto error;
1147 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001148 }
1149 else {
Christopher Fauletfdea1b62020-08-06 08:29:18 +02001150 sname = argp[idx].data.str.area;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001151 px = p;
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001152 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001153 argp[idx].data.srv = findserver(px, sname);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001154 if (!argp[idx].data.srv) {
1155 msg = "server doesn't exist";
1156 goto error;
1157 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001158 argp[idx].type = ARGT_SRV;
1159 break;
1160
1161 case ARGT_IPV4:
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001162 if (argp[idx].type != ARGT_STR) {
1163 msg = "string expected";
1164 goto error;
1165 }
1166 if (inet_pton(AF_INET, argp[idx].data.str.area, &argp[idx].data.ipv4)) {
1167 msg = "invalid IPv4 address";
1168 goto error;
1169 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001170 argp[idx].type = ARGT_IPV4;
1171 break;
1172
1173 case ARGT_MSK4:
Christopher Faulete663a6e2020-08-07 09:11:22 +02001174 if (argp[idx].type == ARGT_SINT)
1175 len2mask4(argp[idx].data.sint, &argp[idx].data.ipv4);
1176 else if (argp[idx].type == ARGT_STR) {
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001177 if (!str2mask(argp[idx].data.str.area, &argp[idx].data.ipv4)) {
1178 msg = "invalid IPv4 mask";
1179 goto error;
1180 }
1181 }
1182 else {
1183 msg = "integer or string expected";
1184 goto error;
Christopher Faulete663a6e2020-08-07 09:11:22 +02001185 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001186 argp[idx].type = ARGT_MSK4;
1187 break;
1188
1189 case ARGT_IPV6:
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001190 if (argp[idx].type != ARGT_STR) {
1191 msg = "string expected";
1192 goto error;
1193 }
1194 if (inet_pton(AF_INET6, argp[idx].data.str.area, &argp[idx].data.ipv6)) {
1195 msg = "invalid IPv6 address";
1196 goto error;
1197 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001198 argp[idx].type = ARGT_IPV6;
1199 break;
1200
1201 case ARGT_MSK6:
Christopher Faulete663a6e2020-08-07 09:11:22 +02001202 if (argp[idx].type == ARGT_SINT)
1203 len2mask6(argp[idx].data.sint, &argp[idx].data.ipv6);
1204 else if (argp[idx].type == ARGT_STR) {
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001205 if (!str2mask6(argp[idx].data.str.area, &argp[idx].data.ipv6)) {
1206 msg = "invalid IPv6 mask";
1207 goto error;
1208 }
1209 }
1210 else {
1211 msg = "integer or string expected";
1212 goto error;
Christopher Faulete663a6e2020-08-07 09:11:22 +02001213 }
Tim Duesterhusb814da62018-01-25 16:24:50 +01001214 argp[idx].type = ARGT_MSK6;
1215 break;
1216
Christopher Fauletfd2e9062020-08-06 11:10:57 +02001217 case ARGT_REG:
1218 if (argp[idx].type != ARGT_STR) {
1219 msg = "string expected";
1220 goto error;
1221 }
1222 reg = regex_comp(argp[idx].data.str.area, !(argp[idx].type_flags & ARGF_REG_ICASE), 1, &err);
1223 if (!reg) {
1224 msg = lua_pushfstring(L, "error compiling regex '%s' : '%s'",
1225 argp[idx].data.str.area, err);
1226 free(err);
1227 goto error;
1228 }
1229 argp[idx].type = ARGT_REG;
1230 argp[idx].data.reg = reg;
1231 break;
1232
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001233 case ARGT_USR:
Christopher Fauletd25d9262020-08-06 11:04:46 +02001234 if (argp[idx].type != ARGT_STR) {
1235 msg = "string expected";
1236 goto error;
1237 }
1238 if (p->uri_auth && p->uri_auth->userlist &&
Tim Duesterhuse5ff1412021-01-02 22:31:53 +01001239 strcmp(p->uri_auth->userlist->name, argp[idx].data.str.area) == 0)
Christopher Fauletd25d9262020-08-06 11:04:46 +02001240 ul = p->uri_auth->userlist;
1241 else
1242 ul = auth_find_userlist(argp[idx].data.str.area);
1243
1244 if (!ul) {
1245 msg = lua_pushfstring(L, "unable to find userlist '%s'", argp[idx].data.str.area);
1246 goto error;
1247 }
1248 argp[idx].type = ARGT_USR;
1249 argp[idx].data.usr = ul;
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001250 break;
1251
1252 case ARGT_STR:
1253 if (!chunk_dup(&tmp, &argp[idx].data.str)) {
1254 msg = "unable to duplicate string arg";
1255 goto error;
1256 }
1257 argp[idx].data.str = tmp;
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001258 break;
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001259
Christopher Fauletd25d9262020-08-06 11:04:46 +02001260 case ARGT_MAP:
Christopher Fauletd25d9262020-08-06 11:04:46 +02001261 msg = "type not yet supported";
1262 goto error;
1263 break;
1264
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001265 }
1266
1267 /* Check for type of argument. */
1268 if ((mask & ARGT_MASK) != argp[idx].type) {
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001269 msg = lua_pushfstring(L, "'%s' expected, got '%s'",
1270 arg_type_names[(mask & ARGT_MASK)],
1271 arg_type_names[argp[idx].type & ARGT_MASK]);
1272 goto error;
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001273 }
1274
1275 /* Next argument. */
1276 mask >>= ARGT_BITS;
1277 idx++;
1278 }
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001279 return 0;
1280
1281 error:
Olivier Houchardca431612022-09-13 00:31:17 +02001282 argp[idx].type = ARGT_STOP;
Willy Tarreauee0d7272021-07-16 10:26:56 +02001283 free_args(argp);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001284 WILL_LJMP(luaL_argerror(L, first + idx, msg));
1285 return 0; /* Never reached */
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001286}
1287
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001288/*
Ilya Shipitsinc02a23f2020-05-06 00:53:22 +05001289 * The following functions are used to make correspondence between the the
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001290 * executed lua pointer and the "struct hlua *" that contain the context.
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001291 *
1292 * - hlua_gethlua : return the hlua context associated with an lua_State.
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001293 * - hlua_sethlua : create the association between hlua context and lua_state.
1294 */
1295static inline struct hlua *hlua_gethlua(lua_State *L)
1296{
Thierry FOURNIER38c5fd62015-03-10 02:40:29 +01001297 struct hlua **hlua = lua_getextraspace(L);
1298 return *hlua;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001299}
1300static inline void hlua_sethlua(struct hlua *hlua)
1301{
Thierry FOURNIER38c5fd62015-03-10 02:40:29 +01001302 struct hlua **hlua_store = lua_getextraspace(hlua->T);
1303 *hlua_store = hlua;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001304}
1305
Willy Tarreau0b7b6392022-06-19 17:39:33 +02001306/* Will return a non-NULL string indicating the Lua call trace if the caller
1307 * currently is executing from within a Lua function. One line per entry will
1308 * be emitted, and each extra line will be prefixed with <pfx>. If a current
1309 * Lua function is not detected, NULL is returned.
1310 */
1311const char *hlua_show_current_location(const char *pfx)
1312{
1313 lua_State *L;
1314 lua_Debug ar;
1315
1316 /* global or per-thread stack initializing ? */
1317 if (hlua_state_id != -1 && (L = hlua_states[hlua_state_id]) && lua_getstack(L, 0, &ar))
1318 return hlua_traceback(L, pfx);
1319
1320 /* per-thread stack running ? */
1321 if (hlua_states[tid + 1] && (L = hlua_states[tid + 1]) && lua_getstack(L, 0, &ar))
1322 return hlua_traceback(L, pfx);
1323
1324 /* global stack running ? */
1325 if (hlua_states[0] && (L = hlua_states[0]) && lua_getstack(L, 0, &ar))
1326 return hlua_traceback(L, pfx);
1327
1328 return NULL;
1329}
1330
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01001331/* This function is used to send logs. It try to send on screen (stderr)
1332 * and on the default syslog server.
1333 */
1334static inline void hlua_sendlog(struct proxy *px, int level, const char *msg)
1335{
1336 struct tm tm;
1337 char *p;
1338
1339 /* Cleanup the log message. */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001340 p = trash.area;
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01001341 for (; *msg != '\0'; msg++, p++) {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001342 if (p >= trash.area + trash.size - 1) {
Thierry FOURNIERccf00632015-09-16 12:47:03 +02001343 /* Break the message if exceed the buffer size. */
1344 *(p-4) = ' ';
1345 *(p-3) = '.';
1346 *(p-2) = '.';
1347 *(p-1) = '.';
1348 break;
1349 }
Willy Tarreau90807112020-02-25 08:16:33 +01001350 if (isprint((unsigned char)*msg))
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01001351 *p = *msg;
1352 else
1353 *p = '.';
1354 }
1355 *p = '\0';
1356
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001357 send_log(px, level, "%s\n", trash.area);
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01001358 if (!(global.mode & MODE_QUIET) || (global.mode & (MODE_VERBOSE | MODE_STARTING))) {
Christopher Fauletf98d8212020-10-02 18:13:52 +02001359 if (level == LOG_DEBUG && !(global.mode & MODE_DEBUG))
1360 return;
1361
Willy Tarreaua678b432015-08-28 10:14:59 +02001362 get_localtime(date.tv_sec, &tm);
1363 fprintf(stderr, "[%s] %03d/%02d%02d%02d (%d) : %s\n",
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01001364 log_levels[level], tm.tm_yday, tm.tm_hour, tm.tm_min, tm.tm_sec,
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001365 (int)getpid(), trash.area);
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01001366 fflush(stderr);
1367 }
1368}
1369
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001370/* This function just ensure that the yield will be always
1371 * returned with a timeout and permit to set some flags
1372 */
1373__LJMP void hlua_yieldk(lua_State *L, int nresults, int ctx,
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001374 lua_KFunction k, int timeout, unsigned int flags)
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001375{
Thierry Fournier4234dbd2020-11-28 13:18:23 +01001376 struct hlua *hlua;
1377
1378 /* Get hlua struct, or NULL if we execute from main lua state */
1379 hlua = hlua_gethlua(L);
1380 if (!hlua) {
1381 return;
1382 }
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001383
1384 /* Set the wake timeout. If timeout is required, we set
1385 * the expiration time.
1386 */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001387 hlua->wake_time = timeout;
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001388
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01001389 hlua->flags |= flags;
1390
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001391 /* Process the yield. */
Willy Tarreau9635e032018-10-16 17:52:55 +02001392 MAY_LJMP(lua_yieldk(L, nresults, ctx, k));
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001393}
1394
Willy Tarreau87b09662015-04-03 00:22:06 +02001395/* This function initialises the Lua environment stored in the stream.
1396 * It must be called at the start of the stream. This function creates
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001397 * an LUA coroutine. It can not be use to crete the main LUA context.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02001398 *
1399 * This function is particular. it initialises a new Lua thread. If the
1400 * initialisation fails (example: out of memory error), the lua function
1401 * throws an error (longjmp).
1402 *
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001403 * This function manipulates two Lua stacks: the main and the thread. Only
Thierry FOURNIERbabae282015-09-17 11:36:37 +02001404 * the main stack can fail. The thread is not manipulated. This function
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001405 * MUST NOT manipulate the created thread stack state, because it is not
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001406 * protected against errors thrown by the thread stack.
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001407 */
Aurelien DARRAGON6b0b9bd2023-03-21 14:02:16 +01001408int hlua_ctx_init(struct hlua *lua, int state_id, struct task *task)
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001409{
1410 lua->Mref = LUA_REFNIL;
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001411 lua->flags = 0;
Willy Tarreauf31af932020-01-14 09:59:38 +01001412 lua->gc_count = 0;
Christopher Fauletbc275a92020-02-26 14:55:16 +01001413 lua->wake_time = TICK_ETERNITY;
Thierry Fournier021d9862020-11-28 23:42:03 +01001414 lua->state_id = state_id;
Aurelien DARRAGONda9503c2022-11-25 09:10:07 +01001415 hlua_timer_init(&lua->timer, 0); /* default value, no timeout */
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01001416 LIST_INIT(&lua->com);
Aurelien DARRAGON3ffbf382023-02-09 17:02:57 +01001417 MT_LIST_INIT(&lua->hc_list);
Aurelien DARRAGON6b0b9bd2023-03-21 14:02:16 +01001418 if (!SET_SAFE_LJMP_PARENT(lua)) {
1419 lua->Tref = LUA_REFNIL;
1420 return 0;
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001421 }
Thierry Fournier021d9862020-11-28 23:42:03 +01001422 lua->T = lua_newthread(hlua_states[state_id]);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001423 if (!lua->T) {
1424 lua->Tref = LUA_REFNIL;
Aurelien DARRAGON6b0b9bd2023-03-21 14:02:16 +01001425 RESET_SAFE_LJMP_PARENT(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001426 return 0;
1427 }
1428 hlua_sethlua(lua);
Thierry Fournier021d9862020-11-28 23:42:03 +01001429 lua->Tref = luaL_ref(hlua_states[state_id], LUA_REGISTRYINDEX);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001430 lua->task = task;
Aurelien DARRAGON6b0b9bd2023-03-21 14:02:16 +01001431 RESET_SAFE_LJMP_PARENT(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001432 return 1;
1433}
1434
Aurelien DARRAGON3ffbf382023-02-09 17:02:57 +01001435/* kill all associated httpclient to this hlua task
1436 * We must take extra precautions as we're manipulating lua-exposed
1437 * objects without the main lua lock.
1438 */
William Lallemandbb581422022-10-20 10:57:28 +02001439static void hlua_httpclient_destroy_all(struct hlua *hlua)
1440{
Aurelien DARRAGON3ffbf382023-02-09 17:02:57 +01001441 struct hlua_httpclient *hlua_hc;
William Lallemandbb581422022-10-20 10:57:28 +02001442
Aurelien DARRAGON3ffbf382023-02-09 17:02:57 +01001443 /* use thread-safe accessors for hc_list since GC cycle initiated by
1444 * another thread sharing the same main lua stack (lua coroutine)
1445 * could execute hlua_httpclient_gc() on the hlua->hc_list items
1446 * in parallel: Lua GC applies on the main stack, it is not limited to
1447 * a single coroutine stack, see Github issue #2037 for reference.
1448 * Remember, coroutines created using lua_newthread() are not meant to
1449 * be thread safe in Lua. (From lua co-author:
1450 * http://lua-users.org/lists/lua-l/2011-07/msg00072.html)
1451 *
1452 * This security measure is superfluous when 'lua-load-per-thread' is used
1453 * since in this case coroutines exclusively run on the same thread
1454 * (main stack is not shared between OS threads).
1455 */
1456 while ((hlua_hc = MT_LIST_POP(&hlua->hc_list, typeof(hlua_hc), by_hlua))) {
1457 httpclient_stop_and_destroy(hlua_hc->hc);
William Lallemandbb581422022-10-20 10:57:28 +02001458 hlua_hc->hc = NULL;
William Lallemandbb581422022-10-20 10:57:28 +02001459 }
1460}
1461
1462
Willy Tarreau87b09662015-04-03 00:22:06 +02001463/* Used to destroy the Lua coroutine when the attached stream or task
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001464 * is destroyed. The destroy also the memory context. The struct "lua"
Aurelien DARRAGON60ab0f72023-03-01 16:45:50 +01001465 * will be freed.
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001466 */
1467void hlua_ctx_destroy(struct hlua *lua)
1468{
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01001469 if (!lua)
Thierry FOURNIERa718b292015-03-04 16:48:34 +01001470 return;
1471
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01001472 if (!lua->T)
1473 goto end;
1474
William Lallemandbb581422022-10-20 10:57:28 +02001475 /* clean all running httpclient */
1476 hlua_httpclient_destroy_all(lua);
1477
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01001478 /* Purge all the pending signals. */
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001479 notification_purge(&lua->com);
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01001480
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001481 if (!SET_SAFE_LJMP(lua))
Thierry FOURNIER75d02082017-07-12 13:41:33 +02001482 return;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001483 luaL_unref(lua->T, LUA_REGISTRYINDEX, lua->Mref);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001484 RESET_SAFE_LJMP(lua);
Thierry FOURNIER5a50a852015-09-23 16:59:28 +02001485
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001486 if (!SET_SAFE_LJMP_PARENT(lua))
Thierry FOURNIER75d02082017-07-12 13:41:33 +02001487 return;
Thierry Fournier021d9862020-11-28 23:42:03 +01001488 luaL_unref(hlua_states[lua->state_id], LUA_REGISTRYINDEX, lua->Tref);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001489 RESET_SAFE_LJMP_PARENT(lua);
Thierry FOURNIER5a50a852015-09-23 16:59:28 +02001490 /* Forces a garbage collecting process. If the Lua program is finished
1491 * without error, we run the GC on the thread pointer. Its freed all
1492 * the unused memory.
1493 * If the thread is finnish with an error or is currently yielded,
1494 * it seems that the GC applied on the thread doesn't clean anything,
1495 * so e run the GC on the main thread.
1496 * NOTE: maybe this action locks all the Lua threads untiml the en of
1497 * the garbage collection.
1498 */
Willy Tarreauf31af932020-01-14 09:59:38 +01001499 if (lua->gc_count) {
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001500 if (!SET_SAFE_LJMP_PARENT(lua))
Thierry FOURNIER75d02082017-07-12 13:41:33 +02001501 return;
Thierry Fournier021d9862020-11-28 23:42:03 +01001502 lua_gc(hlua_states[lua->state_id], LUA_GCCOLLECT, 0);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001503 RESET_SAFE_LJMP_PARENT(lua);
Thierry FOURNIER7c39ab42015-09-27 22:53:33 +02001504 }
Thierry FOURNIER5a50a852015-09-23 16:59:28 +02001505
Thierry FOURNIERa7b536b2015-09-21 22:50:24 +02001506 lua->T = NULL;
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01001507
1508end:
Willy Tarreaubafbe012017-11-24 17:34:44 +01001509 pool_free(pool_head_hlua, lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001510}
1511
1512/* This function is used to restore the Lua context when a coroutine
1513 * fails. This function copy the common memory between old coroutine
1514 * and the new coroutine. The old coroutine is destroyed, and its
1515 * replaced by the new coroutine.
1516 * If the flag "keep_msg" is set, the last entry of the old is assumed
1517 * as string error message and it is copied in the new stack.
1518 */
1519static int hlua_ctx_renew(struct hlua *lua, int keep_msg)
1520{
1521 lua_State *T;
1522 int new_ref;
1523
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001524 /* New Lua coroutine. */
Thierry Fournier021d9862020-11-28 23:42:03 +01001525 T = lua_newthread(hlua_states[lua->state_id]);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001526 if (!T)
1527 return 0;
1528
1529 /* Copy last error message. */
1530 if (keep_msg)
1531 lua_xmove(lua->T, T, 1);
1532
1533 /* Copy data between the coroutines. */
1534 lua_rawgeti(lua->T, LUA_REGISTRYINDEX, lua->Mref);
1535 lua_xmove(lua->T, T, 1);
Ilya Shipitsin46a030c2020-07-05 16:36:08 +05001536 new_ref = luaL_ref(T, LUA_REGISTRYINDEX); /* Value popped. */
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001537
1538 /* Destroy old data. */
1539 luaL_unref(lua->T, LUA_REGISTRYINDEX, lua->Mref);
1540
1541 /* The thread is garbage collected by Lua. */
Thierry Fournier021d9862020-11-28 23:42:03 +01001542 luaL_unref(hlua_states[lua->state_id], LUA_REGISTRYINDEX, lua->Tref);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001543
1544 /* Fill the struct with the new coroutine values. */
1545 lua->Mref = new_ref;
1546 lua->T = T;
Thierry Fournier021d9862020-11-28 23:42:03 +01001547 lua->Tref = luaL_ref(hlua_states[lua->state_id], LUA_REGISTRYINDEX);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001548
1549 /* Set context. */
1550 hlua_sethlua(lua);
1551
1552 return 1;
1553}
1554
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001555void hlua_hook(lua_State *L, lua_Debug *ar)
1556{
Thierry Fournier4234dbd2020-11-28 13:18:23 +01001557 struct hlua *hlua;
1558
1559 /* Get hlua struct, or NULL if we execute from main lua state */
1560 hlua = hlua_gethlua(L);
1561 if (!hlua)
1562 return;
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001563
1564 /* Lua cannot yield when its returning from a function,
1565 * so, we can fix the interrupt hook to 1 instruction,
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001566 * expecting that the function is finished.
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001567 */
1568 if (lua_gethookmask(L) & LUA_MASKRET) {
1569 lua_sethook(hlua->T, hlua_hook, LUA_MASKCOUNT, 1);
1570 return;
1571 }
1572
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001573 /* If we interrupt the Lua processing in yieldable state, we yield.
1574 * If the state is not yieldable, trying yield causes an error.
1575 */
Aurelien DARRAGON0ebd41f2022-11-24 09:51:40 +01001576 if (lua_isyieldable(L)) {
1577 /* note: for converters/fetches.. where yielding is not allowed
1578 * hlua_ctx_resume() will simply perform a goto resume_execution
1579 * instead of rescheduling hlua->task.
1580 * also: hlua_ctx_resume() will take care of checking execution
1581 * timeout and re-applying the hook as needed.
1582 */
Willy Tarreau9635e032018-10-16 17:52:55 +02001583 MAY_LJMP(hlua_yieldk(L, 0, 0, NULL, TICK_ETERNITY, HLUA_CTRLYIELD));
Aurelien DARRAGON0ebd41f2022-11-24 09:51:40 +01001584 /* lua docs says that the hook should return immediately after lua_yieldk
1585 *
1586 * From: https://www.lua.org/manual/5.3/manual.html#lua_yieldk
1587 *
1588 * Moreover, it seems that we don't want to continue after the yield
1589 * because the end of the function is about handling unyieldable function,
1590 * which is not the case here.
1591 *
1592 * ->if we don't return lua_sethook gets incorrectly set with MASKRET later
1593 * in the function.
1594 */
1595 return;
1596 }
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001597
Aurelien DARRAGONda9503c2022-11-25 09:10:07 +01001598 /* If we cannot yield, check the timeout. */
1599 if (!hlua_timer_check(&hlua->timer)) {
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001600 lua_pushfstring(L, "execution timeout");
1601 WILL_LJMP(lua_error(L));
1602 }
1603
1604 /* Try to interrupt the process at the end of the current
1605 * unyieldable function.
1606 */
1607 lua_sethook(hlua->T, hlua_hook, LUA_MASKRET|LUA_MASKCOUNT, hlua_nb_instruction);
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001608}
1609
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001610/* This function start or resumes the Lua stack execution. If the flag
1611 * "yield_allowed" if no set and the LUA stack execution returns a yield
1612 * The function return an error.
1613 *
1614 * The function can returns 4 values:
1615 * - HLUA_E_OK : The execution is terminated without any errors.
1616 * - HLUA_E_AGAIN : The execution must continue at the next associated
1617 * task wakeup.
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001618 * - HLUA_E_ERRMSG : An error has occurred, an error message is set in
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001619 * the top of the stack.
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001620 * - HLUA_E_ERR : An error has occurred without error message.
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001621 *
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001622 * If an error occurred, the stack is renewed and it is ready to run new
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001623 * LUA code.
1624 */
1625static enum hlua_exec hlua_ctx_resume(struct hlua *lua, int yield_allowed)
1626{
Christopher Faulet08ed98f2020-07-28 10:33:25 +02001627#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM >= 504
1628 int nres;
1629#endif
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001630 int ret;
1631 const char *msg;
Thierry FOURNIERfc044c92018-06-07 14:40:48 +02001632 const char *trace;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001633
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +02001634 /* Lock the whole Lua execution. This lock must be before the
1635 * label "resume_execution".
1636 */
Aurelien DARRAGONe36f8032023-03-21 13:22:33 +01001637 hlua_lock(lua);
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +02001638
Aurelien DARRAGONda9503c2022-11-25 09:10:07 +01001639 /* reset the timer as we might be re-entering the function to
1640 * resume the coroutine after a successful yield
1641 * (cumulative time will be updated)
1642 */
1643 hlua_timer_reset(&lua->timer);
1644
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001645resume_execution:
1646
1647 /* This hook interrupts the Lua processing each 'hlua_nb_instruction'
1648 * instructions. it is used for preventing infinite loops.
1649 */
1650 lua_sethook(lua->T, hlua_hook, LUA_MASKCOUNT, hlua_nb_instruction);
1651
Thierry FOURNIER1bfc09b2015-03-05 17:10:14 +01001652 /* Remove all flags except the running flags. */
Thierry FOURNIER2f3867f2015-09-28 01:02:01 +02001653 HLUA_SET_RUN(lua);
1654 HLUA_CLR_CTRLYIELD(lua);
1655 HLUA_CLR_WAKERESWR(lua);
1656 HLUA_CLR_WAKEREQWR(lua);
Christopher Faulet1f43a342021-08-04 17:58:21 +02001657 HLUA_CLR_NOYIELD(lua);
1658 if (!yield_allowed)
1659 HLUA_SET_NOYIELD(lua);
Thierry FOURNIER1bfc09b2015-03-05 17:10:14 +01001660
Aurelien DARRAGONda9503c2022-11-25 09:10:07 +01001661 /* reset wake_time. */
Christopher Fauletbc275a92020-02-26 14:55:16 +01001662 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001663
Aurelien DARRAGONda9503c2022-11-25 09:10:07 +01001664 /* start the timer as we're about to start lua processing */
1665 hlua_timer_start(&lua->timer);
1666
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001667 /* Call the function. */
Christopher Faulet08ed98f2020-07-28 10:33:25 +02001668#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM >= 504
Thierry Fournier021d9862020-11-28 23:42:03 +01001669 ret = lua_resume(lua->T, hlua_states[lua->state_id], lua->nargs, &nres);
Christopher Faulet08ed98f2020-07-28 10:33:25 +02001670#else
Thierry Fournier021d9862020-11-28 23:42:03 +01001671 ret = lua_resume(lua->T, hlua_states[lua->state_id], lua->nargs);
Christopher Faulet08ed98f2020-07-28 10:33:25 +02001672#endif
Aurelien DARRAGONda9503c2022-11-25 09:10:07 +01001673
1674 /* out of lua processing, stop the timer */
1675 hlua_timer_stop(&lua->timer);
1676
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001677 switch (ret) {
1678
1679 case LUA_OK:
1680 ret = HLUA_E_OK;
1681 break;
1682
1683 case LUA_YIELD:
Aurelien DARRAGONda9503c2022-11-25 09:10:07 +01001684 /* Check if the execution timeout is expired. If it is the case, we
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001685 * break the Lua execution.
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001686 */
Aurelien DARRAGONda9503c2022-11-25 09:10:07 +01001687 if (!hlua_timer_check(&lua->timer)) {
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001688 lua_settop(lua->T, 0); /* Empty the stack. */
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001689 ret = HLUA_E_ETMOUT;
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001690 break;
1691 }
1692 /* Process the forced yield. if the general yield is not allowed or
1693 * if no task were associated this the current Lua execution
1694 * coroutine, we resume the execution. Else we want to return in the
1695 * scheduler and we want to be waked up again, to continue the
1696 * current Lua execution. So we schedule our own task.
1697 */
1698 if (HLUA_IS_CTRLYIELDING(lua)) {
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001699 if (!yield_allowed || !lua->task)
1700 goto resume_execution;
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001701 task_wakeup(lua->task, TASK_WOKEN_MSG);
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001702 }
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001703 if (!yield_allowed) {
1704 lua_settop(lua->T, 0); /* Empty the stack. */
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001705 ret = HLUA_E_YIELD;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001706 break;
1707 }
1708 ret = HLUA_E_AGAIN;
1709 break;
1710
1711 case LUA_ERRRUN:
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001712
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001713 /* Special exit case. The traditional exit is returned as an error
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001714 * because the errors ares the only one mean to return immediately
1715 * from and lua execution.
1716 */
1717 if (lua->flags & HLUA_EXIT) {
1718 ret = HLUA_E_OK;
Christopher Faulet7716cdf2020-01-29 11:53:30 +01001719 hlua_ctx_renew(lua, 1);
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001720 break;
1721 }
1722
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001723 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001724 if (!lua_checkstack(lua->T, 1)) {
1725 ret = HLUA_E_ERR;
1726 break;
1727 }
1728 msg = lua_tostring(lua->T, -1);
1729 lua_settop(lua->T, 0); /* Empty the stack. */
1730 lua_pop(lua->T, 1);
Christopher Fauletd09cc512021-03-24 14:48:45 +01001731 trace = hlua_traceback(lua->T, ", ");
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001732 if (msg)
Thierry Fournier46278ff2020-11-29 11:48:12 +01001733 lua_pushfstring(lua->T, "[state-id %d] runtime error: %s from %s", lua->state_id, msg, trace);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001734 else
Thierry Fournier46278ff2020-11-29 11:48:12 +01001735 lua_pushfstring(lua->T, "[state-id %d] unknown runtime error from %s", lua->state_id, trace);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001736 ret = HLUA_E_ERRMSG;
1737 break;
1738
1739 case LUA_ERRMEM:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001740 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001741 lua_settop(lua->T, 0); /* Empty the stack. */
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001742 ret = HLUA_E_NOMEM;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001743 break;
1744
1745 case LUA_ERRERR:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001746 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001747 if (!lua_checkstack(lua->T, 1)) {
1748 ret = HLUA_E_ERR;
1749 break;
1750 }
1751 msg = lua_tostring(lua->T, -1);
1752 lua_settop(lua->T, 0); /* Empty the stack. */
1753 lua_pop(lua->T, 1);
1754 if (msg)
Thierry Fournier46278ff2020-11-29 11:48:12 +01001755 lua_pushfstring(lua->T, "[state-id %d] message handler error: %s", lua->state_id, msg);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001756 else
Thierry Fournier46278ff2020-11-29 11:48:12 +01001757 lua_pushfstring(lua->T, "[state-id %d] message handler error", lua->state_id);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001758 ret = HLUA_E_ERRMSG;
1759 break;
1760
1761 default:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001762 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001763 lua_settop(lua->T, 0); /* Empty the stack. */
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001764 ret = HLUA_E_ERR;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001765 break;
1766 }
1767
1768 switch (ret) {
1769 case HLUA_E_AGAIN:
1770 break;
1771
1772 case HLUA_E_ERRMSG:
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001773 notification_purge(&lua->com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001774 hlua_ctx_renew(lua, 1);
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001775 HLUA_CLR_RUN(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001776 break;
1777
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001778 case HLUA_E_ETMOUT:
1779 case HLUA_E_NOMEM:
1780 case HLUA_E_YIELD:
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001781 case HLUA_E_ERR:
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001782 HLUA_CLR_RUN(lua);
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001783 notification_purge(&lua->com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001784 hlua_ctx_renew(lua, 0);
1785 break;
1786
1787 case HLUA_E_OK:
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001788 HLUA_CLR_RUN(lua);
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001789 notification_purge(&lua->com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001790 break;
1791 }
1792
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +02001793 /* This is the main exit point, remove the Lua lock. */
Aurelien DARRAGONe36f8032023-03-21 13:22:33 +01001794 hlua_unlock(lua);
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +02001795
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001796 return ret;
1797}
1798
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001799/* This function exit the current code. */
1800__LJMP static int hlua_done(lua_State *L)
1801{
Thierry Fournier4234dbd2020-11-28 13:18:23 +01001802 struct hlua *hlua;
1803
1804 /* Get hlua struct, or NULL if we execute from main lua state */
1805 hlua = hlua_gethlua(L);
1806 if (!hlua)
1807 return 0;
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001808
1809 hlua->flags |= HLUA_EXIT;
1810 WILL_LJMP(lua_error(L));
1811
1812 return 0;
1813}
1814
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001815/* This function is an LUA binding. It provides a function
1816 * for deleting ACL from a referenced ACL file.
1817 */
1818__LJMP static int hlua_del_acl(lua_State *L)
1819{
1820 const char *name;
1821 const char *key;
1822 struct pat_ref *ref;
1823
1824 MAY_LJMP(check_args(L, 2, "del_acl"));
1825
1826 name = MAY_LJMP(luaL_checkstring(L, 1));
1827 key = MAY_LJMP(luaL_checkstring(L, 2));
1828
1829 ref = pat_ref_lookup(name);
1830 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001831 WILL_LJMP(luaL_error(L, "'del_acl': unknown acl file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001832
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001833 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001834 pat_ref_delete(ref, key);
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001835 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001836 return 0;
1837}
1838
1839/* This function is an LUA binding. It provides a function
1840 * for deleting map entry from a referenced map file.
1841 */
1842static int hlua_del_map(lua_State *L)
1843{
1844 const char *name;
1845 const char *key;
1846 struct pat_ref *ref;
1847
1848 MAY_LJMP(check_args(L, 2, "del_map"));
1849
1850 name = MAY_LJMP(luaL_checkstring(L, 1));
1851 key = MAY_LJMP(luaL_checkstring(L, 2));
1852
1853 ref = pat_ref_lookup(name);
1854 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001855 WILL_LJMP(luaL_error(L, "'del_map': unknown acl file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001856
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001857 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001858 pat_ref_delete(ref, key);
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001859 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001860 return 0;
1861}
1862
1863/* This function is an LUA binding. It provides a function
1864 * for adding ACL pattern from a referenced ACL file.
1865 */
1866static int hlua_add_acl(lua_State *L)
1867{
1868 const char *name;
1869 const char *key;
1870 struct pat_ref *ref;
1871
1872 MAY_LJMP(check_args(L, 2, "add_acl"));
1873
1874 name = MAY_LJMP(luaL_checkstring(L, 1));
1875 key = MAY_LJMP(luaL_checkstring(L, 2));
1876
1877 ref = pat_ref_lookup(name);
1878 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001879 WILL_LJMP(luaL_error(L, "'add_acl': unknown acl file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001880
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001881 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001882 if (pat_ref_find_elt(ref, key) == NULL)
1883 pat_ref_add(ref, key, NULL, NULL);
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001884 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001885 return 0;
1886}
1887
1888/* This function is an LUA binding. It provides a function
1889 * for setting map pattern and sample from a referenced map
1890 * file.
1891 */
1892static int hlua_set_map(lua_State *L)
1893{
1894 const char *name;
1895 const char *key;
1896 const char *value;
1897 struct pat_ref *ref;
1898
1899 MAY_LJMP(check_args(L, 3, "set_map"));
1900
1901 name = MAY_LJMP(luaL_checkstring(L, 1));
1902 key = MAY_LJMP(luaL_checkstring(L, 2));
1903 value = MAY_LJMP(luaL_checkstring(L, 3));
1904
1905 ref = pat_ref_lookup(name);
1906 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001907 WILL_LJMP(luaL_error(L, "'set_map': unknown map file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001908
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001909 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001910 if (pat_ref_find_elt(ref, key) != NULL)
1911 pat_ref_set(ref, key, value, NULL);
1912 else
1913 pat_ref_add(ref, key, value, NULL);
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001914 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001915 return 0;
1916}
1917
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01001918/* A class is a lot of memory that contain data. This data can be a table,
1919 * an integer or user data. This data is associated with a metatable. This
Ilya Shipitsinc02a23f2020-05-06 00:53:22 +05001920 * metatable have an original version registered in the global context with
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01001921 * the name of the object (_G[<name>] = <metable> ).
1922 *
1923 * A metable is a table that modify the standard behavior of a standard
1924 * access to the associated data. The entries of this new metatable are
1925 * defined as is:
1926 *
1927 * http://lua-users.org/wiki/MetatableEvents
1928 *
1929 * __index
1930 *
1931 * we access an absent field in a table, the result is nil. This is
1932 * true, but it is not the whole truth. Actually, such access triggers
1933 * the interpreter to look for an __index metamethod: If there is no
1934 * such method, as usually happens, then the access results in nil;
1935 * otherwise, the metamethod will provide the result.
1936 *
1937 * Control 'prototype' inheritance. When accessing "myTable[key]" and
1938 * the key does not appear in the table, but the metatable has an __index
1939 * property:
1940 *
1941 * - if the value is a function, the function is called, passing in the
1942 * table and the key; the return value of that function is returned as
1943 * the result.
1944 *
1945 * - if the value is another table, the value of the key in that table is
1946 * asked for and returned (and if it doesn't exist in that table, but that
1947 * table's metatable has an __index property, then it continues on up)
1948 *
1949 * - Use "rawget(myTable,key)" to skip this metamethod.
1950 *
1951 * http://www.lua.org/pil/13.4.1.html
1952 *
1953 * __newindex
1954 *
1955 * Like __index, but control property assignment.
1956 *
1957 * __mode - Control weak references. A string value with one or both
1958 * of the characters 'k' and 'v' which specifies that the the
1959 * keys and/or values in the table are weak references.
1960 *
1961 * __call - Treat a table like a function. When a table is followed by
1962 * parenthesis such as "myTable( 'foo' )" and the metatable has
1963 * a __call key pointing to a function, that function is invoked
1964 * (passing any specified arguments) and the return value is
1965 * returned.
1966 *
1967 * __metatable - Hide the metatable. When "getmetatable( myTable )" is
1968 * called, if the metatable for myTable has a __metatable
1969 * key, the value of that key is returned instead of the
1970 * actual metatable.
1971 *
1972 * __tostring - Control string representation. When the builtin
1973 * "tostring( myTable )" function is called, if the metatable
1974 * for myTable has a __tostring property set to a function,
1975 * that function is invoked (passing myTable to it) and the
1976 * return value is used as the string representation.
1977 *
1978 * __len - Control table length. When the table length is requested using
1979 * the length operator ( '#' ), if the metatable for myTable has
1980 * a __len key pointing to a function, that function is invoked
1981 * (passing myTable to it) and the return value used as the value
1982 * of "#myTable".
1983 *
1984 * __gc - Userdata finalizer code. When userdata is set to be garbage
1985 * collected, if the metatable has a __gc field pointing to a
1986 * function, that function is first invoked, passing the userdata
1987 * to it. The __gc metamethod is not called for tables.
1988 * (See http://lua-users.org/lists/lua-l/2006-11/msg00508.html)
1989 *
1990 * Special metamethods for redefining standard operators:
1991 * http://www.lua.org/pil/13.1.html
1992 *
1993 * __add "+"
1994 * __sub "-"
1995 * __mul "*"
1996 * __div "/"
1997 * __unm "!"
1998 * __pow "^"
1999 * __concat ".."
2000 *
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05002001 * Special methods for redefining standard relations
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01002002 * http://www.lua.org/pil/13.2.html
2003 *
2004 * __eq "=="
2005 * __lt "<"
2006 * __le "<="
2007 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002008
2009/*
2010 *
2011 *
Thierry FOURNIER3def3932015-04-07 11:27:54 +02002012 * Class Map
2013 *
2014 *
2015 */
2016
2017/* Returns a struct hlua_map if the stack entry "ud" is
2018 * a class session, otherwise it throws an error.
2019 */
2020__LJMP static struct map_descriptor *hlua_checkmap(lua_State *L, int ud)
2021{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02002022 return MAY_LJMP(hlua_checkudata(L, ud, class_map_ref));
Thierry FOURNIER3def3932015-04-07 11:27:54 +02002023}
2024
2025/* This function is the map constructor. It don't need
2026 * the class Map object. It creates and return a new Map
2027 * object. It must be called only during "body" or "init"
2028 * context because it process some filesystem accesses.
2029 */
2030__LJMP static int hlua_map_new(struct lua_State *L)
2031{
2032 const char *fn;
2033 int match = PAT_MATCH_STR;
2034 struct sample_conv conv;
2035 const char *file = "";
2036 int line = 0;
2037 lua_Debug ar;
2038 char *err = NULL;
2039 struct arg args[2];
2040
2041 if (lua_gettop(L) < 1 || lua_gettop(L) > 2)
2042 WILL_LJMP(luaL_error(L, "'new' needs at least 1 argument."));
2043
2044 fn = MAY_LJMP(luaL_checkstring(L, 1));
2045
2046 if (lua_gettop(L) >= 2) {
2047 match = MAY_LJMP(luaL_checkinteger(L, 2));
2048 if (match < 0 || match >= PAT_MATCH_NUM)
2049 WILL_LJMP(luaL_error(L, "'new' needs a valid match method."));
2050 }
2051
2052 /* Get Lua filename and line number. */
2053 if (lua_getstack(L, 1, &ar)) { /* check function at level */
2054 lua_getinfo(L, "Sl", &ar); /* get info about it */
2055 if (ar.currentline > 0) { /* is there info? */
2056 file = ar.short_src;
2057 line = ar.currentline;
2058 }
2059 }
2060
2061 /* fill fake sample_conv struct. */
2062 conv.kw = ""; /* unused. */
2063 conv.process = NULL; /* unused. */
2064 conv.arg_mask = 0; /* unused. */
2065 conv.val_args = NULL; /* unused. */
2066 conv.out_type = SMP_T_STR;
2067 conv.private = (void *)(long)match;
2068 switch (match) {
2069 case PAT_MATCH_STR: conv.in_type = SMP_T_STR; break;
2070 case PAT_MATCH_BEG: conv.in_type = SMP_T_STR; break;
2071 case PAT_MATCH_SUB: conv.in_type = SMP_T_STR; break;
2072 case PAT_MATCH_DIR: conv.in_type = SMP_T_STR; break;
2073 case PAT_MATCH_DOM: conv.in_type = SMP_T_STR; break;
2074 case PAT_MATCH_END: conv.in_type = SMP_T_STR; break;
2075 case PAT_MATCH_REG: conv.in_type = SMP_T_STR; break;
Thierry FOURNIER07ee64e2015-07-06 23:43:03 +02002076 case PAT_MATCH_INT: conv.in_type = SMP_T_SINT; break;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02002077 case PAT_MATCH_IP: conv.in_type = SMP_T_ADDR; break;
2078 default:
2079 WILL_LJMP(luaL_error(L, "'new' doesn't support this match mode."));
2080 }
2081
2082 /* fill fake args. */
2083 args[0].type = ARGT_STR;
Christopher Faulet73292e92020-08-06 08:40:09 +02002084 args[0].data.str.area = strdup(fn);
2085 args[0].data.str.data = strlen(fn);
2086 args[0].data.str.size = args[0].data.str.data+1;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02002087 args[1].type = ARGT_STOP;
2088
2089 /* load the map. */
2090 if (!sample_load_map(args, &conv, file, line, &err)) {
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +05002091 /* error case: we can't use luaL_error because we must
Thierry FOURNIER3def3932015-04-07 11:27:54 +02002092 * free the err variable.
2093 */
2094 luaL_where(L, 1);
2095 lua_pushfstring(L, "'new': %s.", err);
2096 lua_concat(L, 2);
2097 free(err);
Christopher Faulet6ad7df42020-08-07 11:45:18 +02002098 chunk_destroy(&args[0].data.str);
Thierry FOURNIER3def3932015-04-07 11:27:54 +02002099 WILL_LJMP(lua_error(L));
2100 }
2101
2102 /* create the lua object. */
2103 lua_newtable(L);
2104 lua_pushlightuserdata(L, args[0].data.map);
2105 lua_rawseti(L, -2, 0);
2106
2107 /* Pop a class Map metatable and affect it to the userdata. */
2108 lua_rawgeti(L, LUA_REGISTRYINDEX, class_map_ref);
2109 lua_setmetatable(L, -2);
2110
2111
2112 return 1;
2113}
2114
2115__LJMP static inline int _hlua_map_lookup(struct lua_State *L, int str)
2116{
2117 struct map_descriptor *desc;
2118 struct pattern *pat;
2119 struct sample smp;
2120
2121 MAY_LJMP(check_args(L, 2, "lookup"));
2122 desc = MAY_LJMP(hlua_checkmap(L, 1));
Thierry FOURNIER07ee64e2015-07-06 23:43:03 +02002123 if (desc->pat.expect_type == SMP_T_SINT) {
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02002124 smp.data.type = SMP_T_SINT;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +02002125 smp.data.u.sint = MAY_LJMP(luaL_checkinteger(L, 2));
Thierry FOURNIER3def3932015-04-07 11:27:54 +02002126 }
2127 else {
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02002128 smp.data.type = SMP_T_STR;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02002129 smp.flags = SMP_F_CONST;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02002130 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 +01002131 smp.data.u.str.size = smp.data.u.str.data + 1;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02002132 }
2133
2134 pat = pattern_exec_match(&desc->pat, &smp, 1);
Thierry FOURNIER503bb092015-08-19 08:35:43 +02002135 if (!pat || !pat->data) {
Thierry FOURNIER3def3932015-04-07 11:27:54 +02002136 if (str)
2137 lua_pushstring(L, "");
2138 else
2139 lua_pushnil(L);
2140 return 1;
2141 }
2142
2143 /* The Lua pattern must return a string, so we can't check the returned type */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02002144 lua_pushlstring(L, pat->data->u.str.area, pat->data->u.str.data);
Thierry FOURNIER3def3932015-04-07 11:27:54 +02002145 return 1;
2146}
2147
2148__LJMP static int hlua_map_lookup(struct lua_State *L)
2149{
2150 return _hlua_map_lookup(L, 0);
2151}
2152
2153__LJMP static int hlua_map_slookup(struct lua_State *L)
2154{
2155 return _hlua_map_lookup(L, 1);
2156}
2157
2158/*
2159 *
2160 *
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002161 * Class Socket
2162 *
2163 *
2164 */
2165
2166__LJMP static struct hlua_socket *hlua_checksocket(lua_State *L, int ud)
2167{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02002168 return MAY_LJMP(hlua_checkudata(L, ud, class_socket_ref));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002169}
2170
2171/* This function is the handler called for each I/O on the established
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002172 * connection. It is used for notify space available to send or data
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002173 * received.
2174 */
Willy Tarreau00a37f02015-04-13 12:05:19 +02002175static void hlua_socket_handler(struct appctx *appctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002176{
Willy Tarreau5321da92022-05-06 11:57:34 +02002177 struct hlua_csk_ctx *ctx = appctx->svcctx;
Willy Tarreauc12b3212022-05-27 11:08:15 +02002178 struct stconn *sc = appctx_sc(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002179
Christopher Faulet31572222023-03-31 11:13:48 +02002180 if (unlikely(se_fl_test(appctx->sedesc, (SE_FL_EOS|SE_FL_ERROR|SE_FL_SHR|SE_FL_SHW)))) {
2181 notification_wake(&ctx->wake_on_read);
2182 notification_wake(&ctx->wake_on_write);
2183 return;
2184 }
2185
Willy Tarreau5321da92022-05-06 11:57:34 +02002186 if (ctx->die) {
Christopher Faulet31572222023-03-31 11:13:48 +02002187 se_fl_set(appctx->sedesc, SE_FL_EOI|SE_FL_EOS);
Willy Tarreau5321da92022-05-06 11:57:34 +02002188 notification_wake(&ctx->wake_on_read);
2189 notification_wake(&ctx->wake_on_write);
Christopher Faulet31572222023-03-31 11:13:48 +02002190 return;
Thierry FOURNIERb13b20a2017-07-16 20:48:54 +02002191 }
2192
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +05002193 /* If we can't write, wakeup the pending write signals. */
Willy Tarreau3e7be362022-05-27 10:35:27 +02002194 if (channel_output_closed(sc_ic(sc)))
Willy Tarreau5321da92022-05-06 11:57:34 +02002195 notification_wake(&ctx->wake_on_write);
Thierry FOURNIER6d695e62015-09-27 19:29:38 +02002196
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +05002197 /* If we can't read, wakeup the pending read signals. */
Willy Tarreau3e7be362022-05-27 10:35:27 +02002198 if (channel_input_closed(sc_oc(sc)))
Willy Tarreau5321da92022-05-06 11:57:34 +02002199 notification_wake(&ctx->wake_on_read);
Thierry FOURNIER6d695e62015-09-27 19:29:38 +02002200
Willy Tarreau5a0b25d2019-07-18 18:01:14 +02002201 /* if the connection is not established, inform the stream that we want
Thierry FOURNIER316e3192015-09-04 18:25:53 +02002202 * to be notified whenever the connection completes.
2203 */
Willy Tarreau3e7be362022-05-27 10:35:27 +02002204 if (sc_opposite(sc)->state < SC_ST_EST) {
Willy Tarreau90e8b452022-05-25 18:21:43 +02002205 applet_need_more_data(appctx);
Willy Tarreaub23edc82022-05-24 16:49:03 +02002206 se_need_remote_conn(appctx->sedesc);
Willy Tarreau4164eb92022-05-25 15:42:03 +02002207 applet_have_more_data(appctx);
Willy Tarreaud4da1962015-04-20 01:31:23 +02002208 return;
Thierry FOURNIER316e3192015-09-04 18:25:53 +02002209 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002210
2211 /* This function is called after the connect. */
Willy Tarreau5321da92022-05-06 11:57:34 +02002212 ctx->connected = 1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002213
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002214 /* Wake the tasks which wants to write if the buffer have available space. */
Willy Tarreau3e7be362022-05-27 10:35:27 +02002215 if (channel_may_recv(sc_ic(sc)))
Willy Tarreau5321da92022-05-06 11:57:34 +02002216 notification_wake(&ctx->wake_on_write);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002217
2218 /* Wake the tasks which wants to read if the buffer contains data. */
Willy Tarreau3e7be362022-05-27 10:35:27 +02002219 if (!channel_is_empty(sc_oc(sc)))
Willy Tarreau5321da92022-05-06 11:57:34 +02002220 notification_wake(&ctx->wake_on_read);
Thierry FOURNIER101b9762018-05-27 01:27:40 +02002221
Thierry FOURNIER101b9762018-05-27 01:27:40 +02002222 /* If write notifications are registered, we considers we want
Willy Tarreau3367d412018-11-15 10:57:41 +01002223 * to write, so we clear the blocking flag.
Thierry FOURNIER101b9762018-05-27 01:27:40 +02002224 */
Willy Tarreau5321da92022-05-06 11:57:34 +02002225 if (notification_registered(&ctx->wake_on_write))
Willy Tarreau4164eb92022-05-25 15:42:03 +02002226 applet_have_more_data(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002227}
2228
Christopher Faulet5f35a3e2022-05-12 15:31:05 +02002229static int hlua_socket_init(struct appctx *appctx)
2230{
2231 struct hlua_csk_ctx *ctx = appctx->svcctx;
2232 struct stream *s;
2233
2234 if (appctx_finalize_startup(appctx, socket_proxy, &BUF_NULL) == -1)
2235 goto error;
2236
2237 s = appctx_strm(appctx);
2238
Willy Tarreau4596fe22022-05-17 19:07:51 +02002239 /* Configure "right" stream connector. This stconn is used to connect
Christopher Faulet5f35a3e2022-05-12 15:31:05 +02002240 * and retrieve data from the server. The connection is initialized
2241 * with the "struct server".
2242 */
Willy Tarreau74568cf2022-05-27 09:03:30 +02002243 sc_set_state(s->scb, SC_ST_ASS);
Christopher Faulet5f35a3e2022-05-12 15:31:05 +02002244
2245 /* Force destination server. */
2246 s->flags |= SF_DIRECT | SF_ASSIGNED | SF_BE_ASSIGNED;
2247 s->target = &socket_tcp->obj_type;
2248
2249 ctx->appctx = appctx;
2250 return 0;
2251
2252 error:
2253 return -1;
2254}
2255
Willy Tarreau87b09662015-04-03 00:22:06 +02002256/* This function is called when the "struct stream" is destroyed.
2257 * Remove the link from the object to this stream.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002258 * Wake all the pending signals.
2259 */
Willy Tarreau00a37f02015-04-13 12:05:19 +02002260static void hlua_socket_release(struct appctx *appctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002261{
Willy Tarreau5321da92022-05-06 11:57:34 +02002262 struct hlua_csk_ctx *ctx = appctx->svcctx;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002263 struct xref *peer;
2264
Christopher Faulet5f35a3e2022-05-12 15:31:05 +02002265 /* Remove my link in the original objects. */
Willy Tarreau5321da92022-05-06 11:57:34 +02002266 peer = xref_get_peer_and_lock(&ctx->xref);
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002267 if (peer)
Willy Tarreau5321da92022-05-06 11:57:34 +02002268 xref_disconnect(&ctx->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002269
2270 /* Wake all the task waiting for me. */
Willy Tarreau5321da92022-05-06 11:57:34 +02002271 notification_wake(&ctx->wake_on_read);
2272 notification_wake(&ctx->wake_on_write);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002273}
2274
2275/* If the garbage collectio of the object is launch, nobody
Willy Tarreau87b09662015-04-03 00:22:06 +02002276 * uses this object. If the stream does not exists, just quit.
2277 * Send the shutdown signal to the stream. In some cases,
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002278 * pending signal can rest in the read and write lists. destroy
2279 * it.
2280 */
2281__LJMP static int hlua_socket_gc(lua_State *L)
2282{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002283 struct hlua_socket *socket;
Willy Tarreau5321da92022-05-06 11:57:34 +02002284 struct hlua_csk_ctx *ctx;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002285 struct xref *peer;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002286
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002287 MAY_LJMP(check_args(L, 1, "__gc"));
2288
2289 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002290 peer = xref_get_peer_and_lock(&socket->xref);
2291 if (!peer)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002292 return 0;
Willy Tarreau5321da92022-05-06 11:57:34 +02002293
2294 ctx = container_of(peer, struct hlua_csk_ctx, xref);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002295
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002296 /* Set the flag which destroy the session. */
Willy Tarreau5321da92022-05-06 11:57:34 +02002297 ctx->die = 1;
2298 appctx_wakeup(ctx->appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002299
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002300 /* Remove all reference between the Lua stack and the coroutine stream. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002301 xref_disconnect(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002302 return 0;
2303}
2304
2305/* The close function send shutdown signal and break the
Willy Tarreau87b09662015-04-03 00:22:06 +02002306 * links between the stream and the object.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002307 */
sada05ed3302018-05-11 11:48:18 -07002308__LJMP static int hlua_socket_close_helper(lua_State *L)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002309{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002310 struct hlua_socket *socket;
Willy Tarreau5321da92022-05-06 11:57:34 +02002311 struct hlua_csk_ctx *ctx;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002312 struct xref *peer;
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002313 struct hlua *hlua;
2314
2315 /* Get hlua struct, or NULL if we execute from main lua state */
2316 hlua = hlua_gethlua(L);
2317 if (!hlua)
2318 return 0;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002319
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002320 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002321
2322 /* Check if we run on the same thread than the xreator thread.
2323 * We cannot access to the socket if the thread is different.
2324 */
2325 if (socket->tid != tid)
2326 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2327
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002328 peer = xref_get_peer_and_lock(&socket->xref);
2329 if (!peer)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002330 return 0;
Willy Tarreauf31af932020-01-14 09:59:38 +01002331
2332 hlua->gc_count--;
Willy Tarreau5321da92022-05-06 11:57:34 +02002333 ctx = container_of(peer, struct hlua_csk_ctx, xref);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002334
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002335 /* Set the flag which destroy the session. */
Willy Tarreau5321da92022-05-06 11:57:34 +02002336 ctx->die = 1;
2337 appctx_wakeup(ctx->appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002338
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002339 /* Remove all reference between the Lua stack and the coroutine stream. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002340 xref_disconnect(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002341 return 0;
2342}
2343
sada05ed3302018-05-11 11:48:18 -07002344/* The close function calls close_helper.
2345 */
2346__LJMP static int hlua_socket_close(lua_State *L)
2347{
2348 MAY_LJMP(check_args(L, 1, "close"));
2349 return hlua_socket_close_helper(L);
2350}
2351
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002352/* This Lua function assumes that the stack contain three parameters.
2353 * 1 - USERDATA containing a struct socket
2354 * 2 - INTEGER with values of the macro defined below
2355 * If the integer is -1, we must read at most one line.
2356 * If the integer is -2, we ust read all the data until the
2357 * end of the stream.
2358 * If the integer is positive value, we must read a number of
2359 * bytes corresponding to this value.
2360 */
2361#define HLSR_READ_LINE (-1)
2362#define HLSR_READ_ALL (-2)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002363__LJMP static int hlua_socket_receive_yield(struct lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002364{
2365 struct hlua_socket *socket = MAY_LJMP(hlua_checksocket(L, 1));
2366 int wanted = lua_tointeger(L, 2);
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002367 struct hlua *hlua;
Willy Tarreau5321da92022-05-06 11:57:34 +02002368 struct hlua_csk_ctx *csk_ctx;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002369 struct appctx *appctx;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02002370 size_t len;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002371 int nblk;
Willy Tarreau206ba832018-06-14 15:27:31 +02002372 const char *blk1;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02002373 size_t len1;
Willy Tarreau206ba832018-06-14 15:27:31 +02002374 const char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02002375 size_t len2;
Thierry FOURNIER00543922015-03-09 18:35:06 +01002376 int skip_at_end = 0;
Willy Tarreau81389672015-03-10 12:03:52 +01002377 struct channel *oc;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002378 struct stream *s;
2379 struct xref *peer;
Thierry FOURNIER8c126c72018-05-25 16:27:44 +02002380 int missing_bytes;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002381
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002382 /* Get hlua struct, or NULL if we execute from main lua state */
2383 hlua = hlua_gethlua(L);
2384
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002385 /* Check if this lua stack is schedulable. */
2386 if (!hlua || !hlua->task)
2387 WILL_LJMP(luaL_error(L, "The 'receive' function is only allowed in "
2388 "'frontend', 'backend' or 'task'"));
2389
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002390 /* Check if we run on the same thread than the xreator thread.
2391 * We cannot access to the socket if the thread is different.
2392 */
2393 if (socket->tid != tid)
2394 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2395
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002396 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002397 peer = xref_get_peer_and_lock(&socket->xref);
2398 if (!peer)
2399 goto no_peer;
Willy Tarreau5321da92022-05-06 11:57:34 +02002400
2401 csk_ctx = container_of(peer, struct hlua_csk_ctx, xref);
2402 appctx = csk_ctx->appctx;
Willy Tarreau0698c802022-05-11 14:09:57 +02002403 s = appctx_strm(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002404
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002405 oc = &s->res;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002406 if (wanted == HLSR_READ_LINE) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002407 /* Read line. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02002408 nblk = co_getline_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002409 if (nblk < 0) /* Connection close. */
2410 goto connection_closed;
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002411 if (nblk == 0) /* No data available. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002412 goto connection_empty;
Thierry FOURNIER00543922015-03-09 18:35:06 +01002413
2414 /* remove final \r\n. */
2415 if (nblk == 1) {
2416 if (blk1[len1-1] == '\n') {
2417 len1--;
2418 skip_at_end++;
2419 if (blk1[len1-1] == '\r') {
2420 len1--;
2421 skip_at_end++;
2422 }
2423 }
2424 }
2425 else {
2426 if (blk2[len2-1] == '\n') {
2427 len2--;
2428 skip_at_end++;
2429 if (blk2[len2-1] == '\r') {
2430 len2--;
2431 skip_at_end++;
2432 }
2433 }
2434 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002435 }
2436
2437 else if (wanted == HLSR_READ_ALL) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002438 /* Read all the available data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02002439 nblk = co_getblk_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002440 if (nblk < 0) /* Connection close. */
2441 goto connection_closed;
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002442 if (nblk == 0) /* No data available. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002443 goto connection_empty;
2444 }
2445
2446 else {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002447 /* Read a block of data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02002448 nblk = co_getblk_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002449 if (nblk < 0) /* Connection close. */
2450 goto connection_closed;
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002451 if (nblk == 0) /* No data available. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002452 goto connection_empty;
2453
Thierry FOURNIER8c126c72018-05-25 16:27:44 +02002454 missing_bytes = wanted - socket->b.n;
2455 if (len1 > missing_bytes) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002456 nblk = 1;
Thierry FOURNIER8c126c72018-05-25 16:27:44 +02002457 len1 = missing_bytes;
2458 } if (nblk == 2 && len1 + len2 > missing_bytes)
2459 len2 = missing_bytes - len1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002460 }
2461
2462 len = len1;
2463
2464 luaL_addlstring(&socket->b, blk1, len1);
2465 if (nblk == 2) {
2466 len += len2;
2467 luaL_addlstring(&socket->b, blk2, len2);
2468 }
2469
2470 /* Consume data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02002471 co_skip(oc, len + skip_at_end);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002472
2473 /* Don't wait anything. */
Thierry FOURNIER7e4ee472018-05-25 15:03:50 +02002474 appctx_wakeup(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002475
2476 /* If the pattern reclaim to read all the data
2477 * in the connection, got out.
2478 */
2479 if (wanted == HLSR_READ_ALL)
2480 goto connection_empty;
Thierry FOURNIER8c126c72018-05-25 16:27:44 +02002481 else if (wanted >= 0 && socket->b.n < wanted)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002482 goto connection_empty;
2483
2484 /* Return result. */
2485 luaL_pushresult(&socket->b);
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002486 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002487 return 1;
2488
2489connection_closed:
2490
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002491 xref_unlock(&socket->xref, peer);
2492
2493no_peer:
2494
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002495 /* If the buffer containds data. */
2496 if (socket->b.n > 0) {
2497 luaL_pushresult(&socket->b);
2498 return 1;
2499 }
2500 lua_pushnil(L);
2501 lua_pushstring(L, "connection closed.");
2502 return 2;
2503
2504connection_empty:
2505
Willy Tarreau5321da92022-05-06 11:57:34 +02002506 if (!notification_new(&hlua->com, &csk_ctx->wake_on_read, hlua->task)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002507 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002508 WILL_LJMP(luaL_error(L, "out of memory"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002509 }
2510 xref_unlock(&socket->xref, peer);
Willy Tarreau9635e032018-10-16 17:52:55 +02002511 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_receive_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002512 return 0;
2513}
2514
Tim Duesterhusb33754c2018-01-04 19:32:14 +01002515/* This Lua function gets two parameters. The first one can be string
2516 * or a number. If the string is "*l", the user requires one line. If
2517 * the string is "*a", the user requires all the contents of the stream.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002518 * If the value is a number, the user require a number of bytes equal
2519 * to the value. The default value is "*l" (a line).
2520 *
Tim Duesterhusb33754c2018-01-04 19:32:14 +01002521 * This parameter with a variable type is converted in integer. This
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002522 * integer takes this values:
2523 * -1 : read a line
2524 * -2 : read all the stream
Tim Duesterhusb33754c2018-01-04 19:32:14 +01002525 * >0 : amount of bytes.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002526 *
Tim Duesterhusb33754c2018-01-04 19:32:14 +01002527 * The second parameter is optional. It contains a string that must be
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002528 * concatenated with the read data.
2529 */
2530__LJMP static int hlua_socket_receive(struct lua_State *L)
2531{
2532 int wanted = HLSR_READ_LINE;
2533 const char *pattern;
Christopher Fauletc31b2002021-05-03 10:11:13 +02002534 int lastarg, type;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002535 char *error;
2536 size_t len;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002537 struct hlua_socket *socket;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002538
2539 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
2540 WILL_LJMP(luaL_error(L, "The 'receive' function requires between 1 and 3 arguments."));
2541
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002542 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002543
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002544 /* Check if we run on the same thread than the xreator thread.
2545 * We cannot access to the socket if the thread is different.
2546 */
2547 if (socket->tid != tid)
2548 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2549
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002550 /* check for pattern. */
2551 if (lua_gettop(L) >= 2) {
2552 type = lua_type(L, 2);
2553 if (type == LUA_TSTRING) {
2554 pattern = lua_tostring(L, 2);
2555 if (strcmp(pattern, "*a") == 0)
2556 wanted = HLSR_READ_ALL;
2557 else if (strcmp(pattern, "*l") == 0)
2558 wanted = HLSR_READ_LINE;
2559 else {
2560 wanted = strtoll(pattern, &error, 10);
2561 if (*error != '\0')
2562 WILL_LJMP(luaL_error(L, "Unsupported pattern."));
2563 }
2564 }
2565 else if (type == LUA_TNUMBER) {
2566 wanted = lua_tointeger(L, 2);
2567 if (wanted < 0)
2568 WILL_LJMP(luaL_error(L, "Unsupported size."));
2569 }
2570 }
2571
2572 /* Set pattern. */
2573 lua_pushinteger(L, wanted);
Tim Duesterhusc6e377e2018-01-04 19:32:13 +01002574
2575 /* Check if we would replace the top by itself. */
2576 if (lua_gettop(L) != 2)
2577 lua_replace(L, 2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002578
Christopher Fauletc31b2002021-05-03 10:11:13 +02002579 /* Save index of the top of the stack because since buffers are used, it
2580 * may change
2581 */
2582 lastarg = lua_gettop(L);
2583
Tim Duesterhusb33754c2018-01-04 19:32:14 +01002584 /* init buffer, and fill it with prefix. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002585 luaL_buffinit(L, &socket->b);
2586
2587 /* Check prefix. */
Christopher Fauletc31b2002021-05-03 10:11:13 +02002588 if (lastarg >= 3) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002589 if (lua_type(L, 3) != LUA_TSTRING)
2590 WILL_LJMP(luaL_error(L, "Expect a 'string' for the prefix"));
2591 pattern = lua_tolstring(L, 3, &len);
2592 luaL_addlstring(&socket->b, pattern, len);
2593 }
2594
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002595 return __LJMP(hlua_socket_receive_yield(L, 0, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002596}
2597
2598/* Write the Lua input string in the output buffer.
Mark Lakes22154b42018-01-29 14:38:40 -08002599 * This function returns a yield if no space is available.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002600 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002601static int hlua_socket_write_yield(struct lua_State *L,int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002602{
2603 struct hlua_socket *socket;
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002604 struct hlua *hlua;
Willy Tarreau5321da92022-05-06 11:57:34 +02002605 struct hlua_csk_ctx *csk_ctx;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002606 struct appctx *appctx;
2607 size_t buf_len;
2608 const char *buf;
2609 int len;
2610 int send_len;
2611 int sent;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002612 struct xref *peer;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002613 struct stream *s;
Willy Tarreau3e7be362022-05-27 10:35:27 +02002614 struct stconn *sc;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002615
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002616 /* Get hlua struct, or NULL if we execute from main lua state */
2617 hlua = hlua_gethlua(L);
2618
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002619 /* Check if this lua stack is schedulable. */
2620 if (!hlua || !hlua->task)
2621 WILL_LJMP(luaL_error(L, "The 'write' function is only allowed in "
2622 "'frontend', 'backend' or 'task'"));
2623
2624 /* Get object */
2625 socket = MAY_LJMP(hlua_checksocket(L, 1));
2626 buf = MAY_LJMP(luaL_checklstring(L, 2, &buf_len));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002627 sent = MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002628
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002629 /* Check if we run on the same thread than the xreator thread.
2630 * We cannot access to the socket if the thread is different.
2631 */
2632 if (socket->tid != tid)
2633 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2634
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002635 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002636 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002637 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002638 lua_pushinteger(L, -1);
2639 return 1;
2640 }
Willy Tarreau5321da92022-05-06 11:57:34 +02002641
2642 csk_ctx = container_of(peer, struct hlua_csk_ctx, xref);
2643 appctx = csk_ctx->appctx;
Willy Tarreauc12b3212022-05-27 11:08:15 +02002644 sc = appctx_sc(appctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02002645 s = __sc_strm(sc);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002646
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002647 /* Check for connection close. */
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002648 if (channel_output_closed(&s->req)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002649 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002650 lua_pushinteger(L, -1);
2651 return 1;
2652 }
2653
2654 /* Update the input buffer data. */
2655 buf += sent;
2656 send_len = buf_len - sent;
2657
2658 /* All the data are sent. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002659 if (sent >= buf_len) {
2660 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002661 return 1; /* Implicitly return the length sent. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002662 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002663
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002664 /* Check if the buffer is available because HAProxy doesn't allocate
Thierry FOURNIER486d52a2015-03-09 17:51:43 +01002665 * the request buffer if its not required.
2666 */
Willy Tarreauc9fa0482018-07-10 17:43:27 +02002667 if (s->req.buf.size == 0) {
Willy Tarreau3e7be362022-05-27 10:35:27 +02002668 if (!sc_alloc_ibuf(sc, &appctx->buffer_wait))
Christopher Faulet33834b12016-12-19 09:29:06 +01002669 goto hlua_socket_write_yield_return;
Thierry FOURNIER486d52a2015-03-09 17:51:43 +01002670 }
2671
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002672 /* Check for available space. */
Willy Tarreauc9fa0482018-07-10 17:43:27 +02002673 len = b_room(&s->req.buf);
Christopher Faulet33834b12016-12-19 09:29:06 +01002674 if (len <= 0) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002675 goto hlua_socket_write_yield_return;
Christopher Faulet33834b12016-12-19 09:29:06 +01002676 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002677
2678 /* send data */
2679 if (len < send_len)
2680 send_len = len;
Thierry FOURNIER66b89192018-05-27 01:14:47 +02002681 len = ci_putblk(&s->req, buf, send_len);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002682
2683 /* "Not enough space" (-1), "Buffer too little to contain
2684 * the data" (-2) are not expected because the available length
2685 * is tested.
2686 * Other unknown error are also not expected.
2687 */
2688 if (len <= 0) {
Willy Tarreaubc18da12015-03-13 14:00:47 +01002689 if (len == -1)
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002690 s->req.flags |= CF_WAKE_WRITE;
Willy Tarreaubc18da12015-03-13 14:00:47 +01002691
sada05ed3302018-05-11 11:48:18 -07002692 MAY_LJMP(hlua_socket_close_helper(L));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002693 lua_pop(L, 1);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002694 lua_pushinteger(L, -1);
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002695 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002696 return 1;
2697 }
2698
2699 /* update buffers. */
Thierry FOURNIER101b9762018-05-27 01:27:40 +02002700 appctx_wakeup(appctx);
Willy Tarreaude70fa12015-09-26 11:25:05 +02002701
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002702 /* Update length sent. */
2703 lua_pop(L, 1);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002704 lua_pushinteger(L, sent + len);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002705
2706 /* All the data buffer is sent ? */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002707 if (sent + len >= buf_len) {
2708 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002709 return 1;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002710 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002711
2712hlua_socket_write_yield_return:
Willy Tarreau5321da92022-05-06 11:57:34 +02002713 if (!notification_new(&hlua->com, &csk_ctx->wake_on_write, hlua->task)) {
Thierry FOURNIERba42fcd2018-05-27 00:59:48 +02002714 xref_unlock(&socket->xref, peer);
2715 WILL_LJMP(luaL_error(L, "out of memory"));
2716 }
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002717 xref_unlock(&socket->xref, peer);
Willy Tarreau9635e032018-10-16 17:52:55 +02002718 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_write_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002719 return 0;
2720}
2721
2722/* This function initiate the send of data. It just check the input
2723 * parameters and push an integer in the Lua stack that contain the
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002724 * amount of data written to the buffer. This is used by the function
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002725 * "hlua_socket_write_yield" that can yield.
2726 *
2727 * The Lua function gets between 3 and 4 parameters. The first one is
2728 * the associated object. The second is a string buffer. The third is
2729 * a facultative integer that represents where is the buffer position
2730 * of the start of the data that can send. The first byte is the
2731 * position "1". The default value is "1". The fourth argument is a
2732 * facultative integer that represents where is the buffer position
2733 * of the end of the data that can send. The default is the last byte.
2734 */
2735static int hlua_socket_send(struct lua_State *L)
2736{
2737 int i;
2738 int j;
2739 const char *buf;
2740 size_t buf_len;
2741
2742 /* Check number of arguments. */
2743 if (lua_gettop(L) < 2 || lua_gettop(L) > 4)
2744 WILL_LJMP(luaL_error(L, "'send' needs between 2 and 4 arguments"));
2745
2746 /* Get the string. */
2747 buf = MAY_LJMP(luaL_checklstring(L, 2, &buf_len));
2748
2749 /* Get and check j. */
2750 if (lua_gettop(L) == 4) {
2751 j = MAY_LJMP(luaL_checkinteger(L, 4));
2752 if (j < 0)
2753 j = buf_len + j + 1;
2754 if (j > buf_len)
2755 j = buf_len + 1;
2756 lua_pop(L, 1);
2757 }
2758 else
2759 j = buf_len;
2760
2761 /* Get and check i. */
2762 if (lua_gettop(L) == 3) {
2763 i = MAY_LJMP(luaL_checkinteger(L, 3));
2764 if (i < 0)
2765 i = buf_len + i + 1;
2766 if (i > buf_len)
2767 i = buf_len + 1;
2768 lua_pop(L, 1);
2769 } else
2770 i = 1;
2771
2772 /* Check bth i and j. */
2773 if (i > j) {
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002774 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002775 return 1;
2776 }
2777 if (i == 0 && j == 0) {
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002778 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002779 return 1;
2780 }
2781 if (i == 0)
2782 i = 1;
2783 if (j == 0)
2784 j = 1;
2785
2786 /* Pop the string. */
2787 lua_pop(L, 1);
2788
2789 /* Update the buffer length. */
2790 buf += i - 1;
2791 buf_len = j - i + 1;
2792 lua_pushlstring(L, buf, buf_len);
2793
2794 /* This unsigned is used to remember the amount of sent data. */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002795 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002796
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002797 return MAY_LJMP(hlua_socket_write_yield(L, 0, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002798}
2799
Willy Tarreau22b0a682015-06-17 19:43:49 +02002800#define SOCKET_INFO_MAX_LEN sizeof("[0000:0000:0000:0000:0000:0000:0000:0000]:12345")
Christopher Faulete6465b32021-10-22 15:36:08 +02002801__LJMP static inline int hlua_socket_info(struct lua_State *L, const struct sockaddr_storage *addr)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002802{
2803 static char buffer[SOCKET_INFO_MAX_LEN];
2804 int ret;
2805 int len;
2806 char *p;
2807
2808 ret = addr_to_str(addr, buffer+1, SOCKET_INFO_MAX_LEN-1);
2809 if (ret <= 0) {
2810 lua_pushnil(L);
2811 return 1;
2812 }
2813
2814 if (ret == AF_UNIX) {
2815 lua_pushstring(L, buffer+1);
2816 return 1;
2817 }
2818 else if (ret == AF_INET6) {
2819 buffer[0] = '[';
2820 len = strlen(buffer);
2821 buffer[len] = ']';
2822 len++;
2823 buffer[len] = ':';
2824 len++;
2825 p = buffer;
2826 }
2827 else if (ret == AF_INET) {
2828 p = buffer + 1;
2829 len = strlen(p);
2830 p[len] = ':';
2831 len++;
2832 }
2833 else {
2834 lua_pushnil(L);
2835 return 1;
2836 }
2837
2838 if (port_to_str(addr, p + len, SOCKET_INFO_MAX_LEN-1 - len) <= 0) {
2839 lua_pushnil(L);
2840 return 1;
2841 }
2842
2843 lua_pushstring(L, p);
2844 return 1;
2845}
2846
2847/* Returns information about the peer of the connection. */
2848__LJMP static int hlua_socket_getpeername(struct lua_State *L)
2849{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002850 struct hlua_socket *socket;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002851 struct xref *peer;
2852 struct appctx *appctx;
Willy Tarreau3e7be362022-05-27 10:35:27 +02002853 struct stconn *sc;
Christopher Faulet16f16af2021-10-27 09:34:56 +02002854 const struct sockaddr_storage *dst;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002855 int ret;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002856
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002857 MAY_LJMP(check_args(L, 1, "getpeername"));
2858
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002859 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002860
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002861 /* Check if we run on the same thread than the xreator thread.
2862 * We cannot access to the socket if the thread is different.
2863 */
2864 if (socket->tid != tid)
2865 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2866
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002867 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002868 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002869 if (!peer) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002870 lua_pushnil(L);
2871 return 1;
2872 }
Willy Tarreau5321da92022-05-06 11:57:34 +02002873
2874 appctx = container_of(peer, struct hlua_csk_ctx, xref)->appctx;
Willy Tarreauc12b3212022-05-27 11:08:15 +02002875 sc = appctx_sc(appctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02002876 dst = sc_dst(sc_opposite(sc));
Christopher Faulet16f16af2021-10-27 09:34:56 +02002877 if (!dst) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002878 xref_unlock(&socket->xref, peer);
Willy Tarreaua71f6422016-11-16 17:00:14 +01002879 lua_pushnil(L);
2880 return 1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002881 }
2882
Christopher Faulet16f16af2021-10-27 09:34:56 +02002883 ret = MAY_LJMP(hlua_socket_info(L, dst));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002884 xref_unlock(&socket->xref, peer);
2885 return ret;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002886}
2887
2888/* Returns information about my connection side. */
2889static int hlua_socket_getsockname(struct lua_State *L)
2890{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002891 struct hlua_socket *socket;
2892 struct connection *conn;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002893 struct appctx *appctx;
2894 struct xref *peer;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002895 struct stream *s;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002896 int ret;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002897
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002898 MAY_LJMP(check_args(L, 1, "getsockname"));
2899
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002900 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002901
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002902 /* Check if we run on the same thread than the xreator thread.
2903 * We cannot access to the socket if the thread is different.
2904 */
2905 if (socket->tid != tid)
2906 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2907
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002908 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002909 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002910 if (!peer) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002911 lua_pushnil(L);
2912 return 1;
2913 }
Willy Tarreau5321da92022-05-06 11:57:34 +02002914
2915 appctx = container_of(peer, struct hlua_csk_ctx, xref)->appctx;
Willy Tarreau0698c802022-05-11 14:09:57 +02002916 s = appctx_strm(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002917
Willy Tarreaufd9417b2022-05-18 16:23:22 +02002918 conn = sc_conn(s->scb);
Willy Tarreau5a0b25d2019-07-18 18:01:14 +02002919 if (!conn || !conn_get_src(conn)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002920 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002921 lua_pushnil(L);
2922 return 1;
2923 }
2924
Willy Tarreau9da9a6f2019-07-17 14:49:44 +02002925 ret = hlua_socket_info(L, conn->src);
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002926 xref_unlock(&socket->xref, peer);
2927 return ret;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002928}
2929
2930/* This struct define the applet. */
Willy Tarreau30576452015-04-13 13:50:30 +02002931static struct applet update_applet = {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002932 .obj_type = OBJ_TYPE_APPLET,
2933 .name = "<LUA_TCP>",
2934 .fct = hlua_socket_handler,
Christopher Faulet5f35a3e2022-05-12 15:31:05 +02002935 .init = hlua_socket_init,
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002936 .release = hlua_socket_release,
2937};
2938
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002939__LJMP static int hlua_socket_connect_yield(struct lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002940{
2941 struct hlua_socket *socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002942 struct hlua *hlua;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002943 struct xref *peer;
Willy Tarreau5321da92022-05-06 11:57:34 +02002944 struct hlua_csk_ctx *csk_ctx;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002945 struct appctx *appctx;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002946 struct stream *s;
2947
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002948 /* Get hlua struct, or NULL if we execute from main lua state */
2949 hlua = hlua_gethlua(L);
2950 if (!hlua)
2951 return 0;
2952
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002953 /* Check if we run on the same thread than the xreator thread.
2954 * We cannot access to the socket if the thread is different.
2955 */
2956 if (socket->tid != tid)
2957 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2958
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002959 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002960 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002961 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002962 lua_pushnil(L);
2963 lua_pushstring(L, "Can't connect");
2964 return 2;
2965 }
Willy Tarreau5321da92022-05-06 11:57:34 +02002966
2967 csk_ctx = container_of(peer, struct hlua_csk_ctx, xref);
2968 appctx = csk_ctx->appctx;
Willy Tarreau0698c802022-05-11 14:09:57 +02002969 s = appctx_strm(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002970
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002971 /* Check if we run on the same thread than the xreator thread.
2972 * We cannot access to the socket if the thread is different.
2973 */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002974 if (socket->tid != tid) {
2975 xref_unlock(&socket->xref, peer);
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002976 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002977 }
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002978
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002979 /* Check for connection close. */
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002980 if (!hlua || channel_output_closed(&s->req)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002981 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002982 lua_pushnil(L);
2983 lua_pushstring(L, "Can't connect");
2984 return 2;
2985 }
2986
Willy Tarreau8e7c6e62022-05-18 17:58:02 +02002987 appctx = __sc_appctx(s->scf);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002988
2989 /* Check for connection established. */
Willy Tarreau5321da92022-05-06 11:57:34 +02002990 if (csk_ctx->connected) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002991 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002992 lua_pushinteger(L, 1);
2993 return 1;
2994 }
2995
Willy Tarreau5321da92022-05-06 11:57:34 +02002996 if (!notification_new(&hlua->com, &csk_ctx->wake_on_write, hlua->task)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002997 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002998 WILL_LJMP(luaL_error(L, "out of memory error"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002999 }
3000 xref_unlock(&socket->xref, peer);
Willy Tarreau9635e032018-10-16 17:52:55 +02003001 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_connect_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003002 return 0;
3003}
3004
3005/* This function fail or initite the connection. */
3006__LJMP static int hlua_socket_connect(struct lua_State *L)
3007{
3008 struct hlua_socket *socket;
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02003009 int port = -1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003010 const char *ip;
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01003011 struct hlua *hlua;
Willy Tarreau5321da92022-05-06 11:57:34 +02003012 struct hlua_csk_ctx *csk_ctx;
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01003013 struct appctx *appctx;
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02003014 int low, high;
3015 struct sockaddr_storage *addr;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003016 struct xref *peer;
Willy Tarreau3e7be362022-05-27 10:35:27 +02003017 struct stconn *sc;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003018 struct stream *s;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003019
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02003020 if (lua_gettop(L) < 2)
3021 WILL_LJMP(luaL_error(L, "connect: need at least 2 arguments"));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003022
3023 /* Get args. */
3024 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02003025
3026 /* Check if we run on the same thread than the xreator thread.
3027 * We cannot access to the socket if the thread is different.
3028 */
3029 if (socket->tid != tid)
3030 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
3031
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003032 ip = MAY_LJMP(luaL_checkstring(L, 2));
Tim Duesterhus6edab862018-01-06 19:04:45 +01003033 if (lua_gettop(L) >= 3) {
3034 luaL_Buffer b;
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02003035 port = MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003036
Tim Duesterhus6edab862018-01-06 19:04:45 +01003037 /* Force the ip to end with a colon, to support IPv6 addresses
3038 * that are not enclosed within square brackets.
3039 */
3040 if (port > 0) {
3041 luaL_buffinit(L, &b);
3042 luaL_addstring(&b, ip);
3043 luaL_addchar(&b, ':');
3044 luaL_pushresult(&b);
3045 ip = lua_tolstring(L, lua_gettop(L), NULL);
3046 }
3047 }
3048
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003049 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02003050 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003051 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003052 lua_pushnil(L);
3053 return 1;
3054 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003055
3056 /* Parse ip address. */
Willy Tarreau5fc93282020-09-16 18:25:03 +02003057 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 +02003058 if (!addr) {
3059 xref_unlock(&socket->xref, peer);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02003060 WILL_LJMP(luaL_error(L, "connect: cannot parse destination address '%s'", ip));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02003061 }
Willy Tarreau9da9a6f2019-07-17 14:49:44 +02003062
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003063 /* Set port. */
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02003064 if (low == 0) {
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02003065 if (addr->ss_family == AF_INET) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02003066 if (port == -1) {
3067 xref_unlock(&socket->xref, peer);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02003068 WILL_LJMP(luaL_error(L, "connect: port missing"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02003069 }
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02003070 ((struct sockaddr_in *)addr)->sin_port = htons(port);
3071 } else if (addr->ss_family == AF_INET6) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02003072 if (port == -1) {
3073 xref_unlock(&socket->xref, peer);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02003074 WILL_LJMP(luaL_error(L, "connect: port missing"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02003075 }
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02003076 ((struct sockaddr_in6 *)addr)->sin6_port = htons(port);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02003077 }
3078 }
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02003079
Willy Tarreau5321da92022-05-06 11:57:34 +02003080 csk_ctx = container_of(peer, struct hlua_csk_ctx, xref);
3081 appctx = csk_ctx->appctx;
Willy Tarreauc12b3212022-05-27 11:08:15 +02003082 sc = appctx_sc(appctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02003083 s = __sc_strm(sc);
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02003084
Willy Tarreau3e7be362022-05-27 10:35:27 +02003085 if (!sockaddr_alloc(&sc_opposite(sc)->dst, addr, sizeof(*addr))) {
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02003086 xref_unlock(&socket->xref, peer);
3087 WILL_LJMP(luaL_error(L, "connect: internal error"));
3088 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003089
Thierry Fournier4234dbd2020-11-28 13:18:23 +01003090 /* Get hlua struct, or NULL if we execute from main lua state */
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01003091 hlua = hlua_gethlua(L);
Thierry Fournier4234dbd2020-11-28 13:18:23 +01003092 if (!hlua)
3093 return 0;
Willy Tarreaubdc97a82015-08-24 15:42:28 +02003094
3095 /* inform the stream that we want to be notified whenever the
3096 * connection completes.
3097 */
Willy Tarreau90e8b452022-05-25 18:21:43 +02003098 applet_need_more_data(appctx);
Willy Tarreau4164eb92022-05-25 15:42:03 +02003099 applet_have_more_data(appctx);
Thierry FOURNIER8c8fbbe2015-09-26 17:02:35 +02003100 appctx_wakeup(appctx);
Willy Tarreaubdc97a82015-08-24 15:42:28 +02003101
Willy Tarreauf31af932020-01-14 09:59:38 +01003102 hlua->gc_count++;
Thierry FOURNIER7c39ab42015-09-27 22:53:33 +02003103
Willy Tarreau5321da92022-05-06 11:57:34 +02003104 if (!notification_new(&hlua->com, &csk_ctx->wake_on_write, hlua->task)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02003105 xref_unlock(&socket->xref, peer);
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01003106 WILL_LJMP(luaL_error(L, "out of memory"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02003107 }
3108 xref_unlock(&socket->xref, peer);
PiBa-NL706d5ee2018-05-05 23:51:42 +02003109
3110 task_wakeup(s->task, TASK_WOKEN_INIT);
3111 /* Return yield waiting for connection. */
3112
Willy Tarreau9635e032018-10-16 17:52:55 +02003113 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_connect_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003114
3115 return 0;
3116}
3117
Baptiste Assmann84bb4932015-03-02 21:40:06 +01003118#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003119__LJMP static int hlua_socket_connect_ssl(struct lua_State *L)
3120{
3121 struct hlua_socket *socket;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003122 struct xref *peer;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003123 struct stream *s;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003124
3125 MAY_LJMP(check_args(L, 3, "connect_ssl"));
3126 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003127
3128 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02003129 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003130 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003131 lua_pushnil(L);
3132 return 1;
3133 }
Willy Tarreau5321da92022-05-06 11:57:34 +02003134
Willy Tarreau0698c802022-05-11 14:09:57 +02003135 s = appctx_strm(container_of(peer, struct hlua_csk_ctx, xref)->appctx);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003136
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +01003137 s->target = &socket_ssl->obj_type;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02003138 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003139 return MAY_LJMP(hlua_socket_connect(L));
3140}
Baptiste Assmann84bb4932015-03-02 21:40:06 +01003141#endif
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003142
3143__LJMP static int hlua_socket_setoption(struct lua_State *L)
3144{
3145 return 0;
3146}
3147
3148__LJMP static int hlua_socket_settimeout(struct lua_State *L)
3149{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003150 struct hlua_socket *socket;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003151 int tmout;
Mark Lakes56cc1252018-03-27 09:48:06 +02003152 double dtmout;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003153 struct xref *peer;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003154 struct stream *s;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003155
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003156 MAY_LJMP(check_args(L, 2, "settimeout"));
3157
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003158 socket = MAY_LJMP(hlua_checksocket(L, 1));
Mark Lakes56cc1252018-03-27 09:48:06 +02003159
Cyril Bonté7ee465f2018-08-19 22:08:50 +02003160 /* convert the timeout to millis */
3161 dtmout = MAY_LJMP(luaL_checknumber(L, 2)) * 1000;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003162
Thierry Fournier17a921b2018-03-08 09:59:02 +01003163 /* Check for negative values */
Mark Lakes56cc1252018-03-27 09:48:06 +02003164 if (dtmout < 0)
Thierry Fournier17a921b2018-03-08 09:59:02 +01003165 WILL_LJMP(luaL_error(L, "settimeout: cannot set negatives values"));
3166
Mark Lakes56cc1252018-03-27 09:48:06 +02003167 if (dtmout > INT_MAX) /* overflow check */
Cyril Bonté7ee465f2018-08-19 22:08:50 +02003168 WILL_LJMP(luaL_error(L, "settimeout: cannot set values larger than %d ms", INT_MAX));
Mark Lakes56cc1252018-03-27 09:48:06 +02003169
3170 tmout = MS_TO_TICKS((int)dtmout);
Cyril Bonté7ee465f2018-08-19 22:08:50 +02003171 if (tmout == 0)
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05003172 tmout++; /* very small timeouts are adjusted to a minimum of 1ms */
Mark Lakes56cc1252018-03-27 09:48:06 +02003173
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02003174 /* Check if we run on the same thread than the xreator thread.
3175 * We cannot access to the socket if the thread is different.
3176 */
3177 if (socket->tid != tid)
3178 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
3179
Mark Lakes56cc1252018-03-27 09:48:06 +02003180 /* check for connection break. If some data were read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02003181 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003182 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003183 hlua_pusherror(L, "socket: not yet initialised, you can't set timeouts.");
3184 WILL_LJMP(lua_error(L));
3185 return 0;
3186 }
Willy Tarreau5321da92022-05-06 11:57:34 +02003187
Willy Tarreau0698c802022-05-11 14:09:57 +02003188 s = appctx_strm(container_of(peer, struct hlua_csk_ctx, xref)->appctx);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003189
Cyril Bonté7bb63452018-08-17 23:51:02 +02003190 s->sess->fe->timeout.connect = tmout;
Christopher Faulet5aaacfb2023-02-15 08:13:33 +01003191 s->scf->ioto = tmout;
3192 s->scb->ioto = tmout;
Cyril Bonté7bb63452018-08-17 23:51:02 +02003193
3194 s->task->expire = tick_add_ifset(now_ms, tmout);
3195 task_queue(s->task);
3196
Thierry FOURNIER952939d2017-09-01 14:17:32 +02003197 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003198
Thierry Fourniere9636f12018-03-08 09:54:32 +01003199 lua_pushinteger(L, 1);
Tim Duesterhus119a5f12018-01-06 19:16:25 +01003200 return 1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003201}
3202
3203__LJMP static int hlua_socket_new(lua_State *L)
3204{
3205 struct hlua_socket *socket;
Willy Tarreau5321da92022-05-06 11:57:34 +02003206 struct hlua_csk_ctx *ctx;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003207 struct appctx *appctx;
3208
3209 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003210 if (!lua_checkstack(L, 3)) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003211 hlua_pusherror(L, "socket: full stack");
3212 goto out_fail_conf;
3213 }
3214
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003215 /* Create the object: obj[0] = userdata. */
3216 lua_newtable(L);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003217 socket = MAY_LJMP(lua_newuserdata(L, sizeof(*socket)));
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003218 lua_rawseti(L, -2, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003219 memset(socket, 0, sizeof(*socket));
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02003220 socket->tid = tid;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003221
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05003222 /* Check if the various memory pools are initialized. */
Willy Tarreaubafbe012017-11-24 17:34:44 +01003223 if (!pool_head_stream || !pool_head_buffer) {
Thierry FOURNIER4a6170c2015-03-09 17:07:10 +01003224 hlua_pusherror(L, "socket: uninitialized pools.");
3225 goto out_fail_conf;
3226 }
3227
Willy Tarreau87b09662015-04-03 00:22:06 +02003228 /* Pop a class stream metatable and affect it to the userdata. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003229 lua_rawgeti(L, LUA_REGISTRYINDEX, class_socket_ref);
3230 lua_setmetatable(L, -2);
3231
Willy Tarreaud420a972015-04-06 00:39:18 +02003232 /* Create the applet context */
Christopher Faulet6095d572022-05-16 17:09:48 +02003233 appctx = appctx_new_here(&update_applet, NULL);
Willy Tarreau61cf7c82015-04-06 00:48:33 +02003234 if (!appctx) {
3235 hlua_pusherror(L, "socket: out of memory");
Christopher Fauleta9e8b392022-03-23 11:01:09 +01003236 goto out_fail_conf;
Willy Tarreau61cf7c82015-04-06 00:48:33 +02003237 }
Willy Tarreau5321da92022-05-06 11:57:34 +02003238 ctx = applet_reserve_svcctx(appctx, sizeof(*ctx));
3239 ctx->connected = 0;
Willy Tarreau5321da92022-05-06 11:57:34 +02003240 ctx->die = 0;
3241 LIST_INIT(&ctx->wake_on_write);
3242 LIST_INIT(&ctx->wake_on_read);
Willy Tarreaub2bf8332015-04-04 15:58:58 +02003243
Christopher Faulet5f35a3e2022-05-12 15:31:05 +02003244 if (appctx_init(appctx) == -1) {
3245 hlua_pusherror(L, "socket: fail to init applet.");
Christopher Faulet13a35e52021-12-20 15:34:16 +01003246 goto out_fail_appctx;
3247 }
3248
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003249 /* Initialise cross reference between stream and Lua socket object. */
Willy Tarreau5321da92022-05-06 11:57:34 +02003250 xref_create(&socket->xref, &ctx->xref);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003251 return 1;
3252
Christopher Faulet13a35e52021-12-20 15:34:16 +01003253 out_fail_appctx:
Christopher Faulet5f35a3e2022-05-12 15:31:05 +02003254 appctx_free_on_early_error(appctx);
Willy Tarreaud420a972015-04-06 00:39:18 +02003255 out_fail_conf:
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003256 WILL_LJMP(lua_error(L));
3257 return 0;
3258}
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01003259
3260/*
3261 *
3262 *
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003263 * Class Channel
3264 *
3265 *
3266 */
3267
3268/* Returns the struct hlua_channel join to the class channel in the
3269 * stack entry "ud" or throws an argument error.
3270 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01003271__LJMP static struct channel *hlua_checkchannel(lua_State *L, int ud)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003272{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003273 return MAY_LJMP(hlua_checkudata(L, ud, class_channel_ref));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003274}
3275
Willy Tarreau47860ed2015-03-10 14:07:50 +01003276/* Pushes the channel onto the top of the stack. If the stask does not have a
3277 * free slots, the function fails and returns 0;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003278 */
Willy Tarreau2a71af42015-03-10 13:51:50 +01003279static int hlua_channel_new(lua_State *L, struct channel *channel)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003280{
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003281 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003282 if (!lua_checkstack(L, 3))
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003283 return 0;
3284
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003285 lua_newtable(L);
Willy Tarreau47860ed2015-03-10 14:07:50 +01003286 lua_pushlightuserdata(L, channel);
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003287 lua_rawseti(L, -2, 0);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003288
3289 /* Pop a class sesison metatable and affect it to the userdata. */
3290 lua_rawgeti(L, LUA_REGISTRYINDEX, class_channel_ref);
3291 lua_setmetatable(L, -2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003292 return 1;
3293}
3294
Christopher Faulet9f55a502020-02-25 15:21:02 +01003295/* Helper function returning a filter attached to a channel at the position <ud>
3296 * in the stack, filling the current offset and length of the filter. If no
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05003297 * filter is attached, NULL is returned and <offset> and <len> are not
Christopher Faulet9f55a502020-02-25 15:21:02 +01003298 * initialized.
3299 */
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003300static 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 +01003301{
3302 struct filter *filter = NULL;
3303
3304 if (lua_getfield(L, ud, "__filter") == LUA_TLIGHTUSERDATA) {
3305 struct hlua_flt_ctx *flt_ctx;
3306
3307 filter = lua_touserdata (L, -1);
3308 flt_ctx = filter->ctx;
3309 if (hlua_filter_from_payload(filter)) {
3310 *offset = flt_ctx->cur_off[CHN_IDX(chn)];
3311 *len = flt_ctx->cur_len[CHN_IDX(chn)];
3312 }
3313 }
3314
3315 lua_pop(L, 1);
3316 return filter;
3317}
3318
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003319/* Copies <len> bytes of data present in the channel's buffer, starting at the
3320* offset <offset>, and put it in a LUA string variable. It is the caller
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003321* responsibility to ensure <len> and <offset> are valid. It always return the
3322* length of the built string. <len> may be 0, in this case, an empty string is
3323* created and 0 is returned.
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003324*/
3325static inline int _hlua_channel_dup(struct channel *chn, lua_State *L, size_t offset, size_t len)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003326{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003327 size_t block1, block2;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003328 luaL_Buffer b;
3329
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003330 block1 = len;
3331 if (block1 > b_contig_data(&chn->buf, b_peek_ofs(&chn->buf, offset)))
3332 block1 = b_contig_data(&chn->buf, b_peek_ofs(&chn->buf, offset));
3333 block2 = len - block1;
3334
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003335 luaL_buffinit(L, &b);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003336 luaL_addlstring(&b, b_peek(&chn->buf, offset), block1);
3337 if (block2)
3338 luaL_addlstring(&b, b_orig(&chn->buf), block2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003339 luaL_pushresult(&b);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003340 return len;
3341}
3342
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003343/* Inserts the string <str> to the channel's buffer at the offset <offset>. This
3344 * function returns -1 if data cannot be copied. Otherwise, it returns the
3345 * number of bytes copied.
3346 */
3347static int _hlua_channel_insert(struct channel *chn, lua_State *L, struct ist str, size_t offset)
3348{
3349 int ret = 0;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003350
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003351 /* Nothing to do, just return */
3352 if (unlikely(istlen(str) == 0))
3353 goto end;
3354
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003355 if (istlen(str) > c_room(chn)) {
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003356 ret = -1;
3357 goto end;
3358 }
3359 ret = b_insert_blk(&chn->buf, offset, istptr(str), istlen(str));
3360
3361 end:
3362 return ret;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003363}
3364
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003365/* Removes <len> bytes of data at the absolute position <offset>.
3366 */
3367static void _hlua_channel_delete(struct channel *chn, size_t offset, size_t len)
3368{
3369 size_t end = offset + len;
3370
3371 if (b_peek(&chn->buf, end) != b_tail(&chn->buf))
3372 b_move(&chn->buf, b_peek_ofs(&chn->buf, end),
3373 b_data(&chn->buf) - end, -len);
3374 b_sub(&chn->buf, len);
3375}
3376
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003377/* Copies input data in the channel's buffer. It is possible to set a specific
3378 * offset (0 by default) and a length (all remaining input data starting for the
3379 * offset by default). If there is not enough input data and more data can be
3380 * received, this function yields.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003381 *
3382 * From an action, All input data are considered. For a filter, the offset and
3383 * the length of input data to consider are retrieved from the filter context.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003384 */
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003385__LJMP static int hlua_channel_get_data_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003386{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003387 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003388 struct filter *filter;
3389 size_t input, output;
3390 int offset, len;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003391
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003392 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003393
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003394 output = co_data(chn);
3395 input = ci_data(chn);
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003396
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003397 filter = hlua_channel_filter(L, 1, chn, &output, &input);
3398 if (filter && !hlua_filter_from_payload(filter))
3399 WILL_LJMP(lua_error(L));
3400
3401 offset = output;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003402 if (lua_gettop(L) > 1) {
3403 offset = MAY_LJMP(luaL_checkinteger(L, 2));
3404 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02003405 offset = MAX(0, (int)input + offset);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003406 offset += output;
3407 if (offset < output || offset > input + output) {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003408 lua_pushfstring(L, "offset out of range.");
3409 WILL_LJMP(lua_error(L));
3410 }
3411 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003412 len = output + input - offset;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003413 if (lua_gettop(L) == 3) {
3414 len = MAY_LJMP(luaL_checkinteger(L, 3));
3415 if (!len)
3416 goto dup;
3417 if (len == -1)
3418 len = global.tune.bufsize;
3419 if (len < 0) {
3420 lua_pushfstring(L, "length out of range.");
3421 WILL_LJMP(lua_error(L));
3422 }
3423 }
3424
Christopher Faulet0ae2e632023-01-10 15:29:54 +01003425 /* Wait for more data if possible if no length was specified and there
3426 * is no data or not enough data was received.
3427 */
3428 if (!len || offset + len > output + input) {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003429 if (!HLUA_CANT_YIELD(hlua_gethlua(L)) && !channel_input_closed(chn) && channel_may_recv(chn)) {
3430 /* Yield waiting for more data, as requested */
3431 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_get_data_yield, TICK_ETERNITY, 0));
3432 }
Christopher Faulet0ae2e632023-01-10 15:29:54 +01003433
3434 /* Return 'nil' if there is no data and the channel can't receive more data */
3435 if (!len) {
3436 lua_pushnil(L);
3437 return -1;
3438 }
3439
3440 /* Otherwise, return all data */
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003441 len = output + input - offset;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003442 }
3443
3444 dup:
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003445 _hlua_channel_dup(chn, L, offset, len);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003446 return 1;
3447}
3448
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003449/* Copies the first line (including the trailing LF) of input data in the
3450 * channel's buffer. It is possible to set a specific offset (0 by default) and
3451 * a length (all remaining input data starting for the offset by default). If
3452 * there is not enough input data and more data can be received, the function
3453 * yields. If a length is explicitly specified, no more data are
3454 * copied. Otherwise, if no LF is found and more data can be received, this
3455 * function yields.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003456 *
3457 * From an action, All input data are considered. For a filter, the offset and
3458 * the length of input data to consider are retrieved from the filter context.
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003459 */
3460__LJMP static int hlua_channel_get_line_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003461{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003462 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003463 struct filter *filter;
3464 size_t l, input, output;
3465 int offset, len;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003466
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003467 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003468 output = co_data(chn);
3469 input = ci_data(chn);
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003470
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003471 filter = hlua_channel_filter(L, 1, chn, &output, &input);
3472 if (filter && !hlua_filter_from_payload(filter))
3473 WILL_LJMP(lua_error(L));
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003474
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003475 offset = output;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003476 if (lua_gettop(L) > 1) {
3477 offset = MAY_LJMP(luaL_checkinteger(L, 2));
3478 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02003479 offset = MAX(0, (int)input + offset);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003480 offset += output;
3481 if (offset < output || offset > input + output) {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003482 lua_pushfstring(L, "offset out of range.");
3483 WILL_LJMP(lua_error(L));
3484 }
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003485 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003486
3487 len = output + input - offset;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003488 if (lua_gettop(L) == 3) {
3489 len = MAY_LJMP(luaL_checkinteger(L, 3));
3490 if (!len)
3491 goto dup;
3492 if (len == -1)
3493 len = global.tune.bufsize;
3494 if (len < 0) {
3495 lua_pushfstring(L, "length out of range.");
3496 WILL_LJMP(lua_error(L));
3497 }
3498 }
3499
3500 for (l = 0; l < len; l++) {
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003501 if (l + offset >= output + input)
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003502 break;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003503 if (*(b_peek(&chn->buf, offset + l)) == '\n') {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003504 len = l+1;
3505 goto dup;
3506 }
3507 }
3508
Christopher Faulet0ae2e632023-01-10 15:29:54 +01003509 /* Wait for more data if possible if no line is found and no length was
3510 * specified or not enough data was received.
3511 */
3512 if (lua_gettop(L) != 3 || offset + len > output + input) {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003513 if (!HLUA_CANT_YIELD(hlua_gethlua(L)) && !channel_input_closed(chn) && channel_may_recv(chn)) {
3514 /* Yield waiting for more data */
3515 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_get_line_yield, TICK_ETERNITY, 0));
3516 }
Christopher Faulet0ae2e632023-01-10 15:29:54 +01003517
3518 /* Return 'nil' if there is no data and the channel can't receive more data */
3519 if (!len) {
3520 lua_pushnil(L);
3521 return -1;
3522 }
3523
3524 /* Otherwise, return all data */
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003525 len = output + input - offset;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003526 }
3527
3528 dup:
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003529 _hlua_channel_dup(chn, L, offset, len);
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003530 return 1;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003531}
3532
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003533/* [ DEPRECATED ]
3534 *
3535 * Duplicate all input data foud in the channel's buffer. The data are not
3536 * removed from the buffer. This function relies on _hlua_channel_dup().
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003537 *
3538 * From an action, All input data are considered. For a filter, the offset and
3539 * the length of input data to consider are retrieved from the filter context.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003540 */
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003541__LJMP static int hlua_channel_dup(lua_State *L)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003542{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003543 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003544 struct filter *filter;
3545 size_t offset, len;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003546
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003547 MAY_LJMP(check_args(L, 1, "dup"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003548 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003549 if (IS_HTX_STRM(chn_strm(chn))) {
3550 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3551 WILL_LJMP(lua_error(L));
3552 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003553
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003554 offset = co_data(chn);
3555 len = ci_data(chn);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003556
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003557 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3558 if (filter && !hlua_filter_from_payload(filter))
3559 WILL_LJMP(lua_error(L));
3560
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003561 if (!ci_data(chn) && channel_input_closed(chn)) {
3562 lua_pushnil(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003563 return 1;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003564 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003565
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003566 _hlua_channel_dup(chn, L, offset, len);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003567 return 1;
3568}
3569
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003570/* [ DEPRECATED ]
3571 *
3572 * Get all input data foud in the channel's buffer. The data are removed from
3573 * the buffer after the copy. This function relies on _hlua_channel_dup() and
3574 * _hlua_channel_delete().
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003575 *
3576 * From an action, All input data are considered. For a filter, the offset and
3577 * the length of input data to consider are retrieved from the filter context.
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003578 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003579__LJMP static int hlua_channel_get(lua_State *L)
3580{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003581 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003582 struct filter *filter;
3583 size_t offset, len;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003584 int ret;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003585
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003586 MAY_LJMP(check_args(L, 1, "get"));
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003587 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3588 if (IS_HTX_STRM(chn_strm(chn))) {
3589 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3590 WILL_LJMP(lua_error(L));
3591 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003592
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003593 offset = co_data(chn);
3594 len = ci_data(chn);
3595
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003596 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3597 if (filter && !hlua_filter_from_payload(filter))
3598 WILL_LJMP(lua_error(L));
3599
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003600 if (!ci_data(chn) && channel_input_closed(chn)) {
3601 lua_pushnil(L);
3602 return 1;
3603 }
3604
3605 ret = _hlua_channel_dup(chn, L, offset, len);
3606 _hlua_channel_delete(chn, offset, ret);
3607 return 1;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003608}
3609
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003610/* This functions consumes and returns one line. If the channel is closed,
3611 * and the last data does not contains a final '\n', the data are returned
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003612 * without the final '\n'. When no more data are available, it returns nil
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003613 * value.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003614 *
3615 * From an action, All input data are considered. For a filter, the offset and
3616 * the length of input data to consider are retrieved from the filter context.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003617 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003618__LJMP static int hlua_channel_getline_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003619{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003620 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003621 struct filter *filter;
3622 size_t l, offset, len;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003623 int ret;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003624
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003625 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003626
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003627 offset = co_data(chn);
3628 len = ci_data(chn);
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003629
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003630 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3631 if (filter && !hlua_filter_from_payload(filter))
3632 WILL_LJMP(lua_error(L));
3633
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003634 if (!ci_data(chn) && channel_input_closed(chn)) {
3635 lua_pushnil(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003636 return 1;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003637 }
3638
3639 for (l = 0; l < len; l++) {
3640 if (*(b_peek(&chn->buf, offset+l)) == '\n') {
3641 len = l+1;
3642 goto dup;
3643 }
3644 }
3645
3646 if (!HLUA_CANT_YIELD(hlua_gethlua(L)) && !channel_input_closed(chn) && channel_may_recv(chn)) {
3647 /* Yield waiting for more data */
3648 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_getline_yield, TICK_ETERNITY, 0));
3649 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003650
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003651 dup:
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003652 ret = _hlua_channel_dup(chn, L, offset, len);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003653 _hlua_channel_delete(chn, offset, ret);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003654 return 1;
3655}
3656
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003657/* [ DEPRECATED ]
3658 *
3659 * Check arguments for the function "hlua_channel_getline_yield".
3660 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003661__LJMP static int hlua_channel_getline(lua_State *L)
3662{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003663 struct channel *chn;
3664
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003665 MAY_LJMP(check_args(L, 1, "getline"));
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003666 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3667 if (IS_HTX_STRM(chn_strm(chn))) {
3668 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3669 WILL_LJMP(lua_error(L));
3670 }
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003671 return MAY_LJMP(hlua_channel_getline_yield(L, 0, 0));
3672}
3673
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003674/* Retrieves a given amount of input data at the given offset. By default all
3675 * available input data are returned. The offset may be negactive to start from
3676 * the end of input data. The length may be -1 to set it to the maximum buffer
3677 * size.
3678 */
3679__LJMP static int hlua_channel_get_data(lua_State *L)
3680{
3681 struct channel *chn;
3682
3683 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
3684 WILL_LJMP(luaL_error(L, "'data' expects at most 2 arguments"));
3685 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3686 if (IS_HTX_STRM(chn_strm(chn))) {
3687 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3688 WILL_LJMP(lua_error(L));
3689 }
3690 return MAY_LJMP(hlua_channel_get_data_yield(L, 0, 0));
3691}
3692
3693/* Retrieves a given amount of input data at the given offset. By default all
3694 * available input data are returned. The offset may be negactive to start from
3695 * the end of input data. The length may be -1 to set it to the maximum buffer
3696 * size.
3697 */
3698__LJMP static int hlua_channel_get_line(lua_State *L)
3699{
3700 struct channel *chn;
3701
3702 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
3703 WILL_LJMP(luaL_error(L, "'line' expects at most 2 arguments"));
3704 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3705 if (IS_HTX_STRM(chn_strm(chn))) {
3706 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3707 WILL_LJMP(lua_error(L));
3708 }
3709 return MAY_LJMP(hlua_channel_get_line_yield(L, 0, 0));
3710}
3711
3712/* Appends a string into the input side of channel. It returns the length of the
3713 * written string, or -1 if the channel is closed or if the buffer size is too
3714 * little for the data. 0 may be returned if nothing is copied. This function
3715 * does not yield.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003716 *
3717 * For a filter, the context is updated on success.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003718 */
Christopher Faulet23976d92021-08-06 09:59:49 +02003719__LJMP static int hlua_channel_append(lua_State *L)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003720{
Christopher Faulet23976d92021-08-06 09:59:49 +02003721 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003722 struct filter *filter;
Christopher Faulet23976d92021-08-06 09:59:49 +02003723 const char *str;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003724 size_t sz, offset, len;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003725 int ret;
Christopher Faulet23976d92021-08-06 09:59:49 +02003726
3727 MAY_LJMP(check_args(L, 2, "append"));
3728 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003729 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
Christopher Faulet1bb6afa2021-03-08 17:57:53 +01003730 if (IS_HTX_STRM(chn_strm(chn))) {
Thierry Fournier77016da2020-08-15 14:35:51 +02003731 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
Christopher Faulet3f829a42018-12-13 21:56:45 +01003732 WILL_LJMP(lua_error(L));
Thierry Fournier77016da2020-08-15 14:35:51 +02003733 }
Christopher Faulet3f829a42018-12-13 21:56:45 +01003734
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003735 offset = co_data(chn);
3736 len = ci_data(chn);
3737
3738 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3739 if (filter && !hlua_filter_from_payload(filter))
3740 WILL_LJMP(lua_error(L));
3741
3742 ret = _hlua_channel_insert(chn, L, ist2(str, sz), offset);
3743 if (ret > 0 && filter) {
3744 struct hlua_flt_ctx *flt_ctx = filter->ctx;
3745
3746 flt_update_offsets(filter, chn, ret);
3747 flt_ctx->cur_len[CHN_IDX(chn)] += ret;
3748 }
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003749 lua_pushinteger(L, ret);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003750 return 1;
3751}
3752
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003753/* Prepends a string into the input side of channel. It returns the length of the
3754 * written string, or -1 if the channel is closed or if the buffer size is too
3755 * little for the data. 0 may be returned if nothing is copied. This function
3756 * does not yield.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003757 *
3758 * For a filter, the context is updated on success.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003759 */
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003760__LJMP static int hlua_channel_prepend(lua_State *L)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003761{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003762 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003763 struct filter *filter;
Christopher Faulet23976d92021-08-06 09:59:49 +02003764 const char *str;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003765 size_t sz, offset, len;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003766 int ret;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003767
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003768 MAY_LJMP(check_args(L, 2, "prepend"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003769 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003770 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
3771 if (IS_HTX_STRM(chn_strm(chn))) {
3772 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3773 WILL_LJMP(lua_error(L));
3774 }
3775
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003776 offset = co_data(chn);
3777 len = ci_data(chn);
3778
3779 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3780 if (filter && !hlua_filter_from_payload(filter))
3781 WILL_LJMP(lua_error(L));
3782
3783 ret = _hlua_channel_insert(chn, L, ist2(str, sz), offset);
3784 if (ret > 0 && filter) {
3785 struct hlua_flt_ctx *flt_ctx = filter->ctx;
3786
3787 flt_update_offsets(filter, chn, ret);
3788 flt_ctx->cur_len[CHN_IDX(chn)] += ret;
3789 }
3790
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003791 lua_pushinteger(L, ret);
3792 return 1;
3793}
3794
3795/* Inserts a given amount of input data at the given offset by a string
Aurelien DARRAGONafb7daf2022-10-04 12:16:05 +02003796 * content. By default the string is appended in front of input data. It
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003797 * returns the length of the written string, or -1 if the channel is closed or
3798 * if the buffer size is too little for the data.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003799 *
3800 * For a filter, the context is updated on success.
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003801 */
3802__LJMP static int hlua_channel_insert_data(lua_State *L)
3803{
3804 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003805 struct filter *filter;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003806 const char *str;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003807 size_t sz, input, output;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003808 int ret, offset;
3809
3810 if (lua_gettop(L) < 2 || lua_gettop(L) > 3)
3811 WILL_LJMP(luaL_error(L, "'insert' expects at least 1 argument and at most 2 arguments"));
3812 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3813 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003814
3815 output = co_data(chn);
3816 input = ci_data(chn);
3817
3818 filter = hlua_channel_filter(L, 1, chn, &output, &input);
3819 if (filter && !hlua_filter_from_payload(filter))
3820 WILL_LJMP(lua_error(L));
3821
Aurelien DARRAGONafb7daf2022-10-04 12:16:05 +02003822 offset = output;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003823 if (lua_gettop(L) > 2) {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003824 offset = MAY_LJMP(luaL_checkinteger(L, 3));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003825 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02003826 offset = MAX(0, (int)input + offset);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003827 offset += output;
Aurelien DARRAGONafb7daf2022-10-04 12:16:05 +02003828 if (offset > output + input) {
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003829 lua_pushfstring(L, "offset out of range.");
3830 WILL_LJMP(lua_error(L));
3831 }
3832 }
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003833 if (IS_HTX_STRM(chn_strm(chn))) {
3834 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3835 WILL_LJMP(lua_error(L));
3836 }
3837
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003838 ret = _hlua_channel_insert(chn, L, ist2(str, sz), offset);
3839 if (ret > 0 && filter) {
3840 struct hlua_flt_ctx *flt_ctx = filter->ctx;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003841
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003842 flt_update_offsets(filter, chn, ret);
3843 flt_ctx->cur_len[CHN_IDX(chn)] += ret;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003844 }
3845
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003846 lua_pushinteger(L, ret);
3847 return 1;
3848}
3849/* Replaces a given amount of input data at the given offset by a string
3850 * content. By default all remaining data are removed (offset = 0 and len =
3851 * -1). It returns the length of the written string, or -1 if the channel is
3852 * closed or if the buffer size is too little for the data.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003853 *
3854 * For a filter, the context is updated on success.
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003855 */
3856__LJMP static int hlua_channel_set_data(lua_State *L)
3857{
3858 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003859 struct filter *filter;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003860 const char *str;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003861 size_t sz, input, output;
3862 int ret, offset, len;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003863
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003864 if (lua_gettop(L) < 2 || lua_gettop(L) > 4)
3865 WILL_LJMP(luaL_error(L, "'set' expects at least 1 argument and at most 3 arguments"));
3866 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3867 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003868
Christopher Faulet1bb6afa2021-03-08 17:57:53 +01003869 if (IS_HTX_STRM(chn_strm(chn))) {
Thierry Fournier77016da2020-08-15 14:35:51 +02003870 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
Christopher Faulet3f829a42018-12-13 21:56:45 +01003871 WILL_LJMP(lua_error(L));
Thierry Fournier77016da2020-08-15 14:35:51 +02003872 }
Christopher Faulet3f829a42018-12-13 21:56:45 +01003873
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003874 output = co_data(chn);
3875 input = ci_data(chn);
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003876
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003877 filter = hlua_channel_filter(L, 1, chn, &output, &input);
3878 if (filter && !hlua_filter_from_payload(filter))
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003879 WILL_LJMP(lua_error(L));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003880
3881 offset = output;
3882 if (lua_gettop(L) > 2) {
3883 offset = MAY_LJMP(luaL_checkinteger(L, 3));
3884 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02003885 offset = MAX(0, (int)input + offset);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003886 offset += output;
3887 if (offset < output || offset > input + output) {
3888 lua_pushfstring(L, "offset out of range.");
3889 WILL_LJMP(lua_error(L));
3890 }
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003891 }
3892
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003893 len = output + input - offset;
3894 if (lua_gettop(L) == 4) {
3895 len = MAY_LJMP(luaL_checkinteger(L, 4));
3896 if (!len)
3897 goto set;
3898 if (len == -1)
3899 len = output + input - offset;
3900 if (len < 0 || offset + len > output + input) {
3901 lua_pushfstring(L, "length out of range.");
3902 WILL_LJMP(lua_error(L));
3903 }
3904 }
3905
3906 set:
Christopher Faulet23976d92021-08-06 09:59:49 +02003907 /* Be sure we can copied the string once input data will be removed. */
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003908 if (sz > c_room(chn) + len)
Christopher Faulet23976d92021-08-06 09:59:49 +02003909 lua_pushinteger(L, -1);
3910 else {
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003911 _hlua_channel_delete(chn, offset, len);
3912 ret = _hlua_channel_insert(chn, L, ist2(str, sz), offset);
3913 if (filter) {
3914 struct hlua_flt_ctx *flt_ctx = filter->ctx;
3915
3916 len -= (ret > 0 ? ret : 0);
3917 flt_update_offsets(filter, chn, -len);
3918 flt_ctx->cur_len[CHN_IDX(chn)] -= len;
3919 }
3920
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003921 lua_pushinteger(L, ret);
Christopher Faulet23976d92021-08-06 09:59:49 +02003922 }
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003923 return 1;
3924}
3925
3926/* Removes a given amount of input data at the given offset. By default all
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003927 * input data are removed (offset = 0 and len = -1). It returns the amount of
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003928 * the removed data.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003929 *
3930 * For a filter, the context is updated on success.
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003931 */
3932__LJMP static int hlua_channel_del_data(lua_State *L)
3933{
3934 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003935 struct filter *filter;
3936 size_t input, output;
3937 int offset, len;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003938
3939 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
3940 WILL_LJMP(luaL_error(L, "'remove' expects at most 2 arguments"));
3941 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003942
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003943 if (IS_HTX_STRM(chn_strm(chn))) {
3944 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3945 WILL_LJMP(lua_error(L));
3946 }
3947
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003948 output = co_data(chn);
3949 input = ci_data(chn);
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003950
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003951 filter = hlua_channel_filter(L, 1, chn, &output, &input);
3952 if (filter && !hlua_filter_from_payload(filter))
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003953 WILL_LJMP(lua_error(L));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003954
3955 offset = output;
Boyang Lie0c54352022-05-10 17:47:23 +00003956 if (lua_gettop(L) > 1) {
3957 offset = MAY_LJMP(luaL_checkinteger(L, 2));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003958 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02003959 offset = MAX(0, (int)input + offset);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003960 offset += output;
3961 if (offset < output || offset > input + output) {
3962 lua_pushfstring(L, "offset out of range.");
3963 WILL_LJMP(lua_error(L));
3964 }
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003965 }
3966
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003967 len = output + input - offset;
Boyang Lie0c54352022-05-10 17:47:23 +00003968 if (lua_gettop(L) == 3) {
3969 len = MAY_LJMP(luaL_checkinteger(L, 3));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003970 if (!len)
3971 goto end;
3972 if (len == -1)
3973 len = output + input - offset;
3974 if (len < 0 || offset + len > output + input) {
3975 lua_pushfstring(L, "length out of range.");
3976 WILL_LJMP(lua_error(L));
3977 }
3978 }
3979
3980 _hlua_channel_delete(chn, offset, len);
3981 if (filter) {
3982 struct hlua_flt_ctx *flt_ctx = filter->ctx;
3983
3984 flt_update_offsets(filter, chn, -len);
3985 flt_ctx->cur_len[CHN_IDX(chn)] -= len;
3986 }
3987
3988 end:
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003989 lua_pushinteger(L, len);
Christopher Faulet23976d92021-08-06 09:59:49 +02003990 return 1;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003991}
3992
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003993/* Append data in the output side of the buffer. This data is immediately
3994 * sent. The function returns the amount of data written. If the buffer
3995 * cannot contain the data, the function yields. The function returns -1
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003996 * if the channel is closed.
3997 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003998__LJMP static int hlua_channel_send_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003999{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02004000 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004001 struct filter *filter;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02004002 const char *str;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004003 size_t offset, len, sz;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02004004 int l, ret;
Thierry Fournier4234dbd2020-11-28 13:18:23 +01004005 struct hlua *hlua;
4006
4007 /* Get hlua struct, or NULL if we execute from main lua state */
4008 hlua = hlua_gethlua(L);
4009 if (!hlua) {
4010 lua_pushnil(L);
4011 return 1;
4012 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004013
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02004014 chn = MAY_LJMP(hlua_checkchannel(L, 1));
4015 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
4016 l = MAY_LJMP(luaL_checkinteger(L, 3));
Christopher Faulet3f829a42018-12-13 21:56:45 +01004017
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004018 offset = co_data(chn);
4019 len = ci_data(chn);
4020
4021 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
4022 if (filter && !hlua_filter_from_payload(filter))
4023 WILL_LJMP(lua_error(L));
4024
4025
Willy Tarreau47860ed2015-03-10 14:07:50 +01004026 if (unlikely(channel_output_closed(chn))) {
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004027 lua_pushinteger(L, -1);
4028 return 1;
4029 }
4030
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02004031 len = c_room(chn);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004032 if (len > sz -l) {
4033 if (filter) {
4034 lua_pushinteger(L, -1);
4035 return 1;
4036 }
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02004037 len = sz - l;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004038 }
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01004039
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004040 ret = _hlua_channel_insert(chn, L, ist2(str, len), offset);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02004041 if (ret == -1) {
4042 lua_pop(L, 1);
4043 lua_pushinteger(L, -1);
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01004044 return 1;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02004045 }
4046 if (ret) {
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004047 if (filter) {
4048 struct hlua_flt_ctx *flt_ctx = filter->ctx;
4049
4050
4051 flt_update_offsets(filter, chn, ret);
4052 FLT_OFF(filter, chn) += ret;
4053 flt_ctx->cur_off[CHN_IDX(chn)] += ret;
4054 }
4055 else
4056 c_adv(chn, ret);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004057
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02004058 l += ret;
4059 lua_pop(L, 1);
4060 lua_pushinteger(L, l);
4061 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004062
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02004063 if (l < sz) {
4064 /* Yield only if the channel's output is not empty.
4065 * Otherwise it means we cannot add more data. */
4066 if (co_data(chn) == 0 || HLUA_CANT_YIELD(hlua_gethlua(L)))
Christopher Faulet2e60aa42021-08-05 11:58:37 +02004067 return 1;
4068
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01004069 /* If we are waiting for space in the response buffer, we
4070 * must set the flag WAKERESWR. This flag required the task
4071 * wake up if any activity is detected on the response buffer.
4072 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01004073 if (chn->flags & CF_ISRESP)
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01004074 HLUA_SET_WAKERESWR(hlua);
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01004075 else
4076 HLUA_SET_WAKEREQWR(hlua);
Willy Tarreau9635e032018-10-16 17:52:55 +02004077 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01004078 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004079
4080 return 1;
4081}
4082
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05004083/* Just a wrapper of "_hlua_channel_send". This wrapper permits
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004084 * yield the LUA process, and resume it without checking the
4085 * input arguments.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004086 *
4087 * This function cannot be called from a filter.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004088 */
4089__LJMP static int hlua_channel_send(lua_State *L)
4090{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02004091 struct channel *chn;
4092
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004093 MAY_LJMP(check_args(L, 2, "send"));
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02004094 chn = MAY_LJMP(hlua_checkchannel(L, 1));
4095 if (IS_HTX_STRM(chn_strm(chn))) {
4096 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
4097 WILL_LJMP(lua_error(L));
4098 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004099 lua_pushinteger(L, 0);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01004100 return MAY_LJMP(hlua_channel_send_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004101}
4102
4103/* This function forward and amount of butes. The data pass from
4104 * the input side of the buffer to the output side, and can be
4105 * forwarded. This function never fails.
4106 *
4107 * The Lua function takes an amount of bytes to be forwarded in
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05004108 * input. It returns the number of bytes forwarded.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004109 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01004110__LJMP static int hlua_channel_forward_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004111{
Willy Tarreau47860ed2015-03-10 14:07:50 +01004112 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004113 struct filter *filter;
4114 size_t offset, len, fwd;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02004115 int l, max;
Thierry Fournier4234dbd2020-11-28 13:18:23 +01004116 struct hlua *hlua;
4117
4118 /* Get hlua struct, or NULL if we execute from main lua state */
4119 hlua = hlua_gethlua(L);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02004120 if (!hlua) {
4121 lua_pushnil(L);
Thierry Fournier4234dbd2020-11-28 13:18:23 +01004122 return 1;
Thierry Fournier77016da2020-08-15 14:35:51 +02004123 }
Christopher Faulet3f829a42018-12-13 21:56:45 +01004124
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02004125 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004126 fwd = MAY_LJMP(luaL_checkinteger(L, 2));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004127 l = MAY_LJMP(luaL_checkinteger(L, -1));
4128
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004129 offset = co_data(chn);
4130 len = ci_data(chn);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02004131
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004132 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
4133 if (filter && !hlua_filter_from_payload(filter))
4134 WILL_LJMP(lua_error(L));
4135
4136 max = fwd - l;
4137 if (max > len)
4138 max = len;
4139
4140 if (filter) {
4141 struct hlua_flt_ctx *flt_ctx = filter->ctx;
4142
4143 FLT_OFF(filter, chn) += max;
4144 flt_ctx->cur_off[CHN_IDX(chn)] += max;
4145 flt_ctx->cur_len[CHN_IDX(chn)] -= max;
4146 }
4147 else
4148 channel_forward(chn, max);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004149
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02004150 l += max;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004151 lua_pop(L, 1);
4152 lua_pushinteger(L, l);
4153
4154 /* Check if it miss bytes to forward. */
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004155 if (l < fwd) {
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004156 /* The the input channel or the output channel are closed, we
4157 * must return the amount of data forwarded.
4158 */
Christopher Faulet2e60aa42021-08-05 11:58:37 +02004159 if (channel_input_closed(chn) || channel_output_closed(chn) || HLUA_CANT_YIELD(hlua_gethlua(L)))
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004160 return 1;
4161
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01004162 /* If we are waiting for space data in the response buffer, we
4163 * must set the flag WAKERESWR. This flag required the task
4164 * wake up if any activity is detected on the response buffer.
4165 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01004166 if (chn->flags & CF_ISRESP)
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01004167 HLUA_SET_WAKERESWR(hlua);
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01004168 else
4169 HLUA_SET_WAKEREQWR(hlua);
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01004170
Ilya Shipitsin4a689da2022-10-29 09:34:32 +05004171 /* Otherwise, we can yield waiting for new data in the input side. */
Willy Tarreau9635e032018-10-16 17:52:55 +02004172 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_forward_yield, TICK_ETERNITY, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004173 }
4174
4175 return 1;
4176}
4177
4178/* Just check the input and prepare the stack for the previous
4179 * function "hlua_channel_forward_yield"
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004180 *
4181 * This function cannot be called from a filter.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004182 */
4183__LJMP static int hlua_channel_forward(lua_State *L)
4184{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02004185 struct channel *chn;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004186
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02004187 MAY_LJMP(check_args(L, 2, "forward"));
4188 chn = MAY_LJMP(hlua_checkchannel(L, 1));
4189 if (IS_HTX_STRM(chn_strm(chn))) {
4190 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
4191 WILL_LJMP(lua_error(L));
4192 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004193 lua_pushinteger(L, 0);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01004194 return MAY_LJMP(hlua_channel_forward_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004195}
4196
4197/* Just returns the number of bytes available in the input
4198 * side of the buffer. This function never fails.
4199 */
4200__LJMP static int hlua_channel_get_in_len(lua_State *L)
4201{
Willy Tarreau47860ed2015-03-10 14:07:50 +01004202 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004203 struct filter *filter;
4204 size_t output, input;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004205
Christopher Faulet6a79fc12021-08-06 16:02:36 +02004206 MAY_LJMP(check_args(L, 1, "input"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004207 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004208
4209 output = co_data(chn);
4210 input = ci_data(chn);
4211 filter = hlua_channel_filter(L, 1, chn, &output, &input);
4212 if (filter || !IS_HTX_STRM(chn_strm(chn)))
4213 lua_pushinteger(L, input);
4214 else {
Christopher Fauleta3ceac12018-12-14 13:39:09 +01004215 struct htx *htx = htxbuf(&chn->buf);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004216
Christopher Fauleta3ceac12018-12-14 13:39:09 +01004217 lua_pushinteger(L, htx->data - co_data(chn));
4218 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004219 return 1;
4220}
4221
Thierry FOURNIER / OZON.IO65192f32016-11-07 15:28:40 +01004222/* Returns true if the channel is full. */
4223__LJMP static int hlua_channel_is_full(lua_State *L)
4224{
4225 struct channel *chn;
Thierry FOURNIER / OZON.IO65192f32016-11-07 15:28:40 +01004226
4227 MAY_LJMP(check_args(L, 1, "is_full"));
4228 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Faulet0ec740e2020-02-26 11:59:19 +01004229 /* ignore the reserve, we are not on a producer side (ie in an
4230 * applet).
4231 */
4232 lua_pushboolean(L, channel_full(chn, 0));
Thierry FOURNIER / OZON.IO65192f32016-11-07 15:28:40 +01004233 return 1;
4234}
4235
Christopher Faulet6a79fc12021-08-06 16:02:36 +02004236/* Returns true if the channel may still receive data. */
4237__LJMP static int hlua_channel_may_recv(lua_State *L)
4238{
4239 struct channel *chn;
4240
4241 MAY_LJMP(check_args(L, 1, "may_recv"));
4242 chn = MAY_LJMP(hlua_checkchannel(L, 1));
4243 lua_pushboolean(L, (!channel_input_closed(chn) && channel_may_recv(chn)));
4244 return 1;
4245}
4246
Christopher Faulet2ac9ba22020-02-25 10:15:50 +01004247/* Returns true if the channel is the response channel. */
4248__LJMP static int hlua_channel_is_resp(lua_State *L)
4249{
4250 struct channel *chn;
4251
4252 MAY_LJMP(check_args(L, 1, "is_resp"));
4253 chn = MAY_LJMP(hlua_checkchannel(L, 1));
4254
4255 lua_pushboolean(L, !!(chn->flags & CF_ISRESP));
4256 return 1;
4257}
4258
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004259/* Just returns the number of bytes available in the output
4260 * side of the buffer. This function never fails.
4261 */
4262__LJMP static int hlua_channel_get_out_len(lua_State *L)
4263{
Willy Tarreau47860ed2015-03-10 14:07:50 +01004264 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004265 size_t output, input;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004266
Christopher Faulet6a79fc12021-08-06 16:02:36 +02004267 MAY_LJMP(check_args(L, 1, "output"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004268 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004269
4270 output = co_data(chn);
4271 input = ci_data(chn);
4272 hlua_channel_filter(L, 1, chn, &output, &input);
4273
4274 lua_pushinteger(L, output);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004275 return 1;
4276}
4277
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004278/*
4279 *
4280 *
4281 * Class Fetches
4282 *
4283 *
4284 */
4285
4286/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02004287 * a class stream, otherwise it throws an error.
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004288 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004289__LJMP static struct hlua_smp *hlua_checkfetches(lua_State *L, int ud)
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004290{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004291 return MAY_LJMP(hlua_checkudata(L, ud, class_fetches_ref));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004292}
4293
4294/* This function creates and push in the stack a fetch object according
4295 * with a current TXN.
4296 */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004297static int hlua_fetches_new(lua_State *L, struct hlua_txn *txn, unsigned int flags)
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004298{
Willy Tarreau7073c472015-04-06 11:15:40 +02004299 struct hlua_smp *hsmp;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004300
4301 /* Check stack size. */
4302 if (!lua_checkstack(L, 3))
4303 return 0;
4304
4305 /* Create the object: obj[0] = userdata.
4306 * Note that the base of the Fetches object is the
4307 * transaction object.
4308 */
4309 lua_newtable(L);
Willy Tarreau7073c472015-04-06 11:15:40 +02004310 hsmp = lua_newuserdata(L, sizeof(*hsmp));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004311 lua_rawseti(L, -2, 0);
4312
Willy Tarreau7073c472015-04-06 11:15:40 +02004313 hsmp->s = txn->s;
4314 hsmp->p = txn->p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01004315 hsmp->dir = txn->dir;
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004316 hsmp->flags = flags;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004317
4318 /* Pop a class sesison metatable and affect it to the userdata. */
4319 lua_rawgeti(L, LUA_REGISTRYINDEX, class_fetches_ref);
4320 lua_setmetatable(L, -2);
4321
4322 return 1;
4323}
4324
4325/* This function is an LUA binding. It is called with each sample-fetch.
4326 * It uses closure argument to store the associated sample-fetch. It
4327 * returns only one argument or throws an error. An error is thrown
4328 * only if an error is encountered during the argument parsing. If
4329 * the "sample-fetch" function fails, nil is returned.
4330 */
4331__LJMP static int hlua_run_sample_fetch(lua_State *L)
4332{
Willy Tarreaub2ccb562015-04-06 11:11:15 +02004333 struct hlua_smp *hsmp;
Willy Tarreau2ec22742015-03-10 14:27:20 +01004334 struct sample_fetch *f;
Frédéric Lécaillef874a832018-06-15 13:56:04 +02004335 struct arg args[ARGM_NBARGS + 1] = {{0}};
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004336 int i;
4337 struct sample smp;
4338
4339 /* Get closure arguments. */
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004340 f = lua_touserdata(L, lua_upvalueindex(1));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004341
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004342 /* Get traditional arguments. */
Willy Tarreaub2ccb562015-04-06 11:11:15 +02004343 hsmp = MAY_LJMP(hlua_checkfetches(L, 1));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004344
Thierry FOURNIERca988662015-12-20 18:43:03 +01004345 /* Check execution authorization. */
4346 if (f->use & SMP_USE_HTTP_ANY &&
4347 !(hsmp->flags & HLUA_F_MAY_USE_HTTP)) {
4348 lua_pushfstring(L, "the sample-fetch '%s' needs an HTTP parser which "
4349 "is not available in Lua services", f->kw);
4350 WILL_LJMP(lua_error(L));
4351 }
4352
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004353 /* Get extra arguments. */
4354 for (i = 0; i < lua_gettop(L) - 1; i++) {
4355 if (i >= ARGM_NBARGS)
4356 break;
4357 hlua_lua2arg(L, i + 2, &args[i]);
4358 }
4359 args[i].type = ARGT_STOP;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004360 args[i].data.str.area = NULL;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004361
4362 /* Check arguments. */
Willy Tarreaub2ccb562015-04-06 11:11:15 +02004363 MAY_LJMP(hlua_lua2arg_check(L, 2, args, f->arg_mask, hsmp->p));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004364
4365 /* Run the special args checker. */
Willy Tarreau2ec22742015-03-10 14:27:20 +01004366 if (f->val_args && !f->val_args(args, NULL)) {
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004367 lua_pushfstring(L, "error in arguments");
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004368 goto error;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004369 }
4370
4371 /* Initialise the sample. */
4372 memset(&smp, 0, sizeof(smp));
4373
4374 /* Run the sample fetch process. */
Willy Tarreau1777ea62016-03-10 16:15:46 +01004375 smp_set_owner(&smp, hsmp->p, hsmp->s->sess, hsmp->s, hsmp->dir & SMP_OPT_DIR);
Thierry FOURNIER0786d052015-05-11 15:42:45 +02004376 if (!f->process(args, &smp, f->kw, f->private)) {
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004377 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004378 lua_pushstring(L, "");
4379 else
4380 lua_pushnil(L);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004381 goto end;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004382 }
4383
4384 /* Convert the returned sample in lua value. */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004385 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004386 hlua_smp2lua_str(L, &smp);
4387 else
4388 hlua_smp2lua(L, &smp);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004389
4390 end:
Willy Tarreauee0d7272021-07-16 10:26:56 +02004391 free_args(args);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004392 return 1;
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004393
4394 error:
Willy Tarreauee0d7272021-07-16 10:26:56 +02004395 free_args(args);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004396 WILL_LJMP(lua_error(L));
4397 return 0; /* Never reached */
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004398}
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004399
4400/*
4401 *
4402 *
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004403 * Class Converters
4404 *
4405 *
4406 */
4407
4408/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02004409 * a class stream, otherwise it throws an error.
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004410 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004411__LJMP static struct hlua_smp *hlua_checkconverters(lua_State *L, int ud)
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004412{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004413 return MAY_LJMP(hlua_checkudata(L, ud, class_converters_ref));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004414}
4415
4416/* This function creates and push in the stack a Converters object
4417 * according with a current TXN.
4418 */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004419static int hlua_converters_new(lua_State *L, struct hlua_txn *txn, unsigned int flags)
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004420{
Willy Tarreau7073c472015-04-06 11:15:40 +02004421 struct hlua_smp *hsmp;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004422
4423 /* Check stack size. */
4424 if (!lua_checkstack(L, 3))
4425 return 0;
4426
4427 /* Create the object: obj[0] = userdata.
4428 * Note that the base of the Converters object is the
4429 * same than the TXN object.
4430 */
4431 lua_newtable(L);
Willy Tarreau7073c472015-04-06 11:15:40 +02004432 hsmp = lua_newuserdata(L, sizeof(*hsmp));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004433 lua_rawseti(L, -2, 0);
4434
Willy Tarreau7073c472015-04-06 11:15:40 +02004435 hsmp->s = txn->s;
4436 hsmp->p = txn->p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01004437 hsmp->dir = txn->dir;
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004438 hsmp->flags = flags;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004439
Willy Tarreau87b09662015-04-03 00:22:06 +02004440 /* Pop a class stream metatable and affect it to the table. */
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004441 lua_rawgeti(L, LUA_REGISTRYINDEX, class_converters_ref);
4442 lua_setmetatable(L, -2);
4443
4444 return 1;
4445}
4446
4447/* This function is an LUA binding. It is called with each converter.
4448 * It uses closure argument to store the associated converter. It
4449 * returns only one argument or throws an error. An error is thrown
4450 * only if an error is encountered during the argument parsing. If
4451 * the converter function function fails, nil is returned.
4452 */
4453__LJMP static int hlua_run_sample_conv(lua_State *L)
4454{
Willy Tarreauda5f1082015-04-06 11:17:13 +02004455 struct hlua_smp *hsmp;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004456 struct sample_conv *conv;
Frédéric Lécaillef874a832018-06-15 13:56:04 +02004457 struct arg args[ARGM_NBARGS + 1] = {{0}};
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004458 int i;
4459 struct sample smp;
4460
4461 /* Get closure arguments. */
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004462 conv = lua_touserdata(L, lua_upvalueindex(1));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004463
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004464 /* Get traditional arguments. */
Willy Tarreauda5f1082015-04-06 11:17:13 +02004465 hsmp = MAY_LJMP(hlua_checkconverters(L, 1));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004466
4467 /* Get extra arguments. */
4468 for (i = 0; i < lua_gettop(L) - 2; i++) {
4469 if (i >= ARGM_NBARGS)
4470 break;
4471 hlua_lua2arg(L, i + 3, &args[i]);
4472 }
4473 args[i].type = ARGT_STOP;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004474 args[i].data.str.area = NULL;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004475
4476 /* Check arguments. */
Willy Tarreauda5f1082015-04-06 11:17:13 +02004477 MAY_LJMP(hlua_lua2arg_check(L, 3, args, conv->arg_mask, hsmp->p));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004478
4479 /* Run the special args checker. */
4480 if (conv->val_args && !conv->val_args(args, conv, "", 0, NULL)) {
4481 hlua_pusherror(L, "error in arguments");
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004482 goto error;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004483 }
4484
4485 /* Initialise the sample. */
Amaury Denoyellebc0af6a2020-10-29 17:21:20 +01004486 memset(&smp, 0, sizeof(smp));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004487 if (!hlua_lua2smp(L, 2, &smp)) {
4488 hlua_pusherror(L, "error in the input argument");
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004489 goto error;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004490 }
4491
Willy Tarreau1777ea62016-03-10 16:15:46 +01004492 smp_set_owner(&smp, hsmp->p, hsmp->s->sess, hsmp->s, hsmp->dir & SMP_OPT_DIR);
4493
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004494 /* Apply expected cast. */
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02004495 if (!sample_casts[smp.data.type][conv->in_type]) {
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004496 hlua_pusherror(L, "invalid input argument: cannot cast '%s' to '%s'",
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02004497 smp_to_type[smp.data.type], smp_to_type[conv->in_type]);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004498 goto error;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004499 }
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02004500 if (sample_casts[smp.data.type][conv->in_type] != c_none &&
4501 !sample_casts[smp.data.type][conv->in_type](&smp)) {
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004502 hlua_pusherror(L, "error during the input argument casting");
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004503 goto error;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004504 }
4505
4506 /* Run the sample conversion process. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02004507 if (!conv->process(args, &smp, conv->private)) {
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004508 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004509 lua_pushstring(L, "");
4510 else
Willy Tarreaua678b432015-08-28 10:14:59 +02004511 lua_pushnil(L);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004512 goto end;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004513 }
4514
4515 /* Convert the returned sample in lua value. */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004516 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004517 hlua_smp2lua_str(L, &smp);
4518 else
4519 hlua_smp2lua(L, &smp);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004520 end:
Willy Tarreauee0d7272021-07-16 10:26:56 +02004521 free_args(args);
Willy Tarreaua678b432015-08-28 10:14:59 +02004522 return 1;
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004523
4524 error:
Willy Tarreauee0d7272021-07-16 10:26:56 +02004525 free_args(args);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004526 WILL_LJMP(lua_error(L));
4527 return 0; /* Never reached */
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004528}
4529
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004530/*
4531 *
4532 *
4533 * Class AppletTCP
4534 *
4535 *
4536 */
4537
4538/* Returns a struct hlua_txn if the stack entry "ud" is
4539 * a class stream, otherwise it throws an error.
4540 */
4541__LJMP static struct hlua_appctx *hlua_checkapplet_tcp(lua_State *L, int ud)
4542{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004543 return MAY_LJMP(hlua_checkudata(L, ud, class_applet_tcp_ref));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004544}
4545
4546/* This function creates and push in the stack an Applet object
4547 * according with a current TXN.
4548 */
4549static int hlua_applet_tcp_new(lua_State *L, struct appctx *ctx)
4550{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004551 struct hlua_appctx *luactx;
Willy Tarreau0698c802022-05-11 14:09:57 +02004552 struct stream *s = appctx_strm(ctx);
Christopher Faulet2da02ae2022-02-24 13:45:27 +01004553 struct proxy *p;
4554
4555 ALREADY_CHECKED(s);
4556 p = s->be;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004557
4558 /* Check stack size. */
4559 if (!lua_checkstack(L, 3))
4560 return 0;
4561
4562 /* Create the object: obj[0] = userdata.
4563 * Note that the base of the Converters object is the
4564 * same than the TXN object.
4565 */
4566 lua_newtable(L);
Willy Tarreau7e702d12021-04-28 17:59:21 +02004567 luactx = lua_newuserdata(L, sizeof(*luactx));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004568 lua_rawseti(L, -2, 0);
Willy Tarreau7e702d12021-04-28 17:59:21 +02004569 luactx->appctx = ctx;
4570 luactx->htxn.s = s;
4571 luactx->htxn.p = p;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004572
4573 /* Create the "f" field that contains a list of fetches. */
4574 lua_pushstring(L, "f");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004575 if (!hlua_fetches_new(L, &luactx->htxn, 0))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004576 return 0;
4577 lua_settable(L, -3);
4578
4579 /* Create the "sf" field that contains a list of stringsafe fetches. */
4580 lua_pushstring(L, "sf");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004581 if (!hlua_fetches_new(L, &luactx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004582 return 0;
4583 lua_settable(L, -3);
4584
4585 /* Create the "c" field that contains a list of converters. */
4586 lua_pushstring(L, "c");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004587 if (!hlua_converters_new(L, &luactx->htxn, 0))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004588 return 0;
4589 lua_settable(L, -3);
4590
4591 /* Create the "sc" field that contains a list of stringsafe converters. */
4592 lua_pushstring(L, "sc");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004593 if (!hlua_converters_new(L, &luactx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004594 return 0;
4595 lua_settable(L, -3);
4596
4597 /* Pop a class stream metatable and affect it to the table. */
4598 lua_rawgeti(L, LUA_REGISTRYINDEX, class_applet_tcp_ref);
4599 lua_setmetatable(L, -2);
4600
4601 return 1;
4602}
4603
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004604__LJMP static int hlua_applet_tcp_set_var(lua_State *L)
4605{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004606 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004607 struct stream *s;
4608 const char *name;
4609 size_t len;
4610 struct sample smp;
4611
Tim Duesterhus4e172c92020-05-19 13:49:42 +02004612 if (lua_gettop(L) < 3 || lua_gettop(L) > 4)
4613 WILL_LJMP(luaL_error(L, "'set_var' needs between 3 and 4 arguments"));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004614
4615 /* It is useles to retrieve the stream, but this function
4616 * runs only in a stream context.
4617 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004618 luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004619 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02004620 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004621
4622 /* Converts the third argument in a sample. */
Amaury Denoyellebc0af6a2020-10-29 17:21:20 +01004623 memset(&smp, 0, sizeof(smp));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004624 hlua_lua2smp(L, 3, &smp);
4625
4626 /* Store the sample in a variable. */
4627 smp_set_owner(&smp, s->be, s->sess, s, 0);
Tim Duesterhus4e172c92020-05-19 13:49:42 +02004628
4629 if (lua_gettop(L) == 4 && lua_toboolean(L, 4))
4630 lua_pushboolean(L, vars_set_by_name_ifexist(name, len, &smp) != 0);
4631 else
4632 lua_pushboolean(L, vars_set_by_name(name, len, &smp) != 0);
4633
Tim Duesterhus84ebc132020-05-19 13:49:41 +02004634 return 1;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004635}
4636
4637__LJMP static int hlua_applet_tcp_unset_var(lua_State *L)
4638{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004639 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004640 struct stream *s;
4641 const char *name;
4642 size_t len;
4643 struct sample smp;
4644
4645 MAY_LJMP(check_args(L, 2, "unset_var"));
4646
4647 /* It is useles to retrieve the stream, but this function
4648 * runs only in a stream context.
4649 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004650 luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004651 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02004652 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004653
4654 /* Unset the variable. */
4655 smp_set_owner(&smp, s->be, s->sess, s, 0);
Tim Duesterhus84ebc132020-05-19 13:49:41 +02004656 lua_pushboolean(L, vars_unset_by_name_ifexist(name, len, &smp) != 0);
4657 return 1;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004658}
4659
4660__LJMP static int hlua_applet_tcp_get_var(lua_State *L)
4661{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004662 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004663 struct stream *s;
4664 const char *name;
4665 size_t len;
4666 struct sample smp;
4667
4668 MAY_LJMP(check_args(L, 2, "get_var"));
4669
4670 /* It is useles to retrieve the stream, but this function
4671 * runs only in a stream context.
4672 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004673 luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004674 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02004675 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004676
4677 smp_set_owner(&smp, s->be, s->sess, s, 0);
Willy Tarreaue352b9d2021-09-03 11:52:38 +02004678 if (!vars_get_by_name(name, len, &smp, NULL)) {
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004679 lua_pushnil(L);
4680 return 1;
4681 }
4682
4683 return hlua_smp2lua(L, &smp);
4684}
4685
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004686__LJMP static int hlua_applet_tcp_set_priv(lua_State *L)
4687{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004688 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
4689 struct stream *s = luactx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01004690 struct hlua *hlua;
4691
4692 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01004693 if (!s->hlua)
4694 return 0;
4695 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004696
4697 MAY_LJMP(check_args(L, 2, "set_priv"));
4698
4699 /* Remove previous value. */
Thierry FOURNIERe068b602017-04-26 13:27:05 +02004700 luaL_unref(L, LUA_REGISTRYINDEX, hlua->Mref);
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004701
4702 /* Get and store new value. */
4703 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
4704 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
4705
4706 return 0;
4707}
4708
4709__LJMP static int hlua_applet_tcp_get_priv(lua_State *L)
4710{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004711 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
4712 struct stream *s = luactx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01004713 struct hlua *hlua;
4714
4715 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01004716 if (!s->hlua) {
4717 lua_pushnil(L);
4718 return 1;
4719 }
4720 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004721
4722 /* Push configuration index in the stack. */
4723 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
4724
4725 return 1;
4726}
4727
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004728/* If expected data not yet available, it returns a yield. This function
4729 * consumes the data in the buffer. It returns a string containing the
4730 * data. This string can be empty.
4731 */
4732__LJMP static int hlua_applet_tcp_getline_yield(lua_State *L, int status, lua_KContext ctx)
4733{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004734 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Willy Tarreauc12b3212022-05-27 11:08:15 +02004735 struct stconn *sc = appctx_sc(luactx->appctx);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004736 int ret;
Willy Tarreau206ba832018-06-14 15:27:31 +02004737 const char *blk1;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004738 size_t len1;
Willy Tarreau206ba832018-06-14 15:27:31 +02004739 const char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004740 size_t len2;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004741
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004742 /* Read the maximum amount of data available. */
Willy Tarreau3e7be362022-05-27 10:35:27 +02004743 ret = co_getline_nc(sc_oc(sc), &blk1, &len1, &blk2, &len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004744
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004745 /* Data not yet available. return yield. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004746 if (ret == 0) {
Willy Tarreau90e8b452022-05-25 18:21:43 +02004747 applet_need_more_data(luactx->appctx);
Willy Tarreau9635e032018-10-16 17:52:55 +02004748 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_getline_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004749 }
4750
4751 /* End of data: commit the total strings and return. */
4752 if (ret < 0) {
Willy Tarreau7e702d12021-04-28 17:59:21 +02004753 luaL_pushresult(&luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004754 return 1;
4755 }
4756
4757 /* Ensure that the block 2 length is usable. */
4758 if (ret == 1)
4759 len2 = 0;
4760
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -07004761 /* don't check the max length read and don't check. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004762 luaL_addlstring(&luactx->b, blk1, len1);
4763 luaL_addlstring(&luactx->b, blk2, len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004764
4765 /* Consume input channel output buffer data. */
Willy Tarreau3e7be362022-05-27 10:35:27 +02004766 co_skip(sc_oc(sc), len1 + len2);
Willy Tarreau7e702d12021-04-28 17:59:21 +02004767 luaL_pushresult(&luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004768 return 1;
4769}
4770
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004771/* Check arguments for the function "hlua_channel_get_yield". */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004772__LJMP static int hlua_applet_tcp_getline(lua_State *L)
4773{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004774 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004775
4776 /* Initialise the string catenation. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004777 luaL_buffinit(L, &luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004778
4779 return MAY_LJMP(hlua_applet_tcp_getline_yield(L, 0, 0));
4780}
4781
4782/* If expected data not yet available, it returns a yield. This function
4783 * consumes the data in the buffer. It returns a string containing the
4784 * data. This string can be empty.
4785 */
4786__LJMP static int hlua_applet_tcp_recv_yield(lua_State *L, int status, lua_KContext ctx)
4787{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004788 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Willy Tarreauc12b3212022-05-27 11:08:15 +02004789 struct stconn *sc = appctx_sc(luactx->appctx);
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004790 size_t len = MAY_LJMP(luaL_checkinteger(L, 2));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004791 int ret;
Willy Tarreau206ba832018-06-14 15:27:31 +02004792 const char *blk1;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004793 size_t len1;
Willy Tarreau206ba832018-06-14 15:27:31 +02004794 const char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004795 size_t len2;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004796
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004797 /* Read the maximum amount of data available. */
Willy Tarreau3e7be362022-05-27 10:35:27 +02004798 ret = co_getblk_nc(sc_oc(sc), &blk1, &len1, &blk2, &len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004799
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004800 /* Data not yet available. return yield. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004801 if (ret == 0) {
Willy Tarreau90e8b452022-05-25 18:21:43 +02004802 applet_need_more_data(luactx->appctx);
Willy Tarreau9635e032018-10-16 17:52:55 +02004803 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004804 }
4805
4806 /* End of data: commit the total strings and return. */
4807 if (ret < 0) {
Willy Tarreau7e702d12021-04-28 17:59:21 +02004808 luaL_pushresult(&luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004809 return 1;
4810 }
4811
4812 /* Ensure that the block 2 length is usable. */
4813 if (ret == 1)
4814 len2 = 0;
4815
4816 if (len == -1) {
4817
4818 /* If len == -1, catenate all the data avalaile and
4819 * yield because we want to get all the data until
4820 * the end of data stream.
4821 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004822 luaL_addlstring(&luactx->b, blk1, len1);
4823 luaL_addlstring(&luactx->b, blk2, len2);
Willy Tarreau3e7be362022-05-27 10:35:27 +02004824 co_skip(sc_oc(sc), len1 + len2);
Willy Tarreau90e8b452022-05-25 18:21:43 +02004825 applet_need_more_data(luactx->appctx);
Willy Tarreau9635e032018-10-16 17:52:55 +02004826 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004827
4828 } else {
4829
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05004830 /* Copy the first block caping to the length required. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004831 if (len1 > len)
4832 len1 = len;
Willy Tarreau7e702d12021-04-28 17:59:21 +02004833 luaL_addlstring(&luactx->b, blk1, len1);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004834 len -= len1;
4835
4836 /* Copy the second block. */
4837 if (len2 > len)
4838 len2 = len;
Willy Tarreau7e702d12021-04-28 17:59:21 +02004839 luaL_addlstring(&luactx->b, blk2, len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004840 len -= len2;
4841
4842 /* Consume input channel output buffer data. */
Willy Tarreau3e7be362022-05-27 10:35:27 +02004843 co_skip(sc_oc(sc), len1 + len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004844
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004845 /* If there is no other data available, yield waiting for new data. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004846 if (len > 0) {
4847 lua_pushinteger(L, len);
4848 lua_replace(L, 2);
Willy Tarreau90e8b452022-05-25 18:21:43 +02004849 applet_need_more_data(luactx->appctx);
Willy Tarreau9635e032018-10-16 17:52:55 +02004850 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004851 }
4852
4853 /* return the result. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004854 luaL_pushresult(&luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004855 return 1;
4856 }
4857
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004858 /* we never execute this */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004859 hlua_pusherror(L, "Lua: internal error");
4860 WILL_LJMP(lua_error(L));
4861 return 0;
4862}
4863
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004864/* Check arguments for the function "hlua_channel_get_yield". */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004865__LJMP static int hlua_applet_tcp_recv(lua_State *L)
4866{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004867 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004868 int len = -1;
4869
4870 if (lua_gettop(L) > 2)
4871 WILL_LJMP(luaL_error(L, "The 'recv' function requires between 1 and 2 arguments."));
4872 if (lua_gettop(L) >= 2) {
4873 len = MAY_LJMP(luaL_checkinteger(L, 2));
4874 lua_pop(L, 1);
4875 }
4876
4877 /* Confirm or set the required length */
4878 lua_pushinteger(L, len);
4879
4880 /* Initialise the string catenation. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004881 luaL_buffinit(L, &luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004882
4883 return MAY_LJMP(hlua_applet_tcp_recv_yield(L, 0, 0));
4884}
4885
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004886/* Append data in the output side of the buffer. This data is immediately
4887 * sent. The function returns the amount of data written. If the buffer
4888 * cannot contain the data, the function yields. The function returns -1
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004889 * if the channel is closed.
4890 */
4891__LJMP static int hlua_applet_tcp_send_yield(lua_State *L, int status, lua_KContext ctx)
4892{
4893 size_t len;
Willy Tarreau7e702d12021-04-28 17:59:21 +02004894 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004895 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
4896 int l = MAY_LJMP(luaL_checkinteger(L, 3));
Willy Tarreauc12b3212022-05-27 11:08:15 +02004897 struct stconn *sc = appctx_sc(luactx->appctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02004898 struct channel *chn = sc_ic(sc);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004899 int max;
4900
4901 /* Get the max amount of data which can write as input in the channel. */
4902 max = channel_recv_max(chn);
4903 if (max > (len - l))
4904 max = len - l;
4905
4906 /* Copy data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02004907 ci_putblk(chn, str + l, max);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004908
4909 /* update counters. */
4910 l += max;
4911 lua_pop(L, 1);
4912 lua_pushinteger(L, l);
4913
4914 /* If some data is not send, declares the situation to the
4915 * applet, and returns a yield.
4916 */
4917 if (l < len) {
Willy Tarreau3e7be362022-05-27 10:35:27 +02004918 sc_need_room(sc);
Willy Tarreau9635e032018-10-16 17:52:55 +02004919 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004920 }
4921
4922 return 1;
4923}
4924
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05004925/* Just a wrapper of "hlua_applet_tcp_send_yield". This wrapper permits
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004926 * yield the LUA process, and resume it without checking the
4927 * input arguments.
4928 */
4929__LJMP static int hlua_applet_tcp_send(lua_State *L)
4930{
4931 MAY_LJMP(check_args(L, 2, "send"));
4932 lua_pushinteger(L, 0);
4933
4934 return MAY_LJMP(hlua_applet_tcp_send_yield(L, 0, 0));
4935}
4936
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004937/*
4938 *
4939 *
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004940 * Class AppletHTTP
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004941 *
4942 *
4943 */
4944
4945/* Returns a struct hlua_txn if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02004946 * a class stream, otherwise it throws an error.
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004947 */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004948__LJMP static struct hlua_appctx *hlua_checkapplet_http(lua_State *L, int ud)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004949{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004950 return MAY_LJMP(hlua_checkudata(L, ud, class_applet_http_ref));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004951}
4952
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004953/* This function creates and push in the stack an Applet object
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004954 * according with a current TXN.
Willy Tarreauaa229cc2022-05-06 14:26:10 +02004955 * It relies on the caller to have already reserved the room in ctx->svcctx
4956 * for the local storage of hlua_http_ctx.
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004957 */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004958static int hlua_applet_http_new(lua_State *L, struct appctx *ctx)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004959{
Willy Tarreauaa229cc2022-05-06 14:26:10 +02004960 struct hlua_http_ctx *http_ctx = ctx->svcctx;
Willy Tarreau7e702d12021-04-28 17:59:21 +02004961 struct hlua_appctx *luactx;
Thierry FOURNIER841475e2015-12-11 17:10:09 +01004962 struct hlua_txn htxn;
Willy Tarreau0698c802022-05-11 14:09:57 +02004963 struct stream *s = appctx_strm(ctx);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004964 struct proxy *px = s->be;
Christopher Fauleta2097962019-07-15 16:25:33 +02004965 struct htx *htx;
4966 struct htx_blk *blk;
4967 struct htx_sl *sl;
4968 struct ist path;
4969 unsigned long long len = 0;
4970 int32_t pos;
Amaury Denoyellec453f952021-07-06 11:40:12 +02004971 struct http_uri_parser parser;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004972
4973 /* Check stack size. */
4974 if (!lua_checkstack(L, 3))
4975 return 0;
4976
4977 /* Create the object: obj[0] = userdata.
4978 * Note that the base of the Converters object is the
4979 * same than the TXN object.
4980 */
4981 lua_newtable(L);
Willy Tarreau7e702d12021-04-28 17:59:21 +02004982 luactx = lua_newuserdata(L, sizeof(*luactx));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004983 lua_rawseti(L, -2, 0);
Willy Tarreau7e702d12021-04-28 17:59:21 +02004984 luactx->appctx = ctx;
Willy Tarreauaa229cc2022-05-06 14:26:10 +02004985 http_ctx->status = 200; /* Default status code returned. */
4986 http_ctx->reason = NULL; /* Use default reason based on status */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004987 luactx->htxn.s = s;
4988 luactx->htxn.p = px;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004989
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004990 /* Create the "f" field that contains a list of fetches. */
4991 lua_pushstring(L, "f");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004992 if (!hlua_fetches_new(L, &luactx->htxn, 0))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004993 return 0;
4994 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004995
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004996 /* Create the "sf" field that contains a list of stringsafe fetches. */
4997 lua_pushstring(L, "sf");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004998 if (!hlua_fetches_new(L, &luactx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004999 return 0;
5000 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005001
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005002 /* Create the "c" field that contains a list of converters. */
5003 lua_pushstring(L, "c");
Willy Tarreau7e702d12021-04-28 17:59:21 +02005004 if (!hlua_converters_new(L, &luactx->htxn, 0))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005005 return 0;
5006 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005007
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005008 /* Create the "sc" field that contains a list of stringsafe converters. */
5009 lua_pushstring(L, "sc");
Willy Tarreau7e702d12021-04-28 17:59:21 +02005010 if (!hlua_converters_new(L, &luactx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005011 return 0;
5012 lua_settable(L, -3);
Willy Tarreaueee5b512015-04-03 23:46:31 +02005013
Christopher Fauleta2097962019-07-15 16:25:33 +02005014 htx = htxbuf(&s->req.buf);
5015 blk = htx_get_first_blk(htx);
Christopher Fauletea009732019-11-18 15:50:25 +01005016 BUG_ON(!blk || htx_get_blk_type(blk) != HTX_BLK_REQ_SL);
Christopher Fauleta2097962019-07-15 16:25:33 +02005017 sl = htx_get_blk_ptr(htx, blk);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005018
Christopher Fauleta2097962019-07-15 16:25:33 +02005019 /* Stores the request method. */
5020 lua_pushstring(L, "method");
5021 lua_pushlstring(L, HTX_SL_REQ_MPTR(sl), HTX_SL_REQ_MLEN(sl));
5022 lua_settable(L, -3);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005023
Christopher Fauleta2097962019-07-15 16:25:33 +02005024 /* Stores the http version. */
5025 lua_pushstring(L, "version");
5026 lua_pushlstring(L, HTX_SL_REQ_VPTR(sl), HTX_SL_REQ_VLEN(sl));
5027 lua_settable(L, -3);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005028
Christopher Fauleta2097962019-07-15 16:25:33 +02005029 /* creates an array of headers. hlua_http_get_headers() crates and push
5030 * the array on the top of the stack.
5031 */
5032 lua_pushstring(L, "headers");
5033 htxn.s = s;
5034 htxn.p = px;
5035 htxn.dir = SMP_OPT_DIR_REQ;
Christopher Faulet9d1332b2020-02-24 16:46:16 +01005036 if (!hlua_http_get_headers(L, &htxn.s->txn->req))
Christopher Fauleta2097962019-07-15 16:25:33 +02005037 return 0;
5038 lua_settable(L, -3);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005039
Amaury Denoyellec453f952021-07-06 11:40:12 +02005040 parser = http_uri_parser_init(htx_sl_req_uri(sl));
5041 path = http_parse_path(&parser);
Tim Duesterhused526372020-03-05 17:56:33 +01005042 if (isttest(path)) {
Christopher Fauleta2097962019-07-15 16:25:33 +02005043 char *p, *q, *end;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005044
Christopher Fauleta2097962019-07-15 16:25:33 +02005045 p = path.ptr;
Tim Duesterhus4c8f75f2021-11-06 15:14:44 +01005046 end = istend(path);
Christopher Fauleta2097962019-07-15 16:25:33 +02005047 q = p;
5048 while (q < end && *q != '?')
5049 q++;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005050
Thierry FOURNIER7d388632017-02-22 02:06:16 +01005051 /* Stores the request path. */
Christopher Fauleta2097962019-07-15 16:25:33 +02005052 lua_pushstring(L, "path");
5053 lua_pushlstring(L, p, q - p);
Thierry FOURNIER7d388632017-02-22 02:06:16 +01005054 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01005055
Christopher Fauleta2097962019-07-15 16:25:33 +02005056 /* Stores the query string. */
5057 lua_pushstring(L, "qs");
5058 if (*q == '?')
5059 q++;
5060 lua_pushlstring(L, q, end - q);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005061 lua_settable(L, -3);
Christopher Fauleta2097962019-07-15 16:25:33 +02005062 }
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005063
Christopher Fauleta2097962019-07-15 16:25:33 +02005064 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
5065 struct htx_blk *blk = htx_get_blk(htx, pos);
5066 enum htx_blk_type type = htx_get_blk_type(blk);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005067
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01005068 if (type == HTX_BLK_TLR || type == HTX_BLK_EOT)
Christopher Fauleta2097962019-07-15 16:25:33 +02005069 break;
5070 if (type == HTX_BLK_DATA)
5071 len += htx_get_blksz(blk);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005072 }
Christopher Faulet2e47e3a2023-01-13 11:40:24 +01005073 if (htx->extra != HTX_UNKOWN_PAYLOAD_LENGTH)
Christopher Fauleta2097962019-07-15 16:25:33 +02005074 len += htx->extra;
5075
5076 /* Stores the request path. */
5077 lua_pushstring(L, "length");
5078 lua_pushinteger(L, len);
5079 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01005080
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005081 /* Create an empty array of HTTP request headers. */
5082 lua_pushstring(L, "response");
5083 lua_newtable(L);
5084 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01005085
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005086 /* Pop a class stream metatable and affect it to the table. */
5087 lua_rawgeti(L, LUA_REGISTRYINDEX, class_applet_http_ref);
5088 lua_setmetatable(L, -2);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005089
5090 return 1;
5091}
5092
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01005093__LJMP static int hlua_applet_http_set_var(lua_State *L)
5094{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005095 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01005096 struct stream *s;
5097 const char *name;
5098 size_t len;
5099 struct sample smp;
5100
Tim Duesterhus4e172c92020-05-19 13:49:42 +02005101 if (lua_gettop(L) < 3 || lua_gettop(L) > 4)
5102 WILL_LJMP(luaL_error(L, "'set_var' needs between 3 and 4 arguments"));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01005103
5104 /* It is useles to retrieve the stream, but this function
5105 * runs only in a stream context.
5106 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005107 luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01005108 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02005109 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01005110
5111 /* Converts the third argument in a sample. */
Amaury Denoyellebc0af6a2020-10-29 17:21:20 +01005112 memset(&smp, 0, sizeof(smp));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01005113 hlua_lua2smp(L, 3, &smp);
5114
5115 /* Store the sample in a variable. */
5116 smp_set_owner(&smp, s->be, s->sess, s, 0);
Tim Duesterhus4e172c92020-05-19 13:49:42 +02005117
5118 if (lua_gettop(L) == 4 && lua_toboolean(L, 4))
5119 lua_pushboolean(L, vars_set_by_name_ifexist(name, len, &smp) != 0);
5120 else
5121 lua_pushboolean(L, vars_set_by_name(name, len, &smp) != 0);
5122
Tim Duesterhus84ebc132020-05-19 13:49:41 +02005123 return 1;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01005124}
5125
5126__LJMP static int hlua_applet_http_unset_var(lua_State *L)
5127{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005128 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01005129 struct stream *s;
5130 const char *name;
5131 size_t len;
5132 struct sample smp;
5133
5134 MAY_LJMP(check_args(L, 2, "unset_var"));
5135
5136 /* It is useles to retrieve the stream, but this function
5137 * runs only in a stream context.
5138 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005139 luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01005140 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02005141 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01005142
5143 /* Unset the variable. */
5144 smp_set_owner(&smp, s->be, s->sess, s, 0);
Tim Duesterhus84ebc132020-05-19 13:49:41 +02005145 lua_pushboolean(L, vars_unset_by_name_ifexist(name, len, &smp) != 0);
5146 return 1;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01005147}
5148
5149__LJMP static int hlua_applet_http_get_var(lua_State *L)
5150{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005151 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01005152 struct stream *s;
5153 const char *name;
5154 size_t len;
5155 struct sample smp;
5156
5157 MAY_LJMP(check_args(L, 2, "get_var"));
5158
5159 /* It is useles to retrieve the stream, but this function
5160 * runs only in a stream context.
5161 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005162 luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01005163 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02005164 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01005165
5166 smp_set_owner(&smp, s->be, s->sess, s, 0);
Willy Tarreaue352b9d2021-09-03 11:52:38 +02005167 if (!vars_get_by_name(name, len, &smp, NULL)) {
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01005168 lua_pushnil(L);
5169 return 1;
5170 }
5171
5172 return hlua_smp2lua(L, &smp);
5173}
5174
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01005175__LJMP static int hlua_applet_http_set_priv(lua_State *L)
5176{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005177 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
5178 struct stream *s = luactx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01005179 struct hlua *hlua;
5180
5181 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005182 if (!s->hlua)
5183 return 0;
5184 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01005185
5186 MAY_LJMP(check_args(L, 2, "set_priv"));
5187
5188 /* Remove previous value. */
Thierry FOURNIERe068b602017-04-26 13:27:05 +02005189 luaL_unref(L, LUA_REGISTRYINDEX, hlua->Mref);
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01005190
5191 /* Get and store new value. */
5192 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
5193 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
5194
5195 return 0;
5196}
5197
5198__LJMP static int hlua_applet_http_get_priv(lua_State *L)
5199{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005200 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
5201 struct stream *s = luactx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01005202 struct hlua *hlua;
5203
5204 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005205 if (!s->hlua) {
5206 lua_pushnil(L);
5207 return 1;
5208 }
5209 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01005210
5211 /* Push configuration index in the stack. */
5212 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
5213
5214 return 1;
5215}
5216
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005217/* If expected data not yet available, it returns a yield. This function
5218 * consumes the data in the buffer. It returns a string containing the
5219 * data. This string can be empty.
5220 */
Christopher Fauleta2097962019-07-15 16:25:33 +02005221__LJMP static int hlua_applet_http_getline_yield(lua_State *L, int status, lua_KContext ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005222{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005223 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Willy Tarreauc12b3212022-05-27 11:08:15 +02005224 struct stconn *sc = appctx_sc(luactx->appctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02005225 struct channel *req = sc_oc(sc);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005226 struct htx *htx;
5227 struct htx_blk *blk;
5228 size_t count;
5229 int stop = 0;
5230
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005231 htx = htx_from_buf(&req->buf);
5232 count = co_data(req);
Christopher Fauleta3f15502019-05-13 15:27:23 +02005233 blk = htx_get_first_blk(htx);
Christopher Fauletcc26b132018-12-18 21:20:57 +01005234
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005235 while (count && !stop && blk) {
5236 enum htx_blk_type type = htx_get_blk_type(blk);
5237 uint32_t sz = htx_get_blksz(blk);
5238 struct ist v;
5239 uint32_t vlen;
5240 char *nl;
5241
5242 vlen = sz;
5243 if (vlen > count) {
5244 if (type != HTX_BLK_DATA)
5245 break;
5246 vlen = count;
5247 }
5248
5249 switch (type) {
5250 case HTX_BLK_UNUSED:
5251 break;
5252
5253 case HTX_BLK_DATA:
5254 v = htx_get_blk_value(htx, blk);
5255 v.len = vlen;
5256 nl = istchr(v, '\n');
5257 if (nl != NULL) {
5258 stop = 1;
5259 vlen = nl - v.ptr + 1;
5260 }
Willy Tarreau7e702d12021-04-28 17:59:21 +02005261 luaL_addlstring(&luactx->b, v.ptr, vlen);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005262 break;
5263
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005264 case HTX_BLK_TLR:
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01005265 case HTX_BLK_EOT:
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005266 stop = 1;
5267 break;
5268
5269 default:
5270 break;
5271 }
5272
Willy Tarreau84240042022-02-28 16:51:23 +01005273 c_rew(req, vlen);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005274 count -= vlen;
5275 if (sz == vlen)
5276 blk = htx_remove_blk(htx, blk);
5277 else {
5278 htx_cut_data_blk(htx, blk, vlen);
5279 break;
5280 }
5281 }
5282
Christopher Fauleteccb31c2021-04-02 14:24:56 +02005283 /* The message was fully consumed and no more data are expected
5284 * (EOM flag set).
5285 */
Christopher Faulet904763f2023-03-22 14:53:11 +01005286 if (htx_is_empty(htx) && (sc->flags & SC_FL_EOI))
Christopher Fauleteccb31c2021-04-02 14:24:56 +02005287 stop = 1;
5288
Christopher Faulet0ae79d02019-02-27 21:36:59 +01005289 htx_to_buf(htx, &req->buf);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005290 if (!stop) {
Willy Tarreau90e8b452022-05-25 18:21:43 +02005291 applet_need_more_data(luactx->appctx);
Christopher Fauleta2097962019-07-15 16:25:33 +02005292 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_getline_yield, TICK_ETERNITY, 0));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005293 }
5294
5295 /* return the result. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005296 luaL_pushresult(&luactx->b);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005297 return 1;
5298}
5299
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005300
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08005301/* Check arguments for the function "hlua_channel_get_yield". */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005302__LJMP static int hlua_applet_http_getline(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005303{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005304 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005305
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005306 /* Initialise the string catenation. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005307 luaL_buffinit(L, &luactx->b);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005308
Christopher Fauleta2097962019-07-15 16:25:33 +02005309 return MAY_LJMP(hlua_applet_http_getline_yield(L, 0, 0));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005310}
5311
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005312/* If expected data not yet available, it returns a yield. This function
5313 * consumes the data in the buffer. It returns a string containing the
5314 * data. This string can be empty.
5315 */
Christopher Fauleta2097962019-07-15 16:25:33 +02005316__LJMP static int hlua_applet_http_recv_yield(lua_State *L, int status, lua_KContext ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005317{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005318 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Willy Tarreauc12b3212022-05-27 11:08:15 +02005319 struct stconn *sc = appctx_sc(luactx->appctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02005320 struct channel *req = sc_oc(sc);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005321 struct htx *htx;
5322 struct htx_blk *blk;
5323 size_t count;
5324 int len;
5325
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005326 htx = htx_from_buf(&req->buf);
5327 len = MAY_LJMP(luaL_checkinteger(L, 2));
5328 count = co_data(req);
Christopher Faulet29f17582019-05-23 11:03:26 +02005329 blk = htx_get_head_blk(htx);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005330 while (count && len && blk) {
5331 enum htx_blk_type type = htx_get_blk_type(blk);
5332 uint32_t sz = htx_get_blksz(blk);
5333 struct ist v;
5334 uint32_t vlen;
5335
5336 vlen = sz;
5337 if (len > 0 && vlen > len)
5338 vlen = len;
5339 if (vlen > count) {
5340 if (type != HTX_BLK_DATA)
5341 break;
5342 vlen = count;
5343 }
5344
5345 switch (type) {
5346 case HTX_BLK_UNUSED:
5347 break;
5348
5349 case HTX_BLK_DATA:
5350 v = htx_get_blk_value(htx, blk);
Willy Tarreau7e702d12021-04-28 17:59:21 +02005351 luaL_addlstring(&luactx->b, v.ptr, vlen);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005352 break;
5353
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005354 case HTX_BLK_TLR:
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01005355 case HTX_BLK_EOT:
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005356 len = 0;
5357 break;
5358
5359 default:
5360 break;
5361 }
5362
Willy Tarreau84240042022-02-28 16:51:23 +01005363 c_rew(req, vlen);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005364 count -= vlen;
5365 if (len > 0)
5366 len -= vlen;
5367 if (sz == vlen)
5368 blk = htx_remove_blk(htx, blk);
5369 else {
5370 htx_cut_data_blk(htx, blk, vlen);
5371 break;
5372 }
5373 }
5374
Christopher Fauleteccb31c2021-04-02 14:24:56 +02005375 /* The message was fully consumed and no more data are expected
5376 * (EOM flag set).
5377 */
Christopher Faulet904763f2023-03-22 14:53:11 +01005378 if (htx_is_empty(htx) && (sc->flags & SC_FL_EOI))
Christopher Fauleteccb31c2021-04-02 14:24:56 +02005379 len = 0;
5380
Christopher Faulet0ae79d02019-02-27 21:36:59 +01005381 htx_to_buf(htx, &req->buf);
5382
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005383 /* If we are no other data available, yield waiting for new data. */
5384 if (len) {
5385 if (len > 0) {
5386 lua_pushinteger(L, len);
5387 lua_replace(L, 2);
5388 }
Willy Tarreau90e8b452022-05-25 18:21:43 +02005389 applet_need_more_data(luactx->appctx);
Willy Tarreau9635e032018-10-16 17:52:55 +02005390 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005391 }
5392
5393 /* return the result. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005394 luaL_pushresult(&luactx->b);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005395 return 1;
5396}
5397
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08005398/* Check arguments for the function "hlua_channel_get_yield". */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005399__LJMP static int hlua_applet_http_recv(lua_State *L)
5400{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005401 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005402 int len = -1;
5403
5404 /* Check arguments. */
5405 if (lua_gettop(L) > 2)
5406 WILL_LJMP(luaL_error(L, "The 'recv' function requires between 1 and 2 arguments."));
5407 if (lua_gettop(L) >= 2) {
5408 len = MAY_LJMP(luaL_checkinteger(L, 2));
5409 lua_pop(L, 1);
5410 }
5411
Christopher Fauleta2097962019-07-15 16:25:33 +02005412 lua_pushinteger(L, len);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005413
Christopher Fauleta2097962019-07-15 16:25:33 +02005414 /* Initialise the string catenation. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005415 luaL_buffinit(L, &luactx->b);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005416
Christopher Fauleta2097962019-07-15 16:25:33 +02005417 return MAY_LJMP(hlua_applet_http_recv_yield(L, 0, 0));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005418}
5419
5420/* Append data in the output side of the buffer. This data is immediately
5421 * sent. The function returns the amount of data written. If the buffer
5422 * cannot contain the data, the function yields. The function returns -1
5423 * if the channel is closed.
5424 */
Christopher Fauleta2097962019-07-15 16:25:33 +02005425__LJMP static int hlua_applet_http_send_yield(lua_State *L, int status, lua_KContext ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005426{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005427 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Willy Tarreauc12b3212022-05-27 11:08:15 +02005428 struct stconn *sc = appctx_sc(luactx->appctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02005429 struct channel *res = sc_ic(sc);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005430 struct htx *htx = htx_from_buf(&res->buf);
5431 const char *data;
5432 size_t len;
5433 int l = MAY_LJMP(luaL_checkinteger(L, 3));
5434 int max;
5435
Christopher Faulet9060fc02019-07-03 11:39:30 +02005436 max = htx_get_max_blksz(htx, channel_htx_recv_max(res, htx));
Christopher Faulet4b0e9b22019-01-09 12:16:58 +01005437 if (!max)
5438 goto snd_yield;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005439
5440 data = MAY_LJMP(luaL_checklstring(L, 2, &len));
5441
5442 /* Get the max amount of data which can write as input in the channel. */
5443 if (max > (len - l))
5444 max = len - l;
5445
5446 /* Copy data. */
Willy Tarreau0a7ef022019-05-28 10:30:11 +02005447 max = htx_add_data(htx, ist2(data + l, max));
Christopher Fauletf6cce3f2019-02-27 21:20:09 +01005448 channel_add_input(res, max);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005449
5450 /* update counters. */
5451 l += max;
5452 lua_pop(L, 1);
5453 lua_pushinteger(L, l);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005454
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005455 /* If some data is not send, declares the situation to the
5456 * applet, and returns a yield.
5457 */
5458 if (l < len) {
Christopher Faulet4b0e9b22019-01-09 12:16:58 +01005459 snd_yield:
Christopher Faulet0ae79d02019-02-27 21:36:59 +01005460 htx_to_buf(htx, &res->buf);
Willy Tarreau3e7be362022-05-27 10:35:27 +02005461 sc_need_room(sc);
Willy Tarreau9635e032018-10-16 17:52:55 +02005462 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005463 }
5464
Christopher Fauleta2097962019-07-15 16:25:33 +02005465 htx_to_buf(htx, &res->buf);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005466 return 1;
5467}
5468
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05005469/* Just a wrapper of "hlua_applet_send_yield". This wrapper permits
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005470 * yield the LUA process, and resume it without checking the
5471 * input arguments.
5472 */
5473__LJMP static int hlua_applet_http_send(lua_State *L)
5474{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005475 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005476 struct hlua_http_ctx *http_ctx = luactx->appctx->svcctx;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005477
5478 /* We want to send some data. Headers must be sent. */
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005479 if (!(http_ctx->flags & APPLET_HDR_SENT)) {
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005480 hlua_pusherror(L, "Lua: 'send' you must call start_response() before sending data.");
5481 WILL_LJMP(lua_error(L));
5482 }
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005483
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05005484 /* This integer is used for followinf the amount of data sent. */
Christopher Fauleta2097962019-07-15 16:25:33 +02005485 lua_pushinteger(L, 0);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005486
Christopher Fauleta2097962019-07-15 16:25:33 +02005487 return MAY_LJMP(hlua_applet_http_send_yield(L, 0, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005488}
5489
5490__LJMP static int hlua_applet_http_addheader(lua_State *L)
5491{
5492 const char *name;
5493 int ret;
5494
5495 MAY_LJMP(hlua_checkapplet_http(L, 1));
5496 name = MAY_LJMP(luaL_checkstring(L, 2));
5497 MAY_LJMP(luaL_checkstring(L, 3));
5498
5499 /* Push in the stack the "response" entry. */
5500 ret = lua_getfield(L, 1, "response");
5501 if (ret != LUA_TTABLE) {
5502 hlua_pusherror(L, "Lua: 'add_header' internal error: AppletHTTP['response'] "
5503 "is expected as an array. %s found", lua_typename(L, ret));
5504 WILL_LJMP(lua_error(L));
5505 }
5506
5507 /* check if the header is already registered if it is not
5508 * the case, register it.
5509 */
5510 ret = lua_getfield(L, -1, name);
5511 if (ret == LUA_TNIL) {
5512
5513 /* Entry not found. */
5514 lua_pop(L, 1); /* remove the nil. The "response" table is the top of the stack. */
5515
5516 /* Insert the new header name in the array in the top of the stack.
5517 * It left the new array in the top of the stack.
5518 */
5519 lua_newtable(L);
5520 lua_pushvalue(L, 2);
5521 lua_pushvalue(L, -2);
5522 lua_settable(L, -4);
5523
5524 } else if (ret != LUA_TTABLE) {
5525
5526 /* corruption error. */
5527 hlua_pusherror(L, "Lua: 'add_header' internal error: AppletHTTP['response']['%s'] "
5528 "is expected as an array. %s found", name, lua_typename(L, ret));
5529 WILL_LJMP(lua_error(L));
5530 }
5531
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -07005532 /* Now the top of thestack is an array of values. We push
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005533 * the header value as new entry.
5534 */
5535 lua_pushvalue(L, 3);
5536 ret = lua_rawlen(L, -2);
5537 lua_rawseti(L, -2, ret + 1);
5538 lua_pushboolean(L, 1);
5539 return 1;
5540}
5541
5542__LJMP static int hlua_applet_http_status(lua_State *L)
5543{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005544 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005545 int status = MAY_LJMP(luaL_checkinteger(L, 2));
Robin H. Johnson52f5db22017-01-01 13:10:52 -08005546 const char *reason = MAY_LJMP(luaL_optlstring(L, 3, NULL, NULL));
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005547 struct hlua_http_ctx *http_ctx = luactx->appctx->svcctx;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005548
5549 if (status < 100 || status > 599) {
5550 lua_pushboolean(L, 0);
5551 return 1;
5552 }
5553
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005554 http_ctx->status = status;
5555 http_ctx->reason = reason;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005556 lua_pushboolean(L, 1);
5557 return 1;
5558}
5559
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005560
Christopher Fauleta2097962019-07-15 16:25:33 +02005561__LJMP static int hlua_applet_http_send_response(lua_State *L)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005562{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005563 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005564 struct hlua_http_ctx *http_ctx = luactx->appctx->svcctx;
Willy Tarreauc12b3212022-05-27 11:08:15 +02005565 struct stconn *sc = appctx_sc(luactx->appctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02005566 struct channel *res = sc_ic(sc);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005567 struct htx *htx;
5568 struct htx_sl *sl;
5569 struct h1m h1m;
5570 const char *status, *reason;
5571 const char *name, *value;
5572 size_t nlen, vlen;
5573 unsigned int flags;
5574
5575 /* Send the message at once. */
5576 htx = htx_from_buf(&res->buf);
5577 h1m_init_res(&h1m);
5578
5579 /* Use the same http version than the request. */
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005580 status = ultoa_r(http_ctx->status, trash.area, trash.size);
5581 reason = http_ctx->reason;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005582 if (reason == NULL)
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005583 reason = http_get_reason(http_ctx->status);
5584 if (http_ctx->flags & APPLET_HTTP11) {
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005585 flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11);
5586 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.1"), ist(status), ist(reason));
5587 }
5588 else {
5589 flags = HTX_SL_F_IS_RESP;
5590 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.0"), ist(status), ist(reason));
5591 }
5592 if (!sl) {
5593 hlua_pusherror(L, "Lua applet http '%s': Failed to create response.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005594 luactx->appctx->rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005595 WILL_LJMP(lua_error(L));
5596 }
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005597 sl->info.res.status = http_ctx->status;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005598
5599 /* Get the array associated to the field "response" in the object AppletHTTP. */
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005600 if (lua_getfield(L, 1, "response") != LUA_TTABLE) {
5601 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response'] missing.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005602 luactx->appctx->rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005603 WILL_LJMP(lua_error(L));
5604 }
5605
5606 /* Browse the list of headers. */
5607 lua_pushnil(L);
5608 while(lua_next(L, -2) != 0) {
5609 /* We expect a string as -2. */
5610 if (lua_type(L, -2) != LUA_TSTRING) {
5611 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response'][] element must be a string. got %s.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005612 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005613 lua_typename(L, lua_type(L, -2)));
5614 WILL_LJMP(lua_error(L));
5615 }
5616 name = lua_tolstring(L, -2, &nlen);
5617
5618 /* We expect an array as -1. */
5619 if (lua_type(L, -1) != LUA_TTABLE) {
5620 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 +02005621 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005622 name,
5623 lua_typename(L, lua_type(L, -1)));
5624 WILL_LJMP(lua_error(L));
5625 }
5626
5627 /* Browse the table who is on the top of the stack. */
5628 lua_pushnil(L);
5629 while(lua_next(L, -2) != 0) {
5630 int id;
5631
5632 /* We expect a number as -2. */
5633 if (lua_type(L, -2) != LUA_TNUMBER) {
5634 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 +02005635 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005636 name,
5637 lua_typename(L, lua_type(L, -2)));
5638 WILL_LJMP(lua_error(L));
5639 }
5640 id = lua_tointeger(L, -2);
5641
5642 /* We expect a string as -2. */
5643 if (lua_type(L, -1) != LUA_TSTRING) {
5644 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 +02005645 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005646 name, id,
5647 lua_typename(L, lua_type(L, -1)));
5648 WILL_LJMP(lua_error(L));
5649 }
5650 value = lua_tolstring(L, -1, &vlen);
5651
5652 /* Simple Protocol checks. */
Christopher Faulet545fbba2021-09-28 09:36:25 +02005653 if (isteqi(ist2(name, nlen), ist("transfer-encoding"))) {
5654 int ret;
5655
5656 ret = h1_parse_xfer_enc_header(&h1m, ist2(value, vlen));
5657 if (ret < 0) {
5658 hlua_pusherror(L, "Lua applet http '%s': Invalid '%s' header.\n",
5659 luactx->appctx->rule->arg.hlua_rule->fcn->name,
5660 name);
5661 WILL_LJMP(lua_error(L));
5662 }
5663 else if (ret == 0)
5664 goto next; /* Skip it */
5665 }
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005666 else if (isteqi(ist2(name, nlen), ist("content-length"))) {
5667 struct ist v = ist2(value, vlen);
5668 int ret;
5669
5670 ret = h1_parse_cont_len_header(&h1m, &v);
5671 if (ret < 0) {
5672 hlua_pusherror(L, "Lua applet http '%s': Invalid '%s' header.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005673 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005674 name);
5675 WILL_LJMP(lua_error(L));
5676 }
5677 else if (ret == 0)
5678 goto next; /* Skip it */
5679 }
5680
5681 /* Add a new header */
5682 if (!htx_add_header(htx, ist2(name, nlen), ist2(value, vlen))) {
5683 hlua_pusherror(L, "Lua applet http '%s': Failed to add header '%s' in the response.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005684 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005685 name);
5686 WILL_LJMP(lua_error(L));
5687 }
5688 next:
5689 /* Remove the array from the stack, and get next element with a remaining string. */
5690 lua_pop(L, 1);
5691 }
5692
5693 /* Remove the array from the stack, and get next element with a remaining string. */
5694 lua_pop(L, 1);
5695 }
5696
5697 if (h1m.flags & H1_MF_CHNK)
5698 h1m.flags &= ~H1_MF_CLEN;
5699 if (h1m.flags & (H1_MF_CLEN|H1_MF_CHNK))
5700 h1m.flags |= H1_MF_XFER_LEN;
5701
5702 /* Uset HTX start-line flags */
5703 if (h1m.flags & H1_MF_XFER_ENC)
5704 flags |= HTX_SL_F_XFER_ENC;
5705 if (h1m.flags & H1_MF_XFER_LEN) {
5706 flags |= HTX_SL_F_XFER_LEN;
5707 if (h1m.flags & H1_MF_CHNK)
5708 flags |= HTX_SL_F_CHNK;
5709 else if (h1m.flags & H1_MF_CLEN)
5710 flags |= HTX_SL_F_CLEN;
5711 if (h1m.body_len == 0)
5712 flags |= HTX_SL_F_BODYLESS;
5713 }
5714 sl->flags |= flags;
5715
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -07005716 /* If we don't have a content-length set, and the HTTP version is 1.1
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005717 * and the status code implies the presence of a message body, we must
5718 * announce a transfer encoding chunked. This is required by haproxy
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05005719 * for the keepalive compliance. If the applet announces a transfer-encoding
5720 * chunked itself, don't do anything.
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005721 */
5722 if ((flags & (HTX_SL_F_VER_11|HTX_SL_F_XFER_LEN)) == HTX_SL_F_VER_11 &&
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005723 http_ctx->status >= 200 && http_ctx->status != 204 && http_ctx->status != 304) {
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005724 /* Add a new header */
5725 sl->flags |= (HTX_SL_F_XFER_ENC|H1_MF_CHNK|H1_MF_XFER_LEN);
5726 if (!htx_add_header(htx, ist("transfer-encoding"), ist("chunked"))) {
5727 hlua_pusherror(L, "Lua applet http '%s': Failed to add header 'transfer-encoding' in the response.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005728 luactx->appctx->rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005729 WILL_LJMP(lua_error(L));
5730 }
5731 }
5732
5733 /* Finalize headers. */
5734 if (!htx_add_endof(htx, HTX_BLK_EOH)) {
5735 hlua_pusherror(L, "Lua applet http '%s': Failed create the response.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005736 luactx->appctx->rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005737 WILL_LJMP(lua_error(L));
5738 }
5739
5740 if (htx_used_space(htx) > b_size(&res->buf) - global.tune.maxrewrite) {
5741 b_reset(&res->buf);
5742 hlua_pusherror(L, "Lua: 'start_response': response header block too big");
5743 WILL_LJMP(lua_error(L));
5744 }
5745
5746 htx_to_buf(htx, &res->buf);
Christopher Fauletf6cce3f2019-02-27 21:20:09 +01005747 channel_add_input(res, htx->data);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005748
5749 /* Headers sent, set the flag. */
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005750 http_ctx->flags |= APPLET_HDR_SENT;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005751 return 0;
5752
5753}
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005754/* We will build the status line and the headers of the HTTP response.
5755 * We will try send at once if its not possible, we give back the hand
5756 * waiting for more room.
5757 */
Christopher Fauleta2097962019-07-15 16:25:33 +02005758__LJMP static int hlua_applet_http_start_response_yield(lua_State *L, int status, lua_KContext ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005759{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005760 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Willy Tarreauc12b3212022-05-27 11:08:15 +02005761 struct stconn *sc = appctx_sc(luactx->appctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02005762 struct channel *res = sc_ic(sc);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005763
5764 if (co_data(res)) {
Willy Tarreau3e7be362022-05-27 10:35:27 +02005765 sc_need_room(sc);
Christopher Fauleta2097962019-07-15 16:25:33 +02005766 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_start_response_yield, TICK_ETERNITY, 0));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005767 }
Christopher Fauleta2097962019-07-15 16:25:33 +02005768 return MAY_LJMP(hlua_applet_http_send_response(L));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005769}
5770
5771
Christopher Fauleta2097962019-07-15 16:25:33 +02005772__LJMP static int hlua_applet_http_start_response(lua_State *L)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005773{
Christopher Fauleta2097962019-07-15 16:25:33 +02005774 return MAY_LJMP(hlua_applet_http_start_response_yield(L, 0, 0));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005775}
5776
Christopher Fauleta2097962019-07-15 16:25:33 +02005777/*
5778 *
5779 *
5780 * Class HTTP
5781 *
5782 *
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005783 */
Christopher Fauleta2097962019-07-15 16:25:33 +02005784
5785/* Returns a struct hlua_txn if the stack entry "ud" is
5786 * a class stream, otherwise it throws an error.
5787 */
5788__LJMP static struct hlua_txn *hlua_checkhttp(lua_State *L, int ud)
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005789{
Christopher Fauleta2097962019-07-15 16:25:33 +02005790 return MAY_LJMP(hlua_checkudata(L, ud, class_http_ref));
5791}
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005792
Christopher Fauleta2097962019-07-15 16:25:33 +02005793/* This function creates and push in the stack a HTTP object
5794 * according with a current TXN.
5795 */
5796static int hlua_http_new(lua_State *L, struct hlua_txn *txn)
5797{
5798 struct hlua_txn *htxn;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005799
Christopher Fauleta2097962019-07-15 16:25:33 +02005800 /* Check stack size. */
5801 if (!lua_checkstack(L, 3))
5802 return 0;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005803
Christopher Fauleta2097962019-07-15 16:25:33 +02005804 /* Create the object: obj[0] = userdata.
5805 * Note that the base of the Converters object is the
5806 * same than the TXN object.
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005807 */
Christopher Fauleta2097962019-07-15 16:25:33 +02005808 lua_newtable(L);
5809 htxn = lua_newuserdata(L, sizeof(*htxn));
5810 lua_rawseti(L, -2, 0);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005811
5812 htxn->s = txn->s;
5813 htxn->p = txn->p;
Christopher Faulet256b69a2019-05-23 11:14:21 +02005814 htxn->dir = txn->dir;
5815 htxn->flags = txn->flags;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005816
5817 /* Pop a class stream metatable and affect it to the table. */
5818 lua_rawgeti(L, LUA_REGISTRYINDEX, class_http_ref);
5819 lua_setmetatable(L, -2);
5820
5821 return 1;
5822}
5823
Christopher Fauletdf97ac42020-02-26 16:57:19 +01005824/* This function creates and returns an array containing the status-line
5825 * elements. This function does not fails.
5826 */
5827__LJMP static int hlua_http_get_stline(lua_State *L, struct htx_sl *sl)
5828{
5829 /* Create the table. */
5830 lua_newtable(L);
5831
5832 if (sl->flags & HTX_SL_F_IS_RESP) {
5833 lua_pushstring(L, "version");
5834 lua_pushlstring(L, HTX_SL_RES_VPTR(sl), HTX_SL_RES_VLEN(sl));
5835 lua_settable(L, -3);
5836 lua_pushstring(L, "code");
5837 lua_pushlstring(L, HTX_SL_RES_CPTR(sl), HTX_SL_RES_CLEN(sl));
5838 lua_settable(L, -3);
5839 lua_pushstring(L, "reason");
5840 lua_pushlstring(L, HTX_SL_RES_RPTR(sl), HTX_SL_RES_RLEN(sl));
5841 lua_settable(L, -3);
5842 }
5843 else {
5844 lua_pushstring(L, "method");
5845 lua_pushlstring(L, HTX_SL_REQ_MPTR(sl), HTX_SL_REQ_MLEN(sl));
5846 lua_settable(L, -3);
5847 lua_pushstring(L, "uri");
5848 lua_pushlstring(L, HTX_SL_REQ_UPTR(sl), HTX_SL_REQ_ULEN(sl));
5849 lua_settable(L, -3);
5850 lua_pushstring(L, "version");
5851 lua_pushlstring(L, HTX_SL_REQ_VPTR(sl), HTX_SL_REQ_VLEN(sl));
5852 lua_settable(L, -3);
5853 }
5854 return 1;
5855}
5856
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005857/* This function creates ans returns an array of HTTP headers.
5858 * This function does not fails. It is used as wrapper with the
5859 * 2 following functions.
5860 */
Christopher Faulet9d1332b2020-02-24 16:46:16 +01005861__LJMP static int hlua_http_get_headers(lua_State *L, struct http_msg *msg)
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005862{
Christopher Fauleta2097962019-07-15 16:25:33 +02005863 struct htx *htx;
5864 int32_t pos;
5865
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005866 /* Create the table. */
5867 lua_newtable(L);
5868
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005869
Christopher Fauleta2097962019-07-15 16:25:33 +02005870 htx = htxbuf(&msg->chn->buf);
5871 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
5872 struct htx_blk *blk = htx_get_blk(htx, pos);
5873 enum htx_blk_type type = htx_get_blk_type(blk);
5874 struct ist n, v;
5875 int len;
Christopher Faulet724a12c2018-12-13 22:12:15 +01005876
Christopher Fauleta2097962019-07-15 16:25:33 +02005877 if (type == HTX_BLK_HDR) {
5878 n = htx_get_blk_name(htx,blk);
5879 v = htx_get_blk_value(htx, blk);
Christopher Faulet724a12c2018-12-13 22:12:15 +01005880 }
Christopher Fauleta2097962019-07-15 16:25:33 +02005881 else if (type == HTX_BLK_EOH)
5882 break;
5883 else
5884 continue;
Christopher Faulet724a12c2018-12-13 22:12:15 +01005885
Christopher Fauleta2097962019-07-15 16:25:33 +02005886 /* Check for existing entry:
5887 * assume that the table is on the top of the stack, and
5888 * push the key in the stack, the function lua_gettable()
5889 * perform the lookup.
5890 */
5891 lua_pushlstring(L, n.ptr, n.len);
5892 lua_gettable(L, -2);
Christopher Faulet724a12c2018-12-13 22:12:15 +01005893
Christopher Fauleta2097962019-07-15 16:25:33 +02005894 switch (lua_type(L, -1)) {
5895 case LUA_TNIL:
5896 /* Table not found, create it. */
5897 lua_pop(L, 1); /* remove the nil value. */
5898 lua_pushlstring(L, n.ptr, n.len); /* push the header name as key. */
5899 lua_newtable(L); /* create and push empty table. */
5900 lua_pushlstring(L, v.ptr, v.len); /* push header value. */
5901 lua_rawseti(L, -2, 0); /* index header value (pop it). */
5902 lua_rawset(L, -3); /* index new table with header name (pop the values). */
Christopher Faulet724a12c2018-12-13 22:12:15 +01005903 break;
Christopher Faulet724a12c2018-12-13 22:12:15 +01005904
Christopher Fauleta2097962019-07-15 16:25:33 +02005905 case LUA_TTABLE:
5906 /* Entry found: push the value in the table. */
5907 len = lua_rawlen(L, -1);
5908 lua_pushlstring(L, v.ptr, v.len); /* push header value. */
5909 lua_rawseti(L, -2, len+1); /* index header value (pop it). */
5910 lua_pop(L, 1); /* remove the table (it is stored in the main table). */
5911 break;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005912
Christopher Fauleta2097962019-07-15 16:25:33 +02005913 default:
5914 /* Other cases are errors. */
5915 hlua_pusherror(L, "internal error during the parsing of headers.");
5916 WILL_LJMP(lua_error(L));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005917 }
5918 }
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005919 return 1;
5920}
5921
5922__LJMP static int hlua_http_req_get_headers(lua_State *L)
5923{
5924 struct hlua_txn *htxn;
5925
5926 MAY_LJMP(check_args(L, 1, "req_get_headers"));
5927 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5928
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005929 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005930 WILL_LJMP(lua_error(L));
5931
Christopher Faulet9d1332b2020-02-24 16:46:16 +01005932 return hlua_http_get_headers(L, &htxn->s->txn->req);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005933}
5934
5935__LJMP static int hlua_http_res_get_headers(lua_State *L)
5936{
5937 struct hlua_txn *htxn;
5938
5939 MAY_LJMP(check_args(L, 1, "res_get_headers"));
5940 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5941
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005942 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005943 WILL_LJMP(lua_error(L));
5944
Christopher Faulet9d1332b2020-02-24 16:46:16 +01005945 return hlua_http_get_headers(L, &htxn->s->txn->rsp);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005946}
5947
5948/* This function replace full header, or just a value in
5949 * the request or in the response. It is a wrapper fir the
5950 * 4 following functions.
5951 */
Christopher Fauletd1914aa2020-02-24 16:52:46 +01005952__LJMP static inline int hlua_http_rep_hdr(lua_State *L, struct http_msg *msg, int full)
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005953{
5954 size_t name_len;
5955 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
5956 const char *reg = MAY_LJMP(luaL_checkstring(L, 3));
5957 const char *value = MAY_LJMP(luaL_checkstring(L, 4));
Christopher Fauleta2097962019-07-15 16:25:33 +02005958 struct htx *htx;
Dragan Dosen26743032019-04-30 15:54:36 +02005959 struct my_regex *re;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005960
Dragan Dosen26743032019-04-30 15:54:36 +02005961 if (!(re = regex_comp(reg, 1, 1, NULL)))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005962 WILL_LJMP(luaL_argerror(L, 3, "invalid regex"));
5963
Christopher Fauleta2097962019-07-15 16:25:33 +02005964 htx = htxbuf(&msg->chn->buf);
Christopher Fauletd1914aa2020-02-24 16:52:46 +01005965 http_replace_hdrs(chn_strm(msg->chn), htx, ist2(name, name_len), value, re, full);
Dragan Dosen26743032019-04-30 15:54:36 +02005966 regex_free(re);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005967 return 0;
5968}
5969
5970__LJMP static int hlua_http_req_rep_hdr(lua_State *L)
5971{
5972 struct hlua_txn *htxn;
5973
5974 MAY_LJMP(check_args(L, 4, "req_rep_hdr"));
5975 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5976
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005977 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005978 WILL_LJMP(lua_error(L));
5979
Christopher Fauletd1914aa2020-02-24 16:52:46 +01005980 return MAY_LJMP(hlua_http_rep_hdr(L, &htxn->s->txn->req, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005981}
5982
5983__LJMP static int hlua_http_res_rep_hdr(lua_State *L)
5984{
5985 struct hlua_txn *htxn;
5986
5987 MAY_LJMP(check_args(L, 4, "res_rep_hdr"));
5988 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5989
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005990 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005991 WILL_LJMP(lua_error(L));
5992
Christopher Fauletd1914aa2020-02-24 16:52:46 +01005993 return MAY_LJMP(hlua_http_rep_hdr(L, &htxn->s->txn->rsp, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005994}
5995
5996__LJMP static int hlua_http_req_rep_val(lua_State *L)
5997{
5998 struct hlua_txn *htxn;
5999
6000 MAY_LJMP(check_args(L, 4, "req_rep_hdr"));
6001 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
6002
Christopher Fauletd8f0e072020-02-25 09:45:51 +01006003 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006004 WILL_LJMP(lua_error(L));
6005
Christopher Fauletd1914aa2020-02-24 16:52:46 +01006006 return MAY_LJMP(hlua_http_rep_hdr(L, &htxn->s->txn->req, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006007}
6008
6009__LJMP static int hlua_http_res_rep_val(lua_State *L)
6010{
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006011 struct hlua_txn *htxn;
6012
6013 MAY_LJMP(check_args(L, 4, "res_rep_val"));
6014 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
6015
Christopher Fauletd8f0e072020-02-25 09:45:51 +01006016 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006017 WILL_LJMP(lua_error(L));
6018
Christopher Fauletd1914aa2020-02-24 16:52:46 +01006019 return MAY_LJMP(hlua_http_rep_hdr(L, &htxn->s->txn->rsp, 0));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006020}
6021
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08006022/* This function deletes all the occurrences of an header.
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006023 * It is a wrapper for the 2 following functions.
6024 */
Christopher Fauletd31c7b32020-02-25 09:37:57 +01006025__LJMP static inline int hlua_http_del_hdr(lua_State *L, struct http_msg *msg)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006026{
6027 size_t len;
6028 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Christopher Fauleta2097962019-07-15 16:25:33 +02006029 struct htx *htx = htxbuf(&msg->chn->buf);
6030 struct http_hdr_ctx ctx;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006031
Christopher Fauleta2097962019-07-15 16:25:33 +02006032 ctx.blk = NULL;
6033 while (http_find_header(htx, ist2(name, len), &ctx, 1))
6034 http_remove_header(htx, &ctx);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006035 return 0;
6036}
6037
6038__LJMP static int hlua_http_req_del_hdr(lua_State *L)
6039{
6040 struct hlua_txn *htxn;
6041
6042 MAY_LJMP(check_args(L, 2, "req_del_hdr"));
6043 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
6044
Christopher Fauletd8f0e072020-02-25 09:45:51 +01006045 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006046 WILL_LJMP(lua_error(L));
6047
Christopher Fauletd31c7b32020-02-25 09:37:57 +01006048 return hlua_http_del_hdr(L, &htxn->s->txn->req);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006049}
6050
6051__LJMP static int hlua_http_res_del_hdr(lua_State *L)
6052{
6053 struct hlua_txn *htxn;
6054
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006055 MAY_LJMP(check_args(L, 2, "res_del_hdr"));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006056 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
6057
Christopher Fauletd8f0e072020-02-25 09:45:51 +01006058 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006059 WILL_LJMP(lua_error(L));
6060
Christopher Fauletd31c7b32020-02-25 09:37:57 +01006061 return hlua_http_del_hdr(L, &htxn->s->txn->rsp);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006062}
6063
6064/* This function adds an header. It is a wrapper used by
6065 * the 2 following functions.
6066 */
Christopher Fauletd31c7b32020-02-25 09:37:57 +01006067__LJMP static inline int hlua_http_add_hdr(lua_State *L, struct http_msg *msg)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006068{
6069 size_t name_len;
6070 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
6071 size_t value_len;
6072 const char *value = MAY_LJMP(luaL_checklstring(L, 3, &value_len));
Christopher Fauleta2097962019-07-15 16:25:33 +02006073 struct htx *htx = htxbuf(&msg->chn->buf);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006074
Christopher Fauleta2097962019-07-15 16:25:33 +02006075 lua_pushboolean(L, http_add_header(htx, ist2(name, name_len),
6076 ist2(value, value_len)));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006077 return 0;
6078}
6079
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006080__LJMP static int hlua_http_req_add_hdr(lua_State *L)
6081{
6082 struct hlua_txn *htxn;
6083
6084 MAY_LJMP(check_args(L, 3, "req_add_hdr"));
6085 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
6086
6087 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
6088 WILL_LJMP(lua_error(L));
6089
6090 return hlua_http_add_hdr(L, &htxn->s->txn->req);
6091}
6092
6093__LJMP static int hlua_http_res_add_hdr(lua_State *L)
6094{
6095 struct hlua_txn *htxn;
6096
6097 MAY_LJMP(check_args(L, 3, "res_add_hdr"));
6098 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
6099
6100 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
6101 WILL_LJMP(lua_error(L));
6102
6103 return hlua_http_add_hdr(L, &htxn->s->txn->rsp);
6104}
6105
6106static int hlua_http_req_set_hdr(lua_State *L)
6107{
6108 struct hlua_txn *htxn;
6109
6110 MAY_LJMP(check_args(L, 3, "req_set_hdr"));
6111 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
6112
6113 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
6114 WILL_LJMP(lua_error(L));
6115
6116 hlua_http_del_hdr(L, &htxn->s->txn->req);
6117 return hlua_http_add_hdr(L, &htxn->s->txn->req);
6118}
6119
6120static int hlua_http_res_set_hdr(lua_State *L)
6121{
6122 struct hlua_txn *htxn;
6123
6124 MAY_LJMP(check_args(L, 3, "res_set_hdr"));
6125 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
6126
6127 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
6128 WILL_LJMP(lua_error(L));
6129
6130 hlua_http_del_hdr(L, &htxn->s->txn->rsp);
6131 return hlua_http_add_hdr(L, &htxn->s->txn->rsp);
6132}
6133
6134/* This function set the method. */
6135static int hlua_http_req_set_meth(lua_State *L)
6136{
6137 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
6138 size_t name_len;
6139 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
6140
6141 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
6142 WILL_LJMP(lua_error(L));
6143
6144 lua_pushboolean(L, http_req_replace_stline(0, name, name_len, htxn->p, htxn->s) != -1);
6145 return 1;
6146}
6147
6148/* This function set the method. */
6149static int hlua_http_req_set_path(lua_State *L)
6150{
6151 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
6152 size_t name_len;
6153 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
6154
6155 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
6156 WILL_LJMP(lua_error(L));
6157
6158 lua_pushboolean(L, http_req_replace_stline(1, name, name_len, htxn->p, htxn->s) != -1);
6159 return 1;
6160}
6161
6162/* This function set the query-string. */
6163static int hlua_http_req_set_query(lua_State *L)
6164{
6165 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
6166 size_t name_len;
6167 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
6168
6169 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
6170 WILL_LJMP(lua_error(L));
6171
6172 /* Check length. */
6173 if (name_len > trash.size - 1) {
6174 lua_pushboolean(L, 0);
6175 return 1;
6176 }
6177
6178 /* Add the mark question as prefix. */
6179 chunk_reset(&trash);
6180 trash.area[trash.data++] = '?';
6181 memcpy(trash.area + trash.data, name, name_len);
6182 trash.data += name_len;
6183
6184 lua_pushboolean(L,
6185 http_req_replace_stline(2, trash.area, trash.data, htxn->p, htxn->s) != -1);
6186 return 1;
6187}
6188
6189/* This function set the uri. */
6190static int hlua_http_req_set_uri(lua_State *L)
6191{
6192 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
6193 size_t name_len;
6194 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
6195
6196 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
6197 WILL_LJMP(lua_error(L));
6198
6199 lua_pushboolean(L, http_req_replace_stline(3, name, name_len, htxn->p, htxn->s) != -1);
6200 return 1;
6201}
6202
6203/* This function set the response code & optionally reason. */
6204static int hlua_http_res_set_status(lua_State *L)
6205{
6206 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
6207 unsigned int code = MAY_LJMP(luaL_checkinteger(L, 2));
6208 const char *str = MAY_LJMP(luaL_optlstring(L, 3, NULL, NULL));
6209 const struct ist reason = ist2(str, (str ? strlen(str) : 0));
6210
6211 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
6212 WILL_LJMP(lua_error(L));
6213
6214 http_res_set_status(code, reason, htxn->s);
6215 return 0;
6216}
6217
6218/*
6219 *
6220 *
6221 * Class HTTPMessage
6222 *
6223 *
6224 */
6225
6226/* Returns a struct http_msg if the stack entry "ud" is a class HTTPMessage,
6227 * otherwise it throws an error.
6228 */
6229__LJMP static struct http_msg *hlua_checkhttpmsg(lua_State *L, int ud)
6230{
6231 return MAY_LJMP(hlua_checkudata(L, ud, class_http_msg_ref));
6232}
6233
6234/* Creates and pushes on the stack a HTTP object according with a current TXN.
6235 */
Christopher Faulet78c35472020-02-26 17:14:08 +01006236static int hlua_http_msg_new(lua_State *L, struct http_msg *msg)
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006237{
6238 /* Check stack size. */
6239 if (!lua_checkstack(L, 3))
6240 return 0;
6241
6242 lua_newtable(L);
6243 lua_pushlightuserdata(L, msg);
6244 lua_rawseti(L, -2, 0);
6245
6246 /* Create the "channel" field that contains the request channel object. */
6247 lua_pushstring(L, "channel");
6248 if (!hlua_channel_new(L, msg->chn))
6249 return 0;
6250 lua_rawset(L, -3);
6251
6252 /* Pop a class stream metatable and affect it to the table. */
6253 lua_rawgeti(L, LUA_REGISTRYINDEX, class_http_msg_ref);
6254 lua_setmetatable(L, -2);
6255
6256 return 1;
6257}
6258
6259/* Helper function returning a filter attached to the HTTP message at the
6260 * position <ud> in the stack, filling the current offset and length of the
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006261 * filter. If no filter is attached, NULL is returned and <offset> and <len> are
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006262 * filled with output and input length respectively.
6263 */
6264static struct filter *hlua_http_msg_filter(lua_State *L, int ud, struct http_msg *msg, size_t *offset, size_t *len)
6265{
6266 struct channel *chn = msg->chn;
6267 struct htx *htx = htxbuf(&chn->buf);
6268 struct filter *filter = NULL;
6269
6270 *offset = co_data(msg->chn);
6271 *len = htx->data - co_data(msg->chn);
6272
6273 if (lua_getfield(L, ud, "__filter") == LUA_TLIGHTUSERDATA) {
6274 filter = lua_touserdata (L, -1);
6275 if (msg->msg_state >= HTTP_MSG_DATA) {
6276 struct hlua_flt_ctx *flt_ctx = filter->ctx;
6277
6278 *offset = flt_ctx->cur_off[CHN_IDX(chn)];
6279 *len = flt_ctx->cur_len[CHN_IDX(chn)];
6280 }
6281 }
6282
6283 lua_pop(L, 1);
6284 return filter;
6285}
6286
6287/* Returns true if the channel attached to the HTTP message is the response
6288 * channel.
6289 */
6290__LJMP static int hlua_http_msg_is_resp(lua_State *L)
6291{
6292 struct http_msg *msg;
6293
6294 MAY_LJMP(check_args(L, 1, "is_resp"));
6295 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6296
6297 lua_pushboolean(L, !!(msg->chn->flags & CF_ISRESP));
6298 return 1;
6299}
6300
6301/* Returns an array containing the elements status-line of the HTTP message. It relies
6302 * on hlua_http_get_stline().
6303 */
6304__LJMP static int hlua_http_msg_get_stline(lua_State *L)
6305{
6306 struct http_msg *msg;
6307 struct htx *htx;
6308 struct htx_sl *sl;
6309
6310 MAY_LJMP(check_args(L, 1, "get_stline"));
6311 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6312
6313 if (msg->msg_state > HTTP_MSG_BODY)
6314 WILL_LJMP(lua_error(L));
6315
6316 htx = htxbuf(&msg->chn->buf);
6317 sl = http_get_stline(htx);
6318 if (!sl)
6319 return 0;
6320 return hlua_http_get_stline(L, sl);
6321}
6322
6323/* Returns an array containing all headers of the HTTP message. it relies on
6324 * hlua_http_get_headers().
6325 */
6326__LJMP static int hlua_http_msg_get_headers(lua_State *L)
6327{
6328 struct http_msg *msg;
6329
6330 MAY_LJMP(check_args(L, 1, "get_headers"));
6331 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6332
6333 if (msg->msg_state > HTTP_MSG_BODY)
6334 WILL_LJMP(lua_error(L));
6335
6336 return hlua_http_get_headers(L, msg);
6337}
6338
6339/* Deletes all occurrences of an header in the HTTP message matching on its
6340 * name. It relies on hlua_http_del_hdr().
6341 */
6342__LJMP static int hlua_http_msg_del_hdr(lua_State *L)
6343{
6344 struct http_msg *msg;
6345
6346 MAY_LJMP(check_args(L, 2, "del_header"));
6347 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6348
6349 if (msg->msg_state > HTTP_MSG_BODY)
6350 WILL_LJMP(lua_error(L));
6351
6352 return hlua_http_del_hdr(L, msg);
6353}
6354
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006355/* Matches the full value line of all occurrences of an header in the HTTP
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006356 * message given its name against a regex and replaces it if it matches. It
6357 * relies on hlua_http_rep_hdr().
6358 */
6359__LJMP static int hlua_http_msg_rep_hdr(lua_State *L)
6360{
6361 struct http_msg *msg;
6362
6363 MAY_LJMP(check_args(L, 4, "rep_header"));
6364 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6365
6366 if (msg->msg_state > HTTP_MSG_BODY)
6367 WILL_LJMP(lua_error(L));
6368
6369 return hlua_http_rep_hdr(L, msg, 1);
6370}
6371
Ilya Shipitsinbd6b4be2021-10-15 16:18:21 +05006372/* Matches all comma-separated values of all occurrences of an header in the HTTP
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006373 * message given its name against a regex and replaces it if it matches. It
6374 * relies on hlua_http_rep_hdr().
6375 */
6376__LJMP static int hlua_http_msg_rep_val(lua_State *L)
6377{
6378 struct http_msg *msg;
6379
6380 MAY_LJMP(check_args(L, 4, "rep_value"));
6381 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6382
6383 if (msg->msg_state > HTTP_MSG_BODY)
6384 WILL_LJMP(lua_error(L));
6385
6386 return hlua_http_rep_hdr(L, msg, 0);
6387}
6388
6389/* Add an header in the HTTP message. It relies on hlua_http_add_hdr() */
6390__LJMP static int hlua_http_msg_add_hdr(lua_State *L)
6391{
6392 struct http_msg *msg;
6393
6394 MAY_LJMP(check_args(L, 3, "add_header"));
6395 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6396
6397 if (msg->msg_state > HTTP_MSG_BODY)
6398 WILL_LJMP(lua_error(L));
6399
6400 return hlua_http_add_hdr(L, msg);
6401}
6402
6403/* Add an header in the HTTP message removing existing headers with the same
6404 * name. It relies on hlua_http_del_hdr() and hlua_http_add_hdr().
6405 */
6406__LJMP static int hlua_http_msg_set_hdr(lua_State *L)
6407{
6408 struct http_msg *msg;
6409
6410 MAY_LJMP(check_args(L, 3, "set_header"));
6411 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6412
6413 if (msg->msg_state > HTTP_MSG_BODY)
6414 WILL_LJMP(lua_error(L));
6415
6416 hlua_http_del_hdr(L, msg);
6417 return hlua_http_add_hdr(L, msg);
6418}
6419
6420/* Rewrites the request method. It relies on http_req_replace_stline(). */
6421__LJMP static int hlua_http_msg_set_meth(lua_State *L)
6422{
6423 struct stream *s;
6424 struct http_msg *msg;
6425 const char *name;
6426 size_t name_len;
6427
6428 MAY_LJMP(check_args(L, 2, "set_method"));
6429 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6430 name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
6431
6432 if ((msg->chn->flags & CF_ISRESP) || msg->msg_state > HTTP_MSG_BODY)
6433 WILL_LJMP(lua_error(L));
6434
6435 s = chn_strm(msg->chn);
6436 lua_pushboolean(L, http_req_replace_stline(0, name, name_len, s->be, s) != -1);
6437 return 1;
6438}
6439
6440/* Rewrites the request path. It relies on http_req_replace_stline(). */
6441__LJMP static int hlua_http_msg_set_path(lua_State *L)
6442{
6443 struct stream *s;
6444 struct http_msg *msg;
6445 const char *name;
6446 size_t name_len;
6447
6448 MAY_LJMP(check_args(L, 2, "set_path"));
6449 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6450 name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
6451
6452 if ((msg->chn->flags & CF_ISRESP) || msg->msg_state > HTTP_MSG_BODY)
6453 WILL_LJMP(lua_error(L));
6454
6455 s = chn_strm(msg->chn);
6456 lua_pushboolean(L, http_req_replace_stline(1, name, name_len, s->be, s) != -1);
6457 return 1;
6458}
6459
6460/* Rewrites the request query-string. It relies on http_req_replace_stline(). */
6461__LJMP static int hlua_http_msg_set_query(lua_State *L)
6462{
6463 struct stream *s;
6464 struct http_msg *msg;
6465 const char *name;
6466 size_t name_len;
6467
6468 MAY_LJMP(check_args(L, 2, "set_query"));
6469 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6470 name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
6471
6472 if ((msg->chn->flags & CF_ISRESP) || msg->msg_state > HTTP_MSG_BODY)
6473 WILL_LJMP(lua_error(L));
6474
6475 /* Check length. */
6476 if (name_len > trash.size - 1) {
6477 lua_pushboolean(L, 0);
6478 return 1;
6479 }
6480
6481 /* Add the mark question as prefix. */
6482 chunk_reset(&trash);
6483 trash.area[trash.data++] = '?';
6484 memcpy(trash.area + trash.data, name, name_len);
6485 trash.data += name_len;
6486
6487 s = chn_strm(msg->chn);
6488 lua_pushboolean(L, http_req_replace_stline(2, trash.area, trash.data, s->be, s) != -1);
6489 return 1;
6490}
6491
6492/* Rewrites the request URI. It relies on http_req_replace_stline(). */
6493__LJMP static int hlua_http_msg_set_uri(lua_State *L)
6494{
6495 struct stream *s;
6496 struct http_msg *msg;
6497 const char *name;
6498 size_t name_len;
6499
6500 MAY_LJMP(check_args(L, 2, "set_uri"));
6501 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6502 name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
6503
6504 if ((msg->chn->flags & CF_ISRESP) || msg->msg_state > HTTP_MSG_BODY)
6505 WILL_LJMP(lua_error(L));
6506
6507 s = chn_strm(msg->chn);
6508 lua_pushboolean(L, http_req_replace_stline(3, name, name_len, s->be, s) != -1);
6509 return 1;
6510}
6511
6512/* Rewrites the response status code. It relies on http_res_set_status(). */
6513__LJMP static int hlua_http_msg_set_status(lua_State *L)
6514{
6515 struct http_msg *msg;
6516 unsigned int code;
6517 const char *reason;
6518 size_t reason_len;
6519
6520 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6521 code = MAY_LJMP(luaL_checkinteger(L, 2));
6522 reason = MAY_LJMP(luaL_optlstring(L, 3, NULL, &reason_len));
6523
6524 if (!(msg->chn->flags & CF_ISRESP) || msg->msg_state > HTTP_MSG_BODY)
6525 WILL_LJMP(lua_error(L));
6526
6527 lua_pushboolean(L, http_res_set_status(code, ist2(reason, reason_len), chn_strm(msg->chn)) != -1);
6528 return 1;
6529}
6530
6531/* Returns true if the HTTP message is full. */
6532__LJMP static int hlua_http_msg_is_full(lua_State *L)
6533{
6534 struct http_msg *msg;
6535
6536 MAY_LJMP(check_args(L, 1, "is_full"));
6537 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6538 lua_pushboolean(L, channel_full(msg->chn, 0));
6539 return 1;
6540}
6541
6542/* Returns true if the HTTP message may still receive data. */
6543__LJMP static int hlua_http_msg_may_recv(lua_State *L)
6544{
6545 struct http_msg *msg;
6546 struct htx *htx;
6547
6548 MAY_LJMP(check_args(L, 1, "may_recv"));
6549 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6550 htx = htxbuf(&msg->chn->buf);
6551 lua_pushboolean(L, (htx_expect_more(htx) && !channel_input_closed(msg->chn) && channel_may_recv(msg->chn)));
6552 return 1;
6553}
6554
6555/* Returns true if the HTTP message EOM was received */
6556__LJMP static int hlua_http_msg_is_eom(lua_State *L)
6557{
6558 struct http_msg *msg;
6559 struct htx *htx;
6560
6561 MAY_LJMP(check_args(L, 1, "may_recv"));
6562 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6563 htx = htxbuf(&msg->chn->buf);
6564 lua_pushboolean(L, !htx_expect_more(htx));
6565 return 1;
6566}
6567
6568/* Returns the number of bytes available in the input side of the HTTP
6569 * message. This function never fails.
6570 */
6571__LJMP static int hlua_http_msg_get_in_len(lua_State *L)
6572{
6573 struct http_msg *msg;
Christopher Fauleteae8afa2020-02-26 17:15:48 +01006574 size_t output, input;
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006575
6576 MAY_LJMP(check_args(L, 1, "input"));
6577 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
Christopher Fauleteae8afa2020-02-26 17:15:48 +01006578 hlua_http_msg_filter(L, 1, msg, &output, &input);
6579 lua_pushinteger(L, input);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006580 return 1;
6581}
6582
6583/* Returns the number of bytes available in the output side of the HTTP
6584 * message. This function never fails.
6585 */
6586__LJMP static int hlua_http_msg_get_out_len(lua_State *L)
6587{
6588 struct http_msg *msg;
Christopher Fauleteae8afa2020-02-26 17:15:48 +01006589 size_t output, input;
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006590
6591 MAY_LJMP(check_args(L, 1, "output"));
6592 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
Christopher Fauleteae8afa2020-02-26 17:15:48 +01006593 hlua_http_msg_filter(L, 1, msg, &output, &input);
6594 lua_pushinteger(L, output);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006595 return 1;
6596}
6597
6598/* Copies at most <len> bytes of DATA blocks from the HTTP message <msg>
6599 * starting at the offset <offset> and put it in a string LUA variables. It
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006600 * returns the built string length. It stops on the first non-DATA HTX
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006601 * block. This function is called during the payload filtering, so the headers
6602 * are already scheduled for output (from the filter point of view).
6603 */
6604static int _hlua_http_msg_dup(struct http_msg *msg, lua_State *L, size_t offset, size_t len)
6605{
6606 struct htx *htx = htxbuf(&msg->chn->buf);
6607 struct htx_blk *blk;
6608 struct htx_ret htxret;
6609 luaL_Buffer b;
6610 int ret = 0;
6611
6612 luaL_buffinit(L, &b);
6613 htxret = htx_find_offset(htx, offset);
6614 for (blk = htxret.blk, offset = htxret.ret; blk && len; blk = htx_get_next_blk(htx, blk)) {
6615 enum htx_blk_type type = htx_get_blk_type(blk);
6616 struct ist v;
6617
6618 switch (type) {
6619 case HTX_BLK_UNUSED:
6620 break;
6621
6622 case HTX_BLK_DATA:
6623 v = htx_get_blk_value(htx, blk);
Tim Duesterhusb113b5c2021-09-15 13:58:44 +02006624 v = istadv(v, offset);
Tim Duesterhus2471f5c2021-11-08 09:05:01 +01006625 v = isttrim(v, len);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006626
6627 luaL_addlstring(&b, v.ptr, v.len);
6628 ret += v.len;
6629 break;
6630
6631 default:
vishnu0af4bd72021-10-24 06:46:24 +05306632 if (!ret)
6633 goto no_data;
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006634 goto end;
6635 }
6636 offset = 0;
6637 }
6638
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006639end:
vishnu0af4bd72021-10-24 06:46:24 +05306640 if (!ret && (htx->flags & HTX_FL_EOM))
6641 goto no_data;
6642 luaL_pushresult(&b);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006643 return ret;
vishnu0af4bd72021-10-24 06:46:24 +05306644
6645 no_data:
6646 /* Remove the empty string and push nil on the stack */
6647 lua_pop(L, 1);
6648 lua_pushnil(L);
6649 return 0;
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006650}
6651
6652/* Copies the string <str> to the HTTP message <msg> at the offset
6653 * <offset>. This function returns -1 if data cannot be copied. Otherwise, it
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006654 * returns the amount of data written. This function is responsible to update
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006655 * the filter context.
6656 */
6657static int _hlua_http_msg_insert(struct http_msg *msg, struct filter *filter, struct ist str, size_t offset)
6658{
6659 struct htx *htx = htx_from_buf(&msg->chn->buf);
6660 struct htx_ret htxret;
6661 int /*max, */ret = 0;
6662
6663 /* Nothing to do, just return */
6664 if (unlikely(istlen(str) == 0))
6665 goto end;
6666
6667 if (istlen(str) > htx_free_data_space(htx)) {
6668 ret = -1;
6669 goto end;
6670 }
6671
6672 htxret = htx_find_offset(htx, offset);
6673 if (!htxret.blk || htx_get_blk_type(htxret.blk) != HTX_BLK_DATA) {
6674 if (!htx_add_last_data(htx, str))
6675 goto end;
6676 }
6677 else {
6678 struct ist v = htx_get_blk_value(htx, htxret.blk);
6679 v.ptr += htxret.ret;
6680 v.len = 0;
6681 if (!htx_replace_blk_value(htx, htxret.blk, v, str))
6682 goto end;
6683 }
6684 ret = str.len;
6685 if (ret) {
6686 struct hlua_flt_ctx *flt_ctx = filter->ctx;
6687 flt_update_offsets(filter, msg->chn, ret);
6688 flt_ctx->cur_len[CHN_IDX(msg->chn)] += ret;
6689 }
6690
6691 end:
6692 htx_to_buf(htx, &msg->chn->buf);
6693 return ret;
6694}
6695
6696/* Helper function removing at most <len> bytes of DATA blocks at the absolute
6697 * position <offset>. It stops on the first non-DATA HTX block. This function is
6698 * called during the payload filtering, so the headers are already scheduled for
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006699 * output (from the filter point of view). This function is responsible to
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006700 * update the filter context.
6701 */
6702static void _hlua_http_msg_delete(struct http_msg *msg, struct filter *filter, size_t offset, size_t len)
6703{
6704 struct hlua_flt_ctx *flt_ctx = filter->ctx;
6705 struct htx *htx = htx_from_buf(&msg->chn->buf);
6706 struct htx_blk *blk;
6707 struct htx_ret htxret;
6708 size_t ret = 0;
6709
6710 /* Be sure <len> is always the amount of DATA to remove */
6711 if (htx->data == offset+len && htx_get_tail_type(htx) == HTX_BLK_DATA) {
Aurelien DARRAGONbcbcf982022-09-28 19:08:15 +02006712 /* When htx tail type == HTX_BLK_DATA, no need to take care
6713 * of special blocks like HTX_BLK_EOT.
6714 * We simply truncate after offset
6715 * (truncate targeted blk and discard the following ones)
6716 */
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006717 htx_truncate(htx, offset);
6718 ret = len;
6719 goto end;
6720 }
6721
6722 htxret = htx_find_offset(htx, offset);
6723 blk = htxret.blk;
6724 if (htxret.ret) {
Aurelien DARRAGONbcbcf982022-09-28 19:08:15 +02006725 /* dealing with offset: we need to trim targeted blk */
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006726 struct ist v;
6727
6728 if (htx_get_blk_type(blk) != HTX_BLK_DATA)
6729 goto end;
Aurelien DARRAGONbcbcf982022-09-28 19:08:15 +02006730
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006731 v = htx_get_blk_value(htx, blk);
Tim Duesterhusa029d782022-10-08 12:33:18 +02006732 v = istadv(v, htxret.ret);
Aurelien DARRAGONbcbcf982022-09-28 19:08:15 +02006733
Tim Duesterhus2471f5c2021-11-08 09:05:01 +01006734 v = isttrim(v, len);
Aurelien DARRAGONbcbcf982022-09-28 19:08:15 +02006735 /* trimming data in blk: discard everything after the offset
6736 * (replace 'v' with 'IST_NULL')
6737 */
Tim Duesterhusb113b5c2021-09-15 13:58:44 +02006738 blk = htx_replace_blk_value(htx, blk, v, IST_NULL);
Aurelien DARRAGONbcbcf982022-09-28 19:08:15 +02006739 if (blk && v.len < len) {
6740 /* In this case, caller wants to keep removing data,
6741 * but we need to spare current blk
6742 * because it was already trimmed
6743 */
6744 blk = htx_get_next_blk(htx, blk);
6745 }
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006746 len -= v.len;
6747 ret += v.len;
6748 }
6749
6750
6751 while (blk && len) {
Aurelien DARRAGONbcbcf982022-09-28 19:08:15 +02006752 /* there is more data that needs to be discarded */
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006753 enum htx_blk_type type = htx_get_blk_type(blk);
6754 uint32_t sz = htx_get_blksz(blk);
6755
6756 switch (type) {
6757 case HTX_BLK_UNUSED:
6758 break;
6759
6760 case HTX_BLK_DATA:
6761 if (len < sz) {
Aurelien DARRAGONbcbcf982022-09-28 19:08:15 +02006762 /* don't discard whole blk, only part of it
6763 * (from the beginning)
6764 */
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006765 htx_cut_data_blk(htx, blk, len);
6766 ret += len;
6767 goto end;
6768 }
6769 break;
6770
6771 default:
Aurelien DARRAGONbcbcf982022-09-28 19:08:15 +02006772 /* HTX_BLK_EOT blk won't be removed */
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006773 goto end;
6774 }
6775
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006776 /* Remove all the data block */
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006777 len -= sz;
6778 ret += sz;
6779 blk = htx_remove_blk(htx, blk);
6780 }
6781
6782end:
6783 flt_update_offsets(filter, msg->chn, -ret);
6784 flt_ctx->cur_len[CHN_IDX(msg->chn)] -= ret;
6785 /* WARNING: we don't call htx_to_buf() on purpose, because we don't want
6786 * to loose the EOM flag if the message is empty.
6787 */
6788}
6789
6790/* Copies input data found in an HTTP message. Unlike the channel function used
6791 * to duplicate raw data, this one can only be called inside a filter, from
6792 * http_payload callback. So it cannot yield. An exception is returned if it is
6793 * called from another callback. If nothing was copied, a nil value is pushed on
6794 * the stack.
6795 */
6796__LJMP static int hlua_http_msg_get_body(lua_State *L)
6797{
6798 struct http_msg *msg;
6799 struct filter *filter;
6800 size_t output, input;
6801 int offset, len;
6802
6803 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
6804 WILL_LJMP(luaL_error(L, "'data' expects at most 2 arguments"));
6805 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6806
6807 if (msg->msg_state < HTTP_MSG_DATA)
6808 WILL_LJMP(lua_error(L));
6809
6810 filter = hlua_http_msg_filter(L, 1, msg, &output, &input);
6811 if (!filter || !hlua_filter_from_payload(filter))
6812 WILL_LJMP(lua_error(L));
6813
6814 if (!ci_data(msg->chn) && channel_input_closed(msg->chn)) {
6815 lua_pushnil(L);
6816 return 1;
6817 }
6818
6819 offset = output;
6820 if (lua_gettop(L) > 1) {
6821 offset = MAY_LJMP(luaL_checkinteger(L, 2));
6822 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02006823 offset = MAX(0, (int)input + offset);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006824 offset += output;
6825 if (offset < output || offset > input + output) {
6826 lua_pushfstring(L, "offset out of range.");
6827 WILL_LJMP(lua_error(L));
6828 }
6829 }
6830 len = output + input - offset;
6831 if (lua_gettop(L) == 3) {
6832 len = MAY_LJMP(luaL_checkinteger(L, 3));
6833 if (!len)
6834 goto dup;
6835 if (len == -1)
6836 len = global.tune.bufsize;
6837 if (len < 0) {
6838 lua_pushfstring(L, "length out of range.");
6839 WILL_LJMP(lua_error(L));
6840 }
6841 }
6842
6843 dup:
6844 _hlua_http_msg_dup(msg, L, offset, len);
6845 return 1;
6846}
6847
6848/* Appends a string to the HTTP message, after all existing DATA blocks but
6849 * before the trailers, if any. It returns the amount of data written or -1 if
6850 * nothing was copied. Unlike the channel function used to append data, this one
6851 * can only be called inside a filter, from http_payload callback. So it cannot
6852 * yield. An exception is returned if it is called from another callback.
6853 */
6854__LJMP static int hlua_http_msg_append(lua_State *L)
6855{
6856 struct http_msg *msg;
6857 struct filter *filter;
6858 const char *str;
6859 size_t offset, len, sz;
6860 int ret;
6861
6862 MAY_LJMP(check_args(L, 2, "append"));
6863 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6864
6865 if (msg->msg_state < HTTP_MSG_DATA)
6866 WILL_LJMP(lua_error(L));
6867
6868 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
6869 filter = hlua_http_msg_filter(L, 1, msg, &offset, &len);
6870 if (!filter || !hlua_filter_from_payload(filter))
6871 WILL_LJMP(lua_error(L));
6872
6873 ret = _hlua_http_msg_insert(msg, filter, ist2(str, sz), offset+len);
6874 lua_pushinteger(L, ret);
6875 return 1;
6876}
6877
6878/* Prepends a string to the HTTP message, before all existing DATA blocks. It
6879 * returns the amount of data written or -1 if nothing was copied. Unlike the
6880 * channel function used to prepend data, this one can only be called inside a
6881 * filter, from http_payload callback. So it cannot yield. An exception is
6882 * returned if it is called from another callback.
6883 */
6884__LJMP static int hlua_http_msg_prepend(lua_State *L)
6885{
6886 struct http_msg *msg;
6887 struct filter *filter;
6888 const char *str;
6889 size_t offset, len, sz;
6890 int ret;
6891
6892 MAY_LJMP(check_args(L, 2, "prepend"));
6893 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006894
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006895 if (msg->msg_state < HTTP_MSG_DATA)
6896 WILL_LJMP(lua_error(L));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006897
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006898 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
6899 filter = hlua_http_msg_filter(L, 1, msg, &offset, &len);
6900 if (!filter || !hlua_filter_from_payload(filter))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006901 WILL_LJMP(lua_error(L));
6902
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006903 ret = _hlua_http_msg_insert(msg, filter, ist2(str, sz), offset);
6904 lua_pushinteger(L, ret);
6905 return 1;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006906}
6907
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006908/* Inserts a string to the HTTP message at a given offset. By default the string
6909 * is appended at the end of DATA blocks. It returns the amount of data written
6910 * or -1 if nothing was copied. Unlike the channel function used to insert data,
6911 * this one can only be called inside a filter, from http_payload callback. So
6912 * it cannot yield. An exception is returned if it is called from another
6913 * callback.
6914 */
6915__LJMP static int hlua_http_msg_insert_data(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006916{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006917 struct http_msg *msg;
6918 struct filter *filter;
6919 const char *str;
6920 size_t input, output, sz;
6921 int offset;
6922 int ret;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006923
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006924 if (lua_gettop(L) < 2 || lua_gettop(L) > 3)
6925 WILL_LJMP(luaL_error(L, "'insert' expects at least 1 argument and at most 2 arguments"));
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006926 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006927
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006928 if (msg->msg_state < HTTP_MSG_DATA)
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006929 WILL_LJMP(lua_error(L));
6930
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006931 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
Aurelien DARRAGON7fdba0a2022-09-28 16:03:45 +02006932 filter = hlua_http_msg_filter(L, 1, msg, &output, &input);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006933 if (!filter || !hlua_filter_from_payload(filter))
6934 WILL_LJMP(lua_error(L));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006935
Aurelien DARRAGON7fdba0a2022-09-28 16:03:45 +02006936 offset = output;
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006937 if (lua_gettop(L) > 2) {
6938 offset = MAY_LJMP(luaL_checkinteger(L, 3));
6939 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02006940 offset = MAX(0, (int)input + offset);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006941 offset += output;
Aurelien DARRAGON7fdba0a2022-09-28 16:03:45 +02006942 if (offset > output + input) {
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006943 lua_pushfstring(L, "offset out of range.");
6944 WILL_LJMP(lua_error(L));
6945 }
6946 }
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006947
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006948 ret = _hlua_http_msg_insert(msg, filter, ist2(str, sz), offset);
6949 lua_pushinteger(L, ret);
6950 return 1;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006951}
6952
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006953/* Removes a given amount of data from the HTTP message at a given offset. By
6954 * default all DATA blocks are removed. It returns the amount of data
6955 * removed. Unlike the channel function used to remove data, this one can only
6956 * be called inside a filter, from http_payload callback. So it cannot yield. An
6957 * exception is returned if it is called from another callback.
6958 */
6959__LJMP static int hlua_http_msg_del_data(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006960{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006961 struct http_msg *msg;
6962 struct filter *filter;
6963 size_t input, output;
6964 int offset, len;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006965
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006966 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
Boyang Lie0c54352022-05-10 17:47:23 +00006967 WILL_LJMP(luaL_error(L, "'remove' expects at most 2 arguments"));
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006968 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006969
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006970 if (msg->msg_state < HTTP_MSG_DATA)
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006971 WILL_LJMP(lua_error(L));
6972
Aurelien DARRAGONd7c71b02022-09-28 15:52:18 +02006973 filter = hlua_http_msg_filter(L, 1, msg, &output, &input);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006974 if (!filter || !hlua_filter_from_payload(filter))
6975 WILL_LJMP(lua_error(L));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006976
Aurelien DARRAGONd7c71b02022-09-28 15:52:18 +02006977 offset = output;
Boyang Lie0c54352022-05-10 17:47:23 +00006978 if (lua_gettop(L) > 1) {
6979 offset = MAY_LJMP(luaL_checkinteger(L, 2));
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006980 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02006981 offset = MAX(0, (int)input + offset);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006982 offset += output;
Aurelien DARRAGONd7c71b02022-09-28 15:52:18 +02006983 if (offset > output + input) {
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006984 lua_pushfstring(L, "offset out of range.");
6985 WILL_LJMP(lua_error(L));
6986 }
6987 }
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006988
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006989 len = output + input - offset;
Boyang Lie0c54352022-05-10 17:47:23 +00006990 if (lua_gettop(L) == 3) {
6991 len = MAY_LJMP(luaL_checkinteger(L, 3));
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006992 if (!len)
6993 goto end;
6994 if (len == -1)
6995 len = output + input - offset;
6996 if (len < 0 || offset + len > output + input) {
6997 lua_pushfstring(L, "length out of range.");
6998 WILL_LJMP(lua_error(L));
6999 }
7000 }
7001
7002 _hlua_http_msg_delete(msg, filter, offset, len);
7003
7004 end:
7005 lua_pushinteger(L, len);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007006 return 1;
7007}
7008
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05007009/* Replaces a given amount of data at the given offset by a string. By default,
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007010 * all remaining data are removed, accordingly to the filter context. It returns
7011 * the amount of data written or -1 if nothing was copied. Unlike the channel
7012 * function used to replace data, this one can only be called inside a filter,
7013 * from http_payload callback. So it cannot yield. An exception is returned if
7014 * it is called from another callback.
7015 */
7016__LJMP static int hlua_http_msg_set_data(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007017{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007018 struct http_msg *msg;
7019 struct filter *filter;
7020 struct htx *htx;
7021 const char *str;
7022 size_t input, output, sz;
7023 int offset, len;
7024 int ret;
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02007025
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007026 if (lua_gettop(L) < 2 || lua_gettop(L) > 4)
7027 WILL_LJMP(luaL_error(L, "'set' expects at least 1 argument and at most 3 arguments"));
7028 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
7029
7030 if (msg->msg_state < HTTP_MSG_DATA)
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02007031 WILL_LJMP(lua_error(L));
7032
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007033 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
7034 filter = hlua_http_msg_filter(L, 1, msg, &output, &input);
7035 if (!filter || !hlua_filter_from_payload(filter))
7036 WILL_LJMP(lua_error(L));
7037
7038 offset = output;
7039 if (lua_gettop(L) > 2) {
7040 offset = MAY_LJMP(luaL_checkinteger(L, 3));
7041 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02007042 offset = MAX(0, (int)input + offset);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007043 offset += output;
7044 if (offset < output || offset > input + output) {
7045 lua_pushfstring(L, "offset out of range.");
7046 WILL_LJMP(lua_error(L));
7047 }
7048 }
7049
7050 len = output + input - offset;
7051 if (lua_gettop(L) == 4) {
7052 len = MAY_LJMP(luaL_checkinteger(L, 4));
7053 if (!len)
7054 goto set;
7055 if (len == -1)
7056 len = output + input - offset;
7057 if (len < 0 || offset + len > output + input) {
7058 lua_pushfstring(L, "length out of range.");
7059 WILL_LJMP(lua_error(L));
7060 }
7061 }
7062
7063 set:
7064 /* Be sure we can copied the string once input data will be removed. */
7065 htx = htx_from_buf(&msg->chn->buf);
7066 if (sz > htx_free_data_space(htx) + len)
7067 lua_pushinteger(L, -1);
7068 else {
7069 _hlua_http_msg_delete(msg, filter, offset, len);
7070 ret = _hlua_http_msg_insert(msg, filter, ist2(str, sz), offset);
7071 lua_pushinteger(L, ret);
7072 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007073 return 1;
7074}
7075
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007076/* Prepends data into an HTTP message and forward it, from the filter point of
7077 * view. It returns the amount of data written or -1 if nothing was sent. Unlike
7078 * the channel function used to send data, this one can only be called inside a
7079 * filter, from http_payload callback. So it cannot yield. An exception is
7080 * returned if it is called from another callback.
7081 */
7082__LJMP static int hlua_http_msg_send(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007083{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007084 struct http_msg *msg;
7085 struct filter *filter;
7086 struct htx *htx;
7087 const char *str;
7088 size_t offset, len, sz;
7089 int ret;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007090
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007091 MAY_LJMP(check_args(L, 2, "send"));
7092 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
7093
7094 if (msg->msg_state < HTTP_MSG_DATA)
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02007095 WILL_LJMP(lua_error(L));
7096
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007097 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
7098 filter = hlua_http_msg_filter(L, 1, msg, &offset, &len);
7099 if (!filter || !hlua_filter_from_payload(filter))
7100 WILL_LJMP(lua_error(L));
7101
7102 /* Return an error if the channel's output is closed */
7103 if (unlikely(channel_output_closed(msg->chn))) {
7104 lua_pushinteger(L, -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007105 return 1;
7106 }
7107
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007108 htx = htx_from_buf(&msg->chn->buf);
7109 if (sz > htx_free_data_space(htx)) {
7110 lua_pushinteger(L, -1);
7111 return 1;
7112 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007113
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007114 ret = _hlua_http_msg_insert(msg, filter, ist2(str, sz), offset);
7115 if (ret > 0) {
7116 struct hlua_flt_ctx *flt_ctx = filter->ctx;
7117
7118 FLT_OFF(filter, msg->chn) += ret;
7119 flt_ctx->cur_len[CHN_IDX(msg->chn)] -= ret;
7120 flt_ctx->cur_off[CHN_IDX(msg->chn)] += ret;
7121 }
7122
7123 lua_pushinteger(L, ret);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007124 return 1;
7125}
7126
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007127/* Forwards a given amount of bytes. It return -1 if the channel's output is
7128 * closed. Otherwise, it returns the number of bytes forwarded. Unlike the
7129 * channel function used to forward data, this one can only be called inside a
7130 * filter, from http_payload callback. So it cannot yield. An exception is
7131 * returned if it is called from another callback. All other functions deal with
7132 * DATA block, this one not.
7133*/
7134__LJMP static int hlua_http_msg_forward(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007135{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007136 struct http_msg *msg;
7137 struct filter *filter;
7138 size_t offset, len;
7139 int fwd, ret = 0;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007140
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007141 MAY_LJMP(check_args(L, 2, "forward"));
7142 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
7143
7144 if (msg->msg_state < HTTP_MSG_DATA)
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02007145 WILL_LJMP(lua_error(L));
7146
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007147 fwd = MAY_LJMP(luaL_checkinteger(L, 2));
7148 filter = hlua_http_msg_filter(L, 1, msg, &offset, &len);
7149 if (!filter || !hlua_filter_from_payload(filter))
7150 WILL_LJMP(lua_error(L));
7151
7152 /* Nothing to do, just return */
7153 if (!fwd)
7154 goto end;
7155
7156 /* Return an error if the channel's output is closed */
7157 if (unlikely(channel_output_closed(msg->chn))) {
7158 ret = -1;
7159 goto end;
7160 }
7161
7162 ret = fwd;
7163 if (ret > len)
7164 ret = len;
7165
7166 if (ret) {
7167 struct hlua_flt_ctx *flt_ctx = filter->ctx;
7168
7169 FLT_OFF(filter, msg->chn) += ret;
7170 flt_ctx->cur_off[CHN_IDX(msg->chn)] += ret;
7171 flt_ctx->cur_len[CHN_IDX(msg->chn)] -= ret;
7172 }
7173
7174 end:
7175 lua_pushinteger(L, ret);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007176 return 1;
7177}
7178
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007179/* Set EOM flag on the HTX message.
7180 *
7181 * NOTE: Not sure it is a good idea to manipulate this flag but for now I don't
7182 * really know how to do without this feature.
7183 */
7184__LJMP static int hlua_http_msg_set_eom(lua_State *L)
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02007185{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007186 struct http_msg *msg;
7187 struct htx *htx;
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02007188
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007189 MAY_LJMP(check_args(L, 1, "set_eom"));
7190 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
7191 htx = htxbuf(&msg->chn->buf);
7192 htx->flags |= HTX_FL_EOM;
7193 return 0;
7194}
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02007195
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007196/* Unset EOM flag on the HTX message.
7197 *
7198 * NOTE: Not sure it is a good idea to manipulate this flag but for now I don't
7199 * really know how to do without this feature.
7200 */
7201__LJMP static int hlua_http_msg_unset_eom(lua_State *L)
7202{
7203 struct http_msg *msg;
7204 struct htx *htx;
7205
7206 MAY_LJMP(check_args(L, 1, "set_eom"));
7207 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
7208 htx = htxbuf(&msg->chn->buf);
7209 htx->flags &= ~HTX_FL_EOM;
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02007210 return 0;
7211}
7212
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007213/*
7214 *
7215 *
William Lallemand3956c4e2021-09-21 16:25:15 +02007216 * Class HTTPClient
7217 *
7218 *
7219 */
7220__LJMP static struct hlua_httpclient *hlua_checkhttpclient(lua_State *L, int ud)
7221{
7222 return MAY_LJMP(hlua_checkudata(L, ud, class_httpclient_ref));
7223}
7224
William Lallemandf77f1de2021-09-28 19:10:38 +02007225
7226/* stops the httpclient and ask it to kill itself */
7227__LJMP static int hlua_httpclient_gc(lua_State *L)
7228{
7229 struct hlua_httpclient *hlua_hc;
7230
7231 MAY_LJMP(check_args(L, 1, "__gc"));
7232
7233 hlua_hc = MAY_LJMP(hlua_checkhttpclient(L, 1));
7234
Aurelien DARRAGON3ffbf382023-02-09 17:02:57 +01007235 if (MT_LIST_DELETE(&hlua_hc->by_hlua)) {
7236 /* we won the race against hlua_httpclient_destroy_all() */
William Lallemandbb581422022-10-20 10:57:28 +02007237 httpclient_stop_and_destroy(hlua_hc->hc);
Aurelien DARRAGON3ffbf382023-02-09 17:02:57 +01007238 hlua_hc->hc = NULL;
7239 }
William Lallemandf77f1de2021-09-28 19:10:38 +02007240
7241 return 0;
7242}
7243
7244
William Lallemand3956c4e2021-09-21 16:25:15 +02007245__LJMP static int hlua_httpclient_new(lua_State *L)
7246{
7247 struct hlua_httpclient *hlua_hc;
7248 struct hlua *hlua;
7249
7250 /* Get hlua struct, or NULL if we execute from main lua state */
7251 hlua = hlua_gethlua(L);
7252 if (!hlua)
7253 return 0;
7254
7255 /* Check stack size. */
7256 if (!lua_checkstack(L, 3)) {
7257 hlua_pusherror(L, "httpclient: full stack");
7258 goto err;
7259 }
7260 /* Create the object: obj[0] = userdata. */
7261 lua_newtable(L);
7262 hlua_hc = MAY_LJMP(lua_newuserdata(L, sizeof(*hlua_hc)));
7263 lua_rawseti(L, -2, 0);
7264 memset(hlua_hc, 0, sizeof(*hlua_hc));
7265
7266 hlua_hc->hc = httpclient_new(hlua, 0, IST_NULL);
7267 if (!hlua_hc->hc)
7268 goto err;
7269
Aurelien DARRAGON3ffbf382023-02-09 17:02:57 +01007270 MT_LIST_APPEND(&hlua->hc_list, &hlua_hc->by_hlua);
William Lallemandbb581422022-10-20 10:57:28 +02007271
William Lallemand3956c4e2021-09-21 16:25:15 +02007272 /* Pop a class stream metatable and affect it to the userdata. */
7273 lua_rawgeti(L, LUA_REGISTRYINDEX, class_httpclient_ref);
7274 lua_setmetatable(L, -2);
7275
7276 return 1;
7277
7278 err:
7279 WILL_LJMP(lua_error(L));
7280 return 0;
7281}
7282
7283
7284/*
7285 * Callback of the httpclient, this callback wakes the lua task up, once the
7286 * httpclient receives some data
7287 *
7288 */
7289
William Lallemandbd5739e2021-10-28 15:41:38 +02007290static void hlua_httpclient_cb(struct httpclient *hc)
William Lallemand3956c4e2021-09-21 16:25:15 +02007291{
7292 struct hlua *hlua = hc->caller;
7293
7294 if (!hlua || !hlua->task)
7295 return;
7296
7297 task_wakeup(hlua->task, TASK_WOKEN_MSG);
7298}
7299
7300/*
William Lallemandd7df73a2021-09-23 17:54:00 +02007301 * Fill the lua stack with headers from the httpclient response
7302 * This works the same way as the hlua_http_get_headers() function
7303 */
7304__LJMP static int hlua_httpclient_get_headers(lua_State *L, struct hlua_httpclient *hlua_hc)
7305{
7306 struct http_hdr *hdr;
7307
7308 lua_newtable(L);
7309
William Lallemandef574b22021-10-05 16:19:31 +02007310 for (hdr = hlua_hc->hc->res.hdrs; hdr && isttest(hdr->n); hdr++) {
William Lallemandd7df73a2021-09-23 17:54:00 +02007311 struct ist n, v;
7312 int len;
7313
7314 n = hdr->n;
7315 v = hdr->v;
7316
7317 /* Check for existing entry:
7318 * assume that the table is on the top of the stack, and
7319 * push the key in the stack, the function lua_gettable()
7320 * perform the lookup.
7321 */
7322
7323 lua_pushlstring(L, n.ptr, n.len);
7324 lua_gettable(L, -2);
7325
7326 switch (lua_type(L, -1)) {
7327 case LUA_TNIL:
7328 /* Table not found, create it. */
7329 lua_pop(L, 1); /* remove the nil value. */
7330 lua_pushlstring(L, n.ptr, n.len); /* push the header name as key. */
7331 lua_newtable(L); /* create and push empty table. */
7332 lua_pushlstring(L, v.ptr, v.len); /* push header value. */
7333 lua_rawseti(L, -2, 0); /* index header value (pop it). */
7334 lua_rawset(L, -3); /* index new table with header name (pop the values). */
7335 break;
7336
7337 case LUA_TTABLE:
7338 /* Entry found: push the value in the table. */
7339 len = lua_rawlen(L, -1);
7340 lua_pushlstring(L, v.ptr, v.len); /* push header value. */
7341 lua_rawseti(L, -2, len+1); /* index header value (pop it). */
7342 lua_pop(L, 1); /* remove the table (it is stored in the main table). */
7343 break;
7344
7345 default:
7346 /* Other cases are errors. */
7347 hlua_pusherror(L, "internal error during the parsing of headers.");
7348 WILL_LJMP(lua_error(L));
7349 }
7350 }
7351 return 1;
7352}
7353
7354/*
William Lallemand746e6f32021-10-06 10:57:44 +02007355 * Allocate and return an array of http_hdr ist extracted from the <headers> lua table
7356 *
7357 * Caller must free the result
7358 */
7359struct http_hdr *hlua_httpclient_table_to_hdrs(lua_State *L)
7360{
7361 struct http_hdr hdrs[global.tune.max_http_hdr];
7362 struct http_hdr *result = NULL;
7363 uint32_t hdr_num = 0;
7364
7365 lua_pushnil(L);
7366 while (lua_next(L, -2) != 0) {
7367 struct ist name, value;
7368 const char *n, *v;
7369 size_t nlen, vlen;
7370
7371 if (!lua_isstring(L, -2) || !lua_istable(L, -1)) {
7372 /* Skip element if the key is not a string or if the value is not a table */
7373 goto next_hdr;
7374 }
7375
7376 n = lua_tolstring(L, -2, &nlen);
7377 name = ist2(n, nlen);
7378
7379 /* Loop on header's values */
7380 lua_pushnil(L);
7381 while (lua_next(L, -2)) {
7382 if (!lua_isstring(L, -1)) {
7383 /* Skip the value if it is not a string */
7384 goto next_value;
7385 }
7386
7387 v = lua_tolstring(L, -1, &vlen);
7388 value = ist2(v, vlen);
7389 name = ist2(n, nlen);
7390
7391 hdrs[hdr_num].n = istdup(name);
7392 hdrs[hdr_num].v = istdup(value);
7393
7394 hdr_num++;
7395
7396 next_value:
7397 lua_pop(L, 1);
7398 }
7399
7400 next_hdr:
7401 lua_pop(L, 1);
7402
7403 }
7404
7405 if (hdr_num) {
7406 /* alloc and copy the headers in the httpclient struct */
Tim Duesterhus16cc16d2021-11-06 15:14:45 +01007407 result = calloc((hdr_num + 1), sizeof(*result));
William Lallemand746e6f32021-10-06 10:57:44 +02007408 if (!result)
7409 goto skip_headers;
7410 memcpy(result, hdrs, sizeof(struct http_hdr) * (hdr_num + 1));
7411
7412 result[hdr_num].n = IST_NULL;
7413 result[hdr_num].v = IST_NULL;
7414 }
7415
7416skip_headers:
William Lallemand746e6f32021-10-06 10:57:44 +02007417
7418 return result;
7419}
7420
7421
William Lallemandbd5739e2021-10-28 15:41:38 +02007422/*
7423 * For each yield, checks if there is some data in the httpclient and push them
7424 * in the lua buffer, once the httpclient finished its job, push the result on
7425 * the stack
7426 */
7427__LJMP static int hlua_httpclient_rcv_yield(lua_State *L, int status, lua_KContext ctx)
7428{
7429 struct buffer *tr;
7430 int res;
7431 struct hlua *hlua = hlua_gethlua(L);
7432 struct hlua_httpclient *hlua_hc = hlua_checkhttpclient(L, 1);
7433
7434
7435 tr = get_trash_chunk();
7436
7437 res = httpclient_res_xfer(hlua_hc->hc, tr);
7438 luaL_addlstring(&hlua_hc->b, b_orig(tr), res);
7439
7440 if (!httpclient_data(hlua_hc->hc) && httpclient_ended(hlua_hc->hc)) {
7441
7442 luaL_pushresult(&hlua_hc->b);
7443 lua_settable(L, -3);
7444
7445 lua_pushstring(L, "status");
7446 lua_pushinteger(L, hlua_hc->hc->res.status);
7447 lua_settable(L, -3);
7448
7449
7450 lua_pushstring(L, "reason");
7451 lua_pushlstring(L, hlua_hc->hc->res.reason.ptr, hlua_hc->hc->res.reason.len);
7452 lua_settable(L, -3);
7453
7454 lua_pushstring(L, "headers");
7455 hlua_httpclient_get_headers(L, hlua_hc);
7456 lua_settable(L, -3);
7457
7458 return 1;
7459 }
7460
7461 if (httpclient_data(hlua_hc->hc))
7462 task_wakeup(hlua->task, TASK_WOKEN_MSG);
7463
7464 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_httpclient_rcv_yield, TICK_ETERNITY, 0));
7465
7466 return 0;
7467}
7468
7469/*
7470 * Call this when trying to stream a body during a request
7471 */
7472__LJMP static int hlua_httpclient_snd_yield(lua_State *L, int status, lua_KContext ctx)
7473{
7474 struct hlua *hlua;
7475 struct hlua_httpclient *hlua_hc = hlua_checkhttpclient(L, 1);
7476 const char *body_str = NULL;
7477 int ret;
7478 int end = 0;
7479 size_t buf_len;
7480 size_t to_send = 0;
7481
7482 hlua = hlua_gethlua(L);
7483
7484 if (!hlua || !hlua->task)
7485 WILL_LJMP(luaL_error(L, "The 'get' function is only allowed in "
7486 "'frontend', 'backend' or 'task'"));
7487
7488 ret = lua_getfield(L, -1, "body");
7489 if (ret != LUA_TSTRING)
7490 goto rcv;
7491
7492 body_str = lua_tolstring(L, -1, &buf_len);
7493 lua_pop(L, 1);
7494
Christopher Fauletfc591292022-01-12 14:46:03 +01007495 to_send = buf_len - hlua_hc->sent;
William Lallemandbd5739e2021-10-28 15:41:38 +02007496
7497 if ((hlua_hc->sent + to_send) >= buf_len)
7498 end = 1;
7499
7500 /* the end flag is always set since we are using the whole remaining size */
7501 hlua_hc->sent += httpclient_req_xfer(hlua_hc->hc, ist2(body_str + hlua_hc->sent, to_send), end);
7502
7503 if (buf_len > hlua_hc->sent) {
7504 /* still need to process the buffer */
7505 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_httpclient_snd_yield, TICK_ETERNITY, 0));
7506 } else {
7507 goto rcv;
7508 /* we sent the whole request buffer we can recv */
7509 }
7510 return 0;
7511
7512rcv:
7513
7514 /* we return a "res" object */
7515 lua_newtable(L);
7516
William Lallemandbd5739e2021-10-28 15:41:38 +02007517 lua_pushstring(L, "body");
William Lallemandd1187eb2021-11-02 10:40:06 +01007518 luaL_buffinit(L, &hlua_hc->b);
William Lallemandbd5739e2021-10-28 15:41:38 +02007519
William Lallemand933fe392021-11-04 09:45:58 +01007520 task_wakeup(hlua->task, TASK_WOKEN_MSG);
William Lallemandbd5739e2021-10-28 15:41:38 +02007521 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_httpclient_rcv_yield, TICK_ETERNITY, 0));
7522
7523 return 1;
7524}
William Lallemand746e6f32021-10-06 10:57:44 +02007525
William Lallemand3956c4e2021-09-21 16:25:15 +02007526/*
William Lallemanddc2cc902021-10-26 11:43:26 +02007527 * Send an HTTP request and wait for a response
William Lallemand3956c4e2021-09-21 16:25:15 +02007528 */
7529
William Lallemanddc2cc902021-10-26 11:43:26 +02007530__LJMP static int hlua_httpclient_send(lua_State *L, enum http_meth_t meth)
William Lallemand3956c4e2021-09-21 16:25:15 +02007531{
7532 struct hlua_httpclient *hlua_hc;
William Lallemand746e6f32021-10-06 10:57:44 +02007533 struct http_hdr *hdrs = NULL;
7534 struct http_hdr *hdrs_i = NULL;
William Lallemand3956c4e2021-09-21 16:25:15 +02007535 struct hlua *hlua;
William Lallemand746e6f32021-10-06 10:57:44 +02007536 const char *url_str = NULL;
William Lallemanddec25c32021-10-25 19:48:37 +02007537 const char *body_str = NULL;
Christopher Faulet380ae9c2022-10-14 14:57:04 +02007538 size_t buf_len = 0;
William Lallemand746e6f32021-10-06 10:57:44 +02007539 int ret;
William Lallemand3956c4e2021-09-21 16:25:15 +02007540
7541 hlua = hlua_gethlua(L);
7542
7543 if (!hlua || !hlua->task)
7544 WILL_LJMP(luaL_error(L, "The 'get' function is only allowed in "
7545 "'frontend', 'backend' or 'task'"));
7546
William Lallemand746e6f32021-10-06 10:57:44 +02007547 if (lua_gettop(L) != 2 || lua_type(L, -1) != LUA_TTABLE)
7548 WILL_LJMP(luaL_error(L, "'get' needs a table as argument"));
7549
William Lallemand4f4f2b72022-02-17 20:00:23 +01007550 hlua_hc = hlua_checkhttpclient(L, 1);
7551
William Lallemand7177a952022-03-03 15:33:12 +01007552 lua_pushnil(L); /* first key */
7553 while (lua_next(L, 2)) {
7554 if (strcmp(lua_tostring(L, -2), "dst") == 0) {
7555 if (httpclient_set_dst(hlua_hc->hc, lua_tostring(L, -1)) < 0)
7556 WILL_LJMP(luaL_error(L, "Can't use the 'dst' argument"));
William Lallemand4f4f2b72022-02-17 20:00:23 +01007557
William Lallemand7177a952022-03-03 15:33:12 +01007558 } else if (strcmp(lua_tostring(L, -2), "url") == 0) {
7559 if (lua_type(L, -1) != LUA_TSTRING)
7560 WILL_LJMP(luaL_error(L, "invalid parameter in 'url', must be a string"));
7561 url_str = lua_tostring(L, -1);
William Lallemand3956c4e2021-09-21 16:25:15 +02007562
William Lallemand7177a952022-03-03 15:33:12 +01007563 } else if (strcmp(lua_tostring(L, -2), "timeout") == 0) {
7564 if (lua_type(L, -1) != LUA_TNUMBER)
7565 WILL_LJMP(luaL_error(L, "invalid parameter in 'timeout', must be a number"));
7566 httpclient_set_timeout(hlua_hc->hc, lua_tointeger(L, -1));
William Lallemandb4a4ef62022-02-23 14:18:16 +01007567
William Lallemand7177a952022-03-03 15:33:12 +01007568 } else if (strcmp(lua_tostring(L, -2), "headers") == 0) {
7569 if (lua_type(L, -1) != LUA_TTABLE)
7570 WILL_LJMP(luaL_error(L, "invalid parameter in 'headers', must be a table"));
7571 hdrs = hlua_httpclient_table_to_hdrs(L);
William Lallemand79416cb2021-09-24 14:51:44 +02007572
William Lallemand7177a952022-03-03 15:33:12 +01007573 } else if (strcmp(lua_tostring(L, -2), "body") == 0) {
7574 if (lua_type(L, -1) != LUA_TSTRING)
7575 WILL_LJMP(luaL_error(L, "invalid parameter in 'body', must be a string"));
7576 body_str = lua_tolstring(L, -1, &buf_len);
William Lallemandbd5739e2021-10-28 15:41:38 +02007577
William Lallemand7177a952022-03-03 15:33:12 +01007578 } else {
7579 WILL_LJMP(luaL_error(L, "'%s' invalid parameter name", lua_tostring(L, -2)));
7580 }
7581 /* removes 'value'; keeps 'key' for next iteration */
7582 lua_pop(L, 1);
7583 }
William Lallemanddec25c32021-10-25 19:48:37 +02007584
William Lallemand746e6f32021-10-06 10:57:44 +02007585 if (!url_str) {
7586 WILL_LJMP(luaL_error(L, "'get' need a 'url' argument"));
7587 return 0;
7588 }
William Lallemand3956c4e2021-09-21 16:25:15 +02007589
William Lallemand10a37362022-03-02 16:18:26 +01007590 hlua_hc->sent = 0;
William Lallemand3956c4e2021-09-21 16:25:15 +02007591
Aurelien DARRAGON03564072023-02-09 15:26:25 +01007592 istfree(&hlua_hc->hc->req.url);
William Lallemand3956c4e2021-09-21 16:25:15 +02007593 hlua_hc->hc->req.url = istdup(ist(url_str));
William Lallemanddc2cc902021-10-26 11:43:26 +02007594 hlua_hc->hc->req.meth = meth;
William Lallemand3956c4e2021-09-21 16:25:15 +02007595
7596 /* update the httpclient callbacks */
William Lallemandbd5739e2021-10-28 15:41:38 +02007597 hlua_hc->hc->ops.res_stline = hlua_httpclient_cb;
7598 hlua_hc->hc->ops.res_headers = hlua_httpclient_cb;
7599 hlua_hc->hc->ops.res_payload = hlua_httpclient_cb;
William Lallemand8f170c72022-03-15 10:52:07 +01007600 hlua_hc->hc->ops.res_end = hlua_httpclient_cb;
William Lallemand3956c4e2021-09-21 16:25:15 +02007601
William Lallemandbd5739e2021-10-28 15:41:38 +02007602 /* a body is available, it will use the request callback */
Christopher Faulet380ae9c2022-10-14 14:57:04 +02007603 if (body_str && buf_len) {
William Lallemandbd5739e2021-10-28 15:41:38 +02007604 hlua_hc->hc->ops.req_payload = hlua_httpclient_cb;
7605 }
William Lallemand3956c4e2021-09-21 16:25:15 +02007606
William Lallemandbd5739e2021-10-28 15:41:38 +02007607 ret = httpclient_req_gen(hlua_hc->hc, hlua_hc->hc->req.url, meth, hdrs, IST_NULL);
William Lallemand3956c4e2021-09-21 16:25:15 +02007608
William Lallemand746e6f32021-10-06 10:57:44 +02007609 /* free the temporary headers array */
7610 hdrs_i = hdrs;
7611 while (hdrs_i && isttest(hdrs_i->n)) {
7612 istfree(&hdrs_i->n);
7613 istfree(&hdrs_i->v);
7614 hdrs_i++;
7615 }
7616 ha_free(&hdrs);
7617
7618
William Lallemand6137a9e2021-10-26 15:01:53 +02007619 if (ret != ERR_NONE) {
7620 WILL_LJMP(luaL_error(L, "Can't generate the HTTP request"));
7621 return 0;
7622 }
7623
William Lallemandc2d3db42022-04-26 11:46:13 +02007624 if (!httpclient_start(hlua_hc->hc))
7625 WILL_LJMP(luaL_error(L, "couldn't start the httpclient"));
William Lallemand6137a9e2021-10-26 15:01:53 +02007626
William Lallemandbd5739e2021-10-28 15:41:38 +02007627 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_httpclient_snd_yield, TICK_ETERNITY, 0));
William Lallemand3956c4e2021-09-21 16:25:15 +02007628
William Lallemand3956c4e2021-09-21 16:25:15 +02007629 return 0;
7630}
7631
7632/*
William Lallemanddc2cc902021-10-26 11:43:26 +02007633 * Sends an HTTP HEAD request and wait for a response
7634 *
7635 * httpclient:head(url, headers, payload)
7636 */
7637__LJMP static int hlua_httpclient_head(lua_State *L)
7638{
7639 return hlua_httpclient_send(L, HTTP_METH_HEAD);
7640}
7641
7642/*
7643 * Send an HTTP GET request and wait for a response
7644 *
7645 * httpclient:get(url, headers, payload)
7646 */
7647__LJMP static int hlua_httpclient_get(lua_State *L)
7648{
7649 return hlua_httpclient_send(L, HTTP_METH_GET);
7650
7651}
7652
7653/*
7654 * Sends an HTTP PUT request and wait for a response
7655 *
7656 * httpclient:put(url, headers, payload)
7657 */
7658__LJMP static int hlua_httpclient_put(lua_State *L)
7659{
7660 return hlua_httpclient_send(L, HTTP_METH_PUT);
7661}
7662
7663/*
7664 * Send an HTTP POST request and wait for a response
7665 *
7666 * httpclient:post(url, headers, payload)
7667 */
7668__LJMP static int hlua_httpclient_post(lua_State *L)
7669{
7670 return hlua_httpclient_send(L, HTTP_METH_POST);
7671}
7672
7673
7674/*
7675 * Sends an HTTP DELETE request and wait for a response
7676 *
7677 * httpclient:delete(url, headers, payload)
7678 */
7679__LJMP static int hlua_httpclient_delete(lua_State *L)
7680{
7681 return hlua_httpclient_send(L, HTTP_METH_DELETE);
7682}
7683
7684/*
William Lallemand3956c4e2021-09-21 16:25:15 +02007685 *
7686 *
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007687 * Class TXN
7688 *
7689 *
7690 */
7691
7692/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02007693 * a class stream, otherwise it throws an error.
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007694 */
7695__LJMP static struct hlua_txn *hlua_checktxn(lua_State *L, int ud)
7696{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02007697 return MAY_LJMP(hlua_checkudata(L, ud, class_txn_ref));
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007698}
7699
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007700__LJMP static int hlua_set_var(lua_State *L)
7701{
7702 struct hlua_txn *htxn;
7703 const char *name;
7704 size_t len;
7705 struct sample smp;
7706
Tim Duesterhus4e172c92020-05-19 13:49:42 +02007707 if (lua_gettop(L) < 3 || lua_gettop(L) > 4)
7708 WILL_LJMP(luaL_error(L, "'set_var' needs between 3 and 4 arguments"));
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007709
7710 /* It is useles to retrieve the stream, but this function
7711 * runs only in a stream context.
7712 */
7713 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7714 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
7715
7716 /* Converts the third argument in a sample. */
Amaury Denoyellebc0af6a2020-10-29 17:21:20 +01007717 memset(&smp, 0, sizeof(smp));
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007718 hlua_lua2smp(L, 3, &smp);
7719
7720 /* Store the sample in a variable. */
Willy Tarreau7560dd42016-03-10 16:28:58 +01007721 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
Tim Duesterhus4e172c92020-05-19 13:49:42 +02007722
7723 if (lua_gettop(L) == 4 && lua_toboolean(L, 4))
7724 lua_pushboolean(L, vars_set_by_name_ifexist(name, len, &smp) != 0);
7725 else
7726 lua_pushboolean(L, vars_set_by_name(name, len, &smp) != 0);
7727
Tim Duesterhus84ebc132020-05-19 13:49:41 +02007728 return 1;
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007729}
7730
Christopher Faulet85d79c92016-11-09 16:54:56 +01007731__LJMP static int hlua_unset_var(lua_State *L)
7732{
7733 struct hlua_txn *htxn;
7734 const char *name;
7735 size_t len;
7736 struct sample smp;
7737
7738 MAY_LJMP(check_args(L, 2, "unset_var"));
7739
7740 /* It is useles to retrieve the stream, but this function
7741 * runs only in a stream context.
7742 */
7743 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7744 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
7745
7746 /* Unset the variable. */
7747 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
Tim Duesterhus84ebc132020-05-19 13:49:41 +02007748 lua_pushboolean(L, vars_unset_by_name_ifexist(name, len, &smp) != 0);
7749 return 1;
Christopher Faulet85d79c92016-11-09 16:54:56 +01007750}
7751
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007752__LJMP static int hlua_get_var(lua_State *L)
7753{
7754 struct hlua_txn *htxn;
7755 const char *name;
7756 size_t len;
7757 struct sample smp;
7758
7759 MAY_LJMP(check_args(L, 2, "get_var"));
7760
7761 /* It is useles to retrieve the stream, but this function
7762 * runs only in a stream context.
7763 */
7764 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7765 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
7766
Willy Tarreau7560dd42016-03-10 16:28:58 +01007767 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
Willy Tarreaue352b9d2021-09-03 11:52:38 +02007768 if (!vars_get_by_name(name, len, &smp, NULL)) {
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007769 lua_pushnil(L);
7770 return 1;
7771 }
7772
7773 return hlua_smp2lua(L, &smp);
7774}
7775
Willy Tarreau59551662015-03-10 14:23:13 +01007776__LJMP static int hlua_set_priv(lua_State *L)
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007777{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007778 struct hlua *hlua;
7779
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007780 MAY_LJMP(check_args(L, 2, "set_priv"));
7781
Willy Tarreau87b09662015-04-03 00:22:06 +02007782 /* It is useles to retrieve the stream, but this function
7783 * runs only in a stream context.
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007784 */
7785 MAY_LJMP(hlua_checktxn(L, 1));
Thierry Fournier4234dbd2020-11-28 13:18:23 +01007786
7787 /* Get hlua struct, or NULL if we execute from main lua state */
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007788 hlua = hlua_gethlua(L);
Thierry Fournier4234dbd2020-11-28 13:18:23 +01007789 if (!hlua)
7790 return 0;
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007791
7792 /* Remove previous value. */
Thierry FOURNIERe068b602017-04-26 13:27:05 +02007793 luaL_unref(L, LUA_REGISTRYINDEX, hlua->Mref);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007794
7795 /* Get and store new value. */
7796 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
7797 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
7798
7799 return 0;
7800}
7801
Willy Tarreau59551662015-03-10 14:23:13 +01007802__LJMP static int hlua_get_priv(lua_State *L)
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007803{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007804 struct hlua *hlua;
7805
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007806 MAY_LJMP(check_args(L, 1, "get_priv"));
7807
Willy Tarreau87b09662015-04-03 00:22:06 +02007808 /* It is useles to retrieve the stream, but this function
7809 * runs only in a stream context.
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007810 */
7811 MAY_LJMP(hlua_checktxn(L, 1));
Thierry Fournier4234dbd2020-11-28 13:18:23 +01007812
7813 /* Get hlua struct, or NULL if we execute from main lua state */
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007814 hlua = hlua_gethlua(L);
Thierry Fournier4234dbd2020-11-28 13:18:23 +01007815 if (!hlua) {
7816 lua_pushnil(L);
7817 return 1;
7818 }
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007819
7820 /* Push configuration index in the stack. */
7821 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
7822
7823 return 1;
7824}
7825
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007826/* Create stack entry containing a class TXN. This function
7827 * return 0 if the stack does not contains free slots,
7828 * otherwise it returns 1.
7829 */
Thierry FOURNIERab00df62016-07-14 11:42:37 +02007830static int hlua_txn_new(lua_State *L, struct stream *s, struct proxy *p, int dir, int flags)
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007831{
Willy Tarreaude491382015-04-06 11:04:28 +02007832 struct hlua_txn *htxn;
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007833
7834 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01007835 if (!lua_checkstack(L, 3))
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007836 return 0;
7837
7838 /* NOTE: The allocation never fails. The failure
7839 * throw an error, and the function never returns.
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08007840 * if the throw is not available, the process is aborted.
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007841 */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01007842 /* Create the object: obj[0] = userdata. */
7843 lua_newtable(L);
Willy Tarreaude491382015-04-06 11:04:28 +02007844 htxn = lua_newuserdata(L, sizeof(*htxn));
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01007845 lua_rawseti(L, -2, 0);
7846
Willy Tarreaude491382015-04-06 11:04:28 +02007847 htxn->s = s;
7848 htxn->p = p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01007849 htxn->dir = dir;
Thierry FOURNIERab00df62016-07-14 11:42:37 +02007850 htxn->flags = flags;
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007851
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01007852 /* Create the "f" field that contains a list of fetches. */
7853 lua_pushstring(L, "f");
Thierry FOURNIERca988662015-12-20 18:43:03 +01007854 if (!hlua_fetches_new(L, htxn, HLUA_F_MAY_USE_HTTP))
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01007855 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007856 lua_rawset(L, -3);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01007857
7858 /* Create the "sf" field that contains a list of stringsafe fetches. */
7859 lua_pushstring(L, "sf");
Thierry FOURNIERca988662015-12-20 18:43:03 +01007860 if (!hlua_fetches_new(L, htxn, HLUA_F_MAY_USE_HTTP | HLUA_F_AS_STRING))
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01007861 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007862 lua_rawset(L, -3);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01007863
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007864 /* Create the "c" field that contains a list of converters. */
7865 lua_pushstring(L, "c");
Willy Tarreaude491382015-04-06 11:04:28 +02007866 if (!hlua_converters_new(L, htxn, 0))
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01007867 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007868 lua_rawset(L, -3);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01007869
7870 /* Create the "sc" field that contains a list of stringsafe converters. */
7871 lua_pushstring(L, "sc");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01007872 if (!hlua_converters_new(L, htxn, HLUA_F_AS_STRING))
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007873 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007874 lua_rawset(L, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007875
Thierry FOURNIER397826a2015-03-11 19:39:09 +01007876 /* Create the "req" field that contains the request channel object. */
7877 lua_pushstring(L, "req");
Willy Tarreau2a71af42015-03-10 13:51:50 +01007878 if (!hlua_channel_new(L, &s->req))
Thierry FOURNIER397826a2015-03-11 19:39:09 +01007879 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007880 lua_rawset(L, -3);
Thierry FOURNIER397826a2015-03-11 19:39:09 +01007881
7882 /* Create the "res" field that contains the response channel object. */
7883 lua_pushstring(L, "res");
Willy Tarreau2a71af42015-03-10 13:51:50 +01007884 if (!hlua_channel_new(L, &s->res))
Thierry FOURNIER397826a2015-03-11 19:39:09 +01007885 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007886 lua_rawset(L, -3);
Thierry FOURNIER397826a2015-03-11 19:39:09 +01007887
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007888 /* Creates the HTTP object is the current proxy allows http. */
7889 lua_pushstring(L, "http");
Christopher Faulet1bb6afa2021-03-08 17:57:53 +01007890 if (IS_HTX_STRM(s)) {
Willy Tarreaude491382015-04-06 11:04:28 +02007891 if (!hlua_http_new(L, htxn))
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007892 return 0;
7893 }
7894 else
7895 lua_pushnil(L);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007896 lua_rawset(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007897
Christopher Faulet78c35472020-02-26 17:14:08 +01007898 if ((htxn->flags & HLUA_TXN_CTX_MASK) == HLUA_TXN_FLT_CTX) {
7899 /* HTTPMessage object are created when a lua TXN is created from
7900 * a filter context only
7901 */
7902
7903 /* Creates the HTTP-Request object is the current proxy allows http. */
7904 lua_pushstring(L, "http_req");
7905 if (p->mode == PR_MODE_HTTP) {
7906 if (!hlua_http_msg_new(L, &s->txn->req))
7907 return 0;
7908 }
7909 else
7910 lua_pushnil(L);
7911 lua_rawset(L, -3);
7912
7913 /* Creates the HTTP-Response object is the current proxy allows http. */
7914 lua_pushstring(L, "http_res");
7915 if (p->mode == PR_MODE_HTTP) {
7916 if (!hlua_http_msg_new(L, &s->txn->rsp))
7917 return 0;
7918 }
7919 else
7920 lua_pushnil(L);
7921 lua_rawset(L, -3);
7922 }
7923
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007924 /* Pop a class sesison metatable and affect it to the userdata. */
7925 lua_rawgeti(L, LUA_REGISTRYINDEX, class_txn_ref);
7926 lua_setmetatable(L, -2);
7927
7928 return 1;
7929}
7930
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01007931__LJMP static int hlua_txn_deflog(lua_State *L)
7932{
7933 const char *msg;
7934 struct hlua_txn *htxn;
7935
7936 MAY_LJMP(check_args(L, 2, "deflog"));
7937 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7938 msg = MAY_LJMP(luaL_checkstring(L, 2));
7939
7940 hlua_sendlog(htxn->s->be, htxn->s->logs.level, msg);
7941 return 0;
7942}
7943
7944__LJMP static int hlua_txn_log(lua_State *L)
7945{
7946 int level;
7947 const char *msg;
7948 struct hlua_txn *htxn;
7949
7950 MAY_LJMP(check_args(L, 3, "log"));
7951 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7952 level = MAY_LJMP(luaL_checkinteger(L, 2));
7953 msg = MAY_LJMP(luaL_checkstring(L, 3));
7954
7955 if (level < 0 || level >= NB_LOG_LEVELS)
7956 WILL_LJMP(luaL_argerror(L, 1, "Invalid loglevel."));
7957
7958 hlua_sendlog(htxn->s->be, level, msg);
7959 return 0;
7960}
7961
7962__LJMP static int hlua_txn_log_debug(lua_State *L)
7963{
7964 const char *msg;
7965 struct hlua_txn *htxn;
7966
7967 MAY_LJMP(check_args(L, 2, "Debug"));
7968 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7969 msg = MAY_LJMP(luaL_checkstring(L, 2));
7970 hlua_sendlog(htxn->s->be, LOG_DEBUG, msg);
7971 return 0;
7972}
7973
7974__LJMP static int hlua_txn_log_info(lua_State *L)
7975{
7976 const char *msg;
7977 struct hlua_txn *htxn;
7978
7979 MAY_LJMP(check_args(L, 2, "Info"));
7980 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7981 msg = MAY_LJMP(luaL_checkstring(L, 2));
7982 hlua_sendlog(htxn->s->be, LOG_INFO, msg);
7983 return 0;
7984}
7985
7986__LJMP static int hlua_txn_log_warning(lua_State *L)
7987{
7988 const char *msg;
7989 struct hlua_txn *htxn;
7990
7991 MAY_LJMP(check_args(L, 2, "Warning"));
7992 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7993 msg = MAY_LJMP(luaL_checkstring(L, 2));
7994 hlua_sendlog(htxn->s->be, LOG_WARNING, msg);
7995 return 0;
7996}
7997
7998__LJMP static int hlua_txn_log_alert(lua_State *L)
7999{
8000 const char *msg;
8001 struct hlua_txn *htxn;
8002
8003 MAY_LJMP(check_args(L, 2, "Alert"));
8004 htxn = MAY_LJMP(hlua_checktxn(L, 1));
8005 msg = MAY_LJMP(luaL_checkstring(L, 2));
8006 hlua_sendlog(htxn->s->be, LOG_ALERT, msg);
8007 return 0;
8008}
8009
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01008010__LJMP static int hlua_txn_set_loglevel(lua_State *L)
8011{
8012 struct hlua_txn *htxn;
8013 int ll;
8014
8015 MAY_LJMP(check_args(L, 2, "set_loglevel"));
8016 htxn = MAY_LJMP(hlua_checktxn(L, 1));
8017 ll = MAY_LJMP(luaL_checkinteger(L, 2));
8018
8019 if (ll < 0 || ll > 7)
8020 WILL_LJMP(luaL_argerror(L, 2, "Bad log level. It must be between 0 and 7"));
8021
8022 htxn->s->logs.level = ll;
8023 return 0;
8024}
8025
8026__LJMP static int hlua_txn_set_tos(lua_State *L)
8027{
8028 struct hlua_txn *htxn;
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01008029 int tos;
8030
8031 MAY_LJMP(check_args(L, 2, "set_tos"));
8032 htxn = MAY_LJMP(hlua_checktxn(L, 1));
8033 tos = MAY_LJMP(luaL_checkinteger(L, 2));
8034
Willy Tarreau1a18b542018-12-11 16:37:42 +01008035 conn_set_tos(objt_conn(htxn->s->sess->origin), tos);
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01008036 return 0;
8037}
8038
8039__LJMP static int hlua_txn_set_mark(lua_State *L)
8040{
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01008041 struct hlua_txn *htxn;
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01008042 int mark;
8043
8044 MAY_LJMP(check_args(L, 2, "set_mark"));
8045 htxn = MAY_LJMP(hlua_checktxn(L, 1));
8046 mark = MAY_LJMP(luaL_checkinteger(L, 2));
8047
Lukas Tribus579e3e32019-08-11 18:03:45 +02008048 conn_set_mark(objt_conn(htxn->s->sess->origin), mark);
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01008049 return 0;
8050}
8051
Patrick Hemmer268a7072018-05-11 12:52:31 -04008052__LJMP static int hlua_txn_set_priority_class(lua_State *L)
8053{
8054 struct hlua_txn *htxn;
8055
8056 MAY_LJMP(check_args(L, 2, "set_priority_class"));
8057 htxn = MAY_LJMP(hlua_checktxn(L, 1));
8058 htxn->s->priority_class = queue_limit_class(MAY_LJMP(luaL_checkinteger(L, 2)));
8059 return 0;
8060}
8061
8062__LJMP static int hlua_txn_set_priority_offset(lua_State *L)
8063{
8064 struct hlua_txn *htxn;
8065
8066 MAY_LJMP(check_args(L, 2, "set_priority_offset"));
8067 htxn = MAY_LJMP(hlua_checktxn(L, 1));
8068 htxn->s->priority_offset = queue_limit_offset(MAY_LJMP(luaL_checkinteger(L, 2)));
8069 return 0;
8070}
8071
Christopher Faulet700d9e82020-01-31 12:21:52 +01008072/* Forward the Reply object to the client. This function converts the reply in
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05008073 * HTX an push it to into the response channel. It is response to forward the
Christopher Faulet700d9e82020-01-31 12:21:52 +01008074 * message and terminate the transaction. It returns 1 on success and 0 on
8075 * error. The Reply must be on top of the stack.
8076 */
8077__LJMP static int hlua_txn_forward_reply(lua_State *L, struct stream *s)
8078{
8079 struct htx *htx;
8080 struct htx_sl *sl;
8081 struct h1m h1m;
8082 const char *status, *reason, *body;
8083 size_t status_len, reason_len, body_len;
8084 int ret, code, flags;
8085
8086 code = 200;
8087 status = "200";
8088 status_len = 3;
8089 ret = lua_getfield(L, -1, "status");
8090 if (ret == LUA_TNUMBER) {
8091 code = lua_tointeger(L, -1);
8092 status = lua_tolstring(L, -1, &status_len);
8093 }
8094 lua_pop(L, 1);
8095
8096 reason = http_get_reason(code);
8097 reason_len = strlen(reason);
8098 ret = lua_getfield(L, -1, "reason");
8099 if (ret == LUA_TSTRING)
8100 reason = lua_tolstring(L, -1, &reason_len);
8101 lua_pop(L, 1);
8102
8103 body = NULL;
8104 body_len = 0;
8105 ret = lua_getfield(L, -1, "body");
8106 if (ret == LUA_TSTRING)
8107 body = lua_tolstring(L, -1, &body_len);
8108 lua_pop(L, 1);
8109
8110 /* Prepare the response before inserting the headers */
8111 h1m_init_res(&h1m);
8112 htx = htx_from_buf(&s->res.buf);
8113 channel_htx_truncate(&s->res, htx);
8114 if (s->txn->req.flags & HTTP_MSGF_VER_11) {
8115 flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11);
8116 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.1"),
8117 ist2(status, status_len), ist2(reason, reason_len));
8118 }
8119 else {
8120 flags = HTX_SL_F_IS_RESP;
8121 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.0"),
8122 ist2(status, status_len), ist2(reason, reason_len));
8123 }
8124 if (!sl)
8125 goto fail;
8126 sl->info.res.status = code;
8127
8128 /* Push in the stack the "headers" entry. */
8129 ret = lua_getfield(L, -1, "headers");
8130 if (ret != LUA_TTABLE)
8131 goto skip_headers;
8132
8133 lua_pushnil(L);
8134 while (lua_next(L, -2) != 0) {
8135 struct ist name, value;
8136 const char *n, *v;
8137 size_t nlen, vlen;
8138
8139 if (!lua_isstring(L, -2) || !lua_istable(L, -1)) {
8140 /* Skip element if the key is not a string or if the value is not a table */
8141 goto next_hdr;
8142 }
8143
8144 n = lua_tolstring(L, -2, &nlen);
8145 name = ist2(n, nlen);
8146 if (isteqi(name, ist("content-length"))) {
8147 /* Always skip content-length header. It will be added
8148 * later with the correct len
8149 */
8150 goto next_hdr;
8151 }
8152
8153 /* Loop on header's values */
8154 lua_pushnil(L);
8155 while (lua_next(L, -2)) {
8156 if (!lua_isstring(L, -1)) {
8157 /* Skip the value if it is not a string */
8158 goto next_value;
8159 }
8160
8161 v = lua_tolstring(L, -1, &vlen);
8162 value = ist2(v, vlen);
8163
8164 if (isteqi(name, ist("transfer-encoding")))
8165 h1_parse_xfer_enc_header(&h1m, value);
8166 if (!htx_add_header(htx, ist2(n, nlen), ist2(v, vlen)))
8167 goto fail;
8168
8169 next_value:
8170 lua_pop(L, 1);
8171 }
8172
8173 next_hdr:
8174 lua_pop(L, 1);
8175 }
8176 skip_headers:
8177 lua_pop(L, 1);
8178
8179 /* Update h1m flags: CLEN is set if CHNK is not present */
8180 if (!(h1m.flags & H1_MF_CHNK)) {
8181 const char *clen = ultoa(body_len);
8182
8183 h1m.flags |= H1_MF_CLEN;
8184 if (!htx_add_header(htx, ist("content-length"), ist(clen)))
8185 goto fail;
8186 }
8187 if (h1m.flags & (H1_MF_CLEN|H1_MF_CHNK))
8188 h1m.flags |= H1_MF_XFER_LEN;
8189
8190 /* Update HTX start-line flags */
8191 if (h1m.flags & H1_MF_XFER_ENC)
8192 flags |= HTX_SL_F_XFER_ENC;
8193 if (h1m.flags & H1_MF_XFER_LEN) {
8194 flags |= HTX_SL_F_XFER_LEN;
8195 if (h1m.flags & H1_MF_CHNK)
8196 flags |= HTX_SL_F_CHNK;
8197 else if (h1m.flags & H1_MF_CLEN)
8198 flags |= HTX_SL_F_CLEN;
8199 if (h1m.body_len == 0)
8200 flags |= HTX_SL_F_BODYLESS;
8201 }
8202 sl->flags |= flags;
8203
8204
8205 if (!htx_add_endof(htx, HTX_BLK_EOH) ||
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01008206 (body_len && !htx_add_data_atonce(htx, ist2(body, body_len))))
Christopher Faulet700d9e82020-01-31 12:21:52 +01008207 goto fail;
8208
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01008209 htx->flags |= HTX_FL_EOM;
8210
Christopher Faulet700d9e82020-01-31 12:21:52 +01008211 /* Now, forward the response and terminate the transaction */
8212 s->txn->status = code;
8213 htx_to_buf(htx, &s->res.buf);
8214 if (!http_forward_proxy_resp(s, 1))
8215 goto fail;
8216
8217 return 1;
8218
8219 fail:
8220 channel_htx_truncate(&s->res, htx);
8221 return 0;
8222}
8223
8224/* Terminate a transaction if called from a lua action. For TCP streams,
8225 * processing is just aborted. Nothing is returned to the client and all
8226 * arguments are ignored. For HTTP streams, if a reply is passed as argument, it
8227 * is forwarded to the client before terminating the transaction. On success,
8228 * the function exits with ACT_RET_DONE code. If an error occurred, it exits
8229 * with ACT_RET_ERR code. If this function is not called from a lua action, it
8230 * just exits without any processing.
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01008231 */
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02008232__LJMP static int hlua_txn_done(lua_State *L)
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01008233{
Willy Tarreaub2ccb562015-04-06 11:11:15 +02008234 struct hlua_txn *htxn;
Christopher Faulet700d9e82020-01-31 12:21:52 +01008235 struct stream *s;
8236 int finst;
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01008237
Willy Tarreaub2ccb562015-04-06 11:11:15 +02008238 htxn = MAY_LJMP(hlua_checktxn(L, 1));
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01008239
Christopher Faulet700d9e82020-01-31 12:21:52 +01008240 /* If the flags NOTERM is set, we cannot terminate the session, so we
8241 * just end the execution of the current lua code. */
8242 if (htxn->flags & HLUA_TXN_NOTERM)
Thierry FOURNIERab00df62016-07-14 11:42:37 +02008243 WILL_LJMP(hlua_done(L));
Thierry FOURNIERab00df62016-07-14 11:42:37 +02008244
Christopher Faulet700d9e82020-01-31 12:21:52 +01008245 s = htxn->s;
Christopher Fauletd8f0e072020-02-25 09:45:51 +01008246 if (!IS_HTX_STRM(htxn->s)) {
Christopher Faulet700d9e82020-01-31 12:21:52 +01008247 struct channel *req = &s->req;
8248 struct channel *res = &s->res;
Willy Tarreau81389672015-03-10 12:03:52 +01008249
Christopher Faulet700d9e82020-01-31 12:21:52 +01008250 channel_auto_read(req);
8251 channel_abort(req);
Christopher Faulet700d9e82020-01-31 12:21:52 +01008252 channel_erase(req);
8253
Christopher Faulet700d9e82020-01-31 12:21:52 +01008254 channel_auto_read(res);
8255 channel_auto_close(res);
Christopher Faulet12762f02023-04-13 15:40:10 +02008256 sc_schedule_abort(s->scb);
Christopher Faulet700d9e82020-01-31 12:21:52 +01008257
8258 finst = ((htxn->dir == SMP_OPT_DIR_REQ) ? SF_FINST_R : SF_FINST_D);
8259 goto done;
Christopher Fauletfe6a71b2019-07-26 16:40:24 +02008260 }
Thierry FOURNIER10ec2142015-08-24 17:23:45 +02008261
Christopher Faulet700d9e82020-01-31 12:21:52 +01008262 if (lua_gettop(L) == 1 || !lua_istable(L, 2)) {
8263 /* No reply or invalid reply */
8264 s->txn->status = 0;
8265 http_reply_and_close(s, 0, NULL);
8266 }
8267 else {
8268 /* Remove extra args to have the reply on top of the stack */
8269 if (lua_gettop(L) > 2)
8270 lua_pop(L, lua_gettop(L) - 2);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01008271
Christopher Faulet700d9e82020-01-31 12:21:52 +01008272 if (!hlua_txn_forward_reply(L, s)) {
8273 if (!(s->flags & SF_ERR_MASK))
8274 s->flags |= SF_ERR_PRXCOND;
8275 lua_pushinteger(L, ACT_RET_ERR);
8276 WILL_LJMP(hlua_done(L));
8277 return 0; /* Never reached */
8278 }
Christopher Faulet4d0e2632019-07-16 10:52:40 +02008279 }
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02008280
Christopher Faulet700d9e82020-01-31 12:21:52 +01008281 finst = ((htxn->dir == SMP_OPT_DIR_REQ) ? SF_FINST_R : SF_FINST_H);
8282 if (htxn->dir == SMP_OPT_DIR_REQ) {
8283 /* let's log the request time */
8284 s->logs.tv_request = now;
8285 if (s->sess->fe == s->be) /* report it if the request was intercepted by the frontend */
Willy Tarreau4781b152021-04-06 13:53:36 +02008286 _HA_ATOMIC_INC(&s->sess->fe->fe_counters.intercepted_req);
Christopher Faulet700d9e82020-01-31 12:21:52 +01008287 }
Christopher Fauletfe6a71b2019-07-26 16:40:24 +02008288
Christopher Faulet700d9e82020-01-31 12:21:52 +01008289 done:
8290 if (!(s->flags & SF_ERR_MASK))
8291 s->flags |= SF_ERR_LOCAL;
8292 if (!(s->flags & SF_FINST_MASK))
8293 s->flags |= finst;
Christopher Fauletfe6a71b2019-07-26 16:40:24 +02008294
Christopher Faulete48d1dc2021-08-13 14:11:17 +02008295 if ((htxn->flags & HLUA_TXN_CTX_MASK) == HLUA_TXN_FLT_CTX)
8296 lua_pushinteger(L, -1);
8297 else
8298 lua_pushinteger(L, ACT_RET_ABRT);
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02008299 WILL_LJMP(hlua_done(L));
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01008300 return 0;
8301}
8302
Christopher Faulet700d9e82020-01-31 12:21:52 +01008303/*
8304 *
8305 *
8306 * Class REPLY
8307 *
8308 *
8309 */
8310
8311/* Pushes the TXN reply onto the top of the stack. If the stask does not have a
8312 * free slots, the function fails and returns 0;
8313 */
8314static int hlua_txn_reply_new(lua_State *L)
8315{
8316 struct hlua_txn *htxn;
8317 const char *reason, *body = NULL;
8318 int ret, status;
8319
8320 htxn = MAY_LJMP(hlua_checktxn(L, 1));
Christopher Fauletd8f0e072020-02-25 09:45:51 +01008321 if (!IS_HTX_STRM(htxn->s)) {
Christopher Faulet700d9e82020-01-31 12:21:52 +01008322 hlua_pusherror(L, "txn object is not an HTTP transaction.");
8323 WILL_LJMP(lua_error(L));
8324 }
8325
8326 /* Default value */
8327 status = 200;
8328 reason = http_get_reason(status);
8329
8330 if (lua_istable(L, 2)) {
8331 /* load status and reason from the table argument at index 2 */
8332 ret = lua_getfield(L, 2, "status");
8333 if (ret == LUA_TNIL)
8334 goto reason;
8335 else if (ret != LUA_TNUMBER) {
8336 /* invalid status: ignore the reason */
8337 goto body;
8338 }
8339 status = lua_tointeger(L, -1);
8340
8341 reason:
8342 lua_pop(L, 1); /* restore the stack: remove status */
8343 ret = lua_getfield(L, 2, "reason");
8344 if (ret == LUA_TSTRING)
8345 reason = lua_tostring(L, -1);
8346
8347 body:
8348 lua_pop(L, 1); /* restore the stack: remove invalid status or reason */
8349 ret = lua_getfield(L, 2, "body");
8350 if (ret == LUA_TSTRING)
8351 body = lua_tostring(L, -1);
8352 lua_pop(L, 1); /* restore the stack: remove body */
8353 }
8354
8355 /* Create the Reply table */
8356 lua_newtable(L);
8357
8358 /* Add status element */
8359 lua_pushstring(L, "status");
8360 lua_pushinteger(L, status);
8361 lua_settable(L, -3);
8362
8363 /* Add reason element */
8364 reason = http_get_reason(status);
8365 lua_pushstring(L, "reason");
8366 lua_pushstring(L, reason);
8367 lua_settable(L, -3);
8368
8369 /* Add body element, nil if undefined */
8370 lua_pushstring(L, "body");
8371 if (body)
8372 lua_pushstring(L, body);
8373 else
8374 lua_pushnil(L);
8375 lua_settable(L, -3);
8376
8377 /* Add headers element */
8378 lua_pushstring(L, "headers");
8379 lua_newtable(L);
8380
8381 /* stack: [ txn, <Arg:table>, <Reply:table>, "headers", <headers:table> ] */
8382 if (lua_istable(L, 2)) {
8383 /* load headers from the table argument at index 2. If it is a table, copy it. */
8384 ret = lua_getfield(L, 2, "headers");
8385 if (ret == LUA_TTABLE) {
8386 /* stack: [ ... <headers:table>, <table> ] */
8387 lua_pushnil(L);
8388 while (lua_next(L, -2) != 0) {
8389 /* stack: [ ... <headers:table>, <table>, k, v] */
8390 if (!lua_isstring(L, -1) && !lua_istable(L, -1)) {
8391 /* invalid value type, skip it */
8392 lua_pop(L, 1);
8393 continue;
8394 }
8395
8396
8397 /* Duplicate the key and swap it with the value. */
8398 lua_pushvalue(L, -2);
8399 lua_insert(L, -2);
8400 /* stack: [ ... <headers:table>, <table>, k, k, v ] */
8401
8402 lua_newtable(L);
8403 lua_insert(L, -2);
8404 /* stack: [ ... <headers:table>, <table>, k, k, <inner:table>, v ] */
8405
8406 if (lua_isstring(L, -1)) {
8407 /* push the value in the inner table */
8408 lua_rawseti(L, -2, 1);
8409 }
8410 else { /* table */
8411 lua_pushnil(L);
8412 while (lua_next(L, -2) != 0) {
8413 /* stack: [ ... <headers:table>, <table>, k, k, <inner:table>, <v:table>, k2, v2 ] */
8414 if (!lua_isstring(L, -1)) {
8415 /* invalid value type, skip it*/
8416 lua_pop(L, 1);
8417 continue;
8418 }
8419 /* push the value in the inner table */
8420 lua_rawseti(L, -4, lua_rawlen(L, -4) + 1);
8421 /* stack: [ ... <headers:table>, <table>, k, k, <inner:table>, <v:table>, k2 ] */
8422 }
8423 lua_pop(L, 1);
8424 /* stack: [ ... <headers:table>, <table>, k, k, <inner:table> ] */
8425 }
8426
8427 /* push (k,v) on the stack in the headers table:
8428 * stack: [ ... <headers:table>, <table>, k, k, v ]
8429 */
8430 lua_settable(L, -5);
8431 /* stack: [ ... <headers:table>, <table>, k ] */
8432 }
8433 }
8434 lua_pop(L, 1);
8435 }
8436 /* stack: [ txn, <Arg:table>, <Reply:table>, "headers", <headers:table> ] */
8437 lua_settable(L, -3);
8438 /* stack: [ txn, <Arg:table>, <Reply:table> ] */
8439
8440 /* Pop a class sesison metatable and affect it to the userdata. */
8441 lua_rawgeti(L, LUA_REGISTRYINDEX, class_txn_reply_ref);
8442 lua_setmetatable(L, -2);
8443 return 1;
8444}
8445
8446/* Set the reply status code, and optionally the reason. If no reason is
8447 * provided, the default one corresponding to the status code is used.
8448 */
8449__LJMP static int hlua_txn_reply_set_status(lua_State *L)
8450{
8451 int status = MAY_LJMP(luaL_checkinteger(L, 2));
8452 const char *reason = MAY_LJMP(luaL_optlstring(L, 3, NULL, NULL));
8453
8454 /* First argument (self) must be a table */
Aurelien DARRAGONd83d0452022-10-05 11:46:45 +02008455 MAY_LJMP(luaL_checktype(L, 1, LUA_TTABLE));
Christopher Faulet700d9e82020-01-31 12:21:52 +01008456
8457 if (status < 100 || status > 599) {
8458 lua_pushboolean(L, 0);
8459 return 1;
8460 }
8461 if (!reason)
8462 reason = http_get_reason(status);
8463
8464 lua_pushinteger(L, status);
8465 lua_setfield(L, 1, "status");
8466
8467 lua_pushstring(L, reason);
8468 lua_setfield(L, 1, "reason");
8469
8470 lua_pushboolean(L, 1);
8471 return 1;
8472}
8473
8474/* Add a header into the reply object. Each header name is associated to an
8475 * array of values in the "headers" table. If the header name is not found, a
8476 * new entry is created.
8477 */
8478__LJMP static int hlua_txn_reply_add_header(lua_State *L)
8479{
8480 const char *name = MAY_LJMP(luaL_checkstring(L, 2));
8481 const char *value = MAY_LJMP(luaL_checkstring(L, 3));
8482 int ret;
8483
8484 /* First argument (self) must be a table */
Aurelien DARRAGONd83d0452022-10-05 11:46:45 +02008485 MAY_LJMP(luaL_checktype(L, 1, LUA_TTABLE));
Christopher Faulet700d9e82020-01-31 12:21:52 +01008486
8487 /* Push in the stack the "headers" entry. */
8488 ret = lua_getfield(L, 1, "headers");
8489 if (ret != LUA_TTABLE) {
8490 hlua_pusherror(L, "Reply['headers'] is expected to a an array. %s found", lua_typename(L, ret));
8491 WILL_LJMP(lua_error(L));
8492 }
8493
8494 /* check if the header is already registered. If not, register it. */
8495 ret = lua_getfield(L, -1, name);
8496 if (ret == LUA_TNIL) {
8497 /* Entry not found. */
8498 lua_pop(L, 1); /* remove the nil. The "headers" table is the top of the stack. */
8499
8500 /* Insert the new header name in the array in the top of the stack.
8501 * It left the new array in the top of the stack.
8502 */
8503 lua_newtable(L);
8504 lua_pushstring(L, name);
8505 lua_pushvalue(L, -2);
8506 lua_settable(L, -4);
8507 }
8508 else if (ret != LUA_TTABLE) {
8509 hlua_pusherror(L, "Reply['headers']['%s'] is expected to be an array. %s found", name, lua_typename(L, ret));
8510 WILL_LJMP(lua_error(L));
8511 }
8512
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -07008513 /* Now the top of thestack is an array of values. We push
Christopher Faulet700d9e82020-01-31 12:21:52 +01008514 * the header value as new entry.
8515 */
8516 lua_pushstring(L, value);
8517 ret = lua_rawlen(L, -2);
8518 lua_rawseti(L, -2, ret + 1);
8519
8520 lua_pushboolean(L, 1);
8521 return 1;
8522}
8523
8524/* Remove all occurrences of a given header name. */
8525__LJMP static int hlua_txn_reply_del_header(lua_State *L)
8526{
8527 const char *name = MAY_LJMP(luaL_checkstring(L, 2));
8528 int ret;
8529
8530 /* First argument (self) must be a table */
Aurelien DARRAGONd83d0452022-10-05 11:46:45 +02008531 MAY_LJMP(luaL_checktype(L, 1, LUA_TTABLE));
Christopher Faulet700d9e82020-01-31 12:21:52 +01008532
8533 /* Push in the stack the "headers" entry. */
8534 ret = lua_getfield(L, 1, "headers");
8535 if (ret != LUA_TTABLE) {
8536 hlua_pusherror(L, "Reply['headers'] is expected to be an array. %s found", lua_typename(L, ret));
8537 WILL_LJMP(lua_error(L));
8538 }
8539
8540 lua_pushstring(L, name);
8541 lua_pushnil(L);
8542 lua_settable(L, -3);
8543
8544 lua_pushboolean(L, 1);
8545 return 1;
8546}
8547
8548/* Set the reply's body. Overwrite any existing entry. */
8549__LJMP static int hlua_txn_reply_set_body(lua_State *L)
8550{
8551 const char *payload = MAY_LJMP(luaL_checkstring(L, 2));
8552
8553 /* First argument (self) must be a table */
Aurelien DARRAGONd83d0452022-10-05 11:46:45 +02008554 MAY_LJMP(luaL_checktype(L, 1, LUA_TTABLE));
Christopher Faulet700d9e82020-01-31 12:21:52 +01008555
8556 lua_pushstring(L, payload);
8557 lua_setfield(L, 1, "body");
8558
8559 lua_pushboolean(L, 1);
8560 return 1;
8561}
8562
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01008563__LJMP static int hlua_log(lua_State *L)
8564{
8565 int level;
8566 const char *msg;
8567
8568 MAY_LJMP(check_args(L, 2, "log"));
8569 level = MAY_LJMP(luaL_checkinteger(L, 1));
8570 msg = MAY_LJMP(luaL_checkstring(L, 2));
8571
8572 if (level < 0 || level >= NB_LOG_LEVELS)
8573 WILL_LJMP(luaL_argerror(L, 1, "Invalid loglevel."));
8574
8575 hlua_sendlog(NULL, level, msg);
8576 return 0;
8577}
8578
8579__LJMP static int hlua_log_debug(lua_State *L)
8580{
8581 const char *msg;
8582
8583 MAY_LJMP(check_args(L, 1, "debug"));
8584 msg = MAY_LJMP(luaL_checkstring(L, 1));
8585 hlua_sendlog(NULL, LOG_DEBUG, msg);
8586 return 0;
8587}
8588
8589__LJMP static int hlua_log_info(lua_State *L)
8590{
8591 const char *msg;
8592
8593 MAY_LJMP(check_args(L, 1, "info"));
8594 msg = MAY_LJMP(luaL_checkstring(L, 1));
8595 hlua_sendlog(NULL, LOG_INFO, msg);
8596 return 0;
8597}
8598
8599__LJMP static int hlua_log_warning(lua_State *L)
8600{
8601 const char *msg;
8602
8603 MAY_LJMP(check_args(L, 1, "warning"));
8604 msg = MAY_LJMP(luaL_checkstring(L, 1));
8605 hlua_sendlog(NULL, LOG_WARNING, msg);
8606 return 0;
8607}
8608
8609__LJMP static int hlua_log_alert(lua_State *L)
8610{
8611 const char *msg;
8612
8613 MAY_LJMP(check_args(L, 1, "alert"));
8614 msg = MAY_LJMP(luaL_checkstring(L, 1));
8615 hlua_sendlog(NULL, LOG_ALERT, msg);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01008616 return 0;
8617}
8618
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01008619__LJMP static int hlua_sleep_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008620{
8621 int wakeup_ms = lua_tointeger(L, -1);
Willy Tarreau12c02702021-09-30 16:12:31 +02008622 if (!tick_is_expired(wakeup_ms, now_ms))
Willy Tarreau9635e032018-10-16 17:52:55 +02008623 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008624 return 0;
8625}
8626
8627__LJMP static int hlua_sleep(lua_State *L)
8628{
8629 unsigned int delay;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008630 unsigned int wakeup_ms;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008631
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008632 MAY_LJMP(check_args(L, 1, "sleep"));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008633
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01008634 delay = MAY_LJMP(luaL_checkinteger(L, 1)) * 1000;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008635 wakeup_ms = tick_add(now_ms, delay);
8636 lua_pushinteger(L, wakeup_ms);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008637
Willy Tarreau9635e032018-10-16 17:52:55 +02008638 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008639 return 0;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008640}
8641
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008642__LJMP static int hlua_msleep(lua_State *L)
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008643{
8644 unsigned int delay;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008645 unsigned int wakeup_ms;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008646
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008647 MAY_LJMP(check_args(L, 1, "msleep"));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008648
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01008649 delay = MAY_LJMP(luaL_checkinteger(L, 1));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008650 wakeup_ms = tick_add(now_ms, delay);
8651 lua_pushinteger(L, wakeup_ms);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008652
Willy Tarreau9635e032018-10-16 17:52:55 +02008653 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008654 return 0;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008655}
8656
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01008657/* This functionis an LUA binding. it permits to give back
8658 * the hand at the HAProxy scheduler. It is used when the
8659 * LUA processing consumes a lot of time.
8660 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01008661__LJMP static int hlua_yield_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008662{
8663 return 0;
8664}
8665
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01008666__LJMP static int hlua_yield(lua_State *L)
8667{
Willy Tarreau9635e032018-10-16 17:52:55 +02008668 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_yield_yield, TICK_ETERNITY, HLUA_CTRLYIELD));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008669 return 0;
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01008670}
8671
Thierry FOURNIER37196f42015-02-16 19:34:56 +01008672/* This function change the nice of the currently executed
8673 * task. It is used set low or high priority at the current
8674 * task.
8675 */
Willy Tarreau59551662015-03-10 14:23:13 +01008676__LJMP static int hlua_set_nice(lua_State *L)
Thierry FOURNIER37196f42015-02-16 19:34:56 +01008677{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01008678 struct hlua *hlua;
8679 int nice;
Thierry FOURNIER37196f42015-02-16 19:34:56 +01008680
Willy Tarreau80f5fae2015-02-27 16:38:20 +01008681 MAY_LJMP(check_args(L, 1, "set_nice"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01008682 nice = MAY_LJMP(luaL_checkinteger(L, 1));
Thierry FOURNIER37196f42015-02-16 19:34:56 +01008683
Thierry Fournier4234dbd2020-11-28 13:18:23 +01008684 /* Get hlua struct, or NULL if we execute from main lua state */
8685 hlua = hlua_gethlua(L);
8686
8687 /* If the task is not set, I'm in a start mode. */
Thierry FOURNIER37196f42015-02-16 19:34:56 +01008688 if (!hlua || !hlua->task)
8689 return 0;
8690
8691 if (nice < -1024)
8692 nice = -1024;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01008693 else if (nice > 1024)
Thierry FOURNIER37196f42015-02-16 19:34:56 +01008694 nice = 1024;
8695
8696 hlua->task->nice = nice;
8697 return 0;
8698}
8699
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08008700/* This function is used as a callback of a task. It is called by the
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008701 * HAProxy task subsystem when the task is awaked. The LUA runtime can
8702 * return an E_AGAIN signal, the emmiter of this signal must set a
8703 * signal to wake the task.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008704 *
8705 * Task wrapper are longjmp safe because the only one Lua code
8706 * executed is the safe hlua_ctx_resume();
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008707 */
Willy Tarreau144f84a2021-03-02 16:09:26 +01008708struct task *hlua_process_task(struct task *task, void *context, unsigned int state)
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008709{
Olivier Houchard9f6af332018-05-25 14:04:04 +02008710 struct hlua *hlua = context;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008711 enum hlua_exec status;
8712
Willy Tarreau6ef52f42022-06-15 14:19:48 +02008713 if (task->tid < 0)
8714 task->tid = tid;
8715
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008716 /* If it is the first call to the task, we must initialize the
8717 * execution timeouts.
8718 */
8719 if (!HLUA_IS_RUNNING(hlua))
Aurelien DARRAGONda9503c2022-11-25 09:10:07 +01008720 hlua_timer_init(&hlua->timer, hlua_timeout_task);
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008721
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008722 /* Execute the Lua code. */
8723 status = hlua_ctx_resume(hlua, 1);
8724
8725 switch (status) {
8726 /* finished or yield */
8727 case HLUA_E_OK:
8728 hlua_ctx_destroy(hlua);
Olivier Houchard3f795f72019-04-17 22:51:06 +02008729 task_destroy(task);
Tim Duesterhuscd235c62018-04-24 13:56:01 +02008730 task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008731 break;
8732
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01008733 case HLUA_E_AGAIN: /* co process or timeout wake me later. */
Thierry FOURNIERcb146882017-12-10 17:10:57 +01008734 notification_gc(&hlua->com);
PiBa-NLfe971b32018-05-02 22:27:14 +02008735 task->expire = hlua->wake_time;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008736 break;
8737
8738 /* finished with error. */
Aurelien DARRAGON79544102022-11-24 14:27:15 +01008739 case HLUA_E_ETMOUT:
8740 SEND_ERR(NULL, "Lua task: execution timeout.\n");
8741 goto err_task_abort;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008742 case HLUA_E_ERRMSG:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008743 SEND_ERR(NULL, "Lua task: %s.\n", lua_tostring(hlua->T, -1));
Aurelien DARRAGON79544102022-11-24 14:27:15 +01008744 goto err_task_abort;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008745 case HLUA_E_ERR:
8746 default:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008747 SEND_ERR(NULL, "Lua task: unknown error.\n");
Aurelien DARRAGON79544102022-11-24 14:27:15 +01008748 err_task_abort:
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008749 hlua_ctx_destroy(hlua);
Olivier Houchard3f795f72019-04-17 22:51:06 +02008750 task_destroy(task);
Emeric Brun253e53e2017-10-17 18:58:40 +02008751 task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008752 break;
8753 }
Emeric Brun253e53e2017-10-17 18:58:40 +02008754 return task;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008755}
8756
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008757/* This function is an LUA binding that register LUA function to be
8758 * executed after the HAProxy configuration parsing and before the
8759 * HAProxy scheduler starts. This function expect only one LUA
8760 * argument that is a function. This function returns nothing, but
8761 * throws if an error is encountered.
8762 */
8763__LJMP static int hlua_register_init(lua_State *L)
8764{
8765 struct hlua_init_function *init;
8766 int ref;
8767
8768 MAY_LJMP(check_args(L, 1, "register_init"));
8769
Aurelien DARRAGON87f52972023-02-24 09:43:54 +01008770 if (hlua_gethlua(L)) {
8771 /* runtime processing */
8772 WILL_LJMP(luaL_error(L, "register_init: not available outside of body context"));
8773 }
8774
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008775 ref = MAY_LJMP(hlua_checkfunction(L, 1));
8776
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02008777 init = calloc(1, sizeof(*init));
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +01008778 if (!init) {
8779 hlua_unref(L, ref);
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01008780 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +01008781 }
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008782
8783 init->function_ref = ref;
Willy Tarreau2b718102021-04-21 07:32:39 +02008784 LIST_APPEND(&hlua_init_functions[hlua_state_id], &init->l);
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008785 return 0;
8786}
8787
Ilya Shipitsin6f86eaa2022-11-30 16:22:42 +05008788/* This function is an LUA binding. It permits to register a task
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008789 * executed in parallel of the main HAroxy activity. The task is
8790 * created and it is set in the HAProxy scheduler. It can be called
8791 * from the "init" section, "post init" or during the runtime.
8792 *
8793 * Lua prototype:
8794 *
Aurelien DARRAGONb8038992023-03-09 16:48:30 +01008795 * <none> core.register_task(<function>[, <arg1>[, <arg2>[, ...[, <arg4>]]]])
8796 *
8797 * <arg1..4> are optional arguments that will be provided to <function>
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008798 */
8799static int hlua_register_task(lua_State *L)
8800{
Christopher Faulet5294ec02021-04-12 12:24:47 +02008801 struct hlua *hlua = NULL;
8802 struct task *task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008803 int ref;
Aurelien DARRAGONb8038992023-03-09 16:48:30 +01008804 int nb_arg;
8805 int it;
8806 int arg_ref[4]; /* optional arguments */
Thierry Fournier021d9862020-11-28 23:42:03 +01008807 int state_id;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008808
Aurelien DARRAGONb8038992023-03-09 16:48:30 +01008809 nb_arg = lua_gettop(L);
8810 if (nb_arg < 1)
8811 WILL_LJMP(luaL_error(L, "register_task: <func> argument is required"));
8812 else if (nb_arg > 5)
8813 WILL_LJMP(luaL_error(L, "register_task: no more that 4 optional arguments may be provided"));
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008814
Aurelien DARRAGONb8038992023-03-09 16:48:30 +01008815 /* first arg: function ref */
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008816 ref = MAY_LJMP(hlua_checkfunction(L, 1));
8817
Aurelien DARRAGONb8038992023-03-09 16:48:30 +01008818 /* extract optional args (if any) */
8819 it = 0;
8820 while (--nb_arg) {
8821 lua_pushvalue(L, 2 + it);
8822 arg_ref[it] = hlua_ref(L); /* get arg reference */
8823 it += 1;
8824 }
8825 nb_arg = it;
8826
Thierry Fournier75fc0292020-11-28 13:18:56 +01008827 /* Get the reference state. If the reference is NULL, L is the master
8828 * state, otherwise hlua->T is.
8829 */
8830 hlua = hlua_gethlua(L);
8831 if (hlua)
Thierry Fournier021d9862020-11-28 23:42:03 +01008832 /* we are in runtime processing */
8833 state_id = hlua->state_id;
Thierry Fournier75fc0292020-11-28 13:18:56 +01008834 else
Thierry Fournier021d9862020-11-28 23:42:03 +01008835 /* we are in initialization mode */
Thierry Fournierc7492592020-11-28 23:57:24 +01008836 state_id = hlua_state_id;
Thierry Fournier75fc0292020-11-28 13:18:56 +01008837
Willy Tarreaubafbe012017-11-24 17:34:44 +01008838 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008839 if (!hlua)
Christopher Faulet5294ec02021-04-12 12:24:47 +02008840 goto alloc_error;
Christopher Faulet1e8433f2021-03-24 15:03:01 +01008841 HLUA_INIT(hlua);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008842
Thierry Fournier59f11be2020-11-29 00:37:41 +01008843 /* We are in the common lua state, execute the task anywhere,
8844 * otherwise, inherit the current thread identifier
8845 */
8846 if (state_id == 0)
Willy Tarreaubeeabf52021-10-01 18:23:30 +02008847 task = task_new_anywhere();
Thierry Fournier59f11be2020-11-29 00:37:41 +01008848 else
Willy Tarreaubeeabf52021-10-01 18:23:30 +02008849 task = task_new_here();
Willy Tarreaue09101e2018-10-16 17:37:12 +02008850 if (!task)
Christopher Faulet5294ec02021-04-12 12:24:47 +02008851 goto alloc_error;
Willy Tarreaue09101e2018-10-16 17:37:12 +02008852
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008853 task->context = hlua;
8854 task->process = hlua_process_task;
8855
Aurelien DARRAGON6b0b9bd2023-03-21 14:02:16 +01008856 if (!hlua_ctx_init(hlua, state_id, task))
Christopher Faulet5294ec02021-04-12 12:24:47 +02008857 goto alloc_error;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008858
Aurelien DARRAGONb8038992023-03-09 16:48:30 +01008859 /* Ensure there is enough space on the stack for the function
8860 * plus optional arguments
8861 */
8862 if (!lua_checkstack(hlua->T, (1 + nb_arg)))
8863 goto alloc_error;
8864
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008865 /* Restore the function in the stack. */
Aurelien DARRAGON4fdf8b52023-03-20 17:22:37 +01008866 hlua_pushref(hlua->T, ref);
Aurelien DARRAGONbe58d662023-03-13 14:09:21 +01008867 /* function ref not needed anymore since it was pushed to the substack */
8868 hlua_unref(L, ref);
8869
Aurelien DARRAGONb8038992023-03-09 16:48:30 +01008870 hlua->nargs = nb_arg;
8871
8872 /* push optional arguments to the function */
8873 for (it = 0; it < nb_arg; it++) {
8874 /* push arg to the stack */
8875 hlua_pushref(hlua->T, arg_ref[it]);
8876 /* arg ref not needed anymore since it was pushed to the substack */
8877 hlua_unref(L, arg_ref[it]);
8878 }
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008879
8880 /* Schedule task. */
Willy Tarreaue3957f82021-09-30 16:17:37 +02008881 task_wakeup(task, TASK_WOKEN_INIT);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008882
8883 return 0;
Christopher Faulet5294ec02021-04-12 12:24:47 +02008884
8885 alloc_error:
8886 task_destroy(task);
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +01008887 hlua_unref(L, ref);
Aurelien DARRAGONb8038992023-03-09 16:48:30 +01008888 for (it = 0; it < nb_arg; it++) {
8889 hlua_unref(L, arg_ref[it]);
8890 }
Christopher Faulet5294ec02021-04-12 12:24:47 +02008891 hlua_ctx_destroy(hlua);
8892 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
8893 return 0; /* Never reached */
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008894}
8895
Aurelien DARRAGONc84899c2023-02-20 18:18:59 +01008896/* called from unsafe location */
8897static void hlua_event_subscription_destroy(struct hlua_event_sub *hlua_sub)
8898{
8899 /* hlua cleanup */
8900
8901 hlua_lock(hlua_sub->hlua);
8902 /* registry is shared between coroutines */
8903 hlua_unref(hlua_sub->hlua->T, hlua_sub->fcn_ref);
8904 hlua_unlock(hlua_sub->hlua);
8905
8906 hlua_ctx_destroy(hlua_sub->hlua);
8907
8908 /* free */
8909 pool_free(pool_head_hlua_event_sub, hlua_sub);
8910}
8911
8912/* single event handler: hlua ctx is shared between multiple events handlers
8913 * issued from the same subscription. Thus, it is not destroyed when the event
8914 * is processed: it is destroyed when no more events are expected for the
8915 * subscription (ie: when the subscription ends).
8916 *
8917 * Moreover, events are processed sequentially within the subscription:
8918 * one event must be fully processed before another one may be processed.
8919 * This ensures proper consistency for lua event handling from an ordering
8920 * point of view. This is especially useful with server events for example
8921 * where ADD/DEL/UP/DOWN events ordering really matters to trigger specific
8922 * actions from lua (e.g.: sending emails or making API calls).
8923 *
8924 * Due to this design, each lua event handler is pleased to process the event
8925 * as fast as possible to prevent the event queue from growing up.
8926 * Strictly speaking, there is no runtime limit for the callback function
8927 * (timeout set to default task timeout), but if the event queue goes past
8928 * the limit of unconsumed events an error will be reported and the
8929 * susbscription will pause itself for as long as it takes for the handler to
8930 * catch up (events will be lost as a result).
8931 * If the event handler does not need the sequential ordering and wants to
8932 * process multiple events at a time, it may spawn a new side-task using
8933 * 'core.register_task' to delegate the event handling and make parallel event
8934 * processing within the same subscription set.
8935 */
8936static void hlua_event_handler(struct hlua *hlua)
8937{
8938 enum hlua_exec status;
8939
8940 /* If it is the first call to the task, we must initialize the
8941 * execution timeouts.
8942 */
Aurelien DARRAGONda9503c2022-11-25 09:10:07 +01008943 if (!HLUA_IS_RUNNING(hlua))
8944 hlua_timer_init(&hlua->timer, hlua_timeout_task);
Aurelien DARRAGONc84899c2023-02-20 18:18:59 +01008945
8946 /* make sure to reset the task expiry before each hlua_ctx_resume()
8947 * since the task is re-used for multiple cb function calls
8948 * We couldn't risk to have t->expire pointing to a past date because
8949 * it was set during last function invocation but was never reset since
8950 * (ie: E_AGAIN)
8951 */
8952 hlua->task->expire = TICK_ETERNITY;
8953
8954 /* Execute the Lua code. */
8955 status = hlua_ctx_resume(hlua, 1);
8956
8957 switch (status) {
8958 /* finished or yield */
8959 case HLUA_E_OK:
8960 break;
8961
8962 case HLUA_E_AGAIN: /* co process or timeout wake me later. */
8963 notification_gc(&hlua->com);
8964 hlua->task->expire = hlua->wake_time;
8965 break;
8966
8967 /* finished with error. */
8968 case HLUA_E_ETMOUT:
8969 SEND_ERR(NULL, "Lua event_hdl: execution timeout.\n");
8970 break;
8971
8972 case HLUA_E_ERRMSG:
8973 SEND_ERR(NULL, "Lua event_hdl: %s.\n", lua_tostring(hlua->T, -1));
8974 break;
8975
8976 case HLUA_E_ERR:
8977 default:
8978 SEND_ERR(NULL, "Lua event_hdl: unknown error.\n");
8979 break;
8980 }
8981}
8982
8983__LJMP static int hlua_event_hdl_cb_data_push_args(struct hlua_event_sub *hlua_sub,
8984 struct event_hdl_sub_type event, void *data)
8985{
8986 struct hlua *hlua = hlua_sub->hlua;
8987
8988 hlua->nargs = 1;
8989 lua_pushstring(hlua->T, event_hdl_sub_type_to_string(event));
8990 if (event_hdl_sub_family_equal(EVENT_HDL_SUB_SERVER, event)) {
8991 struct event_hdl_cb_data_server *e_server = data;
8992 struct proxy *px;
8993 struct server *server;
8994
8995 hlua->nargs += 1;
8996 lua_newtable(hlua->T);
8997 /* Add server name */
8998 lua_pushstring(hlua->T, "name");
8999 lua_pushstring(hlua->T, e_server->safe.name);
9000 lua_settable(hlua->T, -3);
9001 /* Add server puid */
9002 lua_pushstring(hlua->T, "puid");
9003 lua_pushinteger(hlua->T, e_server->safe.puid);
9004 lua_settable(hlua->T, -3);
9005 /* Add server rid */
9006 lua_pushstring(hlua->T, "rid");
9007 lua_pushinteger(hlua->T, e_server->safe.rid);
9008 lua_settable(hlua->T, -3);
9009 /* Add server proxy name */
9010 lua_pushstring(hlua->T, "proxy_name");
9011 lua_pushstring(hlua->T, e_server->safe.proxy_name);
9012 lua_settable(hlua->T, -3);
9013
9014 /* attempt to provide reference server object
9015 * (if it wasn't removed yet, SERVER_DEL will never succeed here)
9016 */
9017 px = proxy_find_by_name(e_server->safe.proxy_name, PR_CAP_BE, 0);
9018 BUG_ON(!px);
9019 server = findserver_unique_id(px, e_server->safe.puid, e_server->safe.rid);
9020 if (server) {
9021 lua_pushstring(hlua->T, "reference");
9022 hlua_fcn_new_server(hlua->T, server);
9023 lua_settable(hlua->T, -3);
9024 }
9025 }
9026 /* sub mgmt */
9027 hlua->nargs += 1;
9028 hlua_fcn_new_event_sub(hlua->T, hlua_sub->sub);
9029
9030 return 1;
9031}
9032
9033/* events runner: if there's an ongoing hlua event handling process, finish it
9034 * then, check if there are new events waiting to be processed
9035 * (events are processed sequentially)
9036 *
9037 * We have a safety measure to warn/guard if the event queue is growing up
9038 * too much due to many events being generated and lua handler is unable to
9039 * keep up the pace (e.g.: when the event queue grows past 100 unconsumed events).
9040 * TODO: make it tunable
9041 */
9042static struct task *hlua_event_runner(struct task *task, void *context, unsigned int state)
9043{
9044 struct hlua_event_sub *hlua_sub = context;
9045 struct event_hdl_async_event *event;
9046 const char *error = NULL;
9047
9048 if (!hlua_sub->paused && event_hdl_async_equeue_size(&hlua_sub->equeue) > 100) {
9049 const char *trace;
9050
9051 /* We reached the limit of pending events in the queue: we should
9052 * warn the user, and temporarily pause the subscription to give a chance
9053 * to the handler to catch up? (it also prevents ressource shortage since
9054 * the queue could grow indefinitely otherwise)
9055 * TODO: find a way to inform the handler that it missed some events
9056 * (example: stats within the subscription in event_hdl api exposed via lua api?)
9057 *
9058 * Nonetheless, reaching this limit means that the handler is not fast enough
9059 * and/or that it subscribed to events that happen too frequently and did not
9060 * expect it. This could come from an inadequate design in the user's script.
9061 */
9062 event_hdl_pause(hlua_sub->sub);
9063 hlua_sub->paused = 1;
9064
9065 /* The following Lua calls can fail. */
9066 if (!SET_SAFE_LJMP(hlua_sub->hlua))
9067 trace = NULL;
9068 trace = hlua_traceback(hlua_sub->hlua->T, ", ");
9069 /* At this point the execution is safe. */
9070 RESET_SAFE_LJMP(hlua_sub->hlua);
9071
9072 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 : ""));
9073 }
9074
9075 if (HLUA_IS_RUNNING(hlua_sub->hlua)) {
9076 /* ongoing hlua event handler, resume it */
9077 hlua_event_handler(hlua_sub->hlua);
9078 } else if ((event = event_hdl_async_equeue_pop(&hlua_sub->equeue))) { /* check for new events */
9079 if (event_hdl_sub_type_equal(event->type, EVENT_HDL_SUB_END)) {
9080 /* ending event: no more events to come */
9081 event_hdl_async_free_event(event);
9082 task_destroy(task);
9083 hlua_event_subscription_destroy(hlua_sub);
9084 return NULL;
9085 }
9086 /* new event: start processing it */
9087
9088 /* The following Lua calls can fail. */
9089 if (!SET_SAFE_LJMP(hlua_sub->hlua)) {
9090 if (lua_type(hlua_sub->hlua->T, -1) == LUA_TSTRING)
9091 error = lua_tostring(hlua_sub->hlua->T, -1);
9092 else
9093 error = "critical error";
9094 ha_alert("Lua event_hdl: %s.\n", error);
9095 goto skip_event;
9096 }
9097
9098 /* Check stack available size. */
9099 if (!lua_checkstack(hlua_sub->hlua->T, 5)) {
9100 ha_alert("Lua event_hdl: full stack.\n");
9101 RESET_SAFE_LJMP(hlua_sub->hlua);
9102 goto skip_event;
9103 }
9104
9105 /* Restore the function in the stack. */
9106 hlua_pushref(hlua_sub->hlua->T, hlua_sub->fcn_ref);
9107
9108 /* push args */
9109 hlua_sub->hlua->nargs = 0;
9110 if (!hlua_event_hdl_cb_data_push_args(hlua_sub, event->type, event->data)) {
9111 RESET_SAFE_LJMP(hlua_sub->hlua);
9112 goto skip_event;
9113 }
9114
9115 /* At this point the execution is safe. */
9116 RESET_SAFE_LJMP(hlua_sub->hlua);
9117
9118 /* At this point the event was successfully translated into hlua ctx,
9119 * or hlua error occured, so we can safely discard it
9120 */
9121 event_hdl_async_free_event(event);
9122 event = NULL;
9123
9124 hlua_event_handler(hlua_sub->hlua);
9125 skip_event:
9126 if (event)
9127 event_hdl_async_free_event(event);
9128
9129 }
9130
9131 if (!HLUA_IS_RUNNING(hlua_sub->hlua)) {
9132 /* we just finished the processing of one event..
9133 * check for new events before becoming idle
9134 */
9135 if (!event_hdl_async_equeue_isempty(&hlua_sub->equeue)) {
9136 /* more events to process, make sure the task
9137 * will be resumed ASAP to process pending events
9138 */
9139 task_wakeup(task, TASK_WOKEN_OTHER);
9140 }
9141 else if (hlua_sub->paused) {
9142 /* empty queue, the handler catched up: resume the subscription */
9143 event_hdl_resume(hlua_sub->sub);
9144 hlua_sub->paused = 0;
9145 }
9146 }
9147
9148 return task;
9149}
9150
9151/* Must be called directly under lua protected/safe environment
9152 * (not from external callback)
9153 * <fcn_ref> should NOT be dropped after the function successfully returns:
9154 * it will be done automatically in hlua_event_subscription_destroy() when the
9155 * subscription ends.
9156 *
9157 * Returns the new subscription on success and NULL on failure (memory error)
9158 */
9159static struct event_hdl_sub *hlua_event_subscribe(event_hdl_sub_list *list, struct event_hdl_sub_type e_type,
9160 int state_id, int fcn_ref)
9161{
9162 struct hlua_event_sub *hlua_sub;
9163 struct task *task = NULL;
9164
9165 hlua_sub = pool_alloc(pool_head_hlua_event_sub);
9166 if (!hlua_sub)
9167 goto mem_error;
9168 hlua_sub->task = NULL;
9169 hlua_sub->hlua = NULL;
9170 hlua_sub->paused = 0;
9171 if ((task = task_new_here()) == NULL) {
9172 ha_alert("out of memory while allocating hlua event task");
9173 goto mem_error;
9174 }
9175 task->process = hlua_event_runner;
9176 task->context = hlua_sub;
9177 event_hdl_async_equeue_init(&hlua_sub->equeue);
9178 hlua_sub->task = task;
9179 hlua_sub->fcn_ref = fcn_ref;
9180 hlua_sub->state_id = state_id;
9181 hlua_sub->hlua = pool_alloc(pool_head_hlua);
9182 if (!hlua_sub->hlua)
9183 goto mem_error;
9184 HLUA_INIT(hlua_sub->hlua);
9185 if (!hlua_ctx_init(hlua_sub->hlua, hlua_sub->state_id, task))
9186 goto mem_error;
9187
9188 hlua_sub->sub = event_hdl_subscribe_ptr(list, e_type,
9189 EVENT_HDL_ASYNC_TASK(&hlua_sub->equeue,
9190 task,
9191 hlua_sub,
9192 NULL));
9193 if (!hlua_sub->sub)
9194 goto mem_error;
9195
9196 return hlua_sub->sub; /* returns pointer to event_hdl_sub struct */
9197
9198 mem_error:
9199 if (hlua_sub) {
9200 if (hlua_sub->task)
9201 task_destroy(hlua_sub->task);
9202 if (hlua_sub->hlua)
9203 hlua_ctx_destroy(hlua_sub->hlua);
9204 pool_free(pool_head_hlua_event_sub, hlua_sub);
9205 }
9206
9207 return NULL;
9208}
9209
9210/* looks for an array of strings referring to a composition of event_hdl subscription
9211 * types at <index> in <L> stack
9212 */
9213__LJMP static struct event_hdl_sub_type hlua_check_event_sub_types(lua_State *L, int index)
9214{
9215 struct event_hdl_sub_type subscriptions;
9216 const char *msg;
9217
9218 if (lua_type(L, index) != LUA_TTABLE) {
9219 msg = lua_pushfstring(L, "table of strings expected, got %s", luaL_typename(L, index));
9220 luaL_argerror(L, index, msg);
9221 }
9222
9223 subscriptions = EVENT_HDL_SUB_NONE;
9224
9225 /* browse the argument as an array. */
9226 lua_pushnil(L);
9227 while (lua_next(L, index) != 0) {
9228 if (lua_type(L, -1) != LUA_TSTRING) {
9229 msg = lua_pushfstring(L, "table of strings expected, got %s", luaL_typename(L, index));
9230 luaL_argerror(L, index, msg);
9231 }
9232
9233 if (event_hdl_sub_type_equal(EVENT_HDL_SUB_NONE, event_hdl_string_to_sub_type(lua_tostring(L, -1)))) {
9234 msg = lua_pushfstring(L, "'%s' event type is unknown", lua_tostring(L, -1));
9235 luaL_argerror(L, index, msg);
9236 }
9237
9238 /* perform subscriptions |= current sub */
9239 subscriptions = event_hdl_sub_type_add(subscriptions, event_hdl_string_to_sub_type(lua_tostring(L, -1)));
9240
9241 /* pop the current value. */
9242 lua_pop(L, 1);
9243 }
9244
9245 return subscriptions;
9246}
9247
9248/* Wrapper for hlua_fcn_new_event_sub(): catch errors raised by
9249 * the function to prevent LJMP
9250 *
9251 * If no error occured, the function returns 1, else it returns 0 and
9252 * the error message is pushed at the top of the stack
9253 */
9254__LJMP static int _hlua_new_event_sub_safe(lua_State *L)
9255{
9256 struct event_hdl_sub *sub = lua_touserdata(L, 1);
9257
9258 /* this function may raise errors */
9259 return MAY_LJMP(hlua_fcn_new_event_sub(L, sub));
9260}
9261static int hlua_new_event_sub_safe(lua_State *L, struct event_hdl_sub *sub)
9262{
9263 if (!lua_checkstack(L, 2))
9264 return 0;
9265 lua_pushcfunction(L, _hlua_new_event_sub_safe);
9266 lua_pushlightuserdata(L, sub);
9267 switch (lua_pcall(L, 1, 1, 0)) {
9268 case LUA_OK:
9269 return 1;
9270 default:
9271 /* error was catched */
9272 return 0;
9273 }
9274}
9275
9276/* This function is a LUA helper used for registering lua event callbacks.
9277 * It expects an event subscription array and the function to be executed
9278 * when subscribed events occur (stack arguments).
9279 * It can be called from the "init" section, "post init" or during the runtime.
9280 *
9281 * <sub_list> is the subscription list where the subscription will be attempted
9282 *
9283 * Pushes the newly allocated subscription on the stack on success
9284 */
9285__LJMP int hlua_event_sub(lua_State *L, event_hdl_sub_list *sub_list)
9286{
9287 struct hlua *hlua;
9288 struct event_hdl_sub *sub;
9289 struct event_hdl_sub_type subscriptions;
9290 int fcn_ref;
9291 int state_id;
9292
9293 MAY_LJMP(check_args(L, 2, "event_sub"));
9294
9295 /* Get the reference state */
9296 hlua = hlua_gethlua(L);
9297 if (hlua)
9298 /* we are in runtime processing, any thread may subscribe to events:
9299 * subscription events will be handled by the thread who performed
9300 * the registration.
9301 */
9302 state_id = hlua->state_id;
9303 else {
9304 /* we are in initialization mode, only thread 0 (actual calling thread)
9305 * may subscribe to events to prevent the same handler (from different lua
9306 * stacks) from being registered multiple times
9307 *
9308 * hlua_state_id == 0: monostack (lua-load)
9309 * hlua_state_id > 0: hlua_state_id=tid+1, multi-stack (lua-load-per-thread)
9310 * (thus if hlua_state_id > 1, it means we are not in primary thread ctx)
9311 */
9312 if (hlua_state_id > 1)
9313 return 0; /* skip registration */
9314 state_id = hlua_state_id;
9315 }
9316
9317 /* First argument : event subscriptions. */
9318 subscriptions = MAY_LJMP(hlua_check_event_sub_types(L, 1));
9319
9320 if (event_hdl_sub_type_equal(subscriptions, EVENT_HDL_SUB_NONE)) {
9321 WILL_LJMP(luaL_error(L, "event_sub: no valid event types were provided"));
9322 return 0; /* Never reached */
9323 }
9324
9325 /* Second argument : lua function. */
9326 fcn_ref = MAY_LJMP(hlua_checkfunction(L, 2));
9327
9328 /* try to subscribe */
9329 sub = hlua_event_subscribe(sub_list, subscriptions, state_id, fcn_ref);
9330 if (!sub) {
9331 hlua_unref(L, fcn_ref);
9332 WILL_LJMP(luaL_error(L, "event_sub: lua out of memory error"));
9333 return 0; /* Never reached */
9334 }
9335
9336 /* push the subscription to the stack
9337 *
9338 * Here we use the safe function so that lua errors will be
9339 * handled explicitly to prevent 'sub' from being lost
9340 */
9341 if (!hlua_new_event_sub_safe(L, sub)) {
9342 /* Some events could already be pending in the handler's queue.
9343 * However it is wiser to cancel the subscription since we are unable to
9344 * provide a valid reference to it.
9345 * Pending events will be delivered (unless lua keeps raising errors).
9346 */
9347 event_hdl_unsubscribe(sub); /* cancel the subscription */
9348 WILL_LJMP(luaL_error(L, "event_sub: cannot push the subscription (%s)", lua_tostring(L, -1)));
9349 return 0; /* Never reached */
9350 }
9351 event_hdl_drop(sub); /* sub has been duplicated, discard old ref */
9352
9353 return 1;
9354}
9355
9356/* This function is a LUA wrapper used for registering global lua event callbacks
9357 * The new subscription is pushed onto the stack on success
9358 * Returns the number of arguments pushed to the stack (1 for success)
9359 */
9360__LJMP static int hlua_event_global_sub(lua_State *L)
9361{
9362 /* NULL <sub_list> = global subscription list */
9363 return MAY_LJMP(hlua_event_sub(L, NULL));
9364}
9365
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009366/* Wrapper called by HAProxy to execute an LUA converter. This wrapper
9367 * doesn't allow "yield" functions because the HAProxy engine cannot
9368 * resume converters.
9369 */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02009370static int hlua_sample_conv_wrapper(const struct arg *arg_p, struct sample *smp, void *private)
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009371{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02009372 struct hlua_function *fcn = private;
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02009373 struct stream *stream = smp->strm;
Thierry Fournierfd107a22016-02-19 19:57:23 +01009374 const char *error;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009375
Willy Tarreaube508f12016-03-10 11:47:01 +01009376 if (!stream)
9377 return 0;
9378
Willy Tarreau87b09662015-04-03 00:22:06 +02009379 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01009380 * Lua context can be not initialized. This behavior
9381 * permits to save performances because a systematic
9382 * Lua initialization cause 5% performances loss.
9383 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009384 if (!stream->hlua) {
Christopher Faulet1e8433f2021-03-24 15:03:01 +01009385 struct hlua *hlua;
9386
9387 hlua = pool_alloc(pool_head_hlua);
9388 if (!hlua) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009389 SEND_ERR(stream->be, "Lua converter '%s': can't initialize Lua context.\n", fcn->name);
9390 return 0;
9391 }
Christopher Faulet1e8433f2021-03-24 15:03:01 +01009392 HLUA_INIT(hlua);
9393 stream->hlua = hlua;
Aurelien DARRAGON6b0b9bd2023-03-21 14:02:16 +01009394 if (!hlua_ctx_init(stream->hlua, fcn_ref_to_stack_id(fcn), stream->task)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009395 SEND_ERR(stream->be, "Lua converter '%s': can't initialize Lua context.\n", fcn->name);
9396 return 0;
9397 }
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01009398 }
9399
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009400 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009401 if (!HLUA_IS_RUNNING(stream->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02009402
9403 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009404 if (!SET_SAFE_LJMP(stream->hlua)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009405 if (lua_type(stream->hlua->T, -1) == LUA_TSTRING)
9406 error = lua_tostring(stream->hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +01009407 else
9408 error = "critical error";
9409 SEND_ERR(stream->be, "Lua converter '%s': %s.\n", fcn->name, error);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02009410 return 0;
9411 }
9412
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009413 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009414 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009415 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009416 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009417 return 0;
9418 }
9419
9420 /* Restore the function in the stack. */
Aurelien DARRAGON4fdf8b52023-03-20 17:22:37 +01009421 hlua_pushref(stream->hlua->T, fcn->function_ref[stream->hlua->state_id]);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009422
9423 /* convert input sample and pust-it in the stack. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009424 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009425 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009426 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009427 return 0;
9428 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009429 hlua_smp2lua(stream->hlua->T, smp);
9430 stream->hlua->nargs = 1;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009431
9432 /* push keywords in the stack. */
9433 if (arg_p) {
9434 for (; arg_p->type != ARGT_STOP; arg_p++) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009435 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009436 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009437 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009438 return 0;
9439 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009440 hlua_arg2lua(stream->hlua->T, arg_p);
9441 stream->hlua->nargs++;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009442 }
9443 }
9444
Thierry FOURNIERbd413492015-03-03 16:52:26 +01009445 /* We must initialize the execution timeouts. */
Aurelien DARRAGONda9503c2022-11-25 09:10:07 +01009446 hlua_timer_init(&stream->hlua->timer, hlua_timeout_session);
Thierry FOURNIERbd413492015-03-03 16:52:26 +01009447
Thierry FOURNIERbabae282015-09-17 11:36:37 +02009448 /* At this point the execution is safe. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009449 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009450 }
9451
9452 /* Execute the function. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009453 switch (hlua_ctx_resume(stream->hlua, 0)) {
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009454 /* finished. */
9455 case HLUA_E_OK:
Thierry FOURNIERfd80df12017-05-12 16:32:20 +02009456 /* If the stack is empty, the function fails. */
9457 if (lua_gettop(stream->hlua->T) <= 0)
9458 return 0;
9459
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009460 /* Convert the returned value in sample. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009461 hlua_lua2smp(stream->hlua->T, -1, smp);
9462 lua_pop(stream->hlua->T, 1);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009463 return 1;
9464
9465 /* yield. */
9466 case HLUA_E_AGAIN:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009467 SEND_ERR(stream->be, "Lua converter '%s': cannot use yielded functions.\n", fcn->name);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009468 return 0;
9469
9470 /* finished with error. */
9471 case HLUA_E_ERRMSG:
9472 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009473 SEND_ERR(stream->be, "Lua converter '%s': %s.\n",
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009474 fcn->name, lua_tostring(stream->hlua->T, -1));
9475 lua_pop(stream->hlua->T, 1);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009476 return 0;
9477
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009478 case HLUA_E_ETMOUT:
9479 SEND_ERR(stream->be, "Lua converter '%s': execution timeout.\n", fcn->name);
9480 return 0;
9481
9482 case HLUA_E_NOMEM:
9483 SEND_ERR(stream->be, "Lua converter '%s': out of memory error.\n", fcn->name);
9484 return 0;
9485
9486 case HLUA_E_YIELD:
9487 SEND_ERR(stream->be, "Lua converter '%s': yield functions like core.tcp() or core.sleep() are not allowed.\n", fcn->name);
9488 return 0;
9489
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009490 case HLUA_E_ERR:
9491 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009492 SEND_ERR(stream->be, "Lua converter '%s' returns an unknown error.\n", fcn->name);
Willy Tarreau14de3952022-11-14 07:08:28 +01009493 __fallthrough;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009494
9495 default:
9496 return 0;
9497 }
9498}
9499
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009500/* Wrapper called by HAProxy to execute a sample-fetch. this wrapper
9501 * doesn't allow "yield" functions because the HAProxy engine cannot
Willy Tarreaube508f12016-03-10 11:47:01 +01009502 * resume sample-fetches. This function will be called by the sample
9503 * fetch engine to call lua-based fetch operations.
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009504 */
Thierry FOURNIER0786d052015-05-11 15:42:45 +02009505static int hlua_sample_fetch_wrapper(const struct arg *arg_p, struct sample *smp,
9506 const char *kw, void *private)
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009507{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02009508 struct hlua_function *fcn = private;
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02009509 struct stream *stream = smp->strm;
Thierry Fournierfd107a22016-02-19 19:57:23 +01009510 const char *error;
Christopher Faulet8c9e6bb2021-08-06 16:29:41 +02009511 unsigned int hflags = HLUA_TXN_NOTERM | HLUA_TXN_SMP_CTX;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009512
Willy Tarreaube508f12016-03-10 11:47:01 +01009513 if (!stream)
9514 return 0;
Christopher Fauletafd8f102018-11-08 11:34:21 +01009515
Willy Tarreau87b09662015-04-03 00:22:06 +02009516 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01009517 * Lua context can be not initialized. This behavior
9518 * permits to save performances because a systematic
9519 * Lua initialization cause 5% performances loss.
9520 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009521 if (!stream->hlua) {
Christopher Faulet1e8433f2021-03-24 15:03:01 +01009522 struct hlua *hlua;
9523
9524 hlua = pool_alloc(pool_head_hlua);
9525 if (!hlua) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009526 SEND_ERR(stream->be, "Lua sample-fetch '%s': can't initialize Lua context.\n", fcn->name);
9527 return 0;
9528 }
Christopher Faulet1e8433f2021-03-24 15:03:01 +01009529 hlua->T = NULL;
9530 stream->hlua = hlua;
Aurelien DARRAGON6b0b9bd2023-03-21 14:02:16 +01009531 if (!hlua_ctx_init(stream->hlua, fcn_ref_to_stack_id(fcn), stream->task)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009532 SEND_ERR(stream->be, "Lua sample-fetch '%s': can't initialize Lua context.\n", fcn->name);
9533 return 0;
9534 }
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01009535 }
9536
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009537 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009538 if (!HLUA_IS_RUNNING(stream->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02009539
9540 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009541 if (!SET_SAFE_LJMP(stream->hlua)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009542 if (lua_type(stream->hlua->T, -1) == LUA_TSTRING)
9543 error = lua_tostring(stream->hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +01009544 else
9545 error = "critical error";
9546 SEND_ERR(smp->px, "Lua sample-fetch '%s': %s.\n", fcn->name, error);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02009547 return 0;
9548 }
9549
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009550 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009551 if (!lua_checkstack(stream->hlua->T, 2)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009552 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009553 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009554 return 0;
9555 }
9556
9557 /* Restore the function in the stack. */
Aurelien DARRAGON4fdf8b52023-03-20 17:22:37 +01009558 hlua_pushref(stream->hlua->T, fcn->function_ref[stream->hlua->state_id]);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009559
9560 /* push arguments in the stack. */
Christopher Fauletbfab2dd2019-07-26 15:09:53 +02009561 if (!hlua_txn_new(stream->hlua->T, stream, smp->px, smp->opt & SMP_OPT_DIR, hflags)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009562 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009563 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009564 return 0;
9565 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009566 stream->hlua->nargs = 1;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009567
9568 /* push keywords in the stack. */
9569 for (; arg_p && arg_p->type != ARGT_STOP; arg_p++) {
9570 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009571 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009572 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009573 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009574 return 0;
9575 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009576 hlua_arg2lua(stream->hlua->T, arg_p);
9577 stream->hlua->nargs++;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009578 }
9579
Thierry FOURNIERbd413492015-03-03 16:52:26 +01009580 /* We must initialize the execution timeouts. */
Aurelien DARRAGONda9503c2022-11-25 09:10:07 +01009581 hlua_timer_init(&stream->hlua->timer, hlua_timeout_session);
Thierry FOURNIERbd413492015-03-03 16:52:26 +01009582
Thierry FOURNIERbabae282015-09-17 11:36:37 +02009583 /* At this point the execution is safe. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009584 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009585 }
9586
9587 /* Execute the function. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009588 switch (hlua_ctx_resume(stream->hlua, 0)) {
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009589 /* finished. */
9590 case HLUA_E_OK:
Thierry FOURNIERfd80df12017-05-12 16:32:20 +02009591 /* If the stack is empty, the function fails. */
9592 if (lua_gettop(stream->hlua->T) <= 0)
9593 return 0;
9594
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009595 /* Convert the returned value in sample. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009596 hlua_lua2smp(stream->hlua->T, -1, smp);
9597 lua_pop(stream->hlua->T, 1);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009598
9599 /* Set the end of execution flag. */
9600 smp->flags &= ~SMP_F_MAY_CHANGE;
9601 return 1;
9602
9603 /* yield. */
9604 case HLUA_E_AGAIN:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009605 SEND_ERR(smp->px, "Lua sample-fetch '%s': cannot use yielded functions.\n", fcn->name);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009606 return 0;
9607
9608 /* finished with error. */
9609 case HLUA_E_ERRMSG:
9610 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009611 SEND_ERR(smp->px, "Lua sample-fetch '%s': %s.\n",
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009612 fcn->name, lua_tostring(stream->hlua->T, -1));
9613 lua_pop(stream->hlua->T, 1);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009614 return 0;
9615
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009616 case HLUA_E_ETMOUT:
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009617 SEND_ERR(smp->px, "Lua sample-fetch '%s': execution timeout.\n", fcn->name);
9618 return 0;
9619
9620 case HLUA_E_NOMEM:
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009621 SEND_ERR(smp->px, "Lua sample-fetch '%s': out of memory error.\n", fcn->name);
9622 return 0;
9623
9624 case HLUA_E_YIELD:
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009625 SEND_ERR(smp->px, "Lua sample-fetch '%s': yield not allowed.\n", fcn->name);
9626 return 0;
9627
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009628 case HLUA_E_ERR:
9629 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009630 SEND_ERR(smp->px, "Lua sample-fetch '%s' returns an unknown error.\n", fcn->name);
Willy Tarreau14de3952022-11-14 07:08:28 +01009631 __fallthrough;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009632
9633 default:
9634 return 0;
9635 }
9636}
9637
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009638/* This function is an LUA binding used for registering
9639 * "sample-conv" functions. It expects a converter name used
9640 * in the haproxy configuration file, and an LUA function.
9641 */
9642__LJMP static int hlua_register_converters(lua_State *L)
9643{
9644 struct sample_conv_kw_list *sck;
9645 const char *name;
9646 int ref;
9647 int len;
Christopher Fauletaa224302021-04-12 14:08:21 +02009648 struct hlua_function *fcn = NULL;
Thierry Fournierf67442e2020-11-28 20:41:07 +01009649 struct sample_conv *sc;
9650 struct buffer *trash;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009651
9652 MAY_LJMP(check_args(L, 2, "register_converters"));
9653
Aurelien DARRAGON87f52972023-02-24 09:43:54 +01009654 if (hlua_gethlua(L)) {
9655 /* runtime processing */
9656 WILL_LJMP(luaL_error(L, "register_converters: not available outside of body context"));
9657 }
9658
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009659 /* First argument : converter name. */
9660 name = MAY_LJMP(luaL_checkstring(L, 1));
9661
9662 /* Second argument : lua function. */
9663 ref = MAY_LJMP(hlua_checkfunction(L, 2));
9664
Thierry Fournierf67442e2020-11-28 20:41:07 +01009665 /* Check if the converter is already registered */
9666 trash = get_trash_chunk();
9667 chunk_printf(trash, "lua.%s", name);
9668 sc = find_sample_conv(trash->area, trash->data);
9669 if (sc != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +01009670 fcn = sc->private;
9671 if (fcn->function_ref[hlua_state_id] != -1) {
9672 ha_warning("Trying to register converter 'lua.%s' more than once. "
9673 "This will become a hard error in version 2.5.\n", name);
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +01009674 hlua_unref(L, fcn->function_ref[hlua_state_id]);
Thierry Fournier59f11be2020-11-29 00:37:41 +01009675 }
9676 fcn->function_ref[hlua_state_id] = ref;
9677 return 0;
Thierry Fournierf67442e2020-11-28 20:41:07 +01009678 }
9679
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009680 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02009681 sck = calloc(1, sizeof(*sck) + sizeof(struct sample_conv) * 2);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009682 if (!sck)
Christopher Fauletaa224302021-04-12 14:08:21 +02009683 goto alloc_error;
Thierry Fournier62a22aa2020-11-28 21:06:35 +01009684 fcn = new_hlua_function();
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009685 if (!fcn)
Christopher Fauletaa224302021-04-12 14:08:21 +02009686 goto alloc_error;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009687
9688 /* Fill fcn. */
9689 fcn->name = strdup(name);
9690 if (!fcn->name)
Christopher Fauletaa224302021-04-12 14:08:21 +02009691 goto alloc_error;
Thierry Fournierc7492592020-11-28 23:57:24 +01009692 fcn->function_ref[hlua_state_id] = ref;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009693
9694 /* List head */
9695 sck->list.n = sck->list.p = NULL;
9696
9697 /* converter keyword. */
9698 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02009699 sck->kw[0].kw = calloc(1, len);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009700 if (!sck->kw[0].kw)
Christopher Fauletaa224302021-04-12 14:08:21 +02009701 goto alloc_error;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009702
9703 snprintf((char *)sck->kw[0].kw, len, "lua.%s", name);
9704 sck->kw[0].process = hlua_sample_conv_wrapper;
David Carlier0c437f42016-04-27 16:21:56 +01009705 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 +01009706 sck->kw[0].val_args = NULL;
9707 sck->kw[0].in_type = SMP_T_STR;
9708 sck->kw[0].out_type = SMP_T_STR;
9709 sck->kw[0].private = fcn;
9710
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009711 /* Register this new converter */
9712 sample_register_convs(sck);
9713
9714 return 0;
Christopher Fauletaa224302021-04-12 14:08:21 +02009715
9716 alloc_error:
9717 release_hlua_function(fcn);
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +01009718 hlua_unref(L, ref);
Christopher Fauletaa224302021-04-12 14:08:21 +02009719 ha_free(&sck);
9720 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
9721 return 0; /* Never reached */
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009722}
9723
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08009724/* This function is an LUA binding used for registering
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009725 * "sample-fetch" functions. It expects a converter name used
9726 * in the haproxy configuration file, and an LUA function.
9727 */
9728__LJMP static int hlua_register_fetches(lua_State *L)
9729{
9730 const char *name;
9731 int ref;
9732 int len;
9733 struct sample_fetch_kw_list *sfk;
Christopher Faulet2567f182021-04-12 14:11:50 +02009734 struct hlua_function *fcn = NULL;
Thierry Fournierf67442e2020-11-28 20:41:07 +01009735 struct sample_fetch *sf;
9736 struct buffer *trash;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009737
9738 MAY_LJMP(check_args(L, 2, "register_fetches"));
9739
Aurelien DARRAGON87f52972023-02-24 09:43:54 +01009740 if (hlua_gethlua(L)) {
9741 /* runtime processing */
9742 WILL_LJMP(luaL_error(L, "register_fetches: not available outside of body context"));
9743 }
9744
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009745 /* First argument : sample-fetch name. */
9746 name = MAY_LJMP(luaL_checkstring(L, 1));
9747
9748 /* Second argument : lua function. */
9749 ref = MAY_LJMP(hlua_checkfunction(L, 2));
9750
Thierry Fournierf67442e2020-11-28 20:41:07 +01009751 /* Check if the sample-fetch is already registered */
9752 trash = get_trash_chunk();
9753 chunk_printf(trash, "lua.%s", name);
9754 sf = find_sample_fetch(trash->area, trash->data);
9755 if (sf != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +01009756 fcn = sf->private;
9757 if (fcn->function_ref[hlua_state_id] != -1) {
9758 ha_warning("Trying to register sample-fetch 'lua.%s' more than once. "
9759 "This will become a hard error in version 2.5.\n", name);
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +01009760 hlua_unref(L, fcn->function_ref[hlua_state_id]);
Thierry Fournier59f11be2020-11-29 00:37:41 +01009761 }
9762 fcn->function_ref[hlua_state_id] = ref;
9763 return 0;
Thierry Fournierf67442e2020-11-28 20:41:07 +01009764 }
9765
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009766 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02009767 sfk = calloc(1, sizeof(*sfk) + sizeof(struct sample_fetch) * 2);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009768 if (!sfk)
Christopher Faulet2567f182021-04-12 14:11:50 +02009769 goto alloc_error;
Thierry Fournier62a22aa2020-11-28 21:06:35 +01009770 fcn = new_hlua_function();
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009771 if (!fcn)
Christopher Faulet2567f182021-04-12 14:11:50 +02009772 goto alloc_error;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009773
9774 /* Fill fcn. */
9775 fcn->name = strdup(name);
9776 if (!fcn->name)
Christopher Faulet2567f182021-04-12 14:11:50 +02009777 goto alloc_error;
Thierry Fournierc7492592020-11-28 23:57:24 +01009778 fcn->function_ref[hlua_state_id] = ref;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009779
9780 /* List head */
9781 sfk->list.n = sfk->list.p = NULL;
9782
9783 /* sample-fetch keyword. */
9784 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02009785 sfk->kw[0].kw = calloc(1, len);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009786 if (!sfk->kw[0].kw)
Christopher Faulet2567f182021-04-12 14:11:50 +02009787 goto alloc_error;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009788
9789 snprintf((char *)sfk->kw[0].kw, len, "lua.%s", name);
9790 sfk->kw[0].process = hlua_sample_fetch_wrapper;
David Carlier0c437f42016-04-27 16:21:56 +01009791 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 +01009792 sfk->kw[0].val_args = NULL;
9793 sfk->kw[0].out_type = SMP_T_STR;
9794 sfk->kw[0].use = SMP_USE_HTTP_ANY;
9795 sfk->kw[0].val = 0;
9796 sfk->kw[0].private = fcn;
9797
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009798 /* Register this new fetch. */
9799 sample_register_fetches(sfk);
9800
9801 return 0;
Christopher Faulet2567f182021-04-12 14:11:50 +02009802
9803 alloc_error:
9804 release_hlua_function(fcn);
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +01009805 hlua_unref(L, ref);
Christopher Faulet2567f182021-04-12 14:11:50 +02009806 ha_free(&sfk);
9807 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
9808 return 0; /* Never reached */
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009809}
9810
Christopher Faulet501465d2020-02-26 14:54:16 +01009811/* This function is a lua binding to set the wake_time.
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01009812 */
Christopher Faulet501465d2020-02-26 14:54:16 +01009813__LJMP static int hlua_set_wake_time(lua_State *L)
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01009814{
Thierry Fournier4234dbd2020-11-28 13:18:23 +01009815 struct hlua *hlua;
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01009816 unsigned int delay;
9817 unsigned int wakeup_ms;
9818
Thierry Fournier4234dbd2020-11-28 13:18:23 +01009819 /* Get hlua struct, or NULL if we execute from main lua state */
9820 hlua = hlua_gethlua(L);
9821 if (!hlua) {
9822 return 0;
9823 }
9824
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01009825 MAY_LJMP(check_args(L, 1, "wake_time"));
9826
9827 delay = MAY_LJMP(luaL_checkinteger(L, 1));
9828 wakeup_ms = tick_add(now_ms, delay);
9829 hlua->wake_time = wakeup_ms;
9830 return 0;
9831}
9832
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009833/* This function is a wrapper to execute each LUA function declared as an action
9834 * wrapper during the initialisation period. This function may return any
9835 * ACT_RET_* value. On error ACT_RET_CONT is returned and the action is
9836 * ignored. If the lua action yields, ACT_RET_YIELD is returned. On success, the
9837 * return value is the first element on the stack.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009838 */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009839static enum act_return hlua_action(struct act_rule *rule, struct proxy *px,
Willy Tarreau658b85b2015-09-27 10:00:49 +02009840 struct session *sess, struct stream *s, int flags)
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009841{
9842 char **arg;
Christopher Faulet8c9e6bb2021-08-06 16:29:41 +02009843 unsigned int hflags = HLUA_TXN_ACT_CTX;
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009844 int dir, act_ret = ACT_RET_CONT;
Thierry Fournierfd107a22016-02-19 19:57:23 +01009845 const char *error;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009846
9847 switch (rule->from) {
Christopher Fauletd8f0e072020-02-25 09:45:51 +01009848 case ACT_F_TCP_REQ_CNT: dir = SMP_OPT_DIR_REQ; break;
9849 case ACT_F_TCP_RES_CNT: dir = SMP_OPT_DIR_RES; break;
9850 case ACT_F_HTTP_REQ: dir = SMP_OPT_DIR_REQ; break;
9851 case ACT_F_HTTP_RES: dir = SMP_OPT_DIR_RES; break;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009852 default:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009853 SEND_ERR(px, "Lua: internal error while execute action.\n");
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009854 goto end;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009855 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009856
Willy Tarreau87b09662015-04-03 00:22:06 +02009857 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01009858 * Lua context can be not initialized. This behavior
9859 * permits to save performances because a systematic
9860 * Lua initialization cause 5% performances loss.
9861 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009862 if (!s->hlua) {
Christopher Faulet1e8433f2021-03-24 15:03:01 +01009863 struct hlua *hlua;
9864
9865 hlua = pool_alloc(pool_head_hlua);
9866 if (!hlua) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009867 SEND_ERR(px, "Lua action '%s': can't initialize Lua context.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009868 rule->arg.hlua_rule->fcn->name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009869 goto end;
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009870 }
Christopher Faulet1e8433f2021-03-24 15:03:01 +01009871 HLUA_INIT(hlua);
9872 s->hlua = hlua;
Aurelien DARRAGON6b0b9bd2023-03-21 14:02:16 +01009873 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 +01009874 SEND_ERR(px, "Lua action '%s': can't initialize Lua context.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009875 rule->arg.hlua_rule->fcn->name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009876 goto end;
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009877 }
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01009878 }
9879
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009880 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009881 if (!HLUA_IS_RUNNING(s->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02009882
9883 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009884 if (!SET_SAFE_LJMP(s->hlua)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009885 if (lua_type(s->hlua->T, -1) == LUA_TSTRING)
9886 error = lua_tostring(s->hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +01009887 else
9888 error = "critical error";
9889 SEND_ERR(px, "Lua function '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009890 rule->arg.hlua_rule->fcn->name, error);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009891 goto end;
Thierry FOURNIERbabae282015-09-17 11:36:37 +02009892 }
9893
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009894 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009895 if (!lua_checkstack(s->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009896 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009897 rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009898 RESET_SAFE_LJMP(s->hlua);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009899 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009900 }
9901
9902 /* Restore the function in the stack. */
Aurelien DARRAGON4fdf8b52023-03-20 17:22:37 +01009903 hlua_pushref(s->hlua->T, rule->arg.hlua_rule->fcn->function_ref[s->hlua->state_id]);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009904
Willy Tarreau87b09662015-04-03 00:22:06 +02009905 /* Create and and push object stream in the stack. */
Christopher Fauletbfab2dd2019-07-26 15:09:53 +02009906 if (!hlua_txn_new(s->hlua->T, s, px, dir, hflags)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009907 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009908 rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009909 RESET_SAFE_LJMP(s->hlua);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009910 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009911 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009912 s->hlua->nargs = 1;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009913
9914 /* push keywords in the stack. */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009915 for (arg = rule->arg.hlua_rule->args; arg && *arg; arg++) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009916 if (!lua_checkstack(s->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009917 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009918 rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009919 RESET_SAFE_LJMP(s->hlua);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009920 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009921 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009922 lua_pushstring(s->hlua->T, *arg);
9923 s->hlua->nargs++;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009924 }
9925
Thierry FOURNIERbabae282015-09-17 11:36:37 +02009926 /* Now the execution is safe. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009927 RESET_SAFE_LJMP(s->hlua);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02009928
Thierry FOURNIERbd413492015-03-03 16:52:26 +01009929 /* We must initialize the execution timeouts. */
Aurelien DARRAGONda9503c2022-11-25 09:10:07 +01009930 hlua_timer_init(&s->hlua->timer, hlua_timeout_session);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009931 }
9932
9933 /* Execute the function. */
Christopher Faulet105ba6c2019-12-18 14:41:51 +01009934 switch (hlua_ctx_resume(s->hlua, !(flags & ACT_OPT_FINAL))) {
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009935 /* finished. */
9936 case HLUA_E_OK:
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009937 /* Catch the return value */
9938 if (lua_gettop(s->hlua->T) > 0)
9939 act_ret = lua_tointeger(s->hlua->T, -1);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009940
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01009941 /* Set timeout in the required channel. */
Christopher Faulet498c4832020-07-28 11:59:58 +02009942 if (act_ret == ACT_RET_YIELD) {
9943 if (flags & ACT_OPT_FINAL)
9944 goto err_yield;
9945
Christopher Faulet8f587ea2020-07-28 12:01:55 +02009946 if (dir == SMP_OPT_DIR_REQ)
9947 s->req.analyse_exp = tick_first((tick_is_expired(s->req.analyse_exp, now_ms) ? 0 : s->req.analyse_exp),
9948 s->hlua->wake_time);
9949 else
9950 s->res.analyse_exp = tick_first((tick_is_expired(s->res.analyse_exp, now_ms) ? 0 : s->res.analyse_exp),
9951 s->hlua->wake_time);
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01009952 }
9953 goto end;
9954
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009955 /* yield. */
9956 case HLUA_E_AGAIN:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01009957 /* Set timeout in the required channel. */
Christopher Faulet8f587ea2020-07-28 12:01:55 +02009958 if (dir == SMP_OPT_DIR_REQ)
9959 s->req.analyse_exp = tick_first((tick_is_expired(s->req.analyse_exp, now_ms) ? 0 : s->req.analyse_exp),
9960 s->hlua->wake_time);
9961 else
9962 s->res.analyse_exp = tick_first((tick_is_expired(s->res.analyse_exp, now_ms) ? 0 : s->res.analyse_exp),
9963 s->hlua->wake_time);
9964
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009965 /* Some actions can be wake up when a "write" event
9966 * is detected on a response channel. This is useful
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08009967 * only for actions targeted on the requests.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009968 */
Christopher Faulet51fa3582019-07-26 14:54:52 +02009969 if (HLUA_IS_WAKERESWR(s->hlua))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01009970 s->res.flags |= CF_WAKE_WRITE;
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009971 if (HLUA_IS_WAKEREQWR(s->hlua))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01009972 s->req.flags |= CF_WAKE_WRITE;
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009973 act_ret = ACT_RET_YIELD;
9974 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009975
9976 /* finished with error. */
9977 case HLUA_E_ERRMSG:
9978 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009979 SEND_ERR(px, "Lua function '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009980 rule->arg.hlua_rule->fcn->name, lua_tostring(s->hlua->T, -1));
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009981 lua_pop(s->hlua->T, 1);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009982 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009983
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009984 case HLUA_E_ETMOUT:
Thierry Fournierad5345f2020-11-29 02:05:57 +01009985 SEND_ERR(px, "Lua function '%s': execution timeout.\n", rule->arg.hlua_rule->fcn->name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009986 goto end;
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009987
9988 case HLUA_E_NOMEM:
Thierry Fournierad5345f2020-11-29 02:05:57 +01009989 SEND_ERR(px, "Lua function '%s': out of memory error.\n", rule->arg.hlua_rule->fcn->name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009990 goto end;
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009991
9992 case HLUA_E_YIELD:
Christopher Faulet498c4832020-07-28 11:59:58 +02009993 err_yield:
9994 act_ret = ACT_RET_CONT;
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009995 SEND_ERR(px, "Lua function '%s': aborting Lua processing on expired timeout.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009996 rule->arg.hlua_rule->fcn->name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009997 goto end;
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009998
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009999 case HLUA_E_ERR:
10000 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +020010001 SEND_ERR(px, "Lua function '%s' return an unknown error.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010002 rule->arg.hlua_rule->fcn->name);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +010010003
10004 default:
Christopher Faulet7716cdf2020-01-29 11:53:30 +010010005 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +010010006 }
Christopher Faulet7716cdf2020-01-29 11:53:30 +010010007
10008 end:
Christopher Faulet2361fd92020-07-30 10:40:58 +020010009 if (act_ret != ACT_RET_YIELD && s->hlua)
Christopher Faulet8f587ea2020-07-28 12:01:55 +020010010 s->hlua->wake_time = TICK_ETERNITY;
Christopher Faulet7716cdf2020-01-29 11:53:30 +010010011 return act_ret;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +010010012}
10013
Willy Tarreau144f84a2021-03-02 16:09:26 +010010014struct task *hlua_applet_wakeup(struct task *t, void *context, unsigned int state)
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010015{
Olivier Houchard9f6af332018-05-25 14:04:04 +020010016 struct appctx *ctx = context;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010017
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010018 appctx_wakeup(ctx);
Willy Tarreaud9587412017-08-23 16:07:33 +020010019 t->expire = TICK_ETERNITY;
Willy Tarreaud1aa41f2017-07-21 16:41:56 +020010020 return t;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010021}
10022
Christopher Faulet4aa1d282022-01-13 16:01:35 +010010023static int hlua_applet_tcp_init(struct appctx *ctx)
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010024{
Willy Tarreaue23f33b2022-05-06 14:07:13 +020010025 struct hlua_tcp_ctx *tcp_ctx = applet_reserve_svcctx(ctx, sizeof(*tcp_ctx));
Willy Tarreauc12b3212022-05-27 11:08:15 +020010026 struct stconn *sc = appctx_sc(ctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +020010027 struct stream *strm = __sc_strm(sc);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +010010028 struct hlua *hlua;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010029 struct task *task;
10030 char **arg;
Thierry Fournierfd107a22016-02-19 19:57:23 +010010031 const char *error;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010032
Willy Tarreaubafbe012017-11-24 17:34:44 +010010033 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +010010034 if (!hlua) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +010010035 SEND_ERR(strm->be, "Lua applet tcp '%s': out of memory.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010036 ctx->rule->arg.hlua_rule->fcn->name);
Christopher Fauletc9929382022-05-12 11:52:27 +020010037 return -1;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +010010038 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010039 HLUA_INIT(hlua);
Willy Tarreaue23f33b2022-05-06 14:07:13 +020010040 tcp_ctx->hlua = hlua;
10041 tcp_ctx->flags = 0;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010042
10043 /* Create task used by signal to wakeup applets. */
Willy Tarreaubeeabf52021-10-01 18:23:30 +020010044 task = task_new_here();
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010045 if (!task) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +010010046 SEND_ERR(strm->be, "Lua applet tcp '%s': out of memory.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010047 ctx->rule->arg.hlua_rule->fcn->name);
Christopher Fauletc9929382022-05-12 11:52:27 +020010048 return -1;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010049 }
10050 task->nice = 0;
10051 task->context = ctx;
10052 task->process = hlua_applet_wakeup;
Willy Tarreaue23f33b2022-05-06 14:07:13 +020010053 tcp_ctx->task = task;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010054
10055 /* In the execution wrappers linked with a stream, the
10056 * Lua context can be not initialized. This behavior
10057 * permits to save performances because a systematic
10058 * Lua initialization cause 5% performances loss.
10059 */
Aurelien DARRAGON6b0b9bd2023-03-21 14:02:16 +010010060 if (!hlua_ctx_init(hlua, fcn_ref_to_stack_id(ctx->rule->arg.hlua_rule->fcn), task)) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +010010061 SEND_ERR(strm->be, "Lua applet tcp '%s': can't initialize Lua context.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010062 ctx->rule->arg.hlua_rule->fcn->name);
Christopher Fauletc9929382022-05-12 11:52:27 +020010063 return -1;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010064 }
10065
10066 /* Set timeout according with the applet configuration. */
Aurelien DARRAGONda9503c2022-11-25 09:10:07 +010010067 hlua_timer_init(&hlua->timer, ctx->applet->timeout);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010068
10069 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010070 if (!SET_SAFE_LJMP(hlua)) {
Thierry Fournierfd107a22016-02-19 19:57:23 +010010071 if (lua_type(hlua->T, -1) == LUA_TSTRING)
10072 error = lua_tostring(hlua->T, -1);
10073 else
10074 error = "critical error";
Christopher Faulet4aa1d282022-01-13 16:01:35 +010010075 SEND_ERR(strm->be, "Lua applet tcp '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010076 ctx->rule->arg.hlua_rule->fcn->name, error);
Christopher Fauletc9929382022-05-12 11:52:27 +020010077 return -1;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010078 }
10079
10080 /* Check stack available size. */
10081 if (!lua_checkstack(hlua->T, 1)) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +010010082 SEND_ERR(strm->be, "Lua applet tcp '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010083 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010084 RESET_SAFE_LJMP(hlua);
Christopher Fauletc9929382022-05-12 11:52:27 +020010085 return -1;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010086 }
10087
10088 /* Restore the function in the stack. */
Aurelien DARRAGON4fdf8b52023-03-20 17:22:37 +010010089 hlua_pushref(hlua->T, ctx->rule->arg.hlua_rule->fcn->function_ref[hlua->state_id]);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010090
10091 /* Create and and push object stream in the stack. */
10092 if (!hlua_applet_tcp_new(hlua->T, ctx)) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +010010093 SEND_ERR(strm->be, "Lua applet tcp '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010094 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010095 RESET_SAFE_LJMP(hlua);
Christopher Fauletc9929382022-05-12 11:52:27 +020010096 return -1;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010097 }
10098 hlua->nargs = 1;
10099
10100 /* push keywords in the stack. */
10101 for (arg = ctx->rule->arg.hlua_rule->args; arg && *arg; arg++) {
10102 if (!lua_checkstack(hlua->T, 1)) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +010010103 SEND_ERR(strm->be, "Lua applet tcp '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010104 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010105 RESET_SAFE_LJMP(hlua);
Christopher Fauletc9929382022-05-12 11:52:27 +020010106 return -1;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010107 }
10108 lua_pushstring(hlua->T, *arg);
10109 hlua->nargs++;
10110 }
10111
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010112 RESET_SAFE_LJMP(hlua);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010113
10114 /* Wakeup the applet ASAP. */
Willy Tarreau90e8b452022-05-25 18:21:43 +020010115 applet_need_more_data(ctx);
Willy Tarreau4164eb92022-05-25 15:42:03 +020010116 applet_have_more_data(ctx);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010117
Christopher Fauletc9929382022-05-12 11:52:27 +020010118 return 0;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010119}
10120
Willy Tarreau60409db2019-08-21 14:14:50 +020010121void hlua_applet_tcp_fct(struct appctx *ctx)
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010122{
Willy Tarreaue23f33b2022-05-06 14:07:13 +020010123 struct hlua_tcp_ctx *tcp_ctx = ctx->svcctx;
Willy Tarreauc12b3212022-05-27 11:08:15 +020010124 struct stconn *sc = appctx_sc(ctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +020010125 struct stream *strm = __sc_strm(sc);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010126 struct act_rule *rule = ctx->rule;
10127 struct proxy *px = strm->be;
Willy Tarreaue23f33b2022-05-06 14:07:13 +020010128 struct hlua *hlua = tcp_ctx->hlua;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010129
Christopher Faulet31572222023-03-31 11:13:48 +020010130 if (unlikely(se_fl_test(ctx->sedesc, (SE_FL_EOS|SE_FL_ERROR|SE_FL_SHR|SE_FL_SHW))))
10131 goto out;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010132
Christopher Faulet31572222023-03-31 11:13:48 +020010133 /* The applet execution is already done. */
10134 if (tcp_ctx->flags & APPLET_DONE)
10135 goto out;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010136
10137 /* Execute the function. */
10138 switch (hlua_ctx_resume(hlua, 1)) {
10139 /* finished. */
10140 case HLUA_E_OK:
Willy Tarreaue23f33b2022-05-06 14:07:13 +020010141 tcp_ctx->flags |= APPLET_DONE;
Christopher Faulet31572222023-03-31 11:13:48 +020010142 se_fl_set(ctx->sedesc, SE_FL_EOI|SE_FL_EOS);
10143 break;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010144
10145 /* yield. */
10146 case HLUA_E_AGAIN:
Thierry Fournier0164f202016-02-20 17:47:43 +010010147 if (hlua->wake_time != TICK_ETERNITY)
Willy Tarreaue23f33b2022-05-06 14:07:13 +020010148 task_schedule(tcp_ctx->task, hlua->wake_time);
Christopher Faulet31572222023-03-31 11:13:48 +020010149 break;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010150
10151 /* finished with error. */
10152 case HLUA_E_ERRMSG:
10153 /* Display log. */
10154 SEND_ERR(px, "Lua applet tcp '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010155 rule->arg.hlua_rule->fcn->name, lua_tostring(hlua->T, -1));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010156 lua_pop(hlua->T, 1);
10157 goto error;
10158
Thierry Fournierd5b073c2018-05-21 19:42:47 +020010159 case HLUA_E_ETMOUT:
10160 SEND_ERR(px, "Lua applet tcp '%s': execution timeout.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010161 rule->arg.hlua_rule->fcn->name);
Thierry Fournierd5b073c2018-05-21 19:42:47 +020010162 goto error;
10163
10164 case HLUA_E_NOMEM:
10165 SEND_ERR(px, "Lua applet tcp '%s': out of memory error.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010166 rule->arg.hlua_rule->fcn->name);
Thierry Fournierd5b073c2018-05-21 19:42:47 +020010167 goto error;
10168
10169 case HLUA_E_YIELD: /* unexpected */
10170 SEND_ERR(px, "Lua applet tcp '%s': yield not allowed.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010171 rule->arg.hlua_rule->fcn->name);
Thierry Fournierd5b073c2018-05-21 19:42:47 +020010172 goto error;
10173
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010174 case HLUA_E_ERR:
10175 /* Display log. */
10176 SEND_ERR(px, "Lua applet tcp '%s' return an unknown error.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010177 rule->arg.hlua_rule->fcn->name);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010178 goto error;
10179
10180 default:
10181 goto error;
10182 }
10183
Christopher Faulet31572222023-03-31 11:13:48 +020010184out:
10185 /* eat the whole request */
10186 co_skip(sc_oc(sc), co_data(sc_oc(sc)));
10187 return;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010188
Christopher Faulet31572222023-03-31 11:13:48 +020010189error:
10190 se_fl_set(ctx->sedesc, SE_FL_ERROR);
Willy Tarreaue23f33b2022-05-06 14:07:13 +020010191 tcp_ctx->flags |= APPLET_DONE;
Christopher Faulet31572222023-03-31 11:13:48 +020010192 goto out;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010193}
10194
10195static void hlua_applet_tcp_release(struct appctx *ctx)
10196{
Willy Tarreaue23f33b2022-05-06 14:07:13 +020010197 struct hlua_tcp_ctx *tcp_ctx = ctx->svcctx;
10198
10199 task_destroy(tcp_ctx->task);
10200 tcp_ctx->task = NULL;
10201 hlua_ctx_destroy(tcp_ctx->hlua);
10202 tcp_ctx->hlua = NULL;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010203}
10204
Christopher Fauletc9929382022-05-12 11:52:27 +020010205/* The function returns 0 if the initialisation is complete or -1 if
10206 * an errors occurs. It also reserves the appctx for an hlua_http_ctx.
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010207 */
Christopher Faulet4aa1d282022-01-13 16:01:35 +010010208static int hlua_applet_http_init(struct appctx *ctx)
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010209{
Willy Tarreauaa229cc2022-05-06 14:26:10 +020010210 struct hlua_http_ctx *http_ctx = applet_reserve_svcctx(ctx, sizeof(*http_ctx));
Willy Tarreauc12b3212022-05-27 11:08:15 +020010211 struct stconn *sc = appctx_sc(ctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +020010212 struct stream *strm = __sc_strm(sc);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010213 struct http_txn *txn;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +010010214 struct hlua *hlua;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010215 char **arg;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010216 struct task *task;
Thierry Fournierfd107a22016-02-19 19:57:23 +010010217 const char *error;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010218
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010219 txn = strm->txn;
Willy Tarreaubafbe012017-11-24 17:34:44 +010010220 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +010010221 if (!hlua) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +010010222 SEND_ERR(strm->be, "Lua applet http '%s': out of memory.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010223 ctx->rule->arg.hlua_rule->fcn->name);
Christopher Fauletc9929382022-05-12 11:52:27 +020010224 return -1;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +010010225 }
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010226 HLUA_INIT(hlua);
Willy Tarreauaa229cc2022-05-06 14:26:10 +020010227 http_ctx->hlua = hlua;
10228 http_ctx->left_bytes = -1;
10229 http_ctx->flags = 0;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010230
Thierry FOURNIERd93ea2b2015-12-20 19:14:52 +010010231 if (txn->req.flags & HTTP_MSGF_VER_11)
Willy Tarreauaa229cc2022-05-06 14:26:10 +020010232 http_ctx->flags |= APPLET_HTTP11;
Thierry FOURNIERd93ea2b2015-12-20 19:14:52 +010010233
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010234 /* Create task used by signal to wakeup applets. */
Willy Tarreaubeeabf52021-10-01 18:23:30 +020010235 task = task_new_here();
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010236 if (!task) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +010010237 SEND_ERR(strm->be, "Lua applet http '%s': out of memory.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010238 ctx->rule->arg.hlua_rule->fcn->name);
Christopher Fauletc9929382022-05-12 11:52:27 +020010239 return -1;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010240 }
10241 task->nice = 0;
10242 task->context = ctx;
10243 task->process = hlua_applet_wakeup;
Willy Tarreauaa229cc2022-05-06 14:26:10 +020010244 http_ctx->task = task;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010245
10246 /* In the execution wrappers linked with a stream, the
10247 * Lua context can be not initialized. This behavior
10248 * permits to save performances because a systematic
10249 * Lua initialization cause 5% performances loss.
10250 */
Aurelien DARRAGON6b0b9bd2023-03-21 14:02:16 +010010251 if (!hlua_ctx_init(hlua, fcn_ref_to_stack_id(ctx->rule->arg.hlua_rule->fcn), task)) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +010010252 SEND_ERR(strm->be, "Lua applet http '%s': can't initialize Lua context.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010253 ctx->rule->arg.hlua_rule->fcn->name);
Christopher Fauletc9929382022-05-12 11:52:27 +020010254 return -1;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010255 }
10256
10257 /* Set timeout according with the applet configuration. */
Aurelien DARRAGONda9503c2022-11-25 09:10:07 +010010258 hlua_timer_init(&hlua->timer, ctx->applet->timeout);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010259
10260 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010261 if (!SET_SAFE_LJMP(hlua)) {
Thierry Fournierfd107a22016-02-19 19:57:23 +010010262 if (lua_type(hlua->T, -1) == LUA_TSTRING)
10263 error = lua_tostring(hlua->T, -1);
10264 else
10265 error = "critical error";
Christopher Faulet4aa1d282022-01-13 16:01:35 +010010266 SEND_ERR(strm->be, "Lua applet http '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010267 ctx->rule->arg.hlua_rule->fcn->name, error);
Christopher Fauletc9929382022-05-12 11:52:27 +020010268 return -1;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010269 }
10270
10271 /* Check stack available size. */
10272 if (!lua_checkstack(hlua->T, 1)) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +010010273 SEND_ERR(strm->be, "Lua applet http '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010274 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010275 RESET_SAFE_LJMP(hlua);
Christopher Fauletc9929382022-05-12 11:52:27 +020010276 return -1;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010277 }
10278
10279 /* Restore the function in the stack. */
Aurelien DARRAGON4fdf8b52023-03-20 17:22:37 +010010280 hlua_pushref(hlua->T, ctx->rule->arg.hlua_rule->fcn->function_ref[hlua->state_id]);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010281
10282 /* Create and and push object stream in the stack. */
10283 if (!hlua_applet_http_new(hlua->T, ctx)) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +010010284 SEND_ERR(strm->be, "Lua applet http '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010285 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010286 RESET_SAFE_LJMP(hlua);
Christopher Fauletc9929382022-05-12 11:52:27 +020010287 return -1;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010288 }
10289 hlua->nargs = 1;
10290
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010291 /* push keywords in the stack. */
10292 for (arg = ctx->rule->arg.hlua_rule->args; arg && *arg; arg++) {
10293 if (!lua_checkstack(hlua->T, 1)) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +010010294 SEND_ERR(strm->be, "Lua applet http '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010295 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010296 RESET_SAFE_LJMP(hlua);
Christopher Fauletc9929382022-05-12 11:52:27 +020010297 return -1;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010298 }
10299 lua_pushstring(hlua->T, *arg);
10300 hlua->nargs++;
10301 }
10302
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010303 RESET_SAFE_LJMP(hlua);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010304
10305 /* Wakeup the applet when data is ready for read. */
Willy Tarreau90e8b452022-05-25 18:21:43 +020010306 applet_need_more_data(ctx);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010307
Christopher Fauletc9929382022-05-12 11:52:27 +020010308 return 0;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010309}
10310
Willy Tarreau60409db2019-08-21 14:14:50 +020010311void hlua_applet_http_fct(struct appctx *ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010312{
Willy Tarreauaa229cc2022-05-06 14:26:10 +020010313 struct hlua_http_ctx *http_ctx = ctx->svcctx;
Willy Tarreauc12b3212022-05-27 11:08:15 +020010314 struct stconn *sc = appctx_sc(ctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +020010315 struct stream *strm = __sc_strm(sc);
10316 struct channel *req = sc_oc(sc);
10317 struct channel *res = sc_ic(sc);
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010318 struct act_rule *rule = ctx->rule;
10319 struct proxy *px = strm->be;
Willy Tarreauaa229cc2022-05-06 14:26:10 +020010320 struct hlua *hlua = http_ctx->hlua;
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010321 struct htx *req_htx, *res_htx;
10322
10323 res_htx = htx_from_buf(&res->buf);
10324
Christopher Faulet31572222023-03-31 11:13:48 +020010325 if (unlikely(se_fl_test(ctx->sedesc, (SE_FL_EOS|SE_FL_ERROR|SE_FL_SHR|SE_FL_SHW))))
10326 goto out;
10327
10328 /* The applet execution is already done. */
10329 if (http_ctx->flags & APPLET_DONE)
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010330 goto out;
10331
Ilya Shipitsin856aabc2020-04-16 23:51:34 +050010332 /* Check if the input buffer is available. */
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010333 if (!b_size(&res->buf)) {
Willy Tarreau3e7be362022-05-27 10:35:27 +020010334 sc_need_room(sc);
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010335 goto out;
10336 }
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010337
10338 /* Set the currently running flag. */
10339 if (!HLUA_IS_RUNNING(hlua) &&
Willy Tarreauaa229cc2022-05-06 14:26:10 +020010340 !(http_ctx->flags & APPLET_DONE)) {
Christopher Fauletbd878d22021-04-28 10:50:21 +020010341 if (!co_data(req)) {
Willy Tarreau90e8b452022-05-25 18:21:43 +020010342 applet_need_more_data(ctx);
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010343 goto out;
10344 }
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010345 }
10346
Christopher Faulet31572222023-03-31 11:13:48 +020010347 /* Execute the function. */
10348 switch (hlua_ctx_resume(hlua, 1)) {
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010349 /* finished. */
10350 case HLUA_E_OK:
Willy Tarreauaa229cc2022-05-06 14:26:10 +020010351 http_ctx->flags |= APPLET_DONE;
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010352 break;
10353
10354 /* yield. */
10355 case HLUA_E_AGAIN:
10356 if (hlua->wake_time != TICK_ETERNITY)
Willy Tarreauaa229cc2022-05-06 14:26:10 +020010357 task_schedule(http_ctx->task, hlua->wake_time);
Christopher Faulet56a3d6e2019-02-27 22:06:23 +010010358 goto out;
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010359
10360 /* finished with error. */
10361 case HLUA_E_ERRMSG:
10362 /* Display log. */
10363 SEND_ERR(px, "Lua applet http '%s': %s.\n",
Christopher Faulet31572222023-03-31 11:13:48 +020010364 rule->arg.hlua_rule->fcn->name, lua_tostring(hlua->T, -1));
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010365 lua_pop(hlua->T, 1);
10366 goto error;
10367
10368 case HLUA_E_ETMOUT:
10369 SEND_ERR(px, "Lua applet http '%s': execution timeout.\n",
Christopher Faulet31572222023-03-31 11:13:48 +020010370 rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010371 goto error;
10372
10373 case HLUA_E_NOMEM:
10374 SEND_ERR(px, "Lua applet http '%s': out of memory error.\n",
Christopher Faulet31572222023-03-31 11:13:48 +020010375 rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010376 goto error;
10377
10378 case HLUA_E_YIELD: /* unexpected */
10379 SEND_ERR(px, "Lua applet http '%s': yield not allowed.\n",
Christopher Faulet31572222023-03-31 11:13:48 +020010380 rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010381 goto error;
10382
10383 case HLUA_E_ERR:
10384 /* Display log. */
10385 SEND_ERR(px, "Lua applet http '%s' return an unknown error.\n",
Christopher Faulet31572222023-03-31 11:13:48 +020010386 rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010387 goto error;
10388
10389 default:
10390 goto error;
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010391 }
10392
Willy Tarreauaa229cc2022-05-06 14:26:10 +020010393 if (http_ctx->flags & APPLET_DONE) {
10394 if (http_ctx->flags & APPLET_RSP_SENT)
Christopher Faulet31572222023-03-31 11:13:48 +020010395 goto out;
Christopher Faulet56a3d6e2019-02-27 22:06:23 +010010396
Willy Tarreauaa229cc2022-05-06 14:26:10 +020010397 if (!(http_ctx->flags & APPLET_HDR_SENT))
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010398 goto error;
10399
Christopher Fauletf89af9c2022-04-07 10:07:18 +020010400 /* no more data are expected. If the response buffer is empty
10401 * for a chunked message, be sure to add something (EOT block in
10402 * this case) to have something to send. It is important to be
10403 * sure the EOM flags will be handled by the endpoint.
10404 */
10405 if (htx_is_empty(res_htx) && (strm->txn->rsp.flags & (HTTP_MSGF_XFER_LEN|HTTP_MSGF_CNT_LEN)) == HTTP_MSGF_XFER_LEN) {
10406 if (!htx_add_endof(res_htx, HTX_BLK_EOT)) {
Willy Tarreau3e7be362022-05-27 10:35:27 +020010407 sc_need_room(sc);
Christopher Fauletf89af9c2022-04-07 10:07:18 +020010408 goto out;
10409 }
10410 channel_add_input(res, 1);
10411 }
10412
Christopher Fauletd1ac2b92020-12-02 19:12:22 +010010413 res_htx->flags |= HTX_FL_EOM;
Christopher Faulet31572222023-03-31 11:13:48 +020010414 se_fl_set(ctx->sedesc, SE_FL_EOI|SE_FL_EOS);
Willy Tarreauaa229cc2022-05-06 14:26:10 +020010415 strm->txn->status = http_ctx->status;
10416 http_ctx->flags |= APPLET_RSP_SENT;
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010417 }
10418
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010419 out:
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010420 htx_to_buf(res_htx, &res->buf);
Christopher Faulet31572222023-03-31 11:13:48 +020010421 /* eat the whole request */
10422 if (co_data(req)) {
10423 req_htx = htx_from_buf(&req->buf);
10424 co_htx_skip(req, req_htx, co_data(req));
10425 htx_to_buf(req_htx, &req->buf);
10426 }
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010427 return;
10428
10429 error:
10430
10431 /* If we are in HTTP mode, and we are not send any
10432 * data, return a 500 server error in best effort:
10433 * if there is no room available in the buffer,
10434 * just close the connection.
10435 */
Willy Tarreauaa229cc2022-05-06 14:26:10 +020010436 if (!(http_ctx->flags & APPLET_HDR_SENT)) {
Christopher Fauletf7346382019-07-17 22:02:08 +020010437 struct buffer *err = &http_err_chunks[HTTP_ERR_500];
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010438
10439 channel_erase(res);
10440 res->buf.data = b_data(err);
10441 memcpy(res->buf.area, b_head(err), b_data(err));
10442 res_htx = htx_from_buf(&res->buf);
Christopher Fauletf6cce3f2019-02-27 21:20:09 +010010443 channel_add_input(res, res_htx->data);
Christopher Faulet31572222023-03-31 11:13:48 +020010444 se_fl_set(ctx->sedesc, SE_FL_EOI|SE_FL_EOS);
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010445 }
Christopher Faulet31572222023-03-31 11:13:48 +020010446 else
10447 se_fl_set(ctx->sedesc, SE_FL_ERROR);
10448
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010449 if (!(strm->flags & SF_ERR_MASK))
10450 strm->flags |= SF_ERR_RESOURCE;
Willy Tarreauaa229cc2022-05-06 14:26:10 +020010451 http_ctx->flags |= APPLET_DONE;
Christopher Faulet31572222023-03-31 11:13:48 +020010452 goto out;
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010453}
10454
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010455static void hlua_applet_http_release(struct appctx *ctx)
10456{
Willy Tarreauaa229cc2022-05-06 14:26:10 +020010457 struct hlua_http_ctx *http_ctx = ctx->svcctx;
10458
10459 task_destroy(http_ctx->task);
10460 http_ctx->task = NULL;
10461 hlua_ctx_destroy(http_ctx->hlua);
10462 http_ctx->hlua = NULL;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010463}
10464
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +020010465/* global {tcp|http}-request parser. Return ACT_RET_PRS_OK in
Ilya Shipitsin856aabc2020-04-16 23:51:34 +050010466 * success case, else return ACT_RET_PRS_ERR.
Thierry FOURNIERbabae282015-09-17 11:36:37 +020010467 *
10468 * This function can fail with an abort() due to an Lua critical error.
10469 * We are in the configuration parsing process of HAProxy, this abort() is
10470 * tolerated.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +010010471 */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +020010472static enum act_parse_ret action_register_lua(const char **args, int *cur_arg, struct proxy *px,
10473 struct act_rule *rule, char **err)
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +010010474{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +020010475 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +010010476 int i;
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010477
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +020010478 /* Memory for the rule. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +020010479 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +020010480 if (!rule->arg.hlua_rule) {
10481 memprintf(err, "out of memory error");
Christopher Faulet528526f2021-04-12 14:37:32 +020010482 goto error;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +020010483 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +010010484
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +010010485 /* Memory for arguments. */
Tim Duesterhuse52b6e52020-09-12 20:26:43 +020010486 rule->arg.hlua_rule->args = calloc(fcn->nargs + 1,
10487 sizeof(*rule->arg.hlua_rule->args));
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +010010488 if (!rule->arg.hlua_rule->args) {
10489 memprintf(err, "out of memory error");
Christopher Faulet528526f2021-04-12 14:37:32 +020010490 goto error;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +010010491 }
10492
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +020010493 /* Reference the Lua function and store the reference. */
Thierry Fournierad5345f2020-11-29 02:05:57 +010010494 rule->arg.hlua_rule->fcn = fcn;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +020010495
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +010010496 /* Expect some arguments */
10497 for (i = 0; i < fcn->nargs; i++) {
Thierry FOURNIER1725c2e2019-01-06 19:38:49 +010010498 if (*args[*cur_arg] == '\0') {
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +010010499 memprintf(err, "expect %d arguments", fcn->nargs);
Christopher Faulet528526f2021-04-12 14:37:32 +020010500 goto error;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +010010501 }
Thierry FOURNIER1725c2e2019-01-06 19:38:49 +010010502 rule->arg.hlua_rule->args[i] = strdup(args[*cur_arg]);
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +010010503 if (!rule->arg.hlua_rule->args[i]) {
10504 memprintf(err, "out of memory error");
Christopher Faulet528526f2021-04-12 14:37:32 +020010505 goto error;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +010010506 }
10507 (*cur_arg)++;
10508 }
10509 rule->arg.hlua_rule->args[i] = NULL;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +020010510
Thierry FOURNIER42148732015-09-02 17:17:33 +020010511 rule->action = ACT_CUSTOM;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +020010512 rule->action_ptr = hlua_action;
Thierry FOURNIERafa80492015-08-19 09:04:15 +020010513 return ACT_RET_PRS_OK;
Christopher Faulet528526f2021-04-12 14:37:32 +020010514
10515 error:
10516 if (rule->arg.hlua_rule) {
10517 if (rule->arg.hlua_rule->args) {
10518 for (i = 0; i < fcn->nargs; i++)
10519 ha_free(&rule->arg.hlua_rule->args[i]);
10520 ha_free(&rule->arg.hlua_rule->args);
10521 }
10522 ha_free(&rule->arg.hlua_rule);
10523 }
10524 return ACT_RET_PRS_ERR;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +010010525}
10526
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010527static enum act_parse_ret action_register_service_http(const char **args, int *cur_arg, struct proxy *px,
10528 struct act_rule *rule, char **err)
10529{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +020010530 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010531
Thierry FOURNIER718e2a72015-12-20 20:13:14 +010010532 /* HTTP applets are forbidden in tcp-request rules.
Ilya Shipitsin856aabc2020-04-16 23:51:34 +050010533 * HTTP applet request requires everything initialized by
Thierry FOURNIER718e2a72015-12-20 20:13:14 +010010534 * "http_process_request" (analyzer flag AN_REQ_HTTP_INNER).
Ilya Shipitsin856aabc2020-04-16 23:51:34 +050010535 * The applet will be immediately initialized, but its before
Thierry FOURNIER718e2a72015-12-20 20:13:14 +010010536 * the call of this analyzer.
10537 */
10538 if (rule->from != ACT_F_HTTP_REQ) {
10539 memprintf(err, "HTTP applets are forbidden from 'tcp-request' rulesets");
10540 return ACT_RET_PRS_ERR;
10541 }
10542
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010543 /* Memory for the rule. */
10544 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
10545 if (!rule->arg.hlua_rule) {
10546 memprintf(err, "out of memory error");
10547 return ACT_RET_PRS_ERR;
10548 }
10549
10550 /* Reference the Lua function and store the reference. */
Thierry Fournierad5345f2020-11-29 02:05:57 +010010551 rule->arg.hlua_rule->fcn = fcn;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010552
10553 /* TODO: later accept arguments. */
10554 rule->arg.hlua_rule->args = NULL;
10555
10556 /* Add applet pointer in the rule. */
10557 rule->applet.obj_type = OBJ_TYPE_APPLET;
10558 rule->applet.name = fcn->name;
10559 rule->applet.init = hlua_applet_http_init;
10560 rule->applet.fct = hlua_applet_http_fct;
10561 rule->applet.release = hlua_applet_http_release;
10562 rule->applet.timeout = hlua_timeout_applet;
10563
10564 return ACT_RET_PRS_OK;
10565}
10566
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010567/* This function is an LUA binding used for registering
10568 * "sample-conv" functions. It expects a converter name used
10569 * in the haproxy configuration file, and an LUA function.
10570 */
10571__LJMP static int hlua_register_action(lua_State *L)
10572{
Christopher Faulet4fc9da02021-04-12 15:08:12 +020010573 struct action_kw_list *akl = NULL;
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010574 const char *name;
10575 int ref;
10576 int len;
Christopher Faulet4fc9da02021-04-12 15:08:12 +020010577 struct hlua_function *fcn = NULL;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +010010578 int nargs;
Thierry Fournierf67442e2020-11-28 20:41:07 +010010579 struct buffer *trash;
10580 struct action_kw *akw;
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010581
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +010010582 /* Initialise the number of expected arguments at 0. */
10583 nargs = 0;
10584
10585 if (lua_gettop(L) < 3 || lua_gettop(L) > 4)
10586 WILL_LJMP(luaL_error(L, "'register_action' needs between 3 and 4 arguments"));
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010587
Aurelien DARRAGON87f52972023-02-24 09:43:54 +010010588 if (hlua_gethlua(L)) {
10589 /* runtime processing */
10590 WILL_LJMP(luaL_error(L, "register_action: not available outside of body context"));
10591 }
10592
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010593 /* First argument : converter name. */
10594 name = MAY_LJMP(luaL_checkstring(L, 1));
10595
10596 /* Second argument : environment. */
10597 if (lua_type(L, 2) != LUA_TTABLE)
10598 WILL_LJMP(luaL_error(L, "register_action: second argument must be a table of strings"));
10599
10600 /* Third argument : lua function. */
10601 ref = MAY_LJMP(hlua_checkfunction(L, 3));
10602
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -080010603 /* Fourth argument : number of mandatory arguments expected on the configuration line. */
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +010010604 if (lua_gettop(L) >= 4)
10605 nargs = MAY_LJMP(luaL_checkinteger(L, 4));
10606
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -080010607 /* browse the second argument as an array. */
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010608 lua_pushnil(L);
10609 while (lua_next(L, 2) != 0) {
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +010010610 if (lua_type(L, -1) != LUA_TSTRING) {
10611 hlua_unref(L, ref);
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010612 WILL_LJMP(luaL_error(L, "register_action: second argument must be a table of strings"));
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +010010613 }
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010614
Thierry Fournierf67442e2020-11-28 20:41:07 +010010615 /* Check if action exists */
10616 trash = get_trash_chunk();
10617 chunk_printf(trash, "lua.%s", name);
10618 if (strcmp(lua_tostring(L, -1), "tcp-req") == 0) {
10619 akw = tcp_req_cont_action(trash->area);
10620 } else if (strcmp(lua_tostring(L, -1), "tcp-res") == 0) {
10621 akw = tcp_res_cont_action(trash->area);
10622 } else if (strcmp(lua_tostring(L, -1), "http-req") == 0) {
10623 akw = action_http_req_custom(trash->area);
10624 } else if (strcmp(lua_tostring(L, -1), "http-res") == 0) {
10625 akw = action_http_res_custom(trash->area);
10626 } else {
10627 akw = NULL;
10628 }
10629 if (akw != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +010010630 fcn = akw->private;
10631 if (fcn->function_ref[hlua_state_id] != -1) {
10632 ha_warning("Trying to register action 'lua.%s' more than once. "
10633 "This will become a hard error in version 2.5.\n", name);
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +010010634 hlua_unref(L, fcn->function_ref[hlua_state_id]);
Thierry Fournier59f11be2020-11-29 00:37:41 +010010635 }
10636 fcn->function_ref[hlua_state_id] = ref;
10637
10638 /* pop the environment string. */
10639 lua_pop(L, 1);
10640 continue;
Thierry Fournierf67442e2020-11-28 20:41:07 +010010641 }
10642
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010643 /* Check required environment. Only accepted "http" or "tcp". */
10644 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +020010645 akl = calloc(1, sizeof(*akl) + sizeof(struct action_kw) * 2);
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010646 if (!akl)
Christopher Faulet4fc9da02021-04-12 15:08:12 +020010647 goto alloc_error;;
Thierry Fournier62a22aa2020-11-28 21:06:35 +010010648 fcn = new_hlua_function();
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010649 if (!fcn)
Christopher Faulet4fc9da02021-04-12 15:08:12 +020010650 goto alloc_error;
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010651
10652 /* Fill fcn. */
10653 fcn->name = strdup(name);
10654 if (!fcn->name)
Christopher Faulet4fc9da02021-04-12 15:08:12 +020010655 goto alloc_error;
Thierry Fournierc7492592020-11-28 23:57:24 +010010656 fcn->function_ref[hlua_state_id] = ref;
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010657
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -070010658 /* Set the expected number of arguments. */
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +010010659 fcn->nargs = nargs;
10660
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010661 /* List head */
10662 akl->list.n = akl->list.p = NULL;
10663
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010664 /* action keyword. */
10665 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +020010666 akl->kw[0].kw = calloc(1, len);
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010667 if (!akl->kw[0].kw)
Christopher Faulet4fc9da02021-04-12 15:08:12 +020010668 goto alloc_error;
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010669
10670 snprintf((char *)akl->kw[0].kw, len, "lua.%s", name);
10671
Amaury Denoyellee4a617c2021-05-06 15:33:09 +020010672 akl->kw[0].flags = 0;
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010673 akl->kw[0].private = fcn;
10674 akl->kw[0].parse = action_register_lua;
10675
10676 /* select the action registering point. */
10677 if (strcmp(lua_tostring(L, -1), "tcp-req") == 0)
10678 tcp_req_cont_keywords_register(akl);
10679 else if (strcmp(lua_tostring(L, -1), "tcp-res") == 0)
10680 tcp_res_cont_keywords_register(akl);
10681 else if (strcmp(lua_tostring(L, -1), "http-req") == 0)
10682 http_req_keywords_register(akl);
10683 else if (strcmp(lua_tostring(L, -1), "http-res") == 0)
10684 http_res_keywords_register(akl);
Christopher Faulet4fc9da02021-04-12 15:08:12 +020010685 else {
10686 release_hlua_function(fcn);
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +010010687 hlua_unref(L, ref);
Christopher Faulet4fc9da02021-04-12 15:08:12 +020010688 if (akl)
10689 ha_free((char **)&(akl->kw[0].kw));
10690 ha_free(&akl);
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +010010691 WILL_LJMP(luaL_error(L, "Lua action environment '%s' is unknown. "
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010692 "'tcp-req', 'tcp-res', 'http-req' or 'http-res' "
10693 "are expected.", lua_tostring(L, -1)));
Christopher Faulet4fc9da02021-04-12 15:08:12 +020010694 }
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010695
10696 /* pop the environment string. */
10697 lua_pop(L, 1);
Christopher Faulet4fc9da02021-04-12 15:08:12 +020010698
10699 /* reset for next loop */
10700 akl = NULL;
10701 fcn = NULL;
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010702 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010703 return ACT_RET_PRS_OK;
Christopher Faulet4fc9da02021-04-12 15:08:12 +020010704
10705 alloc_error:
10706 release_hlua_function(fcn);
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +010010707 hlua_unref(L, ref);
Christopher Faulet4fc9da02021-04-12 15:08:12 +020010708 ha_free(&akl);
10709 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
10710 return 0; /* Never reached */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010711}
10712
10713static enum act_parse_ret action_register_service_tcp(const char **args, int *cur_arg, struct proxy *px,
10714 struct act_rule *rule, char **err)
10715{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +020010716 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010717
Christopher Faulet280f85b2019-07-15 15:02:04 +020010718 if (px->mode == PR_MODE_HTTP) {
10719 memprintf(err, "Lua TCP services cannot be used on HTTP proxies");
Christopher Fauletafd8f102018-11-08 11:34:21 +010010720 return ACT_RET_PRS_ERR;
10721 }
10722
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010723 /* Memory for the rule. */
10724 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
10725 if (!rule->arg.hlua_rule) {
10726 memprintf(err, "out of memory error");
10727 return ACT_RET_PRS_ERR;
10728 }
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010729
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010730 /* Reference the Lua function and store the reference. */
Thierry Fournierad5345f2020-11-29 02:05:57 +010010731 rule->arg.hlua_rule->fcn = fcn;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010732
10733 /* TODO: later accept arguments. */
10734 rule->arg.hlua_rule->args = NULL;
10735
10736 /* Add applet pointer in the rule. */
10737 rule->applet.obj_type = OBJ_TYPE_APPLET;
10738 rule->applet.name = fcn->name;
10739 rule->applet.init = hlua_applet_tcp_init;
10740 rule->applet.fct = hlua_applet_tcp_fct;
10741 rule->applet.release = hlua_applet_tcp_release;
10742 rule->applet.timeout = hlua_timeout_applet;
10743
10744 return 0;
10745}
10746
10747/* This function is an LUA binding used for registering
10748 * "sample-conv" functions. It expects a converter name used
10749 * in the haproxy configuration file, and an LUA function.
10750 */
10751__LJMP static int hlua_register_service(lua_State *L)
10752{
10753 struct action_kw_list *akl;
10754 const char *name;
10755 const char *env;
10756 int ref;
10757 int len;
Christopher Faulet5c028d72021-04-12 15:11:44 +020010758 struct hlua_function *fcn = NULL;
Thierry Fournierf67442e2020-11-28 20:41:07 +010010759 struct buffer *trash;
10760 struct action_kw *akw;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010761
10762 MAY_LJMP(check_args(L, 3, "register_service"));
10763
Aurelien DARRAGON87f52972023-02-24 09:43:54 +010010764 if (hlua_gethlua(L)) {
10765 /* runtime processing */
10766 WILL_LJMP(luaL_error(L, "register_service: not available outside of body context"));
10767 }
10768
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010769 /* First argument : converter name. */
10770 name = MAY_LJMP(luaL_checkstring(L, 1));
10771
10772 /* Second argument : environment. */
10773 env = MAY_LJMP(luaL_checkstring(L, 2));
10774
10775 /* Third argument : lua function. */
10776 ref = MAY_LJMP(hlua_checkfunction(L, 3));
10777
Thierry Fournierf67442e2020-11-28 20:41:07 +010010778 /* Check for service already registered */
10779 trash = get_trash_chunk();
10780 chunk_printf(trash, "lua.%s", name);
10781 akw = service_find(trash->area);
10782 if (akw != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +010010783 fcn = akw->private;
10784 if (fcn->function_ref[hlua_state_id] != -1) {
10785 ha_warning("Trying to register service 'lua.%s' more than once. "
10786 "This will become a hard error in version 2.5.\n", name);
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +010010787 hlua_unref(L, fcn->function_ref[hlua_state_id]);
Thierry Fournier59f11be2020-11-29 00:37:41 +010010788 }
10789 fcn->function_ref[hlua_state_id] = ref;
10790 return 0;
Thierry Fournierf67442e2020-11-28 20:41:07 +010010791 }
10792
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010793 /* Allocate and fill the sample fetch keyword struct. */
10794 akl = calloc(1, sizeof(*akl) + sizeof(struct action_kw) * 2);
10795 if (!akl)
Christopher Faulet5c028d72021-04-12 15:11:44 +020010796 goto alloc_error;
Thierry Fournier62a22aa2020-11-28 21:06:35 +010010797 fcn = new_hlua_function();
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010798 if (!fcn)
Christopher Faulet5c028d72021-04-12 15:11:44 +020010799 goto alloc_error;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010800
10801 /* Fill fcn. */
10802 len = strlen("<lua.>") + strlen(name) + 1;
10803 fcn->name = calloc(1, len);
10804 if (!fcn->name)
Christopher Faulet5c028d72021-04-12 15:11:44 +020010805 goto alloc_error;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010806 snprintf((char *)fcn->name, len, "<lua.%s>", name);
Thierry Fournierc7492592020-11-28 23:57:24 +010010807 fcn->function_ref[hlua_state_id] = ref;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010808
10809 /* List head */
10810 akl->list.n = akl->list.p = NULL;
10811
10812 /* converter keyword. */
10813 len = strlen("lua.") + strlen(name) + 1;
10814 akl->kw[0].kw = calloc(1, len);
10815 if (!akl->kw[0].kw)
Christopher Faulet5c028d72021-04-12 15:11:44 +020010816 goto alloc_error;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010817
10818 snprintf((char *)akl->kw[0].kw, len, "lua.%s", name);
10819
Thierry FOURNIER / OZON.IO02564fd2016-11-12 11:07:05 +010010820 /* Check required environment. Only accepted "http" or "tcp". */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010821 if (strcmp(env, "tcp") == 0)
10822 akl->kw[0].parse = action_register_service_tcp;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010823 else if (strcmp(env, "http") == 0)
10824 akl->kw[0].parse = action_register_service_http;
Christopher Faulet5c028d72021-04-12 15:11:44 +020010825 else {
10826 release_hlua_function(fcn);
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +010010827 hlua_unref(L, ref);
Christopher Faulet5c028d72021-04-12 15:11:44 +020010828 if (akl)
10829 ha_free((char **)&(akl->kw[0].kw));
10830 ha_free(&akl);
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +010010831 WILL_LJMP(luaL_error(L, "Lua service environment '%s' is unknown. "
Eric Salamafe7456f2017-12-21 14:30:07 +010010832 "'tcp' or 'http' are expected.", env));
Christopher Faulet5c028d72021-04-12 15:11:44 +020010833 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010834
Amaury Denoyellee4a617c2021-05-06 15:33:09 +020010835 akl->kw[0].flags = 0;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010836 akl->kw[0].private = fcn;
10837
10838 /* End of array. */
10839 memset(&akl->kw[1], 0, sizeof(*akl->kw));
10840
10841 /* Register this new converter */
10842 service_keywords_register(akl);
10843
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010844 return 0;
Christopher Faulet5c028d72021-04-12 15:11:44 +020010845
10846 alloc_error:
10847 release_hlua_function(fcn);
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +010010848 hlua_unref(L, ref);
Christopher Faulet5c028d72021-04-12 15:11:44 +020010849 ha_free(&akl);
10850 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
10851 return 0; /* Never reached */
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010852}
10853
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010854/* This function initialises Lua cli handler. It copies the
10855 * arguments in the Lua stack and create channel IO objects.
10856 */
Aurélien Nephtaliabbf6072018-04-18 13:26:46 +020010857static int hlua_cli_parse_fct(char **args, char *payload, struct appctx *appctx, void *private)
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010858{
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010859 struct hlua_cli_ctx *ctx = applet_reserve_svcctx(appctx, sizeof(*ctx));
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010860 struct hlua *hlua;
10861 struct hlua_function *fcn;
10862 int i;
10863 const char *error;
10864
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010865 fcn = private;
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010866 ctx->fcn = private;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +010010867
Willy Tarreaubafbe012017-11-24 17:34:44 +010010868 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +010010869 if (!hlua) {
10870 SEND_ERR(NULL, "Lua cli '%s': out of memory.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +010010871 return 1;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +010010872 }
10873 HLUA_INIT(hlua);
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010874 ctx->hlua = hlua;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010875
10876 /* Create task used by signal to wakeup applets.
Ilya Shipitsind4259502020-04-08 01:07:56 +050010877 * We use the same wakeup function than the Lua applet_tcp and
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010878 * applet_http. It is absolutely compatible.
10879 */
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010880 ctx->task = task_new_here();
10881 if (!ctx->task) {
Thierry FOURNIERffbf5692016-12-16 11:14:06 +010010882 SEND_ERR(NULL, "Lua cli '%s': out of memory.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +010010883 goto error;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010884 }
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010885 ctx->task->nice = 0;
10886 ctx->task->context = appctx;
10887 ctx->task->process = hlua_applet_wakeup;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010888
10889 /* Initialises the Lua context */
Aurelien DARRAGON6b0b9bd2023-03-21 14:02:16 +010010890 if (!hlua_ctx_init(hlua, fcn_ref_to_stack_id(fcn), ctx->task)) {
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010891 SEND_ERR(NULL, "Lua cli '%s': can't initialize Lua context.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +010010892 goto error;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010893 }
10894
10895 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010896 if (!SET_SAFE_LJMP(hlua)) {
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010897 if (lua_type(hlua->T, -1) == LUA_TSTRING)
10898 error = lua_tostring(hlua->T, -1);
10899 else
10900 error = "critical error";
10901 SEND_ERR(NULL, "Lua cli '%s': %s.\n", fcn->name, error);
10902 goto error;
10903 }
10904
10905 /* Check stack available size. */
10906 if (!lua_checkstack(hlua->T, 2)) {
10907 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
10908 goto error;
10909 }
10910
10911 /* Restore the function in the stack. */
Aurelien DARRAGON4fdf8b52023-03-20 17:22:37 +010010912 hlua_pushref(hlua->T, fcn->function_ref[hlua->state_id]);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010913
10914 /* Once the arguments parsed, the CLI is like an AppletTCP,
10915 * so push AppletTCP in the stack.
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010916 */
10917 if (!hlua_applet_tcp_new(hlua->T, appctx)) {
10918 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
10919 goto error;
10920 }
10921 hlua->nargs = 1;
10922
10923 /* push keywords in the stack. */
10924 for (i = 0; *args[i]; i++) {
10925 /* Check stack available size. */
10926 if (!lua_checkstack(hlua->T, 1)) {
10927 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
10928 goto error;
10929 }
10930 lua_pushstring(hlua->T, args[i]);
10931 hlua->nargs++;
10932 }
10933
10934 /* We must initialize the execution timeouts. */
Aurelien DARRAGONda9503c2022-11-25 09:10:07 +010010935 hlua_timer_init(&hlua->timer, hlua_timeout_session);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010936
10937 /* At this point the execution is safe. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010938 RESET_SAFE_LJMP(hlua);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010939
10940 /* It's ok */
10941 return 0;
10942
10943 /* It's not ok. */
10944error:
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010945 RESET_SAFE_LJMP(hlua);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010946 hlua_ctx_destroy(hlua);
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010947 ctx->hlua = NULL;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010948 return 1;
10949}
10950
10951static int hlua_cli_io_handler_fct(struct appctx *appctx)
10952{
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010953 struct hlua_cli_ctx *ctx = appctx->svcctx;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010954 struct hlua *hlua;
Willy Tarreau475e4632022-05-27 10:26:46 +020010955 struct stconn *sc;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010956 struct hlua_function *fcn;
10957
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010958 hlua = ctx->hlua;
Willy Tarreauc12b3212022-05-27 11:08:15 +020010959 sc = appctx_sc(appctx);
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010960 fcn = ctx->fcn;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010961
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010962 /* Execute the function. */
10963 switch (hlua_ctx_resume(hlua, 1)) {
10964
10965 /* finished. */
10966 case HLUA_E_OK:
10967 return 1;
10968
10969 /* yield. */
10970 case HLUA_E_AGAIN:
10971 /* We want write. */
10972 if (HLUA_IS_WAKERESWR(hlua))
Willy Tarreau475e4632022-05-27 10:26:46 +020010973 sc_need_room(sc);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010974 /* Set the timeout. */
10975 if (hlua->wake_time != TICK_ETERNITY)
10976 task_schedule(hlua->task, hlua->wake_time);
10977 return 0;
10978
10979 /* finished with error. */
10980 case HLUA_E_ERRMSG:
10981 /* Display log. */
10982 SEND_ERR(NULL, "Lua cli '%s': %s.\n",
10983 fcn->name, lua_tostring(hlua->T, -1));
10984 lua_pop(hlua->T, 1);
10985 return 1;
10986
Thierry Fournierd5b073c2018-05-21 19:42:47 +020010987 case HLUA_E_ETMOUT:
10988 SEND_ERR(NULL, "Lua converter '%s': execution timeout.\n",
10989 fcn->name);
10990 return 1;
10991
10992 case HLUA_E_NOMEM:
10993 SEND_ERR(NULL, "Lua converter '%s': out of memory error.\n",
10994 fcn->name);
10995 return 1;
10996
10997 case HLUA_E_YIELD: /* unexpected */
10998 SEND_ERR(NULL, "Lua converter '%s': yield not allowed.\n",
10999 fcn->name);
11000 return 1;
11001
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011002 case HLUA_E_ERR:
11003 /* Display log. */
11004 SEND_ERR(NULL, "Lua cli '%s' return an unknown error.\n",
11005 fcn->name);
11006 return 1;
11007
11008 default:
11009 return 1;
11010 }
11011
11012 return 1;
11013}
11014
11015static void hlua_cli_io_release_fct(struct appctx *appctx)
11016{
Willy Tarreaubcda5f62022-05-03 18:13:39 +020011017 struct hlua_cli_ctx *ctx = appctx->svcctx;
11018
11019 hlua_ctx_destroy(ctx->hlua);
11020 ctx->hlua = NULL;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011021}
11022
11023/* This function is an LUA binding used for registering
11024 * new keywords in the cli. It expects a list of keywords
11025 * which are the "path". It is limited to 5 keywords. A
11026 * description of the command, a function to be executed
11027 * for the parsing and a function for io handlers.
11028 */
11029__LJMP static int hlua_register_cli(lua_State *L)
11030{
11031 struct cli_kw_list *cli_kws;
11032 const char *message;
11033 int ref_io;
11034 int len;
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020011035 struct hlua_function *fcn = NULL;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011036 int index;
11037 int i;
Thierry Fournierf67442e2020-11-28 20:41:07 +010011038 struct buffer *trash;
11039 const char *kw[5];
11040 struct cli_kw *cli_kw;
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020011041 const char *errmsg;
Willy Tarreau22450af2023-04-07 15:27:55 +020011042 char *end;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011043
11044 MAY_LJMP(check_args(L, 3, "register_cli"));
11045
Aurelien DARRAGON87f52972023-02-24 09:43:54 +010011046 if (hlua_gethlua(L)) {
11047 /* runtime processing */
11048 WILL_LJMP(luaL_error(L, "register_cli: not available outside of body context"));
11049 }
11050
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011051 /* First argument : an array of maximum 5 keywords. */
11052 if (!lua_istable(L, 1))
11053 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table"));
11054
11055 /* Second argument : string with contextual message. */
11056 message = MAY_LJMP(luaL_checkstring(L, 2));
11057
11058 /* Third and fourth argument : lua function. */
11059 ref_io = MAY_LJMP(hlua_checkfunction(L, 3));
11060
Thierry Fournierf67442e2020-11-28 20:41:07 +010011061 /* Check for CLI service already registered */
11062 trash = get_trash_chunk();
11063 index = 0;
11064 lua_pushnil(L);
11065 memset(kw, 0, sizeof(kw));
11066 while (lua_next(L, 1) != 0) {
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +010011067 if (index >= CLI_PREFIX_KW_NB) {
11068 hlua_unref(L, ref_io);
Thierry Fournierf67442e2020-11-28 20:41:07 +010011069 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 +010011070 }
11071 if (lua_type(L, -1) != LUA_TSTRING) {
11072 hlua_unref(L, ref_io);
Thierry Fournierf67442e2020-11-28 20:41:07 +010011073 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table filled with strings"));
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +010011074 }
Thierry Fournierf67442e2020-11-28 20:41:07 +010011075 kw[index] = lua_tostring(L, -1);
11076 if (index == 0)
11077 chunk_printf(trash, "%s", kw[index]);
11078 else
11079 chunk_appendf(trash, " %s", kw[index]);
11080 index++;
11081 lua_pop(L, 1);
11082 }
11083 cli_kw = cli_find_kw_exact((char **)kw);
11084 if (cli_kw != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +010011085 fcn = cli_kw->private;
11086 if (fcn->function_ref[hlua_state_id] != -1) {
11087 ha_warning("Trying to register CLI keyword 'lua.%s' more than once. "
11088 "This will become a hard error in version 2.5.\n", trash->area);
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +010011089 hlua_unref(L, fcn->function_ref[hlua_state_id]);
Thierry Fournier59f11be2020-11-29 00:37:41 +010011090 }
11091 fcn->function_ref[hlua_state_id] = ref_io;
11092 return 0;
Thierry Fournierf67442e2020-11-28 20:41:07 +010011093 }
11094
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011095 /* Allocate and fill the sample fetch keyword struct. */
11096 cli_kws = calloc(1, sizeof(*cli_kws) + sizeof(struct cli_kw) * 2);
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020011097 if (!cli_kws) {
11098 errmsg = "Lua out of memory error.";
11099 goto error;
11100 }
Thierry Fournier62a22aa2020-11-28 21:06:35 +010011101 fcn = new_hlua_function();
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020011102 if (!fcn) {
11103 errmsg = "Lua out of memory error.";
11104 goto error;
11105 }
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011106
11107 /* Fill path. */
11108 index = 0;
11109 lua_pushnil(L);
11110 while(lua_next(L, 1) != 0) {
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020011111 if (index >= 5) {
11112 errmsg = "1st argument must be a table with a maximum of 5 entries";
11113 goto error;
11114 }
11115 if (lua_type(L, -1) != LUA_TSTRING) {
11116 errmsg = "1st argument must be a table filled with strings";
11117 goto error;
11118 }
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011119 cli_kws->kw[0].str_kw[index] = strdup(lua_tostring(L, -1));
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020011120 if (!cli_kws->kw[0].str_kw[index]) {
11121 errmsg = "Lua out of memory error.";
11122 goto error;
11123 }
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011124 index++;
11125 lua_pop(L, 1);
11126 }
11127
11128 /* Copy help message. */
11129 cli_kws->kw[0].usage = strdup(message);
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020011130 if (!cli_kws->kw[0].usage) {
11131 errmsg = "Lua out of memory error.";
11132 goto error;
11133 }
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011134
11135 /* Fill fcn io handler. */
11136 len = strlen("<lua.cli>") + 1;
11137 for (i = 0; i < index; i++)
11138 len += strlen(cli_kws->kw[0].str_kw[i]) + 1;
11139 fcn->name = calloc(1, len);
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020011140 if (!fcn->name) {
11141 errmsg = "Lua out of memory error.";
11142 goto error;
11143 }
Willy Tarreau22450af2023-04-07 15:27:55 +020011144
11145 end = fcn->name;
11146 len = 8;
11147 memcpy(end, "<lua.cli", len);
11148 end += len;
11149
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011150 for (i = 0; i < index; i++) {
Willy Tarreau22450af2023-04-07 15:27:55 +020011151 *(end++) = '.';
11152 len = strlen(cli_kws->kw[0].str_kw[i]);
11153 memcpy(end, cli_kws->kw[0].str_kw[i], len);
11154 end += len;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011155 }
Willy Tarreau22450af2023-04-07 15:27:55 +020011156 *(end++) = '>';
11157 *(end++) = 0;
11158
Thierry Fournierc7492592020-11-28 23:57:24 +010011159 fcn->function_ref[hlua_state_id] = ref_io;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011160
11161 /* Fill last entries. */
11162 cli_kws->kw[0].private = fcn;
11163 cli_kws->kw[0].parse = hlua_cli_parse_fct;
11164 cli_kws->kw[0].io_handler = hlua_cli_io_handler_fct;
11165 cli_kws->kw[0].io_release = hlua_cli_io_release_fct;
11166
11167 /* Register this new converter */
11168 cli_register_kw(cli_kws);
11169
11170 return 0;
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020011171
11172 error:
11173 release_hlua_function(fcn);
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +010011174 hlua_unref(L, ref_io);
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020011175 if (cli_kws) {
11176 for (i = 0; i < index; i++)
11177 ha_free((char **)&(cli_kws->kw[0].str_kw[i]));
11178 ha_free((char **)&(cli_kws->kw[0].usage));
11179 }
11180 ha_free(&cli_kws);
11181 WILL_LJMP(luaL_error(L, errmsg));
11182 return 0; /* Never reached */
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011183}
11184
Christopher Faulet69c581a2021-05-31 08:54:04 +020011185static int hlua_filter_init_per_thread(struct proxy *px, struct flt_conf *fconf)
11186{
11187 struct hlua_flt_config *conf = fconf->conf;
11188 lua_State *L;
11189 int error, pos, state_id, flt_ref;
11190
11191 state_id = reg_flt_to_stack_id(conf->reg);
11192 L = hlua_states[state_id];
11193 pos = lua_gettop(L);
11194
11195 /* The filter parsing function */
Aurelien DARRAGON4fdf8b52023-03-20 17:22:37 +010011196 hlua_pushref(L, conf->reg->fun_ref[state_id]);
Christopher Faulet69c581a2021-05-31 08:54:04 +020011197
11198 /* Push the filter class on the stack and resolve all callbacks */
Aurelien DARRAGON4fdf8b52023-03-20 17:22:37 +010011199 hlua_pushref(L, conf->reg->flt_ref[state_id]);
Christopher Faulet69c581a2021-05-31 08:54:04 +020011200
11201 /* Duplicate the filter class so each filter will have its own copy */
11202 lua_newtable(L);
11203 lua_pushnil(L);
11204
11205 while (lua_next(L, pos+2)) {
11206 lua_pushvalue(L, -2);
11207 lua_insert(L, -2);
11208 lua_settable(L, -4);
11209 }
Aurelien DARRAGON73d1a982023-03-20 17:42:08 +010011210 flt_ref = hlua_ref(L);
Christopher Faulet69c581a2021-05-31 08:54:04 +020011211
11212 /* Remove the original lua filter class from the stack */
11213 lua_pop(L, 1);
11214
11215 /* Push the copy on the stack */
Aurelien DARRAGON4fdf8b52023-03-20 17:22:37 +010011216 hlua_pushref(L, flt_ref);
Christopher Faulet69c581a2021-05-31 08:54:04 +020011217
11218 /* extra args are pushed in a table */
11219 lua_newtable(L);
11220 for (pos = 0; conf->args[pos]; pos++) {
11221 /* Check stack available size. */
11222 if (!lua_checkstack(L, 1)) {
11223 ha_alert("Lua filter '%s' : Lua error : full stack.", conf->reg->name);
11224 goto error;
11225 }
11226 lua_pushstring(L, conf->args[pos]);
11227 lua_rawseti(L, -2, lua_rawlen(L, -2) + 1);
11228 }
11229
11230 error = lua_pcall(L, 2, LUA_MULTRET, 0);
11231 switch (error) {
11232 case LUA_OK:
11233 /* replace the filter ref */
11234 conf->ref[state_id] = flt_ref;
11235 break;
11236 case LUA_ERRRUN:
11237 ha_alert("Lua filter '%s' : runtime error : %s", conf->reg->name, lua_tostring(L, -1));
11238 goto error;
11239 case LUA_ERRMEM:
11240 ha_alert("Lua filter '%s' : out of memory error", conf->reg->name);
11241 goto error;
11242 case LUA_ERRERR:
11243 ha_alert("Lua filter '%s' : message handler error : %s", conf->reg->name, lua_tostring(L, -1));
11244 goto error;
11245#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM <= 503
11246 case LUA_ERRGCMM:
11247 ha_alert("Lua filter '%s' : garbage collector error : %s", conf->reg->name, lua_tostring(L, -1));
11248 goto error;
11249#endif
11250 default:
Ilya Shipitsinff0f2782021-08-22 22:18:07 +050011251 ha_alert("Lua filter '%s' : unknown error : %s", conf->reg->name, lua_tostring(L, -1));
Christopher Faulet69c581a2021-05-31 08:54:04 +020011252 goto error;
11253 }
11254
11255 lua_settop(L, 0);
11256 return 0;
11257
11258 error:
11259 lua_settop(L, 0);
11260 return -1;
11261}
11262
11263static void hlua_filter_deinit_per_thread(struct proxy *px, struct flt_conf *fconf)
11264{
11265 struct hlua_flt_config *conf = fconf->conf;
11266 lua_State *L;
11267 int state_id;
11268
11269 if (!conf)
11270 return;
11271
11272 state_id = reg_flt_to_stack_id(conf->reg);
11273 L = hlua_states[state_id];
Aurelien DARRAGONfde199d2023-03-20 15:09:33 +010011274 hlua_unref(L, conf->ref[state_id]);
Christopher Faulet69c581a2021-05-31 08:54:04 +020011275}
11276
11277static int hlua_filter_init(struct proxy *px, struct flt_conf *fconf)
11278{
11279 struct hlua_flt_config *conf = fconf->conf;
11280 int state_id = reg_flt_to_stack_id(conf->reg);
11281
11282 /* Rely on per-thread init for global scripts */
11283 if (!state_id)
11284 return hlua_filter_init_per_thread(px, fconf);
11285 return 0;
11286}
11287
11288static void hlua_filter_deinit(struct proxy *px, struct flt_conf *fconf)
11289{
11290
11291 if (fconf->conf) {
11292 struct hlua_flt_config *conf = fconf->conf;
11293 int state_id = reg_flt_to_stack_id(conf->reg);
11294 int pos;
11295
11296 /* Rely on per-thread deinit for global scripts */
11297 if (!state_id)
11298 hlua_filter_deinit_per_thread(px, fconf);
11299
11300 for (pos = 0; conf->args[pos]; pos++)
11301 free(conf->args[pos]);
11302 free(conf->args);
11303 }
11304 ha_free(&fconf->conf);
11305 ha_free((char **)&fconf->id);
11306 ha_free(&fconf->ops);
11307}
11308
11309static int hlua_filter_new(struct stream *s, struct filter *filter)
11310{
11311 struct hlua_flt_config *conf = FLT_CONF(filter);
11312 struct hlua_flt_ctx *flt_ctx = NULL;
11313 int ret = 1;
11314
11315 /* In the execution wrappers linked with a stream, the
11316 * Lua context can be not initialized. This behavior
11317 * permits to save performances because a systematic
11318 * Lua initialization cause 5% performances loss.
11319 */
11320 if (!s->hlua) {
11321 struct hlua *hlua;
11322
11323 hlua = pool_alloc(pool_head_hlua);
11324 if (!hlua) {
11325 SEND_ERR(s->be, "Lua filter '%s': can't initialize Lua context.\n",
11326 conf->reg->name);
11327 ret = 0;
11328 goto end;
11329 }
11330 HLUA_INIT(hlua);
11331 s->hlua = hlua;
Aurelien DARRAGON6b0b9bd2023-03-21 14:02:16 +010011332 if (!hlua_ctx_init(s->hlua, reg_flt_to_stack_id(conf->reg), s->task)) {
Christopher Faulet69c581a2021-05-31 08:54:04 +020011333 SEND_ERR(s->be, "Lua filter '%s': can't initialize Lua context.\n",
11334 conf->reg->name);
11335 ret = 0;
11336 goto end;
11337 }
11338 }
11339
11340 flt_ctx = pool_zalloc(pool_head_hlua_flt_ctx);
11341 if (!flt_ctx) {
11342 SEND_ERR(s->be, "Lua filter '%s': can't initialize filter Lua context.\n",
11343 conf->reg->name);
11344 ret = 0;
11345 goto end;
11346 }
11347 flt_ctx->hlua[0] = pool_alloc(pool_head_hlua);
11348 flt_ctx->hlua[1] = pool_alloc(pool_head_hlua);
11349 if (!flt_ctx->hlua[0] || !flt_ctx->hlua[1]) {
11350 SEND_ERR(s->be, "Lua filter '%s': can't initialize filter Lua context.\n",
11351 conf->reg->name);
11352 ret = 0;
11353 goto end;
11354 }
11355 HLUA_INIT(flt_ctx->hlua[0]);
11356 HLUA_INIT(flt_ctx->hlua[1]);
Aurelien DARRAGON6b0b9bd2023-03-21 14:02:16 +010011357 if (!hlua_ctx_init(flt_ctx->hlua[0], reg_flt_to_stack_id(conf->reg), s->task) ||
11358 !hlua_ctx_init(flt_ctx->hlua[1], reg_flt_to_stack_id(conf->reg), s->task)) {
Christopher Faulet69c581a2021-05-31 08:54:04 +020011359 SEND_ERR(s->be, "Lua filter '%s': can't initialize filter Lua context.\n",
11360 conf->reg->name);
11361 ret = 0;
11362 goto end;
11363 }
11364
11365 if (!HLUA_IS_RUNNING(s->hlua)) {
11366 /* The following Lua calls can fail. */
11367 if (!SET_SAFE_LJMP(s->hlua)) {
11368 const char *error;
11369
11370 if (lua_type(s->hlua->T, -1) == LUA_TSTRING)
11371 error = lua_tostring(s->hlua->T, -1);
11372 else
11373 error = "critical error";
11374 SEND_ERR(s->be, "Lua filter '%s': %s.\n", conf->reg->name, error);
11375 ret = 0;
11376 goto end;
11377 }
11378
11379 /* Check stack size. */
11380 if (!lua_checkstack(s->hlua->T, 1)) {
11381 SEND_ERR(s->be, "Lua filter '%s': full stack.\n", conf->reg->name);
Tim Duesterhus22817382021-09-11 23:17:25 +020011382 RESET_SAFE_LJMP(s->hlua);
Christopher Faulet69c581a2021-05-31 08:54:04 +020011383 ret = 0;
11384 goto end;
11385 }
11386
Aurelien DARRAGON4fdf8b52023-03-20 17:22:37 +010011387 hlua_pushref(s->hlua->T, conf->ref[s->hlua->state_id]);
Christopher Faulet69c581a2021-05-31 08:54:04 +020011388 if (lua_getfield(s->hlua->T, -1, "new") != LUA_TFUNCTION) {
11389 SEND_ERR(s->be, "Lua filter '%s': 'new' field is not a function.\n",
11390 conf->reg->name);
11391 RESET_SAFE_LJMP(s->hlua);
11392 ret = 0;
11393 goto end;
11394 }
11395 lua_insert(s->hlua->T, -2);
11396
11397 /* Push the copy on the stack */
11398 s->hlua->nargs = 1;
11399
11400 /* We must initialize the execution timeouts. */
Aurelien DARRAGONda9503c2022-11-25 09:10:07 +010011401 hlua_timer_init(&s->hlua->timer, hlua_timeout_session);
Christopher Faulet69c581a2021-05-31 08:54:04 +020011402
11403 /* At this point the execution is safe. */
11404 RESET_SAFE_LJMP(s->hlua);
11405 }
11406
11407 switch (hlua_ctx_resume(s->hlua, 0)) {
11408 case HLUA_E_OK:
11409 /* Nothing returned or not a table, ignore the filter for current stream */
11410 if (!lua_gettop(s->hlua->T) || !lua_istable(s->hlua->T, 1)) {
11411 ret = 0;
11412 goto end;
11413 }
11414
11415 /* Attached the filter pointer to the ctx */
11416 lua_pushstring(s->hlua->T, "__filter");
11417 lua_pushlightuserdata(s->hlua->T, filter);
11418 lua_settable(s->hlua->T, -3);
11419
11420 /* Save a ref on the filter ctx */
11421 lua_pushvalue(s->hlua->T, 1);
Aurelien DARRAGON73d1a982023-03-20 17:42:08 +010011422 flt_ctx->ref = hlua_ref(s->hlua->T);
Christopher Faulet69c581a2021-05-31 08:54:04 +020011423 filter->ctx = flt_ctx;
11424 break;
11425 case HLUA_E_ERRMSG:
11426 SEND_ERR(s->be, "Lua filter '%s' : %s.\n", conf->reg->name, lua_tostring(s->hlua->T, -1));
11427 ret = -1;
11428 goto end;
11429 case HLUA_E_ETMOUT:
11430 SEND_ERR(s->be, "Lua filter '%s' : 'new' execution timeout.\n", conf->reg->name);
11431 ret = 0;
11432 goto end;
11433 case HLUA_E_NOMEM:
11434 SEND_ERR(s->be, "Lua filter '%s' : out of memory error.\n", conf->reg->name);
11435 ret = 0;
11436 goto end;
11437 case HLUA_E_AGAIN:
11438 case HLUA_E_YIELD:
11439 SEND_ERR(s->be, "Lua filter '%s': yield functions like core.tcp() or core.sleep()"
11440 " are not allowed from 'new' function.\n", conf->reg->name);
11441 ret = 0;
11442 goto end;
11443 case HLUA_E_ERR:
11444 SEND_ERR(s->be, "Lua filter '%s': 'new' returns an unknown error.\n", conf->reg->name);
11445 ret = 0;
11446 goto end;
11447 default:
11448 ret = 0;
11449 goto end;
11450 }
11451
11452 end:
11453 if (s->hlua)
11454 lua_settop(s->hlua->T, 0);
11455 if (ret <= 0) {
11456 if (flt_ctx) {
11457 hlua_ctx_destroy(flt_ctx->hlua[0]);
11458 hlua_ctx_destroy(flt_ctx->hlua[1]);
11459 pool_free(pool_head_hlua_flt_ctx, flt_ctx);
11460 }
11461 }
11462 return ret;
11463}
11464
11465static void hlua_filter_delete(struct stream *s, struct filter *filter)
11466{
11467 struct hlua_flt_ctx *flt_ctx = filter->ctx;
11468
Aurelien DARRAGONfde199d2023-03-20 15:09:33 +010011469 hlua_unref(s->hlua->T, flt_ctx->ref);
Christopher Faulet69c581a2021-05-31 08:54:04 +020011470 hlua_ctx_destroy(flt_ctx->hlua[0]);
11471 hlua_ctx_destroy(flt_ctx->hlua[1]);
11472 pool_free(pool_head_hlua_flt_ctx, flt_ctx);
11473 filter->ctx = NULL;
11474}
11475
Christopher Faulet9f55a502020-02-25 15:21:02 +010011476static int hlua_filter_from_payload(struct filter *filter)
11477{
11478 struct hlua_flt_ctx *flt_ctx = filter->ctx;
11479
11480 return (flt_ctx && !!(flt_ctx->flags & HLUA_FLT_CTX_FL_PAYLOAD));
11481}
11482
Christopher Fauletc404f112020-02-26 15:03:09 +010011483static int hlua_filter_callback(struct stream *s, struct filter *filter, const char *fun,
11484 int dir, unsigned int flags)
11485{
11486 struct hlua *flt_hlua;
11487 struct hlua_flt_config *conf = FLT_CONF(filter);
11488 struct hlua_flt_ctx *flt_ctx = filter->ctx;
11489 unsigned int hflags = HLUA_TXN_FLT_CTX;
11490 int ret = 1;
11491
11492 flt_hlua = flt_ctx->hlua[(dir == SMP_OPT_DIR_REQ ? 0 : 1)];
11493 if (!flt_hlua)
11494 goto end;
11495
11496 if (!HLUA_IS_RUNNING(flt_hlua)) {
11497 int extra_idx = lua_gettop(flt_hlua->T);
11498
11499 /* The following Lua calls can fail. */
11500 if (!SET_SAFE_LJMP(flt_hlua)) {
11501 const char *error;
11502
11503 if (lua_type(flt_hlua->T, -1) == LUA_TSTRING)
11504 error = lua_tostring(flt_hlua->T, -1);
11505 else
11506 error = "critical error";
11507 SEND_ERR(s->be, "Lua filter '%s': %s.\n", conf->reg->name, error);
11508 goto end;
11509 }
11510
11511 /* Check stack size. */
11512 if (!lua_checkstack(flt_hlua->T, 3)) {
11513 SEND_ERR(s->be, "Lua filter '%s': full stack.\n", conf->reg->name);
11514 RESET_SAFE_LJMP(flt_hlua);
11515 goto end;
11516 }
11517
Aurelien DARRAGON4fdf8b52023-03-20 17:22:37 +010011518 hlua_pushref(flt_hlua->T, flt_ctx->ref);
Christopher Fauletc404f112020-02-26 15:03:09 +010011519 if (lua_getfield(flt_hlua->T, -1, fun) != LUA_TFUNCTION) {
11520 RESET_SAFE_LJMP(flt_hlua);
11521 goto end;
11522 }
11523 lua_insert(flt_hlua->T, -2);
11524
11525 if (!hlua_txn_new(flt_hlua->T, s, s->be, dir, hflags)) {
11526 SEND_ERR(s->be, "Lua filter '%s': full stack.\n", conf->reg->name);
11527 RESET_SAFE_LJMP(flt_hlua);
11528 goto end;
11529 }
11530 flt_hlua->nargs = 2;
11531
11532 if (flags & HLUA_FLT_CB_ARG_CHN) {
11533 if (dir == SMP_OPT_DIR_REQ)
11534 lua_getfield(flt_hlua->T, -1, "req");
11535 else
11536 lua_getfield(flt_hlua->T, -1, "res");
11537 if (lua_type(flt_hlua->T, -1) == LUA_TTABLE) {
11538 lua_pushstring(flt_hlua->T, "__filter");
11539 lua_pushlightuserdata(flt_hlua->T, filter);
11540 lua_settable(flt_hlua->T, -3);
11541 }
11542 flt_hlua->nargs++;
11543 }
11544 else if (flags & HLUA_FLT_CB_ARG_HTTP_MSG) {
Christopher Fauleteae8afa2020-02-26 17:15:48 +010011545 if (dir == SMP_OPT_DIR_REQ)
11546 lua_getfield(flt_hlua->T, -1, "http_req");
11547 else
11548 lua_getfield(flt_hlua->T, -1, "http_res");
11549 if (lua_type(flt_hlua->T, -1) == LUA_TTABLE) {
11550 lua_pushstring(flt_hlua->T, "__filter");
11551 lua_pushlightuserdata(flt_hlua->T, filter);
11552 lua_settable(flt_hlua->T, -3);
11553 }
11554 flt_hlua->nargs++;
Christopher Fauletc404f112020-02-26 15:03:09 +010011555 }
11556
11557 /* Check stack size. */
11558 if (!lua_checkstack(flt_hlua->T, 1)) {
11559 SEND_ERR(s->be, "Lua filter '%s': full stack.\n", conf->reg->name);
11560 RESET_SAFE_LJMP(flt_hlua);
11561 goto end;
11562 }
11563
11564 while (extra_idx--) {
11565 lua_pushvalue(flt_hlua->T, 1);
11566 lua_remove(flt_hlua->T, 1);
11567 flt_hlua->nargs++;
11568 }
11569
11570 /* We must initialize the execution timeouts. */
Aurelien DARRAGONda9503c2022-11-25 09:10:07 +010011571 hlua_timer_init(&flt_hlua->timer, hlua_timeout_session);
Christopher Fauletc404f112020-02-26 15:03:09 +010011572
11573 /* At this point the execution is safe. */
11574 RESET_SAFE_LJMP(flt_hlua);
11575 }
11576
11577 switch (hlua_ctx_resume(flt_hlua, !(flags & HLUA_FLT_CB_FINAL))) {
11578 case HLUA_E_OK:
11579 /* Catch the return value if it required */
11580 if ((flags & HLUA_FLT_CB_RETVAL) && lua_gettop(flt_hlua->T) > 0) {
11581 ret = lua_tointeger(flt_hlua->T, -1);
11582 lua_settop(flt_hlua->T, 0); /* Empty the stack. */
11583 }
11584
11585 /* Set timeout in the required channel. */
11586 if (flt_hlua->wake_time != TICK_ETERNITY) {
11587 if (dir == SMP_OPT_DIR_REQ)
11588 s->req.analyse_exp = flt_hlua->wake_time;
11589 else
11590 s->res.analyse_exp = flt_hlua->wake_time;
11591 }
11592 break;
11593 case HLUA_E_AGAIN:
11594 /* Set timeout in the required channel. */
11595 if (flt_hlua->wake_time != TICK_ETERNITY) {
11596 if (dir == SMP_OPT_DIR_REQ)
11597 s->req.analyse_exp = flt_hlua->wake_time;
11598 else
11599 s->res.analyse_exp = flt_hlua->wake_time;
11600 }
11601 /* Some actions can be wake up when a "write" event
11602 * is detected on a response channel. This is useful
11603 * only for actions targeted on the requests.
11604 */
11605 if (HLUA_IS_WAKERESWR(flt_hlua))
11606 s->res.flags |= CF_WAKE_WRITE;
11607 if (HLUA_IS_WAKEREQWR(flt_hlua))
11608 s->req.flags |= CF_WAKE_WRITE;
11609 ret = 0;
11610 goto end;
11611 case HLUA_E_ERRMSG:
11612 SEND_ERR(s->be, "Lua filter '%s' : %s.\n", conf->reg->name, lua_tostring(flt_hlua->T, -1));
11613 ret = -1;
11614 goto end;
11615 case HLUA_E_ETMOUT:
11616 SEND_ERR(s->be, "Lua filter '%s' : '%s' callback execution timeout.\n", conf->reg->name, fun);
11617 goto end;
11618 case HLUA_E_NOMEM:
11619 SEND_ERR(s->be, "Lua filter '%s' : out of memory error.\n", conf->reg->name);
11620 goto end;
11621 case HLUA_E_YIELD:
11622 SEND_ERR(s->be, "Lua filter '%s': yield functions like core.tcp() or core.sleep()"
11623 " are not allowed from '%s' callback.\n", conf->reg->name, fun);
11624 goto end;
11625 case HLUA_E_ERR:
11626 SEND_ERR(s->be, "Lua filter '%s': '%s' returns an unknown error.\n", conf->reg->name, fun);
11627 goto end;
11628 default:
11629 goto end;
11630 }
11631
11632
11633 end:
11634 return ret;
11635}
11636
11637static int hlua_filter_start_analyze(struct stream *s, struct filter *filter, struct channel *chn)
11638{
11639 struct hlua_flt_ctx *flt_ctx = filter->ctx;
11640
11641 flt_ctx->flags = 0;
11642 return hlua_filter_callback(s, filter, "start_analyze",
11643 (!(chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES),
11644 (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_RETVAL | HLUA_FLT_CB_ARG_CHN));
11645}
11646
11647static int hlua_filter_end_analyze(struct stream *s, struct filter *filter, struct channel *chn)
11648{
11649 struct hlua_flt_ctx *flt_ctx = filter->ctx;
11650
11651 flt_ctx->flags &= ~HLUA_FLT_CTX_FL_PAYLOAD;
11652 return hlua_filter_callback(s, filter, "end_analyze",
11653 (!(chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES),
11654 (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_RETVAL | HLUA_FLT_CB_ARG_CHN));
11655}
11656
Christopher Fauleteae8afa2020-02-26 17:15:48 +010011657static int hlua_filter_http_headers(struct stream *s, struct filter *filter, struct http_msg *msg)
11658{
11659 struct hlua_flt_ctx *flt_ctx = filter->ctx;
11660
11661 flt_ctx->flags &= ~HLUA_FLT_CTX_FL_PAYLOAD;
11662 return hlua_filter_callback(s, filter, "http_headers",
11663 (!(msg->chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES),
11664 (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_RETVAL | HLUA_FLT_CB_ARG_HTTP_MSG));
11665}
11666
11667static int hlua_filter_http_payload(struct stream *s, struct filter *filter, struct http_msg *msg,
11668 unsigned int offset, unsigned int len)
11669{
11670 struct hlua_flt_ctx *flt_ctx = filter->ctx;
11671 struct hlua *flt_hlua;
11672 int dir = (!(msg->chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES);
11673 int idx = (dir == SMP_OPT_DIR_REQ ? 0 : 1);
11674 int ret;
11675
11676 flt_hlua = flt_ctx->hlua[idx];
11677 flt_ctx->cur_off[idx] = offset;
11678 flt_ctx->cur_len[idx] = len;
11679 flt_ctx->flags |= HLUA_FLT_CTX_FL_PAYLOAD;
11680 ret = hlua_filter_callback(s, filter, "http_payload", dir, (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_ARG_HTTP_MSG));
11681 if (ret != -1) {
11682 ret = flt_ctx->cur_len[idx];
11683 if (lua_gettop(flt_hlua->T) > 0) {
11684 ret = lua_tointeger(flt_hlua->T, -1);
11685 if (ret > flt_ctx->cur_len[idx])
11686 ret = flt_ctx->cur_len[idx];
11687 lua_settop(flt_hlua->T, 0); /* Empty the stack. */
11688 }
11689 }
11690 return ret;
11691}
11692
11693static int hlua_filter_http_end(struct stream *s, struct filter *filter, struct http_msg *msg)
11694{
11695 struct hlua_flt_ctx *flt_ctx = filter->ctx;
11696
11697 flt_ctx->flags &= ~HLUA_FLT_CTX_FL_PAYLOAD;
11698 return hlua_filter_callback(s, filter, "http_end",
11699 (!(msg->chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES),
11700 (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_RETVAL | HLUA_FLT_CB_ARG_HTTP_MSG));
11701}
11702
Christopher Fauletc404f112020-02-26 15:03:09 +010011703static int hlua_filter_tcp_payload(struct stream *s, struct filter *filter, struct channel *chn,
11704 unsigned int offset, unsigned int len)
11705{
11706 struct hlua_flt_ctx *flt_ctx = filter->ctx;
11707 struct hlua *flt_hlua;
11708 int dir = (!(chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES);
11709 int idx = (dir == SMP_OPT_DIR_REQ ? 0 : 1);
11710 int ret;
11711
11712 flt_hlua = flt_ctx->hlua[idx];
11713 flt_ctx->cur_off[idx] = offset;
11714 flt_ctx->cur_len[idx] = len;
11715 flt_ctx->flags |= HLUA_FLT_CTX_FL_PAYLOAD;
11716 ret = hlua_filter_callback(s, filter, "tcp_payload", dir, (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_ARG_CHN));
11717 if (ret != -1) {
11718 ret = flt_ctx->cur_len[idx];
11719 if (lua_gettop(flt_hlua->T) > 0) {
11720 ret = lua_tointeger(flt_hlua->T, -1);
11721 if (ret > flt_ctx->cur_len[idx])
11722 ret = flt_ctx->cur_len[idx];
11723 lua_settop(flt_hlua->T, 0); /* Empty the stack. */
11724 }
11725 }
11726 return ret;
11727}
11728
Christopher Faulet69c581a2021-05-31 08:54:04 +020011729static int hlua_filter_parse_fct(char **args, int *cur_arg, struct proxy *px,
11730 struct flt_conf *fconf, char **err, void *private)
11731{
11732 struct hlua_reg_filter *reg_flt = private;
11733 lua_State *L;
11734 struct hlua_flt_config *conf = NULL;
11735 const char *flt_id = NULL;
11736 int state_id, pos, flt_flags = 0;
11737 struct flt_ops *hlua_flt_ops = NULL;
11738
11739 state_id = reg_flt_to_stack_id(reg_flt);
11740 L = hlua_states[state_id];
11741
11742 /* Initialize the filter ops with default callbacks */
11743 hlua_flt_ops = calloc(1, sizeof(*hlua_flt_ops));
Christopher Fauletc86bb872021-08-13 08:33:57 +020011744 if (!hlua_flt_ops)
11745 goto error;
Christopher Faulet69c581a2021-05-31 08:54:04 +020011746 hlua_flt_ops->init = hlua_filter_init;
11747 hlua_flt_ops->deinit = hlua_filter_deinit;
11748 if (state_id) {
11749 /* Set per-thread callback if script is loaded per-thread */
11750 hlua_flt_ops->init_per_thread = hlua_filter_init_per_thread;
11751 hlua_flt_ops->deinit_per_thread = hlua_filter_deinit_per_thread;
11752 }
11753 hlua_flt_ops->attach = hlua_filter_new;
11754 hlua_flt_ops->detach = hlua_filter_delete;
11755
11756 /* Push the filter class on the stack and resolve all callbacks */
Aurelien DARRAGON4fdf8b52023-03-20 17:22:37 +010011757 hlua_pushref(L, reg_flt->flt_ref[state_id]);
Christopher Faulet69c581a2021-05-31 08:54:04 +020011758
Christopher Fauletc404f112020-02-26 15:03:09 +010011759 if (lua_getfield(L, -1, "start_analyze") == LUA_TFUNCTION)
11760 hlua_flt_ops->channel_start_analyze = hlua_filter_start_analyze;
11761 lua_pop(L, 1);
11762 if (lua_getfield(L, -1, "end_analyze") == LUA_TFUNCTION)
11763 hlua_flt_ops->channel_end_analyze = hlua_filter_end_analyze;
11764 lua_pop(L, 1);
Christopher Fauleteae8afa2020-02-26 17:15:48 +010011765 if (lua_getfield(L, -1, "http_headers") == LUA_TFUNCTION)
11766 hlua_flt_ops->http_headers = hlua_filter_http_headers;
11767 lua_pop(L, 1);
11768 if (lua_getfield(L, -1, "http_payload") == LUA_TFUNCTION)
11769 hlua_flt_ops->http_payload = hlua_filter_http_payload;
11770 lua_pop(L, 1);
11771 if (lua_getfield(L, -1, "http_end") == LUA_TFUNCTION)
11772 hlua_flt_ops->http_end = hlua_filter_http_end;
11773 lua_pop(L, 1);
Christopher Fauletc404f112020-02-26 15:03:09 +010011774 if (lua_getfield(L, -1, "tcp_payload") == LUA_TFUNCTION)
11775 hlua_flt_ops->tcp_payload = hlua_filter_tcp_payload;
11776 lua_pop(L, 1);
Christopher Faulet69c581a2021-05-31 08:54:04 +020011777
11778 /* Get id and flags of the filter class */
11779 if (lua_getfield(L, -1, "id") == LUA_TSTRING)
11780 flt_id = lua_tostring(L, -1);
11781 lua_pop(L, 1);
11782 if (lua_getfield(L, -1, "flags") == LUA_TNUMBER)
11783 flt_flags = lua_tointeger(L, -1);
11784 lua_pop(L, 1);
11785
11786 /* Create the filter config */
11787 conf = calloc(1, sizeof(*conf));
Christopher Fauletc86bb872021-08-13 08:33:57 +020011788 if (!conf)
Christopher Faulet69c581a2021-05-31 08:54:04 +020011789 goto error;
Christopher Faulet69c581a2021-05-31 08:54:04 +020011790 conf->reg = reg_flt;
11791
11792 /* duplicate args */
11793 for (pos = 0; *args[*cur_arg + 1 + pos]; pos++);
11794 conf->args = calloc(pos + 1, sizeof(*conf->args));
Christopher Fauletc86bb872021-08-13 08:33:57 +020011795 if (!conf->args)
11796 goto error;
11797 for (pos = 0; *args[*cur_arg + 1 + pos]; pos++) {
Christopher Faulet69c581a2021-05-31 08:54:04 +020011798 conf->args[pos] = strdup(args[*cur_arg + 1 + pos]);
Christopher Fauletc86bb872021-08-13 08:33:57 +020011799 if (!conf->args[pos])
11800 goto error;
11801 }
Christopher Faulet69c581a2021-05-31 08:54:04 +020011802 conf->args[pos] = NULL;
11803 *cur_arg += pos + 1;
11804
Christopher Fauletc86bb872021-08-13 08:33:57 +020011805 if (flt_id) {
11806 fconf->id = strdup(flt_id);
11807 if (!fconf->id)
11808 goto error;
11809 }
Christopher Faulet69c581a2021-05-31 08:54:04 +020011810 fconf->flags = flt_flags;
11811 fconf->conf = conf;
11812 fconf->ops = hlua_flt_ops;
11813
11814 lua_settop(L, 0);
11815 return 0;
11816
11817 error:
Christopher Fauletc86bb872021-08-13 08:33:57 +020011818 memprintf(err, "Lua filter '%s' : Lua out of memory error", reg_flt->name);
Christopher Faulet69c581a2021-05-31 08:54:04 +020011819 free(hlua_flt_ops);
Christopher Fauletc86bb872021-08-13 08:33:57 +020011820 if (conf && conf->args) {
11821 for (pos = 0; conf->args[pos]; pos++)
11822 free(conf->args[pos]);
11823 free(conf->args);
11824 }
Christopher Faulet69c581a2021-05-31 08:54:04 +020011825 free(conf);
Christopher Fauletc86bb872021-08-13 08:33:57 +020011826 free((char *)fconf->id);
Christopher Faulet69c581a2021-05-31 08:54:04 +020011827 lua_settop(L, 0);
11828 return -1;
11829}
11830
Christopher Fauletc404f112020-02-26 15:03:09 +010011831__LJMP static int hlua_register_data_filter(lua_State *L)
11832{
11833 struct filter *filter;
11834 struct channel *chn;
11835
11836 MAY_LJMP(check_args(L, 2, "register_data_filter"));
11837 MAY_LJMP(luaL_checktype(L, 1, LUA_TTABLE));
11838 chn = MAY_LJMP(hlua_checkchannel(L, 2));
11839
11840 lua_getfield(L, 1, "__filter");
11841 MAY_LJMP(luaL_checktype(L, -1, LUA_TLIGHTUSERDATA));
11842 filter = lua_touserdata (L, -1);
11843 lua_pop(L, 1);
11844
11845 register_data_filter(chn_strm(chn), chn, filter);
11846 return 1;
11847}
11848
11849__LJMP static int hlua_unregister_data_filter(lua_State *L)
11850{
11851 struct filter *filter;
11852 struct channel *chn;
11853
11854 MAY_LJMP(check_args(L, 2, "unregister_data_filter"));
11855 MAY_LJMP(luaL_checktype(L, 1, LUA_TTABLE));
11856 chn = MAY_LJMP(hlua_checkchannel(L, 2));
11857
11858 lua_getfield(L, 1, "__filter");
11859 MAY_LJMP(luaL_checktype(L, -1, LUA_TLIGHTUSERDATA));
11860 filter = lua_touserdata (L, -1);
11861 lua_pop(L, 1);
11862
11863 unregister_data_filter(chn_strm(chn), chn, filter);
11864 return 1;
11865}
11866
Christopher Faulet69c581a2021-05-31 08:54:04 +020011867/* This function is an LUA binding used for registering a filter. It expects a
Ilya Shipitsinff0f2782021-08-22 22:18:07 +050011868 * filter name used in the haproxy configuration file and a LUA function to
Christopher Faulet69c581a2021-05-31 08:54:04 +020011869 * parse configuration arguments.
11870 */
11871__LJMP static int hlua_register_filter(lua_State *L)
11872{
11873 struct buffer *trash;
11874 struct flt_kw_list *fkl;
11875 struct flt_kw *fkw;
11876 const char *name;
11877 struct hlua_reg_filter *reg_flt= NULL;
11878 int flt_ref, fun_ref;
11879 int len;
11880
11881 MAY_LJMP(check_args(L, 3, "register_filter"));
11882
Aurelien DARRAGON87f52972023-02-24 09:43:54 +010011883 if (hlua_gethlua(L)) {
11884 /* runtime processing */
11885 WILL_LJMP(luaL_error(L, "register_filter: not available outside of body context"));
11886 }
11887
Christopher Faulet69c581a2021-05-31 08:54:04 +020011888 /* First argument : filter name. */
11889 name = MAY_LJMP(luaL_checkstring(L, 1));
11890
11891 /* Second argument : The filter class */
11892 flt_ref = MAY_LJMP(hlua_checktable(L, 2));
11893
11894 /* Third argument : lua function. */
11895 fun_ref = MAY_LJMP(hlua_checkfunction(L, 3));
11896
11897 trash = get_trash_chunk();
11898 chunk_printf(trash, "lua.%s", name);
11899 fkw = flt_find_kw(trash->area);
11900 if (fkw != NULL) {
11901 reg_flt = fkw->private;
11902 if (reg_flt->flt_ref[hlua_state_id] != -1 || reg_flt->fun_ref[hlua_state_id] != -1) {
11903 ha_warning("Trying to register filter 'lua.%s' more than once. "
11904 "This will become a hard error in version 2.5.\n", name);
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +010011905 if (reg_flt->flt_ref[hlua_state_id] != -1)
11906 hlua_unref(L, reg_flt->flt_ref[hlua_state_id]);
11907 if (reg_flt->fun_ref[hlua_state_id] != -1)
11908 hlua_unref(L, reg_flt->fun_ref[hlua_state_id]);
Christopher Faulet69c581a2021-05-31 08:54:04 +020011909 }
11910 reg_flt->flt_ref[hlua_state_id] = flt_ref;
11911 reg_flt->fun_ref[hlua_state_id] = fun_ref;
11912 return 0;
11913 }
11914
11915 fkl = calloc(1, sizeof(*fkl) + sizeof(struct flt_kw) * 2);
11916 if (!fkl)
11917 goto alloc_error;
11918 fkl->scope = "HLUA";
11919
11920 reg_flt = new_hlua_reg_filter(name);
11921 if (!reg_flt)
11922 goto alloc_error;
11923
11924 reg_flt->flt_ref[hlua_state_id] = flt_ref;
11925 reg_flt->fun_ref[hlua_state_id] = fun_ref;
11926
11927 /* The filter keyword */
11928 len = strlen("lua.") + strlen(name) + 1;
11929 fkl->kw[0].kw = calloc(1, len);
11930 if (!fkl->kw[0].kw)
11931 goto alloc_error;
11932
11933 snprintf((char *)fkl->kw[0].kw, len, "lua.%s", name);
11934
11935 fkl->kw[0].parse = hlua_filter_parse_fct;
11936 fkl->kw[0].private = reg_flt;
11937 memset(&fkl->kw[1], 0, sizeof(*fkl->kw));
11938
11939 /* Register this new filter */
11940 flt_register_keywords(fkl);
11941
11942 return 0;
11943
11944 alloc_error:
11945 release_hlua_reg_filter(reg_flt);
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +010011946 hlua_unref(L, flt_ref);
11947 hlua_unref(L, fun_ref);
Christopher Faulet69c581a2021-05-31 08:54:04 +020011948 ha_free(&fkl);
11949 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
11950 return 0; /* Never reached */
11951}
11952
Thierry FOURNIERbd413492015-03-03 16:52:26 +010011953static int hlua_read_timeout(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011954 const struct proxy *defpx, const char *file, int line,
Thierry FOURNIERbd413492015-03-03 16:52:26 +010011955 char **err, unsigned int *timeout)
11956{
11957 const char *error;
11958
11959 error = parse_time_err(args[1], timeout, TIME_UNIT_MS);
Willy Tarreau9faebe32019-06-07 19:00:37 +020011960 if (error == PARSE_TIME_OVER) {
11961 memprintf(err, "timer overflow in argument <%s> to <%s> (maximum value is 2147483647 ms or ~24.8 days)",
11962 args[1], args[0]);
11963 return -1;
11964 }
11965 else if (error == PARSE_TIME_UNDER) {
11966 memprintf(err, "timer underflow in argument <%s> to <%s> (minimum non-null value is 1 ms)",
11967 args[1], args[0]);
11968 return -1;
11969 }
11970 else if (error) {
Thierry FOURNIERbd413492015-03-03 16:52:26 +010011971 memprintf(err, "%s: invalid timeout", args[0]);
11972 return -1;
11973 }
11974 return 0;
11975}
11976
Aurelien DARRAGON58e36e52023-04-06 22:51:56 +020011977static int hlua_burst_timeout(char **args, int section_type, struct proxy *curpx,
11978 const struct proxy *defpx, const char *file, int line,
11979 char **err)
11980{
11981 return hlua_read_timeout(args, section_type, curpx, defpx,
11982 file, line, err, &hlua_timeout_burst);
11983}
11984
Thierry FOURNIERbd413492015-03-03 16:52:26 +010011985static int hlua_session_timeout(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011986 const struct proxy *defpx, const char *file, int line,
Thierry FOURNIERbd413492015-03-03 16:52:26 +010011987 char **err)
11988{
11989 return hlua_read_timeout(args, section_type, curpx, defpx,
11990 file, line, err, &hlua_timeout_session);
11991}
11992
11993static int hlua_task_timeout(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011994 const struct proxy *defpx, const char *file, int line,
Thierry FOURNIERbd413492015-03-03 16:52:26 +010011995 char **err)
11996{
11997 return hlua_read_timeout(args, section_type, curpx, defpx,
11998 file, line, err, &hlua_timeout_task);
11999}
12000
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020012001static int hlua_applet_timeout(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010012002 const struct proxy *defpx, const char *file, int line,
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020012003 char **err)
12004{
12005 return hlua_read_timeout(args, section_type, curpx, defpx,
12006 file, line, err, &hlua_timeout_applet);
12007}
12008
Thierry FOURNIERee9f8022015-03-03 17:37:37 +010012009static int hlua_forced_yield(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010012010 const struct proxy *defpx, const char *file, int line,
Thierry FOURNIERee9f8022015-03-03 17:37:37 +010012011 char **err)
12012{
12013 char *error;
12014
12015 hlua_nb_instruction = strtoll(args[1], &error, 10);
12016 if (*error != '\0') {
12017 memprintf(err, "%s: invalid number", args[0]);
12018 return -1;
12019 }
12020 return 0;
12021}
12022
Willy Tarreau32f61e22015-03-18 17:54:59 +010012023static int hlua_parse_maxmem(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010012024 const struct proxy *defpx, const char *file, int line,
Willy Tarreau32f61e22015-03-18 17:54:59 +010012025 char **err)
12026{
12027 char *error;
12028
12029 if (*(args[1]) == 0) {
Thierry Fournier70e38e92022-09-19 09:01:53 +020012030 memprintf(err, "'%s' expects an integer argument (Lua memory size in MB).", args[0]);
Willy Tarreau32f61e22015-03-18 17:54:59 +010012031 return -1;
12032 }
12033 hlua_global_allocator.limit = strtoll(args[1], &error, 10) * 1024L * 1024L;
12034 if (*error != '\0') {
12035 memprintf(err, "%s: invalid number %s (error at '%c')", args[0], args[1], *error);
12036 return -1;
12037 }
12038 return 0;
12039}
12040
12041
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010012042/* This function is called by the main configuration key "lua-load". It loads and
12043 * execute an lua file during the parsing of the HAProxy configuration file. It is
12044 * the main lua entry point.
12045 *
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -080012046 * This function runs with the HAProxy keywords API. It returns -1 if an error
12047 * occurs, otherwise it returns 0.
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010012048 *
12049 * In some error case, LUA set an error message in top of the stack. This function
12050 * returns this error message in the HAProxy logs and pop it from the stack.
Thierry FOURNIERbabae282015-09-17 11:36:37 +020012051 *
12052 * This function can fail with an abort() due to an Lua critical error.
12053 * We are in the configuration parsing process of HAProxy, this abort() is
12054 * tolerated.
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010012055 */
Thierry Fournierae6b5682022-09-19 09:04:16 +020012056static int hlua_load_state(char **args, lua_State *L, char **err)
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010012057{
12058 int error;
Thierry Fournierae6b5682022-09-19 09:04:16 +020012059 int nargs;
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010012060
12061 /* Just load and compile the file. */
Thierry Fournierae6b5682022-09-19 09:04:16 +020012062 error = luaL_loadfile(L, args[0]);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010012063 if (error) {
Thierry Fournierae6b5682022-09-19 09:04:16 +020012064 memprintf(err, "error in Lua file '%s': %s", args[0], lua_tostring(L, -1));
Thierry Fournierc93c15c2020-11-28 15:02:13 +010012065 lua_pop(L, 1);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010012066 return -1;
12067 }
Thierry Fournierae6b5682022-09-19 09:04:16 +020012068
12069 /* Push args in the Lua stack, except the first one which is the filename */
12070 for (nargs = 1; *(args[nargs]) != 0; nargs++) {
Aurelien DARRAGON4d7aefe2022-09-23 10:22:14 +020012071 /* Check stack size. */
12072 if (!lua_checkstack(L, 1)) {
12073 memprintf(err, "Lua runtime error while loading arguments: stack is full.");
12074 return -1;
12075 }
Thierry Fournierae6b5682022-09-19 09:04:16 +020012076 lua_pushstring(L, args[nargs]);
12077 }
12078 nargs--;
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010012079
12080 /* If no syntax error where detected, execute the code. */
Thierry Fournierae6b5682022-09-19 09:04:16 +020012081 error = lua_pcall(L, nargs, LUA_MULTRET, 0);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010012082 switch (error) {
12083 case LUA_OK:
12084 break;
12085 case LUA_ERRRUN:
Thierry Fournier70e38e92022-09-19 09:01:53 +020012086 memprintf(err, "Lua runtime error: %s", lua_tostring(L, -1));
Thierry Fournierc93c15c2020-11-28 15:02:13 +010012087 lua_pop(L, 1);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010012088 return -1;
12089 case LUA_ERRMEM:
Thierry Fournier70e38e92022-09-19 09:01:53 +020012090 memprintf(err, "Lua out of memory error");
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010012091 return -1;
12092 case LUA_ERRERR:
Thierry Fournier70e38e92022-09-19 09:01:53 +020012093 memprintf(err, "Lua message handler error: %s", lua_tostring(L, -1));
Thierry Fournierc93c15c2020-11-28 15:02:13 +010012094 lua_pop(L, 1);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010012095 return -1;
Christopher Faulet08ed98f2020-07-28 10:33:25 +020012096#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM <= 503
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010012097 case LUA_ERRGCMM:
Thierry Fournier70e38e92022-09-19 09:01:53 +020012098 memprintf(err, "Lua garbage collector error: %s", lua_tostring(L, -1));
Thierry Fournierc93c15c2020-11-28 15:02:13 +010012099 lua_pop(L, 1);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010012100 return -1;
Christopher Faulet08ed98f2020-07-28 10:33:25 +020012101#endif
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010012102 default:
Thierry Fournier70e38e92022-09-19 09:01:53 +020012103 memprintf(err, "Lua unknown error: %s", lua_tostring(L, -1));
Thierry Fournierc93c15c2020-11-28 15:02:13 +010012104 lua_pop(L, 1);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010012105 return -1;
12106 }
12107
12108 return 0;
12109}
12110
Thierry Fournierc93c15c2020-11-28 15:02:13 +010012111static int hlua_load(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010012112 const struct proxy *defpx, const char *file, int line,
Thierry Fournierc93c15c2020-11-28 15:02:13 +010012113 char **err)
12114{
12115 if (*(args[1]) == 0) {
Thierry Fournier70e38e92022-09-19 09:01:53 +020012116 memprintf(err, "'%s' expects a file name as parameter.", args[0]);
Thierry Fournierc93c15c2020-11-28 15:02:13 +010012117 return -1;
12118 }
12119
Thierry Fournier59f11be2020-11-29 00:37:41 +010012120 /* loading for global state */
Thierry Fournierc7492592020-11-28 23:57:24 +010012121 hlua_state_id = 0;
Willy Tarreau43ab05b2021-09-28 09:43:11 +020012122 ha_set_thread(NULL);
Thierry Fournierae6b5682022-09-19 09:04:16 +020012123 return hlua_load_state(&args[1], hlua_states[0], err);
Thierry Fournierc93c15c2020-11-28 15:02:13 +010012124}
12125
Thierry Fournier59f11be2020-11-29 00:37:41 +010012126static int hlua_load_per_thread(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010012127 const struct proxy *defpx, const char *file, int line,
Thierry Fournier59f11be2020-11-29 00:37:41 +010012128 char **err)
12129{
12130 int len;
Thierry Fournierae6b5682022-09-19 09:04:16 +020012131 int i;
Thierry Fournier59f11be2020-11-29 00:37:41 +010012132
12133 if (*(args[1]) == 0) {
Thierry Fournier70e38e92022-09-19 09:01:53 +020012134 memprintf(err, "'%s' expects a file as parameter.", args[0]);
Thierry Fournier59f11be2020-11-29 00:37:41 +010012135 return -1;
12136 }
12137
12138 if (per_thread_load == NULL) {
12139 /* allocate the first entry large enough to store the final NULL */
12140 per_thread_load = calloc(1, sizeof(*per_thread_load));
12141 if (per_thread_load == NULL) {
12142 memprintf(err, "out of memory error");
12143 return -1;
12144 }
12145 }
12146
12147 /* count used entries */
12148 for (len = 0; per_thread_load[len] != NULL; len++)
12149 ;
12150
12151 per_thread_load = realloc(per_thread_load, (len + 2) * sizeof(*per_thread_load));
12152 if (per_thread_load == NULL) {
12153 memprintf(err, "out of memory error");
12154 return -1;
12155 }
Thierry Fournier59f11be2020-11-29 00:37:41 +010012156 per_thread_load[len + 1] = NULL;
12157
Thierry Fournierae6b5682022-09-19 09:04:16 +020012158 /* count args excepting the first, allocate array and copy args */
12159 for (i = 0; *(args[i + 1]) != 0; i++);
Aurelien DARRAGONb12d1692022-09-23 08:48:34 +020012160 per_thread_load[len] = calloc(i + 1, sizeof(*per_thread_load[len]));
Thierry Fournier59f11be2020-11-29 00:37:41 +010012161 if (per_thread_load[len] == NULL) {
12162 memprintf(err, "out of memory error");
12163 return -1;
12164 }
Thierry Fournierae6b5682022-09-19 09:04:16 +020012165 for (i = 1; *(args[i]) != 0; i++) {
12166 per_thread_load[len][i - 1] = strdup(args[i]);
12167 if (per_thread_load[len][i - 1] == NULL) {
12168 memprintf(err, "out of memory error");
12169 return -1;
12170 }
12171 }
12172 per_thread_load[len][i - 1] = strdup("");
12173 if (per_thread_load[len][i - 1] == NULL) {
12174 memprintf(err, "out of memory error");
12175 return -1;
12176 }
Thierry Fournier59f11be2020-11-29 00:37:41 +010012177
12178 /* loading for thread 1 only */
12179 hlua_state_id = 1;
Willy Tarreau43ab05b2021-09-28 09:43:11 +020012180 ha_set_thread(NULL);
Thierry Fournierae6b5682022-09-19 09:04:16 +020012181 return hlua_load_state(per_thread_load[len], hlua_states[1], err);
Thierry Fournier59f11be2020-11-29 00:37:41 +010012182}
12183
Tim Duesterhusc9fc9f22020-01-12 13:55:39 +010012184/* Prepend the given <path> followed by a semicolon to the `package.<type>` variable
12185 * in the given <ctx>.
12186 */
Thierry Fournier3fb9e512020-11-28 10:13:12 +010012187static int hlua_prepend_path(lua_State *L, char *type, char *path)
Tim Duesterhusc9fc9f22020-01-12 13:55:39 +010012188{
Thierry Fournier3fb9e512020-11-28 10:13:12 +010012189 lua_getglobal(L, "package"); /* push package variable */
12190 lua_pushstring(L, path); /* push given path */
12191 lua_pushstring(L, ";"); /* push semicolon */
12192 lua_getfield(L, -3, type); /* push old path */
12193 lua_concat(L, 3); /* concatenate to new path */
12194 lua_setfield(L, -2, type); /* store new path */
12195 lua_pop(L, 1); /* pop package variable */
Tim Duesterhusc9fc9f22020-01-12 13:55:39 +010012196
12197 return 0;
12198}
12199
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010012200static int hlua_config_prepend_path(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010012201 const struct proxy *defpx, const char *file, int line,
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010012202 char **err)
12203{
12204 char *path;
12205 char *type = "path";
Tim Duesterhus621e74a2021-01-03 20:04:36 +010012206 struct prepend_path *p = NULL;
Bertrand Jacquin7fbc7702021-11-24 21:16:06 +000012207 size_t i;
Thierry Fournier59f11be2020-11-29 00:37:41 +010012208
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010012209 if (too_many_args(2, args, err, NULL)) {
Tim Duesterhus621e74a2021-01-03 20:04:36 +010012210 goto err;
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010012211 }
12212
12213 if (!(*args[1])) {
12214 memprintf(err, "'%s' expects to receive a <path> as argument", args[0]);
Tim Duesterhus621e74a2021-01-03 20:04:36 +010012215 goto err;
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010012216 }
12217 path = args[1];
12218
12219 if (*args[2]) {
12220 if (strcmp(args[2], "path") != 0 && strcmp(args[2], "cpath") != 0) {
12221 memprintf(err, "'%s' expects <type> to either be 'path' or 'cpath'", args[0]);
Tim Duesterhus621e74a2021-01-03 20:04:36 +010012222 goto err;
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010012223 }
12224 type = args[2];
12225 }
12226
Thierry Fournier59f11be2020-11-29 00:37:41 +010012227 p = calloc(1, sizeof(*p));
12228 if (p == NULL) {
Tim Duesterhusf89d43a2021-01-03 20:04:37 +010012229 memprintf(err, "memory allocation failed");
Tim Duesterhus621e74a2021-01-03 20:04:36 +010012230 goto err;
Thierry Fournier59f11be2020-11-29 00:37:41 +010012231 }
12232 p->path = strdup(path);
12233 if (p->path == NULL) {
Tim Duesterhusf89d43a2021-01-03 20:04:37 +010012234 memprintf(err, "memory allocation failed");
Tim Duesterhus621e74a2021-01-03 20:04:36 +010012235 goto err2;
Thierry Fournier59f11be2020-11-29 00:37:41 +010012236 }
12237 p->type = strdup(type);
12238 if (p->type == NULL) {
Tim Duesterhusf89d43a2021-01-03 20:04:37 +010012239 memprintf(err, "memory allocation failed");
Tim Duesterhus621e74a2021-01-03 20:04:36 +010012240 goto err2;
Thierry Fournier59f11be2020-11-29 00:37:41 +010012241 }
Willy Tarreau2b718102021-04-21 07:32:39 +020012242 LIST_APPEND(&prepend_path_list, &p->l);
Thierry Fournier59f11be2020-11-29 00:37:41 +010012243
Tim Duesterhus9e5e5862021-10-11 18:51:08 +020012244 /* Handle the global state and the per-thread state for the first
12245 * thread. The remaining threads will be initialized based on
12246 * prepend_path_list.
12247 */
Bertrand Jacquin7fbc7702021-11-24 21:16:06 +000012248 for (i = 0; i < 2; i++) {
Tim Duesterhus9e5e5862021-10-11 18:51:08 +020012249 lua_State *L = hlua_states[i];
12250 const char *error;
12251
12252 if (setjmp(safe_ljmp_env) != 0) {
12253 lua_atpanic(L, hlua_panic_safe);
12254 if (lua_type(L, -1) == LUA_TSTRING)
12255 error = lua_tostring(L, -1);
12256 else
12257 error = "critical error";
12258 fprintf(stderr, "lua-prepend-path: %s.\n", error);
12259 exit(1);
12260 } else {
12261 lua_atpanic(L, hlua_panic_ljmp);
12262 }
12263
12264 hlua_prepend_path(L, type, path);
12265
12266 lua_atpanic(L, hlua_panic_safe);
12267 }
12268
Thierry Fournier59f11be2020-11-29 00:37:41 +010012269 return 0;
Tim Duesterhus621e74a2021-01-03 20:04:36 +010012270
12271err2:
12272 free(p->type);
12273 free(p->path);
12274err:
12275 free(p);
12276 return -1;
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010012277}
12278
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010012279/* configuration keywords declaration */
12280static struct cfg_kw_list cfg_kws = {{ },{
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010012281 { CFG_GLOBAL, "lua-prepend-path", hlua_config_prepend_path },
Thierry FOURNIERbd413492015-03-03 16:52:26 +010012282 { CFG_GLOBAL, "lua-load", hlua_load },
Thierry Fournier59f11be2020-11-29 00:37:41 +010012283 { CFG_GLOBAL, "lua-load-per-thread", hlua_load_per_thread },
Thierry FOURNIERbd413492015-03-03 16:52:26 +010012284 { CFG_GLOBAL, "tune.lua.session-timeout", hlua_session_timeout },
12285 { CFG_GLOBAL, "tune.lua.task-timeout", hlua_task_timeout },
Thierry FOURNIER56da1012015-10-01 08:42:31 +020012286 { CFG_GLOBAL, "tune.lua.service-timeout", hlua_applet_timeout },
Aurelien DARRAGON58e36e52023-04-06 22:51:56 +020012287 { CFG_GLOBAL, "tune.lua.burst-timeout", hlua_burst_timeout },
Thierry FOURNIERee9f8022015-03-03 17:37:37 +010012288 { CFG_GLOBAL, "tune.lua.forced-yield", hlua_forced_yield },
Willy Tarreau32f61e22015-03-18 17:54:59 +010012289 { CFG_GLOBAL, "tune.lua.maxmem", hlua_parse_maxmem },
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010012290 { 0, NULL, NULL },
12291}};
12292
Willy Tarreau0108d902018-11-25 19:14:37 +010012293INITCALL1(STG_REGISTER, cfg_register_keywords, &cfg_kws);
12294
William Lallemand52139182022-03-30 15:05:42 +020012295#ifdef USE_OPENSSL
Christopher Fauletafd8f102018-11-08 11:34:21 +010012296
William Lallemand30fcca12022-03-30 12:03:12 +020012297/*
12298 * This function replace a ckch_store by another one, and rebuild the ckch_inst and all its dependencies.
12299 * It does the sam as "cli_io_handler_commit_cert" but for lua, the major
12300 * difference is that the yield in lua and for the CLI is not handled the same
12301 * way.
12302 */
12303__LJMP static int hlua_ckch_commit_yield(lua_State *L, int status, lua_KContext ctx)
12304{
12305 struct ckch_inst **lua_ckchi = lua_touserdata(L, -1);
12306 struct ckch_store **lua_ckchs = lua_touserdata(L, -2);
12307 struct ckch_inst *ckchi = *lua_ckchi;
12308 struct ckch_store *old_ckchs = lua_ckchs[0];
12309 struct ckch_store *new_ckchs = lua_ckchs[1];
12310 struct hlua *hlua;
12311 char *err = NULL;
12312 int y = 1;
12313
12314 hlua = hlua_gethlua(L);
12315
12316 /* get the first ckchi to copy */
12317 if (ckchi == NULL)
12318 ckchi = LIST_ELEM(old_ckchs->ckch_inst.n, typeof(ckchi), by_ckchs);
12319
12320 /* walk through the old ckch_inst and creates new ckch_inst using the updated ckchs */
12321 list_for_each_entry_from(ckchi, &old_ckchs->ckch_inst, by_ckchs) {
12322 struct ckch_inst *new_inst;
12323
12324 /* it takes a lot of CPU to creates SSL_CTXs, so we yield every 10 CKCH instances */
12325 if (y % 10 == 0) {
12326
12327 *lua_ckchi = ckchi;
12328
12329 task_wakeup(hlua->task, TASK_WOKEN_MSG);
12330 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_ckch_commit_yield, TICK_ETERNITY, 0));
12331 }
12332
12333 if (ckch_inst_rebuild(new_ckchs, ckchi, &new_inst, &err))
12334 goto error;
12335
12336 /* link the new ckch_inst to the duplicate */
12337 LIST_APPEND(&new_ckchs->ckch_inst, &new_inst->by_ckchs);
12338 y++;
12339 }
12340
12341 /* The generation is finished, we can insert everything */
12342 ckch_store_replace(old_ckchs, new_ckchs);
12343
12344 lua_pop(L, 2); /* pop the lua_ckchs and ckchi */
12345
12346 HA_SPIN_UNLOCK(CKCH_LOCK, &ckch_lock);
12347
12348 return 0;
12349
12350error:
12351 ckch_store_free(new_ckchs);
12352 HA_SPIN_UNLOCK(CKCH_LOCK, &ckch_lock);
12353 WILL_LJMP(luaL_error(L, "%s", err));
12354 free(err);
12355
12356 return 0;
12357}
12358
12359/*
12360 * Replace a ckch_store <filename> in the ckchs_tree with a ckch_store created
12361 * from the table in parameter.
12362 *
12363 * This is equivalent to "set ssl cert" + "commit ssl cert" over the CLI, which
12364 * means it does not need to have a transaction since everything is done in the
12365 * same function.
12366 *
12367 * CertCache.set{filename="", crt="", key="", sctl="", ocsp="", issuer=""}
12368 *
12369 */
12370__LJMP static int hlua_ckch_set(lua_State *L)
12371{
12372 struct hlua *hlua;
12373 struct ckch_inst **lua_ckchi;
12374 struct ckch_store **lua_ckchs;
12375 struct ckch_store *old_ckchs = NULL;
12376 struct ckch_store *new_ckchs = NULL;
12377 int errcode = 0;
12378 char *err = NULL;
12379 struct cert_exts *cert_ext = NULL;
12380 char *filename;
William Lallemand52ddd992022-11-22 11:51:53 +010012381 struct ckch_data *data;
William Lallemand30fcca12022-03-30 12:03:12 +020012382 int ret;
12383
12384 if (lua_type(L, -1) != LUA_TTABLE)
12385 WILL_LJMP(luaL_error(L, "'CertCache.set' needs a table as argument"));
12386
12387 hlua = hlua_gethlua(L);
12388
12389 /* FIXME: this should not return an error but should come back later */
12390 if (HA_SPIN_TRYLOCK(CKCH_LOCK, &ckch_lock))
12391 WILL_LJMP(luaL_error(L, "CertCache already under lock"));
12392
12393 ret = lua_getfield(L, -1, "filename");
12394 if (ret != LUA_TSTRING) {
Thierry Fournier70e38e92022-09-19 09:01:53 +020012395 memprintf(&err, "%sNo filename specified!", err ? err : "");
William Lallemand30fcca12022-03-30 12:03:12 +020012396 errcode |= ERR_ALERT | ERR_FATAL;
12397 goto end;
12398 }
12399 filename = (char *)lua_tostring(L, -1);
12400
12401
12402 /* look for the filename in the tree */
12403 old_ckchs = ckchs_lookup(filename);
12404 if (!old_ckchs) {
Thierry Fournier70e38e92022-09-19 09:01:53 +020012405 memprintf(&err, "%sCan't replace a certificate which is not referenced by the configuration!", err ? err : "");
William Lallemand30fcca12022-03-30 12:03:12 +020012406 errcode |= ERR_ALERT | ERR_FATAL;
12407 goto end;
12408 }
12409 /* TODO: handle extra_files_noext */
12410
12411 new_ckchs = ckchs_dup(old_ckchs);
12412 if (!new_ckchs) {
Thierry Fournier70e38e92022-09-19 09:01:53 +020012413 memprintf(&err, "%sCannot allocate memory!", err ? err : "");
William Lallemand30fcca12022-03-30 12:03:12 +020012414 errcode |= ERR_ALERT | ERR_FATAL;
12415 goto end;
12416 }
12417
William Lallemand52ddd992022-11-22 11:51:53 +010012418 data = new_ckchs->data;
William Lallemand30fcca12022-03-30 12:03:12 +020012419
12420 /* loop on the field in the table, which have the same name as the
12421 * possible extensions of files */
12422 lua_pushnil(L);
12423 while (lua_next(L, 1)) {
12424 int i;
12425 const char *field = lua_tostring(L, -2);
12426 char *payload = (char *)lua_tostring(L, -1);
12427
12428 if (!field || strcmp(field, "filename") == 0) {
12429 lua_pop(L, 1);
12430 continue;
12431 }
12432
12433 for (i = 0; field && cert_exts[i].ext != NULL; i++) {
12434 if (strcmp(field, cert_exts[i].ext) == 0) {
12435 cert_ext = &cert_exts[i];
12436 break;
12437 }
12438 }
12439
12440 /* this is the default type, the field is not supported */
12441 if (cert_ext == NULL) {
Thierry Fournier70e38e92022-09-19 09:01:53 +020012442 memprintf(&err, "%sUnsupported field '%s'", err ? err : "", field);
William Lallemand30fcca12022-03-30 12:03:12 +020012443 errcode |= ERR_ALERT | ERR_FATAL;
12444 goto end;
12445 }
12446
12447 /* appply the change on the duplicate */
William Lallemand52ddd992022-11-22 11:51:53 +010012448 if (cert_ext->load(filename, payload, data, &err) != 0) {
Thierry Fournier70e38e92022-09-19 09:01:53 +020012449 memprintf(&err, "%sCan't load the payload for '%s'", err ? err : "", cert_ext->ext);
William Lallemand30fcca12022-03-30 12:03:12 +020012450 errcode |= ERR_ALERT | ERR_FATAL;
12451 goto end;
12452 }
12453 lua_pop(L, 1);
12454 }
12455
12456 /* store the pointers on the lua stack */
12457 lua_ckchs = lua_newuserdata(L, sizeof(struct ckch_store *) * 2);
12458 lua_ckchs[0] = old_ckchs;
12459 lua_ckchs[1] = new_ckchs;
12460 lua_ckchi = lua_newuserdata(L, sizeof(struct ckch_inst *));
12461 *lua_ckchi = NULL;
12462
12463 task_wakeup(hlua->task, TASK_WOKEN_MSG);
12464 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_ckch_commit_yield, TICK_ETERNITY, 0));
12465
12466end:
12467 HA_SPIN_UNLOCK(CKCH_LOCK, &ckch_lock);
12468
12469 if (errcode & ERR_CODE) {
12470 ckch_store_free(new_ckchs);
12471 WILL_LJMP(luaL_error(L, "%s", err));
12472 }
12473 free(err);
12474
12475 return 0;
12476}
12477
William Lallemand52139182022-03-30 15:05:42 +020012478#else
12479
12480__LJMP static int hlua_ckch_set(lua_State *L)
12481{
12482 WILL_LJMP(luaL_error(L, "'CertCache.set' needs an HAProxy built with OpenSSL"));
12483
12484 return 0;
12485}
12486#endif /* ! USE_OPENSSL */
12487
12488
12489
Thierry FOURNIERbabae282015-09-17 11:36:37 +020012490/* This function can fail with an abort() due to an Lua critical error.
12491 * We are in the initialisation process of HAProxy, this abort() is
12492 * tolerated.
12493 */
Thierry Fournierb8cef172020-11-28 15:37:17 +010012494int hlua_post_init_state(lua_State *L)
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010012495{
12496 struct hlua_init_function *init;
12497 const char *msg;
12498 enum hlua_exec ret;
Thierry Fournierfd107a22016-02-19 19:57:23 +010012499 const char *error;
Thierry Fournier670db242020-11-28 10:49:59 +010012500 const char *kind;
12501 const char *trace;
12502 int return_status = 1;
12503#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM >= 504
12504 int nres;
12505#endif
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010012506
Willy Tarreaucdb53462020-12-02 12:12:00 +010012507 /* disable memory limit checks if limit is not set */
12508 if (!hlua_global_allocator.limit)
12509 hlua_global_allocator.limit = ~hlua_global_allocator.limit;
12510
Ilya Shipitsin856aabc2020-04-16 23:51:34 +050012511 /* Call post initialisation function in safe environment. */
Thierry Fournier3c539322020-11-28 16:05:05 +010012512 if (setjmp(safe_ljmp_env) != 0) {
12513 lua_atpanic(L, hlua_panic_safe);
Thierry Fournierb8cef172020-11-28 15:37:17 +010012514 if (lua_type(L, -1) == LUA_TSTRING)
12515 error = lua_tostring(L, -1);
Thierry Fournier3d4a6752016-02-19 20:53:30 +010012516 else
12517 error = "critical error";
12518 fprintf(stderr, "Lua post-init: %s.\n", error);
12519 exit(1);
Thierry Fournier3c539322020-11-28 16:05:05 +010012520 } else {
12521 lua_atpanic(L, hlua_panic_ljmp);
Thierry Fournier3d4a6752016-02-19 20:53:30 +010012522 }
Frédéric Lécaille54f2bcf2018-08-29 13:46:24 +020012523
Thierry Fournierc7492592020-11-28 23:57:24 +010012524 list_for_each_entry(init, &hlua_init_functions[hlua_state_id], l) {
Aurelien DARRAGON4fdf8b52023-03-20 17:22:37 +010012525 hlua_pushref(L, init->function_ref);
Aurelien DARRAGON16d047b2023-03-20 16:29:55 +010012526 /* function ref should be released right away since it was pushed
12527 * on the stack and will not be used anymore
12528 */
12529 hlua_unref(L, init->function_ref);
Thierry Fournier670db242020-11-28 10:49:59 +010012530
12531#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM >= 504
Thierry Fournierb8cef172020-11-28 15:37:17 +010012532 ret = lua_resume(L, L, 0, &nres);
Thierry Fournier670db242020-11-28 10:49:59 +010012533#else
Thierry Fournierb8cef172020-11-28 15:37:17 +010012534 ret = lua_resume(L, L, 0);
Thierry Fournier670db242020-11-28 10:49:59 +010012535#endif
12536 kind = NULL;
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010012537 switch (ret) {
Thierry Fournier670db242020-11-28 10:49:59 +010012538
12539 case LUA_OK:
Thierry Fournierb8cef172020-11-28 15:37:17 +010012540 lua_pop(L, -1);
Thierry Fournier13d08b72020-11-28 11:02:58 +010012541 break;
Thierry Fournier670db242020-11-28 10:49:59 +010012542
12543 case LUA_ERRERR:
12544 kind = "message handler error";
Willy Tarreau14de3952022-11-14 07:08:28 +010012545 __fallthrough;
Thierry Fournier670db242020-11-28 10:49:59 +010012546 case LUA_ERRRUN:
12547 if (!kind)
12548 kind = "runtime error";
Thierry Fournierb8cef172020-11-28 15:37:17 +010012549 msg = lua_tostring(L, -1);
12550 lua_settop(L, 0); /* Empty the stack. */
12551 lua_pop(L, 1);
Christopher Fauletd09cc512021-03-24 14:48:45 +010012552 trace = hlua_traceback(L, ", ");
Thierry Fournier670db242020-11-28 10:49:59 +010012553 if (msg)
12554 ha_alert("Lua init: %s: '%s' from %s\n", kind, msg, trace);
12555 else
12556 ha_alert("Lua init: unknown %s from %s\n", kind, trace);
12557 return_status = 0;
12558 break;
12559
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010012560 default:
Thierry Fournier670db242020-11-28 10:49:59 +010012561 /* Unknown error */
12562 kind = "Unknown error";
Willy Tarreau14de3952022-11-14 07:08:28 +010012563 __fallthrough;
Thierry Fournier670db242020-11-28 10:49:59 +010012564 case LUA_YIELD:
12565 /* yield is not configured at this step, this state doesn't happen */
12566 if (!kind)
12567 kind = "yield not allowed";
Willy Tarreau14de3952022-11-14 07:08:28 +010012568 __fallthrough;
Thierry Fournier670db242020-11-28 10:49:59 +010012569 case LUA_ERRMEM:
12570 if (!kind)
12571 kind = "out of memory error";
Thierry Fournierb8cef172020-11-28 15:37:17 +010012572 lua_settop(L, 0);
12573 lua_pop(L, 1);
Christopher Fauletd09cc512021-03-24 14:48:45 +010012574 trace = hlua_traceback(L, ", ");
Thierry Fournier670db242020-11-28 10:49:59 +010012575 ha_alert("Lua init: %s: %s\n", kind, trace);
12576 return_status = 0;
12577 break;
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010012578 }
Thierry Fournier670db242020-11-28 10:49:59 +010012579 if (!return_status)
12580 break;
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010012581 }
Thierry Fournier3c539322020-11-28 16:05:05 +010012582
12583 lua_atpanic(L, hlua_panic_safe);
Thierry Fournier670db242020-11-28 10:49:59 +010012584 return return_status;
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010012585}
12586
Thierry Fournierb8cef172020-11-28 15:37:17 +010012587int hlua_post_init()
12588{
Thierry Fournier59f11be2020-11-29 00:37:41 +010012589 int ret;
12590 int i;
12591 int errors;
12592 char *err = NULL;
12593 struct hlua_function *fcn;
Christopher Faulet69c581a2021-05-31 08:54:04 +020012594 struct hlua_reg_filter *reg_flt;
Thierry Fournier59f11be2020-11-29 00:37:41 +010012595
Willy Tarreaub1310492021-08-30 09:35:18 +020012596#if defined(USE_OPENSSL)
Thierry Fournierb8cef172020-11-28 15:37:17 +010012597 /* Initialize SSL server. */
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010012598 if (socket_ssl->xprt->prepare_srv) {
Thierry Fournierb8cef172020-11-28 15:37:17 +010012599 int saved_used_backed = global.ssl_used_backend;
12600 // don't affect maxconn automatic computation
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010012601 socket_ssl->xprt->prepare_srv(socket_ssl);
Thierry Fournierb8cef172020-11-28 15:37:17 +010012602 global.ssl_used_backend = saved_used_backed;
12603 }
12604#endif
12605
Thierry Fournierc7492592020-11-28 23:57:24 +010012606 /* Perform post init of common thread */
12607 hlua_state_id = 0;
Willy Tarreau43ab05b2021-09-28 09:43:11 +020012608 ha_set_thread(&ha_thread_info[0]);
Thierry Fournier59f11be2020-11-29 00:37:41 +010012609 ret = hlua_post_init_state(hlua_states[hlua_state_id]);
12610 if (ret == 0)
12611 return 0;
12612
12613 /* init remaining lua states and load files */
12614 for (hlua_state_id = 2; hlua_state_id < global.nbthread + 1; hlua_state_id++) {
12615
12616 /* set thread context */
Willy Tarreau43ab05b2021-09-28 09:43:11 +020012617 ha_set_thread(&ha_thread_info[hlua_state_id - 1]);
Thierry Fournier59f11be2020-11-29 00:37:41 +010012618
12619 /* Init lua state */
12620 hlua_states[hlua_state_id] = hlua_init_state(hlua_state_id);
12621
12622 /* Load lua files */
12623 for (i = 0; per_thread_load && per_thread_load[i]; i++) {
12624 ret = hlua_load_state(per_thread_load[i], hlua_states[hlua_state_id], &err);
12625 if (ret != 0) {
12626 ha_alert("Lua init: %s\n", err);
12627 return 0;
12628 }
12629 }
12630 }
12631
12632 /* Reset thread context */
Willy Tarreau43ab05b2021-09-28 09:43:11 +020012633 ha_set_thread(NULL);
Thierry Fournier59f11be2020-11-29 00:37:41 +010012634
12635 /* Execute post init for all states */
12636 for (hlua_state_id = 1; hlua_state_id < global.nbthread + 1; hlua_state_id++) {
12637
12638 /* set thread context */
Willy Tarreau43ab05b2021-09-28 09:43:11 +020012639 ha_set_thread(&ha_thread_info[hlua_state_id - 1]);
Thierry Fournier59f11be2020-11-29 00:37:41 +010012640
12641 /* run post init */
12642 ret = hlua_post_init_state(hlua_states[hlua_state_id]);
12643 if (ret == 0)
12644 return 0;
12645 }
12646
12647 /* Reset thread context */
Willy Tarreau43ab05b2021-09-28 09:43:11 +020012648 ha_set_thread(NULL);
Thierry Fournier59f11be2020-11-29 00:37:41 +010012649
12650 /* control functions registering. Each function must have:
12651 * - only the function_ref[0] set positive and all other to -1
12652 * - only the function_ref[0] set to -1 and all other positive
12653 * This ensure a same reference is not used both in shared
12654 * lua state and thread dedicated lua state. Note: is the case
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +050012655 * reach, the shared state is priority, but the bug will be
Thierry Fournier59f11be2020-11-29 00:37:41 +010012656 * complicated to found for the end user.
12657 */
12658 errors = 0;
12659 list_for_each_entry(fcn, &referenced_functions, l) {
12660 ret = 0;
12661 for (i = 1; i < global.nbthread + 1; i++) {
12662 if (fcn->function_ref[i] == -1)
12663 ret--;
12664 else
12665 ret++;
12666 }
12667 if (abs(ret) != global.nbthread) {
12668 ha_alert("Lua function '%s' is not referenced in all thread. "
12669 "Expect function in all thread or in none thread.\n", fcn->name);
12670 errors++;
12671 continue;
12672 }
12673
12674 if ((fcn->function_ref[0] == -1) == (ret < 0)) {
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +050012675 ha_alert("Lua function '%s' is referenced both ins shared Lua context (through lua-load) "
12676 "and per-thread Lua context (through lua-load-per-thread). these two context "
Thierry Fournier59f11be2020-11-29 00:37:41 +010012677 "exclusive.\n", fcn->name);
12678 errors++;
12679 }
12680 }
12681
Christopher Faulet69c581a2021-05-31 08:54:04 +020012682 /* Do the same with registered filters */
12683 list_for_each_entry(reg_flt, &referenced_filters, l) {
12684 ret = 0;
12685 for (i = 1; i < global.nbthread + 1; i++) {
12686 if (reg_flt->flt_ref[i] == -1)
12687 ret--;
12688 else
12689 ret++;
12690 }
12691 if (abs(ret) != global.nbthread) {
12692 ha_alert("Lua filter '%s' is not referenced in all thread. "
12693 "Expect function in all thread or in none thread.\n", reg_flt->name);
12694 errors++;
12695 continue;
12696 }
12697
12698 if ((reg_flt->flt_ref[0] == -1) == (ret < 0)) {
12699 ha_alert("Lua filter '%s' is referenced both ins shared Lua context (through lua-load) "
12700 "and per-thread Lua context (through lua-load-per-thread). these two context "
12701 "exclusive.\n", fcn->name);
12702 errors++;
12703 }
12704 }
12705
12706
Thierry Fournier59f11be2020-11-29 00:37:41 +010012707 if (errors > 0)
12708 return 0;
12709
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +050012710 /* after this point, this global will no longer be used, so set to
Thierry Fournier59f11be2020-11-29 00:37:41 +010012711 * -1 in order to have probably a segfault if someone use it
12712 */
12713 hlua_state_id = -1;
12714
12715 return 1;
Thierry Fournierb8cef172020-11-28 15:37:17 +010012716}
12717
Willy Tarreau32f61e22015-03-18 17:54:59 +010012718/* The memory allocator used by the Lua stack. <ud> is a pointer to the
12719 * allocator's context. <ptr> is the pointer to alloc/free/realloc. <osize>
12720 * is the previously allocated size or the kind of object in case of a new
Willy Tarreaud36c7fa2020-12-02 12:26:29 +010012721 * allocation. <nsize> is the requested new size. A new allocation is
12722 * indicated by <ptr> being NULL. A free is indicated by <nsize> being
Willy Tarreaucdb53462020-12-02 12:12:00 +010012723 * zero. This one verifies that the limits are respected but is optimized
12724 * for the fast case where limits are not used, hence stats are not updated.
Willy Tarreaua5efdff2021-10-22 16:00:02 +020012725 *
12726 * Warning: while this API ressembles glibc's realloc() a lot, glibc surpasses
12727 * POSIX by making realloc(ptr,0) an effective free(), but others do not do
12728 * that and will simply allocate zero as if it were the result of malloc(0),
12729 * so mapping this onto realloc() will lead to memory leaks on non-glibc
12730 * systems.
Willy Tarreau32f61e22015-03-18 17:54:59 +010012731 */
12732static void *hlua_alloc(void *ud, void *ptr, size_t osize, size_t nsize)
12733{
12734 struct hlua_mem_allocator *zone = ud;
Willy Tarreaucdb53462020-12-02 12:12:00 +010012735 size_t limit, old, new;
12736
12737 /* a limit of ~0 means unlimited and boot complete, so there's no need
12738 * for accounting anymore.
12739 */
Willy Tarreaua5efdff2021-10-22 16:00:02 +020012740 if (likely(~zone->limit == 0)) {
12741 if (!nsize)
12742 ha_free(&ptr);
12743 else
12744 ptr = realloc(ptr, nsize);
12745 return ptr;
12746 }
Willy Tarreau32f61e22015-03-18 17:54:59 +010012747
Willy Tarreaud36c7fa2020-12-02 12:26:29 +010012748 if (!ptr)
12749 osize = 0;
Willy Tarreau32f61e22015-03-18 17:54:59 +010012750
Willy Tarreaucdb53462020-12-02 12:12:00 +010012751 /* enforce strict limits across all threads */
12752 limit = zone->limit;
12753 old = _HA_ATOMIC_LOAD(&zone->allocated);
12754 do {
12755 new = old + nsize - osize;
12756 if (unlikely(nsize && limit && new > limit))
12757 return NULL;
12758 } while (!_HA_ATOMIC_CAS(&zone->allocated, &old, new));
Willy Tarreau32f61e22015-03-18 17:54:59 +010012759
Willy Tarreaua5efdff2021-10-22 16:00:02 +020012760 if (!nsize)
12761 ha_free(&ptr);
12762 else
12763 ptr = realloc(ptr, nsize);
Willy Tarreaucdb53462020-12-02 12:12:00 +010012764
12765 if (unlikely(!ptr && nsize)) // failed
12766 _HA_ATOMIC_SUB(&zone->allocated, nsize - osize);
12767
12768 __ha_barrier_atomic_store();
Willy Tarreau32f61e22015-03-18 17:54:59 +010012769 return ptr;
12770}
12771
Thierry Fournierecb83c22020-11-28 15:49:44 +010012772/* This function can fail with an abort() due to a Lua critical error.
Thierry FOURNIERbabae282015-09-17 11:36:37 +020012773 * We are in the initialisation process of HAProxy, this abort() is
12774 * tolerated.
12775 */
Thierry Fournierecb83c22020-11-28 15:49:44 +010012776lua_State *hlua_init_state(int thread_num)
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +010012777{
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010012778 int i;
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010012779 int idx;
12780 struct sample_fetch *sf;
Thierry FOURNIER594afe72015-03-10 23:58:30 +010012781 struct sample_conv *sc;
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010012782 char *p;
Thierry Fournierfd107a22016-02-19 19:57:23 +010012783 const char *error_msg;
Thierry Fournier4234dbd2020-11-28 13:18:23 +010012784 void **context;
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012785 lua_State *L;
Thierry Fournier59f11be2020-11-29 00:37:41 +010012786 struct prepend_path *pp;
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010012787
Thierry FOURNIER380d0932015-01-23 14:27:52 +010012788 /* Init main lua stack. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012789 L = lua_newstate(hlua_alloc, &hlua_global_allocator);
Thierry FOURNIER380d0932015-01-23 14:27:52 +010012790
Thierry Fournier4234dbd2020-11-28 13:18:23 +010012791 /* Initialise Lua context to NULL */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012792 context = lua_getextraspace(L);
Thierry Fournier4234dbd2020-11-28 13:18:23 +010012793 *context = NULL;
12794
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -080012795 /* From this point, until the end of the initialisation function,
Thierry FOURNIERbabae282015-09-17 11:36:37 +020012796 * the Lua function can fail with an abort. We are in the initialisation
12797 * process of HAProxy, this abort() is tolerated.
12798 */
12799
Thierry Fournier3c539322020-11-28 16:05:05 +010012800 /* Call post initialisation function in safe environment. */
12801 if (setjmp(safe_ljmp_env) != 0) {
12802 lua_atpanic(L, hlua_panic_safe);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012803 if (lua_type(L, -1) == LUA_TSTRING)
12804 error_msg = lua_tostring(L, -1);
Thierry Fournier2f05cc62020-11-28 16:08:02 +010012805 else
12806 error_msg = "critical error";
12807 fprintf(stderr, "Lua init: %s.\n", error_msg);
12808 exit(1);
Thierry Fournier3c539322020-11-28 16:05:05 +010012809 } else {
12810 lua_atpanic(L, hlua_panic_ljmp);
Thierry Fournier2f05cc62020-11-28 16:08:02 +010012811 }
12812
Thierry FOURNIER380d0932015-01-23 14:27:52 +010012813 /* Initialise lua. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012814 luaL_openlibs(L);
Tim Duesterhus541fe1e2020-01-12 13:55:41 +010012815#define HLUA_PREPEND_PATH_TOSTRING1(x) #x
12816#define HLUA_PREPEND_PATH_TOSTRING(x) HLUA_PREPEND_PATH_TOSTRING1(x)
12817#ifdef HLUA_PREPEND_PATH
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012818 hlua_prepend_path(L, "path", HLUA_PREPEND_PATH_TOSTRING(HLUA_PREPEND_PATH));
Tim Duesterhus541fe1e2020-01-12 13:55:41 +010012819#endif
12820#ifdef HLUA_PREPEND_CPATH
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012821 hlua_prepend_path(L, "cpath", HLUA_PREPEND_PATH_TOSTRING(HLUA_PREPEND_CPATH));
Tim Duesterhus541fe1e2020-01-12 13:55:41 +010012822#endif
12823#undef HLUA_PREPEND_PATH_TOSTRING
12824#undef HLUA_PREPEND_PATH_TOSTRING1
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010012825
Thierry Fournier59f11be2020-11-29 00:37:41 +010012826 /* Apply configured prepend path */
12827 list_for_each_entry(pp, &prepend_path_list, l)
12828 hlua_prepend_path(L, pp->type, pp->path);
12829
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010012830 /*
12831 *
12832 * Create "core" object.
12833 *
12834 */
12835
Thierry FOURNIERa2d8c652015-03-11 17:29:39 +010012836 /* This table entry is the object "core" base. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012837 lua_newtable(L);
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010012838
Thierry Fournierecb83c22020-11-28 15:49:44 +010012839 /* set the thread id */
12840 hlua_class_const_int(L, "thread", thread_num);
12841
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010012842 /* Push the loglevel constants. */
Willy Tarreau80f5fae2015-02-27 16:38:20 +010012843 for (i = 0; i < NB_LOG_LEVELS; i++)
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012844 hlua_class_const_int(L, log_levels[i], i);
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010012845
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010012846 /* Register special functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012847 hlua_class_function(L, "register_init", hlua_register_init);
12848 hlua_class_function(L, "register_task", hlua_register_task);
12849 hlua_class_function(L, "register_fetches", hlua_register_fetches);
12850 hlua_class_function(L, "register_converters", hlua_register_converters);
12851 hlua_class_function(L, "register_action", hlua_register_action);
12852 hlua_class_function(L, "register_service", hlua_register_service);
12853 hlua_class_function(L, "register_cli", hlua_register_cli);
Christopher Faulet69c581a2021-05-31 08:54:04 +020012854 hlua_class_function(L, "register_filter", hlua_register_filter);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012855 hlua_class_function(L, "yield", hlua_yield);
12856 hlua_class_function(L, "set_nice", hlua_set_nice);
12857 hlua_class_function(L, "sleep", hlua_sleep);
12858 hlua_class_function(L, "msleep", hlua_msleep);
12859 hlua_class_function(L, "add_acl", hlua_add_acl);
12860 hlua_class_function(L, "del_acl", hlua_del_acl);
12861 hlua_class_function(L, "set_map", hlua_set_map);
12862 hlua_class_function(L, "del_map", hlua_del_map);
12863 hlua_class_function(L, "tcp", hlua_socket_new);
William Lallemand3956c4e2021-09-21 16:25:15 +020012864 hlua_class_function(L, "httpclient", hlua_httpclient_new);
Aurelien DARRAGONc84899c2023-02-20 18:18:59 +010012865 hlua_class_function(L, "event_sub", hlua_event_global_sub);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012866 hlua_class_function(L, "log", hlua_log);
12867 hlua_class_function(L, "Debug", hlua_log_debug);
12868 hlua_class_function(L, "Info", hlua_log_info);
12869 hlua_class_function(L, "Warning", hlua_log_warning);
12870 hlua_class_function(L, "Alert", hlua_log_alert);
12871 hlua_class_function(L, "done", hlua_done);
12872 hlua_fcn_reg_core_fcn(L);
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010012873
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012874 lua_setglobal(L, "core");
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010012875
12876 /*
12877 *
Christopher Faulet0f3c8902020-01-31 18:57:12 +010012878 * Create "act" object.
12879 *
12880 */
12881
12882 /* This table entry is the object "act" base. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012883 lua_newtable(L);
Christopher Faulet0f3c8902020-01-31 18:57:12 +010012884
12885 /* push action return constants */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012886 hlua_class_const_int(L, "CONTINUE", ACT_RET_CONT);
12887 hlua_class_const_int(L, "STOP", ACT_RET_STOP);
12888 hlua_class_const_int(L, "YIELD", ACT_RET_YIELD);
12889 hlua_class_const_int(L, "ERROR", ACT_RET_ERR);
12890 hlua_class_const_int(L, "DONE", ACT_RET_DONE);
12891 hlua_class_const_int(L, "DENY", ACT_RET_DENY);
12892 hlua_class_const_int(L, "ABORT", ACT_RET_ABRT);
12893 hlua_class_const_int(L, "INVALID", ACT_RET_INV);
Christopher Faulet0f3c8902020-01-31 18:57:12 +010012894
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012895 hlua_class_function(L, "wake_time", hlua_set_wake_time);
Christopher Faulet2c2c2e32020-01-31 19:07:52 +010012896
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012897 lua_setglobal(L, "act");
Christopher Faulet0f3c8902020-01-31 18:57:12 +010012898
12899 /*
12900 *
Christopher Faulet69c581a2021-05-31 08:54:04 +020012901 * Create "Filter" object.
12902 *
12903 */
12904
12905 /* This table entry is the object "filter" base. */
12906 lua_newtable(L);
12907
12908 /* push flags and constants */
12909 hlua_class_const_int(L, "CONTINUE", 1);
12910 hlua_class_const_int(L, "WAIT", 0);
12911 hlua_class_const_int(L, "ERROR", -1);
12912
12913 hlua_class_const_int(L, "FLT_CFG_FL_HTX", FLT_CFG_FL_HTX);
12914
Christopher Fauletc404f112020-02-26 15:03:09 +010012915 hlua_class_function(L, "wake_time", hlua_set_wake_time);
12916 hlua_class_function(L, "register_data_filter", hlua_register_data_filter);
12917 hlua_class_function(L, "unregister_data_filter", hlua_unregister_data_filter);
12918
Christopher Faulet69c581a2021-05-31 08:54:04 +020012919 lua_setglobal(L, "filter");
12920
12921 /*
12922 *
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012923 * Register class Map
12924 *
12925 */
12926
12927 /* This table entry is the object "Map" base. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012928 lua_newtable(L);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012929
12930 /* register pattern types. */
12931 for (i=0; i<PAT_MATCH_NUM; i++)
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012932 hlua_class_const_int(L, pat_match_names[i], i);
Thierry FOURNIER4dc71972017-01-28 08:33:08 +010012933 for (i=0; i<PAT_MATCH_NUM; i++) {
Willy Tarreau843b7cb2018-07-13 10:54:26 +020012934 snprintf(trash.area, trash.size, "_%s", pat_match_names[i]);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012935 hlua_class_const_int(L, trash.area, i);
Thierry FOURNIER4dc71972017-01-28 08:33:08 +010012936 }
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012937
12938 /* register constructor. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012939 hlua_class_function(L, "new", hlua_map_new);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012940
12941 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012942 lua_newtable(L);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012943
Ilya Shipitsind4259502020-04-08 01:07:56 +050012944 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012945 lua_pushstring(L, "__index");
12946 lua_newtable(L);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012947
12948 /* Register . */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012949 hlua_class_function(L, "lookup", hlua_map_lookup);
12950 hlua_class_function(L, "slookup", hlua_map_slookup);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012951
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012952 lua_rawset(L, -3);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012953
Thierry Fournier45e78d72016-02-19 18:34:46 +010012954 /* Register previous table in the registry with reference and named entry.
12955 * The function hlua_register_metatable() pops the stack, so we
12956 * previously create a copy of the table.
12957 */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012958 lua_pushvalue(L, -1); /* Copy the -1 entry and push it on the stack. */
12959 class_map_ref = hlua_register_metatable(L, CLASS_MAP);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012960
12961 /* Assign the metatable to the mai Map object. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012962 lua_setmetatable(L, -2);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012963
12964 /* Set a name to the table. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012965 lua_setglobal(L, "Map");
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012966
12967 /*
12968 *
William Lallemand30fcca12022-03-30 12:03:12 +020012969 * Register "CertCache" class
12970 *
12971 */
12972
12973 /* Create and fill the metatable. */
12974 lua_newtable(L);
12975 /* Register */
12976 hlua_class_function(L, "set", hlua_ckch_set);
12977 lua_setglobal(L, CLASS_CERTCACHE); /* Create global object called Regex */
12978
12979 /*
12980 *
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010012981 * Register class Channel
12982 *
12983 */
12984
12985 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012986 lua_newtable(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010012987
Ilya Shipitsind4259502020-04-08 01:07:56 +050012988 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012989 lua_pushstring(L, "__index");
12990 lua_newtable(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010012991
12992 /* Register . */
Christopher Faulet6a79fc12021-08-06 16:02:36 +020012993 hlua_class_function(L, "data", hlua_channel_get_data);
12994 hlua_class_function(L, "line", hlua_channel_get_line);
12995 hlua_class_function(L, "set", hlua_channel_set_data);
12996 hlua_class_function(L, "remove", hlua_channel_del_data);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012997 hlua_class_function(L, "append", hlua_channel_append);
Christopher Faulet6a79fc12021-08-06 16:02:36 +020012998 hlua_class_function(L, "prepend", hlua_channel_prepend);
12999 hlua_class_function(L, "insert", hlua_channel_insert_data);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013000 hlua_class_function(L, "send", hlua_channel_send);
13001 hlua_class_function(L, "forward", hlua_channel_forward);
Christopher Faulet6a79fc12021-08-06 16:02:36 +020013002 hlua_class_function(L, "input", hlua_channel_get_in_len);
13003 hlua_class_function(L, "output", hlua_channel_get_out_len);
13004 hlua_class_function(L, "may_recv", hlua_channel_may_recv);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013005 hlua_class_function(L, "is_full", hlua_channel_is_full);
13006 hlua_class_function(L, "is_resp", hlua_channel_is_resp);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010013007
Christopher Faulet6a79fc12021-08-06 16:02:36 +020013008 /* Deprecated API */
13009 hlua_class_function(L, "get", hlua_channel_get);
13010 hlua_class_function(L, "dup", hlua_channel_dup);
13011 hlua_class_function(L, "getline", hlua_channel_getline);
13012 hlua_class_function(L, "get_in_len", hlua_channel_get_in_len);
13013 hlua_class_function(L, "get_out_len", hlua_channel_get_out_len);
13014
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013015 lua_rawset(L, -3);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010013016
13017 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013018 class_channel_ref = hlua_register_metatable(L, CLASS_CHANNEL);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010013019
13020 /*
13021 *
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010013022 * Register class Fetches
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010013023 *
13024 */
13025
13026 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013027 lua_newtable(L);
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010013028
Ilya Shipitsind4259502020-04-08 01:07:56 +050013029 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013030 lua_pushstring(L, "__index");
13031 lua_newtable(L);
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010013032
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010013033 /* Browse existing fetches and create the associated
13034 * object method.
13035 */
13036 sf = NULL;
13037 while ((sf = sample_fetch_getnext(sf, &idx)) != NULL) {
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010013038 /* gL.Tua doesn't support '.' and '-' in the function names, replace it
13039 * by an underscore.
13040 */
Willy Tarreau5ef96562021-08-26 16:48:53 +020013041 strlcpy2(trash.area, sf->kw, trash.size);
Willy Tarreau843b7cb2018-07-13 10:54:26 +020013042 for (p = trash.area; *p; p++)
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010013043 if (*p == '.' || *p == '-' || *p == '+')
13044 *p = '_';
13045
13046 /* Register the function. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013047 lua_pushstring(L, trash.area);
13048 lua_pushlightuserdata(L, sf);
13049 lua_pushcclosure(L, hlua_run_sample_fetch, 1);
13050 lua_rawset(L, -3);
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010013051 }
13052
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013053 lua_rawset(L, -3);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010013054
13055 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013056 class_fetches_ref = hlua_register_metatable(L, CLASS_FETCHES);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010013057
13058 /*
13059 *
Thierry FOURNIER594afe72015-03-10 23:58:30 +010013060 * Register class Converters
13061 *
13062 */
13063
13064 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013065 lua_newtable(L);
Thierry FOURNIER594afe72015-03-10 23:58:30 +010013066
13067 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013068 lua_pushstring(L, "__index");
13069 lua_newtable(L);
Thierry FOURNIER594afe72015-03-10 23:58:30 +010013070
13071 /* Browse existing converters and create the associated
13072 * object method.
13073 */
13074 sc = NULL;
13075 while ((sc = sample_conv_getnext(sc, &idx)) != NULL) {
Thierry FOURNIER594afe72015-03-10 23:58:30 +010013076 /* gL.Tua doesn't support '.' and '-' in the function names, replace it
13077 * by an underscore.
13078 */
Willy Tarreau5ef96562021-08-26 16:48:53 +020013079 strlcpy2(trash.area, sc->kw, trash.size);
Willy Tarreau843b7cb2018-07-13 10:54:26 +020013080 for (p = trash.area; *p; p++)
Thierry FOURNIER594afe72015-03-10 23:58:30 +010013081 if (*p == '.' || *p == '-' || *p == '+')
13082 *p = '_';
13083
13084 /* Register the function. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013085 lua_pushstring(L, trash.area);
13086 lua_pushlightuserdata(L, sc);
13087 lua_pushcclosure(L, hlua_run_sample_conv, 1);
13088 lua_rawset(L, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +010013089 }
13090
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013091 lua_rawset(L, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +010013092
13093 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013094 class_converters_ref = hlua_register_metatable(L, CLASS_CONVERTERS);
Thierry FOURNIER594afe72015-03-10 23:58:30 +010013095
13096 /*
13097 *
Thierry FOURNIER08504f42015-03-16 14:17:08 +010013098 * Register class HTTP
13099 *
13100 */
13101
13102 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013103 lua_newtable(L);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010013104
Ilya Shipitsind4259502020-04-08 01:07:56 +050013105 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013106 lua_pushstring(L, "__index");
13107 lua_newtable(L);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010013108
13109 /* Register Lua functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013110 hlua_class_function(L, "req_get_headers",hlua_http_req_get_headers);
13111 hlua_class_function(L, "req_del_header", hlua_http_req_del_hdr);
13112 hlua_class_function(L, "req_rep_header", hlua_http_req_rep_hdr);
13113 hlua_class_function(L, "req_rep_value", hlua_http_req_rep_val);
13114 hlua_class_function(L, "req_add_header", hlua_http_req_add_hdr);
13115 hlua_class_function(L, "req_set_header", hlua_http_req_set_hdr);
13116 hlua_class_function(L, "req_set_method", hlua_http_req_set_meth);
13117 hlua_class_function(L, "req_set_path", hlua_http_req_set_path);
13118 hlua_class_function(L, "req_set_query", hlua_http_req_set_query);
13119 hlua_class_function(L, "req_set_uri", hlua_http_req_set_uri);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010013120
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013121 hlua_class_function(L, "res_get_headers",hlua_http_res_get_headers);
13122 hlua_class_function(L, "res_del_header", hlua_http_res_del_hdr);
13123 hlua_class_function(L, "res_rep_header", hlua_http_res_rep_hdr);
13124 hlua_class_function(L, "res_rep_value", hlua_http_res_rep_val);
13125 hlua_class_function(L, "res_add_header", hlua_http_res_add_hdr);
13126 hlua_class_function(L, "res_set_header", hlua_http_res_set_hdr);
13127 hlua_class_function(L, "res_set_status", hlua_http_res_set_status);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010013128
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013129 lua_rawset(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010013130
13131 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013132 class_http_ref = hlua_register_metatable(L, CLASS_HTTP);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010013133
Christopher Fauletdf97ac42020-02-26 16:57:19 +010013134 /*
13135 *
13136 * Register class HTTPMessage
13137 *
13138 */
13139
13140 /* Create and fill the metatable. */
13141 lua_newtable(L);
13142
Ilya Shipitsinff0f2782021-08-22 22:18:07 +050013143 /* Create and fill the __index entry. */
Christopher Fauletdf97ac42020-02-26 16:57:19 +010013144 lua_pushstring(L, "__index");
13145 lua_newtable(L);
13146
13147 /* Register Lua functions. */
13148 hlua_class_function(L, "is_resp", hlua_http_msg_is_resp);
13149 hlua_class_function(L, "get_stline", hlua_http_msg_get_stline);
13150 hlua_class_function(L, "get_headers", hlua_http_msg_get_headers);
13151 hlua_class_function(L, "del_header", hlua_http_msg_del_hdr);
13152 hlua_class_function(L, "rep_header", hlua_http_msg_rep_hdr);
13153 hlua_class_function(L, "rep_value", hlua_http_msg_rep_val);
13154 hlua_class_function(L, "add_header", hlua_http_msg_add_hdr);
13155 hlua_class_function(L, "set_header", hlua_http_msg_set_hdr);
13156 hlua_class_function(L, "set_method", hlua_http_msg_set_meth);
13157 hlua_class_function(L, "set_path", hlua_http_msg_set_path);
13158 hlua_class_function(L, "set_query", hlua_http_msg_set_query);
13159 hlua_class_function(L, "set_uri", hlua_http_msg_set_uri);
13160 hlua_class_function(L, "set_status", hlua_http_msg_set_status);
13161 hlua_class_function(L, "is_full", hlua_http_msg_is_full);
13162 hlua_class_function(L, "may_recv", hlua_http_msg_may_recv);
13163 hlua_class_function(L, "eom", hlua_http_msg_is_eom);
13164 hlua_class_function(L, "input", hlua_http_msg_get_in_len);
13165 hlua_class_function(L, "output", hlua_http_msg_get_out_len);
13166
13167 hlua_class_function(L, "body", hlua_http_msg_get_body);
13168 hlua_class_function(L, "set", hlua_http_msg_set_data);
13169 hlua_class_function(L, "remove", hlua_http_msg_del_data);
13170 hlua_class_function(L, "append", hlua_http_msg_append);
13171 hlua_class_function(L, "prepend", hlua_http_msg_prepend);
13172 hlua_class_function(L, "insert", hlua_http_msg_insert_data);
13173 hlua_class_function(L, "set_eom", hlua_http_msg_set_eom);
13174 hlua_class_function(L, "unset_eom", hlua_http_msg_unset_eom);
13175
13176 hlua_class_function(L, "send", hlua_http_msg_send);
13177 hlua_class_function(L, "forward", hlua_http_msg_forward);
13178
13179 lua_rawset(L, -3);
13180
13181 /* Register previous table in the registry with reference and named entry. */
13182 class_http_msg_ref = hlua_register_metatable(L, CLASS_HTTP_MSG);
William Lallemand3956c4e2021-09-21 16:25:15 +020013183
13184 /*
13185 *
13186 * Register class HTTPClient
13187 *
13188 */
13189
13190 /* Create and fill the metatable. */
13191 lua_newtable(L);
13192 lua_pushstring(L, "__index");
13193 lua_newtable(L);
13194 hlua_class_function(L, "get", hlua_httpclient_get);
William Lallemanddc2cc902021-10-26 11:43:26 +020013195 hlua_class_function(L, "head", hlua_httpclient_head);
13196 hlua_class_function(L, "put", hlua_httpclient_put);
13197 hlua_class_function(L, "post", hlua_httpclient_post);
13198 hlua_class_function(L, "delete", hlua_httpclient_delete);
William Lallemand3956c4e2021-09-21 16:25:15 +020013199 lua_settable(L, -3); /* Sets the __index entry. */
William Lallemandf77f1de2021-09-28 19:10:38 +020013200 /* Register the garbage collector entry. */
13201 lua_pushstring(L, "__gc");
13202 lua_pushcclosure(L, hlua_httpclient_gc, 0);
13203 lua_settable(L, -3); /* Push the last 2 entries in the table at index -3 */
13204
William Lallemand3956c4e2021-09-21 16:25:15 +020013205
13206
13207 class_httpclient_ref = hlua_register_metatable(L, CLASS_HTTPCLIENT);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010013208 /*
13209 *
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020013210 * Register class AppletTCP
13211 *
13212 */
13213
13214 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013215 lua_newtable(L);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020013216
Ilya Shipitsind4259502020-04-08 01:07:56 +050013217 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013218 lua_pushstring(L, "__index");
13219 lua_newtable(L);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020013220
13221 /* Register Lua functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013222 hlua_class_function(L, "getline", hlua_applet_tcp_getline);
13223 hlua_class_function(L, "receive", hlua_applet_tcp_recv);
13224 hlua_class_function(L, "send", hlua_applet_tcp_send);
13225 hlua_class_function(L, "set_priv", hlua_applet_tcp_set_priv);
13226 hlua_class_function(L, "get_priv", hlua_applet_tcp_get_priv);
13227 hlua_class_function(L, "set_var", hlua_applet_tcp_set_var);
13228 hlua_class_function(L, "unset_var", hlua_applet_tcp_unset_var);
13229 hlua_class_function(L, "get_var", hlua_applet_tcp_get_var);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020013230
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013231 lua_settable(L, -3);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020013232
13233 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013234 class_applet_tcp_ref = hlua_register_metatable(L, CLASS_APPLET_TCP);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020013235
13236 /*
13237 *
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020013238 * Register class AppletHTTP
13239 *
13240 */
13241
13242 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013243 lua_newtable(L);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020013244
Ilya Shipitsind4259502020-04-08 01:07:56 +050013245 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013246 lua_pushstring(L, "__index");
13247 lua_newtable(L);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020013248
13249 /* Register Lua functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013250 hlua_class_function(L, "set_priv", hlua_applet_http_set_priv);
13251 hlua_class_function(L, "get_priv", hlua_applet_http_get_priv);
13252 hlua_class_function(L, "set_var", hlua_applet_http_set_var);
13253 hlua_class_function(L, "unset_var", hlua_applet_http_unset_var);
13254 hlua_class_function(L, "get_var", hlua_applet_http_get_var);
13255 hlua_class_function(L, "getline", hlua_applet_http_getline);
13256 hlua_class_function(L, "receive", hlua_applet_http_recv);
13257 hlua_class_function(L, "send", hlua_applet_http_send);
13258 hlua_class_function(L, "add_header", hlua_applet_http_addheader);
13259 hlua_class_function(L, "set_status", hlua_applet_http_status);
13260 hlua_class_function(L, "start_response", hlua_applet_http_start_response);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020013261
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013262 lua_settable(L, -3);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020013263
13264 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013265 class_applet_http_ref = hlua_register_metatable(L, CLASS_APPLET_HTTP);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020013266
13267 /*
13268 *
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010013269 * Register class TXN
13270 *
13271 */
13272
13273 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013274 lua_newtable(L);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010013275
Ilya Shipitsind4259502020-04-08 01:07:56 +050013276 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013277 lua_pushstring(L, "__index");
13278 lua_newtable(L);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010013279
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +010013280 /* Register Lua functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013281 hlua_class_function(L, "set_priv", hlua_set_priv);
13282 hlua_class_function(L, "get_priv", hlua_get_priv);
13283 hlua_class_function(L, "set_var", hlua_set_var);
13284 hlua_class_function(L, "unset_var", hlua_unset_var);
13285 hlua_class_function(L, "get_var", hlua_get_var);
13286 hlua_class_function(L, "done", hlua_txn_done);
13287 hlua_class_function(L, "reply", hlua_txn_reply_new);
13288 hlua_class_function(L, "set_loglevel", hlua_txn_set_loglevel);
13289 hlua_class_function(L, "set_tos", hlua_txn_set_tos);
13290 hlua_class_function(L, "set_mark", hlua_txn_set_mark);
13291 hlua_class_function(L, "set_priority_class", hlua_txn_set_priority_class);
13292 hlua_class_function(L, "set_priority_offset", hlua_txn_set_priority_offset);
13293 hlua_class_function(L, "deflog", hlua_txn_deflog);
13294 hlua_class_function(L, "log", hlua_txn_log);
13295 hlua_class_function(L, "Debug", hlua_txn_log_debug);
13296 hlua_class_function(L, "Info", hlua_txn_log_info);
13297 hlua_class_function(L, "Warning", hlua_txn_log_warning);
13298 hlua_class_function(L, "Alert", hlua_txn_log_alert);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +010013299
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013300 lua_rawset(L, -3);
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010013301
13302 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013303 class_txn_ref = hlua_register_metatable(L, CLASS_TXN);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010013304
13305 /*
13306 *
Christopher Faulet700d9e82020-01-31 12:21:52 +010013307 * Register class reply
13308 *
13309 */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013310 lua_newtable(L);
13311 lua_pushstring(L, "__index");
13312 lua_newtable(L);
13313 hlua_class_function(L, "set_status", hlua_txn_reply_set_status);
13314 hlua_class_function(L, "add_header", hlua_txn_reply_add_header);
13315 hlua_class_function(L, "del_header", hlua_txn_reply_del_header);
13316 hlua_class_function(L, "set_body", hlua_txn_reply_set_body);
13317 lua_settable(L, -3); /* Sets the __index entry. */
13318 class_txn_reply_ref = luaL_ref(L, LUA_REGISTRYINDEX);
Christopher Faulet700d9e82020-01-31 12:21:52 +010013319
13320
13321 /*
13322 *
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010013323 * Register class Socket
13324 *
13325 */
13326
13327 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013328 lua_newtable(L);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010013329
Ilya Shipitsind4259502020-04-08 01:07:56 +050013330 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013331 lua_pushstring(L, "__index");
13332 lua_newtable(L);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010013333
Baptiste Assmann84bb4932015-03-02 21:40:06 +010013334#ifdef USE_OPENSSL
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013335 hlua_class_function(L, "connect_ssl", hlua_socket_connect_ssl);
Baptiste Assmann84bb4932015-03-02 21:40:06 +010013336#endif
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013337 hlua_class_function(L, "connect", hlua_socket_connect);
13338 hlua_class_function(L, "send", hlua_socket_send);
13339 hlua_class_function(L, "receive", hlua_socket_receive);
13340 hlua_class_function(L, "close", hlua_socket_close);
13341 hlua_class_function(L, "getpeername", hlua_socket_getpeername);
13342 hlua_class_function(L, "getsockname", hlua_socket_getsockname);
13343 hlua_class_function(L, "setoption", hlua_socket_setoption);
13344 hlua_class_function(L, "settimeout", hlua_socket_settimeout);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010013345
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013346 lua_rawset(L, -3); /* Push the last 2 entries in the table at index -3 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010013347
13348 /* Register the garbage collector entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013349 lua_pushstring(L, "__gc");
13350 lua_pushcclosure(L, hlua_socket_gc, 0);
13351 lua_rawset(L, -3); /* Push the last 2 entries in the table at index -3 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010013352
13353 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013354 class_socket_ref = hlua_register_metatable(L, CLASS_SOCKET);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010013355
Thierry Fournieraafc7772020-12-04 11:47:47 +010013356 lua_atpanic(L, hlua_panic_safe);
13357
13358 return L;
13359}
13360
13361void hlua_init(void) {
13362 int i;
Amaury Denoyelle239fdbf2021-03-24 10:22:03 +010013363 char *errmsg;
Thierry Fournieraafc7772020-12-04 11:47:47 +010013364#ifdef USE_OPENSSL
13365 struct srv_kw *kw;
13366 int tmp_error;
13367 char *error;
13368 char *args[] = { /* SSL client configuration. */
13369 "ssl",
13370 "verify",
13371 "none",
13372 NULL
13373 };
13374#endif
13375
13376 /* Init post init function list head */
13377 for (i = 0; i < MAX_THREADS + 1; i++)
13378 LIST_INIT(&hlua_init_functions[i]);
13379
13380 /* Init state for common/shared lua parts */
13381 hlua_state_id = 0;
Willy Tarreau43ab05b2021-09-28 09:43:11 +020013382 ha_set_thread(NULL);
Thierry Fournieraafc7772020-12-04 11:47:47 +010013383 hlua_states[0] = hlua_init_state(0);
13384
13385 /* Init state 1 for thread 0. We have at least one thread. */
13386 hlua_state_id = 1;
Willy Tarreau43ab05b2021-09-28 09:43:11 +020013387 ha_set_thread(NULL);
Thierry Fournieraafc7772020-12-04 11:47:47 +010013388 hlua_states[1] = hlua_init_state(1);
13389
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010013390 /* Proxy and server configuration initialisation. */
William Lallemand6bb77b92021-07-28 15:48:16 +020013391 socket_proxy = alloc_new_proxy("LUA-SOCKET", PR_CAP_FE|PR_CAP_BE|PR_CAP_INT, &errmsg);
Amaury Denoyelle239fdbf2021-03-24 10:22:03 +010013392 if (!socket_proxy) {
13393 fprintf(stderr, "Lua init: %s\n", errmsg);
13394 exit(1);
13395 }
13396 proxy_preset_defaults(socket_proxy);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010013397
13398 /* Init TCP server: unchanged parameters */
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010013399 socket_tcp = new_server(socket_proxy);
13400 if (!socket_tcp) {
13401 fprintf(stderr, "Lua init: failed to allocate tcp server socket\n");
13402 exit(1);
13403 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010013404
13405#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010013406 /* Init TCP server: unchanged parameters */
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010013407 socket_ssl = new_server(socket_proxy);
13408 if (!socket_ssl) {
13409 fprintf(stderr, "Lua init: failed to allocate ssl server socket\n");
13410 exit(1);
13411 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010013412
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010013413 socket_ssl->use_ssl = 1;
13414 socket_ssl->xprt = xprt_get(XPRT_SSL);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010013415
Bertrand Jacquin80839ff2021-01-21 19:14:46 +000013416 for (i = 0; args[i] != NULL; i++) {
13417 if ((kw = srv_find_kw(args[i])) != NULL) { /* Maybe it's registered server keyword */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010013418 /*
13419 *
13420 * If the keyword is not known, we can search in the registered
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -080013421 * server keywords. This is useful to configure special SSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010013422 * features like client certificates and ssl_verify.
13423 *
13424 */
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010013425 tmp_error = kw->parse(args, &i, socket_proxy, socket_ssl, &error);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010013426 if (tmp_error != 0) {
13427 fprintf(stderr, "INTERNAL ERROR: %s\n", error);
13428 abort(); /* This must be never arrives because the command line
13429 not editable by the user. */
13430 }
Bertrand Jacquin80839ff2021-01-21 19:14:46 +000013431 i += kw->skip;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010013432 }
13433 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010013434#endif
Thierry Fournier75933d42016-01-21 09:30:18 +010013435
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +010013436}
Willy Tarreaubb57d942016-12-21 19:04:56 +010013437
Tim Duesterhusd0c0ca22020-07-04 11:53:26 +020013438static void hlua_deinit()
13439{
Willy Tarreau186f3762020-12-04 11:48:12 +010013440 int thr;
Christopher Faulet69c581a2021-05-31 08:54:04 +020013441 struct hlua_reg_filter *reg_flt, *reg_flt_bck;
13442
13443 list_for_each_entry_safe(reg_flt, reg_flt_bck, &referenced_filters, l)
13444 release_hlua_reg_filter(reg_flt);
Willy Tarreau186f3762020-12-04 11:48:12 +010013445
13446 for (thr = 0; thr < MAX_THREADS+1; thr++) {
13447 if (hlua_states[thr])
13448 lua_close(hlua_states[thr]);
13449 }
Willy Tarreau430bf4a2021-03-04 09:45:32 +010013450
Amaury Denoyellebc2ebfa2021-08-25 15:34:53 +020013451 srv_drop(socket_tcp);
Willy Tarreau430bf4a2021-03-04 09:45:32 +010013452
Willy Tarreau0f143af2021-03-05 10:41:48 +010013453#ifdef USE_OPENSSL
Amaury Denoyellebc2ebfa2021-08-25 15:34:53 +020013454 srv_drop(socket_ssl);
Willy Tarreau0f143af2021-03-05 10:41:48 +010013455#endif
Amaury Denoyelle239fdbf2021-03-24 10:22:03 +010013456
13457 free_proxy(socket_proxy);
Tim Duesterhusd0c0ca22020-07-04 11:53:26 +020013458}
13459
13460REGISTER_POST_DEINIT(hlua_deinit);
13461
Willy Tarreau80713382018-11-26 10:19:54 +010013462static void hlua_register_build_options(void)
13463{
Willy Tarreaubb57d942016-12-21 19:04:56 +010013464 char *ptr = NULL;
Willy Tarreau80713382018-11-26 10:19:54 +010013465
Willy Tarreaubb57d942016-12-21 19:04:56 +010013466 memprintf(&ptr, "Built with Lua version : %s", LUA_RELEASE);
13467 hap_register_build_opts(ptr, 1);
13468}
Willy Tarreau80713382018-11-26 10:19:54 +010013469
13470INITCALL0(STG_REGISTER, hlua_register_build_options);