blob: 492ee7e76f344ec294db39156eebf87ee86ac148 [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 */
357static uint32_t hlua_timeout_session = 4000; /* session timeout. */
358static uint32_t hlua_timeout_task = 0; /* task timeout. */
359static uint32_t hlua_timeout_applet = 4000; /* applet timeout. */
360
361/* hlua multipurpose timer:
362 * used to compute burst lua time (within a single hlua_ctx_resume())
363 * and cumulative lua time for a given coroutine, and to check
364 * the lua coroutine against the configured timeouts
365 */
366
367/* fetch per-thread cpu_time with ms precision (may wrap) */
368static inline uint32_t _hlua_time_ms()
369{
370 /* We're interested in the current cpu time in ms, which will be returned
371 * as a uint32_t to save some space.
372 * We must take the following into account:
373 *
374 * - now_cpu_time_fast() which returns the time in nanoseconds as a uint64_t
375 * will wrap every 585 years.
376 * - uint32_t may only contain 4294967295ms (~=49.7 days), so _hlua_time_ms()
377 * itself will also wrap every 49.7 days.
378 *
379 * While we can safely ignore the now_cpu_time_fast() wrap, we must
380 * take care of the uint32_t wrap by making sure to exclusively
381 * manipulate the time using uint32_t everywhere _hlua_time_ms()
382 * is involved.
383 */
384 return (uint32_t)(now_cpu_time_fast() / 1000000ULL);
385}
386
387/* computes time spent in a single lua execution (in ms) */
388static inline uint32_t _hlua_time_burst(const struct hlua_timer *timer)
389{
390 uint32_t burst_ms;
391
392 /* wrapping is expected and properly
393 * handled thanks to _hlua_time_ms() and burst_ms
394 * being of the same type
395 */
396 burst_ms = _hlua_time_ms() - timer->start;
397 return burst_ms;
398}
399
400static inline void hlua_timer_init(struct hlua_timer *timer, unsigned int max)
401{
402 timer->cumulative = 0;
403 timer->burst = 0;
404 timer->max = max;
405}
406
407/* reset the timer ctx between 2 yields */
408static inline void hlua_timer_reset(struct hlua_timer *timer)
409{
410 timer->cumulative += timer->burst;
411 timer->burst = 0;
412}
413
414/* start the timer right before a new execution */
415static inline void hlua_timer_start(struct hlua_timer *timer)
416{
417 timer->start = _hlua_time_ms();
418}
419
420/* update hlua timer when finishing an execution */
421static inline void hlua_timer_stop(struct hlua_timer *timer)
422{
423 timer->burst += _hlua_time_burst(timer);
424}
425
426/* check the timers for current hlua context
427 * Returns 1 if the check succeeded and 0 if it failed
428 * (ie: timeout exceeded)
Thierry FOURNIERbd413492015-03-03 16:52:26 +0100429 */
Aurelien DARRAGONda9503c2022-11-25 09:10:07 +0100430static inline int hlua_timer_check(const struct hlua_timer *timer)
431{
432 uint32_t pburst = _hlua_time_burst(timer); /* pending burst time in ms */
433
434 if (timer->max && (timer->cumulative + timer->burst + pburst) > timer->max)
435 return 0; /* cumulative timeout exceeded */
436 return 1; /* ok */
437}
Thierry FOURNIERbd413492015-03-03 16:52:26 +0100438
Thierry FOURNIERee9f8022015-03-03 17:37:37 +0100439/* Interrupts the Lua processing each "hlua_nb_instruction" instructions.
440 * it is used for preventing infinite loops.
441 *
442 * I test the scheer with an infinite loop containing one incrementation
443 * and one test. I run this loop between 10 seconds, I raise a ceil of
444 * 710M loops from one interrupt each 9000 instructions, so I fix the value
445 * to one interrupt each 10 000 instructions.
446 *
447 * configured | Number of
448 * instructions | loops executed
449 * between two | in milions
450 * forced yields |
451 * ---------------+---------------
452 * 10 | 160
453 * 500 | 670
454 * 1000 | 680
455 * 5000 | 700
456 * 7000 | 700
457 * 8000 | 700
458 * 9000 | 710 <- ceil
459 * 10000 | 710
460 * 100000 | 710
461 * 1000000 | 710
462 *
463 */
464static unsigned int hlua_nb_instruction = 10000;
465
Willy Tarreaucdb53462020-12-02 12:12:00 +0100466/* Descriptor for the memory allocation state. The limit is pre-initialised to
467 * 0 until it is replaced by "tune.lua.maxmem" during the config parsing, or it
468 * is replaced with ~0 during post_init after everything was loaded. This way
469 * it is guaranteed that if limit is ~0 the boot is complete and that if it's
470 * zero it's not yet limited and proper accounting is required.
Willy Tarreau32f61e22015-03-18 17:54:59 +0100471 */
472struct hlua_mem_allocator {
473 size_t allocated;
474 size_t limit;
475};
476
Willy Tarreaucdb53462020-12-02 12:12:00 +0100477static struct hlua_mem_allocator hlua_global_allocator THREAD_ALIGNED(64);
Willy Tarreau32f61e22015-03-18 17:54:59 +0100478
Aurelien DARRAGONc84899c2023-02-20 18:18:59 +0100479/* hlua event subscription */
480struct hlua_event_sub {
481 int fcn_ref;
482 int state_id;
483 struct hlua *hlua;
484 struct task *task;
485 event_hdl_async_equeue equeue;
486 struct event_hdl_sub *sub;
487 uint8_t paused;
488};
489
490/* This is the memory pool containing struct hlua_event_sub
491 * for event subscriptions from lua
492 */
493DECLARE_STATIC_POOL(pool_head_hlua_event_sub, "hlua_esub", sizeof(struct hlua_event_sub));
494
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100495/* These functions converts types between HAProxy internal args or
496 * sample and LUA types. Another function permits to check if the
497 * LUA stack contains arguments according with an required ARG_T
498 * format.
499 */
500static int hlua_arg2lua(lua_State *L, const struct arg *arg);
501static int hlua_lua2arg(lua_State *L, int ud, struct arg *arg);
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100502__LJMP static int hlua_lua2arg_check(lua_State *L, int first, struct arg *argp,
David Carlier0c437f42016-04-27 16:21:56 +0100503 uint64_t mask, struct proxy *p);
Willy Tarreau5eadada2015-03-10 17:28:54 +0100504static int hlua_smp2lua(lua_State *L, struct sample *smp);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100505static int hlua_smp2lua_str(lua_State *L, struct sample *smp);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100506static int hlua_lua2smp(lua_State *L, int ud, struct sample *smp);
507
Christopher Faulet9d1332b2020-02-24 16:46:16 +0100508__LJMP static int hlua_http_get_headers(lua_State *L, struct http_msg *msg);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200509
Thierry Fournier59f11be2020-11-29 00:37:41 +0100510struct prepend_path {
511 struct list l;
512 char *type;
513 char *path;
514};
515
516static struct list prepend_path_list = LIST_HEAD_INIT(prepend_path_list);
517
Thierry FOURNIER23bc3752015-09-11 19:15:43 +0200518#define SEND_ERR(__be, __fmt, __args...) \
519 do { \
520 send_log(__be, LOG_ERR, __fmt, ## __args); \
521 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE)) \
Christopher Faulet767a84b2017-11-24 16:50:31 +0100522 ha_alert(__fmt, ## __args); \
Thierry FOURNIER23bc3752015-09-11 19:15:43 +0200523 } while (0)
524
Thierry Fournier62a22aa2020-11-28 21:06:35 +0100525static inline struct hlua_function *new_hlua_function()
526{
527 struct hlua_function *fcn;
Thierry Fournierc7492592020-11-28 23:57:24 +0100528 int i;
Thierry Fournier62a22aa2020-11-28 21:06:35 +0100529
530 fcn = calloc(1, sizeof(*fcn));
531 if (!fcn)
532 return NULL;
Willy Tarreau2b718102021-04-21 07:32:39 +0200533 LIST_APPEND(&referenced_functions, &fcn->l);
Thierry Fournierc7492592020-11-28 23:57:24 +0100534 for (i = 0; i < MAX_THREADS + 1; i++)
535 fcn->function_ref[i] = -1;
Thierry Fournier62a22aa2020-11-28 21:06:35 +0100536 return fcn;
537}
538
Christopher Fauletdda44442021-04-12 14:05:43 +0200539static inline void release_hlua_function(struct hlua_function *fcn)
540{
541 if (!fcn)
542 return;
543 if (fcn->name)
544 ha_free(&fcn->name);
Willy Tarreau2b718102021-04-21 07:32:39 +0200545 LIST_DELETE(&fcn->l);
Christopher Fauletdda44442021-04-12 14:05:43 +0200546 ha_free(&fcn);
547}
548
Thierry Fournierc7492592020-11-28 23:57:24 +0100549/* If the common state is set, the stack id is 0, otherwise it is the tid + 1 */
550static inline int fcn_ref_to_stack_id(struct hlua_function *fcn)
551{
552 if (fcn->function_ref[0] == -1)
553 return tid + 1;
554 return 0;
555}
556
Christopher Faulet69c581a2021-05-31 08:54:04 +0200557/* Create a new registered filter. Only its name is filled */
558static inline struct hlua_reg_filter *new_hlua_reg_filter(const char *name)
559{
560 struct hlua_reg_filter *reg_flt;
561 int i;
562
563 reg_flt = calloc(1, sizeof(*reg_flt));
564 if (!reg_flt)
565 return NULL;
566 reg_flt->name = strdup(name);
567 if (!reg_flt->name) {
568 free(reg_flt);
569 return NULL;
570 }
571 LIST_APPEND(&referenced_filters, &reg_flt->l);
572 for (i = 0; i < MAX_THREADS + 1; i++) {
573 reg_flt->flt_ref[i] = -1;
574 reg_flt->fun_ref[i] = -1;
575 }
576 return reg_flt;
577}
578
579/* Release a registered filter */
580static inline void release_hlua_reg_filter(struct hlua_reg_filter *reg_flt)
581{
582 if (!reg_flt)
583 return;
584 if (reg_flt->name)
585 ha_free(&reg_flt->name);
586 LIST_DELETE(&reg_flt->l);
587 ha_free(&reg_flt);
588}
589
590/* If the common state is set, the stack id is 0, otherwise it is the tid + 1 */
591static inline int reg_flt_to_stack_id(struct hlua_reg_filter *reg_flt)
592{
593 if (reg_flt->fun_ref[0] == -1)
594 return tid + 1;
595 return 0;
596}
597
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100598/* Used to check an Lua function type in the stack. It creates and
599 * returns a reference of the function. This function throws an
Aurelien DARRAGONf8f8a2b2023-03-02 17:50:49 +0100600 * error if the argument is not a "function".
601 * When no longer used, the ref must be released with hlua_unref()
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100602 */
Aurelien DARRAGON9ee0d042023-03-20 18:36:08 +0100603__LJMP int hlua_checkfunction(lua_State *L, int argno)
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100604{
605 if (!lua_isfunction(L, argno)) {
Thierry FOURNIERfd1e9552018-02-23 18:41:18 +0100606 const char *msg = lua_pushfstring(L, "function expected, got %s", luaL_typename(L, argno));
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100607 WILL_LJMP(luaL_argerror(L, argno, msg));
608 }
609 lua_pushvalue(L, argno);
610 return luaL_ref(L, LUA_REGISTRYINDEX);
611}
612
Christopher Fauletba9e21d2020-02-25 10:20:04 +0100613/* Used to check an Lua table type in the stack. It creates and
614 * returns a reference of the table. This function throws an
Aurelien DARRAGONf8f8a2b2023-03-02 17:50:49 +0100615 * error if the argument is not a "table".
616 * When no longer used, the ref must be released with hlua_unref()
Christopher Fauletba9e21d2020-02-25 10:20:04 +0100617 */
Aurelien DARRAGON9ee0d042023-03-20 18:36:08 +0100618__LJMP int hlua_checktable(lua_State *L, int argno)
Christopher Fauletba9e21d2020-02-25 10:20:04 +0100619{
620 if (!lua_istable(L, argno)) {
621 const char *msg = lua_pushfstring(L, "table expected, got %s", luaL_typename(L, argno));
622 WILL_LJMP(luaL_argerror(L, argno, msg));
623 }
624 lua_pushvalue(L, argno);
625 return luaL_ref(L, LUA_REGISTRYINDEX);
626}
627
Aurelien DARRAGONf8f8a2b2023-03-02 17:50:49 +0100628/* Get a reference to the object that is at the top of the stack
629 * The referenced object will be popped from the stack
630 *
631 * The function returns the reference to the object which must
632 * be cleared using hlua_unref() when no longer used
633 */
634__LJMP int hlua_ref(lua_State *L)
635{
636 return MAY_LJMP(luaL_ref(L, LUA_REGISTRYINDEX));
637}
638
639/* Pushes a reference previously created using luaL_ref(L, LUA_REGISTRYINDEX)
640 * on <L> stack
641 * (ie: hlua_checkfunction(), hlua_checktable() or hlua_ref())
642 *
643 * When the reference is no longer used, it should be released by calling
644 * hlua_unref()
645 *
646 * <L> can be from any co-routine as long as it belongs to the same lua
647 * parent state that the one used to get the reference.
648 */
649void hlua_pushref(lua_State *L, int ref)
650{
651 lua_rawgeti(L, LUA_REGISTRYINDEX, ref);
652}
653
654/* Releases a reference previously created using luaL_ref(L, LUA_REGISTRYINDEX)
655 * (ie: hlua_checkfunction(), hlua_checktable() or hlua_ref())
656 *
657 * This will allow the reference to be reused and the referred object
658 * to be garbage collected.
659 *
660 * <L> can be from any co-routine as long as it belongs to the same lua
661 * parent state that the one used to get the reference.
662 */
663void hlua_unref(lua_State *L, int ref)
664{
665 luaL_unref(L, LUA_REGISTRYINDEX, ref);
666}
667
Christopher Fauletd09cc512021-03-24 14:48:45 +0100668__LJMP const char *hlua_traceback(lua_State *L, const char* sep)
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200669{
670 lua_Debug ar;
671 int level = 0;
Willy Tarreau83061a82018-07-13 11:56:34 +0200672 struct buffer *msg = get_trash_chunk();
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200673
674 while (lua_getstack(L, level++, &ar)) {
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200675 /* Fill fields:
676 * 'S': fills in the fields source, short_src, linedefined, lastlinedefined, and what;
677 * 'l': fills in the field currentline;
678 * 'n': fills in the field name and namewhat;
679 * 't': fills in the field istailcall;
680 */
681 lua_getinfo(L, "Slnt", &ar);
682
Willy Tarreau5c143402022-06-19 17:35:53 +0200683 /* skip these empty entries, usually they come from deep C functions */
684 if (ar.currentline < 0 && *ar.what == 'C' && !*ar.namewhat && !ar.name)
685 continue;
686
687 /* Add separator */
688 if (b_data(msg))
689 chunk_appendf(msg, "%s", sep);
690
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200691 /* Append code localisation */
692 if (ar.currentline > 0)
Christopher Fauletd09cc512021-03-24 14:48:45 +0100693 chunk_appendf(msg, "%s:%d: ", ar.short_src, ar.currentline);
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200694 else
Christopher Fauletd09cc512021-03-24 14:48:45 +0100695 chunk_appendf(msg, "%s: ", ar.short_src);
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200696
697 /*
698 * Get function name
699 *
700 * if namewhat is no empty, name is defined.
701 * what contains "Lua" for Lua function, "C" for C function,
702 * or "main" for main code.
703 */
704 if (*ar.namewhat != '\0' && ar.name != NULL) /* is there a name from code? */
Christopher Fauletd09cc512021-03-24 14:48:45 +0100705 chunk_appendf(msg, "in %s '%s'", ar.namewhat, ar.name); /* use it */
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200706
707 else if (*ar.what == 'm') /* "main", the code is not executed in a function */
Christopher Fauletd09cc512021-03-24 14:48:45 +0100708 chunk_appendf(msg, "in main chunk");
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200709
710 else if (*ar.what != 'C') /* for Lua functions, use <file:line> */
Christopher Fauletd09cc512021-03-24 14:48:45 +0100711 chunk_appendf(msg, "in function line %d", ar.linedefined);
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200712
713 else /* nothing left... */
714 chunk_appendf(msg, "?");
715
716
717 /* Display tailed call */
718 if (ar.istailcall)
719 chunk_appendf(msg, " ...");
720 }
721
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200722 return msg->area;
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200723}
724
725
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100726/* This function check the number of arguments available in the
727 * stack. If the number of arguments available is not the same
Ilya Shipitsinc02a23f2020-05-06 00:53:22 +0500728 * then <nb> an error is thrown.
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100729 */
730__LJMP static inline void check_args(lua_State *L, int nb, char *fcn)
731{
732 if (lua_gettop(L) == nb)
733 return;
734 WILL_LJMP(luaL_error(L, "'%s' needs %d arguments", fcn, nb));
735}
736
Mark Lakes22154b42018-01-29 14:38:40 -0800737/* This function pushes an error string prefixed by the file name
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100738 * and the line number where the error is encountered.
739 */
740static int hlua_pusherror(lua_State *L, const char *fmt, ...)
741{
742 va_list argp;
743 va_start(argp, fmt);
744 luaL_where(L, 1);
745 lua_pushvfstring(L, fmt, argp);
746 va_end(argp);
747 lua_concat(L, 2);
748 return 1;
749}
750
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100751/* This functions is used with sample fetch and converters. It
752 * converts the HAProxy configuration argument in a lua stack
753 * values.
754 *
755 * It takes an array of "arg", and each entry of the array is
756 * converted and pushed in the LUA stack.
757 */
758static int hlua_arg2lua(lua_State *L, const struct arg *arg)
759{
760 switch (arg->type) {
761 case ARGT_SINT:
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100762 case ARGT_TIME:
763 case ARGT_SIZE:
Thierry FOURNIERf90838b2015-03-06 13:48:32 +0100764 lua_pushinteger(L, arg->data.sint);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100765 break;
766
767 case ARGT_STR:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200768 lua_pushlstring(L, arg->data.str.area, arg->data.str.data);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100769 break;
770
771 case ARGT_IPV4:
772 case ARGT_IPV6:
773 case ARGT_MSK4:
774 case ARGT_MSK6:
775 case ARGT_FE:
776 case ARGT_BE:
777 case ARGT_TAB:
778 case ARGT_SRV:
779 case ARGT_USR:
780 case ARGT_MAP:
781 default:
782 lua_pushnil(L);
783 break;
784 }
785 return 1;
786}
787
Ilya Shipitsinc02a23f2020-05-06 00:53:22 +0500788/* This function take one entry in an LUA stack at the index "ud",
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100789 * and try to convert it in an HAProxy argument entry. This is useful
Ilya Shipitsind4259502020-04-08 01:07:56 +0500790 * with sample fetch wrappers. The input arguments are given to the
791 * lua wrapper and converted as arg list by the function.
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100792 */
793static int hlua_lua2arg(lua_State *L, int ud, struct arg *arg)
794{
795 switch (lua_type(L, ud)) {
796
797 case LUA_TNUMBER:
798 case LUA_TBOOLEAN:
799 arg->type = ARGT_SINT;
800 arg->data.sint = lua_tointeger(L, ud);
801 break;
802
803 case LUA_TSTRING:
804 arg->type = ARGT_STR;
Tim Duesterhus2e89dec2019-09-29 23:03:08 +0200805 arg->data.str.area = (char *)lua_tolstring(L, ud, &arg->data.str.data);
Tim Duesterhus29d2e8a2019-09-29 23:03:07 +0200806 /* We don't know the actual size of the underlying allocation, so be conservative. */
Christopher Fauletfdea1b62020-08-06 08:29:18 +0200807 arg->data.str.size = arg->data.str.data+1; /* count the terminating null byte */
Tim Duesterhus29d2e8a2019-09-29 23:03:07 +0200808 arg->data.str.head = 0;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100809 break;
810
811 case LUA_TUSERDATA:
812 case LUA_TNIL:
813 case LUA_TTABLE:
814 case LUA_TFUNCTION:
815 case LUA_TTHREAD:
816 case LUA_TLIGHTUSERDATA:
817 arg->type = ARGT_SINT;
Thierry FOURNIERbf65cd42015-07-20 17:45:02 +0200818 arg->data.sint = 0;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100819 break;
820 }
821 return 1;
822}
823
824/* the following functions are used to convert a struct sample
825 * in Lua type. This useful to convert the return of the
Ilya Shipitsind4259502020-04-08 01:07:56 +0500826 * fetches or converters.
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100827 */
Willy Tarreau5eadada2015-03-10 17:28:54 +0100828static int hlua_smp2lua(lua_State *L, struct sample *smp)
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100829{
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200830 switch (smp->data.type) {
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100831 case SMP_T_SINT:
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100832 case SMP_T_BOOL:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200833 lua_pushinteger(L, smp->data.u.sint);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100834 break;
835
836 case SMP_T_BIN:
837 case SMP_T_STR:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200838 lua_pushlstring(L, smp->data.u.str.area, smp->data.u.str.data);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100839 break;
840
841 case SMP_T_METH:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200842 switch (smp->data.u.meth.meth) {
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100843 case HTTP_METH_OPTIONS: lua_pushstring(L, "OPTIONS"); break;
844 case HTTP_METH_GET: lua_pushstring(L, "GET"); break;
845 case HTTP_METH_HEAD: lua_pushstring(L, "HEAD"); break;
846 case HTTP_METH_POST: lua_pushstring(L, "POST"); break;
847 case HTTP_METH_PUT: lua_pushstring(L, "PUT"); break;
848 case HTTP_METH_DELETE: lua_pushstring(L, "DELETE"); break;
849 case HTTP_METH_TRACE: lua_pushstring(L, "TRACE"); break;
850 case HTTP_METH_CONNECT: lua_pushstring(L, "CONNECT"); break;
851 case HTTP_METH_OTHER:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200852 lua_pushlstring(L, smp->data.u.meth.str.area, smp->data.u.meth.str.data);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100853 break;
854 default:
855 lua_pushnil(L);
856 break;
857 }
858 break;
859
860 case SMP_T_IPV4:
861 case SMP_T_IPV6:
862 case SMP_T_ADDR: /* This type is never used to qualify a sample. */
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200863 if (sample_casts[smp->data.type][SMP_T_STR] &&
864 sample_casts[smp->data.type][SMP_T_STR](smp))
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200865 lua_pushlstring(L, smp->data.u.str.area, smp->data.u.str.data);
Willy Tarreau5eadada2015-03-10 17:28:54 +0100866 else
867 lua_pushnil(L);
868 break;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100869 default:
870 lua_pushnil(L);
871 break;
872 }
873 return 1;
874}
875
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100876/* the following functions are used to convert a struct sample
877 * in Lua strings. This is useful to convert the return of the
Ilya Shipitsind4259502020-04-08 01:07:56 +0500878 * fetches or converters.
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100879 */
880static int hlua_smp2lua_str(lua_State *L, struct sample *smp)
881{
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200882 switch (smp->data.type) {
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100883
884 case SMP_T_BIN:
885 case SMP_T_STR:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200886 lua_pushlstring(L, smp->data.u.str.area, smp->data.u.str.data);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100887 break;
888
889 case SMP_T_METH:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200890 switch (smp->data.u.meth.meth) {
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100891 case HTTP_METH_OPTIONS: lua_pushstring(L, "OPTIONS"); break;
892 case HTTP_METH_GET: lua_pushstring(L, "GET"); break;
893 case HTTP_METH_HEAD: lua_pushstring(L, "HEAD"); break;
894 case HTTP_METH_POST: lua_pushstring(L, "POST"); break;
895 case HTTP_METH_PUT: lua_pushstring(L, "PUT"); break;
896 case HTTP_METH_DELETE: lua_pushstring(L, "DELETE"); break;
897 case HTTP_METH_TRACE: lua_pushstring(L, "TRACE"); break;
898 case HTTP_METH_CONNECT: lua_pushstring(L, "CONNECT"); break;
899 case HTTP_METH_OTHER:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200900 lua_pushlstring(L, smp->data.u.meth.str.area, smp->data.u.meth.str.data);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100901 break;
902 default:
903 lua_pushstring(L, "");
904 break;
905 }
906 break;
907
908 case SMP_T_SINT:
909 case SMP_T_BOOL:
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100910 case SMP_T_IPV4:
911 case SMP_T_IPV6:
912 case SMP_T_ADDR: /* This type is never used to qualify a sample. */
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200913 if (sample_casts[smp->data.type][SMP_T_STR] &&
914 sample_casts[smp->data.type][SMP_T_STR](smp))
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200915 lua_pushlstring(L, smp->data.u.str.area, smp->data.u.str.data);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100916 else
917 lua_pushstring(L, "");
918 break;
919 default:
920 lua_pushstring(L, "");
921 break;
922 }
923 return 1;
924}
925
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100926/* the following functions are used to convert an Lua type in a
927 * struct sample. This is useful to provide data from a converter
928 * to the LUA code.
929 */
930static int hlua_lua2smp(lua_State *L, int ud, struct sample *smp)
931{
932 switch (lua_type(L, ud)) {
933
934 case LUA_TNUMBER:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200935 smp->data.type = SMP_T_SINT;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200936 smp->data.u.sint = lua_tointeger(L, ud);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100937 break;
938
939
940 case LUA_TBOOLEAN:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200941 smp->data.type = SMP_T_BOOL;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200942 smp->data.u.sint = lua_toboolean(L, ud);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100943 break;
944
945 case LUA_TSTRING:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200946 smp->data.type = SMP_T_STR;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100947 smp->flags |= SMP_F_CONST;
Tim Duesterhus2e89dec2019-09-29 23:03:08 +0200948 smp->data.u.str.area = (char *)lua_tolstring(L, ud, &smp->data.u.str.data);
Tim Duesterhus29d2e8a2019-09-29 23:03:07 +0200949 /* We don't know the actual size of the underlying allocation, so be conservative. */
Christopher Fauletfdea1b62020-08-06 08:29:18 +0200950 smp->data.u.str.size = smp->data.u.str.data+1; /* count the terminating null byte */
Tim Duesterhus29d2e8a2019-09-29 23:03:07 +0200951 smp->data.u.str.head = 0;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100952 break;
953
954 case LUA_TUSERDATA:
955 case LUA_TNIL:
956 case LUA_TTABLE:
957 case LUA_TFUNCTION:
958 case LUA_TTHREAD:
959 case LUA_TLIGHTUSERDATA:
Thierry FOURNIER93405e12015-08-26 14:19:03 +0200960 case LUA_TNONE:
961 default:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200962 smp->data.type = SMP_T_BOOL;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200963 smp->data.u.sint = 0;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100964 break;
965 }
966 return 1;
967}
968
Ilya Shipitsind4259502020-04-08 01:07:56 +0500969/* This function check the "argp" built by another conversion function
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -0800970 * is in accord with the expected argp defined by the "mask". The function
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100971 * returns true or false. It can be adjust the types if there compatibles.
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100972 *
Ilya Shipitsinc02a23f2020-05-06 00:53:22 +0500973 * This function assumes that the argp argument contains ARGM_NBARGS + 1
Willy Tarreauee0d7272021-07-16 10:26:56 +0200974 * entries and that there is at least one stop at the last position.
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100975 */
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100976__LJMP int hlua_lua2arg_check(lua_State *L, int first, struct arg *argp,
David Carlier0c437f42016-04-27 16:21:56 +0100977 uint64_t mask, struct proxy *p)
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100978{
979 int min_arg;
Willy Tarreauee0d7272021-07-16 10:26:56 +0200980 int idx;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100981 struct proxy *px;
Christopher Fauletd25d9262020-08-06 11:04:46 +0200982 struct userlist *ul;
Christopher Fauletfd2e9062020-08-06 11:10:57 +0200983 struct my_regex *reg;
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200984 const char *msg = NULL;
Christopher Fauletfd2e9062020-08-06 11:10:57 +0200985 char *sname, *pname, *err = NULL;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100986
987 idx = 0;
988 min_arg = ARGM(mask);
989 mask >>= ARGM_BITS;
990
991 while (1) {
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200992 struct buffer tmp = BUF_NULL;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100993
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100994 /* Check for mandatory arguments. */
995 if (argp[idx].type == ARGT_STOP) {
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100996 if (idx < min_arg) {
997
998 /* If miss other argument than the first one, we return an error. */
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200999 if (idx > 0) {
1000 msg = "Mandatory argument expected";
1001 goto error;
1002 }
Thierry FOURNIER3caa0392015-03-13 13:38:17 +01001003
1004 /* If first argument have a certain type, some default values
1005 * may be used. See the function smp_resolve_args().
1006 */
1007 switch (mask & ARGT_MASK) {
1008
1009 case ARGT_FE:
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001010 if (!(p->cap & PR_CAP_FE)) {
1011 msg = "Mandatory argument expected";
1012 goto error;
1013 }
Thierry FOURNIER3caa0392015-03-13 13:38:17 +01001014 argp[idx].data.prx = p;
1015 argp[idx].type = ARGT_FE;
1016 argp[idx+1].type = ARGT_STOP;
1017 break;
1018
1019 case ARGT_BE:
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001020 if (!(p->cap & PR_CAP_BE)) {
1021 msg = "Mandatory argument expected";
1022 goto error;
1023 }
Thierry FOURNIER3caa0392015-03-13 13:38:17 +01001024 argp[idx].data.prx = p;
1025 argp[idx].type = ARGT_BE;
1026 argp[idx+1].type = ARGT_STOP;
1027 break;
1028
1029 case ARGT_TAB:
Olivier Houchard14f62682022-09-13 00:35:53 +02001030 if (!p->table) {
1031 msg = "Mandatory argument expected";
1032 goto error;
1033 }
1034 argp[idx].data.t = p->table;
Thierry FOURNIER3caa0392015-03-13 13:38:17 +01001035 argp[idx].type = ARGT_TAB;
1036 argp[idx+1].type = ARGT_STOP;
1037 break;
1038
1039 default:
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001040 msg = "Mandatory argument expected";
1041 goto error;
Thierry FOURNIER3caa0392015-03-13 13:38:17 +01001042 break;
1043 }
1044 }
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001045 break;
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001046 }
1047
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001048 /* Check for exceed the number of required argument. */
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001049 if ((mask & ARGT_MASK) == ARGT_STOP &&
1050 argp[idx].type != ARGT_STOP) {
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001051 msg = "Last argument expected";
1052 goto error;
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001053 }
1054
1055 if ((mask & ARGT_MASK) == ARGT_STOP &&
1056 argp[idx].type == ARGT_STOP) {
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001057 break;
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001058 }
1059
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001060 /* Convert some argument types. All string in argp[] are for not
1061 * duplicated yet.
1062 */
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001063 switch (mask & ARGT_MASK) {
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001064 case ARGT_SINT:
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001065 if (argp[idx].type != ARGT_SINT) {
1066 msg = "integer expected";
1067 goto error;
1068 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001069 argp[idx].type = ARGT_SINT;
1070 break;
1071
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001072 case ARGT_TIME:
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001073 if (argp[idx].type != ARGT_SINT) {
1074 msg = "integer expected";
1075 goto error;
1076 }
Thierry FOURNIER29176f32015-07-07 00:41:29 +02001077 argp[idx].type = ARGT_TIME;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001078 break;
1079
1080 case ARGT_SIZE:
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001081 if (argp[idx].type != ARGT_SINT) {
1082 msg = "integer expected";
1083 goto error;
1084 }
Thierry FOURNIER29176f32015-07-07 00:41:29 +02001085 argp[idx].type = ARGT_SIZE;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001086 break;
1087
1088 case ARGT_FE:
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001089 if (argp[idx].type != ARGT_STR) {
1090 msg = "string expected";
1091 goto error;
1092 }
Christopher Fauletfdea1b62020-08-06 08:29:18 +02001093 argp[idx].data.prx = proxy_fe_by_name(argp[idx].data.str.area);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001094 if (!argp[idx].data.prx) {
1095 msg = "frontend doesn't exist";
1096 goto error;
1097 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001098 argp[idx].type = ARGT_FE;
1099 break;
1100
1101 case ARGT_BE:
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001102 if (argp[idx].type != ARGT_STR) {
1103 msg = "string expected";
1104 goto error;
1105 }
Christopher Fauletfdea1b62020-08-06 08:29:18 +02001106 argp[idx].data.prx = proxy_be_by_name(argp[idx].data.str.area);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001107 if (!argp[idx].data.prx) {
1108 msg = "backend doesn't exist";
1109 goto error;
1110 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001111 argp[idx].type = ARGT_BE;
1112 break;
1113
1114 case ARGT_TAB:
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001115 if (argp[idx].type != ARGT_STR) {
1116 msg = "string expected";
1117 goto error;
1118 }
Christopher Fauletfdea1b62020-08-06 08:29:18 +02001119 argp[idx].data.t = stktable_find_by_name(argp[idx].data.str.area);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001120 if (!argp[idx].data.t) {
1121 msg = "table doesn't exist";
1122 goto error;
1123 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001124 argp[idx].type = ARGT_TAB;
1125 break;
1126
1127 case ARGT_SRV:
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001128 if (argp[idx].type != ARGT_STR) {
1129 msg = "string expected";
1130 goto error;
1131 }
Christopher Fauletfdea1b62020-08-06 08:29:18 +02001132 sname = strrchr(argp[idx].data.str.area, '/');
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001133 if (sname) {
1134 *sname++ = '\0';
Christopher Fauletfdea1b62020-08-06 08:29:18 +02001135 pname = argp[idx].data.str.area;
Willy Tarreau9e0bb102015-05-26 11:24:42 +02001136 px = proxy_be_by_name(pname);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001137 if (!px) {
1138 msg = "backend doesn't exist";
1139 goto error;
1140 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001141 }
1142 else {
Christopher Fauletfdea1b62020-08-06 08:29:18 +02001143 sname = argp[idx].data.str.area;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001144 px = p;
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001145 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001146 argp[idx].data.srv = findserver(px, sname);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001147 if (!argp[idx].data.srv) {
1148 msg = "server doesn't exist";
1149 goto error;
1150 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001151 argp[idx].type = ARGT_SRV;
1152 break;
1153
1154 case ARGT_IPV4:
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001155 if (argp[idx].type != ARGT_STR) {
1156 msg = "string expected";
1157 goto error;
1158 }
1159 if (inet_pton(AF_INET, argp[idx].data.str.area, &argp[idx].data.ipv4)) {
1160 msg = "invalid IPv4 address";
1161 goto error;
1162 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001163 argp[idx].type = ARGT_IPV4;
1164 break;
1165
1166 case ARGT_MSK4:
Christopher Faulete663a6e2020-08-07 09:11:22 +02001167 if (argp[idx].type == ARGT_SINT)
1168 len2mask4(argp[idx].data.sint, &argp[idx].data.ipv4);
1169 else if (argp[idx].type == ARGT_STR) {
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001170 if (!str2mask(argp[idx].data.str.area, &argp[idx].data.ipv4)) {
1171 msg = "invalid IPv4 mask";
1172 goto error;
1173 }
1174 }
1175 else {
1176 msg = "integer or string expected";
1177 goto error;
Christopher Faulete663a6e2020-08-07 09:11:22 +02001178 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001179 argp[idx].type = ARGT_MSK4;
1180 break;
1181
1182 case ARGT_IPV6:
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001183 if (argp[idx].type != ARGT_STR) {
1184 msg = "string expected";
1185 goto error;
1186 }
1187 if (inet_pton(AF_INET6, argp[idx].data.str.area, &argp[idx].data.ipv6)) {
1188 msg = "invalid IPv6 address";
1189 goto error;
1190 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001191 argp[idx].type = ARGT_IPV6;
1192 break;
1193
1194 case ARGT_MSK6:
Christopher Faulete663a6e2020-08-07 09:11:22 +02001195 if (argp[idx].type == ARGT_SINT)
1196 len2mask6(argp[idx].data.sint, &argp[idx].data.ipv6);
1197 else if (argp[idx].type == ARGT_STR) {
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001198 if (!str2mask6(argp[idx].data.str.area, &argp[idx].data.ipv6)) {
1199 msg = "invalid IPv6 mask";
1200 goto error;
1201 }
1202 }
1203 else {
1204 msg = "integer or string expected";
1205 goto error;
Christopher Faulete663a6e2020-08-07 09:11:22 +02001206 }
Tim Duesterhusb814da62018-01-25 16:24:50 +01001207 argp[idx].type = ARGT_MSK6;
1208 break;
1209
Christopher Fauletfd2e9062020-08-06 11:10:57 +02001210 case ARGT_REG:
1211 if (argp[idx].type != ARGT_STR) {
1212 msg = "string expected";
1213 goto error;
1214 }
1215 reg = regex_comp(argp[idx].data.str.area, !(argp[idx].type_flags & ARGF_REG_ICASE), 1, &err);
1216 if (!reg) {
1217 msg = lua_pushfstring(L, "error compiling regex '%s' : '%s'",
1218 argp[idx].data.str.area, err);
1219 free(err);
1220 goto error;
1221 }
1222 argp[idx].type = ARGT_REG;
1223 argp[idx].data.reg = reg;
1224 break;
1225
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001226 case ARGT_USR:
Christopher Fauletd25d9262020-08-06 11:04:46 +02001227 if (argp[idx].type != ARGT_STR) {
1228 msg = "string expected";
1229 goto error;
1230 }
1231 if (p->uri_auth && p->uri_auth->userlist &&
Tim Duesterhuse5ff1412021-01-02 22:31:53 +01001232 strcmp(p->uri_auth->userlist->name, argp[idx].data.str.area) == 0)
Christopher Fauletd25d9262020-08-06 11:04:46 +02001233 ul = p->uri_auth->userlist;
1234 else
1235 ul = auth_find_userlist(argp[idx].data.str.area);
1236
1237 if (!ul) {
1238 msg = lua_pushfstring(L, "unable to find userlist '%s'", argp[idx].data.str.area);
1239 goto error;
1240 }
1241 argp[idx].type = ARGT_USR;
1242 argp[idx].data.usr = ul;
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001243 break;
1244
1245 case ARGT_STR:
1246 if (!chunk_dup(&tmp, &argp[idx].data.str)) {
1247 msg = "unable to duplicate string arg";
1248 goto error;
1249 }
1250 argp[idx].data.str = tmp;
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001251 break;
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001252
Christopher Fauletd25d9262020-08-06 11:04:46 +02001253 case ARGT_MAP:
Christopher Fauletd25d9262020-08-06 11:04:46 +02001254 msg = "type not yet supported";
1255 goto error;
1256 break;
1257
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001258 }
1259
1260 /* Check for type of argument. */
1261 if ((mask & ARGT_MASK) != argp[idx].type) {
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001262 msg = lua_pushfstring(L, "'%s' expected, got '%s'",
1263 arg_type_names[(mask & ARGT_MASK)],
1264 arg_type_names[argp[idx].type & ARGT_MASK]);
1265 goto error;
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001266 }
1267
1268 /* Next argument. */
1269 mask >>= ARGT_BITS;
1270 idx++;
1271 }
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001272 return 0;
1273
1274 error:
Olivier Houchardca431612022-09-13 00:31:17 +02001275 argp[idx].type = ARGT_STOP;
Willy Tarreauee0d7272021-07-16 10:26:56 +02001276 free_args(argp);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001277 WILL_LJMP(luaL_argerror(L, first + idx, msg));
1278 return 0; /* Never reached */
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001279}
1280
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001281/*
Ilya Shipitsinc02a23f2020-05-06 00:53:22 +05001282 * The following functions are used to make correspondence between the the
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001283 * executed lua pointer and the "struct hlua *" that contain the context.
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001284 *
1285 * - hlua_gethlua : return the hlua context associated with an lua_State.
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001286 * - hlua_sethlua : create the association between hlua context and lua_state.
1287 */
1288static inline struct hlua *hlua_gethlua(lua_State *L)
1289{
Thierry FOURNIER38c5fd62015-03-10 02:40:29 +01001290 struct hlua **hlua = lua_getextraspace(L);
1291 return *hlua;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001292}
1293static inline void hlua_sethlua(struct hlua *hlua)
1294{
Thierry FOURNIER38c5fd62015-03-10 02:40:29 +01001295 struct hlua **hlua_store = lua_getextraspace(hlua->T);
1296 *hlua_store = hlua;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001297}
1298
Willy Tarreau0b7b6392022-06-19 17:39:33 +02001299/* Will return a non-NULL string indicating the Lua call trace if the caller
1300 * currently is executing from within a Lua function. One line per entry will
1301 * be emitted, and each extra line will be prefixed with <pfx>. If a current
1302 * Lua function is not detected, NULL is returned.
1303 */
1304const char *hlua_show_current_location(const char *pfx)
1305{
1306 lua_State *L;
1307 lua_Debug ar;
1308
1309 /* global or per-thread stack initializing ? */
1310 if (hlua_state_id != -1 && (L = hlua_states[hlua_state_id]) && lua_getstack(L, 0, &ar))
1311 return hlua_traceback(L, pfx);
1312
1313 /* per-thread stack running ? */
1314 if (hlua_states[tid + 1] && (L = hlua_states[tid + 1]) && lua_getstack(L, 0, &ar))
1315 return hlua_traceback(L, pfx);
1316
1317 /* global stack running ? */
1318 if (hlua_states[0] && (L = hlua_states[0]) && lua_getstack(L, 0, &ar))
1319 return hlua_traceback(L, pfx);
1320
1321 return NULL;
1322}
1323
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01001324/* This function is used to send logs. It try to send on screen (stderr)
1325 * and on the default syslog server.
1326 */
1327static inline void hlua_sendlog(struct proxy *px, int level, const char *msg)
1328{
1329 struct tm tm;
1330 char *p;
1331
1332 /* Cleanup the log message. */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001333 p = trash.area;
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01001334 for (; *msg != '\0'; msg++, p++) {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001335 if (p >= trash.area + trash.size - 1) {
Thierry FOURNIERccf00632015-09-16 12:47:03 +02001336 /* Break the message if exceed the buffer size. */
1337 *(p-4) = ' ';
1338 *(p-3) = '.';
1339 *(p-2) = '.';
1340 *(p-1) = '.';
1341 break;
1342 }
Willy Tarreau90807112020-02-25 08:16:33 +01001343 if (isprint((unsigned char)*msg))
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01001344 *p = *msg;
1345 else
1346 *p = '.';
1347 }
1348 *p = '\0';
1349
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001350 send_log(px, level, "%s\n", trash.area);
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01001351 if (!(global.mode & MODE_QUIET) || (global.mode & (MODE_VERBOSE | MODE_STARTING))) {
Christopher Fauletf98d8212020-10-02 18:13:52 +02001352 if (level == LOG_DEBUG && !(global.mode & MODE_DEBUG))
1353 return;
1354
Willy Tarreaua678b432015-08-28 10:14:59 +02001355 get_localtime(date.tv_sec, &tm);
1356 fprintf(stderr, "[%s] %03d/%02d%02d%02d (%d) : %s\n",
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01001357 log_levels[level], tm.tm_yday, tm.tm_hour, tm.tm_min, tm.tm_sec,
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001358 (int)getpid(), trash.area);
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01001359 fflush(stderr);
1360 }
1361}
1362
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001363/* This function just ensure that the yield will be always
1364 * returned with a timeout and permit to set some flags
1365 */
1366__LJMP void hlua_yieldk(lua_State *L, int nresults, int ctx,
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001367 lua_KFunction k, int timeout, unsigned int flags)
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001368{
Thierry Fournier4234dbd2020-11-28 13:18:23 +01001369 struct hlua *hlua;
1370
1371 /* Get hlua struct, or NULL if we execute from main lua state */
1372 hlua = hlua_gethlua(L);
1373 if (!hlua) {
1374 return;
1375 }
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001376
1377 /* Set the wake timeout. If timeout is required, we set
1378 * the expiration time.
1379 */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001380 hlua->wake_time = timeout;
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001381
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01001382 hlua->flags |= flags;
1383
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001384 /* Process the yield. */
Willy Tarreau9635e032018-10-16 17:52:55 +02001385 MAY_LJMP(lua_yieldk(L, nresults, ctx, k));
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001386}
1387
Willy Tarreau87b09662015-04-03 00:22:06 +02001388/* This function initialises the Lua environment stored in the stream.
1389 * It must be called at the start of the stream. This function creates
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001390 * an LUA coroutine. It can not be use to crete the main LUA context.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02001391 *
1392 * This function is particular. it initialises a new Lua thread. If the
1393 * initialisation fails (example: out of memory error), the lua function
1394 * throws an error (longjmp).
1395 *
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001396 * This function manipulates two Lua stacks: the main and the thread. Only
Thierry FOURNIERbabae282015-09-17 11:36:37 +02001397 * the main stack can fail. The thread is not manipulated. This function
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001398 * MUST NOT manipulate the created thread stack state, because it is not
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001399 * protected against errors thrown by the thread stack.
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001400 */
Aurelien DARRAGON6b0b9bd2023-03-21 14:02:16 +01001401int hlua_ctx_init(struct hlua *lua, int state_id, struct task *task)
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001402{
1403 lua->Mref = LUA_REFNIL;
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001404 lua->flags = 0;
Willy Tarreauf31af932020-01-14 09:59:38 +01001405 lua->gc_count = 0;
Christopher Fauletbc275a92020-02-26 14:55:16 +01001406 lua->wake_time = TICK_ETERNITY;
Thierry Fournier021d9862020-11-28 23:42:03 +01001407 lua->state_id = state_id;
Aurelien DARRAGONda9503c2022-11-25 09:10:07 +01001408 hlua_timer_init(&lua->timer, 0); /* default value, no timeout */
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01001409 LIST_INIT(&lua->com);
Aurelien DARRAGON3ffbf382023-02-09 17:02:57 +01001410 MT_LIST_INIT(&lua->hc_list);
Aurelien DARRAGON6b0b9bd2023-03-21 14:02:16 +01001411 if (!SET_SAFE_LJMP_PARENT(lua)) {
1412 lua->Tref = LUA_REFNIL;
1413 return 0;
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001414 }
Thierry Fournier021d9862020-11-28 23:42:03 +01001415 lua->T = lua_newthread(hlua_states[state_id]);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001416 if (!lua->T) {
1417 lua->Tref = LUA_REFNIL;
Aurelien DARRAGON6b0b9bd2023-03-21 14:02:16 +01001418 RESET_SAFE_LJMP_PARENT(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001419 return 0;
1420 }
1421 hlua_sethlua(lua);
Thierry Fournier021d9862020-11-28 23:42:03 +01001422 lua->Tref = luaL_ref(hlua_states[state_id], LUA_REGISTRYINDEX);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001423 lua->task = task;
Aurelien DARRAGON6b0b9bd2023-03-21 14:02:16 +01001424 RESET_SAFE_LJMP_PARENT(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001425 return 1;
1426}
1427
Aurelien DARRAGON3ffbf382023-02-09 17:02:57 +01001428/* kill all associated httpclient to this hlua task
1429 * We must take extra precautions as we're manipulating lua-exposed
1430 * objects without the main lua lock.
1431 */
William Lallemandbb581422022-10-20 10:57:28 +02001432static void hlua_httpclient_destroy_all(struct hlua *hlua)
1433{
Aurelien DARRAGON3ffbf382023-02-09 17:02:57 +01001434 struct hlua_httpclient *hlua_hc;
William Lallemandbb581422022-10-20 10:57:28 +02001435
Aurelien DARRAGON3ffbf382023-02-09 17:02:57 +01001436 /* use thread-safe accessors for hc_list since GC cycle initiated by
1437 * another thread sharing the same main lua stack (lua coroutine)
1438 * could execute hlua_httpclient_gc() on the hlua->hc_list items
1439 * in parallel: Lua GC applies on the main stack, it is not limited to
1440 * a single coroutine stack, see Github issue #2037 for reference.
1441 * Remember, coroutines created using lua_newthread() are not meant to
1442 * be thread safe in Lua. (From lua co-author:
1443 * http://lua-users.org/lists/lua-l/2011-07/msg00072.html)
1444 *
1445 * This security measure is superfluous when 'lua-load-per-thread' is used
1446 * since in this case coroutines exclusively run on the same thread
1447 * (main stack is not shared between OS threads).
1448 */
1449 while ((hlua_hc = MT_LIST_POP(&hlua->hc_list, typeof(hlua_hc), by_hlua))) {
1450 httpclient_stop_and_destroy(hlua_hc->hc);
William Lallemandbb581422022-10-20 10:57:28 +02001451 hlua_hc->hc = NULL;
William Lallemandbb581422022-10-20 10:57:28 +02001452 }
1453}
1454
1455
Willy Tarreau87b09662015-04-03 00:22:06 +02001456/* Used to destroy the Lua coroutine when the attached stream or task
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001457 * is destroyed. The destroy also the memory context. The struct "lua"
Aurelien DARRAGON60ab0f72023-03-01 16:45:50 +01001458 * will be freed.
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001459 */
1460void hlua_ctx_destroy(struct hlua *lua)
1461{
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01001462 if (!lua)
Thierry FOURNIERa718b292015-03-04 16:48:34 +01001463 return;
1464
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01001465 if (!lua->T)
1466 goto end;
1467
William Lallemandbb581422022-10-20 10:57:28 +02001468 /* clean all running httpclient */
1469 hlua_httpclient_destroy_all(lua);
1470
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01001471 /* Purge all the pending signals. */
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001472 notification_purge(&lua->com);
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01001473
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001474 if (!SET_SAFE_LJMP(lua))
Thierry FOURNIER75d02082017-07-12 13:41:33 +02001475 return;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001476 luaL_unref(lua->T, LUA_REGISTRYINDEX, lua->Mref);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001477 RESET_SAFE_LJMP(lua);
Thierry FOURNIER5a50a852015-09-23 16:59:28 +02001478
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001479 if (!SET_SAFE_LJMP_PARENT(lua))
Thierry FOURNIER75d02082017-07-12 13:41:33 +02001480 return;
Thierry Fournier021d9862020-11-28 23:42:03 +01001481 luaL_unref(hlua_states[lua->state_id], LUA_REGISTRYINDEX, lua->Tref);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001482 RESET_SAFE_LJMP_PARENT(lua);
Thierry FOURNIER5a50a852015-09-23 16:59:28 +02001483 /* Forces a garbage collecting process. If the Lua program is finished
1484 * without error, we run the GC on the thread pointer. Its freed all
1485 * the unused memory.
1486 * If the thread is finnish with an error or is currently yielded,
1487 * it seems that the GC applied on the thread doesn't clean anything,
1488 * so e run the GC on the main thread.
1489 * NOTE: maybe this action locks all the Lua threads untiml the en of
1490 * the garbage collection.
1491 */
Willy Tarreauf31af932020-01-14 09:59:38 +01001492 if (lua->gc_count) {
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001493 if (!SET_SAFE_LJMP_PARENT(lua))
Thierry FOURNIER75d02082017-07-12 13:41:33 +02001494 return;
Thierry Fournier021d9862020-11-28 23:42:03 +01001495 lua_gc(hlua_states[lua->state_id], LUA_GCCOLLECT, 0);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001496 RESET_SAFE_LJMP_PARENT(lua);
Thierry FOURNIER7c39ab42015-09-27 22:53:33 +02001497 }
Thierry FOURNIER5a50a852015-09-23 16:59:28 +02001498
Thierry FOURNIERa7b536b2015-09-21 22:50:24 +02001499 lua->T = NULL;
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01001500
1501end:
Willy Tarreaubafbe012017-11-24 17:34:44 +01001502 pool_free(pool_head_hlua, lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001503}
1504
1505/* This function is used to restore the Lua context when a coroutine
1506 * fails. This function copy the common memory between old coroutine
1507 * and the new coroutine. The old coroutine is destroyed, and its
1508 * replaced by the new coroutine.
1509 * If the flag "keep_msg" is set, the last entry of the old is assumed
1510 * as string error message and it is copied in the new stack.
1511 */
1512static int hlua_ctx_renew(struct hlua *lua, int keep_msg)
1513{
1514 lua_State *T;
1515 int new_ref;
1516
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001517 /* New Lua coroutine. */
Thierry Fournier021d9862020-11-28 23:42:03 +01001518 T = lua_newthread(hlua_states[lua->state_id]);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001519 if (!T)
1520 return 0;
1521
1522 /* Copy last error message. */
1523 if (keep_msg)
1524 lua_xmove(lua->T, T, 1);
1525
1526 /* Copy data between the coroutines. */
1527 lua_rawgeti(lua->T, LUA_REGISTRYINDEX, lua->Mref);
1528 lua_xmove(lua->T, T, 1);
Ilya Shipitsin46a030c2020-07-05 16:36:08 +05001529 new_ref = luaL_ref(T, LUA_REGISTRYINDEX); /* Value popped. */
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001530
1531 /* Destroy old data. */
1532 luaL_unref(lua->T, LUA_REGISTRYINDEX, lua->Mref);
1533
1534 /* The thread is garbage collected by Lua. */
Thierry Fournier021d9862020-11-28 23:42:03 +01001535 luaL_unref(hlua_states[lua->state_id], LUA_REGISTRYINDEX, lua->Tref);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001536
1537 /* Fill the struct with the new coroutine values. */
1538 lua->Mref = new_ref;
1539 lua->T = T;
Thierry Fournier021d9862020-11-28 23:42:03 +01001540 lua->Tref = luaL_ref(hlua_states[lua->state_id], LUA_REGISTRYINDEX);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001541
1542 /* Set context. */
1543 hlua_sethlua(lua);
1544
1545 return 1;
1546}
1547
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001548void hlua_hook(lua_State *L, lua_Debug *ar)
1549{
Thierry Fournier4234dbd2020-11-28 13:18:23 +01001550 struct hlua *hlua;
1551
1552 /* Get hlua struct, or NULL if we execute from main lua state */
1553 hlua = hlua_gethlua(L);
1554 if (!hlua)
1555 return;
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001556
1557 /* Lua cannot yield when its returning from a function,
1558 * so, we can fix the interrupt hook to 1 instruction,
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001559 * expecting that the function is finished.
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001560 */
1561 if (lua_gethookmask(L) & LUA_MASKRET) {
1562 lua_sethook(hlua->T, hlua_hook, LUA_MASKCOUNT, 1);
1563 return;
1564 }
1565
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001566 /* If we interrupt the Lua processing in yieldable state, we yield.
1567 * If the state is not yieldable, trying yield causes an error.
1568 */
Aurelien DARRAGON0ebd41f2022-11-24 09:51:40 +01001569 if (lua_isyieldable(L)) {
1570 /* note: for converters/fetches.. where yielding is not allowed
1571 * hlua_ctx_resume() will simply perform a goto resume_execution
1572 * instead of rescheduling hlua->task.
1573 * also: hlua_ctx_resume() will take care of checking execution
1574 * timeout and re-applying the hook as needed.
1575 */
Willy Tarreau9635e032018-10-16 17:52:55 +02001576 MAY_LJMP(hlua_yieldk(L, 0, 0, NULL, TICK_ETERNITY, HLUA_CTRLYIELD));
Aurelien DARRAGON0ebd41f2022-11-24 09:51:40 +01001577 /* lua docs says that the hook should return immediately after lua_yieldk
1578 *
1579 * From: https://www.lua.org/manual/5.3/manual.html#lua_yieldk
1580 *
1581 * Moreover, it seems that we don't want to continue after the yield
1582 * because the end of the function is about handling unyieldable function,
1583 * which is not the case here.
1584 *
1585 * ->if we don't return lua_sethook gets incorrectly set with MASKRET later
1586 * in the function.
1587 */
1588 return;
1589 }
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001590
Aurelien DARRAGONda9503c2022-11-25 09:10:07 +01001591 /* If we cannot yield, check the timeout. */
1592 if (!hlua_timer_check(&hlua->timer)) {
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001593 lua_pushfstring(L, "execution timeout");
1594 WILL_LJMP(lua_error(L));
1595 }
1596
1597 /* Try to interrupt the process at the end of the current
1598 * unyieldable function.
1599 */
1600 lua_sethook(hlua->T, hlua_hook, LUA_MASKRET|LUA_MASKCOUNT, hlua_nb_instruction);
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001601}
1602
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001603/* This function start or resumes the Lua stack execution. If the flag
1604 * "yield_allowed" if no set and the LUA stack execution returns a yield
1605 * The function return an error.
1606 *
1607 * The function can returns 4 values:
1608 * - HLUA_E_OK : The execution is terminated without any errors.
1609 * - HLUA_E_AGAIN : The execution must continue at the next associated
1610 * task wakeup.
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001611 * - HLUA_E_ERRMSG : An error has occurred, an error message is set in
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001612 * the top of the stack.
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001613 * - HLUA_E_ERR : An error has occurred without error message.
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001614 *
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001615 * If an error occurred, the stack is renewed and it is ready to run new
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001616 * LUA code.
1617 */
1618static enum hlua_exec hlua_ctx_resume(struct hlua *lua, int yield_allowed)
1619{
Christopher Faulet08ed98f2020-07-28 10:33:25 +02001620#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM >= 504
1621 int nres;
1622#endif
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001623 int ret;
1624 const char *msg;
Thierry FOURNIERfc044c92018-06-07 14:40:48 +02001625 const char *trace;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001626
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +02001627 /* Lock the whole Lua execution. This lock must be before the
1628 * label "resume_execution".
1629 */
Aurelien DARRAGONe36f8032023-03-21 13:22:33 +01001630 hlua_lock(lua);
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +02001631
Aurelien DARRAGONda9503c2022-11-25 09:10:07 +01001632 /* reset the timer as we might be re-entering the function to
1633 * resume the coroutine after a successful yield
1634 * (cumulative time will be updated)
1635 */
1636 hlua_timer_reset(&lua->timer);
1637
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001638resume_execution:
1639
1640 /* This hook interrupts the Lua processing each 'hlua_nb_instruction'
1641 * instructions. it is used for preventing infinite loops.
1642 */
1643 lua_sethook(lua->T, hlua_hook, LUA_MASKCOUNT, hlua_nb_instruction);
1644
Thierry FOURNIER1bfc09b2015-03-05 17:10:14 +01001645 /* Remove all flags except the running flags. */
Thierry FOURNIER2f3867f2015-09-28 01:02:01 +02001646 HLUA_SET_RUN(lua);
1647 HLUA_CLR_CTRLYIELD(lua);
1648 HLUA_CLR_WAKERESWR(lua);
1649 HLUA_CLR_WAKEREQWR(lua);
Christopher Faulet1f43a342021-08-04 17:58:21 +02001650 HLUA_CLR_NOYIELD(lua);
1651 if (!yield_allowed)
1652 HLUA_SET_NOYIELD(lua);
Thierry FOURNIER1bfc09b2015-03-05 17:10:14 +01001653
Aurelien DARRAGONda9503c2022-11-25 09:10:07 +01001654 /* reset wake_time. */
Christopher Fauletbc275a92020-02-26 14:55:16 +01001655 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001656
Aurelien DARRAGONda9503c2022-11-25 09:10:07 +01001657 /* start the timer as we're about to start lua processing */
1658 hlua_timer_start(&lua->timer);
1659
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001660 /* Call the function. */
Christopher Faulet08ed98f2020-07-28 10:33:25 +02001661#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM >= 504
Thierry Fournier021d9862020-11-28 23:42:03 +01001662 ret = lua_resume(lua->T, hlua_states[lua->state_id], lua->nargs, &nres);
Christopher Faulet08ed98f2020-07-28 10:33:25 +02001663#else
Thierry Fournier021d9862020-11-28 23:42:03 +01001664 ret = lua_resume(lua->T, hlua_states[lua->state_id], lua->nargs);
Christopher Faulet08ed98f2020-07-28 10:33:25 +02001665#endif
Aurelien DARRAGONda9503c2022-11-25 09:10:07 +01001666
1667 /* out of lua processing, stop the timer */
1668 hlua_timer_stop(&lua->timer);
1669
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001670 switch (ret) {
1671
1672 case LUA_OK:
1673 ret = HLUA_E_OK;
1674 break;
1675
1676 case LUA_YIELD:
Aurelien DARRAGONda9503c2022-11-25 09:10:07 +01001677 /* Check if the execution timeout is expired. If it is the case, we
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001678 * break the Lua execution.
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001679 */
Aurelien DARRAGONda9503c2022-11-25 09:10:07 +01001680 if (!hlua_timer_check(&lua->timer)) {
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001681 lua_settop(lua->T, 0); /* Empty the stack. */
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001682 ret = HLUA_E_ETMOUT;
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001683 break;
1684 }
1685 /* Process the forced yield. if the general yield is not allowed or
1686 * if no task were associated this the current Lua execution
1687 * coroutine, we resume the execution. Else we want to return in the
1688 * scheduler and we want to be waked up again, to continue the
1689 * current Lua execution. So we schedule our own task.
1690 */
1691 if (HLUA_IS_CTRLYIELDING(lua)) {
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001692 if (!yield_allowed || !lua->task)
1693 goto resume_execution;
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001694 task_wakeup(lua->task, TASK_WOKEN_MSG);
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001695 }
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001696 if (!yield_allowed) {
1697 lua_settop(lua->T, 0); /* Empty the stack. */
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001698 ret = HLUA_E_YIELD;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001699 break;
1700 }
1701 ret = HLUA_E_AGAIN;
1702 break;
1703
1704 case LUA_ERRRUN:
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001705
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001706 /* Special exit case. The traditional exit is returned as an error
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001707 * because the errors ares the only one mean to return immediately
1708 * from and lua execution.
1709 */
1710 if (lua->flags & HLUA_EXIT) {
1711 ret = HLUA_E_OK;
Christopher Faulet7716cdf2020-01-29 11:53:30 +01001712 hlua_ctx_renew(lua, 1);
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001713 break;
1714 }
1715
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001716 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001717 if (!lua_checkstack(lua->T, 1)) {
1718 ret = HLUA_E_ERR;
1719 break;
1720 }
1721 msg = lua_tostring(lua->T, -1);
1722 lua_settop(lua->T, 0); /* Empty the stack. */
1723 lua_pop(lua->T, 1);
Christopher Fauletd09cc512021-03-24 14:48:45 +01001724 trace = hlua_traceback(lua->T, ", ");
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001725 if (msg)
Thierry Fournier46278ff2020-11-29 11:48:12 +01001726 lua_pushfstring(lua->T, "[state-id %d] runtime error: %s from %s", lua->state_id, msg, trace);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001727 else
Thierry Fournier46278ff2020-11-29 11:48:12 +01001728 lua_pushfstring(lua->T, "[state-id %d] unknown runtime error from %s", lua->state_id, trace);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001729 ret = HLUA_E_ERRMSG;
1730 break;
1731
1732 case LUA_ERRMEM:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001733 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001734 lua_settop(lua->T, 0); /* Empty the stack. */
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001735 ret = HLUA_E_NOMEM;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001736 break;
1737
1738 case LUA_ERRERR:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001739 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001740 if (!lua_checkstack(lua->T, 1)) {
1741 ret = HLUA_E_ERR;
1742 break;
1743 }
1744 msg = lua_tostring(lua->T, -1);
1745 lua_settop(lua->T, 0); /* Empty the stack. */
1746 lua_pop(lua->T, 1);
1747 if (msg)
Thierry Fournier46278ff2020-11-29 11:48:12 +01001748 lua_pushfstring(lua->T, "[state-id %d] message handler error: %s", lua->state_id, msg);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001749 else
Thierry Fournier46278ff2020-11-29 11:48:12 +01001750 lua_pushfstring(lua->T, "[state-id %d] message handler error", lua->state_id);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001751 ret = HLUA_E_ERRMSG;
1752 break;
1753
1754 default:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001755 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001756 lua_settop(lua->T, 0); /* Empty the stack. */
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001757 ret = HLUA_E_ERR;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001758 break;
1759 }
1760
1761 switch (ret) {
1762 case HLUA_E_AGAIN:
1763 break;
1764
1765 case HLUA_E_ERRMSG:
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001766 notification_purge(&lua->com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001767 hlua_ctx_renew(lua, 1);
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001768 HLUA_CLR_RUN(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001769 break;
1770
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001771 case HLUA_E_ETMOUT:
1772 case HLUA_E_NOMEM:
1773 case HLUA_E_YIELD:
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001774 case HLUA_E_ERR:
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001775 HLUA_CLR_RUN(lua);
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001776 notification_purge(&lua->com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001777 hlua_ctx_renew(lua, 0);
1778 break;
1779
1780 case HLUA_E_OK:
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001781 HLUA_CLR_RUN(lua);
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001782 notification_purge(&lua->com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001783 break;
1784 }
1785
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +02001786 /* This is the main exit point, remove the Lua lock. */
Aurelien DARRAGONe36f8032023-03-21 13:22:33 +01001787 hlua_unlock(lua);
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +02001788
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001789 return ret;
1790}
1791
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001792/* This function exit the current code. */
1793__LJMP static int hlua_done(lua_State *L)
1794{
Thierry Fournier4234dbd2020-11-28 13:18:23 +01001795 struct hlua *hlua;
1796
1797 /* Get hlua struct, or NULL if we execute from main lua state */
1798 hlua = hlua_gethlua(L);
1799 if (!hlua)
1800 return 0;
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001801
1802 hlua->flags |= HLUA_EXIT;
1803 WILL_LJMP(lua_error(L));
1804
1805 return 0;
1806}
1807
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001808/* This function is an LUA binding. It provides a function
1809 * for deleting ACL from a referenced ACL file.
1810 */
1811__LJMP static int hlua_del_acl(lua_State *L)
1812{
1813 const char *name;
1814 const char *key;
1815 struct pat_ref *ref;
1816
1817 MAY_LJMP(check_args(L, 2, "del_acl"));
1818
1819 name = MAY_LJMP(luaL_checkstring(L, 1));
1820 key = MAY_LJMP(luaL_checkstring(L, 2));
1821
1822 ref = pat_ref_lookup(name);
1823 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001824 WILL_LJMP(luaL_error(L, "'del_acl': unknown acl file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001825
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001826 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001827 pat_ref_delete(ref, key);
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001828 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001829 return 0;
1830}
1831
1832/* This function is an LUA binding. It provides a function
1833 * for deleting map entry from a referenced map file.
1834 */
1835static int hlua_del_map(lua_State *L)
1836{
1837 const char *name;
1838 const char *key;
1839 struct pat_ref *ref;
1840
1841 MAY_LJMP(check_args(L, 2, "del_map"));
1842
1843 name = MAY_LJMP(luaL_checkstring(L, 1));
1844 key = MAY_LJMP(luaL_checkstring(L, 2));
1845
1846 ref = pat_ref_lookup(name);
1847 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001848 WILL_LJMP(luaL_error(L, "'del_map': unknown acl file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001849
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001850 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001851 pat_ref_delete(ref, key);
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001852 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001853 return 0;
1854}
1855
1856/* This function is an LUA binding. It provides a function
1857 * for adding ACL pattern from a referenced ACL file.
1858 */
1859static int hlua_add_acl(lua_State *L)
1860{
1861 const char *name;
1862 const char *key;
1863 struct pat_ref *ref;
1864
1865 MAY_LJMP(check_args(L, 2, "add_acl"));
1866
1867 name = MAY_LJMP(luaL_checkstring(L, 1));
1868 key = MAY_LJMP(luaL_checkstring(L, 2));
1869
1870 ref = pat_ref_lookup(name);
1871 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001872 WILL_LJMP(luaL_error(L, "'add_acl': unknown acl file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001873
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001874 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001875 if (pat_ref_find_elt(ref, key) == NULL)
1876 pat_ref_add(ref, key, NULL, NULL);
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001877 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001878 return 0;
1879}
1880
1881/* This function is an LUA binding. It provides a function
1882 * for setting map pattern and sample from a referenced map
1883 * file.
1884 */
1885static int hlua_set_map(lua_State *L)
1886{
1887 const char *name;
1888 const char *key;
1889 const char *value;
1890 struct pat_ref *ref;
1891
1892 MAY_LJMP(check_args(L, 3, "set_map"));
1893
1894 name = MAY_LJMP(luaL_checkstring(L, 1));
1895 key = MAY_LJMP(luaL_checkstring(L, 2));
1896 value = MAY_LJMP(luaL_checkstring(L, 3));
1897
1898 ref = pat_ref_lookup(name);
1899 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001900 WILL_LJMP(luaL_error(L, "'set_map': unknown map file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001901
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001902 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001903 if (pat_ref_find_elt(ref, key) != NULL)
1904 pat_ref_set(ref, key, value, NULL);
1905 else
1906 pat_ref_add(ref, key, value, NULL);
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001907 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001908 return 0;
1909}
1910
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01001911/* A class is a lot of memory that contain data. This data can be a table,
1912 * an integer or user data. This data is associated with a metatable. This
Ilya Shipitsinc02a23f2020-05-06 00:53:22 +05001913 * metatable have an original version registered in the global context with
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01001914 * the name of the object (_G[<name>] = <metable> ).
1915 *
1916 * A metable is a table that modify the standard behavior of a standard
1917 * access to the associated data. The entries of this new metatable are
1918 * defined as is:
1919 *
1920 * http://lua-users.org/wiki/MetatableEvents
1921 *
1922 * __index
1923 *
1924 * we access an absent field in a table, the result is nil. This is
1925 * true, but it is not the whole truth. Actually, such access triggers
1926 * the interpreter to look for an __index metamethod: If there is no
1927 * such method, as usually happens, then the access results in nil;
1928 * otherwise, the metamethod will provide the result.
1929 *
1930 * Control 'prototype' inheritance. When accessing "myTable[key]" and
1931 * the key does not appear in the table, but the metatable has an __index
1932 * property:
1933 *
1934 * - if the value is a function, the function is called, passing in the
1935 * table and the key; the return value of that function is returned as
1936 * the result.
1937 *
1938 * - if the value is another table, the value of the key in that table is
1939 * asked for and returned (and if it doesn't exist in that table, but that
1940 * table's metatable has an __index property, then it continues on up)
1941 *
1942 * - Use "rawget(myTable,key)" to skip this metamethod.
1943 *
1944 * http://www.lua.org/pil/13.4.1.html
1945 *
1946 * __newindex
1947 *
1948 * Like __index, but control property assignment.
1949 *
1950 * __mode - Control weak references. A string value with one or both
1951 * of the characters 'k' and 'v' which specifies that the the
1952 * keys and/or values in the table are weak references.
1953 *
1954 * __call - Treat a table like a function. When a table is followed by
1955 * parenthesis such as "myTable( 'foo' )" and the metatable has
1956 * a __call key pointing to a function, that function is invoked
1957 * (passing any specified arguments) and the return value is
1958 * returned.
1959 *
1960 * __metatable - Hide the metatable. When "getmetatable( myTable )" is
1961 * called, if the metatable for myTable has a __metatable
1962 * key, the value of that key is returned instead of the
1963 * actual metatable.
1964 *
1965 * __tostring - Control string representation. When the builtin
1966 * "tostring( myTable )" function is called, if the metatable
1967 * for myTable has a __tostring property set to a function,
1968 * that function is invoked (passing myTable to it) and the
1969 * return value is used as the string representation.
1970 *
1971 * __len - Control table length. When the table length is requested using
1972 * the length operator ( '#' ), if the metatable for myTable has
1973 * a __len key pointing to a function, that function is invoked
1974 * (passing myTable to it) and the return value used as the value
1975 * of "#myTable".
1976 *
1977 * __gc - Userdata finalizer code. When userdata is set to be garbage
1978 * collected, if the metatable has a __gc field pointing to a
1979 * function, that function is first invoked, passing the userdata
1980 * to it. The __gc metamethod is not called for tables.
1981 * (See http://lua-users.org/lists/lua-l/2006-11/msg00508.html)
1982 *
1983 * Special metamethods for redefining standard operators:
1984 * http://www.lua.org/pil/13.1.html
1985 *
1986 * __add "+"
1987 * __sub "-"
1988 * __mul "*"
1989 * __div "/"
1990 * __unm "!"
1991 * __pow "^"
1992 * __concat ".."
1993 *
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001994 * Special methods for redefining standard relations
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01001995 * http://www.lua.org/pil/13.2.html
1996 *
1997 * __eq "=="
1998 * __lt "<"
1999 * __le "<="
2000 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002001
2002/*
2003 *
2004 *
Thierry FOURNIER3def3932015-04-07 11:27:54 +02002005 * Class Map
2006 *
2007 *
2008 */
2009
2010/* Returns a struct hlua_map if the stack entry "ud" is
2011 * a class session, otherwise it throws an error.
2012 */
2013__LJMP static struct map_descriptor *hlua_checkmap(lua_State *L, int ud)
2014{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02002015 return MAY_LJMP(hlua_checkudata(L, ud, class_map_ref));
Thierry FOURNIER3def3932015-04-07 11:27:54 +02002016}
2017
2018/* This function is the map constructor. It don't need
2019 * the class Map object. It creates and return a new Map
2020 * object. It must be called only during "body" or "init"
2021 * context because it process some filesystem accesses.
2022 */
2023__LJMP static int hlua_map_new(struct lua_State *L)
2024{
2025 const char *fn;
2026 int match = PAT_MATCH_STR;
2027 struct sample_conv conv;
2028 const char *file = "";
2029 int line = 0;
2030 lua_Debug ar;
2031 char *err = NULL;
2032 struct arg args[2];
2033
2034 if (lua_gettop(L) < 1 || lua_gettop(L) > 2)
2035 WILL_LJMP(luaL_error(L, "'new' needs at least 1 argument."));
2036
2037 fn = MAY_LJMP(luaL_checkstring(L, 1));
2038
2039 if (lua_gettop(L) >= 2) {
2040 match = MAY_LJMP(luaL_checkinteger(L, 2));
2041 if (match < 0 || match >= PAT_MATCH_NUM)
2042 WILL_LJMP(luaL_error(L, "'new' needs a valid match method."));
2043 }
2044
2045 /* Get Lua filename and line number. */
2046 if (lua_getstack(L, 1, &ar)) { /* check function at level */
2047 lua_getinfo(L, "Sl", &ar); /* get info about it */
2048 if (ar.currentline > 0) { /* is there info? */
2049 file = ar.short_src;
2050 line = ar.currentline;
2051 }
2052 }
2053
2054 /* fill fake sample_conv struct. */
2055 conv.kw = ""; /* unused. */
2056 conv.process = NULL; /* unused. */
2057 conv.arg_mask = 0; /* unused. */
2058 conv.val_args = NULL; /* unused. */
2059 conv.out_type = SMP_T_STR;
2060 conv.private = (void *)(long)match;
2061 switch (match) {
2062 case PAT_MATCH_STR: conv.in_type = SMP_T_STR; break;
2063 case PAT_MATCH_BEG: conv.in_type = SMP_T_STR; break;
2064 case PAT_MATCH_SUB: conv.in_type = SMP_T_STR; break;
2065 case PAT_MATCH_DIR: conv.in_type = SMP_T_STR; break;
2066 case PAT_MATCH_DOM: conv.in_type = SMP_T_STR; break;
2067 case PAT_MATCH_END: conv.in_type = SMP_T_STR; break;
2068 case PAT_MATCH_REG: conv.in_type = SMP_T_STR; break;
Thierry FOURNIER07ee64e2015-07-06 23:43:03 +02002069 case PAT_MATCH_INT: conv.in_type = SMP_T_SINT; break;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02002070 case PAT_MATCH_IP: conv.in_type = SMP_T_ADDR; break;
2071 default:
2072 WILL_LJMP(luaL_error(L, "'new' doesn't support this match mode."));
2073 }
2074
2075 /* fill fake args. */
2076 args[0].type = ARGT_STR;
Christopher Faulet73292e92020-08-06 08:40:09 +02002077 args[0].data.str.area = strdup(fn);
2078 args[0].data.str.data = strlen(fn);
2079 args[0].data.str.size = args[0].data.str.data+1;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02002080 args[1].type = ARGT_STOP;
2081
2082 /* load the map. */
2083 if (!sample_load_map(args, &conv, file, line, &err)) {
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +05002084 /* error case: we can't use luaL_error because we must
Thierry FOURNIER3def3932015-04-07 11:27:54 +02002085 * free the err variable.
2086 */
2087 luaL_where(L, 1);
2088 lua_pushfstring(L, "'new': %s.", err);
2089 lua_concat(L, 2);
2090 free(err);
Christopher Faulet6ad7df42020-08-07 11:45:18 +02002091 chunk_destroy(&args[0].data.str);
Thierry FOURNIER3def3932015-04-07 11:27:54 +02002092 WILL_LJMP(lua_error(L));
2093 }
2094
2095 /* create the lua object. */
2096 lua_newtable(L);
2097 lua_pushlightuserdata(L, args[0].data.map);
2098 lua_rawseti(L, -2, 0);
2099
2100 /* Pop a class Map metatable and affect it to the userdata. */
2101 lua_rawgeti(L, LUA_REGISTRYINDEX, class_map_ref);
2102 lua_setmetatable(L, -2);
2103
2104
2105 return 1;
2106}
2107
2108__LJMP static inline int _hlua_map_lookup(struct lua_State *L, int str)
2109{
2110 struct map_descriptor *desc;
2111 struct pattern *pat;
2112 struct sample smp;
2113
2114 MAY_LJMP(check_args(L, 2, "lookup"));
2115 desc = MAY_LJMP(hlua_checkmap(L, 1));
Thierry FOURNIER07ee64e2015-07-06 23:43:03 +02002116 if (desc->pat.expect_type == SMP_T_SINT) {
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02002117 smp.data.type = SMP_T_SINT;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +02002118 smp.data.u.sint = MAY_LJMP(luaL_checkinteger(L, 2));
Thierry FOURNIER3def3932015-04-07 11:27:54 +02002119 }
2120 else {
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02002121 smp.data.type = SMP_T_STR;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02002122 smp.flags = SMP_F_CONST;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02002123 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 +01002124 smp.data.u.str.size = smp.data.u.str.data + 1;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02002125 }
2126
2127 pat = pattern_exec_match(&desc->pat, &smp, 1);
Thierry FOURNIER503bb092015-08-19 08:35:43 +02002128 if (!pat || !pat->data) {
Thierry FOURNIER3def3932015-04-07 11:27:54 +02002129 if (str)
2130 lua_pushstring(L, "");
2131 else
2132 lua_pushnil(L);
2133 return 1;
2134 }
2135
2136 /* The Lua pattern must return a string, so we can't check the returned type */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02002137 lua_pushlstring(L, pat->data->u.str.area, pat->data->u.str.data);
Thierry FOURNIER3def3932015-04-07 11:27:54 +02002138 return 1;
2139}
2140
2141__LJMP static int hlua_map_lookup(struct lua_State *L)
2142{
2143 return _hlua_map_lookup(L, 0);
2144}
2145
2146__LJMP static int hlua_map_slookup(struct lua_State *L)
2147{
2148 return _hlua_map_lookup(L, 1);
2149}
2150
2151/*
2152 *
2153 *
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002154 * Class Socket
2155 *
2156 *
2157 */
2158
2159__LJMP static struct hlua_socket *hlua_checksocket(lua_State *L, int ud)
2160{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02002161 return MAY_LJMP(hlua_checkudata(L, ud, class_socket_ref));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002162}
2163
2164/* This function is the handler called for each I/O on the established
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002165 * connection. It is used for notify space available to send or data
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002166 * received.
2167 */
Willy Tarreau00a37f02015-04-13 12:05:19 +02002168static void hlua_socket_handler(struct appctx *appctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002169{
Willy Tarreau5321da92022-05-06 11:57:34 +02002170 struct hlua_csk_ctx *ctx = appctx->svcctx;
Willy Tarreauc12b3212022-05-27 11:08:15 +02002171 struct stconn *sc = appctx_sc(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002172
Christopher Faulet31572222023-03-31 11:13:48 +02002173 if (unlikely(se_fl_test(appctx->sedesc, (SE_FL_EOS|SE_FL_ERROR|SE_FL_SHR|SE_FL_SHW)))) {
2174 notification_wake(&ctx->wake_on_read);
2175 notification_wake(&ctx->wake_on_write);
2176 return;
2177 }
2178
Willy Tarreau5321da92022-05-06 11:57:34 +02002179 if (ctx->die) {
Christopher Faulet31572222023-03-31 11:13:48 +02002180 se_fl_set(appctx->sedesc, SE_FL_EOI|SE_FL_EOS);
Willy Tarreau5321da92022-05-06 11:57:34 +02002181 notification_wake(&ctx->wake_on_read);
2182 notification_wake(&ctx->wake_on_write);
Christopher Faulet31572222023-03-31 11:13:48 +02002183 return;
Thierry FOURNIERb13b20a2017-07-16 20:48:54 +02002184 }
2185
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +05002186 /* If we can't write, wakeup the pending write signals. */
Willy Tarreau3e7be362022-05-27 10:35:27 +02002187 if (channel_output_closed(sc_ic(sc)))
Willy Tarreau5321da92022-05-06 11:57:34 +02002188 notification_wake(&ctx->wake_on_write);
Thierry FOURNIER6d695e62015-09-27 19:29:38 +02002189
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +05002190 /* If we can't read, wakeup the pending read signals. */
Willy Tarreau3e7be362022-05-27 10:35:27 +02002191 if (channel_input_closed(sc_oc(sc)))
Willy Tarreau5321da92022-05-06 11:57:34 +02002192 notification_wake(&ctx->wake_on_read);
Thierry FOURNIER6d695e62015-09-27 19:29:38 +02002193
Willy Tarreau5a0b25d2019-07-18 18:01:14 +02002194 /* if the connection is not established, inform the stream that we want
Thierry FOURNIER316e3192015-09-04 18:25:53 +02002195 * to be notified whenever the connection completes.
2196 */
Willy Tarreau3e7be362022-05-27 10:35:27 +02002197 if (sc_opposite(sc)->state < SC_ST_EST) {
Willy Tarreau90e8b452022-05-25 18:21:43 +02002198 applet_need_more_data(appctx);
Willy Tarreaub23edc82022-05-24 16:49:03 +02002199 se_need_remote_conn(appctx->sedesc);
Willy Tarreau4164eb92022-05-25 15:42:03 +02002200 applet_have_more_data(appctx);
Willy Tarreaud4da1962015-04-20 01:31:23 +02002201 return;
Thierry FOURNIER316e3192015-09-04 18:25:53 +02002202 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002203
2204 /* This function is called after the connect. */
Willy Tarreau5321da92022-05-06 11:57:34 +02002205 ctx->connected = 1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002206
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002207 /* Wake the tasks which wants to write if the buffer have available space. */
Willy Tarreau3e7be362022-05-27 10:35:27 +02002208 if (channel_may_recv(sc_ic(sc)))
Willy Tarreau5321da92022-05-06 11:57:34 +02002209 notification_wake(&ctx->wake_on_write);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002210
2211 /* Wake the tasks which wants to read if the buffer contains data. */
Willy Tarreau3e7be362022-05-27 10:35:27 +02002212 if (!channel_is_empty(sc_oc(sc)))
Willy Tarreau5321da92022-05-06 11:57:34 +02002213 notification_wake(&ctx->wake_on_read);
Thierry FOURNIER101b9762018-05-27 01:27:40 +02002214
Thierry FOURNIER101b9762018-05-27 01:27:40 +02002215 /* If write notifications are registered, we considers we want
Willy Tarreau3367d412018-11-15 10:57:41 +01002216 * to write, so we clear the blocking flag.
Thierry FOURNIER101b9762018-05-27 01:27:40 +02002217 */
Willy Tarreau5321da92022-05-06 11:57:34 +02002218 if (notification_registered(&ctx->wake_on_write))
Willy Tarreau4164eb92022-05-25 15:42:03 +02002219 applet_have_more_data(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002220}
2221
Christopher Faulet5f35a3e2022-05-12 15:31:05 +02002222static int hlua_socket_init(struct appctx *appctx)
2223{
2224 struct hlua_csk_ctx *ctx = appctx->svcctx;
2225 struct stream *s;
2226
2227 if (appctx_finalize_startup(appctx, socket_proxy, &BUF_NULL) == -1)
2228 goto error;
2229
2230 s = appctx_strm(appctx);
2231
Willy Tarreau4596fe22022-05-17 19:07:51 +02002232 /* Configure "right" stream connector. This stconn is used to connect
Christopher Faulet5f35a3e2022-05-12 15:31:05 +02002233 * and retrieve data from the server. The connection is initialized
2234 * with the "struct server".
2235 */
Willy Tarreau74568cf2022-05-27 09:03:30 +02002236 sc_set_state(s->scb, SC_ST_ASS);
Christopher Faulet5f35a3e2022-05-12 15:31:05 +02002237
2238 /* Force destination server. */
2239 s->flags |= SF_DIRECT | SF_ASSIGNED | SF_BE_ASSIGNED;
2240 s->target = &socket_tcp->obj_type;
2241
2242 ctx->appctx = appctx;
2243 return 0;
2244
2245 error:
2246 return -1;
2247}
2248
Willy Tarreau87b09662015-04-03 00:22:06 +02002249/* This function is called when the "struct stream" is destroyed.
2250 * Remove the link from the object to this stream.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002251 * Wake all the pending signals.
2252 */
Willy Tarreau00a37f02015-04-13 12:05:19 +02002253static void hlua_socket_release(struct appctx *appctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002254{
Willy Tarreau5321da92022-05-06 11:57:34 +02002255 struct hlua_csk_ctx *ctx = appctx->svcctx;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002256 struct xref *peer;
2257
Christopher Faulet5f35a3e2022-05-12 15:31:05 +02002258 /* Remove my link in the original objects. */
Willy Tarreau5321da92022-05-06 11:57:34 +02002259 peer = xref_get_peer_and_lock(&ctx->xref);
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002260 if (peer)
Willy Tarreau5321da92022-05-06 11:57:34 +02002261 xref_disconnect(&ctx->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002262
2263 /* Wake all the task waiting for me. */
Willy Tarreau5321da92022-05-06 11:57:34 +02002264 notification_wake(&ctx->wake_on_read);
2265 notification_wake(&ctx->wake_on_write);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002266}
2267
2268/* If the garbage collectio of the object is launch, nobody
Willy Tarreau87b09662015-04-03 00:22:06 +02002269 * uses this object. If the stream does not exists, just quit.
2270 * Send the shutdown signal to the stream. In some cases,
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002271 * pending signal can rest in the read and write lists. destroy
2272 * it.
2273 */
2274__LJMP static int hlua_socket_gc(lua_State *L)
2275{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002276 struct hlua_socket *socket;
Willy Tarreau5321da92022-05-06 11:57:34 +02002277 struct hlua_csk_ctx *ctx;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002278 struct xref *peer;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002279
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002280 MAY_LJMP(check_args(L, 1, "__gc"));
2281
2282 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002283 peer = xref_get_peer_and_lock(&socket->xref);
2284 if (!peer)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002285 return 0;
Willy Tarreau5321da92022-05-06 11:57:34 +02002286
2287 ctx = container_of(peer, struct hlua_csk_ctx, xref);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002288
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002289 /* Set the flag which destroy the session. */
Willy Tarreau5321da92022-05-06 11:57:34 +02002290 ctx->die = 1;
2291 appctx_wakeup(ctx->appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002292
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002293 /* Remove all reference between the Lua stack and the coroutine stream. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002294 xref_disconnect(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002295 return 0;
2296}
2297
2298/* The close function send shutdown signal and break the
Willy Tarreau87b09662015-04-03 00:22:06 +02002299 * links between the stream and the object.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002300 */
sada05ed3302018-05-11 11:48:18 -07002301__LJMP static int hlua_socket_close_helper(lua_State *L)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002302{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002303 struct hlua_socket *socket;
Willy Tarreau5321da92022-05-06 11:57:34 +02002304 struct hlua_csk_ctx *ctx;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002305 struct xref *peer;
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002306 struct hlua *hlua;
2307
2308 /* Get hlua struct, or NULL if we execute from main lua state */
2309 hlua = hlua_gethlua(L);
2310 if (!hlua)
2311 return 0;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002312
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002313 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002314
2315 /* Check if we run on the same thread than the xreator thread.
2316 * We cannot access to the socket if the thread is different.
2317 */
2318 if (socket->tid != tid)
2319 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2320
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002321 peer = xref_get_peer_and_lock(&socket->xref);
2322 if (!peer)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002323 return 0;
Willy Tarreauf31af932020-01-14 09:59:38 +01002324
2325 hlua->gc_count--;
Willy Tarreau5321da92022-05-06 11:57:34 +02002326 ctx = container_of(peer, struct hlua_csk_ctx, xref);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002327
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002328 /* Set the flag which destroy the session. */
Willy Tarreau5321da92022-05-06 11:57:34 +02002329 ctx->die = 1;
2330 appctx_wakeup(ctx->appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002331
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002332 /* Remove all reference between the Lua stack and the coroutine stream. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002333 xref_disconnect(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002334 return 0;
2335}
2336
sada05ed3302018-05-11 11:48:18 -07002337/* The close function calls close_helper.
2338 */
2339__LJMP static int hlua_socket_close(lua_State *L)
2340{
2341 MAY_LJMP(check_args(L, 1, "close"));
2342 return hlua_socket_close_helper(L);
2343}
2344
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002345/* This Lua function assumes that the stack contain three parameters.
2346 * 1 - USERDATA containing a struct socket
2347 * 2 - INTEGER with values of the macro defined below
2348 * If the integer is -1, we must read at most one line.
2349 * If the integer is -2, we ust read all the data until the
2350 * end of the stream.
2351 * If the integer is positive value, we must read a number of
2352 * bytes corresponding to this value.
2353 */
2354#define HLSR_READ_LINE (-1)
2355#define HLSR_READ_ALL (-2)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002356__LJMP static int hlua_socket_receive_yield(struct lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002357{
2358 struct hlua_socket *socket = MAY_LJMP(hlua_checksocket(L, 1));
2359 int wanted = lua_tointeger(L, 2);
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002360 struct hlua *hlua;
Willy Tarreau5321da92022-05-06 11:57:34 +02002361 struct hlua_csk_ctx *csk_ctx;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002362 struct appctx *appctx;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02002363 size_t len;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002364 int nblk;
Willy Tarreau206ba832018-06-14 15:27:31 +02002365 const char *blk1;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02002366 size_t len1;
Willy Tarreau206ba832018-06-14 15:27:31 +02002367 const char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02002368 size_t len2;
Thierry FOURNIER00543922015-03-09 18:35:06 +01002369 int skip_at_end = 0;
Willy Tarreau81389672015-03-10 12:03:52 +01002370 struct channel *oc;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002371 struct stream *s;
2372 struct xref *peer;
Thierry FOURNIER8c126c72018-05-25 16:27:44 +02002373 int missing_bytes;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002374
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002375 /* Get hlua struct, or NULL if we execute from main lua state */
2376 hlua = hlua_gethlua(L);
2377
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002378 /* Check if this lua stack is schedulable. */
2379 if (!hlua || !hlua->task)
2380 WILL_LJMP(luaL_error(L, "The 'receive' function is only allowed in "
2381 "'frontend', 'backend' or 'task'"));
2382
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002383 /* Check if we run on the same thread than the xreator thread.
2384 * We cannot access to the socket if the thread is different.
2385 */
2386 if (socket->tid != tid)
2387 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2388
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002389 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002390 peer = xref_get_peer_and_lock(&socket->xref);
2391 if (!peer)
2392 goto no_peer;
Willy Tarreau5321da92022-05-06 11:57:34 +02002393
2394 csk_ctx = container_of(peer, struct hlua_csk_ctx, xref);
2395 appctx = csk_ctx->appctx;
Willy Tarreau0698c802022-05-11 14:09:57 +02002396 s = appctx_strm(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002397
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002398 oc = &s->res;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002399 if (wanted == HLSR_READ_LINE) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002400 /* Read line. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02002401 nblk = co_getline_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002402 if (nblk < 0) /* Connection close. */
2403 goto connection_closed;
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002404 if (nblk == 0) /* No data available. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002405 goto connection_empty;
Thierry FOURNIER00543922015-03-09 18:35:06 +01002406
2407 /* remove final \r\n. */
2408 if (nblk == 1) {
2409 if (blk1[len1-1] == '\n') {
2410 len1--;
2411 skip_at_end++;
2412 if (blk1[len1-1] == '\r') {
2413 len1--;
2414 skip_at_end++;
2415 }
2416 }
2417 }
2418 else {
2419 if (blk2[len2-1] == '\n') {
2420 len2--;
2421 skip_at_end++;
2422 if (blk2[len2-1] == '\r') {
2423 len2--;
2424 skip_at_end++;
2425 }
2426 }
2427 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002428 }
2429
2430 else if (wanted == HLSR_READ_ALL) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002431 /* Read all the available data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02002432 nblk = co_getblk_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002433 if (nblk < 0) /* Connection close. */
2434 goto connection_closed;
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002435 if (nblk == 0) /* No data available. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002436 goto connection_empty;
2437 }
2438
2439 else {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002440 /* Read a block of data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02002441 nblk = co_getblk_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002442 if (nblk < 0) /* Connection close. */
2443 goto connection_closed;
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002444 if (nblk == 0) /* No data available. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002445 goto connection_empty;
2446
Thierry FOURNIER8c126c72018-05-25 16:27:44 +02002447 missing_bytes = wanted - socket->b.n;
2448 if (len1 > missing_bytes) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002449 nblk = 1;
Thierry FOURNIER8c126c72018-05-25 16:27:44 +02002450 len1 = missing_bytes;
2451 } if (nblk == 2 && len1 + len2 > missing_bytes)
2452 len2 = missing_bytes - len1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002453 }
2454
2455 len = len1;
2456
2457 luaL_addlstring(&socket->b, blk1, len1);
2458 if (nblk == 2) {
2459 len += len2;
2460 luaL_addlstring(&socket->b, blk2, len2);
2461 }
2462
2463 /* Consume data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02002464 co_skip(oc, len + skip_at_end);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002465
2466 /* Don't wait anything. */
Thierry FOURNIER7e4ee472018-05-25 15:03:50 +02002467 appctx_wakeup(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002468
2469 /* If the pattern reclaim to read all the data
2470 * in the connection, got out.
2471 */
2472 if (wanted == HLSR_READ_ALL)
2473 goto connection_empty;
Thierry FOURNIER8c126c72018-05-25 16:27:44 +02002474 else if (wanted >= 0 && socket->b.n < wanted)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002475 goto connection_empty;
2476
2477 /* Return result. */
2478 luaL_pushresult(&socket->b);
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002479 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002480 return 1;
2481
2482connection_closed:
2483
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002484 xref_unlock(&socket->xref, peer);
2485
2486no_peer:
2487
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002488 /* If the buffer containds data. */
2489 if (socket->b.n > 0) {
2490 luaL_pushresult(&socket->b);
2491 return 1;
2492 }
2493 lua_pushnil(L);
2494 lua_pushstring(L, "connection closed.");
2495 return 2;
2496
2497connection_empty:
2498
Willy Tarreau5321da92022-05-06 11:57:34 +02002499 if (!notification_new(&hlua->com, &csk_ctx->wake_on_read, hlua->task)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002500 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002501 WILL_LJMP(luaL_error(L, "out of memory"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002502 }
2503 xref_unlock(&socket->xref, peer);
Willy Tarreau9635e032018-10-16 17:52:55 +02002504 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_receive_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002505 return 0;
2506}
2507
Tim Duesterhusb33754c2018-01-04 19:32:14 +01002508/* This Lua function gets two parameters. The first one can be string
2509 * or a number. If the string is "*l", the user requires one line. If
2510 * the string is "*a", the user requires all the contents of the stream.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002511 * If the value is a number, the user require a number of bytes equal
2512 * to the value. The default value is "*l" (a line).
2513 *
Tim Duesterhusb33754c2018-01-04 19:32:14 +01002514 * This parameter with a variable type is converted in integer. This
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002515 * integer takes this values:
2516 * -1 : read a line
2517 * -2 : read all the stream
Tim Duesterhusb33754c2018-01-04 19:32:14 +01002518 * >0 : amount of bytes.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002519 *
Tim Duesterhusb33754c2018-01-04 19:32:14 +01002520 * The second parameter is optional. It contains a string that must be
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002521 * concatenated with the read data.
2522 */
2523__LJMP static int hlua_socket_receive(struct lua_State *L)
2524{
2525 int wanted = HLSR_READ_LINE;
2526 const char *pattern;
Christopher Fauletc31b2002021-05-03 10:11:13 +02002527 int lastarg, type;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002528 char *error;
2529 size_t len;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002530 struct hlua_socket *socket;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002531
2532 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
2533 WILL_LJMP(luaL_error(L, "The 'receive' function requires between 1 and 3 arguments."));
2534
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002535 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002536
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002537 /* Check if we run on the same thread than the xreator thread.
2538 * We cannot access to the socket if the thread is different.
2539 */
2540 if (socket->tid != tid)
2541 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2542
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002543 /* check for pattern. */
2544 if (lua_gettop(L) >= 2) {
2545 type = lua_type(L, 2);
2546 if (type == LUA_TSTRING) {
2547 pattern = lua_tostring(L, 2);
2548 if (strcmp(pattern, "*a") == 0)
2549 wanted = HLSR_READ_ALL;
2550 else if (strcmp(pattern, "*l") == 0)
2551 wanted = HLSR_READ_LINE;
2552 else {
2553 wanted = strtoll(pattern, &error, 10);
2554 if (*error != '\0')
2555 WILL_LJMP(luaL_error(L, "Unsupported pattern."));
2556 }
2557 }
2558 else if (type == LUA_TNUMBER) {
2559 wanted = lua_tointeger(L, 2);
2560 if (wanted < 0)
2561 WILL_LJMP(luaL_error(L, "Unsupported size."));
2562 }
2563 }
2564
2565 /* Set pattern. */
2566 lua_pushinteger(L, wanted);
Tim Duesterhusc6e377e2018-01-04 19:32:13 +01002567
2568 /* Check if we would replace the top by itself. */
2569 if (lua_gettop(L) != 2)
2570 lua_replace(L, 2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002571
Christopher Fauletc31b2002021-05-03 10:11:13 +02002572 /* Save index of the top of the stack because since buffers are used, it
2573 * may change
2574 */
2575 lastarg = lua_gettop(L);
2576
Tim Duesterhusb33754c2018-01-04 19:32:14 +01002577 /* init buffer, and fill it with prefix. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002578 luaL_buffinit(L, &socket->b);
2579
2580 /* Check prefix. */
Christopher Fauletc31b2002021-05-03 10:11:13 +02002581 if (lastarg >= 3) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002582 if (lua_type(L, 3) != LUA_TSTRING)
2583 WILL_LJMP(luaL_error(L, "Expect a 'string' for the prefix"));
2584 pattern = lua_tolstring(L, 3, &len);
2585 luaL_addlstring(&socket->b, pattern, len);
2586 }
2587
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002588 return __LJMP(hlua_socket_receive_yield(L, 0, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002589}
2590
2591/* Write the Lua input string in the output buffer.
Mark Lakes22154b42018-01-29 14:38:40 -08002592 * This function returns a yield if no space is available.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002593 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002594static int hlua_socket_write_yield(struct lua_State *L,int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002595{
2596 struct hlua_socket *socket;
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002597 struct hlua *hlua;
Willy Tarreau5321da92022-05-06 11:57:34 +02002598 struct hlua_csk_ctx *csk_ctx;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002599 struct appctx *appctx;
2600 size_t buf_len;
2601 const char *buf;
2602 int len;
2603 int send_len;
2604 int sent;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002605 struct xref *peer;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002606 struct stream *s;
Willy Tarreau3e7be362022-05-27 10:35:27 +02002607 struct stconn *sc;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002608
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002609 /* Get hlua struct, or NULL if we execute from main lua state */
2610 hlua = hlua_gethlua(L);
2611
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002612 /* Check if this lua stack is schedulable. */
2613 if (!hlua || !hlua->task)
2614 WILL_LJMP(luaL_error(L, "The 'write' function is only allowed in "
2615 "'frontend', 'backend' or 'task'"));
2616
2617 /* Get object */
2618 socket = MAY_LJMP(hlua_checksocket(L, 1));
2619 buf = MAY_LJMP(luaL_checklstring(L, 2, &buf_len));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002620 sent = MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002621
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002622 /* Check if we run on the same thread than the xreator thread.
2623 * We cannot access to the socket if the thread is different.
2624 */
2625 if (socket->tid != tid)
2626 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2627
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002628 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002629 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002630 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002631 lua_pushinteger(L, -1);
2632 return 1;
2633 }
Willy Tarreau5321da92022-05-06 11:57:34 +02002634
2635 csk_ctx = container_of(peer, struct hlua_csk_ctx, xref);
2636 appctx = csk_ctx->appctx;
Willy Tarreauc12b3212022-05-27 11:08:15 +02002637 sc = appctx_sc(appctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02002638 s = __sc_strm(sc);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002639
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002640 /* Check for connection close. */
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002641 if (channel_output_closed(&s->req)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002642 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002643 lua_pushinteger(L, -1);
2644 return 1;
2645 }
2646
2647 /* Update the input buffer data. */
2648 buf += sent;
2649 send_len = buf_len - sent;
2650
2651 /* All the data are sent. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002652 if (sent >= buf_len) {
2653 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002654 return 1; /* Implicitly return the length sent. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002655 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002656
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002657 /* Check if the buffer is available because HAProxy doesn't allocate
Thierry FOURNIER486d52a2015-03-09 17:51:43 +01002658 * the request buffer if its not required.
2659 */
Willy Tarreauc9fa0482018-07-10 17:43:27 +02002660 if (s->req.buf.size == 0) {
Willy Tarreau3e7be362022-05-27 10:35:27 +02002661 if (!sc_alloc_ibuf(sc, &appctx->buffer_wait))
Christopher Faulet33834b12016-12-19 09:29:06 +01002662 goto hlua_socket_write_yield_return;
Thierry FOURNIER486d52a2015-03-09 17:51:43 +01002663 }
2664
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002665 /* Check for available space. */
Willy Tarreauc9fa0482018-07-10 17:43:27 +02002666 len = b_room(&s->req.buf);
Christopher Faulet33834b12016-12-19 09:29:06 +01002667 if (len <= 0) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002668 goto hlua_socket_write_yield_return;
Christopher Faulet33834b12016-12-19 09:29:06 +01002669 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002670
2671 /* send data */
2672 if (len < send_len)
2673 send_len = len;
Thierry FOURNIER66b89192018-05-27 01:14:47 +02002674 len = ci_putblk(&s->req, buf, send_len);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002675
2676 /* "Not enough space" (-1), "Buffer too little to contain
2677 * the data" (-2) are not expected because the available length
2678 * is tested.
2679 * Other unknown error are also not expected.
2680 */
2681 if (len <= 0) {
Willy Tarreaubc18da12015-03-13 14:00:47 +01002682 if (len == -1)
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002683 s->req.flags |= CF_WAKE_WRITE;
Willy Tarreaubc18da12015-03-13 14:00:47 +01002684
sada05ed3302018-05-11 11:48:18 -07002685 MAY_LJMP(hlua_socket_close_helper(L));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002686 lua_pop(L, 1);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002687 lua_pushinteger(L, -1);
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002688 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002689 return 1;
2690 }
2691
2692 /* update buffers. */
Thierry FOURNIER101b9762018-05-27 01:27:40 +02002693 appctx_wakeup(appctx);
Willy Tarreaude70fa12015-09-26 11:25:05 +02002694
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002695 /* Update length sent. */
2696 lua_pop(L, 1);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002697 lua_pushinteger(L, sent + len);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002698
2699 /* All the data buffer is sent ? */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002700 if (sent + len >= buf_len) {
2701 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002702 return 1;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002703 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002704
2705hlua_socket_write_yield_return:
Willy Tarreau5321da92022-05-06 11:57:34 +02002706 if (!notification_new(&hlua->com, &csk_ctx->wake_on_write, hlua->task)) {
Thierry FOURNIERba42fcd2018-05-27 00:59:48 +02002707 xref_unlock(&socket->xref, peer);
2708 WILL_LJMP(luaL_error(L, "out of memory"));
2709 }
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002710 xref_unlock(&socket->xref, peer);
Willy Tarreau9635e032018-10-16 17:52:55 +02002711 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_write_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002712 return 0;
2713}
2714
2715/* This function initiate the send of data. It just check the input
2716 * parameters and push an integer in the Lua stack that contain the
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002717 * amount of data written to the buffer. This is used by the function
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002718 * "hlua_socket_write_yield" that can yield.
2719 *
2720 * The Lua function gets between 3 and 4 parameters. The first one is
2721 * the associated object. The second is a string buffer. The third is
2722 * a facultative integer that represents where is the buffer position
2723 * of the start of the data that can send. The first byte is the
2724 * position "1". The default value is "1". The fourth argument is a
2725 * facultative integer that represents where is the buffer position
2726 * of the end of the data that can send. The default is the last byte.
2727 */
2728static int hlua_socket_send(struct lua_State *L)
2729{
2730 int i;
2731 int j;
2732 const char *buf;
2733 size_t buf_len;
2734
2735 /* Check number of arguments. */
2736 if (lua_gettop(L) < 2 || lua_gettop(L) > 4)
2737 WILL_LJMP(luaL_error(L, "'send' needs between 2 and 4 arguments"));
2738
2739 /* Get the string. */
2740 buf = MAY_LJMP(luaL_checklstring(L, 2, &buf_len));
2741
2742 /* Get and check j. */
2743 if (lua_gettop(L) == 4) {
2744 j = MAY_LJMP(luaL_checkinteger(L, 4));
2745 if (j < 0)
2746 j = buf_len + j + 1;
2747 if (j > buf_len)
2748 j = buf_len + 1;
2749 lua_pop(L, 1);
2750 }
2751 else
2752 j = buf_len;
2753
2754 /* Get and check i. */
2755 if (lua_gettop(L) == 3) {
2756 i = MAY_LJMP(luaL_checkinteger(L, 3));
2757 if (i < 0)
2758 i = buf_len + i + 1;
2759 if (i > buf_len)
2760 i = buf_len + 1;
2761 lua_pop(L, 1);
2762 } else
2763 i = 1;
2764
2765 /* Check bth i and j. */
2766 if (i > j) {
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002767 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002768 return 1;
2769 }
2770 if (i == 0 && j == 0) {
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002771 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002772 return 1;
2773 }
2774 if (i == 0)
2775 i = 1;
2776 if (j == 0)
2777 j = 1;
2778
2779 /* Pop the string. */
2780 lua_pop(L, 1);
2781
2782 /* Update the buffer length. */
2783 buf += i - 1;
2784 buf_len = j - i + 1;
2785 lua_pushlstring(L, buf, buf_len);
2786
2787 /* This unsigned is used to remember the amount of sent data. */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002788 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002789
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002790 return MAY_LJMP(hlua_socket_write_yield(L, 0, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002791}
2792
Willy Tarreau22b0a682015-06-17 19:43:49 +02002793#define SOCKET_INFO_MAX_LEN sizeof("[0000:0000:0000:0000:0000:0000:0000:0000]:12345")
Christopher Faulete6465b32021-10-22 15:36:08 +02002794__LJMP static inline int hlua_socket_info(struct lua_State *L, const struct sockaddr_storage *addr)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002795{
2796 static char buffer[SOCKET_INFO_MAX_LEN];
2797 int ret;
2798 int len;
2799 char *p;
2800
2801 ret = addr_to_str(addr, buffer+1, SOCKET_INFO_MAX_LEN-1);
2802 if (ret <= 0) {
2803 lua_pushnil(L);
2804 return 1;
2805 }
2806
2807 if (ret == AF_UNIX) {
2808 lua_pushstring(L, buffer+1);
2809 return 1;
2810 }
2811 else if (ret == AF_INET6) {
2812 buffer[0] = '[';
2813 len = strlen(buffer);
2814 buffer[len] = ']';
2815 len++;
2816 buffer[len] = ':';
2817 len++;
2818 p = buffer;
2819 }
2820 else if (ret == AF_INET) {
2821 p = buffer + 1;
2822 len = strlen(p);
2823 p[len] = ':';
2824 len++;
2825 }
2826 else {
2827 lua_pushnil(L);
2828 return 1;
2829 }
2830
2831 if (port_to_str(addr, p + len, SOCKET_INFO_MAX_LEN-1 - len) <= 0) {
2832 lua_pushnil(L);
2833 return 1;
2834 }
2835
2836 lua_pushstring(L, p);
2837 return 1;
2838}
2839
2840/* Returns information about the peer of the connection. */
2841__LJMP static int hlua_socket_getpeername(struct lua_State *L)
2842{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002843 struct hlua_socket *socket;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002844 struct xref *peer;
2845 struct appctx *appctx;
Willy Tarreau3e7be362022-05-27 10:35:27 +02002846 struct stconn *sc;
Christopher Faulet16f16af2021-10-27 09:34:56 +02002847 const struct sockaddr_storage *dst;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002848 int ret;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002849
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002850 MAY_LJMP(check_args(L, 1, "getpeername"));
2851
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002852 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002853
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002854 /* Check if we run on the same thread than the xreator thread.
2855 * We cannot access to the socket if the thread is different.
2856 */
2857 if (socket->tid != tid)
2858 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2859
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002860 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002861 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002862 if (!peer) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002863 lua_pushnil(L);
2864 return 1;
2865 }
Willy Tarreau5321da92022-05-06 11:57:34 +02002866
2867 appctx = container_of(peer, struct hlua_csk_ctx, xref)->appctx;
Willy Tarreauc12b3212022-05-27 11:08:15 +02002868 sc = appctx_sc(appctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02002869 dst = sc_dst(sc_opposite(sc));
Christopher Faulet16f16af2021-10-27 09:34:56 +02002870 if (!dst) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002871 xref_unlock(&socket->xref, peer);
Willy Tarreaua71f6422016-11-16 17:00:14 +01002872 lua_pushnil(L);
2873 return 1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002874 }
2875
Christopher Faulet16f16af2021-10-27 09:34:56 +02002876 ret = MAY_LJMP(hlua_socket_info(L, dst));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002877 xref_unlock(&socket->xref, peer);
2878 return ret;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002879}
2880
2881/* Returns information about my connection side. */
2882static int hlua_socket_getsockname(struct lua_State *L)
2883{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002884 struct hlua_socket *socket;
2885 struct connection *conn;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002886 struct appctx *appctx;
2887 struct xref *peer;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002888 struct stream *s;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002889 int ret;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002890
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002891 MAY_LJMP(check_args(L, 1, "getsockname"));
2892
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002893 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002894
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002895 /* Check if we run on the same thread than the xreator thread.
2896 * We cannot access to the socket if the thread is different.
2897 */
2898 if (socket->tid != tid)
2899 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2900
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002901 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002902 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002903 if (!peer) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002904 lua_pushnil(L);
2905 return 1;
2906 }
Willy Tarreau5321da92022-05-06 11:57:34 +02002907
2908 appctx = container_of(peer, struct hlua_csk_ctx, xref)->appctx;
Willy Tarreau0698c802022-05-11 14:09:57 +02002909 s = appctx_strm(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002910
Willy Tarreaufd9417b2022-05-18 16:23:22 +02002911 conn = sc_conn(s->scb);
Willy Tarreau5a0b25d2019-07-18 18:01:14 +02002912 if (!conn || !conn_get_src(conn)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002913 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002914 lua_pushnil(L);
2915 return 1;
2916 }
2917
Willy Tarreau9da9a6f2019-07-17 14:49:44 +02002918 ret = hlua_socket_info(L, conn->src);
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002919 xref_unlock(&socket->xref, peer);
2920 return ret;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002921}
2922
2923/* This struct define the applet. */
Willy Tarreau30576452015-04-13 13:50:30 +02002924static struct applet update_applet = {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002925 .obj_type = OBJ_TYPE_APPLET,
2926 .name = "<LUA_TCP>",
2927 .fct = hlua_socket_handler,
Christopher Faulet5f35a3e2022-05-12 15:31:05 +02002928 .init = hlua_socket_init,
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002929 .release = hlua_socket_release,
2930};
2931
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002932__LJMP static int hlua_socket_connect_yield(struct lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002933{
2934 struct hlua_socket *socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002935 struct hlua *hlua;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002936 struct xref *peer;
Willy Tarreau5321da92022-05-06 11:57:34 +02002937 struct hlua_csk_ctx *csk_ctx;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002938 struct appctx *appctx;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002939 struct stream *s;
2940
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002941 /* Get hlua struct, or NULL if we execute from main lua state */
2942 hlua = hlua_gethlua(L);
2943 if (!hlua)
2944 return 0;
2945
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002946 /* Check if we run on the same thread than the xreator thread.
2947 * We cannot access to the socket if the thread is different.
2948 */
2949 if (socket->tid != tid)
2950 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2951
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002952 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002953 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002954 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002955 lua_pushnil(L);
2956 lua_pushstring(L, "Can't connect");
2957 return 2;
2958 }
Willy Tarreau5321da92022-05-06 11:57:34 +02002959
2960 csk_ctx = container_of(peer, struct hlua_csk_ctx, xref);
2961 appctx = csk_ctx->appctx;
Willy Tarreau0698c802022-05-11 14:09:57 +02002962 s = appctx_strm(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002963
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002964 /* Check if we run on the same thread than the xreator thread.
2965 * We cannot access to the socket if the thread is different.
2966 */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002967 if (socket->tid != tid) {
2968 xref_unlock(&socket->xref, peer);
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002969 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002970 }
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002971
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002972 /* Check for connection close. */
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002973 if (!hlua || channel_output_closed(&s->req)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002974 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002975 lua_pushnil(L);
2976 lua_pushstring(L, "Can't connect");
2977 return 2;
2978 }
2979
Willy Tarreau8e7c6e62022-05-18 17:58:02 +02002980 appctx = __sc_appctx(s->scf);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002981
2982 /* Check for connection established. */
Willy Tarreau5321da92022-05-06 11:57:34 +02002983 if (csk_ctx->connected) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002984 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002985 lua_pushinteger(L, 1);
2986 return 1;
2987 }
2988
Willy Tarreau5321da92022-05-06 11:57:34 +02002989 if (!notification_new(&hlua->com, &csk_ctx->wake_on_write, hlua->task)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002990 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002991 WILL_LJMP(luaL_error(L, "out of memory error"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002992 }
2993 xref_unlock(&socket->xref, peer);
Willy Tarreau9635e032018-10-16 17:52:55 +02002994 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_connect_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002995 return 0;
2996}
2997
2998/* This function fail or initite the connection. */
2999__LJMP static int hlua_socket_connect(struct lua_State *L)
3000{
3001 struct hlua_socket *socket;
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02003002 int port = -1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003003 const char *ip;
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01003004 struct hlua *hlua;
Willy Tarreau5321da92022-05-06 11:57:34 +02003005 struct hlua_csk_ctx *csk_ctx;
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01003006 struct appctx *appctx;
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02003007 int low, high;
3008 struct sockaddr_storage *addr;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003009 struct xref *peer;
Willy Tarreau3e7be362022-05-27 10:35:27 +02003010 struct stconn *sc;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003011 struct stream *s;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003012
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02003013 if (lua_gettop(L) < 2)
3014 WILL_LJMP(luaL_error(L, "connect: need at least 2 arguments"));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003015
3016 /* Get args. */
3017 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02003018
3019 /* Check if we run on the same thread than the xreator thread.
3020 * We cannot access to the socket if the thread is different.
3021 */
3022 if (socket->tid != tid)
3023 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
3024
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003025 ip = MAY_LJMP(luaL_checkstring(L, 2));
Tim Duesterhus6edab862018-01-06 19:04:45 +01003026 if (lua_gettop(L) >= 3) {
3027 luaL_Buffer b;
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02003028 port = MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003029
Tim Duesterhus6edab862018-01-06 19:04:45 +01003030 /* Force the ip to end with a colon, to support IPv6 addresses
3031 * that are not enclosed within square brackets.
3032 */
3033 if (port > 0) {
3034 luaL_buffinit(L, &b);
3035 luaL_addstring(&b, ip);
3036 luaL_addchar(&b, ':');
3037 luaL_pushresult(&b);
3038 ip = lua_tolstring(L, lua_gettop(L), NULL);
3039 }
3040 }
3041
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003042 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02003043 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003044 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003045 lua_pushnil(L);
3046 return 1;
3047 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003048
3049 /* Parse ip address. */
Willy Tarreau5fc93282020-09-16 18:25:03 +02003050 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 +02003051 if (!addr) {
3052 xref_unlock(&socket->xref, peer);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02003053 WILL_LJMP(luaL_error(L, "connect: cannot parse destination address '%s'", ip));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02003054 }
Willy Tarreau9da9a6f2019-07-17 14:49:44 +02003055
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003056 /* Set port. */
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02003057 if (low == 0) {
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02003058 if (addr->ss_family == AF_INET) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02003059 if (port == -1) {
3060 xref_unlock(&socket->xref, peer);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02003061 WILL_LJMP(luaL_error(L, "connect: port missing"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02003062 }
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02003063 ((struct sockaddr_in *)addr)->sin_port = htons(port);
3064 } else if (addr->ss_family == AF_INET6) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02003065 if (port == -1) {
3066 xref_unlock(&socket->xref, peer);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02003067 WILL_LJMP(luaL_error(L, "connect: port missing"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02003068 }
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02003069 ((struct sockaddr_in6 *)addr)->sin6_port = htons(port);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02003070 }
3071 }
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02003072
Willy Tarreau5321da92022-05-06 11:57:34 +02003073 csk_ctx = container_of(peer, struct hlua_csk_ctx, xref);
3074 appctx = csk_ctx->appctx;
Willy Tarreauc12b3212022-05-27 11:08:15 +02003075 sc = appctx_sc(appctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02003076 s = __sc_strm(sc);
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02003077
Willy Tarreau3e7be362022-05-27 10:35:27 +02003078 if (!sockaddr_alloc(&sc_opposite(sc)->dst, addr, sizeof(*addr))) {
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02003079 xref_unlock(&socket->xref, peer);
3080 WILL_LJMP(luaL_error(L, "connect: internal error"));
3081 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003082
Thierry Fournier4234dbd2020-11-28 13:18:23 +01003083 /* Get hlua struct, or NULL if we execute from main lua state */
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01003084 hlua = hlua_gethlua(L);
Thierry Fournier4234dbd2020-11-28 13:18:23 +01003085 if (!hlua)
3086 return 0;
Willy Tarreaubdc97a82015-08-24 15:42:28 +02003087
3088 /* inform the stream that we want to be notified whenever the
3089 * connection completes.
3090 */
Willy Tarreau90e8b452022-05-25 18:21:43 +02003091 applet_need_more_data(appctx);
Willy Tarreau4164eb92022-05-25 15:42:03 +02003092 applet_have_more_data(appctx);
Thierry FOURNIER8c8fbbe2015-09-26 17:02:35 +02003093 appctx_wakeup(appctx);
Willy Tarreaubdc97a82015-08-24 15:42:28 +02003094
Willy Tarreauf31af932020-01-14 09:59:38 +01003095 hlua->gc_count++;
Thierry FOURNIER7c39ab42015-09-27 22:53:33 +02003096
Willy Tarreau5321da92022-05-06 11:57:34 +02003097 if (!notification_new(&hlua->com, &csk_ctx->wake_on_write, hlua->task)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02003098 xref_unlock(&socket->xref, peer);
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01003099 WILL_LJMP(luaL_error(L, "out of memory"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02003100 }
3101 xref_unlock(&socket->xref, peer);
PiBa-NL706d5ee2018-05-05 23:51:42 +02003102
3103 task_wakeup(s->task, TASK_WOKEN_INIT);
3104 /* Return yield waiting for connection. */
3105
Willy Tarreau9635e032018-10-16 17:52:55 +02003106 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_connect_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003107
3108 return 0;
3109}
3110
Baptiste Assmann84bb4932015-03-02 21:40:06 +01003111#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003112__LJMP static int hlua_socket_connect_ssl(struct lua_State *L)
3113{
3114 struct hlua_socket *socket;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003115 struct xref *peer;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003116 struct stream *s;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003117
3118 MAY_LJMP(check_args(L, 3, "connect_ssl"));
3119 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003120
3121 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02003122 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003123 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003124 lua_pushnil(L);
3125 return 1;
3126 }
Willy Tarreau5321da92022-05-06 11:57:34 +02003127
Willy Tarreau0698c802022-05-11 14:09:57 +02003128 s = appctx_strm(container_of(peer, struct hlua_csk_ctx, xref)->appctx);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003129
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +01003130 s->target = &socket_ssl->obj_type;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02003131 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003132 return MAY_LJMP(hlua_socket_connect(L));
3133}
Baptiste Assmann84bb4932015-03-02 21:40:06 +01003134#endif
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003135
3136__LJMP static int hlua_socket_setoption(struct lua_State *L)
3137{
3138 return 0;
3139}
3140
3141__LJMP static int hlua_socket_settimeout(struct lua_State *L)
3142{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003143 struct hlua_socket *socket;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003144 int tmout;
Mark Lakes56cc1252018-03-27 09:48:06 +02003145 double dtmout;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003146 struct xref *peer;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003147 struct stream *s;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003148
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003149 MAY_LJMP(check_args(L, 2, "settimeout"));
3150
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003151 socket = MAY_LJMP(hlua_checksocket(L, 1));
Mark Lakes56cc1252018-03-27 09:48:06 +02003152
Cyril Bonté7ee465f2018-08-19 22:08:50 +02003153 /* convert the timeout to millis */
3154 dtmout = MAY_LJMP(luaL_checknumber(L, 2)) * 1000;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003155
Thierry Fournier17a921b2018-03-08 09:59:02 +01003156 /* Check for negative values */
Mark Lakes56cc1252018-03-27 09:48:06 +02003157 if (dtmout < 0)
Thierry Fournier17a921b2018-03-08 09:59:02 +01003158 WILL_LJMP(luaL_error(L, "settimeout: cannot set negatives values"));
3159
Mark Lakes56cc1252018-03-27 09:48:06 +02003160 if (dtmout > INT_MAX) /* overflow check */
Cyril Bonté7ee465f2018-08-19 22:08:50 +02003161 WILL_LJMP(luaL_error(L, "settimeout: cannot set values larger than %d ms", INT_MAX));
Mark Lakes56cc1252018-03-27 09:48:06 +02003162
3163 tmout = MS_TO_TICKS((int)dtmout);
Cyril Bonté7ee465f2018-08-19 22:08:50 +02003164 if (tmout == 0)
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05003165 tmout++; /* very small timeouts are adjusted to a minimum of 1ms */
Mark Lakes56cc1252018-03-27 09:48:06 +02003166
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02003167 /* Check if we run on the same thread than the xreator thread.
3168 * We cannot access to the socket if the thread is different.
3169 */
3170 if (socket->tid != tid)
3171 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
3172
Mark Lakes56cc1252018-03-27 09:48:06 +02003173 /* check for connection break. If some data were read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02003174 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003175 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003176 hlua_pusherror(L, "socket: not yet initialised, you can't set timeouts.");
3177 WILL_LJMP(lua_error(L));
3178 return 0;
3179 }
Willy Tarreau5321da92022-05-06 11:57:34 +02003180
Willy Tarreau0698c802022-05-11 14:09:57 +02003181 s = appctx_strm(container_of(peer, struct hlua_csk_ctx, xref)->appctx);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003182
Cyril Bonté7bb63452018-08-17 23:51:02 +02003183 s->sess->fe->timeout.connect = tmout;
Christopher Faulet5aaacfb2023-02-15 08:13:33 +01003184 s->scf->ioto = tmout;
3185 s->scb->ioto = tmout;
Cyril Bonté7bb63452018-08-17 23:51:02 +02003186
3187 s->task->expire = tick_add_ifset(now_ms, tmout);
3188 task_queue(s->task);
3189
Thierry FOURNIER952939d2017-09-01 14:17:32 +02003190 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003191
Thierry Fourniere9636f12018-03-08 09:54:32 +01003192 lua_pushinteger(L, 1);
Tim Duesterhus119a5f12018-01-06 19:16:25 +01003193 return 1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003194}
3195
3196__LJMP static int hlua_socket_new(lua_State *L)
3197{
3198 struct hlua_socket *socket;
Willy Tarreau5321da92022-05-06 11:57:34 +02003199 struct hlua_csk_ctx *ctx;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003200 struct appctx *appctx;
3201
3202 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003203 if (!lua_checkstack(L, 3)) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003204 hlua_pusherror(L, "socket: full stack");
3205 goto out_fail_conf;
3206 }
3207
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003208 /* Create the object: obj[0] = userdata. */
3209 lua_newtable(L);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003210 socket = MAY_LJMP(lua_newuserdata(L, sizeof(*socket)));
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003211 lua_rawseti(L, -2, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003212 memset(socket, 0, sizeof(*socket));
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02003213 socket->tid = tid;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003214
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05003215 /* Check if the various memory pools are initialized. */
Willy Tarreaubafbe012017-11-24 17:34:44 +01003216 if (!pool_head_stream || !pool_head_buffer) {
Thierry FOURNIER4a6170c2015-03-09 17:07:10 +01003217 hlua_pusherror(L, "socket: uninitialized pools.");
3218 goto out_fail_conf;
3219 }
3220
Willy Tarreau87b09662015-04-03 00:22:06 +02003221 /* Pop a class stream metatable and affect it to the userdata. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003222 lua_rawgeti(L, LUA_REGISTRYINDEX, class_socket_ref);
3223 lua_setmetatable(L, -2);
3224
Willy Tarreaud420a972015-04-06 00:39:18 +02003225 /* Create the applet context */
Christopher Faulet6095d572022-05-16 17:09:48 +02003226 appctx = appctx_new_here(&update_applet, NULL);
Willy Tarreau61cf7c82015-04-06 00:48:33 +02003227 if (!appctx) {
3228 hlua_pusherror(L, "socket: out of memory");
Christopher Fauleta9e8b392022-03-23 11:01:09 +01003229 goto out_fail_conf;
Willy Tarreau61cf7c82015-04-06 00:48:33 +02003230 }
Willy Tarreau5321da92022-05-06 11:57:34 +02003231 ctx = applet_reserve_svcctx(appctx, sizeof(*ctx));
3232 ctx->connected = 0;
Willy Tarreau5321da92022-05-06 11:57:34 +02003233 ctx->die = 0;
3234 LIST_INIT(&ctx->wake_on_write);
3235 LIST_INIT(&ctx->wake_on_read);
Willy Tarreaub2bf8332015-04-04 15:58:58 +02003236
Christopher Faulet5f35a3e2022-05-12 15:31:05 +02003237 if (appctx_init(appctx) == -1) {
3238 hlua_pusherror(L, "socket: fail to init applet.");
Christopher Faulet13a35e52021-12-20 15:34:16 +01003239 goto out_fail_appctx;
3240 }
3241
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003242 /* Initialise cross reference between stream and Lua socket object. */
Willy Tarreau5321da92022-05-06 11:57:34 +02003243 xref_create(&socket->xref, &ctx->xref);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003244 return 1;
3245
Christopher Faulet13a35e52021-12-20 15:34:16 +01003246 out_fail_appctx:
Christopher Faulet5f35a3e2022-05-12 15:31:05 +02003247 appctx_free_on_early_error(appctx);
Willy Tarreaud420a972015-04-06 00:39:18 +02003248 out_fail_conf:
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003249 WILL_LJMP(lua_error(L));
3250 return 0;
3251}
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01003252
3253/*
3254 *
3255 *
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003256 * Class Channel
3257 *
3258 *
3259 */
3260
3261/* Returns the struct hlua_channel join to the class channel in the
3262 * stack entry "ud" or throws an argument error.
3263 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01003264__LJMP static struct channel *hlua_checkchannel(lua_State *L, int ud)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003265{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003266 return MAY_LJMP(hlua_checkudata(L, ud, class_channel_ref));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003267}
3268
Willy Tarreau47860ed2015-03-10 14:07:50 +01003269/* Pushes the channel onto the top of the stack. If the stask does not have a
3270 * free slots, the function fails and returns 0;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003271 */
Willy Tarreau2a71af42015-03-10 13:51:50 +01003272static int hlua_channel_new(lua_State *L, struct channel *channel)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003273{
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003274 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003275 if (!lua_checkstack(L, 3))
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003276 return 0;
3277
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003278 lua_newtable(L);
Willy Tarreau47860ed2015-03-10 14:07:50 +01003279 lua_pushlightuserdata(L, channel);
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003280 lua_rawseti(L, -2, 0);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003281
3282 /* Pop a class sesison metatable and affect it to the userdata. */
3283 lua_rawgeti(L, LUA_REGISTRYINDEX, class_channel_ref);
3284 lua_setmetatable(L, -2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003285 return 1;
3286}
3287
Christopher Faulet9f55a502020-02-25 15:21:02 +01003288/* Helper function returning a filter attached to a channel at the position <ud>
3289 * in the stack, filling the current offset and length of the filter. If no
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05003290 * filter is attached, NULL is returned and <offset> and <len> are not
Christopher Faulet9f55a502020-02-25 15:21:02 +01003291 * initialized.
3292 */
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003293static 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 +01003294{
3295 struct filter *filter = NULL;
3296
3297 if (lua_getfield(L, ud, "__filter") == LUA_TLIGHTUSERDATA) {
3298 struct hlua_flt_ctx *flt_ctx;
3299
3300 filter = lua_touserdata (L, -1);
3301 flt_ctx = filter->ctx;
3302 if (hlua_filter_from_payload(filter)) {
3303 *offset = flt_ctx->cur_off[CHN_IDX(chn)];
3304 *len = flt_ctx->cur_len[CHN_IDX(chn)];
3305 }
3306 }
3307
3308 lua_pop(L, 1);
3309 return filter;
3310}
3311
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003312/* Copies <len> bytes of data present in the channel's buffer, starting at the
3313* offset <offset>, and put it in a LUA string variable. It is the caller
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003314* responsibility to ensure <len> and <offset> are valid. It always return the
3315* length of the built string. <len> may be 0, in this case, an empty string is
3316* created and 0 is returned.
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003317*/
3318static inline int _hlua_channel_dup(struct channel *chn, lua_State *L, size_t offset, size_t len)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003319{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003320 size_t block1, block2;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003321 luaL_Buffer b;
3322
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003323 block1 = len;
3324 if (block1 > b_contig_data(&chn->buf, b_peek_ofs(&chn->buf, offset)))
3325 block1 = b_contig_data(&chn->buf, b_peek_ofs(&chn->buf, offset));
3326 block2 = len - block1;
3327
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003328 luaL_buffinit(L, &b);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003329 luaL_addlstring(&b, b_peek(&chn->buf, offset), block1);
3330 if (block2)
3331 luaL_addlstring(&b, b_orig(&chn->buf), block2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003332 luaL_pushresult(&b);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003333 return len;
3334}
3335
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003336/* Inserts the string <str> to the channel's buffer at the offset <offset>. This
3337 * function returns -1 if data cannot be copied. Otherwise, it returns the
3338 * number of bytes copied.
3339 */
3340static int _hlua_channel_insert(struct channel *chn, lua_State *L, struct ist str, size_t offset)
3341{
3342 int ret = 0;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003343
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003344 /* Nothing to do, just return */
3345 if (unlikely(istlen(str) == 0))
3346 goto end;
3347
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003348 if (istlen(str) > c_room(chn)) {
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003349 ret = -1;
3350 goto end;
3351 }
3352 ret = b_insert_blk(&chn->buf, offset, istptr(str), istlen(str));
3353
3354 end:
3355 return ret;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003356}
3357
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003358/* Removes <len> bytes of data at the absolute position <offset>.
3359 */
3360static void _hlua_channel_delete(struct channel *chn, size_t offset, size_t len)
3361{
3362 size_t end = offset + len;
3363
3364 if (b_peek(&chn->buf, end) != b_tail(&chn->buf))
3365 b_move(&chn->buf, b_peek_ofs(&chn->buf, end),
3366 b_data(&chn->buf) - end, -len);
3367 b_sub(&chn->buf, len);
3368}
3369
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003370/* Copies input data in the channel's buffer. It is possible to set a specific
3371 * offset (0 by default) and a length (all remaining input data starting for the
3372 * offset by default). If there is not enough input data and more data can be
3373 * received, this function yields.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003374 *
3375 * From an action, All input data are considered. For a filter, the offset and
3376 * the length of input data to consider are retrieved from the filter context.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003377 */
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003378__LJMP static int hlua_channel_get_data_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003379{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003380 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003381 struct filter *filter;
3382 size_t input, output;
3383 int offset, len;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003384
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003385 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003386
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003387 output = co_data(chn);
3388 input = ci_data(chn);
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003389
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003390 filter = hlua_channel_filter(L, 1, chn, &output, &input);
3391 if (filter && !hlua_filter_from_payload(filter))
3392 WILL_LJMP(lua_error(L));
3393
3394 offset = output;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003395 if (lua_gettop(L) > 1) {
3396 offset = MAY_LJMP(luaL_checkinteger(L, 2));
3397 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02003398 offset = MAX(0, (int)input + offset);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003399 offset += output;
3400 if (offset < output || offset > input + output) {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003401 lua_pushfstring(L, "offset out of range.");
3402 WILL_LJMP(lua_error(L));
3403 }
3404 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003405 len = output + input - offset;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003406 if (lua_gettop(L) == 3) {
3407 len = MAY_LJMP(luaL_checkinteger(L, 3));
3408 if (!len)
3409 goto dup;
3410 if (len == -1)
3411 len = global.tune.bufsize;
3412 if (len < 0) {
3413 lua_pushfstring(L, "length out of range.");
3414 WILL_LJMP(lua_error(L));
3415 }
3416 }
3417
Christopher Faulet0ae2e632023-01-10 15:29:54 +01003418 /* Wait for more data if possible if no length was specified and there
3419 * is no data or not enough data was received.
3420 */
3421 if (!len || offset + len > output + input) {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003422 if (!HLUA_CANT_YIELD(hlua_gethlua(L)) && !channel_input_closed(chn) && channel_may_recv(chn)) {
3423 /* Yield waiting for more data, as requested */
3424 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_get_data_yield, TICK_ETERNITY, 0));
3425 }
Christopher Faulet0ae2e632023-01-10 15:29:54 +01003426
3427 /* Return 'nil' if there is no data and the channel can't receive more data */
3428 if (!len) {
3429 lua_pushnil(L);
3430 return -1;
3431 }
3432
3433 /* Otherwise, return all data */
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003434 len = output + input - offset;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003435 }
3436
3437 dup:
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003438 _hlua_channel_dup(chn, L, offset, len);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003439 return 1;
3440}
3441
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003442/* Copies the first line (including the trailing LF) of input data in the
3443 * channel's buffer. It is possible to set a specific offset (0 by default) and
3444 * a length (all remaining input data starting for the offset by default). If
3445 * there is not enough input data and more data can be received, the function
3446 * yields. If a length is explicitly specified, no more data are
3447 * copied. Otherwise, if no LF is found and more data can be received, this
3448 * function yields.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003449 *
3450 * From an action, All input data are considered. For a filter, the offset and
3451 * the length of input data to consider are retrieved from the filter context.
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003452 */
3453__LJMP static int hlua_channel_get_line_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003454{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003455 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003456 struct filter *filter;
3457 size_t l, input, output;
3458 int offset, len;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003459
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003460 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003461 output = co_data(chn);
3462 input = ci_data(chn);
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003463
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003464 filter = hlua_channel_filter(L, 1, chn, &output, &input);
3465 if (filter && !hlua_filter_from_payload(filter))
3466 WILL_LJMP(lua_error(L));
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003467
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003468 offset = output;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003469 if (lua_gettop(L) > 1) {
3470 offset = MAY_LJMP(luaL_checkinteger(L, 2));
3471 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02003472 offset = MAX(0, (int)input + offset);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003473 offset += output;
3474 if (offset < output || offset > input + output) {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003475 lua_pushfstring(L, "offset out of range.");
3476 WILL_LJMP(lua_error(L));
3477 }
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003478 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003479
3480 len = output + input - offset;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003481 if (lua_gettop(L) == 3) {
3482 len = MAY_LJMP(luaL_checkinteger(L, 3));
3483 if (!len)
3484 goto dup;
3485 if (len == -1)
3486 len = global.tune.bufsize;
3487 if (len < 0) {
3488 lua_pushfstring(L, "length out of range.");
3489 WILL_LJMP(lua_error(L));
3490 }
3491 }
3492
3493 for (l = 0; l < len; l++) {
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003494 if (l + offset >= output + input)
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003495 break;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003496 if (*(b_peek(&chn->buf, offset + l)) == '\n') {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003497 len = l+1;
3498 goto dup;
3499 }
3500 }
3501
Christopher Faulet0ae2e632023-01-10 15:29:54 +01003502 /* Wait for more data if possible if no line is found and no length was
3503 * specified or not enough data was received.
3504 */
3505 if (lua_gettop(L) != 3 || offset + len > output + input) {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003506 if (!HLUA_CANT_YIELD(hlua_gethlua(L)) && !channel_input_closed(chn) && channel_may_recv(chn)) {
3507 /* Yield waiting for more data */
3508 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_get_line_yield, TICK_ETERNITY, 0));
3509 }
Christopher Faulet0ae2e632023-01-10 15:29:54 +01003510
3511 /* Return 'nil' if there is no data and the channel can't receive more data */
3512 if (!len) {
3513 lua_pushnil(L);
3514 return -1;
3515 }
3516
3517 /* Otherwise, return all data */
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003518 len = output + input - offset;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003519 }
3520
3521 dup:
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003522 _hlua_channel_dup(chn, L, offset, len);
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003523 return 1;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003524}
3525
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003526/* [ DEPRECATED ]
3527 *
3528 * Duplicate all input data foud in the channel's buffer. The data are not
3529 * removed from the buffer. This function relies on _hlua_channel_dup().
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003530 *
3531 * From an action, All input data are considered. For a filter, the offset and
3532 * the length of input data to consider are retrieved from the filter context.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003533 */
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003534__LJMP static int hlua_channel_dup(lua_State *L)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003535{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003536 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003537 struct filter *filter;
3538 size_t offset, len;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003539
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003540 MAY_LJMP(check_args(L, 1, "dup"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003541 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003542 if (IS_HTX_STRM(chn_strm(chn))) {
3543 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3544 WILL_LJMP(lua_error(L));
3545 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003546
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003547 offset = co_data(chn);
3548 len = ci_data(chn);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003549
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003550 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3551 if (filter && !hlua_filter_from_payload(filter))
3552 WILL_LJMP(lua_error(L));
3553
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003554 if (!ci_data(chn) && channel_input_closed(chn)) {
3555 lua_pushnil(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003556 return 1;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003557 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003558
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003559 _hlua_channel_dup(chn, L, offset, len);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003560 return 1;
3561}
3562
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003563/* [ DEPRECATED ]
3564 *
3565 * Get all input data foud in the channel's buffer. The data are removed from
3566 * the buffer after the copy. This function relies on _hlua_channel_dup() and
3567 * _hlua_channel_delete().
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003568 *
3569 * From an action, All input data are considered. For a filter, the offset and
3570 * the length of input data to consider are retrieved from the filter context.
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003571 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003572__LJMP static int hlua_channel_get(lua_State *L)
3573{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003574 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003575 struct filter *filter;
3576 size_t offset, len;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003577 int ret;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003578
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003579 MAY_LJMP(check_args(L, 1, "get"));
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003580 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3581 if (IS_HTX_STRM(chn_strm(chn))) {
3582 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3583 WILL_LJMP(lua_error(L));
3584 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003585
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003586 offset = co_data(chn);
3587 len = ci_data(chn);
3588
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003589 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3590 if (filter && !hlua_filter_from_payload(filter))
3591 WILL_LJMP(lua_error(L));
3592
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003593 if (!ci_data(chn) && channel_input_closed(chn)) {
3594 lua_pushnil(L);
3595 return 1;
3596 }
3597
3598 ret = _hlua_channel_dup(chn, L, offset, len);
3599 _hlua_channel_delete(chn, offset, ret);
3600 return 1;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003601}
3602
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003603/* This functions consumes and returns one line. If the channel is closed,
3604 * and the last data does not contains a final '\n', the data are returned
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003605 * without the final '\n'. When no more data are available, it returns nil
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003606 * value.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003607 *
3608 * From an action, All input data are considered. For a filter, the offset and
3609 * the length of input data to consider are retrieved from the filter context.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003610 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003611__LJMP static int hlua_channel_getline_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003612{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003613 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003614 struct filter *filter;
3615 size_t l, offset, len;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003616 int ret;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003617
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003618 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003619
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003620 offset = co_data(chn);
3621 len = ci_data(chn);
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003622
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003623 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3624 if (filter && !hlua_filter_from_payload(filter))
3625 WILL_LJMP(lua_error(L));
3626
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003627 if (!ci_data(chn) && channel_input_closed(chn)) {
3628 lua_pushnil(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003629 return 1;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003630 }
3631
3632 for (l = 0; l < len; l++) {
3633 if (*(b_peek(&chn->buf, offset+l)) == '\n') {
3634 len = l+1;
3635 goto dup;
3636 }
3637 }
3638
3639 if (!HLUA_CANT_YIELD(hlua_gethlua(L)) && !channel_input_closed(chn) && channel_may_recv(chn)) {
3640 /* Yield waiting for more data */
3641 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_getline_yield, TICK_ETERNITY, 0));
3642 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003643
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003644 dup:
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003645 ret = _hlua_channel_dup(chn, L, offset, len);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003646 _hlua_channel_delete(chn, offset, ret);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003647 return 1;
3648}
3649
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003650/* [ DEPRECATED ]
3651 *
3652 * Check arguments for the function "hlua_channel_getline_yield".
3653 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003654__LJMP static int hlua_channel_getline(lua_State *L)
3655{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003656 struct channel *chn;
3657
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003658 MAY_LJMP(check_args(L, 1, "getline"));
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003659 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3660 if (IS_HTX_STRM(chn_strm(chn))) {
3661 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3662 WILL_LJMP(lua_error(L));
3663 }
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003664 return MAY_LJMP(hlua_channel_getline_yield(L, 0, 0));
3665}
3666
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003667/* Retrieves a given amount of input data at the given offset. By default all
3668 * available input data are returned. The offset may be negactive to start from
3669 * the end of input data. The length may be -1 to set it to the maximum buffer
3670 * size.
3671 */
3672__LJMP static int hlua_channel_get_data(lua_State *L)
3673{
3674 struct channel *chn;
3675
3676 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
3677 WILL_LJMP(luaL_error(L, "'data' expects at most 2 arguments"));
3678 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3679 if (IS_HTX_STRM(chn_strm(chn))) {
3680 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3681 WILL_LJMP(lua_error(L));
3682 }
3683 return MAY_LJMP(hlua_channel_get_data_yield(L, 0, 0));
3684}
3685
3686/* Retrieves a given amount of input data at the given offset. By default all
3687 * available input data are returned. The offset may be negactive to start from
3688 * the end of input data. The length may be -1 to set it to the maximum buffer
3689 * size.
3690 */
3691__LJMP static int hlua_channel_get_line(lua_State *L)
3692{
3693 struct channel *chn;
3694
3695 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
3696 WILL_LJMP(luaL_error(L, "'line' expects at most 2 arguments"));
3697 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3698 if (IS_HTX_STRM(chn_strm(chn))) {
3699 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3700 WILL_LJMP(lua_error(L));
3701 }
3702 return MAY_LJMP(hlua_channel_get_line_yield(L, 0, 0));
3703}
3704
3705/* Appends a string into the input side of channel. It returns the length of the
3706 * written string, or -1 if the channel is closed or if the buffer size is too
3707 * little for the data. 0 may be returned if nothing is copied. This function
3708 * does not yield.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003709 *
3710 * For a filter, the context is updated on success.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003711 */
Christopher Faulet23976d92021-08-06 09:59:49 +02003712__LJMP static int hlua_channel_append(lua_State *L)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003713{
Christopher Faulet23976d92021-08-06 09:59:49 +02003714 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003715 struct filter *filter;
Christopher Faulet23976d92021-08-06 09:59:49 +02003716 const char *str;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003717 size_t sz, offset, len;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003718 int ret;
Christopher Faulet23976d92021-08-06 09:59:49 +02003719
3720 MAY_LJMP(check_args(L, 2, "append"));
3721 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003722 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
Christopher Faulet1bb6afa2021-03-08 17:57:53 +01003723 if (IS_HTX_STRM(chn_strm(chn))) {
Thierry Fournier77016da2020-08-15 14:35:51 +02003724 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
Christopher Faulet3f829a42018-12-13 21:56:45 +01003725 WILL_LJMP(lua_error(L));
Thierry Fournier77016da2020-08-15 14:35:51 +02003726 }
Christopher Faulet3f829a42018-12-13 21:56:45 +01003727
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003728 offset = co_data(chn);
3729 len = ci_data(chn);
3730
3731 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3732 if (filter && !hlua_filter_from_payload(filter))
3733 WILL_LJMP(lua_error(L));
3734
3735 ret = _hlua_channel_insert(chn, L, ist2(str, sz), offset);
3736 if (ret > 0 && filter) {
3737 struct hlua_flt_ctx *flt_ctx = filter->ctx;
3738
3739 flt_update_offsets(filter, chn, ret);
3740 flt_ctx->cur_len[CHN_IDX(chn)] += ret;
3741 }
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003742 lua_pushinteger(L, ret);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003743 return 1;
3744}
3745
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003746/* Prepends a string into the input side of channel. It returns the length of the
3747 * written string, or -1 if the channel is closed or if the buffer size is too
3748 * little for the data. 0 may be returned if nothing is copied. This function
3749 * does not yield.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003750 *
3751 * For a filter, the context is updated on success.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003752 */
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003753__LJMP static int hlua_channel_prepend(lua_State *L)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003754{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003755 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003756 struct filter *filter;
Christopher Faulet23976d92021-08-06 09:59:49 +02003757 const char *str;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003758 size_t sz, offset, len;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003759 int ret;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003760
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003761 MAY_LJMP(check_args(L, 2, "prepend"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003762 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003763 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
3764 if (IS_HTX_STRM(chn_strm(chn))) {
3765 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3766 WILL_LJMP(lua_error(L));
3767 }
3768
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003769 offset = co_data(chn);
3770 len = ci_data(chn);
3771
3772 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3773 if (filter && !hlua_filter_from_payload(filter))
3774 WILL_LJMP(lua_error(L));
3775
3776 ret = _hlua_channel_insert(chn, L, ist2(str, sz), offset);
3777 if (ret > 0 && filter) {
3778 struct hlua_flt_ctx *flt_ctx = filter->ctx;
3779
3780 flt_update_offsets(filter, chn, ret);
3781 flt_ctx->cur_len[CHN_IDX(chn)] += ret;
3782 }
3783
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003784 lua_pushinteger(L, ret);
3785 return 1;
3786}
3787
3788/* Inserts a given amount of input data at the given offset by a string
Aurelien DARRAGONafb7daf2022-10-04 12:16:05 +02003789 * content. By default the string is appended in front of input data. It
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003790 * returns the length of the written string, or -1 if the channel is closed or
3791 * if the buffer size is too little for the data.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003792 *
3793 * For a filter, the context is updated on success.
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003794 */
3795__LJMP static int hlua_channel_insert_data(lua_State *L)
3796{
3797 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003798 struct filter *filter;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003799 const char *str;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003800 size_t sz, input, output;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003801 int ret, offset;
3802
3803 if (lua_gettop(L) < 2 || lua_gettop(L) > 3)
3804 WILL_LJMP(luaL_error(L, "'insert' expects at least 1 argument and at most 2 arguments"));
3805 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3806 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003807
3808 output = co_data(chn);
3809 input = ci_data(chn);
3810
3811 filter = hlua_channel_filter(L, 1, chn, &output, &input);
3812 if (filter && !hlua_filter_from_payload(filter))
3813 WILL_LJMP(lua_error(L));
3814
Aurelien DARRAGONafb7daf2022-10-04 12:16:05 +02003815 offset = output;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003816 if (lua_gettop(L) > 2) {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003817 offset = MAY_LJMP(luaL_checkinteger(L, 3));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003818 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02003819 offset = MAX(0, (int)input + offset);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003820 offset += output;
Aurelien DARRAGONafb7daf2022-10-04 12:16:05 +02003821 if (offset > output + input) {
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003822 lua_pushfstring(L, "offset out of range.");
3823 WILL_LJMP(lua_error(L));
3824 }
3825 }
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003826 if (IS_HTX_STRM(chn_strm(chn))) {
3827 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3828 WILL_LJMP(lua_error(L));
3829 }
3830
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003831 ret = _hlua_channel_insert(chn, L, ist2(str, sz), offset);
3832 if (ret > 0 && filter) {
3833 struct hlua_flt_ctx *flt_ctx = filter->ctx;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003834
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003835 flt_update_offsets(filter, chn, ret);
3836 flt_ctx->cur_len[CHN_IDX(chn)] += ret;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003837 }
3838
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003839 lua_pushinteger(L, ret);
3840 return 1;
3841}
3842/* Replaces a given amount of input data at the given offset by a string
3843 * content. By default all remaining data are removed (offset = 0 and len =
3844 * -1). It returns the length of the written string, or -1 if the channel is
3845 * closed or if the buffer size is too little for the data.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003846 *
3847 * For a filter, the context is updated on success.
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003848 */
3849__LJMP static int hlua_channel_set_data(lua_State *L)
3850{
3851 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003852 struct filter *filter;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003853 const char *str;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003854 size_t sz, input, output;
3855 int ret, offset, len;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003856
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003857 if (lua_gettop(L) < 2 || lua_gettop(L) > 4)
3858 WILL_LJMP(luaL_error(L, "'set' expects at least 1 argument and at most 3 arguments"));
3859 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3860 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003861
Christopher Faulet1bb6afa2021-03-08 17:57:53 +01003862 if (IS_HTX_STRM(chn_strm(chn))) {
Thierry Fournier77016da2020-08-15 14:35:51 +02003863 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
Christopher Faulet3f829a42018-12-13 21:56:45 +01003864 WILL_LJMP(lua_error(L));
Thierry Fournier77016da2020-08-15 14:35:51 +02003865 }
Christopher Faulet3f829a42018-12-13 21:56:45 +01003866
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003867 output = co_data(chn);
3868 input = ci_data(chn);
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003869
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003870 filter = hlua_channel_filter(L, 1, chn, &output, &input);
3871 if (filter && !hlua_filter_from_payload(filter))
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003872 WILL_LJMP(lua_error(L));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003873
3874 offset = output;
3875 if (lua_gettop(L) > 2) {
3876 offset = MAY_LJMP(luaL_checkinteger(L, 3));
3877 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02003878 offset = MAX(0, (int)input + offset);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003879 offset += output;
3880 if (offset < output || offset > input + output) {
3881 lua_pushfstring(L, "offset out of range.");
3882 WILL_LJMP(lua_error(L));
3883 }
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003884 }
3885
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003886 len = output + input - offset;
3887 if (lua_gettop(L) == 4) {
3888 len = MAY_LJMP(luaL_checkinteger(L, 4));
3889 if (!len)
3890 goto set;
3891 if (len == -1)
3892 len = output + input - offset;
3893 if (len < 0 || offset + len > output + input) {
3894 lua_pushfstring(L, "length out of range.");
3895 WILL_LJMP(lua_error(L));
3896 }
3897 }
3898
3899 set:
Christopher Faulet23976d92021-08-06 09:59:49 +02003900 /* Be sure we can copied the string once input data will be removed. */
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003901 if (sz > c_room(chn) + len)
Christopher Faulet23976d92021-08-06 09:59:49 +02003902 lua_pushinteger(L, -1);
3903 else {
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003904 _hlua_channel_delete(chn, offset, len);
3905 ret = _hlua_channel_insert(chn, L, ist2(str, sz), offset);
3906 if (filter) {
3907 struct hlua_flt_ctx *flt_ctx = filter->ctx;
3908
3909 len -= (ret > 0 ? ret : 0);
3910 flt_update_offsets(filter, chn, -len);
3911 flt_ctx->cur_len[CHN_IDX(chn)] -= len;
3912 }
3913
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003914 lua_pushinteger(L, ret);
Christopher Faulet23976d92021-08-06 09:59:49 +02003915 }
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003916 return 1;
3917}
3918
3919/* Removes a given amount of input data at the given offset. By default all
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003920 * input data are removed (offset = 0 and len = -1). It returns the amount of
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003921 * the removed data.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003922 *
3923 * For a filter, the context is updated on success.
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003924 */
3925__LJMP static int hlua_channel_del_data(lua_State *L)
3926{
3927 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003928 struct filter *filter;
3929 size_t input, output;
3930 int offset, len;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003931
3932 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
3933 WILL_LJMP(luaL_error(L, "'remove' expects at most 2 arguments"));
3934 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003935
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003936 if (IS_HTX_STRM(chn_strm(chn))) {
3937 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3938 WILL_LJMP(lua_error(L));
3939 }
3940
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003941 output = co_data(chn);
3942 input = ci_data(chn);
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003943
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003944 filter = hlua_channel_filter(L, 1, chn, &output, &input);
3945 if (filter && !hlua_filter_from_payload(filter))
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003946 WILL_LJMP(lua_error(L));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003947
3948 offset = output;
Boyang Lie0c54352022-05-10 17:47:23 +00003949 if (lua_gettop(L) > 1) {
3950 offset = MAY_LJMP(luaL_checkinteger(L, 2));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003951 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02003952 offset = MAX(0, (int)input + offset);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003953 offset += output;
3954 if (offset < output || offset > input + output) {
3955 lua_pushfstring(L, "offset out of range.");
3956 WILL_LJMP(lua_error(L));
3957 }
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003958 }
3959
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003960 len = output + input - offset;
Boyang Lie0c54352022-05-10 17:47:23 +00003961 if (lua_gettop(L) == 3) {
3962 len = MAY_LJMP(luaL_checkinteger(L, 3));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003963 if (!len)
3964 goto end;
3965 if (len == -1)
3966 len = output + input - offset;
3967 if (len < 0 || offset + len > output + input) {
3968 lua_pushfstring(L, "length out of range.");
3969 WILL_LJMP(lua_error(L));
3970 }
3971 }
3972
3973 _hlua_channel_delete(chn, offset, len);
3974 if (filter) {
3975 struct hlua_flt_ctx *flt_ctx = filter->ctx;
3976
3977 flt_update_offsets(filter, chn, -len);
3978 flt_ctx->cur_len[CHN_IDX(chn)] -= len;
3979 }
3980
3981 end:
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003982 lua_pushinteger(L, len);
Christopher Faulet23976d92021-08-06 09:59:49 +02003983 return 1;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003984}
3985
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003986/* Append data in the output side of the buffer. This data is immediately
3987 * sent. The function returns the amount of data written. If the buffer
3988 * cannot contain the data, the function yields. The function returns -1
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003989 * if the channel is closed.
3990 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003991__LJMP static int hlua_channel_send_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003992{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003993 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003994 struct filter *filter;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003995 const char *str;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003996 size_t offset, len, sz;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003997 int l, ret;
Thierry Fournier4234dbd2020-11-28 13:18:23 +01003998 struct hlua *hlua;
3999
4000 /* Get hlua struct, or NULL if we execute from main lua state */
4001 hlua = hlua_gethlua(L);
4002 if (!hlua) {
4003 lua_pushnil(L);
4004 return 1;
4005 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004006
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02004007 chn = MAY_LJMP(hlua_checkchannel(L, 1));
4008 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
4009 l = MAY_LJMP(luaL_checkinteger(L, 3));
Christopher Faulet3f829a42018-12-13 21:56:45 +01004010
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004011 offset = co_data(chn);
4012 len = ci_data(chn);
4013
4014 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
4015 if (filter && !hlua_filter_from_payload(filter))
4016 WILL_LJMP(lua_error(L));
4017
4018
Willy Tarreau47860ed2015-03-10 14:07:50 +01004019 if (unlikely(channel_output_closed(chn))) {
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004020 lua_pushinteger(L, -1);
4021 return 1;
4022 }
4023
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02004024 len = c_room(chn);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004025 if (len > sz -l) {
4026 if (filter) {
4027 lua_pushinteger(L, -1);
4028 return 1;
4029 }
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02004030 len = sz - l;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004031 }
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01004032
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004033 ret = _hlua_channel_insert(chn, L, ist2(str, len), offset);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02004034 if (ret == -1) {
4035 lua_pop(L, 1);
4036 lua_pushinteger(L, -1);
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01004037 return 1;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02004038 }
4039 if (ret) {
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004040 if (filter) {
4041 struct hlua_flt_ctx *flt_ctx = filter->ctx;
4042
4043
4044 flt_update_offsets(filter, chn, ret);
4045 FLT_OFF(filter, chn) += ret;
4046 flt_ctx->cur_off[CHN_IDX(chn)] += ret;
4047 }
4048 else
4049 c_adv(chn, ret);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004050
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02004051 l += ret;
4052 lua_pop(L, 1);
4053 lua_pushinteger(L, l);
4054 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004055
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02004056 if (l < sz) {
4057 /* Yield only if the channel's output is not empty.
4058 * Otherwise it means we cannot add more data. */
4059 if (co_data(chn) == 0 || HLUA_CANT_YIELD(hlua_gethlua(L)))
Christopher Faulet2e60aa42021-08-05 11:58:37 +02004060 return 1;
4061
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01004062 /* If we are waiting for space in the response buffer, we
4063 * must set the flag WAKERESWR. This flag required the task
4064 * wake up if any activity is detected on the response buffer.
4065 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01004066 if (chn->flags & CF_ISRESP)
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01004067 HLUA_SET_WAKERESWR(hlua);
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01004068 else
4069 HLUA_SET_WAKEREQWR(hlua);
Willy Tarreau9635e032018-10-16 17:52:55 +02004070 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01004071 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004072
4073 return 1;
4074}
4075
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05004076/* Just a wrapper of "_hlua_channel_send". This wrapper permits
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004077 * yield the LUA process, and resume it without checking the
4078 * input arguments.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004079 *
4080 * This function cannot be called from a filter.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004081 */
4082__LJMP static int hlua_channel_send(lua_State *L)
4083{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02004084 struct channel *chn;
4085
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004086 MAY_LJMP(check_args(L, 2, "send"));
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02004087 chn = MAY_LJMP(hlua_checkchannel(L, 1));
4088 if (IS_HTX_STRM(chn_strm(chn))) {
4089 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
4090 WILL_LJMP(lua_error(L));
4091 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004092 lua_pushinteger(L, 0);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01004093 return MAY_LJMP(hlua_channel_send_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004094}
4095
4096/* This function forward and amount of butes. The data pass from
4097 * the input side of the buffer to the output side, and can be
4098 * forwarded. This function never fails.
4099 *
4100 * The Lua function takes an amount of bytes to be forwarded in
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05004101 * input. It returns the number of bytes forwarded.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004102 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01004103__LJMP static int hlua_channel_forward_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004104{
Willy Tarreau47860ed2015-03-10 14:07:50 +01004105 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004106 struct filter *filter;
4107 size_t offset, len, fwd;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02004108 int l, max;
Thierry Fournier4234dbd2020-11-28 13:18:23 +01004109 struct hlua *hlua;
4110
4111 /* Get hlua struct, or NULL if we execute from main lua state */
4112 hlua = hlua_gethlua(L);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02004113 if (!hlua) {
4114 lua_pushnil(L);
Thierry Fournier4234dbd2020-11-28 13:18:23 +01004115 return 1;
Thierry Fournier77016da2020-08-15 14:35:51 +02004116 }
Christopher Faulet3f829a42018-12-13 21:56:45 +01004117
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02004118 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004119 fwd = MAY_LJMP(luaL_checkinteger(L, 2));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004120 l = MAY_LJMP(luaL_checkinteger(L, -1));
4121
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004122 offset = co_data(chn);
4123 len = ci_data(chn);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02004124
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004125 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
4126 if (filter && !hlua_filter_from_payload(filter))
4127 WILL_LJMP(lua_error(L));
4128
4129 max = fwd - l;
4130 if (max > len)
4131 max = len;
4132
4133 if (filter) {
4134 struct hlua_flt_ctx *flt_ctx = filter->ctx;
4135
4136 FLT_OFF(filter, chn) += max;
4137 flt_ctx->cur_off[CHN_IDX(chn)] += max;
4138 flt_ctx->cur_len[CHN_IDX(chn)] -= max;
4139 }
4140 else
4141 channel_forward(chn, max);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004142
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02004143 l += max;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004144 lua_pop(L, 1);
4145 lua_pushinteger(L, l);
4146
4147 /* Check if it miss bytes to forward. */
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004148 if (l < fwd) {
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004149 /* The the input channel or the output channel are closed, we
4150 * must return the amount of data forwarded.
4151 */
Christopher Faulet2e60aa42021-08-05 11:58:37 +02004152 if (channel_input_closed(chn) || channel_output_closed(chn) || HLUA_CANT_YIELD(hlua_gethlua(L)))
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004153 return 1;
4154
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01004155 /* If we are waiting for space data in the response buffer, we
4156 * must set the flag WAKERESWR. This flag required the task
4157 * wake up if any activity is detected on the response buffer.
4158 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01004159 if (chn->flags & CF_ISRESP)
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01004160 HLUA_SET_WAKERESWR(hlua);
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01004161 else
4162 HLUA_SET_WAKEREQWR(hlua);
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01004163
Ilya Shipitsin4a689da2022-10-29 09:34:32 +05004164 /* Otherwise, we can yield waiting for new data in the input side. */
Willy Tarreau9635e032018-10-16 17:52:55 +02004165 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_forward_yield, TICK_ETERNITY, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004166 }
4167
4168 return 1;
4169}
4170
4171/* Just check the input and prepare the stack for the previous
4172 * function "hlua_channel_forward_yield"
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004173 *
4174 * This function cannot be called from a filter.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004175 */
4176__LJMP static int hlua_channel_forward(lua_State *L)
4177{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02004178 struct channel *chn;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004179
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02004180 MAY_LJMP(check_args(L, 2, "forward"));
4181 chn = MAY_LJMP(hlua_checkchannel(L, 1));
4182 if (IS_HTX_STRM(chn_strm(chn))) {
4183 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
4184 WILL_LJMP(lua_error(L));
4185 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004186 lua_pushinteger(L, 0);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01004187 return MAY_LJMP(hlua_channel_forward_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004188}
4189
4190/* Just returns the number of bytes available in the input
4191 * side of the buffer. This function never fails.
4192 */
4193__LJMP static int hlua_channel_get_in_len(lua_State *L)
4194{
Willy Tarreau47860ed2015-03-10 14:07:50 +01004195 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004196 struct filter *filter;
4197 size_t output, input;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004198
Christopher Faulet6a79fc12021-08-06 16:02:36 +02004199 MAY_LJMP(check_args(L, 1, "input"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004200 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004201
4202 output = co_data(chn);
4203 input = ci_data(chn);
4204 filter = hlua_channel_filter(L, 1, chn, &output, &input);
4205 if (filter || !IS_HTX_STRM(chn_strm(chn)))
4206 lua_pushinteger(L, input);
4207 else {
Christopher Fauleta3ceac12018-12-14 13:39:09 +01004208 struct htx *htx = htxbuf(&chn->buf);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004209
Christopher Fauleta3ceac12018-12-14 13:39:09 +01004210 lua_pushinteger(L, htx->data - co_data(chn));
4211 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004212 return 1;
4213}
4214
Thierry FOURNIER / OZON.IO65192f32016-11-07 15:28:40 +01004215/* Returns true if the channel is full. */
4216__LJMP static int hlua_channel_is_full(lua_State *L)
4217{
4218 struct channel *chn;
Thierry FOURNIER / OZON.IO65192f32016-11-07 15:28:40 +01004219
4220 MAY_LJMP(check_args(L, 1, "is_full"));
4221 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Faulet0ec740e2020-02-26 11:59:19 +01004222 /* ignore the reserve, we are not on a producer side (ie in an
4223 * applet).
4224 */
4225 lua_pushboolean(L, channel_full(chn, 0));
Thierry FOURNIER / OZON.IO65192f32016-11-07 15:28:40 +01004226 return 1;
4227}
4228
Christopher Faulet6a79fc12021-08-06 16:02:36 +02004229/* Returns true if the channel may still receive data. */
4230__LJMP static int hlua_channel_may_recv(lua_State *L)
4231{
4232 struct channel *chn;
4233
4234 MAY_LJMP(check_args(L, 1, "may_recv"));
4235 chn = MAY_LJMP(hlua_checkchannel(L, 1));
4236 lua_pushboolean(L, (!channel_input_closed(chn) && channel_may_recv(chn)));
4237 return 1;
4238}
4239
Christopher Faulet2ac9ba22020-02-25 10:15:50 +01004240/* Returns true if the channel is the response channel. */
4241__LJMP static int hlua_channel_is_resp(lua_State *L)
4242{
4243 struct channel *chn;
4244
4245 MAY_LJMP(check_args(L, 1, "is_resp"));
4246 chn = MAY_LJMP(hlua_checkchannel(L, 1));
4247
4248 lua_pushboolean(L, !!(chn->flags & CF_ISRESP));
4249 return 1;
4250}
4251
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004252/* Just returns the number of bytes available in the output
4253 * side of the buffer. This function never fails.
4254 */
4255__LJMP static int hlua_channel_get_out_len(lua_State *L)
4256{
Willy Tarreau47860ed2015-03-10 14:07:50 +01004257 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004258 size_t output, input;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004259
Christopher Faulet6a79fc12021-08-06 16:02:36 +02004260 MAY_LJMP(check_args(L, 1, "output"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004261 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004262
4263 output = co_data(chn);
4264 input = ci_data(chn);
4265 hlua_channel_filter(L, 1, chn, &output, &input);
4266
4267 lua_pushinteger(L, output);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004268 return 1;
4269}
4270
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004271/*
4272 *
4273 *
4274 * Class Fetches
4275 *
4276 *
4277 */
4278
4279/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02004280 * a class stream, otherwise it throws an error.
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004281 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004282__LJMP static struct hlua_smp *hlua_checkfetches(lua_State *L, int ud)
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004283{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004284 return MAY_LJMP(hlua_checkudata(L, ud, class_fetches_ref));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004285}
4286
4287/* This function creates and push in the stack a fetch object according
4288 * with a current TXN.
4289 */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004290static int hlua_fetches_new(lua_State *L, struct hlua_txn *txn, unsigned int flags)
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004291{
Willy Tarreau7073c472015-04-06 11:15:40 +02004292 struct hlua_smp *hsmp;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004293
4294 /* Check stack size. */
4295 if (!lua_checkstack(L, 3))
4296 return 0;
4297
4298 /* Create the object: obj[0] = userdata.
4299 * Note that the base of the Fetches object is the
4300 * transaction object.
4301 */
4302 lua_newtable(L);
Willy Tarreau7073c472015-04-06 11:15:40 +02004303 hsmp = lua_newuserdata(L, sizeof(*hsmp));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004304 lua_rawseti(L, -2, 0);
4305
Willy Tarreau7073c472015-04-06 11:15:40 +02004306 hsmp->s = txn->s;
4307 hsmp->p = txn->p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01004308 hsmp->dir = txn->dir;
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004309 hsmp->flags = flags;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004310
4311 /* Pop a class sesison metatable and affect it to the userdata. */
4312 lua_rawgeti(L, LUA_REGISTRYINDEX, class_fetches_ref);
4313 lua_setmetatable(L, -2);
4314
4315 return 1;
4316}
4317
4318/* This function is an LUA binding. It is called with each sample-fetch.
4319 * It uses closure argument to store the associated sample-fetch. It
4320 * returns only one argument or throws an error. An error is thrown
4321 * only if an error is encountered during the argument parsing. If
4322 * the "sample-fetch" function fails, nil is returned.
4323 */
4324__LJMP static int hlua_run_sample_fetch(lua_State *L)
4325{
Willy Tarreaub2ccb562015-04-06 11:11:15 +02004326 struct hlua_smp *hsmp;
Willy Tarreau2ec22742015-03-10 14:27:20 +01004327 struct sample_fetch *f;
Frédéric Lécaillef874a832018-06-15 13:56:04 +02004328 struct arg args[ARGM_NBARGS + 1] = {{0}};
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004329 int i;
4330 struct sample smp;
4331
4332 /* Get closure arguments. */
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004333 f = lua_touserdata(L, lua_upvalueindex(1));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004334
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004335 /* Get traditional arguments. */
Willy Tarreaub2ccb562015-04-06 11:11:15 +02004336 hsmp = MAY_LJMP(hlua_checkfetches(L, 1));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004337
Thierry FOURNIERca988662015-12-20 18:43:03 +01004338 /* Check execution authorization. */
4339 if (f->use & SMP_USE_HTTP_ANY &&
4340 !(hsmp->flags & HLUA_F_MAY_USE_HTTP)) {
4341 lua_pushfstring(L, "the sample-fetch '%s' needs an HTTP parser which "
4342 "is not available in Lua services", f->kw);
4343 WILL_LJMP(lua_error(L));
4344 }
4345
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004346 /* Get extra arguments. */
4347 for (i = 0; i < lua_gettop(L) - 1; i++) {
4348 if (i >= ARGM_NBARGS)
4349 break;
4350 hlua_lua2arg(L, i + 2, &args[i]);
4351 }
4352 args[i].type = ARGT_STOP;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004353 args[i].data.str.area = NULL;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004354
4355 /* Check arguments. */
Willy Tarreaub2ccb562015-04-06 11:11:15 +02004356 MAY_LJMP(hlua_lua2arg_check(L, 2, args, f->arg_mask, hsmp->p));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004357
4358 /* Run the special args checker. */
Willy Tarreau2ec22742015-03-10 14:27:20 +01004359 if (f->val_args && !f->val_args(args, NULL)) {
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004360 lua_pushfstring(L, "error in arguments");
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004361 goto error;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004362 }
4363
4364 /* Initialise the sample. */
4365 memset(&smp, 0, sizeof(smp));
4366
4367 /* Run the sample fetch process. */
Willy Tarreau1777ea62016-03-10 16:15:46 +01004368 smp_set_owner(&smp, hsmp->p, hsmp->s->sess, hsmp->s, hsmp->dir & SMP_OPT_DIR);
Thierry FOURNIER0786d052015-05-11 15:42:45 +02004369 if (!f->process(args, &smp, f->kw, f->private)) {
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004370 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004371 lua_pushstring(L, "");
4372 else
4373 lua_pushnil(L);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004374 goto end;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004375 }
4376
4377 /* Convert the returned sample in lua value. */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004378 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004379 hlua_smp2lua_str(L, &smp);
4380 else
4381 hlua_smp2lua(L, &smp);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004382
4383 end:
Willy Tarreauee0d7272021-07-16 10:26:56 +02004384 free_args(args);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004385 return 1;
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004386
4387 error:
Willy Tarreauee0d7272021-07-16 10:26:56 +02004388 free_args(args);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004389 WILL_LJMP(lua_error(L));
4390 return 0; /* Never reached */
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004391}
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004392
4393/*
4394 *
4395 *
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004396 * Class Converters
4397 *
4398 *
4399 */
4400
4401/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02004402 * a class stream, otherwise it throws an error.
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004403 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004404__LJMP static struct hlua_smp *hlua_checkconverters(lua_State *L, int ud)
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004405{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004406 return MAY_LJMP(hlua_checkudata(L, ud, class_converters_ref));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004407}
4408
4409/* This function creates and push in the stack a Converters object
4410 * according with a current TXN.
4411 */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004412static int hlua_converters_new(lua_State *L, struct hlua_txn *txn, unsigned int flags)
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004413{
Willy Tarreau7073c472015-04-06 11:15:40 +02004414 struct hlua_smp *hsmp;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004415
4416 /* Check stack size. */
4417 if (!lua_checkstack(L, 3))
4418 return 0;
4419
4420 /* Create the object: obj[0] = userdata.
4421 * Note that the base of the Converters object is the
4422 * same than the TXN object.
4423 */
4424 lua_newtable(L);
Willy Tarreau7073c472015-04-06 11:15:40 +02004425 hsmp = lua_newuserdata(L, sizeof(*hsmp));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004426 lua_rawseti(L, -2, 0);
4427
Willy Tarreau7073c472015-04-06 11:15:40 +02004428 hsmp->s = txn->s;
4429 hsmp->p = txn->p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01004430 hsmp->dir = txn->dir;
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004431 hsmp->flags = flags;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004432
Willy Tarreau87b09662015-04-03 00:22:06 +02004433 /* Pop a class stream metatable and affect it to the table. */
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004434 lua_rawgeti(L, LUA_REGISTRYINDEX, class_converters_ref);
4435 lua_setmetatable(L, -2);
4436
4437 return 1;
4438}
4439
4440/* This function is an LUA binding. It is called with each converter.
4441 * It uses closure argument to store the associated converter. It
4442 * returns only one argument or throws an error. An error is thrown
4443 * only if an error is encountered during the argument parsing. If
4444 * the converter function function fails, nil is returned.
4445 */
4446__LJMP static int hlua_run_sample_conv(lua_State *L)
4447{
Willy Tarreauda5f1082015-04-06 11:17:13 +02004448 struct hlua_smp *hsmp;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004449 struct sample_conv *conv;
Frédéric Lécaillef874a832018-06-15 13:56:04 +02004450 struct arg args[ARGM_NBARGS + 1] = {{0}};
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004451 int i;
4452 struct sample smp;
4453
4454 /* Get closure arguments. */
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004455 conv = lua_touserdata(L, lua_upvalueindex(1));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004456
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004457 /* Get traditional arguments. */
Willy Tarreauda5f1082015-04-06 11:17:13 +02004458 hsmp = MAY_LJMP(hlua_checkconverters(L, 1));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004459
4460 /* Get extra arguments. */
4461 for (i = 0; i < lua_gettop(L) - 2; i++) {
4462 if (i >= ARGM_NBARGS)
4463 break;
4464 hlua_lua2arg(L, i + 3, &args[i]);
4465 }
4466 args[i].type = ARGT_STOP;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004467 args[i].data.str.area = NULL;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004468
4469 /* Check arguments. */
Willy Tarreauda5f1082015-04-06 11:17:13 +02004470 MAY_LJMP(hlua_lua2arg_check(L, 3, args, conv->arg_mask, hsmp->p));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004471
4472 /* Run the special args checker. */
4473 if (conv->val_args && !conv->val_args(args, conv, "", 0, NULL)) {
4474 hlua_pusherror(L, "error in arguments");
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004475 goto error;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004476 }
4477
4478 /* Initialise the sample. */
Amaury Denoyellebc0af6a2020-10-29 17:21:20 +01004479 memset(&smp, 0, sizeof(smp));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004480 if (!hlua_lua2smp(L, 2, &smp)) {
4481 hlua_pusherror(L, "error in the input argument");
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004482 goto error;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004483 }
4484
Willy Tarreau1777ea62016-03-10 16:15:46 +01004485 smp_set_owner(&smp, hsmp->p, hsmp->s->sess, hsmp->s, hsmp->dir & SMP_OPT_DIR);
4486
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004487 /* Apply expected cast. */
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02004488 if (!sample_casts[smp.data.type][conv->in_type]) {
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004489 hlua_pusherror(L, "invalid input argument: cannot cast '%s' to '%s'",
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02004490 smp_to_type[smp.data.type], smp_to_type[conv->in_type]);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004491 goto error;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004492 }
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02004493 if (sample_casts[smp.data.type][conv->in_type] != c_none &&
4494 !sample_casts[smp.data.type][conv->in_type](&smp)) {
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004495 hlua_pusherror(L, "error during the input argument casting");
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004496 goto error;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004497 }
4498
4499 /* Run the sample conversion process. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02004500 if (!conv->process(args, &smp, conv->private)) {
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004501 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004502 lua_pushstring(L, "");
4503 else
Willy Tarreaua678b432015-08-28 10:14:59 +02004504 lua_pushnil(L);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004505 goto end;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004506 }
4507
4508 /* Convert the returned sample in lua value. */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004509 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004510 hlua_smp2lua_str(L, &smp);
4511 else
4512 hlua_smp2lua(L, &smp);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004513 end:
Willy Tarreauee0d7272021-07-16 10:26:56 +02004514 free_args(args);
Willy Tarreaua678b432015-08-28 10:14:59 +02004515 return 1;
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004516
4517 error:
Willy Tarreauee0d7272021-07-16 10:26:56 +02004518 free_args(args);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004519 WILL_LJMP(lua_error(L));
4520 return 0; /* Never reached */
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004521}
4522
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004523/*
4524 *
4525 *
4526 * Class AppletTCP
4527 *
4528 *
4529 */
4530
4531/* Returns a struct hlua_txn if the stack entry "ud" is
4532 * a class stream, otherwise it throws an error.
4533 */
4534__LJMP static struct hlua_appctx *hlua_checkapplet_tcp(lua_State *L, int ud)
4535{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004536 return MAY_LJMP(hlua_checkudata(L, ud, class_applet_tcp_ref));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004537}
4538
4539/* This function creates and push in the stack an Applet object
4540 * according with a current TXN.
4541 */
4542static int hlua_applet_tcp_new(lua_State *L, struct appctx *ctx)
4543{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004544 struct hlua_appctx *luactx;
Willy Tarreau0698c802022-05-11 14:09:57 +02004545 struct stream *s = appctx_strm(ctx);
Christopher Faulet2da02ae2022-02-24 13:45:27 +01004546 struct proxy *p;
4547
4548 ALREADY_CHECKED(s);
4549 p = s->be;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004550
4551 /* Check stack size. */
4552 if (!lua_checkstack(L, 3))
4553 return 0;
4554
4555 /* Create the object: obj[0] = userdata.
4556 * Note that the base of the Converters object is the
4557 * same than the TXN object.
4558 */
4559 lua_newtable(L);
Willy Tarreau7e702d12021-04-28 17:59:21 +02004560 luactx = lua_newuserdata(L, sizeof(*luactx));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004561 lua_rawseti(L, -2, 0);
Willy Tarreau7e702d12021-04-28 17:59:21 +02004562 luactx->appctx = ctx;
4563 luactx->htxn.s = s;
4564 luactx->htxn.p = p;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004565
4566 /* Create the "f" field that contains a list of fetches. */
4567 lua_pushstring(L, "f");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004568 if (!hlua_fetches_new(L, &luactx->htxn, 0))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004569 return 0;
4570 lua_settable(L, -3);
4571
4572 /* Create the "sf" field that contains a list of stringsafe fetches. */
4573 lua_pushstring(L, "sf");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004574 if (!hlua_fetches_new(L, &luactx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004575 return 0;
4576 lua_settable(L, -3);
4577
4578 /* Create the "c" field that contains a list of converters. */
4579 lua_pushstring(L, "c");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004580 if (!hlua_converters_new(L, &luactx->htxn, 0))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004581 return 0;
4582 lua_settable(L, -3);
4583
4584 /* Create the "sc" field that contains a list of stringsafe converters. */
4585 lua_pushstring(L, "sc");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004586 if (!hlua_converters_new(L, &luactx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004587 return 0;
4588 lua_settable(L, -3);
4589
4590 /* Pop a class stream metatable and affect it to the table. */
4591 lua_rawgeti(L, LUA_REGISTRYINDEX, class_applet_tcp_ref);
4592 lua_setmetatable(L, -2);
4593
4594 return 1;
4595}
4596
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004597__LJMP static int hlua_applet_tcp_set_var(lua_State *L)
4598{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004599 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004600 struct stream *s;
4601 const char *name;
4602 size_t len;
4603 struct sample smp;
4604
Tim Duesterhus4e172c92020-05-19 13:49:42 +02004605 if (lua_gettop(L) < 3 || lua_gettop(L) > 4)
4606 WILL_LJMP(luaL_error(L, "'set_var' needs between 3 and 4 arguments"));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004607
4608 /* It is useles to retrieve the stream, but this function
4609 * runs only in a stream context.
4610 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004611 luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004612 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02004613 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004614
4615 /* Converts the third argument in a sample. */
Amaury Denoyellebc0af6a2020-10-29 17:21:20 +01004616 memset(&smp, 0, sizeof(smp));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004617 hlua_lua2smp(L, 3, &smp);
4618
4619 /* Store the sample in a variable. */
4620 smp_set_owner(&smp, s->be, s->sess, s, 0);
Tim Duesterhus4e172c92020-05-19 13:49:42 +02004621
4622 if (lua_gettop(L) == 4 && lua_toboolean(L, 4))
4623 lua_pushboolean(L, vars_set_by_name_ifexist(name, len, &smp) != 0);
4624 else
4625 lua_pushboolean(L, vars_set_by_name(name, len, &smp) != 0);
4626
Tim Duesterhus84ebc132020-05-19 13:49:41 +02004627 return 1;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004628}
4629
4630__LJMP static int hlua_applet_tcp_unset_var(lua_State *L)
4631{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004632 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004633 struct stream *s;
4634 const char *name;
4635 size_t len;
4636 struct sample smp;
4637
4638 MAY_LJMP(check_args(L, 2, "unset_var"));
4639
4640 /* It is useles to retrieve the stream, but this function
4641 * runs only in a stream context.
4642 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004643 luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004644 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02004645 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004646
4647 /* Unset the variable. */
4648 smp_set_owner(&smp, s->be, s->sess, s, 0);
Tim Duesterhus84ebc132020-05-19 13:49:41 +02004649 lua_pushboolean(L, vars_unset_by_name_ifexist(name, len, &smp) != 0);
4650 return 1;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004651}
4652
4653__LJMP static int hlua_applet_tcp_get_var(lua_State *L)
4654{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004655 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004656 struct stream *s;
4657 const char *name;
4658 size_t len;
4659 struct sample smp;
4660
4661 MAY_LJMP(check_args(L, 2, "get_var"));
4662
4663 /* It is useles to retrieve the stream, but this function
4664 * runs only in a stream context.
4665 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004666 luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004667 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02004668 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004669
4670 smp_set_owner(&smp, s->be, s->sess, s, 0);
Willy Tarreaue352b9d2021-09-03 11:52:38 +02004671 if (!vars_get_by_name(name, len, &smp, NULL)) {
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004672 lua_pushnil(L);
4673 return 1;
4674 }
4675
4676 return hlua_smp2lua(L, &smp);
4677}
4678
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004679__LJMP static int hlua_applet_tcp_set_priv(lua_State *L)
4680{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004681 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
4682 struct stream *s = luactx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01004683 struct hlua *hlua;
4684
4685 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01004686 if (!s->hlua)
4687 return 0;
4688 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004689
4690 MAY_LJMP(check_args(L, 2, "set_priv"));
4691
4692 /* Remove previous value. */
Thierry FOURNIERe068b602017-04-26 13:27:05 +02004693 luaL_unref(L, LUA_REGISTRYINDEX, hlua->Mref);
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004694
4695 /* Get and store new value. */
4696 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
4697 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
4698
4699 return 0;
4700}
4701
4702__LJMP static int hlua_applet_tcp_get_priv(lua_State *L)
4703{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004704 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
4705 struct stream *s = luactx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01004706 struct hlua *hlua;
4707
4708 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01004709 if (!s->hlua) {
4710 lua_pushnil(L);
4711 return 1;
4712 }
4713 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004714
4715 /* Push configuration index in the stack. */
4716 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
4717
4718 return 1;
4719}
4720
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004721/* If expected data not yet available, it returns a yield. This function
4722 * consumes the data in the buffer. It returns a string containing the
4723 * data. This string can be empty.
4724 */
4725__LJMP static int hlua_applet_tcp_getline_yield(lua_State *L, int status, lua_KContext ctx)
4726{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004727 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Willy Tarreauc12b3212022-05-27 11:08:15 +02004728 struct stconn *sc = appctx_sc(luactx->appctx);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004729 int ret;
Willy Tarreau206ba832018-06-14 15:27:31 +02004730 const char *blk1;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004731 size_t len1;
Willy Tarreau206ba832018-06-14 15:27:31 +02004732 const char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004733 size_t len2;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004734
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004735 /* Read the maximum amount of data available. */
Willy Tarreau3e7be362022-05-27 10:35:27 +02004736 ret = co_getline_nc(sc_oc(sc), &blk1, &len1, &blk2, &len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004737
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004738 /* Data not yet available. return yield. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004739 if (ret == 0) {
Willy Tarreau90e8b452022-05-25 18:21:43 +02004740 applet_need_more_data(luactx->appctx);
Willy Tarreau9635e032018-10-16 17:52:55 +02004741 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_getline_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004742 }
4743
4744 /* End of data: commit the total strings and return. */
4745 if (ret < 0) {
Willy Tarreau7e702d12021-04-28 17:59:21 +02004746 luaL_pushresult(&luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004747 return 1;
4748 }
4749
4750 /* Ensure that the block 2 length is usable. */
4751 if (ret == 1)
4752 len2 = 0;
4753
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -07004754 /* don't check the max length read and don't check. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004755 luaL_addlstring(&luactx->b, blk1, len1);
4756 luaL_addlstring(&luactx->b, blk2, len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004757
4758 /* Consume input channel output buffer data. */
Willy Tarreau3e7be362022-05-27 10:35:27 +02004759 co_skip(sc_oc(sc), len1 + len2);
Willy Tarreau7e702d12021-04-28 17:59:21 +02004760 luaL_pushresult(&luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004761 return 1;
4762}
4763
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004764/* Check arguments for the function "hlua_channel_get_yield". */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004765__LJMP static int hlua_applet_tcp_getline(lua_State *L)
4766{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004767 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004768
4769 /* Initialise the string catenation. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004770 luaL_buffinit(L, &luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004771
4772 return MAY_LJMP(hlua_applet_tcp_getline_yield(L, 0, 0));
4773}
4774
4775/* If expected data not yet available, it returns a yield. This function
4776 * consumes the data in the buffer. It returns a string containing the
4777 * data. This string can be empty.
4778 */
4779__LJMP static int hlua_applet_tcp_recv_yield(lua_State *L, int status, lua_KContext ctx)
4780{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004781 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Willy Tarreauc12b3212022-05-27 11:08:15 +02004782 struct stconn *sc = appctx_sc(luactx->appctx);
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004783 size_t len = MAY_LJMP(luaL_checkinteger(L, 2));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004784 int ret;
Willy Tarreau206ba832018-06-14 15:27:31 +02004785 const char *blk1;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004786 size_t len1;
Willy Tarreau206ba832018-06-14 15:27:31 +02004787 const char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004788 size_t len2;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004789
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004790 /* Read the maximum amount of data available. */
Willy Tarreau3e7be362022-05-27 10:35:27 +02004791 ret = co_getblk_nc(sc_oc(sc), &blk1, &len1, &blk2, &len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004792
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004793 /* Data not yet available. return yield. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004794 if (ret == 0) {
Willy Tarreau90e8b452022-05-25 18:21:43 +02004795 applet_need_more_data(luactx->appctx);
Willy Tarreau9635e032018-10-16 17:52:55 +02004796 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004797 }
4798
4799 /* End of data: commit the total strings and return. */
4800 if (ret < 0) {
Willy Tarreau7e702d12021-04-28 17:59:21 +02004801 luaL_pushresult(&luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004802 return 1;
4803 }
4804
4805 /* Ensure that the block 2 length is usable. */
4806 if (ret == 1)
4807 len2 = 0;
4808
4809 if (len == -1) {
4810
4811 /* If len == -1, catenate all the data avalaile and
4812 * yield because we want to get all the data until
4813 * the end of data stream.
4814 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004815 luaL_addlstring(&luactx->b, blk1, len1);
4816 luaL_addlstring(&luactx->b, blk2, len2);
Willy Tarreau3e7be362022-05-27 10:35:27 +02004817 co_skip(sc_oc(sc), len1 + len2);
Willy Tarreau90e8b452022-05-25 18:21:43 +02004818 applet_need_more_data(luactx->appctx);
Willy Tarreau9635e032018-10-16 17:52:55 +02004819 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004820
4821 } else {
4822
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05004823 /* Copy the first block caping to the length required. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004824 if (len1 > len)
4825 len1 = len;
Willy Tarreau7e702d12021-04-28 17:59:21 +02004826 luaL_addlstring(&luactx->b, blk1, len1);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004827 len -= len1;
4828
4829 /* Copy the second block. */
4830 if (len2 > len)
4831 len2 = len;
Willy Tarreau7e702d12021-04-28 17:59:21 +02004832 luaL_addlstring(&luactx->b, blk2, len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004833 len -= len2;
4834
4835 /* Consume input channel output buffer data. */
Willy Tarreau3e7be362022-05-27 10:35:27 +02004836 co_skip(sc_oc(sc), len1 + len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004837
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004838 /* If there is no other data available, yield waiting for new data. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004839 if (len > 0) {
4840 lua_pushinteger(L, len);
4841 lua_replace(L, 2);
Willy Tarreau90e8b452022-05-25 18:21:43 +02004842 applet_need_more_data(luactx->appctx);
Willy Tarreau9635e032018-10-16 17:52:55 +02004843 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004844 }
4845
4846 /* return the result. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004847 luaL_pushresult(&luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004848 return 1;
4849 }
4850
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004851 /* we never execute this */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004852 hlua_pusherror(L, "Lua: internal error");
4853 WILL_LJMP(lua_error(L));
4854 return 0;
4855}
4856
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004857/* Check arguments for the function "hlua_channel_get_yield". */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004858__LJMP static int hlua_applet_tcp_recv(lua_State *L)
4859{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004860 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004861 int len = -1;
4862
4863 if (lua_gettop(L) > 2)
4864 WILL_LJMP(luaL_error(L, "The 'recv' function requires between 1 and 2 arguments."));
4865 if (lua_gettop(L) >= 2) {
4866 len = MAY_LJMP(luaL_checkinteger(L, 2));
4867 lua_pop(L, 1);
4868 }
4869
4870 /* Confirm or set the required length */
4871 lua_pushinteger(L, len);
4872
4873 /* Initialise the string catenation. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004874 luaL_buffinit(L, &luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004875
4876 return MAY_LJMP(hlua_applet_tcp_recv_yield(L, 0, 0));
4877}
4878
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004879/* Append data in the output side of the buffer. This data is immediately
4880 * sent. The function returns the amount of data written. If the buffer
4881 * cannot contain the data, the function yields. The function returns -1
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004882 * if the channel is closed.
4883 */
4884__LJMP static int hlua_applet_tcp_send_yield(lua_State *L, int status, lua_KContext ctx)
4885{
4886 size_t len;
Willy Tarreau7e702d12021-04-28 17:59:21 +02004887 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004888 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
4889 int l = MAY_LJMP(luaL_checkinteger(L, 3));
Willy Tarreauc12b3212022-05-27 11:08:15 +02004890 struct stconn *sc = appctx_sc(luactx->appctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02004891 struct channel *chn = sc_ic(sc);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004892 int max;
4893
4894 /* Get the max amount of data which can write as input in the channel. */
4895 max = channel_recv_max(chn);
4896 if (max > (len - l))
4897 max = len - l;
4898
4899 /* Copy data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02004900 ci_putblk(chn, str + l, max);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004901
4902 /* update counters. */
4903 l += max;
4904 lua_pop(L, 1);
4905 lua_pushinteger(L, l);
4906
4907 /* If some data is not send, declares the situation to the
4908 * applet, and returns a yield.
4909 */
4910 if (l < len) {
Willy Tarreau3e7be362022-05-27 10:35:27 +02004911 sc_need_room(sc);
Willy Tarreau9635e032018-10-16 17:52:55 +02004912 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004913 }
4914
4915 return 1;
4916}
4917
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05004918/* Just a wrapper of "hlua_applet_tcp_send_yield". This wrapper permits
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004919 * yield the LUA process, and resume it without checking the
4920 * input arguments.
4921 */
4922__LJMP static int hlua_applet_tcp_send(lua_State *L)
4923{
4924 MAY_LJMP(check_args(L, 2, "send"));
4925 lua_pushinteger(L, 0);
4926
4927 return MAY_LJMP(hlua_applet_tcp_send_yield(L, 0, 0));
4928}
4929
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004930/*
4931 *
4932 *
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004933 * Class AppletHTTP
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004934 *
4935 *
4936 */
4937
4938/* Returns a struct hlua_txn if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02004939 * a class stream, otherwise it throws an error.
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004940 */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004941__LJMP static struct hlua_appctx *hlua_checkapplet_http(lua_State *L, int ud)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004942{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004943 return MAY_LJMP(hlua_checkudata(L, ud, class_applet_http_ref));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004944}
4945
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004946/* This function creates and push in the stack an Applet object
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004947 * according with a current TXN.
Willy Tarreauaa229cc2022-05-06 14:26:10 +02004948 * It relies on the caller to have already reserved the room in ctx->svcctx
4949 * for the local storage of hlua_http_ctx.
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004950 */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004951static int hlua_applet_http_new(lua_State *L, struct appctx *ctx)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004952{
Willy Tarreauaa229cc2022-05-06 14:26:10 +02004953 struct hlua_http_ctx *http_ctx = ctx->svcctx;
Willy Tarreau7e702d12021-04-28 17:59:21 +02004954 struct hlua_appctx *luactx;
Thierry FOURNIER841475e2015-12-11 17:10:09 +01004955 struct hlua_txn htxn;
Willy Tarreau0698c802022-05-11 14:09:57 +02004956 struct stream *s = appctx_strm(ctx);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004957 struct proxy *px = s->be;
Christopher Fauleta2097962019-07-15 16:25:33 +02004958 struct htx *htx;
4959 struct htx_blk *blk;
4960 struct htx_sl *sl;
4961 struct ist path;
4962 unsigned long long len = 0;
4963 int32_t pos;
Amaury Denoyellec453f952021-07-06 11:40:12 +02004964 struct http_uri_parser parser;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004965
4966 /* Check stack size. */
4967 if (!lua_checkstack(L, 3))
4968 return 0;
4969
4970 /* Create the object: obj[0] = userdata.
4971 * Note that the base of the Converters object is the
4972 * same than the TXN object.
4973 */
4974 lua_newtable(L);
Willy Tarreau7e702d12021-04-28 17:59:21 +02004975 luactx = lua_newuserdata(L, sizeof(*luactx));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004976 lua_rawseti(L, -2, 0);
Willy Tarreau7e702d12021-04-28 17:59:21 +02004977 luactx->appctx = ctx;
Willy Tarreauaa229cc2022-05-06 14:26:10 +02004978 http_ctx->status = 200; /* Default status code returned. */
4979 http_ctx->reason = NULL; /* Use default reason based on status */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004980 luactx->htxn.s = s;
4981 luactx->htxn.p = px;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004982
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004983 /* Create the "f" field that contains a list of fetches. */
4984 lua_pushstring(L, "f");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004985 if (!hlua_fetches_new(L, &luactx->htxn, 0))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004986 return 0;
4987 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004988
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004989 /* Create the "sf" field that contains a list of stringsafe fetches. */
4990 lua_pushstring(L, "sf");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004991 if (!hlua_fetches_new(L, &luactx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004992 return 0;
4993 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004994
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004995 /* Create the "c" field that contains a list of converters. */
4996 lua_pushstring(L, "c");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004997 if (!hlua_converters_new(L, &luactx->htxn, 0))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004998 return 0;
4999 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005000
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005001 /* Create the "sc" field that contains a list of stringsafe converters. */
5002 lua_pushstring(L, "sc");
Willy Tarreau7e702d12021-04-28 17:59:21 +02005003 if (!hlua_converters_new(L, &luactx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005004 return 0;
5005 lua_settable(L, -3);
Willy Tarreaueee5b512015-04-03 23:46:31 +02005006
Christopher Fauleta2097962019-07-15 16:25:33 +02005007 htx = htxbuf(&s->req.buf);
5008 blk = htx_get_first_blk(htx);
Christopher Fauletea009732019-11-18 15:50:25 +01005009 BUG_ON(!blk || htx_get_blk_type(blk) != HTX_BLK_REQ_SL);
Christopher Fauleta2097962019-07-15 16:25:33 +02005010 sl = htx_get_blk_ptr(htx, blk);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005011
Christopher Fauleta2097962019-07-15 16:25:33 +02005012 /* Stores the request method. */
5013 lua_pushstring(L, "method");
5014 lua_pushlstring(L, HTX_SL_REQ_MPTR(sl), HTX_SL_REQ_MLEN(sl));
5015 lua_settable(L, -3);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005016
Christopher Fauleta2097962019-07-15 16:25:33 +02005017 /* Stores the http version. */
5018 lua_pushstring(L, "version");
5019 lua_pushlstring(L, HTX_SL_REQ_VPTR(sl), HTX_SL_REQ_VLEN(sl));
5020 lua_settable(L, -3);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005021
Christopher Fauleta2097962019-07-15 16:25:33 +02005022 /* creates an array of headers. hlua_http_get_headers() crates and push
5023 * the array on the top of the stack.
5024 */
5025 lua_pushstring(L, "headers");
5026 htxn.s = s;
5027 htxn.p = px;
5028 htxn.dir = SMP_OPT_DIR_REQ;
Christopher Faulet9d1332b2020-02-24 16:46:16 +01005029 if (!hlua_http_get_headers(L, &htxn.s->txn->req))
Christopher Fauleta2097962019-07-15 16:25:33 +02005030 return 0;
5031 lua_settable(L, -3);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005032
Amaury Denoyellec453f952021-07-06 11:40:12 +02005033 parser = http_uri_parser_init(htx_sl_req_uri(sl));
5034 path = http_parse_path(&parser);
Tim Duesterhused526372020-03-05 17:56:33 +01005035 if (isttest(path)) {
Christopher Fauleta2097962019-07-15 16:25:33 +02005036 char *p, *q, *end;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005037
Christopher Fauleta2097962019-07-15 16:25:33 +02005038 p = path.ptr;
Tim Duesterhus4c8f75f2021-11-06 15:14:44 +01005039 end = istend(path);
Christopher Fauleta2097962019-07-15 16:25:33 +02005040 q = p;
5041 while (q < end && *q != '?')
5042 q++;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005043
Thierry FOURNIER7d388632017-02-22 02:06:16 +01005044 /* Stores the request path. */
Christopher Fauleta2097962019-07-15 16:25:33 +02005045 lua_pushstring(L, "path");
5046 lua_pushlstring(L, p, q - p);
Thierry FOURNIER7d388632017-02-22 02:06:16 +01005047 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01005048
Christopher Fauleta2097962019-07-15 16:25:33 +02005049 /* Stores the query string. */
5050 lua_pushstring(L, "qs");
5051 if (*q == '?')
5052 q++;
5053 lua_pushlstring(L, q, end - q);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005054 lua_settable(L, -3);
Christopher Fauleta2097962019-07-15 16:25:33 +02005055 }
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005056
Christopher Fauleta2097962019-07-15 16:25:33 +02005057 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
5058 struct htx_blk *blk = htx_get_blk(htx, pos);
5059 enum htx_blk_type type = htx_get_blk_type(blk);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005060
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01005061 if (type == HTX_BLK_TLR || type == HTX_BLK_EOT)
Christopher Fauleta2097962019-07-15 16:25:33 +02005062 break;
5063 if (type == HTX_BLK_DATA)
5064 len += htx_get_blksz(blk);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005065 }
Christopher Faulet2e47e3a2023-01-13 11:40:24 +01005066 if (htx->extra != HTX_UNKOWN_PAYLOAD_LENGTH)
Christopher Fauleta2097962019-07-15 16:25:33 +02005067 len += htx->extra;
5068
5069 /* Stores the request path. */
5070 lua_pushstring(L, "length");
5071 lua_pushinteger(L, len);
5072 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01005073
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005074 /* Create an empty array of HTTP request headers. */
5075 lua_pushstring(L, "response");
5076 lua_newtable(L);
5077 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01005078
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005079 /* Pop a class stream metatable and affect it to the table. */
5080 lua_rawgeti(L, LUA_REGISTRYINDEX, class_applet_http_ref);
5081 lua_setmetatable(L, -2);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005082
5083 return 1;
5084}
5085
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01005086__LJMP static int hlua_applet_http_set_var(lua_State *L)
5087{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005088 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01005089 struct stream *s;
5090 const char *name;
5091 size_t len;
5092 struct sample smp;
5093
Tim Duesterhus4e172c92020-05-19 13:49:42 +02005094 if (lua_gettop(L) < 3 || lua_gettop(L) > 4)
5095 WILL_LJMP(luaL_error(L, "'set_var' needs between 3 and 4 arguments"));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01005096
5097 /* It is useles to retrieve the stream, but this function
5098 * runs only in a stream context.
5099 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005100 luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01005101 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02005102 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01005103
5104 /* Converts the third argument in a sample. */
Amaury Denoyellebc0af6a2020-10-29 17:21:20 +01005105 memset(&smp, 0, sizeof(smp));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01005106 hlua_lua2smp(L, 3, &smp);
5107
5108 /* Store the sample in a variable. */
5109 smp_set_owner(&smp, s->be, s->sess, s, 0);
Tim Duesterhus4e172c92020-05-19 13:49:42 +02005110
5111 if (lua_gettop(L) == 4 && lua_toboolean(L, 4))
5112 lua_pushboolean(L, vars_set_by_name_ifexist(name, len, &smp) != 0);
5113 else
5114 lua_pushboolean(L, vars_set_by_name(name, len, &smp) != 0);
5115
Tim Duesterhus84ebc132020-05-19 13:49:41 +02005116 return 1;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01005117}
5118
5119__LJMP static int hlua_applet_http_unset_var(lua_State *L)
5120{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005121 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01005122 struct stream *s;
5123 const char *name;
5124 size_t len;
5125 struct sample smp;
5126
5127 MAY_LJMP(check_args(L, 2, "unset_var"));
5128
5129 /* It is useles to retrieve the stream, but this function
5130 * runs only in a stream context.
5131 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005132 luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01005133 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02005134 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01005135
5136 /* Unset the variable. */
5137 smp_set_owner(&smp, s->be, s->sess, s, 0);
Tim Duesterhus84ebc132020-05-19 13:49:41 +02005138 lua_pushboolean(L, vars_unset_by_name_ifexist(name, len, &smp) != 0);
5139 return 1;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01005140}
5141
5142__LJMP static int hlua_applet_http_get_var(lua_State *L)
5143{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005144 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01005145 struct stream *s;
5146 const char *name;
5147 size_t len;
5148 struct sample smp;
5149
5150 MAY_LJMP(check_args(L, 2, "get_var"));
5151
5152 /* It is useles to retrieve the stream, but this function
5153 * runs only in a stream context.
5154 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005155 luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01005156 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02005157 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01005158
5159 smp_set_owner(&smp, s->be, s->sess, s, 0);
Willy Tarreaue352b9d2021-09-03 11:52:38 +02005160 if (!vars_get_by_name(name, len, &smp, NULL)) {
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01005161 lua_pushnil(L);
5162 return 1;
5163 }
5164
5165 return hlua_smp2lua(L, &smp);
5166}
5167
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01005168__LJMP static int hlua_applet_http_set_priv(lua_State *L)
5169{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005170 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
5171 struct stream *s = luactx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01005172 struct hlua *hlua;
5173
5174 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005175 if (!s->hlua)
5176 return 0;
5177 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01005178
5179 MAY_LJMP(check_args(L, 2, "set_priv"));
5180
5181 /* Remove previous value. */
Thierry FOURNIERe068b602017-04-26 13:27:05 +02005182 luaL_unref(L, LUA_REGISTRYINDEX, hlua->Mref);
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01005183
5184 /* Get and store new value. */
5185 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
5186 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
5187
5188 return 0;
5189}
5190
5191__LJMP static int hlua_applet_http_get_priv(lua_State *L)
5192{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005193 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
5194 struct stream *s = luactx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01005195 struct hlua *hlua;
5196
5197 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005198 if (!s->hlua) {
5199 lua_pushnil(L);
5200 return 1;
5201 }
5202 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01005203
5204 /* Push configuration index in the stack. */
5205 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
5206
5207 return 1;
5208}
5209
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005210/* If expected data not yet available, it returns a yield. This function
5211 * consumes the data in the buffer. It returns a string containing the
5212 * data. This string can be empty.
5213 */
Christopher Fauleta2097962019-07-15 16:25:33 +02005214__LJMP static int hlua_applet_http_getline_yield(lua_State *L, int status, lua_KContext ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005215{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005216 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Willy Tarreauc12b3212022-05-27 11:08:15 +02005217 struct stconn *sc = appctx_sc(luactx->appctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02005218 struct channel *req = sc_oc(sc);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005219 struct htx *htx;
5220 struct htx_blk *blk;
5221 size_t count;
5222 int stop = 0;
5223
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005224 htx = htx_from_buf(&req->buf);
5225 count = co_data(req);
Christopher Fauleta3f15502019-05-13 15:27:23 +02005226 blk = htx_get_first_blk(htx);
Christopher Fauletcc26b132018-12-18 21:20:57 +01005227
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005228 while (count && !stop && blk) {
5229 enum htx_blk_type type = htx_get_blk_type(blk);
5230 uint32_t sz = htx_get_blksz(blk);
5231 struct ist v;
5232 uint32_t vlen;
5233 char *nl;
5234
5235 vlen = sz;
5236 if (vlen > count) {
5237 if (type != HTX_BLK_DATA)
5238 break;
5239 vlen = count;
5240 }
5241
5242 switch (type) {
5243 case HTX_BLK_UNUSED:
5244 break;
5245
5246 case HTX_BLK_DATA:
5247 v = htx_get_blk_value(htx, blk);
5248 v.len = vlen;
5249 nl = istchr(v, '\n');
5250 if (nl != NULL) {
5251 stop = 1;
5252 vlen = nl - v.ptr + 1;
5253 }
Willy Tarreau7e702d12021-04-28 17:59:21 +02005254 luaL_addlstring(&luactx->b, v.ptr, vlen);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005255 break;
5256
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005257 case HTX_BLK_TLR:
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01005258 case HTX_BLK_EOT:
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005259 stop = 1;
5260 break;
5261
5262 default:
5263 break;
5264 }
5265
Willy Tarreau84240042022-02-28 16:51:23 +01005266 c_rew(req, vlen);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005267 count -= vlen;
5268 if (sz == vlen)
5269 blk = htx_remove_blk(htx, blk);
5270 else {
5271 htx_cut_data_blk(htx, blk, vlen);
5272 break;
5273 }
5274 }
5275
Christopher Fauleteccb31c2021-04-02 14:24:56 +02005276 /* The message was fully consumed and no more data are expected
5277 * (EOM flag set).
5278 */
Christopher Faulet904763f2023-03-22 14:53:11 +01005279 if (htx_is_empty(htx) && (sc->flags & SC_FL_EOI))
Christopher Fauleteccb31c2021-04-02 14:24:56 +02005280 stop = 1;
5281
Christopher Faulet0ae79d02019-02-27 21:36:59 +01005282 htx_to_buf(htx, &req->buf);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005283 if (!stop) {
Willy Tarreau90e8b452022-05-25 18:21:43 +02005284 applet_need_more_data(luactx->appctx);
Christopher Fauleta2097962019-07-15 16:25:33 +02005285 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_getline_yield, TICK_ETERNITY, 0));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005286 }
5287
5288 /* return the result. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005289 luaL_pushresult(&luactx->b);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005290 return 1;
5291}
5292
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005293
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08005294/* Check arguments for the function "hlua_channel_get_yield". */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005295__LJMP static int hlua_applet_http_getline(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005296{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005297 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005298
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005299 /* Initialise the string catenation. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005300 luaL_buffinit(L, &luactx->b);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005301
Christopher Fauleta2097962019-07-15 16:25:33 +02005302 return MAY_LJMP(hlua_applet_http_getline_yield(L, 0, 0));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005303}
5304
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005305/* If expected data not yet available, it returns a yield. This function
5306 * consumes the data in the buffer. It returns a string containing the
5307 * data. This string can be empty.
5308 */
Christopher Fauleta2097962019-07-15 16:25:33 +02005309__LJMP static int hlua_applet_http_recv_yield(lua_State *L, int status, lua_KContext ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005310{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005311 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Willy Tarreauc12b3212022-05-27 11:08:15 +02005312 struct stconn *sc = appctx_sc(luactx->appctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02005313 struct channel *req = sc_oc(sc);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005314 struct htx *htx;
5315 struct htx_blk *blk;
5316 size_t count;
5317 int len;
5318
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005319 htx = htx_from_buf(&req->buf);
5320 len = MAY_LJMP(luaL_checkinteger(L, 2));
5321 count = co_data(req);
Christopher Faulet29f17582019-05-23 11:03:26 +02005322 blk = htx_get_head_blk(htx);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005323 while (count && len && blk) {
5324 enum htx_blk_type type = htx_get_blk_type(blk);
5325 uint32_t sz = htx_get_blksz(blk);
5326 struct ist v;
5327 uint32_t vlen;
5328
5329 vlen = sz;
5330 if (len > 0 && vlen > len)
5331 vlen = len;
5332 if (vlen > count) {
5333 if (type != HTX_BLK_DATA)
5334 break;
5335 vlen = count;
5336 }
5337
5338 switch (type) {
5339 case HTX_BLK_UNUSED:
5340 break;
5341
5342 case HTX_BLK_DATA:
5343 v = htx_get_blk_value(htx, blk);
Willy Tarreau7e702d12021-04-28 17:59:21 +02005344 luaL_addlstring(&luactx->b, v.ptr, vlen);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005345 break;
5346
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005347 case HTX_BLK_TLR:
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01005348 case HTX_BLK_EOT:
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005349 len = 0;
5350 break;
5351
5352 default:
5353 break;
5354 }
5355
Willy Tarreau84240042022-02-28 16:51:23 +01005356 c_rew(req, vlen);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005357 count -= vlen;
5358 if (len > 0)
5359 len -= vlen;
5360 if (sz == vlen)
5361 blk = htx_remove_blk(htx, blk);
5362 else {
5363 htx_cut_data_blk(htx, blk, vlen);
5364 break;
5365 }
5366 }
5367
Christopher Fauleteccb31c2021-04-02 14:24:56 +02005368 /* The message was fully consumed and no more data are expected
5369 * (EOM flag set).
5370 */
Christopher Faulet904763f2023-03-22 14:53:11 +01005371 if (htx_is_empty(htx) && (sc->flags & SC_FL_EOI))
Christopher Fauleteccb31c2021-04-02 14:24:56 +02005372 len = 0;
5373
Christopher Faulet0ae79d02019-02-27 21:36:59 +01005374 htx_to_buf(htx, &req->buf);
5375
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005376 /* If we are no other data available, yield waiting for new data. */
5377 if (len) {
5378 if (len > 0) {
5379 lua_pushinteger(L, len);
5380 lua_replace(L, 2);
5381 }
Willy Tarreau90e8b452022-05-25 18:21:43 +02005382 applet_need_more_data(luactx->appctx);
Willy Tarreau9635e032018-10-16 17:52:55 +02005383 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005384 }
5385
5386 /* return the result. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005387 luaL_pushresult(&luactx->b);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005388 return 1;
5389}
5390
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08005391/* Check arguments for the function "hlua_channel_get_yield". */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005392__LJMP static int hlua_applet_http_recv(lua_State *L)
5393{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005394 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005395 int len = -1;
5396
5397 /* Check arguments. */
5398 if (lua_gettop(L) > 2)
5399 WILL_LJMP(luaL_error(L, "The 'recv' function requires between 1 and 2 arguments."));
5400 if (lua_gettop(L) >= 2) {
5401 len = MAY_LJMP(luaL_checkinteger(L, 2));
5402 lua_pop(L, 1);
5403 }
5404
Christopher Fauleta2097962019-07-15 16:25:33 +02005405 lua_pushinteger(L, len);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005406
Christopher Fauleta2097962019-07-15 16:25:33 +02005407 /* Initialise the string catenation. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005408 luaL_buffinit(L, &luactx->b);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005409
Christopher Fauleta2097962019-07-15 16:25:33 +02005410 return MAY_LJMP(hlua_applet_http_recv_yield(L, 0, 0));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005411}
5412
5413/* Append data in the output side of the buffer. This data is immediately
5414 * sent. The function returns the amount of data written. If the buffer
5415 * cannot contain the data, the function yields. The function returns -1
5416 * if the channel is closed.
5417 */
Christopher Fauleta2097962019-07-15 16:25:33 +02005418__LJMP static int hlua_applet_http_send_yield(lua_State *L, int status, lua_KContext ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005419{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005420 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Willy Tarreauc12b3212022-05-27 11:08:15 +02005421 struct stconn *sc = appctx_sc(luactx->appctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02005422 struct channel *res = sc_ic(sc);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005423 struct htx *htx = htx_from_buf(&res->buf);
5424 const char *data;
5425 size_t len;
5426 int l = MAY_LJMP(luaL_checkinteger(L, 3));
5427 int max;
5428
Christopher Faulet9060fc02019-07-03 11:39:30 +02005429 max = htx_get_max_blksz(htx, channel_htx_recv_max(res, htx));
Christopher Faulet4b0e9b22019-01-09 12:16:58 +01005430 if (!max)
5431 goto snd_yield;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005432
5433 data = MAY_LJMP(luaL_checklstring(L, 2, &len));
5434
5435 /* Get the max amount of data which can write as input in the channel. */
5436 if (max > (len - l))
5437 max = len - l;
5438
5439 /* Copy data. */
Willy Tarreau0a7ef022019-05-28 10:30:11 +02005440 max = htx_add_data(htx, ist2(data + l, max));
Christopher Fauletf6cce3f2019-02-27 21:20:09 +01005441 channel_add_input(res, max);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005442
5443 /* update counters. */
5444 l += max;
5445 lua_pop(L, 1);
5446 lua_pushinteger(L, l);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005447
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005448 /* If some data is not send, declares the situation to the
5449 * applet, and returns a yield.
5450 */
5451 if (l < len) {
Christopher Faulet4b0e9b22019-01-09 12:16:58 +01005452 snd_yield:
Christopher Faulet0ae79d02019-02-27 21:36:59 +01005453 htx_to_buf(htx, &res->buf);
Willy Tarreau3e7be362022-05-27 10:35:27 +02005454 sc_need_room(sc);
Willy Tarreau9635e032018-10-16 17:52:55 +02005455 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005456 }
5457
Christopher Fauleta2097962019-07-15 16:25:33 +02005458 htx_to_buf(htx, &res->buf);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005459 return 1;
5460}
5461
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05005462/* Just a wrapper of "hlua_applet_send_yield". This wrapper permits
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005463 * yield the LUA process, and resume it without checking the
5464 * input arguments.
5465 */
5466__LJMP static int hlua_applet_http_send(lua_State *L)
5467{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005468 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005469 struct hlua_http_ctx *http_ctx = luactx->appctx->svcctx;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005470
5471 /* We want to send some data. Headers must be sent. */
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005472 if (!(http_ctx->flags & APPLET_HDR_SENT)) {
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005473 hlua_pusherror(L, "Lua: 'send' you must call start_response() before sending data.");
5474 WILL_LJMP(lua_error(L));
5475 }
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005476
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05005477 /* This integer is used for followinf the amount of data sent. */
Christopher Fauleta2097962019-07-15 16:25:33 +02005478 lua_pushinteger(L, 0);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005479
Christopher Fauleta2097962019-07-15 16:25:33 +02005480 return MAY_LJMP(hlua_applet_http_send_yield(L, 0, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005481}
5482
5483__LJMP static int hlua_applet_http_addheader(lua_State *L)
5484{
5485 const char *name;
5486 int ret;
5487
5488 MAY_LJMP(hlua_checkapplet_http(L, 1));
5489 name = MAY_LJMP(luaL_checkstring(L, 2));
5490 MAY_LJMP(luaL_checkstring(L, 3));
5491
5492 /* Push in the stack the "response" entry. */
5493 ret = lua_getfield(L, 1, "response");
5494 if (ret != LUA_TTABLE) {
5495 hlua_pusherror(L, "Lua: 'add_header' internal error: AppletHTTP['response'] "
5496 "is expected as an array. %s found", lua_typename(L, ret));
5497 WILL_LJMP(lua_error(L));
5498 }
5499
5500 /* check if the header is already registered if it is not
5501 * the case, register it.
5502 */
5503 ret = lua_getfield(L, -1, name);
5504 if (ret == LUA_TNIL) {
5505
5506 /* Entry not found. */
5507 lua_pop(L, 1); /* remove the nil. The "response" table is the top of the stack. */
5508
5509 /* Insert the new header name in the array in the top of the stack.
5510 * It left the new array in the top of the stack.
5511 */
5512 lua_newtable(L);
5513 lua_pushvalue(L, 2);
5514 lua_pushvalue(L, -2);
5515 lua_settable(L, -4);
5516
5517 } else if (ret != LUA_TTABLE) {
5518
5519 /* corruption error. */
5520 hlua_pusherror(L, "Lua: 'add_header' internal error: AppletHTTP['response']['%s'] "
5521 "is expected as an array. %s found", name, lua_typename(L, ret));
5522 WILL_LJMP(lua_error(L));
5523 }
5524
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -07005525 /* Now the top of thestack is an array of values. We push
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005526 * the header value as new entry.
5527 */
5528 lua_pushvalue(L, 3);
5529 ret = lua_rawlen(L, -2);
5530 lua_rawseti(L, -2, ret + 1);
5531 lua_pushboolean(L, 1);
5532 return 1;
5533}
5534
5535__LJMP static int hlua_applet_http_status(lua_State *L)
5536{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005537 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005538 int status = MAY_LJMP(luaL_checkinteger(L, 2));
Robin H. Johnson52f5db22017-01-01 13:10:52 -08005539 const char *reason = MAY_LJMP(luaL_optlstring(L, 3, NULL, NULL));
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005540 struct hlua_http_ctx *http_ctx = luactx->appctx->svcctx;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005541
5542 if (status < 100 || status > 599) {
5543 lua_pushboolean(L, 0);
5544 return 1;
5545 }
5546
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005547 http_ctx->status = status;
5548 http_ctx->reason = reason;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005549 lua_pushboolean(L, 1);
5550 return 1;
5551}
5552
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005553
Christopher Fauleta2097962019-07-15 16:25:33 +02005554__LJMP static int hlua_applet_http_send_response(lua_State *L)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005555{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005556 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005557 struct hlua_http_ctx *http_ctx = luactx->appctx->svcctx;
Willy Tarreauc12b3212022-05-27 11:08:15 +02005558 struct stconn *sc = appctx_sc(luactx->appctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02005559 struct channel *res = sc_ic(sc);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005560 struct htx *htx;
5561 struct htx_sl *sl;
5562 struct h1m h1m;
5563 const char *status, *reason;
5564 const char *name, *value;
5565 size_t nlen, vlen;
5566 unsigned int flags;
5567
5568 /* Send the message at once. */
5569 htx = htx_from_buf(&res->buf);
5570 h1m_init_res(&h1m);
5571
5572 /* Use the same http version than the request. */
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005573 status = ultoa_r(http_ctx->status, trash.area, trash.size);
5574 reason = http_ctx->reason;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005575 if (reason == NULL)
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005576 reason = http_get_reason(http_ctx->status);
5577 if (http_ctx->flags & APPLET_HTTP11) {
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005578 flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11);
5579 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.1"), ist(status), ist(reason));
5580 }
5581 else {
5582 flags = HTX_SL_F_IS_RESP;
5583 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.0"), ist(status), ist(reason));
5584 }
5585 if (!sl) {
5586 hlua_pusherror(L, "Lua applet http '%s': Failed to create response.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005587 luactx->appctx->rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005588 WILL_LJMP(lua_error(L));
5589 }
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005590 sl->info.res.status = http_ctx->status;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005591
5592 /* Get the array associated to the field "response" in the object AppletHTTP. */
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005593 if (lua_getfield(L, 1, "response") != LUA_TTABLE) {
5594 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response'] missing.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005595 luactx->appctx->rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005596 WILL_LJMP(lua_error(L));
5597 }
5598
5599 /* Browse the list of headers. */
5600 lua_pushnil(L);
5601 while(lua_next(L, -2) != 0) {
5602 /* We expect a string as -2. */
5603 if (lua_type(L, -2) != LUA_TSTRING) {
5604 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response'][] element must be a string. got %s.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005605 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005606 lua_typename(L, lua_type(L, -2)));
5607 WILL_LJMP(lua_error(L));
5608 }
5609 name = lua_tolstring(L, -2, &nlen);
5610
5611 /* We expect an array as -1. */
5612 if (lua_type(L, -1) != LUA_TTABLE) {
5613 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 +02005614 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005615 name,
5616 lua_typename(L, lua_type(L, -1)));
5617 WILL_LJMP(lua_error(L));
5618 }
5619
5620 /* Browse the table who is on the top of the stack. */
5621 lua_pushnil(L);
5622 while(lua_next(L, -2) != 0) {
5623 int id;
5624
5625 /* We expect a number as -2. */
5626 if (lua_type(L, -2) != LUA_TNUMBER) {
5627 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 +02005628 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005629 name,
5630 lua_typename(L, lua_type(L, -2)));
5631 WILL_LJMP(lua_error(L));
5632 }
5633 id = lua_tointeger(L, -2);
5634
5635 /* We expect a string as -2. */
5636 if (lua_type(L, -1) != LUA_TSTRING) {
5637 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 +02005638 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005639 name, id,
5640 lua_typename(L, lua_type(L, -1)));
5641 WILL_LJMP(lua_error(L));
5642 }
5643 value = lua_tolstring(L, -1, &vlen);
5644
5645 /* Simple Protocol checks. */
Christopher Faulet545fbba2021-09-28 09:36:25 +02005646 if (isteqi(ist2(name, nlen), ist("transfer-encoding"))) {
5647 int ret;
5648
5649 ret = h1_parse_xfer_enc_header(&h1m, ist2(value, vlen));
5650 if (ret < 0) {
5651 hlua_pusherror(L, "Lua applet http '%s': Invalid '%s' header.\n",
5652 luactx->appctx->rule->arg.hlua_rule->fcn->name,
5653 name);
5654 WILL_LJMP(lua_error(L));
5655 }
5656 else if (ret == 0)
5657 goto next; /* Skip it */
5658 }
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005659 else if (isteqi(ist2(name, nlen), ist("content-length"))) {
5660 struct ist v = ist2(value, vlen);
5661 int ret;
5662
5663 ret = h1_parse_cont_len_header(&h1m, &v);
5664 if (ret < 0) {
5665 hlua_pusherror(L, "Lua applet http '%s': Invalid '%s' header.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005666 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005667 name);
5668 WILL_LJMP(lua_error(L));
5669 }
5670 else if (ret == 0)
5671 goto next; /* Skip it */
5672 }
5673
5674 /* Add a new header */
5675 if (!htx_add_header(htx, ist2(name, nlen), ist2(value, vlen))) {
5676 hlua_pusherror(L, "Lua applet http '%s': Failed to add header '%s' in the response.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005677 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005678 name);
5679 WILL_LJMP(lua_error(L));
5680 }
5681 next:
5682 /* Remove the array from the stack, and get next element with a remaining string. */
5683 lua_pop(L, 1);
5684 }
5685
5686 /* Remove the array from the stack, and get next element with a remaining string. */
5687 lua_pop(L, 1);
5688 }
5689
5690 if (h1m.flags & H1_MF_CHNK)
5691 h1m.flags &= ~H1_MF_CLEN;
5692 if (h1m.flags & (H1_MF_CLEN|H1_MF_CHNK))
5693 h1m.flags |= H1_MF_XFER_LEN;
5694
5695 /* Uset HTX start-line flags */
5696 if (h1m.flags & H1_MF_XFER_ENC)
5697 flags |= HTX_SL_F_XFER_ENC;
5698 if (h1m.flags & H1_MF_XFER_LEN) {
5699 flags |= HTX_SL_F_XFER_LEN;
5700 if (h1m.flags & H1_MF_CHNK)
5701 flags |= HTX_SL_F_CHNK;
5702 else if (h1m.flags & H1_MF_CLEN)
5703 flags |= HTX_SL_F_CLEN;
5704 if (h1m.body_len == 0)
5705 flags |= HTX_SL_F_BODYLESS;
5706 }
5707 sl->flags |= flags;
5708
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -07005709 /* If we don't have a content-length set, and the HTTP version is 1.1
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005710 * and the status code implies the presence of a message body, we must
5711 * announce a transfer encoding chunked. This is required by haproxy
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05005712 * for the keepalive compliance. If the applet announces a transfer-encoding
5713 * chunked itself, don't do anything.
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005714 */
5715 if ((flags & (HTX_SL_F_VER_11|HTX_SL_F_XFER_LEN)) == HTX_SL_F_VER_11 &&
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005716 http_ctx->status >= 200 && http_ctx->status != 204 && http_ctx->status != 304) {
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005717 /* Add a new header */
5718 sl->flags |= (HTX_SL_F_XFER_ENC|H1_MF_CHNK|H1_MF_XFER_LEN);
5719 if (!htx_add_header(htx, ist("transfer-encoding"), ist("chunked"))) {
5720 hlua_pusherror(L, "Lua applet http '%s': Failed to add header 'transfer-encoding' in the response.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005721 luactx->appctx->rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005722 WILL_LJMP(lua_error(L));
5723 }
5724 }
5725
5726 /* Finalize headers. */
5727 if (!htx_add_endof(htx, HTX_BLK_EOH)) {
5728 hlua_pusherror(L, "Lua applet http '%s': Failed create the response.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005729 luactx->appctx->rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005730 WILL_LJMP(lua_error(L));
5731 }
5732
5733 if (htx_used_space(htx) > b_size(&res->buf) - global.tune.maxrewrite) {
5734 b_reset(&res->buf);
5735 hlua_pusherror(L, "Lua: 'start_response': response header block too big");
5736 WILL_LJMP(lua_error(L));
5737 }
5738
5739 htx_to_buf(htx, &res->buf);
Christopher Fauletf6cce3f2019-02-27 21:20:09 +01005740 channel_add_input(res, htx->data);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005741
5742 /* Headers sent, set the flag. */
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005743 http_ctx->flags |= APPLET_HDR_SENT;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005744 return 0;
5745
5746}
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005747/* We will build the status line and the headers of the HTTP response.
5748 * We will try send at once if its not possible, we give back the hand
5749 * waiting for more room.
5750 */
Christopher Fauleta2097962019-07-15 16:25:33 +02005751__LJMP static int hlua_applet_http_start_response_yield(lua_State *L, int status, lua_KContext ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005752{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005753 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Willy Tarreauc12b3212022-05-27 11:08:15 +02005754 struct stconn *sc = appctx_sc(luactx->appctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02005755 struct channel *res = sc_ic(sc);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005756
5757 if (co_data(res)) {
Willy Tarreau3e7be362022-05-27 10:35:27 +02005758 sc_need_room(sc);
Christopher Fauleta2097962019-07-15 16:25:33 +02005759 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_start_response_yield, TICK_ETERNITY, 0));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005760 }
Christopher Fauleta2097962019-07-15 16:25:33 +02005761 return MAY_LJMP(hlua_applet_http_send_response(L));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005762}
5763
5764
Christopher Fauleta2097962019-07-15 16:25:33 +02005765__LJMP static int hlua_applet_http_start_response(lua_State *L)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005766{
Christopher Fauleta2097962019-07-15 16:25:33 +02005767 return MAY_LJMP(hlua_applet_http_start_response_yield(L, 0, 0));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005768}
5769
Christopher Fauleta2097962019-07-15 16:25:33 +02005770/*
5771 *
5772 *
5773 * Class HTTP
5774 *
5775 *
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005776 */
Christopher Fauleta2097962019-07-15 16:25:33 +02005777
5778/* Returns a struct hlua_txn if the stack entry "ud" is
5779 * a class stream, otherwise it throws an error.
5780 */
5781__LJMP static struct hlua_txn *hlua_checkhttp(lua_State *L, int ud)
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005782{
Christopher Fauleta2097962019-07-15 16:25:33 +02005783 return MAY_LJMP(hlua_checkudata(L, ud, class_http_ref));
5784}
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005785
Christopher Fauleta2097962019-07-15 16:25:33 +02005786/* This function creates and push in the stack a HTTP object
5787 * according with a current TXN.
5788 */
5789static int hlua_http_new(lua_State *L, struct hlua_txn *txn)
5790{
5791 struct hlua_txn *htxn;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005792
Christopher Fauleta2097962019-07-15 16:25:33 +02005793 /* Check stack size. */
5794 if (!lua_checkstack(L, 3))
5795 return 0;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005796
Christopher Fauleta2097962019-07-15 16:25:33 +02005797 /* Create the object: obj[0] = userdata.
5798 * Note that the base of the Converters object is the
5799 * same than the TXN object.
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005800 */
Christopher Fauleta2097962019-07-15 16:25:33 +02005801 lua_newtable(L);
5802 htxn = lua_newuserdata(L, sizeof(*htxn));
5803 lua_rawseti(L, -2, 0);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005804
5805 htxn->s = txn->s;
5806 htxn->p = txn->p;
Christopher Faulet256b69a2019-05-23 11:14:21 +02005807 htxn->dir = txn->dir;
5808 htxn->flags = txn->flags;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005809
5810 /* Pop a class stream metatable and affect it to the table. */
5811 lua_rawgeti(L, LUA_REGISTRYINDEX, class_http_ref);
5812 lua_setmetatable(L, -2);
5813
5814 return 1;
5815}
5816
Christopher Fauletdf97ac42020-02-26 16:57:19 +01005817/* This function creates and returns an array containing the status-line
5818 * elements. This function does not fails.
5819 */
5820__LJMP static int hlua_http_get_stline(lua_State *L, struct htx_sl *sl)
5821{
5822 /* Create the table. */
5823 lua_newtable(L);
5824
5825 if (sl->flags & HTX_SL_F_IS_RESP) {
5826 lua_pushstring(L, "version");
5827 lua_pushlstring(L, HTX_SL_RES_VPTR(sl), HTX_SL_RES_VLEN(sl));
5828 lua_settable(L, -3);
5829 lua_pushstring(L, "code");
5830 lua_pushlstring(L, HTX_SL_RES_CPTR(sl), HTX_SL_RES_CLEN(sl));
5831 lua_settable(L, -3);
5832 lua_pushstring(L, "reason");
5833 lua_pushlstring(L, HTX_SL_RES_RPTR(sl), HTX_SL_RES_RLEN(sl));
5834 lua_settable(L, -3);
5835 }
5836 else {
5837 lua_pushstring(L, "method");
5838 lua_pushlstring(L, HTX_SL_REQ_MPTR(sl), HTX_SL_REQ_MLEN(sl));
5839 lua_settable(L, -3);
5840 lua_pushstring(L, "uri");
5841 lua_pushlstring(L, HTX_SL_REQ_UPTR(sl), HTX_SL_REQ_ULEN(sl));
5842 lua_settable(L, -3);
5843 lua_pushstring(L, "version");
5844 lua_pushlstring(L, HTX_SL_REQ_VPTR(sl), HTX_SL_REQ_VLEN(sl));
5845 lua_settable(L, -3);
5846 }
5847 return 1;
5848}
5849
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005850/* This function creates ans returns an array of HTTP headers.
5851 * This function does not fails. It is used as wrapper with the
5852 * 2 following functions.
5853 */
Christopher Faulet9d1332b2020-02-24 16:46:16 +01005854__LJMP static int hlua_http_get_headers(lua_State *L, struct http_msg *msg)
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005855{
Christopher Fauleta2097962019-07-15 16:25:33 +02005856 struct htx *htx;
5857 int32_t pos;
5858
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005859 /* Create the table. */
5860 lua_newtable(L);
5861
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005862
Christopher Fauleta2097962019-07-15 16:25:33 +02005863 htx = htxbuf(&msg->chn->buf);
5864 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
5865 struct htx_blk *blk = htx_get_blk(htx, pos);
5866 enum htx_blk_type type = htx_get_blk_type(blk);
5867 struct ist n, v;
5868 int len;
Christopher Faulet724a12c2018-12-13 22:12:15 +01005869
Christopher Fauleta2097962019-07-15 16:25:33 +02005870 if (type == HTX_BLK_HDR) {
5871 n = htx_get_blk_name(htx,blk);
5872 v = htx_get_blk_value(htx, blk);
Christopher Faulet724a12c2018-12-13 22:12:15 +01005873 }
Christopher Fauleta2097962019-07-15 16:25:33 +02005874 else if (type == HTX_BLK_EOH)
5875 break;
5876 else
5877 continue;
Christopher Faulet724a12c2018-12-13 22:12:15 +01005878
Christopher Fauleta2097962019-07-15 16:25:33 +02005879 /* Check for existing entry:
5880 * assume that the table is on the top of the stack, and
5881 * push the key in the stack, the function lua_gettable()
5882 * perform the lookup.
5883 */
5884 lua_pushlstring(L, n.ptr, n.len);
5885 lua_gettable(L, -2);
Christopher Faulet724a12c2018-12-13 22:12:15 +01005886
Christopher Fauleta2097962019-07-15 16:25:33 +02005887 switch (lua_type(L, -1)) {
5888 case LUA_TNIL:
5889 /* Table not found, create it. */
5890 lua_pop(L, 1); /* remove the nil value. */
5891 lua_pushlstring(L, n.ptr, n.len); /* push the header name as key. */
5892 lua_newtable(L); /* create and push empty table. */
5893 lua_pushlstring(L, v.ptr, v.len); /* push header value. */
5894 lua_rawseti(L, -2, 0); /* index header value (pop it). */
5895 lua_rawset(L, -3); /* index new table with header name (pop the values). */
Christopher Faulet724a12c2018-12-13 22:12:15 +01005896 break;
Christopher Faulet724a12c2018-12-13 22:12:15 +01005897
Christopher Fauleta2097962019-07-15 16:25:33 +02005898 case LUA_TTABLE:
5899 /* Entry found: push the value in the table. */
5900 len = lua_rawlen(L, -1);
5901 lua_pushlstring(L, v.ptr, v.len); /* push header value. */
5902 lua_rawseti(L, -2, len+1); /* index header value (pop it). */
5903 lua_pop(L, 1); /* remove the table (it is stored in the main table). */
5904 break;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005905
Christopher Fauleta2097962019-07-15 16:25:33 +02005906 default:
5907 /* Other cases are errors. */
5908 hlua_pusherror(L, "internal error during the parsing of headers.");
5909 WILL_LJMP(lua_error(L));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005910 }
5911 }
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005912 return 1;
5913}
5914
5915__LJMP static int hlua_http_req_get_headers(lua_State *L)
5916{
5917 struct hlua_txn *htxn;
5918
5919 MAY_LJMP(check_args(L, 1, "req_get_headers"));
5920 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5921
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005922 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005923 WILL_LJMP(lua_error(L));
5924
Christopher Faulet9d1332b2020-02-24 16:46:16 +01005925 return hlua_http_get_headers(L, &htxn->s->txn->req);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005926}
5927
5928__LJMP static int hlua_http_res_get_headers(lua_State *L)
5929{
5930 struct hlua_txn *htxn;
5931
5932 MAY_LJMP(check_args(L, 1, "res_get_headers"));
5933 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5934
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005935 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005936 WILL_LJMP(lua_error(L));
5937
Christopher Faulet9d1332b2020-02-24 16:46:16 +01005938 return hlua_http_get_headers(L, &htxn->s->txn->rsp);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005939}
5940
5941/* This function replace full header, or just a value in
5942 * the request or in the response. It is a wrapper fir the
5943 * 4 following functions.
5944 */
Christopher Fauletd1914aa2020-02-24 16:52:46 +01005945__LJMP static inline int hlua_http_rep_hdr(lua_State *L, struct http_msg *msg, int full)
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005946{
5947 size_t name_len;
5948 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
5949 const char *reg = MAY_LJMP(luaL_checkstring(L, 3));
5950 const char *value = MAY_LJMP(luaL_checkstring(L, 4));
Christopher Fauleta2097962019-07-15 16:25:33 +02005951 struct htx *htx;
Dragan Dosen26743032019-04-30 15:54:36 +02005952 struct my_regex *re;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005953
Dragan Dosen26743032019-04-30 15:54:36 +02005954 if (!(re = regex_comp(reg, 1, 1, NULL)))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005955 WILL_LJMP(luaL_argerror(L, 3, "invalid regex"));
5956
Christopher Fauleta2097962019-07-15 16:25:33 +02005957 htx = htxbuf(&msg->chn->buf);
Christopher Fauletd1914aa2020-02-24 16:52:46 +01005958 http_replace_hdrs(chn_strm(msg->chn), htx, ist2(name, name_len), value, re, full);
Dragan Dosen26743032019-04-30 15:54:36 +02005959 regex_free(re);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005960 return 0;
5961}
5962
5963__LJMP static int hlua_http_req_rep_hdr(lua_State *L)
5964{
5965 struct hlua_txn *htxn;
5966
5967 MAY_LJMP(check_args(L, 4, "req_rep_hdr"));
5968 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5969
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005970 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005971 WILL_LJMP(lua_error(L));
5972
Christopher Fauletd1914aa2020-02-24 16:52:46 +01005973 return MAY_LJMP(hlua_http_rep_hdr(L, &htxn->s->txn->req, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005974}
5975
5976__LJMP static int hlua_http_res_rep_hdr(lua_State *L)
5977{
5978 struct hlua_txn *htxn;
5979
5980 MAY_LJMP(check_args(L, 4, "res_rep_hdr"));
5981 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5982
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005983 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005984 WILL_LJMP(lua_error(L));
5985
Christopher Fauletd1914aa2020-02-24 16:52:46 +01005986 return MAY_LJMP(hlua_http_rep_hdr(L, &htxn->s->txn->rsp, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005987}
5988
5989__LJMP static int hlua_http_req_rep_val(lua_State *L)
5990{
5991 struct hlua_txn *htxn;
5992
5993 MAY_LJMP(check_args(L, 4, "req_rep_hdr"));
5994 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5995
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005996 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005997 WILL_LJMP(lua_error(L));
5998
Christopher Fauletd1914aa2020-02-24 16:52:46 +01005999 return MAY_LJMP(hlua_http_rep_hdr(L, &htxn->s->txn->req, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006000}
6001
6002__LJMP static int hlua_http_res_rep_val(lua_State *L)
6003{
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006004 struct hlua_txn *htxn;
6005
6006 MAY_LJMP(check_args(L, 4, "res_rep_val"));
6007 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
6008
Christopher Fauletd8f0e072020-02-25 09:45:51 +01006009 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006010 WILL_LJMP(lua_error(L));
6011
Christopher Fauletd1914aa2020-02-24 16:52:46 +01006012 return MAY_LJMP(hlua_http_rep_hdr(L, &htxn->s->txn->rsp, 0));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006013}
6014
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08006015/* This function deletes all the occurrences of an header.
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006016 * It is a wrapper for the 2 following functions.
6017 */
Christopher Fauletd31c7b32020-02-25 09:37:57 +01006018__LJMP static inline int hlua_http_del_hdr(lua_State *L, struct http_msg *msg)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006019{
6020 size_t len;
6021 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Christopher Fauleta2097962019-07-15 16:25:33 +02006022 struct htx *htx = htxbuf(&msg->chn->buf);
6023 struct http_hdr_ctx ctx;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006024
Christopher Fauleta2097962019-07-15 16:25:33 +02006025 ctx.blk = NULL;
6026 while (http_find_header(htx, ist2(name, len), &ctx, 1))
6027 http_remove_header(htx, &ctx);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006028 return 0;
6029}
6030
6031__LJMP static int hlua_http_req_del_hdr(lua_State *L)
6032{
6033 struct hlua_txn *htxn;
6034
6035 MAY_LJMP(check_args(L, 2, "req_del_hdr"));
6036 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
6037
Christopher Fauletd8f0e072020-02-25 09:45:51 +01006038 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006039 WILL_LJMP(lua_error(L));
6040
Christopher Fauletd31c7b32020-02-25 09:37:57 +01006041 return hlua_http_del_hdr(L, &htxn->s->txn->req);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006042}
6043
6044__LJMP static int hlua_http_res_del_hdr(lua_State *L)
6045{
6046 struct hlua_txn *htxn;
6047
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006048 MAY_LJMP(check_args(L, 2, "res_del_hdr"));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006049 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
6050
Christopher Fauletd8f0e072020-02-25 09:45:51 +01006051 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006052 WILL_LJMP(lua_error(L));
6053
Christopher Fauletd31c7b32020-02-25 09:37:57 +01006054 return hlua_http_del_hdr(L, &htxn->s->txn->rsp);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006055}
6056
6057/* This function adds an header. It is a wrapper used by
6058 * the 2 following functions.
6059 */
Christopher Fauletd31c7b32020-02-25 09:37:57 +01006060__LJMP static inline int hlua_http_add_hdr(lua_State *L, struct http_msg *msg)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006061{
6062 size_t name_len;
6063 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
6064 size_t value_len;
6065 const char *value = MAY_LJMP(luaL_checklstring(L, 3, &value_len));
Christopher Fauleta2097962019-07-15 16:25:33 +02006066 struct htx *htx = htxbuf(&msg->chn->buf);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006067
Christopher Fauleta2097962019-07-15 16:25:33 +02006068 lua_pushboolean(L, http_add_header(htx, ist2(name, name_len),
6069 ist2(value, value_len)));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006070 return 0;
6071}
6072
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006073__LJMP static int hlua_http_req_add_hdr(lua_State *L)
6074{
6075 struct hlua_txn *htxn;
6076
6077 MAY_LJMP(check_args(L, 3, "req_add_hdr"));
6078 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
6079
6080 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
6081 WILL_LJMP(lua_error(L));
6082
6083 return hlua_http_add_hdr(L, &htxn->s->txn->req);
6084}
6085
6086__LJMP static int hlua_http_res_add_hdr(lua_State *L)
6087{
6088 struct hlua_txn *htxn;
6089
6090 MAY_LJMP(check_args(L, 3, "res_add_hdr"));
6091 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
6092
6093 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
6094 WILL_LJMP(lua_error(L));
6095
6096 return hlua_http_add_hdr(L, &htxn->s->txn->rsp);
6097}
6098
6099static int hlua_http_req_set_hdr(lua_State *L)
6100{
6101 struct hlua_txn *htxn;
6102
6103 MAY_LJMP(check_args(L, 3, "req_set_hdr"));
6104 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
6105
6106 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
6107 WILL_LJMP(lua_error(L));
6108
6109 hlua_http_del_hdr(L, &htxn->s->txn->req);
6110 return hlua_http_add_hdr(L, &htxn->s->txn->req);
6111}
6112
6113static int hlua_http_res_set_hdr(lua_State *L)
6114{
6115 struct hlua_txn *htxn;
6116
6117 MAY_LJMP(check_args(L, 3, "res_set_hdr"));
6118 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
6119
6120 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
6121 WILL_LJMP(lua_error(L));
6122
6123 hlua_http_del_hdr(L, &htxn->s->txn->rsp);
6124 return hlua_http_add_hdr(L, &htxn->s->txn->rsp);
6125}
6126
6127/* This function set the method. */
6128static int hlua_http_req_set_meth(lua_State *L)
6129{
6130 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
6131 size_t name_len;
6132 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
6133
6134 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
6135 WILL_LJMP(lua_error(L));
6136
6137 lua_pushboolean(L, http_req_replace_stline(0, name, name_len, htxn->p, htxn->s) != -1);
6138 return 1;
6139}
6140
6141/* This function set the method. */
6142static int hlua_http_req_set_path(lua_State *L)
6143{
6144 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
6145 size_t name_len;
6146 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
6147
6148 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
6149 WILL_LJMP(lua_error(L));
6150
6151 lua_pushboolean(L, http_req_replace_stline(1, name, name_len, htxn->p, htxn->s) != -1);
6152 return 1;
6153}
6154
6155/* This function set the query-string. */
6156static int hlua_http_req_set_query(lua_State *L)
6157{
6158 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
6159 size_t name_len;
6160 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
6161
6162 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
6163 WILL_LJMP(lua_error(L));
6164
6165 /* Check length. */
6166 if (name_len > trash.size - 1) {
6167 lua_pushboolean(L, 0);
6168 return 1;
6169 }
6170
6171 /* Add the mark question as prefix. */
6172 chunk_reset(&trash);
6173 trash.area[trash.data++] = '?';
6174 memcpy(trash.area + trash.data, name, name_len);
6175 trash.data += name_len;
6176
6177 lua_pushboolean(L,
6178 http_req_replace_stline(2, trash.area, trash.data, htxn->p, htxn->s) != -1);
6179 return 1;
6180}
6181
6182/* This function set the uri. */
6183static int hlua_http_req_set_uri(lua_State *L)
6184{
6185 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
6186 size_t name_len;
6187 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
6188
6189 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
6190 WILL_LJMP(lua_error(L));
6191
6192 lua_pushboolean(L, http_req_replace_stline(3, name, name_len, htxn->p, htxn->s) != -1);
6193 return 1;
6194}
6195
6196/* This function set the response code & optionally reason. */
6197static int hlua_http_res_set_status(lua_State *L)
6198{
6199 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
6200 unsigned int code = MAY_LJMP(luaL_checkinteger(L, 2));
6201 const char *str = MAY_LJMP(luaL_optlstring(L, 3, NULL, NULL));
6202 const struct ist reason = ist2(str, (str ? strlen(str) : 0));
6203
6204 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
6205 WILL_LJMP(lua_error(L));
6206
6207 http_res_set_status(code, reason, htxn->s);
6208 return 0;
6209}
6210
6211/*
6212 *
6213 *
6214 * Class HTTPMessage
6215 *
6216 *
6217 */
6218
6219/* Returns a struct http_msg if the stack entry "ud" is a class HTTPMessage,
6220 * otherwise it throws an error.
6221 */
6222__LJMP static struct http_msg *hlua_checkhttpmsg(lua_State *L, int ud)
6223{
6224 return MAY_LJMP(hlua_checkudata(L, ud, class_http_msg_ref));
6225}
6226
6227/* Creates and pushes on the stack a HTTP object according with a current TXN.
6228 */
Christopher Faulet78c35472020-02-26 17:14:08 +01006229static int hlua_http_msg_new(lua_State *L, struct http_msg *msg)
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006230{
6231 /* Check stack size. */
6232 if (!lua_checkstack(L, 3))
6233 return 0;
6234
6235 lua_newtable(L);
6236 lua_pushlightuserdata(L, msg);
6237 lua_rawseti(L, -2, 0);
6238
6239 /* Create the "channel" field that contains the request channel object. */
6240 lua_pushstring(L, "channel");
6241 if (!hlua_channel_new(L, msg->chn))
6242 return 0;
6243 lua_rawset(L, -3);
6244
6245 /* Pop a class stream metatable and affect it to the table. */
6246 lua_rawgeti(L, LUA_REGISTRYINDEX, class_http_msg_ref);
6247 lua_setmetatable(L, -2);
6248
6249 return 1;
6250}
6251
6252/* Helper function returning a filter attached to the HTTP message at the
6253 * position <ud> in the stack, filling the current offset and length of the
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006254 * filter. If no filter is attached, NULL is returned and <offset> and <len> are
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006255 * filled with output and input length respectively.
6256 */
6257static struct filter *hlua_http_msg_filter(lua_State *L, int ud, struct http_msg *msg, size_t *offset, size_t *len)
6258{
6259 struct channel *chn = msg->chn;
6260 struct htx *htx = htxbuf(&chn->buf);
6261 struct filter *filter = NULL;
6262
6263 *offset = co_data(msg->chn);
6264 *len = htx->data - co_data(msg->chn);
6265
6266 if (lua_getfield(L, ud, "__filter") == LUA_TLIGHTUSERDATA) {
6267 filter = lua_touserdata (L, -1);
6268 if (msg->msg_state >= HTTP_MSG_DATA) {
6269 struct hlua_flt_ctx *flt_ctx = filter->ctx;
6270
6271 *offset = flt_ctx->cur_off[CHN_IDX(chn)];
6272 *len = flt_ctx->cur_len[CHN_IDX(chn)];
6273 }
6274 }
6275
6276 lua_pop(L, 1);
6277 return filter;
6278}
6279
6280/* Returns true if the channel attached to the HTTP message is the response
6281 * channel.
6282 */
6283__LJMP static int hlua_http_msg_is_resp(lua_State *L)
6284{
6285 struct http_msg *msg;
6286
6287 MAY_LJMP(check_args(L, 1, "is_resp"));
6288 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6289
6290 lua_pushboolean(L, !!(msg->chn->flags & CF_ISRESP));
6291 return 1;
6292}
6293
6294/* Returns an array containing the elements status-line of the HTTP message. It relies
6295 * on hlua_http_get_stline().
6296 */
6297__LJMP static int hlua_http_msg_get_stline(lua_State *L)
6298{
6299 struct http_msg *msg;
6300 struct htx *htx;
6301 struct htx_sl *sl;
6302
6303 MAY_LJMP(check_args(L, 1, "get_stline"));
6304 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6305
6306 if (msg->msg_state > HTTP_MSG_BODY)
6307 WILL_LJMP(lua_error(L));
6308
6309 htx = htxbuf(&msg->chn->buf);
6310 sl = http_get_stline(htx);
6311 if (!sl)
6312 return 0;
6313 return hlua_http_get_stline(L, sl);
6314}
6315
6316/* Returns an array containing all headers of the HTTP message. it relies on
6317 * hlua_http_get_headers().
6318 */
6319__LJMP static int hlua_http_msg_get_headers(lua_State *L)
6320{
6321 struct http_msg *msg;
6322
6323 MAY_LJMP(check_args(L, 1, "get_headers"));
6324 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6325
6326 if (msg->msg_state > HTTP_MSG_BODY)
6327 WILL_LJMP(lua_error(L));
6328
6329 return hlua_http_get_headers(L, msg);
6330}
6331
6332/* Deletes all occurrences of an header in the HTTP message matching on its
6333 * name. It relies on hlua_http_del_hdr().
6334 */
6335__LJMP static int hlua_http_msg_del_hdr(lua_State *L)
6336{
6337 struct http_msg *msg;
6338
6339 MAY_LJMP(check_args(L, 2, "del_header"));
6340 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6341
6342 if (msg->msg_state > HTTP_MSG_BODY)
6343 WILL_LJMP(lua_error(L));
6344
6345 return hlua_http_del_hdr(L, msg);
6346}
6347
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006348/* Matches the full value line of all occurrences of an header in the HTTP
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006349 * message given its name against a regex and replaces it if it matches. It
6350 * relies on hlua_http_rep_hdr().
6351 */
6352__LJMP static int hlua_http_msg_rep_hdr(lua_State *L)
6353{
6354 struct http_msg *msg;
6355
6356 MAY_LJMP(check_args(L, 4, "rep_header"));
6357 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6358
6359 if (msg->msg_state > HTTP_MSG_BODY)
6360 WILL_LJMP(lua_error(L));
6361
6362 return hlua_http_rep_hdr(L, msg, 1);
6363}
6364
Ilya Shipitsinbd6b4be2021-10-15 16:18:21 +05006365/* Matches all comma-separated values of all occurrences of an header in the HTTP
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006366 * message given its name against a regex and replaces it if it matches. It
6367 * relies on hlua_http_rep_hdr().
6368 */
6369__LJMP static int hlua_http_msg_rep_val(lua_State *L)
6370{
6371 struct http_msg *msg;
6372
6373 MAY_LJMP(check_args(L, 4, "rep_value"));
6374 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6375
6376 if (msg->msg_state > HTTP_MSG_BODY)
6377 WILL_LJMP(lua_error(L));
6378
6379 return hlua_http_rep_hdr(L, msg, 0);
6380}
6381
6382/* Add an header in the HTTP message. It relies on hlua_http_add_hdr() */
6383__LJMP static int hlua_http_msg_add_hdr(lua_State *L)
6384{
6385 struct http_msg *msg;
6386
6387 MAY_LJMP(check_args(L, 3, "add_header"));
6388 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6389
6390 if (msg->msg_state > HTTP_MSG_BODY)
6391 WILL_LJMP(lua_error(L));
6392
6393 return hlua_http_add_hdr(L, msg);
6394}
6395
6396/* Add an header in the HTTP message removing existing headers with the same
6397 * name. It relies on hlua_http_del_hdr() and hlua_http_add_hdr().
6398 */
6399__LJMP static int hlua_http_msg_set_hdr(lua_State *L)
6400{
6401 struct http_msg *msg;
6402
6403 MAY_LJMP(check_args(L, 3, "set_header"));
6404 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6405
6406 if (msg->msg_state > HTTP_MSG_BODY)
6407 WILL_LJMP(lua_error(L));
6408
6409 hlua_http_del_hdr(L, msg);
6410 return hlua_http_add_hdr(L, msg);
6411}
6412
6413/* Rewrites the request method. It relies on http_req_replace_stline(). */
6414__LJMP static int hlua_http_msg_set_meth(lua_State *L)
6415{
6416 struct stream *s;
6417 struct http_msg *msg;
6418 const char *name;
6419 size_t name_len;
6420
6421 MAY_LJMP(check_args(L, 2, "set_method"));
6422 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6423 name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
6424
6425 if ((msg->chn->flags & CF_ISRESP) || msg->msg_state > HTTP_MSG_BODY)
6426 WILL_LJMP(lua_error(L));
6427
6428 s = chn_strm(msg->chn);
6429 lua_pushboolean(L, http_req_replace_stline(0, name, name_len, s->be, s) != -1);
6430 return 1;
6431}
6432
6433/* Rewrites the request path. It relies on http_req_replace_stline(). */
6434__LJMP static int hlua_http_msg_set_path(lua_State *L)
6435{
6436 struct stream *s;
6437 struct http_msg *msg;
6438 const char *name;
6439 size_t name_len;
6440
6441 MAY_LJMP(check_args(L, 2, "set_path"));
6442 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6443 name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
6444
6445 if ((msg->chn->flags & CF_ISRESP) || msg->msg_state > HTTP_MSG_BODY)
6446 WILL_LJMP(lua_error(L));
6447
6448 s = chn_strm(msg->chn);
6449 lua_pushboolean(L, http_req_replace_stline(1, name, name_len, s->be, s) != -1);
6450 return 1;
6451}
6452
6453/* Rewrites the request query-string. It relies on http_req_replace_stline(). */
6454__LJMP static int hlua_http_msg_set_query(lua_State *L)
6455{
6456 struct stream *s;
6457 struct http_msg *msg;
6458 const char *name;
6459 size_t name_len;
6460
6461 MAY_LJMP(check_args(L, 2, "set_query"));
6462 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6463 name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
6464
6465 if ((msg->chn->flags & CF_ISRESP) || msg->msg_state > HTTP_MSG_BODY)
6466 WILL_LJMP(lua_error(L));
6467
6468 /* Check length. */
6469 if (name_len > trash.size - 1) {
6470 lua_pushboolean(L, 0);
6471 return 1;
6472 }
6473
6474 /* Add the mark question as prefix. */
6475 chunk_reset(&trash);
6476 trash.area[trash.data++] = '?';
6477 memcpy(trash.area + trash.data, name, name_len);
6478 trash.data += name_len;
6479
6480 s = chn_strm(msg->chn);
6481 lua_pushboolean(L, http_req_replace_stline(2, trash.area, trash.data, s->be, s) != -1);
6482 return 1;
6483}
6484
6485/* Rewrites the request URI. It relies on http_req_replace_stline(). */
6486__LJMP static int hlua_http_msg_set_uri(lua_State *L)
6487{
6488 struct stream *s;
6489 struct http_msg *msg;
6490 const char *name;
6491 size_t name_len;
6492
6493 MAY_LJMP(check_args(L, 2, "set_uri"));
6494 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6495 name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
6496
6497 if ((msg->chn->flags & CF_ISRESP) || msg->msg_state > HTTP_MSG_BODY)
6498 WILL_LJMP(lua_error(L));
6499
6500 s = chn_strm(msg->chn);
6501 lua_pushboolean(L, http_req_replace_stline(3, name, name_len, s->be, s) != -1);
6502 return 1;
6503}
6504
6505/* Rewrites the response status code. It relies on http_res_set_status(). */
6506__LJMP static int hlua_http_msg_set_status(lua_State *L)
6507{
6508 struct http_msg *msg;
6509 unsigned int code;
6510 const char *reason;
6511 size_t reason_len;
6512
6513 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6514 code = MAY_LJMP(luaL_checkinteger(L, 2));
6515 reason = MAY_LJMP(luaL_optlstring(L, 3, NULL, &reason_len));
6516
6517 if (!(msg->chn->flags & CF_ISRESP) || msg->msg_state > HTTP_MSG_BODY)
6518 WILL_LJMP(lua_error(L));
6519
6520 lua_pushboolean(L, http_res_set_status(code, ist2(reason, reason_len), chn_strm(msg->chn)) != -1);
6521 return 1;
6522}
6523
6524/* Returns true if the HTTP message is full. */
6525__LJMP static int hlua_http_msg_is_full(lua_State *L)
6526{
6527 struct http_msg *msg;
6528
6529 MAY_LJMP(check_args(L, 1, "is_full"));
6530 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6531 lua_pushboolean(L, channel_full(msg->chn, 0));
6532 return 1;
6533}
6534
6535/* Returns true if the HTTP message may still receive data. */
6536__LJMP static int hlua_http_msg_may_recv(lua_State *L)
6537{
6538 struct http_msg *msg;
6539 struct htx *htx;
6540
6541 MAY_LJMP(check_args(L, 1, "may_recv"));
6542 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6543 htx = htxbuf(&msg->chn->buf);
6544 lua_pushboolean(L, (htx_expect_more(htx) && !channel_input_closed(msg->chn) && channel_may_recv(msg->chn)));
6545 return 1;
6546}
6547
6548/* Returns true if the HTTP message EOM was received */
6549__LJMP static int hlua_http_msg_is_eom(lua_State *L)
6550{
6551 struct http_msg *msg;
6552 struct htx *htx;
6553
6554 MAY_LJMP(check_args(L, 1, "may_recv"));
6555 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6556 htx = htxbuf(&msg->chn->buf);
6557 lua_pushboolean(L, !htx_expect_more(htx));
6558 return 1;
6559}
6560
6561/* Returns the number of bytes available in the input side of the HTTP
6562 * message. This function never fails.
6563 */
6564__LJMP static int hlua_http_msg_get_in_len(lua_State *L)
6565{
6566 struct http_msg *msg;
Christopher Fauleteae8afa2020-02-26 17:15:48 +01006567 size_t output, input;
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006568
6569 MAY_LJMP(check_args(L, 1, "input"));
6570 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
Christopher Fauleteae8afa2020-02-26 17:15:48 +01006571 hlua_http_msg_filter(L, 1, msg, &output, &input);
6572 lua_pushinteger(L, input);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006573 return 1;
6574}
6575
6576/* Returns the number of bytes available in the output side of the HTTP
6577 * message. This function never fails.
6578 */
6579__LJMP static int hlua_http_msg_get_out_len(lua_State *L)
6580{
6581 struct http_msg *msg;
Christopher Fauleteae8afa2020-02-26 17:15:48 +01006582 size_t output, input;
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006583
6584 MAY_LJMP(check_args(L, 1, "output"));
6585 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
Christopher Fauleteae8afa2020-02-26 17:15:48 +01006586 hlua_http_msg_filter(L, 1, msg, &output, &input);
6587 lua_pushinteger(L, output);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006588 return 1;
6589}
6590
6591/* Copies at most <len> bytes of DATA blocks from the HTTP message <msg>
6592 * starting at the offset <offset> and put it in a string LUA variables. It
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006593 * returns the built string length. It stops on the first non-DATA HTX
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006594 * block. This function is called during the payload filtering, so the headers
6595 * are already scheduled for output (from the filter point of view).
6596 */
6597static int _hlua_http_msg_dup(struct http_msg *msg, lua_State *L, size_t offset, size_t len)
6598{
6599 struct htx *htx = htxbuf(&msg->chn->buf);
6600 struct htx_blk *blk;
6601 struct htx_ret htxret;
6602 luaL_Buffer b;
6603 int ret = 0;
6604
6605 luaL_buffinit(L, &b);
6606 htxret = htx_find_offset(htx, offset);
6607 for (blk = htxret.blk, offset = htxret.ret; blk && len; blk = htx_get_next_blk(htx, blk)) {
6608 enum htx_blk_type type = htx_get_blk_type(blk);
6609 struct ist v;
6610
6611 switch (type) {
6612 case HTX_BLK_UNUSED:
6613 break;
6614
6615 case HTX_BLK_DATA:
6616 v = htx_get_blk_value(htx, blk);
Tim Duesterhusb113b5c2021-09-15 13:58:44 +02006617 v = istadv(v, offset);
Tim Duesterhus2471f5c2021-11-08 09:05:01 +01006618 v = isttrim(v, len);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006619
6620 luaL_addlstring(&b, v.ptr, v.len);
6621 ret += v.len;
6622 break;
6623
6624 default:
vishnu0af4bd72021-10-24 06:46:24 +05306625 if (!ret)
6626 goto no_data;
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006627 goto end;
6628 }
6629 offset = 0;
6630 }
6631
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006632end:
vishnu0af4bd72021-10-24 06:46:24 +05306633 if (!ret && (htx->flags & HTX_FL_EOM))
6634 goto no_data;
6635 luaL_pushresult(&b);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006636 return ret;
vishnu0af4bd72021-10-24 06:46:24 +05306637
6638 no_data:
6639 /* Remove the empty string and push nil on the stack */
6640 lua_pop(L, 1);
6641 lua_pushnil(L);
6642 return 0;
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006643}
6644
6645/* Copies the string <str> to the HTTP message <msg> at the offset
6646 * <offset>. This function returns -1 if data cannot be copied. Otherwise, it
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006647 * returns the amount of data written. This function is responsible to update
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006648 * the filter context.
6649 */
6650static int _hlua_http_msg_insert(struct http_msg *msg, struct filter *filter, struct ist str, size_t offset)
6651{
6652 struct htx *htx = htx_from_buf(&msg->chn->buf);
6653 struct htx_ret htxret;
6654 int /*max, */ret = 0;
6655
6656 /* Nothing to do, just return */
6657 if (unlikely(istlen(str) == 0))
6658 goto end;
6659
6660 if (istlen(str) > htx_free_data_space(htx)) {
6661 ret = -1;
6662 goto end;
6663 }
6664
6665 htxret = htx_find_offset(htx, offset);
6666 if (!htxret.blk || htx_get_blk_type(htxret.blk) != HTX_BLK_DATA) {
6667 if (!htx_add_last_data(htx, str))
6668 goto end;
6669 }
6670 else {
6671 struct ist v = htx_get_blk_value(htx, htxret.blk);
6672 v.ptr += htxret.ret;
6673 v.len = 0;
6674 if (!htx_replace_blk_value(htx, htxret.blk, v, str))
6675 goto end;
6676 }
6677 ret = str.len;
6678 if (ret) {
6679 struct hlua_flt_ctx *flt_ctx = filter->ctx;
6680 flt_update_offsets(filter, msg->chn, ret);
6681 flt_ctx->cur_len[CHN_IDX(msg->chn)] += ret;
6682 }
6683
6684 end:
6685 htx_to_buf(htx, &msg->chn->buf);
6686 return ret;
6687}
6688
6689/* Helper function removing at most <len> bytes of DATA blocks at the absolute
6690 * position <offset>. It stops on the first non-DATA HTX block. This function is
6691 * called during the payload filtering, so the headers are already scheduled for
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006692 * output (from the filter point of view). This function is responsible to
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006693 * update the filter context.
6694 */
6695static void _hlua_http_msg_delete(struct http_msg *msg, struct filter *filter, size_t offset, size_t len)
6696{
6697 struct hlua_flt_ctx *flt_ctx = filter->ctx;
6698 struct htx *htx = htx_from_buf(&msg->chn->buf);
6699 struct htx_blk *blk;
6700 struct htx_ret htxret;
6701 size_t ret = 0;
6702
6703 /* Be sure <len> is always the amount of DATA to remove */
6704 if (htx->data == offset+len && htx_get_tail_type(htx) == HTX_BLK_DATA) {
Aurelien DARRAGONbcbcf982022-09-28 19:08:15 +02006705 /* When htx tail type == HTX_BLK_DATA, no need to take care
6706 * of special blocks like HTX_BLK_EOT.
6707 * We simply truncate after offset
6708 * (truncate targeted blk and discard the following ones)
6709 */
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006710 htx_truncate(htx, offset);
6711 ret = len;
6712 goto end;
6713 }
6714
6715 htxret = htx_find_offset(htx, offset);
6716 blk = htxret.blk;
6717 if (htxret.ret) {
Aurelien DARRAGONbcbcf982022-09-28 19:08:15 +02006718 /* dealing with offset: we need to trim targeted blk */
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006719 struct ist v;
6720
6721 if (htx_get_blk_type(blk) != HTX_BLK_DATA)
6722 goto end;
Aurelien DARRAGONbcbcf982022-09-28 19:08:15 +02006723
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006724 v = htx_get_blk_value(htx, blk);
Tim Duesterhusa029d782022-10-08 12:33:18 +02006725 v = istadv(v, htxret.ret);
Aurelien DARRAGONbcbcf982022-09-28 19:08:15 +02006726
Tim Duesterhus2471f5c2021-11-08 09:05:01 +01006727 v = isttrim(v, len);
Aurelien DARRAGONbcbcf982022-09-28 19:08:15 +02006728 /* trimming data in blk: discard everything after the offset
6729 * (replace 'v' with 'IST_NULL')
6730 */
Tim Duesterhusb113b5c2021-09-15 13:58:44 +02006731 blk = htx_replace_blk_value(htx, blk, v, IST_NULL);
Aurelien DARRAGONbcbcf982022-09-28 19:08:15 +02006732 if (blk && v.len < len) {
6733 /* In this case, caller wants to keep removing data,
6734 * but we need to spare current blk
6735 * because it was already trimmed
6736 */
6737 blk = htx_get_next_blk(htx, blk);
6738 }
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006739 len -= v.len;
6740 ret += v.len;
6741 }
6742
6743
6744 while (blk && len) {
Aurelien DARRAGONbcbcf982022-09-28 19:08:15 +02006745 /* there is more data that needs to be discarded */
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006746 enum htx_blk_type type = htx_get_blk_type(blk);
6747 uint32_t sz = htx_get_blksz(blk);
6748
6749 switch (type) {
6750 case HTX_BLK_UNUSED:
6751 break;
6752
6753 case HTX_BLK_DATA:
6754 if (len < sz) {
Aurelien DARRAGONbcbcf982022-09-28 19:08:15 +02006755 /* don't discard whole blk, only part of it
6756 * (from the beginning)
6757 */
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006758 htx_cut_data_blk(htx, blk, len);
6759 ret += len;
6760 goto end;
6761 }
6762 break;
6763
6764 default:
Aurelien DARRAGONbcbcf982022-09-28 19:08:15 +02006765 /* HTX_BLK_EOT blk won't be removed */
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006766 goto end;
6767 }
6768
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006769 /* Remove all the data block */
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006770 len -= sz;
6771 ret += sz;
6772 blk = htx_remove_blk(htx, blk);
6773 }
6774
6775end:
6776 flt_update_offsets(filter, msg->chn, -ret);
6777 flt_ctx->cur_len[CHN_IDX(msg->chn)] -= ret;
6778 /* WARNING: we don't call htx_to_buf() on purpose, because we don't want
6779 * to loose the EOM flag if the message is empty.
6780 */
6781}
6782
6783/* Copies input data found in an HTTP message. Unlike the channel function used
6784 * to duplicate raw data, this one can only be called inside a filter, from
6785 * http_payload callback. So it cannot yield. An exception is returned if it is
6786 * called from another callback. If nothing was copied, a nil value is pushed on
6787 * the stack.
6788 */
6789__LJMP static int hlua_http_msg_get_body(lua_State *L)
6790{
6791 struct http_msg *msg;
6792 struct filter *filter;
6793 size_t output, input;
6794 int offset, len;
6795
6796 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
6797 WILL_LJMP(luaL_error(L, "'data' expects at most 2 arguments"));
6798 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6799
6800 if (msg->msg_state < HTTP_MSG_DATA)
6801 WILL_LJMP(lua_error(L));
6802
6803 filter = hlua_http_msg_filter(L, 1, msg, &output, &input);
6804 if (!filter || !hlua_filter_from_payload(filter))
6805 WILL_LJMP(lua_error(L));
6806
6807 if (!ci_data(msg->chn) && channel_input_closed(msg->chn)) {
6808 lua_pushnil(L);
6809 return 1;
6810 }
6811
6812 offset = output;
6813 if (lua_gettop(L) > 1) {
6814 offset = MAY_LJMP(luaL_checkinteger(L, 2));
6815 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02006816 offset = MAX(0, (int)input + offset);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006817 offset += output;
6818 if (offset < output || offset > input + output) {
6819 lua_pushfstring(L, "offset out of range.");
6820 WILL_LJMP(lua_error(L));
6821 }
6822 }
6823 len = output + input - offset;
6824 if (lua_gettop(L) == 3) {
6825 len = MAY_LJMP(luaL_checkinteger(L, 3));
6826 if (!len)
6827 goto dup;
6828 if (len == -1)
6829 len = global.tune.bufsize;
6830 if (len < 0) {
6831 lua_pushfstring(L, "length out of range.");
6832 WILL_LJMP(lua_error(L));
6833 }
6834 }
6835
6836 dup:
6837 _hlua_http_msg_dup(msg, L, offset, len);
6838 return 1;
6839}
6840
6841/* Appends a string to the HTTP message, after all existing DATA blocks but
6842 * before the trailers, if any. It returns the amount of data written or -1 if
6843 * nothing was copied. Unlike the channel function used to append data, this one
6844 * can only be called inside a filter, from http_payload callback. So it cannot
6845 * yield. An exception is returned if it is called from another callback.
6846 */
6847__LJMP static int hlua_http_msg_append(lua_State *L)
6848{
6849 struct http_msg *msg;
6850 struct filter *filter;
6851 const char *str;
6852 size_t offset, len, sz;
6853 int ret;
6854
6855 MAY_LJMP(check_args(L, 2, "append"));
6856 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6857
6858 if (msg->msg_state < HTTP_MSG_DATA)
6859 WILL_LJMP(lua_error(L));
6860
6861 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
6862 filter = hlua_http_msg_filter(L, 1, msg, &offset, &len);
6863 if (!filter || !hlua_filter_from_payload(filter))
6864 WILL_LJMP(lua_error(L));
6865
6866 ret = _hlua_http_msg_insert(msg, filter, ist2(str, sz), offset+len);
6867 lua_pushinteger(L, ret);
6868 return 1;
6869}
6870
6871/* Prepends a string to the HTTP message, before all existing DATA blocks. It
6872 * returns the amount of data written or -1 if nothing was copied. Unlike the
6873 * channel function used to prepend data, this one can only be called inside a
6874 * filter, from http_payload callback. So it cannot yield. An exception is
6875 * returned if it is called from another callback.
6876 */
6877__LJMP static int hlua_http_msg_prepend(lua_State *L)
6878{
6879 struct http_msg *msg;
6880 struct filter *filter;
6881 const char *str;
6882 size_t offset, len, sz;
6883 int ret;
6884
6885 MAY_LJMP(check_args(L, 2, "prepend"));
6886 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006887
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006888 if (msg->msg_state < HTTP_MSG_DATA)
6889 WILL_LJMP(lua_error(L));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006890
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006891 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
6892 filter = hlua_http_msg_filter(L, 1, msg, &offset, &len);
6893 if (!filter || !hlua_filter_from_payload(filter))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006894 WILL_LJMP(lua_error(L));
6895
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006896 ret = _hlua_http_msg_insert(msg, filter, ist2(str, sz), offset);
6897 lua_pushinteger(L, ret);
6898 return 1;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006899}
6900
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006901/* Inserts a string to the HTTP message at a given offset. By default the string
6902 * is appended at the end of DATA blocks. It returns the amount of data written
6903 * or -1 if nothing was copied. Unlike the channel function used to insert data,
6904 * this one can only be called inside a filter, from http_payload callback. So
6905 * it cannot yield. An exception is returned if it is called from another
6906 * callback.
6907 */
6908__LJMP static int hlua_http_msg_insert_data(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006909{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006910 struct http_msg *msg;
6911 struct filter *filter;
6912 const char *str;
6913 size_t input, output, sz;
6914 int offset;
6915 int ret;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006916
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006917 if (lua_gettop(L) < 2 || lua_gettop(L) > 3)
6918 WILL_LJMP(luaL_error(L, "'insert' expects at least 1 argument and at most 2 arguments"));
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006919 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006920
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006921 if (msg->msg_state < HTTP_MSG_DATA)
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006922 WILL_LJMP(lua_error(L));
6923
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006924 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
Aurelien DARRAGON7fdba0a2022-09-28 16:03:45 +02006925 filter = hlua_http_msg_filter(L, 1, msg, &output, &input);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006926 if (!filter || !hlua_filter_from_payload(filter))
6927 WILL_LJMP(lua_error(L));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006928
Aurelien DARRAGON7fdba0a2022-09-28 16:03:45 +02006929 offset = output;
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006930 if (lua_gettop(L) > 2) {
6931 offset = MAY_LJMP(luaL_checkinteger(L, 3));
6932 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02006933 offset = MAX(0, (int)input + offset);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006934 offset += output;
Aurelien DARRAGON7fdba0a2022-09-28 16:03:45 +02006935 if (offset > output + input) {
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006936 lua_pushfstring(L, "offset out of range.");
6937 WILL_LJMP(lua_error(L));
6938 }
6939 }
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006940
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006941 ret = _hlua_http_msg_insert(msg, filter, ist2(str, sz), offset);
6942 lua_pushinteger(L, ret);
6943 return 1;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006944}
6945
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006946/* Removes a given amount of data from the HTTP message at a given offset. By
6947 * default all DATA blocks are removed. It returns the amount of data
6948 * removed. Unlike the channel function used to remove data, this one can only
6949 * be called inside a filter, from http_payload callback. So it cannot yield. An
6950 * exception is returned if it is called from another callback.
6951 */
6952__LJMP static int hlua_http_msg_del_data(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006953{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006954 struct http_msg *msg;
6955 struct filter *filter;
6956 size_t input, output;
6957 int offset, len;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006958
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006959 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
Boyang Lie0c54352022-05-10 17:47:23 +00006960 WILL_LJMP(luaL_error(L, "'remove' expects at most 2 arguments"));
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006961 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006962
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006963 if (msg->msg_state < HTTP_MSG_DATA)
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006964 WILL_LJMP(lua_error(L));
6965
Aurelien DARRAGONd7c71b02022-09-28 15:52:18 +02006966 filter = hlua_http_msg_filter(L, 1, msg, &output, &input);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006967 if (!filter || !hlua_filter_from_payload(filter))
6968 WILL_LJMP(lua_error(L));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006969
Aurelien DARRAGONd7c71b02022-09-28 15:52:18 +02006970 offset = output;
Boyang Lie0c54352022-05-10 17:47:23 +00006971 if (lua_gettop(L) > 1) {
6972 offset = MAY_LJMP(luaL_checkinteger(L, 2));
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006973 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02006974 offset = MAX(0, (int)input + offset);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006975 offset += output;
Aurelien DARRAGONd7c71b02022-09-28 15:52:18 +02006976 if (offset > output + input) {
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006977 lua_pushfstring(L, "offset out of range.");
6978 WILL_LJMP(lua_error(L));
6979 }
6980 }
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006981
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006982 len = output + input - offset;
Boyang Lie0c54352022-05-10 17:47:23 +00006983 if (lua_gettop(L) == 3) {
6984 len = MAY_LJMP(luaL_checkinteger(L, 3));
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006985 if (!len)
6986 goto end;
6987 if (len == -1)
6988 len = output + input - offset;
6989 if (len < 0 || offset + len > output + input) {
6990 lua_pushfstring(L, "length out of range.");
6991 WILL_LJMP(lua_error(L));
6992 }
6993 }
6994
6995 _hlua_http_msg_delete(msg, filter, offset, len);
6996
6997 end:
6998 lua_pushinteger(L, len);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006999 return 1;
7000}
7001
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05007002/* Replaces a given amount of data at the given offset by a string. By default,
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007003 * all remaining data are removed, accordingly to the filter context. It returns
7004 * the amount of data written or -1 if nothing was copied. Unlike the channel
7005 * function used to replace data, this one can only be called inside a filter,
7006 * from http_payload callback. So it cannot yield. An exception is returned if
7007 * it is called from another callback.
7008 */
7009__LJMP static int hlua_http_msg_set_data(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007010{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007011 struct http_msg *msg;
7012 struct filter *filter;
7013 struct htx *htx;
7014 const char *str;
7015 size_t input, output, sz;
7016 int offset, len;
7017 int ret;
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02007018
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007019 if (lua_gettop(L) < 2 || lua_gettop(L) > 4)
7020 WILL_LJMP(luaL_error(L, "'set' expects at least 1 argument and at most 3 arguments"));
7021 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
7022
7023 if (msg->msg_state < HTTP_MSG_DATA)
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02007024 WILL_LJMP(lua_error(L));
7025
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007026 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
7027 filter = hlua_http_msg_filter(L, 1, msg, &output, &input);
7028 if (!filter || !hlua_filter_from_payload(filter))
7029 WILL_LJMP(lua_error(L));
7030
7031 offset = output;
7032 if (lua_gettop(L) > 2) {
7033 offset = MAY_LJMP(luaL_checkinteger(L, 3));
7034 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02007035 offset = MAX(0, (int)input + offset);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007036 offset += output;
7037 if (offset < output || offset > input + output) {
7038 lua_pushfstring(L, "offset out of range.");
7039 WILL_LJMP(lua_error(L));
7040 }
7041 }
7042
7043 len = output + input - offset;
7044 if (lua_gettop(L) == 4) {
7045 len = MAY_LJMP(luaL_checkinteger(L, 4));
7046 if (!len)
7047 goto set;
7048 if (len == -1)
7049 len = output + input - offset;
7050 if (len < 0 || offset + len > output + input) {
7051 lua_pushfstring(L, "length out of range.");
7052 WILL_LJMP(lua_error(L));
7053 }
7054 }
7055
7056 set:
7057 /* Be sure we can copied the string once input data will be removed. */
7058 htx = htx_from_buf(&msg->chn->buf);
7059 if (sz > htx_free_data_space(htx) + len)
7060 lua_pushinteger(L, -1);
7061 else {
7062 _hlua_http_msg_delete(msg, filter, offset, len);
7063 ret = _hlua_http_msg_insert(msg, filter, ist2(str, sz), offset);
7064 lua_pushinteger(L, ret);
7065 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007066 return 1;
7067}
7068
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007069/* Prepends data into an HTTP message and forward it, from the filter point of
7070 * view. It returns the amount of data written or -1 if nothing was sent. Unlike
7071 * the channel function used to send data, this one can only be called inside a
7072 * filter, from http_payload callback. So it cannot yield. An exception is
7073 * returned if it is called from another callback.
7074 */
7075__LJMP static int hlua_http_msg_send(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007076{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007077 struct http_msg *msg;
7078 struct filter *filter;
7079 struct htx *htx;
7080 const char *str;
7081 size_t offset, len, sz;
7082 int ret;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007083
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007084 MAY_LJMP(check_args(L, 2, "send"));
7085 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
7086
7087 if (msg->msg_state < HTTP_MSG_DATA)
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02007088 WILL_LJMP(lua_error(L));
7089
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007090 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
7091 filter = hlua_http_msg_filter(L, 1, msg, &offset, &len);
7092 if (!filter || !hlua_filter_from_payload(filter))
7093 WILL_LJMP(lua_error(L));
7094
7095 /* Return an error if the channel's output is closed */
7096 if (unlikely(channel_output_closed(msg->chn))) {
7097 lua_pushinteger(L, -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007098 return 1;
7099 }
7100
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007101 htx = htx_from_buf(&msg->chn->buf);
7102 if (sz > htx_free_data_space(htx)) {
7103 lua_pushinteger(L, -1);
7104 return 1;
7105 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007106
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007107 ret = _hlua_http_msg_insert(msg, filter, ist2(str, sz), offset);
7108 if (ret > 0) {
7109 struct hlua_flt_ctx *flt_ctx = filter->ctx;
7110
7111 FLT_OFF(filter, msg->chn) += ret;
7112 flt_ctx->cur_len[CHN_IDX(msg->chn)] -= ret;
7113 flt_ctx->cur_off[CHN_IDX(msg->chn)] += ret;
7114 }
7115
7116 lua_pushinteger(L, ret);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007117 return 1;
7118}
7119
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007120/* Forwards a given amount of bytes. It return -1 if the channel's output is
7121 * closed. Otherwise, it returns the number of bytes forwarded. Unlike the
7122 * channel function used to forward data, this one can only be called inside a
7123 * filter, from http_payload callback. So it cannot yield. An exception is
7124 * returned if it is called from another callback. All other functions deal with
7125 * DATA block, this one not.
7126*/
7127__LJMP static int hlua_http_msg_forward(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007128{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007129 struct http_msg *msg;
7130 struct filter *filter;
7131 size_t offset, len;
7132 int fwd, ret = 0;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007133
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007134 MAY_LJMP(check_args(L, 2, "forward"));
7135 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
7136
7137 if (msg->msg_state < HTTP_MSG_DATA)
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02007138 WILL_LJMP(lua_error(L));
7139
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007140 fwd = MAY_LJMP(luaL_checkinteger(L, 2));
7141 filter = hlua_http_msg_filter(L, 1, msg, &offset, &len);
7142 if (!filter || !hlua_filter_from_payload(filter))
7143 WILL_LJMP(lua_error(L));
7144
7145 /* Nothing to do, just return */
7146 if (!fwd)
7147 goto end;
7148
7149 /* Return an error if the channel's output is closed */
7150 if (unlikely(channel_output_closed(msg->chn))) {
7151 ret = -1;
7152 goto end;
7153 }
7154
7155 ret = fwd;
7156 if (ret > len)
7157 ret = len;
7158
7159 if (ret) {
7160 struct hlua_flt_ctx *flt_ctx = filter->ctx;
7161
7162 FLT_OFF(filter, msg->chn) += ret;
7163 flt_ctx->cur_off[CHN_IDX(msg->chn)] += ret;
7164 flt_ctx->cur_len[CHN_IDX(msg->chn)] -= ret;
7165 }
7166
7167 end:
7168 lua_pushinteger(L, ret);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007169 return 1;
7170}
7171
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007172/* Set EOM flag on the HTX message.
7173 *
7174 * NOTE: Not sure it is a good idea to manipulate this flag but for now I don't
7175 * really know how to do without this feature.
7176 */
7177__LJMP static int hlua_http_msg_set_eom(lua_State *L)
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02007178{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007179 struct http_msg *msg;
7180 struct htx *htx;
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02007181
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007182 MAY_LJMP(check_args(L, 1, "set_eom"));
7183 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
7184 htx = htxbuf(&msg->chn->buf);
7185 htx->flags |= HTX_FL_EOM;
7186 return 0;
7187}
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02007188
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007189/* Unset EOM flag on the HTX message.
7190 *
7191 * NOTE: Not sure it is a good idea to manipulate this flag but for now I don't
7192 * really know how to do without this feature.
7193 */
7194__LJMP static int hlua_http_msg_unset_eom(lua_State *L)
7195{
7196 struct http_msg *msg;
7197 struct htx *htx;
7198
7199 MAY_LJMP(check_args(L, 1, "set_eom"));
7200 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
7201 htx = htxbuf(&msg->chn->buf);
7202 htx->flags &= ~HTX_FL_EOM;
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02007203 return 0;
7204}
7205
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007206/*
7207 *
7208 *
William Lallemand3956c4e2021-09-21 16:25:15 +02007209 * Class HTTPClient
7210 *
7211 *
7212 */
7213__LJMP static struct hlua_httpclient *hlua_checkhttpclient(lua_State *L, int ud)
7214{
7215 return MAY_LJMP(hlua_checkudata(L, ud, class_httpclient_ref));
7216}
7217
William Lallemandf77f1de2021-09-28 19:10:38 +02007218
7219/* stops the httpclient and ask it to kill itself */
7220__LJMP static int hlua_httpclient_gc(lua_State *L)
7221{
7222 struct hlua_httpclient *hlua_hc;
7223
7224 MAY_LJMP(check_args(L, 1, "__gc"));
7225
7226 hlua_hc = MAY_LJMP(hlua_checkhttpclient(L, 1));
7227
Aurelien DARRAGON3ffbf382023-02-09 17:02:57 +01007228 if (MT_LIST_DELETE(&hlua_hc->by_hlua)) {
7229 /* we won the race against hlua_httpclient_destroy_all() */
William Lallemandbb581422022-10-20 10:57:28 +02007230 httpclient_stop_and_destroy(hlua_hc->hc);
Aurelien DARRAGON3ffbf382023-02-09 17:02:57 +01007231 hlua_hc->hc = NULL;
7232 }
William Lallemandf77f1de2021-09-28 19:10:38 +02007233
7234 return 0;
7235}
7236
7237
William Lallemand3956c4e2021-09-21 16:25:15 +02007238__LJMP static int hlua_httpclient_new(lua_State *L)
7239{
7240 struct hlua_httpclient *hlua_hc;
7241 struct hlua *hlua;
7242
7243 /* Get hlua struct, or NULL if we execute from main lua state */
7244 hlua = hlua_gethlua(L);
7245 if (!hlua)
7246 return 0;
7247
7248 /* Check stack size. */
7249 if (!lua_checkstack(L, 3)) {
7250 hlua_pusherror(L, "httpclient: full stack");
7251 goto err;
7252 }
7253 /* Create the object: obj[0] = userdata. */
7254 lua_newtable(L);
7255 hlua_hc = MAY_LJMP(lua_newuserdata(L, sizeof(*hlua_hc)));
7256 lua_rawseti(L, -2, 0);
7257 memset(hlua_hc, 0, sizeof(*hlua_hc));
7258
7259 hlua_hc->hc = httpclient_new(hlua, 0, IST_NULL);
7260 if (!hlua_hc->hc)
7261 goto err;
7262
Aurelien DARRAGON3ffbf382023-02-09 17:02:57 +01007263 MT_LIST_APPEND(&hlua->hc_list, &hlua_hc->by_hlua);
William Lallemandbb581422022-10-20 10:57:28 +02007264
William Lallemand3956c4e2021-09-21 16:25:15 +02007265 /* Pop a class stream metatable and affect it to the userdata. */
7266 lua_rawgeti(L, LUA_REGISTRYINDEX, class_httpclient_ref);
7267 lua_setmetatable(L, -2);
7268
7269 return 1;
7270
7271 err:
7272 WILL_LJMP(lua_error(L));
7273 return 0;
7274}
7275
7276
7277/*
7278 * Callback of the httpclient, this callback wakes the lua task up, once the
7279 * httpclient receives some data
7280 *
7281 */
7282
William Lallemandbd5739e2021-10-28 15:41:38 +02007283static void hlua_httpclient_cb(struct httpclient *hc)
William Lallemand3956c4e2021-09-21 16:25:15 +02007284{
7285 struct hlua *hlua = hc->caller;
7286
7287 if (!hlua || !hlua->task)
7288 return;
7289
7290 task_wakeup(hlua->task, TASK_WOKEN_MSG);
7291}
7292
7293/*
William Lallemandd7df73a2021-09-23 17:54:00 +02007294 * Fill the lua stack with headers from the httpclient response
7295 * This works the same way as the hlua_http_get_headers() function
7296 */
7297__LJMP static int hlua_httpclient_get_headers(lua_State *L, struct hlua_httpclient *hlua_hc)
7298{
7299 struct http_hdr *hdr;
7300
7301 lua_newtable(L);
7302
William Lallemandef574b22021-10-05 16:19:31 +02007303 for (hdr = hlua_hc->hc->res.hdrs; hdr && isttest(hdr->n); hdr++) {
William Lallemandd7df73a2021-09-23 17:54:00 +02007304 struct ist n, v;
7305 int len;
7306
7307 n = hdr->n;
7308 v = hdr->v;
7309
7310 /* Check for existing entry:
7311 * assume that the table is on the top of the stack, and
7312 * push the key in the stack, the function lua_gettable()
7313 * perform the lookup.
7314 */
7315
7316 lua_pushlstring(L, n.ptr, n.len);
7317 lua_gettable(L, -2);
7318
7319 switch (lua_type(L, -1)) {
7320 case LUA_TNIL:
7321 /* Table not found, create it. */
7322 lua_pop(L, 1); /* remove the nil value. */
7323 lua_pushlstring(L, n.ptr, n.len); /* push the header name as key. */
7324 lua_newtable(L); /* create and push empty table. */
7325 lua_pushlstring(L, v.ptr, v.len); /* push header value. */
7326 lua_rawseti(L, -2, 0); /* index header value (pop it). */
7327 lua_rawset(L, -3); /* index new table with header name (pop the values). */
7328 break;
7329
7330 case LUA_TTABLE:
7331 /* Entry found: push the value in the table. */
7332 len = lua_rawlen(L, -1);
7333 lua_pushlstring(L, v.ptr, v.len); /* push header value. */
7334 lua_rawseti(L, -2, len+1); /* index header value (pop it). */
7335 lua_pop(L, 1); /* remove the table (it is stored in the main table). */
7336 break;
7337
7338 default:
7339 /* Other cases are errors. */
7340 hlua_pusherror(L, "internal error during the parsing of headers.");
7341 WILL_LJMP(lua_error(L));
7342 }
7343 }
7344 return 1;
7345}
7346
7347/*
William Lallemand746e6f32021-10-06 10:57:44 +02007348 * Allocate and return an array of http_hdr ist extracted from the <headers> lua table
7349 *
7350 * Caller must free the result
7351 */
7352struct http_hdr *hlua_httpclient_table_to_hdrs(lua_State *L)
7353{
7354 struct http_hdr hdrs[global.tune.max_http_hdr];
7355 struct http_hdr *result = NULL;
7356 uint32_t hdr_num = 0;
7357
7358 lua_pushnil(L);
7359 while (lua_next(L, -2) != 0) {
7360 struct ist name, value;
7361 const char *n, *v;
7362 size_t nlen, vlen;
7363
7364 if (!lua_isstring(L, -2) || !lua_istable(L, -1)) {
7365 /* Skip element if the key is not a string or if the value is not a table */
7366 goto next_hdr;
7367 }
7368
7369 n = lua_tolstring(L, -2, &nlen);
7370 name = ist2(n, nlen);
7371
7372 /* Loop on header's values */
7373 lua_pushnil(L);
7374 while (lua_next(L, -2)) {
7375 if (!lua_isstring(L, -1)) {
7376 /* Skip the value if it is not a string */
7377 goto next_value;
7378 }
7379
7380 v = lua_tolstring(L, -1, &vlen);
7381 value = ist2(v, vlen);
7382 name = ist2(n, nlen);
7383
7384 hdrs[hdr_num].n = istdup(name);
7385 hdrs[hdr_num].v = istdup(value);
7386
7387 hdr_num++;
7388
7389 next_value:
7390 lua_pop(L, 1);
7391 }
7392
7393 next_hdr:
7394 lua_pop(L, 1);
7395
7396 }
7397
7398 if (hdr_num) {
7399 /* alloc and copy the headers in the httpclient struct */
Tim Duesterhus16cc16d2021-11-06 15:14:45 +01007400 result = calloc((hdr_num + 1), sizeof(*result));
William Lallemand746e6f32021-10-06 10:57:44 +02007401 if (!result)
7402 goto skip_headers;
7403 memcpy(result, hdrs, sizeof(struct http_hdr) * (hdr_num + 1));
7404
7405 result[hdr_num].n = IST_NULL;
7406 result[hdr_num].v = IST_NULL;
7407 }
7408
7409skip_headers:
William Lallemand746e6f32021-10-06 10:57:44 +02007410
7411 return result;
7412}
7413
7414
William Lallemandbd5739e2021-10-28 15:41:38 +02007415/*
7416 * For each yield, checks if there is some data in the httpclient and push them
7417 * in the lua buffer, once the httpclient finished its job, push the result on
7418 * the stack
7419 */
7420__LJMP static int hlua_httpclient_rcv_yield(lua_State *L, int status, lua_KContext ctx)
7421{
7422 struct buffer *tr;
7423 int res;
7424 struct hlua *hlua = hlua_gethlua(L);
7425 struct hlua_httpclient *hlua_hc = hlua_checkhttpclient(L, 1);
7426
7427
7428 tr = get_trash_chunk();
7429
7430 res = httpclient_res_xfer(hlua_hc->hc, tr);
7431 luaL_addlstring(&hlua_hc->b, b_orig(tr), res);
7432
7433 if (!httpclient_data(hlua_hc->hc) && httpclient_ended(hlua_hc->hc)) {
7434
7435 luaL_pushresult(&hlua_hc->b);
7436 lua_settable(L, -3);
7437
7438 lua_pushstring(L, "status");
7439 lua_pushinteger(L, hlua_hc->hc->res.status);
7440 lua_settable(L, -3);
7441
7442
7443 lua_pushstring(L, "reason");
7444 lua_pushlstring(L, hlua_hc->hc->res.reason.ptr, hlua_hc->hc->res.reason.len);
7445 lua_settable(L, -3);
7446
7447 lua_pushstring(L, "headers");
7448 hlua_httpclient_get_headers(L, hlua_hc);
7449 lua_settable(L, -3);
7450
7451 return 1;
7452 }
7453
7454 if (httpclient_data(hlua_hc->hc))
7455 task_wakeup(hlua->task, TASK_WOKEN_MSG);
7456
7457 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_httpclient_rcv_yield, TICK_ETERNITY, 0));
7458
7459 return 0;
7460}
7461
7462/*
7463 * Call this when trying to stream a body during a request
7464 */
7465__LJMP static int hlua_httpclient_snd_yield(lua_State *L, int status, lua_KContext ctx)
7466{
7467 struct hlua *hlua;
7468 struct hlua_httpclient *hlua_hc = hlua_checkhttpclient(L, 1);
7469 const char *body_str = NULL;
7470 int ret;
7471 int end = 0;
7472 size_t buf_len;
7473 size_t to_send = 0;
7474
7475 hlua = hlua_gethlua(L);
7476
7477 if (!hlua || !hlua->task)
7478 WILL_LJMP(luaL_error(L, "The 'get' function is only allowed in "
7479 "'frontend', 'backend' or 'task'"));
7480
7481 ret = lua_getfield(L, -1, "body");
7482 if (ret != LUA_TSTRING)
7483 goto rcv;
7484
7485 body_str = lua_tolstring(L, -1, &buf_len);
7486 lua_pop(L, 1);
7487
Christopher Fauletfc591292022-01-12 14:46:03 +01007488 to_send = buf_len - hlua_hc->sent;
William Lallemandbd5739e2021-10-28 15:41:38 +02007489
7490 if ((hlua_hc->sent + to_send) >= buf_len)
7491 end = 1;
7492
7493 /* the end flag is always set since we are using the whole remaining size */
7494 hlua_hc->sent += httpclient_req_xfer(hlua_hc->hc, ist2(body_str + hlua_hc->sent, to_send), end);
7495
7496 if (buf_len > hlua_hc->sent) {
7497 /* still need to process the buffer */
7498 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_httpclient_snd_yield, TICK_ETERNITY, 0));
7499 } else {
7500 goto rcv;
7501 /* we sent the whole request buffer we can recv */
7502 }
7503 return 0;
7504
7505rcv:
7506
7507 /* we return a "res" object */
7508 lua_newtable(L);
7509
William Lallemandbd5739e2021-10-28 15:41:38 +02007510 lua_pushstring(L, "body");
William Lallemandd1187eb2021-11-02 10:40:06 +01007511 luaL_buffinit(L, &hlua_hc->b);
William Lallemandbd5739e2021-10-28 15:41:38 +02007512
William Lallemand933fe392021-11-04 09:45:58 +01007513 task_wakeup(hlua->task, TASK_WOKEN_MSG);
William Lallemandbd5739e2021-10-28 15:41:38 +02007514 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_httpclient_rcv_yield, TICK_ETERNITY, 0));
7515
7516 return 1;
7517}
William Lallemand746e6f32021-10-06 10:57:44 +02007518
William Lallemand3956c4e2021-09-21 16:25:15 +02007519/*
William Lallemanddc2cc902021-10-26 11:43:26 +02007520 * Send an HTTP request and wait for a response
William Lallemand3956c4e2021-09-21 16:25:15 +02007521 */
7522
William Lallemanddc2cc902021-10-26 11:43:26 +02007523__LJMP static int hlua_httpclient_send(lua_State *L, enum http_meth_t meth)
William Lallemand3956c4e2021-09-21 16:25:15 +02007524{
7525 struct hlua_httpclient *hlua_hc;
William Lallemand746e6f32021-10-06 10:57:44 +02007526 struct http_hdr *hdrs = NULL;
7527 struct http_hdr *hdrs_i = NULL;
William Lallemand3956c4e2021-09-21 16:25:15 +02007528 struct hlua *hlua;
William Lallemand746e6f32021-10-06 10:57:44 +02007529 const char *url_str = NULL;
William Lallemanddec25c32021-10-25 19:48:37 +02007530 const char *body_str = NULL;
Christopher Faulet380ae9c2022-10-14 14:57:04 +02007531 size_t buf_len = 0;
William Lallemand746e6f32021-10-06 10:57:44 +02007532 int ret;
William Lallemand3956c4e2021-09-21 16:25:15 +02007533
7534 hlua = hlua_gethlua(L);
7535
7536 if (!hlua || !hlua->task)
7537 WILL_LJMP(luaL_error(L, "The 'get' function is only allowed in "
7538 "'frontend', 'backend' or 'task'"));
7539
William Lallemand746e6f32021-10-06 10:57:44 +02007540 if (lua_gettop(L) != 2 || lua_type(L, -1) != LUA_TTABLE)
7541 WILL_LJMP(luaL_error(L, "'get' needs a table as argument"));
7542
William Lallemand4f4f2b72022-02-17 20:00:23 +01007543 hlua_hc = hlua_checkhttpclient(L, 1);
7544
William Lallemand7177a952022-03-03 15:33:12 +01007545 lua_pushnil(L); /* first key */
7546 while (lua_next(L, 2)) {
7547 if (strcmp(lua_tostring(L, -2), "dst") == 0) {
7548 if (httpclient_set_dst(hlua_hc->hc, lua_tostring(L, -1)) < 0)
7549 WILL_LJMP(luaL_error(L, "Can't use the 'dst' argument"));
William Lallemand4f4f2b72022-02-17 20:00:23 +01007550
William Lallemand7177a952022-03-03 15:33:12 +01007551 } else if (strcmp(lua_tostring(L, -2), "url") == 0) {
7552 if (lua_type(L, -1) != LUA_TSTRING)
7553 WILL_LJMP(luaL_error(L, "invalid parameter in 'url', must be a string"));
7554 url_str = lua_tostring(L, -1);
William Lallemand3956c4e2021-09-21 16:25:15 +02007555
William Lallemand7177a952022-03-03 15:33:12 +01007556 } else if (strcmp(lua_tostring(L, -2), "timeout") == 0) {
7557 if (lua_type(L, -1) != LUA_TNUMBER)
7558 WILL_LJMP(luaL_error(L, "invalid parameter in 'timeout', must be a number"));
7559 httpclient_set_timeout(hlua_hc->hc, lua_tointeger(L, -1));
William Lallemandb4a4ef62022-02-23 14:18:16 +01007560
William Lallemand7177a952022-03-03 15:33:12 +01007561 } else if (strcmp(lua_tostring(L, -2), "headers") == 0) {
7562 if (lua_type(L, -1) != LUA_TTABLE)
7563 WILL_LJMP(luaL_error(L, "invalid parameter in 'headers', must be a table"));
7564 hdrs = hlua_httpclient_table_to_hdrs(L);
William Lallemand79416cb2021-09-24 14:51:44 +02007565
William Lallemand7177a952022-03-03 15:33:12 +01007566 } else if (strcmp(lua_tostring(L, -2), "body") == 0) {
7567 if (lua_type(L, -1) != LUA_TSTRING)
7568 WILL_LJMP(luaL_error(L, "invalid parameter in 'body', must be a string"));
7569 body_str = lua_tolstring(L, -1, &buf_len);
William Lallemandbd5739e2021-10-28 15:41:38 +02007570
William Lallemand7177a952022-03-03 15:33:12 +01007571 } else {
7572 WILL_LJMP(luaL_error(L, "'%s' invalid parameter name", lua_tostring(L, -2)));
7573 }
7574 /* removes 'value'; keeps 'key' for next iteration */
7575 lua_pop(L, 1);
7576 }
William Lallemanddec25c32021-10-25 19:48:37 +02007577
William Lallemand746e6f32021-10-06 10:57:44 +02007578 if (!url_str) {
7579 WILL_LJMP(luaL_error(L, "'get' need a 'url' argument"));
7580 return 0;
7581 }
William Lallemand3956c4e2021-09-21 16:25:15 +02007582
William Lallemand10a37362022-03-02 16:18:26 +01007583 hlua_hc->sent = 0;
William Lallemand3956c4e2021-09-21 16:25:15 +02007584
Aurelien DARRAGON03564072023-02-09 15:26:25 +01007585 istfree(&hlua_hc->hc->req.url);
William Lallemand3956c4e2021-09-21 16:25:15 +02007586 hlua_hc->hc->req.url = istdup(ist(url_str));
William Lallemanddc2cc902021-10-26 11:43:26 +02007587 hlua_hc->hc->req.meth = meth;
William Lallemand3956c4e2021-09-21 16:25:15 +02007588
7589 /* update the httpclient callbacks */
William Lallemandbd5739e2021-10-28 15:41:38 +02007590 hlua_hc->hc->ops.res_stline = hlua_httpclient_cb;
7591 hlua_hc->hc->ops.res_headers = hlua_httpclient_cb;
7592 hlua_hc->hc->ops.res_payload = hlua_httpclient_cb;
William Lallemand8f170c72022-03-15 10:52:07 +01007593 hlua_hc->hc->ops.res_end = hlua_httpclient_cb;
William Lallemand3956c4e2021-09-21 16:25:15 +02007594
William Lallemandbd5739e2021-10-28 15:41:38 +02007595 /* a body is available, it will use the request callback */
Christopher Faulet380ae9c2022-10-14 14:57:04 +02007596 if (body_str && buf_len) {
William Lallemandbd5739e2021-10-28 15:41:38 +02007597 hlua_hc->hc->ops.req_payload = hlua_httpclient_cb;
7598 }
William Lallemand3956c4e2021-09-21 16:25:15 +02007599
William Lallemandbd5739e2021-10-28 15:41:38 +02007600 ret = httpclient_req_gen(hlua_hc->hc, hlua_hc->hc->req.url, meth, hdrs, IST_NULL);
William Lallemand3956c4e2021-09-21 16:25:15 +02007601
William Lallemand746e6f32021-10-06 10:57:44 +02007602 /* free the temporary headers array */
7603 hdrs_i = hdrs;
7604 while (hdrs_i && isttest(hdrs_i->n)) {
7605 istfree(&hdrs_i->n);
7606 istfree(&hdrs_i->v);
7607 hdrs_i++;
7608 }
7609 ha_free(&hdrs);
7610
7611
William Lallemand6137a9e2021-10-26 15:01:53 +02007612 if (ret != ERR_NONE) {
7613 WILL_LJMP(luaL_error(L, "Can't generate the HTTP request"));
7614 return 0;
7615 }
7616
William Lallemandc2d3db42022-04-26 11:46:13 +02007617 if (!httpclient_start(hlua_hc->hc))
7618 WILL_LJMP(luaL_error(L, "couldn't start the httpclient"));
William Lallemand6137a9e2021-10-26 15:01:53 +02007619
William Lallemandbd5739e2021-10-28 15:41:38 +02007620 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_httpclient_snd_yield, TICK_ETERNITY, 0));
William Lallemand3956c4e2021-09-21 16:25:15 +02007621
William Lallemand3956c4e2021-09-21 16:25:15 +02007622 return 0;
7623}
7624
7625/*
William Lallemanddc2cc902021-10-26 11:43:26 +02007626 * Sends an HTTP HEAD request and wait for a response
7627 *
7628 * httpclient:head(url, headers, payload)
7629 */
7630__LJMP static int hlua_httpclient_head(lua_State *L)
7631{
7632 return hlua_httpclient_send(L, HTTP_METH_HEAD);
7633}
7634
7635/*
7636 * Send an HTTP GET request and wait for a response
7637 *
7638 * httpclient:get(url, headers, payload)
7639 */
7640__LJMP static int hlua_httpclient_get(lua_State *L)
7641{
7642 return hlua_httpclient_send(L, HTTP_METH_GET);
7643
7644}
7645
7646/*
7647 * Sends an HTTP PUT request and wait for a response
7648 *
7649 * httpclient:put(url, headers, payload)
7650 */
7651__LJMP static int hlua_httpclient_put(lua_State *L)
7652{
7653 return hlua_httpclient_send(L, HTTP_METH_PUT);
7654}
7655
7656/*
7657 * Send an HTTP POST request and wait for a response
7658 *
7659 * httpclient:post(url, headers, payload)
7660 */
7661__LJMP static int hlua_httpclient_post(lua_State *L)
7662{
7663 return hlua_httpclient_send(L, HTTP_METH_POST);
7664}
7665
7666
7667/*
7668 * Sends an HTTP DELETE request and wait for a response
7669 *
7670 * httpclient:delete(url, headers, payload)
7671 */
7672__LJMP static int hlua_httpclient_delete(lua_State *L)
7673{
7674 return hlua_httpclient_send(L, HTTP_METH_DELETE);
7675}
7676
7677/*
William Lallemand3956c4e2021-09-21 16:25:15 +02007678 *
7679 *
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007680 * Class TXN
7681 *
7682 *
7683 */
7684
7685/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02007686 * a class stream, otherwise it throws an error.
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007687 */
7688__LJMP static struct hlua_txn *hlua_checktxn(lua_State *L, int ud)
7689{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02007690 return MAY_LJMP(hlua_checkudata(L, ud, class_txn_ref));
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007691}
7692
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007693__LJMP static int hlua_set_var(lua_State *L)
7694{
7695 struct hlua_txn *htxn;
7696 const char *name;
7697 size_t len;
7698 struct sample smp;
7699
Tim Duesterhus4e172c92020-05-19 13:49:42 +02007700 if (lua_gettop(L) < 3 || lua_gettop(L) > 4)
7701 WILL_LJMP(luaL_error(L, "'set_var' needs between 3 and 4 arguments"));
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007702
7703 /* It is useles to retrieve the stream, but this function
7704 * runs only in a stream context.
7705 */
7706 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7707 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
7708
7709 /* Converts the third argument in a sample. */
Amaury Denoyellebc0af6a2020-10-29 17:21:20 +01007710 memset(&smp, 0, sizeof(smp));
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007711 hlua_lua2smp(L, 3, &smp);
7712
7713 /* Store the sample in a variable. */
Willy Tarreau7560dd42016-03-10 16:28:58 +01007714 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
Tim Duesterhus4e172c92020-05-19 13:49:42 +02007715
7716 if (lua_gettop(L) == 4 && lua_toboolean(L, 4))
7717 lua_pushboolean(L, vars_set_by_name_ifexist(name, len, &smp) != 0);
7718 else
7719 lua_pushboolean(L, vars_set_by_name(name, len, &smp) != 0);
7720
Tim Duesterhus84ebc132020-05-19 13:49:41 +02007721 return 1;
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007722}
7723
Christopher Faulet85d79c92016-11-09 16:54:56 +01007724__LJMP static int hlua_unset_var(lua_State *L)
7725{
7726 struct hlua_txn *htxn;
7727 const char *name;
7728 size_t len;
7729 struct sample smp;
7730
7731 MAY_LJMP(check_args(L, 2, "unset_var"));
7732
7733 /* It is useles to retrieve the stream, but this function
7734 * runs only in a stream context.
7735 */
7736 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7737 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
7738
7739 /* Unset the variable. */
7740 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
Tim Duesterhus84ebc132020-05-19 13:49:41 +02007741 lua_pushboolean(L, vars_unset_by_name_ifexist(name, len, &smp) != 0);
7742 return 1;
Christopher Faulet85d79c92016-11-09 16:54:56 +01007743}
7744
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007745__LJMP static int hlua_get_var(lua_State *L)
7746{
7747 struct hlua_txn *htxn;
7748 const char *name;
7749 size_t len;
7750 struct sample smp;
7751
7752 MAY_LJMP(check_args(L, 2, "get_var"));
7753
7754 /* It is useles to retrieve the stream, but this function
7755 * runs only in a stream context.
7756 */
7757 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7758 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
7759
Willy Tarreau7560dd42016-03-10 16:28:58 +01007760 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
Willy Tarreaue352b9d2021-09-03 11:52:38 +02007761 if (!vars_get_by_name(name, len, &smp, NULL)) {
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007762 lua_pushnil(L);
7763 return 1;
7764 }
7765
7766 return hlua_smp2lua(L, &smp);
7767}
7768
Willy Tarreau59551662015-03-10 14:23:13 +01007769__LJMP static int hlua_set_priv(lua_State *L)
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007770{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007771 struct hlua *hlua;
7772
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007773 MAY_LJMP(check_args(L, 2, "set_priv"));
7774
Willy Tarreau87b09662015-04-03 00:22:06 +02007775 /* It is useles to retrieve the stream, but this function
7776 * runs only in a stream context.
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007777 */
7778 MAY_LJMP(hlua_checktxn(L, 1));
Thierry Fournier4234dbd2020-11-28 13:18:23 +01007779
7780 /* Get hlua struct, or NULL if we execute from main lua state */
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007781 hlua = hlua_gethlua(L);
Thierry Fournier4234dbd2020-11-28 13:18:23 +01007782 if (!hlua)
7783 return 0;
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007784
7785 /* Remove previous value. */
Thierry FOURNIERe068b602017-04-26 13:27:05 +02007786 luaL_unref(L, LUA_REGISTRYINDEX, hlua->Mref);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007787
7788 /* Get and store new value. */
7789 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
7790 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
7791
7792 return 0;
7793}
7794
Willy Tarreau59551662015-03-10 14:23:13 +01007795__LJMP static int hlua_get_priv(lua_State *L)
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007796{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007797 struct hlua *hlua;
7798
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007799 MAY_LJMP(check_args(L, 1, "get_priv"));
7800
Willy Tarreau87b09662015-04-03 00:22:06 +02007801 /* It is useles to retrieve the stream, but this function
7802 * runs only in a stream context.
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007803 */
7804 MAY_LJMP(hlua_checktxn(L, 1));
Thierry Fournier4234dbd2020-11-28 13:18:23 +01007805
7806 /* Get hlua struct, or NULL if we execute from main lua state */
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007807 hlua = hlua_gethlua(L);
Thierry Fournier4234dbd2020-11-28 13:18:23 +01007808 if (!hlua) {
7809 lua_pushnil(L);
7810 return 1;
7811 }
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007812
7813 /* Push configuration index in the stack. */
7814 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
7815
7816 return 1;
7817}
7818
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007819/* Create stack entry containing a class TXN. This function
7820 * return 0 if the stack does not contains free slots,
7821 * otherwise it returns 1.
7822 */
Thierry FOURNIERab00df62016-07-14 11:42:37 +02007823static int hlua_txn_new(lua_State *L, struct stream *s, struct proxy *p, int dir, int flags)
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007824{
Willy Tarreaude491382015-04-06 11:04:28 +02007825 struct hlua_txn *htxn;
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007826
7827 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01007828 if (!lua_checkstack(L, 3))
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007829 return 0;
7830
7831 /* NOTE: The allocation never fails. The failure
7832 * throw an error, and the function never returns.
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08007833 * if the throw is not available, the process is aborted.
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007834 */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01007835 /* Create the object: obj[0] = userdata. */
7836 lua_newtable(L);
Willy Tarreaude491382015-04-06 11:04:28 +02007837 htxn = lua_newuserdata(L, sizeof(*htxn));
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01007838 lua_rawseti(L, -2, 0);
7839
Willy Tarreaude491382015-04-06 11:04:28 +02007840 htxn->s = s;
7841 htxn->p = p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01007842 htxn->dir = dir;
Thierry FOURNIERab00df62016-07-14 11:42:37 +02007843 htxn->flags = flags;
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007844
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01007845 /* Create the "f" field that contains a list of fetches. */
7846 lua_pushstring(L, "f");
Thierry FOURNIERca988662015-12-20 18:43:03 +01007847 if (!hlua_fetches_new(L, htxn, HLUA_F_MAY_USE_HTTP))
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01007848 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007849 lua_rawset(L, -3);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01007850
7851 /* Create the "sf" field that contains a list of stringsafe fetches. */
7852 lua_pushstring(L, "sf");
Thierry FOURNIERca988662015-12-20 18:43:03 +01007853 if (!hlua_fetches_new(L, htxn, HLUA_F_MAY_USE_HTTP | HLUA_F_AS_STRING))
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01007854 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007855 lua_rawset(L, -3);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01007856
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007857 /* Create the "c" field that contains a list of converters. */
7858 lua_pushstring(L, "c");
Willy Tarreaude491382015-04-06 11:04:28 +02007859 if (!hlua_converters_new(L, htxn, 0))
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01007860 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007861 lua_rawset(L, -3);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01007862
7863 /* Create the "sc" field that contains a list of stringsafe converters. */
7864 lua_pushstring(L, "sc");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01007865 if (!hlua_converters_new(L, htxn, HLUA_F_AS_STRING))
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007866 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007867 lua_rawset(L, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007868
Thierry FOURNIER397826a2015-03-11 19:39:09 +01007869 /* Create the "req" field that contains the request channel object. */
7870 lua_pushstring(L, "req");
Willy Tarreau2a71af42015-03-10 13:51:50 +01007871 if (!hlua_channel_new(L, &s->req))
Thierry FOURNIER397826a2015-03-11 19:39:09 +01007872 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007873 lua_rawset(L, -3);
Thierry FOURNIER397826a2015-03-11 19:39:09 +01007874
7875 /* Create the "res" field that contains the response channel object. */
7876 lua_pushstring(L, "res");
Willy Tarreau2a71af42015-03-10 13:51:50 +01007877 if (!hlua_channel_new(L, &s->res))
Thierry FOURNIER397826a2015-03-11 19:39:09 +01007878 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007879 lua_rawset(L, -3);
Thierry FOURNIER397826a2015-03-11 19:39:09 +01007880
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007881 /* Creates the HTTP object is the current proxy allows http. */
7882 lua_pushstring(L, "http");
Christopher Faulet1bb6afa2021-03-08 17:57:53 +01007883 if (IS_HTX_STRM(s)) {
Willy Tarreaude491382015-04-06 11:04:28 +02007884 if (!hlua_http_new(L, htxn))
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007885 return 0;
7886 }
7887 else
7888 lua_pushnil(L);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007889 lua_rawset(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007890
Christopher Faulet78c35472020-02-26 17:14:08 +01007891 if ((htxn->flags & HLUA_TXN_CTX_MASK) == HLUA_TXN_FLT_CTX) {
7892 /* HTTPMessage object are created when a lua TXN is created from
7893 * a filter context only
7894 */
7895
7896 /* Creates the HTTP-Request object is the current proxy allows http. */
7897 lua_pushstring(L, "http_req");
7898 if (p->mode == PR_MODE_HTTP) {
7899 if (!hlua_http_msg_new(L, &s->txn->req))
7900 return 0;
7901 }
7902 else
7903 lua_pushnil(L);
7904 lua_rawset(L, -3);
7905
7906 /* Creates the HTTP-Response object is the current proxy allows http. */
7907 lua_pushstring(L, "http_res");
7908 if (p->mode == PR_MODE_HTTP) {
7909 if (!hlua_http_msg_new(L, &s->txn->rsp))
7910 return 0;
7911 }
7912 else
7913 lua_pushnil(L);
7914 lua_rawset(L, -3);
7915 }
7916
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007917 /* Pop a class sesison metatable and affect it to the userdata. */
7918 lua_rawgeti(L, LUA_REGISTRYINDEX, class_txn_ref);
7919 lua_setmetatable(L, -2);
7920
7921 return 1;
7922}
7923
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01007924__LJMP static int hlua_txn_deflog(lua_State *L)
7925{
7926 const char *msg;
7927 struct hlua_txn *htxn;
7928
7929 MAY_LJMP(check_args(L, 2, "deflog"));
7930 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7931 msg = MAY_LJMP(luaL_checkstring(L, 2));
7932
7933 hlua_sendlog(htxn->s->be, htxn->s->logs.level, msg);
7934 return 0;
7935}
7936
7937__LJMP static int hlua_txn_log(lua_State *L)
7938{
7939 int level;
7940 const char *msg;
7941 struct hlua_txn *htxn;
7942
7943 MAY_LJMP(check_args(L, 3, "log"));
7944 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7945 level = MAY_LJMP(luaL_checkinteger(L, 2));
7946 msg = MAY_LJMP(luaL_checkstring(L, 3));
7947
7948 if (level < 0 || level >= NB_LOG_LEVELS)
7949 WILL_LJMP(luaL_argerror(L, 1, "Invalid loglevel."));
7950
7951 hlua_sendlog(htxn->s->be, level, msg);
7952 return 0;
7953}
7954
7955__LJMP static int hlua_txn_log_debug(lua_State *L)
7956{
7957 const char *msg;
7958 struct hlua_txn *htxn;
7959
7960 MAY_LJMP(check_args(L, 2, "Debug"));
7961 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7962 msg = MAY_LJMP(luaL_checkstring(L, 2));
7963 hlua_sendlog(htxn->s->be, LOG_DEBUG, msg);
7964 return 0;
7965}
7966
7967__LJMP static int hlua_txn_log_info(lua_State *L)
7968{
7969 const char *msg;
7970 struct hlua_txn *htxn;
7971
7972 MAY_LJMP(check_args(L, 2, "Info"));
7973 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7974 msg = MAY_LJMP(luaL_checkstring(L, 2));
7975 hlua_sendlog(htxn->s->be, LOG_INFO, msg);
7976 return 0;
7977}
7978
7979__LJMP static int hlua_txn_log_warning(lua_State *L)
7980{
7981 const char *msg;
7982 struct hlua_txn *htxn;
7983
7984 MAY_LJMP(check_args(L, 2, "Warning"));
7985 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7986 msg = MAY_LJMP(luaL_checkstring(L, 2));
7987 hlua_sendlog(htxn->s->be, LOG_WARNING, msg);
7988 return 0;
7989}
7990
7991__LJMP static int hlua_txn_log_alert(lua_State *L)
7992{
7993 const char *msg;
7994 struct hlua_txn *htxn;
7995
7996 MAY_LJMP(check_args(L, 2, "Alert"));
7997 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7998 msg = MAY_LJMP(luaL_checkstring(L, 2));
7999 hlua_sendlog(htxn->s->be, LOG_ALERT, msg);
8000 return 0;
8001}
8002
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01008003__LJMP static int hlua_txn_set_loglevel(lua_State *L)
8004{
8005 struct hlua_txn *htxn;
8006 int ll;
8007
8008 MAY_LJMP(check_args(L, 2, "set_loglevel"));
8009 htxn = MAY_LJMP(hlua_checktxn(L, 1));
8010 ll = MAY_LJMP(luaL_checkinteger(L, 2));
8011
8012 if (ll < 0 || ll > 7)
8013 WILL_LJMP(luaL_argerror(L, 2, "Bad log level. It must be between 0 and 7"));
8014
8015 htxn->s->logs.level = ll;
8016 return 0;
8017}
8018
8019__LJMP static int hlua_txn_set_tos(lua_State *L)
8020{
8021 struct hlua_txn *htxn;
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01008022 int tos;
8023
8024 MAY_LJMP(check_args(L, 2, "set_tos"));
8025 htxn = MAY_LJMP(hlua_checktxn(L, 1));
8026 tos = MAY_LJMP(luaL_checkinteger(L, 2));
8027
Willy Tarreau1a18b542018-12-11 16:37:42 +01008028 conn_set_tos(objt_conn(htxn->s->sess->origin), tos);
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01008029 return 0;
8030}
8031
8032__LJMP static int hlua_txn_set_mark(lua_State *L)
8033{
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01008034 struct hlua_txn *htxn;
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01008035 int mark;
8036
8037 MAY_LJMP(check_args(L, 2, "set_mark"));
8038 htxn = MAY_LJMP(hlua_checktxn(L, 1));
8039 mark = MAY_LJMP(luaL_checkinteger(L, 2));
8040
Lukas Tribus579e3e32019-08-11 18:03:45 +02008041 conn_set_mark(objt_conn(htxn->s->sess->origin), mark);
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01008042 return 0;
8043}
8044
Patrick Hemmer268a7072018-05-11 12:52:31 -04008045__LJMP static int hlua_txn_set_priority_class(lua_State *L)
8046{
8047 struct hlua_txn *htxn;
8048
8049 MAY_LJMP(check_args(L, 2, "set_priority_class"));
8050 htxn = MAY_LJMP(hlua_checktxn(L, 1));
8051 htxn->s->priority_class = queue_limit_class(MAY_LJMP(luaL_checkinteger(L, 2)));
8052 return 0;
8053}
8054
8055__LJMP static int hlua_txn_set_priority_offset(lua_State *L)
8056{
8057 struct hlua_txn *htxn;
8058
8059 MAY_LJMP(check_args(L, 2, "set_priority_offset"));
8060 htxn = MAY_LJMP(hlua_checktxn(L, 1));
8061 htxn->s->priority_offset = queue_limit_offset(MAY_LJMP(luaL_checkinteger(L, 2)));
8062 return 0;
8063}
8064
Christopher Faulet700d9e82020-01-31 12:21:52 +01008065/* Forward the Reply object to the client. This function converts the reply in
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05008066 * HTX an push it to into the response channel. It is response to forward the
Christopher Faulet700d9e82020-01-31 12:21:52 +01008067 * message and terminate the transaction. It returns 1 on success and 0 on
8068 * error. The Reply must be on top of the stack.
8069 */
8070__LJMP static int hlua_txn_forward_reply(lua_State *L, struct stream *s)
8071{
8072 struct htx *htx;
8073 struct htx_sl *sl;
8074 struct h1m h1m;
8075 const char *status, *reason, *body;
8076 size_t status_len, reason_len, body_len;
8077 int ret, code, flags;
8078
8079 code = 200;
8080 status = "200";
8081 status_len = 3;
8082 ret = lua_getfield(L, -1, "status");
8083 if (ret == LUA_TNUMBER) {
8084 code = lua_tointeger(L, -1);
8085 status = lua_tolstring(L, -1, &status_len);
8086 }
8087 lua_pop(L, 1);
8088
8089 reason = http_get_reason(code);
8090 reason_len = strlen(reason);
8091 ret = lua_getfield(L, -1, "reason");
8092 if (ret == LUA_TSTRING)
8093 reason = lua_tolstring(L, -1, &reason_len);
8094 lua_pop(L, 1);
8095
8096 body = NULL;
8097 body_len = 0;
8098 ret = lua_getfield(L, -1, "body");
8099 if (ret == LUA_TSTRING)
8100 body = lua_tolstring(L, -1, &body_len);
8101 lua_pop(L, 1);
8102
8103 /* Prepare the response before inserting the headers */
8104 h1m_init_res(&h1m);
8105 htx = htx_from_buf(&s->res.buf);
8106 channel_htx_truncate(&s->res, htx);
8107 if (s->txn->req.flags & HTTP_MSGF_VER_11) {
8108 flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11);
8109 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.1"),
8110 ist2(status, status_len), ist2(reason, reason_len));
8111 }
8112 else {
8113 flags = HTX_SL_F_IS_RESP;
8114 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.0"),
8115 ist2(status, status_len), ist2(reason, reason_len));
8116 }
8117 if (!sl)
8118 goto fail;
8119 sl->info.res.status = code;
8120
8121 /* Push in the stack the "headers" entry. */
8122 ret = lua_getfield(L, -1, "headers");
8123 if (ret != LUA_TTABLE)
8124 goto skip_headers;
8125
8126 lua_pushnil(L);
8127 while (lua_next(L, -2) != 0) {
8128 struct ist name, value;
8129 const char *n, *v;
8130 size_t nlen, vlen;
8131
8132 if (!lua_isstring(L, -2) || !lua_istable(L, -1)) {
8133 /* Skip element if the key is not a string or if the value is not a table */
8134 goto next_hdr;
8135 }
8136
8137 n = lua_tolstring(L, -2, &nlen);
8138 name = ist2(n, nlen);
8139 if (isteqi(name, ist("content-length"))) {
8140 /* Always skip content-length header. It will be added
8141 * later with the correct len
8142 */
8143 goto next_hdr;
8144 }
8145
8146 /* Loop on header's values */
8147 lua_pushnil(L);
8148 while (lua_next(L, -2)) {
8149 if (!lua_isstring(L, -1)) {
8150 /* Skip the value if it is not a string */
8151 goto next_value;
8152 }
8153
8154 v = lua_tolstring(L, -1, &vlen);
8155 value = ist2(v, vlen);
8156
8157 if (isteqi(name, ist("transfer-encoding")))
8158 h1_parse_xfer_enc_header(&h1m, value);
8159 if (!htx_add_header(htx, ist2(n, nlen), ist2(v, vlen)))
8160 goto fail;
8161
8162 next_value:
8163 lua_pop(L, 1);
8164 }
8165
8166 next_hdr:
8167 lua_pop(L, 1);
8168 }
8169 skip_headers:
8170 lua_pop(L, 1);
8171
8172 /* Update h1m flags: CLEN is set if CHNK is not present */
8173 if (!(h1m.flags & H1_MF_CHNK)) {
8174 const char *clen = ultoa(body_len);
8175
8176 h1m.flags |= H1_MF_CLEN;
8177 if (!htx_add_header(htx, ist("content-length"), ist(clen)))
8178 goto fail;
8179 }
8180 if (h1m.flags & (H1_MF_CLEN|H1_MF_CHNK))
8181 h1m.flags |= H1_MF_XFER_LEN;
8182
8183 /* Update HTX start-line flags */
8184 if (h1m.flags & H1_MF_XFER_ENC)
8185 flags |= HTX_SL_F_XFER_ENC;
8186 if (h1m.flags & H1_MF_XFER_LEN) {
8187 flags |= HTX_SL_F_XFER_LEN;
8188 if (h1m.flags & H1_MF_CHNK)
8189 flags |= HTX_SL_F_CHNK;
8190 else if (h1m.flags & H1_MF_CLEN)
8191 flags |= HTX_SL_F_CLEN;
8192 if (h1m.body_len == 0)
8193 flags |= HTX_SL_F_BODYLESS;
8194 }
8195 sl->flags |= flags;
8196
8197
8198 if (!htx_add_endof(htx, HTX_BLK_EOH) ||
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01008199 (body_len && !htx_add_data_atonce(htx, ist2(body, body_len))))
Christopher Faulet700d9e82020-01-31 12:21:52 +01008200 goto fail;
8201
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01008202 htx->flags |= HTX_FL_EOM;
8203
Christopher Faulet700d9e82020-01-31 12:21:52 +01008204 /* Now, forward the response and terminate the transaction */
8205 s->txn->status = code;
8206 htx_to_buf(htx, &s->res.buf);
8207 if (!http_forward_proxy_resp(s, 1))
8208 goto fail;
8209
8210 return 1;
8211
8212 fail:
8213 channel_htx_truncate(&s->res, htx);
8214 return 0;
8215}
8216
8217/* Terminate a transaction if called from a lua action. For TCP streams,
8218 * processing is just aborted. Nothing is returned to the client and all
8219 * arguments are ignored. For HTTP streams, if a reply is passed as argument, it
8220 * is forwarded to the client before terminating the transaction. On success,
8221 * the function exits with ACT_RET_DONE code. If an error occurred, it exits
8222 * with ACT_RET_ERR code. If this function is not called from a lua action, it
8223 * just exits without any processing.
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01008224 */
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02008225__LJMP static int hlua_txn_done(lua_State *L)
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01008226{
Willy Tarreaub2ccb562015-04-06 11:11:15 +02008227 struct hlua_txn *htxn;
Christopher Faulet700d9e82020-01-31 12:21:52 +01008228 struct stream *s;
8229 int finst;
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01008230
Willy Tarreaub2ccb562015-04-06 11:11:15 +02008231 htxn = MAY_LJMP(hlua_checktxn(L, 1));
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01008232
Christopher Faulet700d9e82020-01-31 12:21:52 +01008233 /* If the flags NOTERM is set, we cannot terminate the session, so we
8234 * just end the execution of the current lua code. */
8235 if (htxn->flags & HLUA_TXN_NOTERM)
Thierry FOURNIERab00df62016-07-14 11:42:37 +02008236 WILL_LJMP(hlua_done(L));
Thierry FOURNIERab00df62016-07-14 11:42:37 +02008237
Christopher Faulet700d9e82020-01-31 12:21:52 +01008238 s = htxn->s;
Christopher Fauletd8f0e072020-02-25 09:45:51 +01008239 if (!IS_HTX_STRM(htxn->s)) {
Christopher Faulet700d9e82020-01-31 12:21:52 +01008240 struct channel *req = &s->req;
8241 struct channel *res = &s->res;
Willy Tarreau81389672015-03-10 12:03:52 +01008242
Christopher Faulet700d9e82020-01-31 12:21:52 +01008243 channel_auto_read(req);
8244 channel_abort(req);
Christopher Faulet700d9e82020-01-31 12:21:52 +01008245 channel_erase(req);
8246
Christopher Faulet700d9e82020-01-31 12:21:52 +01008247 channel_auto_read(res);
8248 channel_auto_close(res);
Christopher Faulet12762f02023-04-13 15:40:10 +02008249 sc_schedule_abort(s->scb);
Christopher Faulet700d9e82020-01-31 12:21:52 +01008250
8251 finst = ((htxn->dir == SMP_OPT_DIR_REQ) ? SF_FINST_R : SF_FINST_D);
8252 goto done;
Christopher Fauletfe6a71b2019-07-26 16:40:24 +02008253 }
Thierry FOURNIER10ec2142015-08-24 17:23:45 +02008254
Christopher Faulet700d9e82020-01-31 12:21:52 +01008255 if (lua_gettop(L) == 1 || !lua_istable(L, 2)) {
8256 /* No reply or invalid reply */
8257 s->txn->status = 0;
8258 http_reply_and_close(s, 0, NULL);
8259 }
8260 else {
8261 /* Remove extra args to have the reply on top of the stack */
8262 if (lua_gettop(L) > 2)
8263 lua_pop(L, lua_gettop(L) - 2);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01008264
Christopher Faulet700d9e82020-01-31 12:21:52 +01008265 if (!hlua_txn_forward_reply(L, s)) {
8266 if (!(s->flags & SF_ERR_MASK))
8267 s->flags |= SF_ERR_PRXCOND;
8268 lua_pushinteger(L, ACT_RET_ERR);
8269 WILL_LJMP(hlua_done(L));
8270 return 0; /* Never reached */
8271 }
Christopher Faulet4d0e2632019-07-16 10:52:40 +02008272 }
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02008273
Christopher Faulet700d9e82020-01-31 12:21:52 +01008274 finst = ((htxn->dir == SMP_OPT_DIR_REQ) ? SF_FINST_R : SF_FINST_H);
8275 if (htxn->dir == SMP_OPT_DIR_REQ) {
8276 /* let's log the request time */
8277 s->logs.tv_request = now;
8278 if (s->sess->fe == s->be) /* report it if the request was intercepted by the frontend */
Willy Tarreau4781b152021-04-06 13:53:36 +02008279 _HA_ATOMIC_INC(&s->sess->fe->fe_counters.intercepted_req);
Christopher Faulet700d9e82020-01-31 12:21:52 +01008280 }
Christopher Fauletfe6a71b2019-07-26 16:40:24 +02008281
Christopher Faulet700d9e82020-01-31 12:21:52 +01008282 done:
8283 if (!(s->flags & SF_ERR_MASK))
8284 s->flags |= SF_ERR_LOCAL;
8285 if (!(s->flags & SF_FINST_MASK))
8286 s->flags |= finst;
Christopher Fauletfe6a71b2019-07-26 16:40:24 +02008287
Christopher Faulete48d1dc2021-08-13 14:11:17 +02008288 if ((htxn->flags & HLUA_TXN_CTX_MASK) == HLUA_TXN_FLT_CTX)
8289 lua_pushinteger(L, -1);
8290 else
8291 lua_pushinteger(L, ACT_RET_ABRT);
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02008292 WILL_LJMP(hlua_done(L));
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01008293 return 0;
8294}
8295
Christopher Faulet700d9e82020-01-31 12:21:52 +01008296/*
8297 *
8298 *
8299 * Class REPLY
8300 *
8301 *
8302 */
8303
8304/* Pushes the TXN reply onto the top of the stack. If the stask does not have a
8305 * free slots, the function fails and returns 0;
8306 */
8307static int hlua_txn_reply_new(lua_State *L)
8308{
8309 struct hlua_txn *htxn;
8310 const char *reason, *body = NULL;
8311 int ret, status;
8312
8313 htxn = MAY_LJMP(hlua_checktxn(L, 1));
Christopher Fauletd8f0e072020-02-25 09:45:51 +01008314 if (!IS_HTX_STRM(htxn->s)) {
Christopher Faulet700d9e82020-01-31 12:21:52 +01008315 hlua_pusherror(L, "txn object is not an HTTP transaction.");
8316 WILL_LJMP(lua_error(L));
8317 }
8318
8319 /* Default value */
8320 status = 200;
8321 reason = http_get_reason(status);
8322
8323 if (lua_istable(L, 2)) {
8324 /* load status and reason from the table argument at index 2 */
8325 ret = lua_getfield(L, 2, "status");
8326 if (ret == LUA_TNIL)
8327 goto reason;
8328 else if (ret != LUA_TNUMBER) {
8329 /* invalid status: ignore the reason */
8330 goto body;
8331 }
8332 status = lua_tointeger(L, -1);
8333
8334 reason:
8335 lua_pop(L, 1); /* restore the stack: remove status */
8336 ret = lua_getfield(L, 2, "reason");
8337 if (ret == LUA_TSTRING)
8338 reason = lua_tostring(L, -1);
8339
8340 body:
8341 lua_pop(L, 1); /* restore the stack: remove invalid status or reason */
8342 ret = lua_getfield(L, 2, "body");
8343 if (ret == LUA_TSTRING)
8344 body = lua_tostring(L, -1);
8345 lua_pop(L, 1); /* restore the stack: remove body */
8346 }
8347
8348 /* Create the Reply table */
8349 lua_newtable(L);
8350
8351 /* Add status element */
8352 lua_pushstring(L, "status");
8353 lua_pushinteger(L, status);
8354 lua_settable(L, -3);
8355
8356 /* Add reason element */
8357 reason = http_get_reason(status);
8358 lua_pushstring(L, "reason");
8359 lua_pushstring(L, reason);
8360 lua_settable(L, -3);
8361
8362 /* Add body element, nil if undefined */
8363 lua_pushstring(L, "body");
8364 if (body)
8365 lua_pushstring(L, body);
8366 else
8367 lua_pushnil(L);
8368 lua_settable(L, -3);
8369
8370 /* Add headers element */
8371 lua_pushstring(L, "headers");
8372 lua_newtable(L);
8373
8374 /* stack: [ txn, <Arg:table>, <Reply:table>, "headers", <headers:table> ] */
8375 if (lua_istable(L, 2)) {
8376 /* load headers from the table argument at index 2. If it is a table, copy it. */
8377 ret = lua_getfield(L, 2, "headers");
8378 if (ret == LUA_TTABLE) {
8379 /* stack: [ ... <headers:table>, <table> ] */
8380 lua_pushnil(L);
8381 while (lua_next(L, -2) != 0) {
8382 /* stack: [ ... <headers:table>, <table>, k, v] */
8383 if (!lua_isstring(L, -1) && !lua_istable(L, -1)) {
8384 /* invalid value type, skip it */
8385 lua_pop(L, 1);
8386 continue;
8387 }
8388
8389
8390 /* Duplicate the key and swap it with the value. */
8391 lua_pushvalue(L, -2);
8392 lua_insert(L, -2);
8393 /* stack: [ ... <headers:table>, <table>, k, k, v ] */
8394
8395 lua_newtable(L);
8396 lua_insert(L, -2);
8397 /* stack: [ ... <headers:table>, <table>, k, k, <inner:table>, v ] */
8398
8399 if (lua_isstring(L, -1)) {
8400 /* push the value in the inner table */
8401 lua_rawseti(L, -2, 1);
8402 }
8403 else { /* table */
8404 lua_pushnil(L);
8405 while (lua_next(L, -2) != 0) {
8406 /* stack: [ ... <headers:table>, <table>, k, k, <inner:table>, <v:table>, k2, v2 ] */
8407 if (!lua_isstring(L, -1)) {
8408 /* invalid value type, skip it*/
8409 lua_pop(L, 1);
8410 continue;
8411 }
8412 /* push the value in the inner table */
8413 lua_rawseti(L, -4, lua_rawlen(L, -4) + 1);
8414 /* stack: [ ... <headers:table>, <table>, k, k, <inner:table>, <v:table>, k2 ] */
8415 }
8416 lua_pop(L, 1);
8417 /* stack: [ ... <headers:table>, <table>, k, k, <inner:table> ] */
8418 }
8419
8420 /* push (k,v) on the stack in the headers table:
8421 * stack: [ ... <headers:table>, <table>, k, k, v ]
8422 */
8423 lua_settable(L, -5);
8424 /* stack: [ ... <headers:table>, <table>, k ] */
8425 }
8426 }
8427 lua_pop(L, 1);
8428 }
8429 /* stack: [ txn, <Arg:table>, <Reply:table>, "headers", <headers:table> ] */
8430 lua_settable(L, -3);
8431 /* stack: [ txn, <Arg:table>, <Reply:table> ] */
8432
8433 /* Pop a class sesison metatable and affect it to the userdata. */
8434 lua_rawgeti(L, LUA_REGISTRYINDEX, class_txn_reply_ref);
8435 lua_setmetatable(L, -2);
8436 return 1;
8437}
8438
8439/* Set the reply status code, and optionally the reason. If no reason is
8440 * provided, the default one corresponding to the status code is used.
8441 */
8442__LJMP static int hlua_txn_reply_set_status(lua_State *L)
8443{
8444 int status = MAY_LJMP(luaL_checkinteger(L, 2));
8445 const char *reason = MAY_LJMP(luaL_optlstring(L, 3, NULL, NULL));
8446
8447 /* First argument (self) must be a table */
Aurelien DARRAGONd83d0452022-10-05 11:46:45 +02008448 MAY_LJMP(luaL_checktype(L, 1, LUA_TTABLE));
Christopher Faulet700d9e82020-01-31 12:21:52 +01008449
8450 if (status < 100 || status > 599) {
8451 lua_pushboolean(L, 0);
8452 return 1;
8453 }
8454 if (!reason)
8455 reason = http_get_reason(status);
8456
8457 lua_pushinteger(L, status);
8458 lua_setfield(L, 1, "status");
8459
8460 lua_pushstring(L, reason);
8461 lua_setfield(L, 1, "reason");
8462
8463 lua_pushboolean(L, 1);
8464 return 1;
8465}
8466
8467/* Add a header into the reply object. Each header name is associated to an
8468 * array of values in the "headers" table. If the header name is not found, a
8469 * new entry is created.
8470 */
8471__LJMP static int hlua_txn_reply_add_header(lua_State *L)
8472{
8473 const char *name = MAY_LJMP(luaL_checkstring(L, 2));
8474 const char *value = MAY_LJMP(luaL_checkstring(L, 3));
8475 int ret;
8476
8477 /* First argument (self) must be a table */
Aurelien DARRAGONd83d0452022-10-05 11:46:45 +02008478 MAY_LJMP(luaL_checktype(L, 1, LUA_TTABLE));
Christopher Faulet700d9e82020-01-31 12:21:52 +01008479
8480 /* Push in the stack the "headers" entry. */
8481 ret = lua_getfield(L, 1, "headers");
8482 if (ret != LUA_TTABLE) {
8483 hlua_pusherror(L, "Reply['headers'] is expected to a an array. %s found", lua_typename(L, ret));
8484 WILL_LJMP(lua_error(L));
8485 }
8486
8487 /* check if the header is already registered. If not, register it. */
8488 ret = lua_getfield(L, -1, name);
8489 if (ret == LUA_TNIL) {
8490 /* Entry not found. */
8491 lua_pop(L, 1); /* remove the nil. The "headers" table is the top of the stack. */
8492
8493 /* Insert the new header name in the array in the top of the stack.
8494 * It left the new array in the top of the stack.
8495 */
8496 lua_newtable(L);
8497 lua_pushstring(L, name);
8498 lua_pushvalue(L, -2);
8499 lua_settable(L, -4);
8500 }
8501 else if (ret != LUA_TTABLE) {
8502 hlua_pusherror(L, "Reply['headers']['%s'] is expected to be an array. %s found", name, lua_typename(L, ret));
8503 WILL_LJMP(lua_error(L));
8504 }
8505
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -07008506 /* Now the top of thestack is an array of values. We push
Christopher Faulet700d9e82020-01-31 12:21:52 +01008507 * the header value as new entry.
8508 */
8509 lua_pushstring(L, value);
8510 ret = lua_rawlen(L, -2);
8511 lua_rawseti(L, -2, ret + 1);
8512
8513 lua_pushboolean(L, 1);
8514 return 1;
8515}
8516
8517/* Remove all occurrences of a given header name. */
8518__LJMP static int hlua_txn_reply_del_header(lua_State *L)
8519{
8520 const char *name = MAY_LJMP(luaL_checkstring(L, 2));
8521 int ret;
8522
8523 /* First argument (self) must be a table */
Aurelien DARRAGONd83d0452022-10-05 11:46:45 +02008524 MAY_LJMP(luaL_checktype(L, 1, LUA_TTABLE));
Christopher Faulet700d9e82020-01-31 12:21:52 +01008525
8526 /* Push in the stack the "headers" entry. */
8527 ret = lua_getfield(L, 1, "headers");
8528 if (ret != LUA_TTABLE) {
8529 hlua_pusherror(L, "Reply['headers'] is expected to be an array. %s found", lua_typename(L, ret));
8530 WILL_LJMP(lua_error(L));
8531 }
8532
8533 lua_pushstring(L, name);
8534 lua_pushnil(L);
8535 lua_settable(L, -3);
8536
8537 lua_pushboolean(L, 1);
8538 return 1;
8539}
8540
8541/* Set the reply's body. Overwrite any existing entry. */
8542__LJMP static int hlua_txn_reply_set_body(lua_State *L)
8543{
8544 const char *payload = MAY_LJMP(luaL_checkstring(L, 2));
8545
8546 /* First argument (self) must be a table */
Aurelien DARRAGONd83d0452022-10-05 11:46:45 +02008547 MAY_LJMP(luaL_checktype(L, 1, LUA_TTABLE));
Christopher Faulet700d9e82020-01-31 12:21:52 +01008548
8549 lua_pushstring(L, payload);
8550 lua_setfield(L, 1, "body");
8551
8552 lua_pushboolean(L, 1);
8553 return 1;
8554}
8555
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01008556__LJMP static int hlua_log(lua_State *L)
8557{
8558 int level;
8559 const char *msg;
8560
8561 MAY_LJMP(check_args(L, 2, "log"));
8562 level = MAY_LJMP(luaL_checkinteger(L, 1));
8563 msg = MAY_LJMP(luaL_checkstring(L, 2));
8564
8565 if (level < 0 || level >= NB_LOG_LEVELS)
8566 WILL_LJMP(luaL_argerror(L, 1, "Invalid loglevel."));
8567
8568 hlua_sendlog(NULL, level, msg);
8569 return 0;
8570}
8571
8572__LJMP static int hlua_log_debug(lua_State *L)
8573{
8574 const char *msg;
8575
8576 MAY_LJMP(check_args(L, 1, "debug"));
8577 msg = MAY_LJMP(luaL_checkstring(L, 1));
8578 hlua_sendlog(NULL, LOG_DEBUG, msg);
8579 return 0;
8580}
8581
8582__LJMP static int hlua_log_info(lua_State *L)
8583{
8584 const char *msg;
8585
8586 MAY_LJMP(check_args(L, 1, "info"));
8587 msg = MAY_LJMP(luaL_checkstring(L, 1));
8588 hlua_sendlog(NULL, LOG_INFO, msg);
8589 return 0;
8590}
8591
8592__LJMP static int hlua_log_warning(lua_State *L)
8593{
8594 const char *msg;
8595
8596 MAY_LJMP(check_args(L, 1, "warning"));
8597 msg = MAY_LJMP(luaL_checkstring(L, 1));
8598 hlua_sendlog(NULL, LOG_WARNING, msg);
8599 return 0;
8600}
8601
8602__LJMP static int hlua_log_alert(lua_State *L)
8603{
8604 const char *msg;
8605
8606 MAY_LJMP(check_args(L, 1, "alert"));
8607 msg = MAY_LJMP(luaL_checkstring(L, 1));
8608 hlua_sendlog(NULL, LOG_ALERT, msg);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01008609 return 0;
8610}
8611
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01008612__LJMP static int hlua_sleep_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008613{
8614 int wakeup_ms = lua_tointeger(L, -1);
Willy Tarreau12c02702021-09-30 16:12:31 +02008615 if (!tick_is_expired(wakeup_ms, now_ms))
Willy Tarreau9635e032018-10-16 17:52:55 +02008616 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008617 return 0;
8618}
8619
8620__LJMP static int hlua_sleep(lua_State *L)
8621{
8622 unsigned int delay;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008623 unsigned int wakeup_ms;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008624
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008625 MAY_LJMP(check_args(L, 1, "sleep"));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008626
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01008627 delay = MAY_LJMP(luaL_checkinteger(L, 1)) * 1000;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008628 wakeup_ms = tick_add(now_ms, delay);
8629 lua_pushinteger(L, wakeup_ms);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008630
Willy Tarreau9635e032018-10-16 17:52:55 +02008631 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008632 return 0;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008633}
8634
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008635__LJMP static int hlua_msleep(lua_State *L)
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008636{
8637 unsigned int delay;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008638 unsigned int wakeup_ms;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008639
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008640 MAY_LJMP(check_args(L, 1, "msleep"));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008641
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01008642 delay = MAY_LJMP(luaL_checkinteger(L, 1));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008643 wakeup_ms = tick_add(now_ms, delay);
8644 lua_pushinteger(L, wakeup_ms);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008645
Willy Tarreau9635e032018-10-16 17:52:55 +02008646 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008647 return 0;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008648}
8649
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01008650/* This functionis an LUA binding. it permits to give back
8651 * the hand at the HAProxy scheduler. It is used when the
8652 * LUA processing consumes a lot of time.
8653 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01008654__LJMP static int hlua_yield_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008655{
8656 return 0;
8657}
8658
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01008659__LJMP static int hlua_yield(lua_State *L)
8660{
Willy Tarreau9635e032018-10-16 17:52:55 +02008661 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_yield_yield, TICK_ETERNITY, HLUA_CTRLYIELD));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008662 return 0;
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01008663}
8664
Thierry FOURNIER37196f42015-02-16 19:34:56 +01008665/* This function change the nice of the currently executed
8666 * task. It is used set low or high priority at the current
8667 * task.
8668 */
Willy Tarreau59551662015-03-10 14:23:13 +01008669__LJMP static int hlua_set_nice(lua_State *L)
Thierry FOURNIER37196f42015-02-16 19:34:56 +01008670{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01008671 struct hlua *hlua;
8672 int nice;
Thierry FOURNIER37196f42015-02-16 19:34:56 +01008673
Willy Tarreau80f5fae2015-02-27 16:38:20 +01008674 MAY_LJMP(check_args(L, 1, "set_nice"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01008675 nice = MAY_LJMP(luaL_checkinteger(L, 1));
Thierry FOURNIER37196f42015-02-16 19:34:56 +01008676
Thierry Fournier4234dbd2020-11-28 13:18:23 +01008677 /* Get hlua struct, or NULL if we execute from main lua state */
8678 hlua = hlua_gethlua(L);
8679
8680 /* If the task is not set, I'm in a start mode. */
Thierry FOURNIER37196f42015-02-16 19:34:56 +01008681 if (!hlua || !hlua->task)
8682 return 0;
8683
8684 if (nice < -1024)
8685 nice = -1024;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01008686 else if (nice > 1024)
Thierry FOURNIER37196f42015-02-16 19:34:56 +01008687 nice = 1024;
8688
8689 hlua->task->nice = nice;
8690 return 0;
8691}
8692
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08008693/* This function is used as a callback of a task. It is called by the
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008694 * HAProxy task subsystem when the task is awaked. The LUA runtime can
8695 * return an E_AGAIN signal, the emmiter of this signal must set a
8696 * signal to wake the task.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008697 *
8698 * Task wrapper are longjmp safe because the only one Lua code
8699 * executed is the safe hlua_ctx_resume();
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008700 */
Willy Tarreau144f84a2021-03-02 16:09:26 +01008701struct task *hlua_process_task(struct task *task, void *context, unsigned int state)
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008702{
Olivier Houchard9f6af332018-05-25 14:04:04 +02008703 struct hlua *hlua = context;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008704 enum hlua_exec status;
8705
Willy Tarreau6ef52f42022-06-15 14:19:48 +02008706 if (task->tid < 0)
8707 task->tid = tid;
8708
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008709 /* If it is the first call to the task, we must initialize the
8710 * execution timeouts.
8711 */
8712 if (!HLUA_IS_RUNNING(hlua))
Aurelien DARRAGONda9503c2022-11-25 09:10:07 +01008713 hlua_timer_init(&hlua->timer, hlua_timeout_task);
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008714
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008715 /* Execute the Lua code. */
8716 status = hlua_ctx_resume(hlua, 1);
8717
8718 switch (status) {
8719 /* finished or yield */
8720 case HLUA_E_OK:
8721 hlua_ctx_destroy(hlua);
Olivier Houchard3f795f72019-04-17 22:51:06 +02008722 task_destroy(task);
Tim Duesterhuscd235c62018-04-24 13:56:01 +02008723 task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008724 break;
8725
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01008726 case HLUA_E_AGAIN: /* co process or timeout wake me later. */
Thierry FOURNIERcb146882017-12-10 17:10:57 +01008727 notification_gc(&hlua->com);
PiBa-NLfe971b32018-05-02 22:27:14 +02008728 task->expire = hlua->wake_time;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008729 break;
8730
8731 /* finished with error. */
Aurelien DARRAGON79544102022-11-24 14:27:15 +01008732 case HLUA_E_ETMOUT:
8733 SEND_ERR(NULL, "Lua task: execution timeout.\n");
8734 goto err_task_abort;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008735 case HLUA_E_ERRMSG:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008736 SEND_ERR(NULL, "Lua task: %s.\n", lua_tostring(hlua->T, -1));
Aurelien DARRAGON79544102022-11-24 14:27:15 +01008737 goto err_task_abort;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008738 case HLUA_E_ERR:
8739 default:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008740 SEND_ERR(NULL, "Lua task: unknown error.\n");
Aurelien DARRAGON79544102022-11-24 14:27:15 +01008741 err_task_abort:
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008742 hlua_ctx_destroy(hlua);
Olivier Houchard3f795f72019-04-17 22:51:06 +02008743 task_destroy(task);
Emeric Brun253e53e2017-10-17 18:58:40 +02008744 task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008745 break;
8746 }
Emeric Brun253e53e2017-10-17 18:58:40 +02008747 return task;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008748}
8749
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008750/* This function is an LUA binding that register LUA function to be
8751 * executed after the HAProxy configuration parsing and before the
8752 * HAProxy scheduler starts. This function expect only one LUA
8753 * argument that is a function. This function returns nothing, but
8754 * throws if an error is encountered.
8755 */
8756__LJMP static int hlua_register_init(lua_State *L)
8757{
8758 struct hlua_init_function *init;
8759 int ref;
8760
8761 MAY_LJMP(check_args(L, 1, "register_init"));
8762
Aurelien DARRAGON87f52972023-02-24 09:43:54 +01008763 if (hlua_gethlua(L)) {
8764 /* runtime processing */
8765 WILL_LJMP(luaL_error(L, "register_init: not available outside of body context"));
8766 }
8767
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008768 ref = MAY_LJMP(hlua_checkfunction(L, 1));
8769
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02008770 init = calloc(1, sizeof(*init));
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +01008771 if (!init) {
8772 hlua_unref(L, ref);
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01008773 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +01008774 }
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008775
8776 init->function_ref = ref;
Willy Tarreau2b718102021-04-21 07:32:39 +02008777 LIST_APPEND(&hlua_init_functions[hlua_state_id], &init->l);
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008778 return 0;
8779}
8780
Ilya Shipitsin6f86eaa2022-11-30 16:22:42 +05008781/* This function is an LUA binding. It permits to register a task
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008782 * executed in parallel of the main HAroxy activity. The task is
8783 * created and it is set in the HAProxy scheduler. It can be called
8784 * from the "init" section, "post init" or during the runtime.
8785 *
8786 * Lua prototype:
8787 *
Aurelien DARRAGONb8038992023-03-09 16:48:30 +01008788 * <none> core.register_task(<function>[, <arg1>[, <arg2>[, ...[, <arg4>]]]])
8789 *
8790 * <arg1..4> are optional arguments that will be provided to <function>
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008791 */
8792static int hlua_register_task(lua_State *L)
8793{
Christopher Faulet5294ec02021-04-12 12:24:47 +02008794 struct hlua *hlua = NULL;
8795 struct task *task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008796 int ref;
Aurelien DARRAGONb8038992023-03-09 16:48:30 +01008797 int nb_arg;
8798 int it;
8799 int arg_ref[4]; /* optional arguments */
Thierry Fournier021d9862020-11-28 23:42:03 +01008800 int state_id;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008801
Aurelien DARRAGONb8038992023-03-09 16:48:30 +01008802 nb_arg = lua_gettop(L);
8803 if (nb_arg < 1)
8804 WILL_LJMP(luaL_error(L, "register_task: <func> argument is required"));
8805 else if (nb_arg > 5)
8806 WILL_LJMP(luaL_error(L, "register_task: no more that 4 optional arguments may be provided"));
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008807
Aurelien DARRAGONb8038992023-03-09 16:48:30 +01008808 /* first arg: function ref */
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008809 ref = MAY_LJMP(hlua_checkfunction(L, 1));
8810
Aurelien DARRAGONb8038992023-03-09 16:48:30 +01008811 /* extract optional args (if any) */
8812 it = 0;
8813 while (--nb_arg) {
8814 lua_pushvalue(L, 2 + it);
8815 arg_ref[it] = hlua_ref(L); /* get arg reference */
8816 it += 1;
8817 }
8818 nb_arg = it;
8819
Thierry Fournier75fc0292020-11-28 13:18:56 +01008820 /* Get the reference state. If the reference is NULL, L is the master
8821 * state, otherwise hlua->T is.
8822 */
8823 hlua = hlua_gethlua(L);
8824 if (hlua)
Thierry Fournier021d9862020-11-28 23:42:03 +01008825 /* we are in runtime processing */
8826 state_id = hlua->state_id;
Thierry Fournier75fc0292020-11-28 13:18:56 +01008827 else
Thierry Fournier021d9862020-11-28 23:42:03 +01008828 /* we are in initialization mode */
Thierry Fournierc7492592020-11-28 23:57:24 +01008829 state_id = hlua_state_id;
Thierry Fournier75fc0292020-11-28 13:18:56 +01008830
Willy Tarreaubafbe012017-11-24 17:34:44 +01008831 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008832 if (!hlua)
Christopher Faulet5294ec02021-04-12 12:24:47 +02008833 goto alloc_error;
Christopher Faulet1e8433f2021-03-24 15:03:01 +01008834 HLUA_INIT(hlua);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008835
Thierry Fournier59f11be2020-11-29 00:37:41 +01008836 /* We are in the common lua state, execute the task anywhere,
8837 * otherwise, inherit the current thread identifier
8838 */
8839 if (state_id == 0)
Willy Tarreaubeeabf52021-10-01 18:23:30 +02008840 task = task_new_anywhere();
Thierry Fournier59f11be2020-11-29 00:37:41 +01008841 else
Willy Tarreaubeeabf52021-10-01 18:23:30 +02008842 task = task_new_here();
Willy Tarreaue09101e2018-10-16 17:37:12 +02008843 if (!task)
Christopher Faulet5294ec02021-04-12 12:24:47 +02008844 goto alloc_error;
Willy Tarreaue09101e2018-10-16 17:37:12 +02008845
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008846 task->context = hlua;
8847 task->process = hlua_process_task;
8848
Aurelien DARRAGON6b0b9bd2023-03-21 14:02:16 +01008849 if (!hlua_ctx_init(hlua, state_id, task))
Christopher Faulet5294ec02021-04-12 12:24:47 +02008850 goto alloc_error;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008851
Aurelien DARRAGONb8038992023-03-09 16:48:30 +01008852 /* Ensure there is enough space on the stack for the function
8853 * plus optional arguments
8854 */
8855 if (!lua_checkstack(hlua->T, (1 + nb_arg)))
8856 goto alloc_error;
8857
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008858 /* Restore the function in the stack. */
Aurelien DARRAGON4fdf8b52023-03-20 17:22:37 +01008859 hlua_pushref(hlua->T, ref);
Aurelien DARRAGONbe58d662023-03-13 14:09:21 +01008860 /* function ref not needed anymore since it was pushed to the substack */
8861 hlua_unref(L, ref);
8862
Aurelien DARRAGONb8038992023-03-09 16:48:30 +01008863 hlua->nargs = nb_arg;
8864
8865 /* push optional arguments to the function */
8866 for (it = 0; it < nb_arg; it++) {
8867 /* push arg to the stack */
8868 hlua_pushref(hlua->T, arg_ref[it]);
8869 /* arg ref not needed anymore since it was pushed to the substack */
8870 hlua_unref(L, arg_ref[it]);
8871 }
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008872
8873 /* Schedule task. */
Willy Tarreaue3957f82021-09-30 16:17:37 +02008874 task_wakeup(task, TASK_WOKEN_INIT);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008875
8876 return 0;
Christopher Faulet5294ec02021-04-12 12:24:47 +02008877
8878 alloc_error:
8879 task_destroy(task);
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +01008880 hlua_unref(L, ref);
Aurelien DARRAGONb8038992023-03-09 16:48:30 +01008881 for (it = 0; it < nb_arg; it++) {
8882 hlua_unref(L, arg_ref[it]);
8883 }
Christopher Faulet5294ec02021-04-12 12:24:47 +02008884 hlua_ctx_destroy(hlua);
8885 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
8886 return 0; /* Never reached */
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008887}
8888
Aurelien DARRAGONc84899c2023-02-20 18:18:59 +01008889/* called from unsafe location */
8890static void hlua_event_subscription_destroy(struct hlua_event_sub *hlua_sub)
8891{
8892 /* hlua cleanup */
8893
8894 hlua_lock(hlua_sub->hlua);
8895 /* registry is shared between coroutines */
8896 hlua_unref(hlua_sub->hlua->T, hlua_sub->fcn_ref);
8897 hlua_unlock(hlua_sub->hlua);
8898
8899 hlua_ctx_destroy(hlua_sub->hlua);
8900
8901 /* free */
8902 pool_free(pool_head_hlua_event_sub, hlua_sub);
8903}
8904
8905/* single event handler: hlua ctx is shared between multiple events handlers
8906 * issued from the same subscription. Thus, it is not destroyed when the event
8907 * is processed: it is destroyed when no more events are expected for the
8908 * subscription (ie: when the subscription ends).
8909 *
8910 * Moreover, events are processed sequentially within the subscription:
8911 * one event must be fully processed before another one may be processed.
8912 * This ensures proper consistency for lua event handling from an ordering
8913 * point of view. This is especially useful with server events for example
8914 * where ADD/DEL/UP/DOWN events ordering really matters to trigger specific
8915 * actions from lua (e.g.: sending emails or making API calls).
8916 *
8917 * Due to this design, each lua event handler is pleased to process the event
8918 * as fast as possible to prevent the event queue from growing up.
8919 * Strictly speaking, there is no runtime limit for the callback function
8920 * (timeout set to default task timeout), but if the event queue goes past
8921 * the limit of unconsumed events an error will be reported and the
8922 * susbscription will pause itself for as long as it takes for the handler to
8923 * catch up (events will be lost as a result).
8924 * If the event handler does not need the sequential ordering and wants to
8925 * process multiple events at a time, it may spawn a new side-task using
8926 * 'core.register_task' to delegate the event handling and make parallel event
8927 * processing within the same subscription set.
8928 */
8929static void hlua_event_handler(struct hlua *hlua)
8930{
8931 enum hlua_exec status;
8932
8933 /* If it is the first call to the task, we must initialize the
8934 * execution timeouts.
8935 */
Aurelien DARRAGONda9503c2022-11-25 09:10:07 +01008936 if (!HLUA_IS_RUNNING(hlua))
8937 hlua_timer_init(&hlua->timer, hlua_timeout_task);
Aurelien DARRAGONc84899c2023-02-20 18:18:59 +01008938
8939 /* make sure to reset the task expiry before each hlua_ctx_resume()
8940 * since the task is re-used for multiple cb function calls
8941 * We couldn't risk to have t->expire pointing to a past date because
8942 * it was set during last function invocation but was never reset since
8943 * (ie: E_AGAIN)
8944 */
8945 hlua->task->expire = TICK_ETERNITY;
8946
8947 /* Execute the Lua code. */
8948 status = hlua_ctx_resume(hlua, 1);
8949
8950 switch (status) {
8951 /* finished or yield */
8952 case HLUA_E_OK:
8953 break;
8954
8955 case HLUA_E_AGAIN: /* co process or timeout wake me later. */
8956 notification_gc(&hlua->com);
8957 hlua->task->expire = hlua->wake_time;
8958 break;
8959
8960 /* finished with error. */
8961 case HLUA_E_ETMOUT:
8962 SEND_ERR(NULL, "Lua event_hdl: execution timeout.\n");
8963 break;
8964
8965 case HLUA_E_ERRMSG:
8966 SEND_ERR(NULL, "Lua event_hdl: %s.\n", lua_tostring(hlua->T, -1));
8967 break;
8968
8969 case HLUA_E_ERR:
8970 default:
8971 SEND_ERR(NULL, "Lua event_hdl: unknown error.\n");
8972 break;
8973 }
8974}
8975
8976__LJMP static int hlua_event_hdl_cb_data_push_args(struct hlua_event_sub *hlua_sub,
8977 struct event_hdl_sub_type event, void *data)
8978{
8979 struct hlua *hlua = hlua_sub->hlua;
8980
8981 hlua->nargs = 1;
8982 lua_pushstring(hlua->T, event_hdl_sub_type_to_string(event));
8983 if (event_hdl_sub_family_equal(EVENT_HDL_SUB_SERVER, event)) {
8984 struct event_hdl_cb_data_server *e_server = data;
8985 struct proxy *px;
8986 struct server *server;
8987
8988 hlua->nargs += 1;
8989 lua_newtable(hlua->T);
8990 /* Add server name */
8991 lua_pushstring(hlua->T, "name");
8992 lua_pushstring(hlua->T, e_server->safe.name);
8993 lua_settable(hlua->T, -3);
8994 /* Add server puid */
8995 lua_pushstring(hlua->T, "puid");
8996 lua_pushinteger(hlua->T, e_server->safe.puid);
8997 lua_settable(hlua->T, -3);
8998 /* Add server rid */
8999 lua_pushstring(hlua->T, "rid");
9000 lua_pushinteger(hlua->T, e_server->safe.rid);
9001 lua_settable(hlua->T, -3);
9002 /* Add server proxy name */
9003 lua_pushstring(hlua->T, "proxy_name");
9004 lua_pushstring(hlua->T, e_server->safe.proxy_name);
9005 lua_settable(hlua->T, -3);
9006
9007 /* attempt to provide reference server object
9008 * (if it wasn't removed yet, SERVER_DEL will never succeed here)
9009 */
9010 px = proxy_find_by_name(e_server->safe.proxy_name, PR_CAP_BE, 0);
9011 BUG_ON(!px);
9012 server = findserver_unique_id(px, e_server->safe.puid, e_server->safe.rid);
9013 if (server) {
9014 lua_pushstring(hlua->T, "reference");
9015 hlua_fcn_new_server(hlua->T, server);
9016 lua_settable(hlua->T, -3);
9017 }
9018 }
9019 /* sub mgmt */
9020 hlua->nargs += 1;
9021 hlua_fcn_new_event_sub(hlua->T, hlua_sub->sub);
9022
9023 return 1;
9024}
9025
9026/* events runner: if there's an ongoing hlua event handling process, finish it
9027 * then, check if there are new events waiting to be processed
9028 * (events are processed sequentially)
9029 *
9030 * We have a safety measure to warn/guard if the event queue is growing up
9031 * too much due to many events being generated and lua handler is unable to
9032 * keep up the pace (e.g.: when the event queue grows past 100 unconsumed events).
9033 * TODO: make it tunable
9034 */
9035static struct task *hlua_event_runner(struct task *task, void *context, unsigned int state)
9036{
9037 struct hlua_event_sub *hlua_sub = context;
9038 struct event_hdl_async_event *event;
9039 const char *error = NULL;
9040
9041 if (!hlua_sub->paused && event_hdl_async_equeue_size(&hlua_sub->equeue) > 100) {
9042 const char *trace;
9043
9044 /* We reached the limit of pending events in the queue: we should
9045 * warn the user, and temporarily pause the subscription to give a chance
9046 * to the handler to catch up? (it also prevents ressource shortage since
9047 * the queue could grow indefinitely otherwise)
9048 * TODO: find a way to inform the handler that it missed some events
9049 * (example: stats within the subscription in event_hdl api exposed via lua api?)
9050 *
9051 * Nonetheless, reaching this limit means that the handler is not fast enough
9052 * and/or that it subscribed to events that happen too frequently and did not
9053 * expect it. This could come from an inadequate design in the user's script.
9054 */
9055 event_hdl_pause(hlua_sub->sub);
9056 hlua_sub->paused = 1;
9057
9058 /* The following Lua calls can fail. */
9059 if (!SET_SAFE_LJMP(hlua_sub->hlua))
9060 trace = NULL;
9061 trace = hlua_traceback(hlua_sub->hlua->T, ", ");
9062 /* At this point the execution is safe. */
9063 RESET_SAFE_LJMP(hlua_sub->hlua);
9064
9065 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 : ""));
9066 }
9067
9068 if (HLUA_IS_RUNNING(hlua_sub->hlua)) {
9069 /* ongoing hlua event handler, resume it */
9070 hlua_event_handler(hlua_sub->hlua);
9071 } else if ((event = event_hdl_async_equeue_pop(&hlua_sub->equeue))) { /* check for new events */
9072 if (event_hdl_sub_type_equal(event->type, EVENT_HDL_SUB_END)) {
9073 /* ending event: no more events to come */
9074 event_hdl_async_free_event(event);
9075 task_destroy(task);
9076 hlua_event_subscription_destroy(hlua_sub);
9077 return NULL;
9078 }
9079 /* new event: start processing it */
9080
9081 /* The following Lua calls can fail. */
9082 if (!SET_SAFE_LJMP(hlua_sub->hlua)) {
9083 if (lua_type(hlua_sub->hlua->T, -1) == LUA_TSTRING)
9084 error = lua_tostring(hlua_sub->hlua->T, -1);
9085 else
9086 error = "critical error";
9087 ha_alert("Lua event_hdl: %s.\n", error);
9088 goto skip_event;
9089 }
9090
9091 /* Check stack available size. */
9092 if (!lua_checkstack(hlua_sub->hlua->T, 5)) {
9093 ha_alert("Lua event_hdl: full stack.\n");
9094 RESET_SAFE_LJMP(hlua_sub->hlua);
9095 goto skip_event;
9096 }
9097
9098 /* Restore the function in the stack. */
9099 hlua_pushref(hlua_sub->hlua->T, hlua_sub->fcn_ref);
9100
9101 /* push args */
9102 hlua_sub->hlua->nargs = 0;
9103 if (!hlua_event_hdl_cb_data_push_args(hlua_sub, event->type, event->data)) {
9104 RESET_SAFE_LJMP(hlua_sub->hlua);
9105 goto skip_event;
9106 }
9107
9108 /* At this point the execution is safe. */
9109 RESET_SAFE_LJMP(hlua_sub->hlua);
9110
9111 /* At this point the event was successfully translated into hlua ctx,
9112 * or hlua error occured, so we can safely discard it
9113 */
9114 event_hdl_async_free_event(event);
9115 event = NULL;
9116
9117 hlua_event_handler(hlua_sub->hlua);
9118 skip_event:
9119 if (event)
9120 event_hdl_async_free_event(event);
9121
9122 }
9123
9124 if (!HLUA_IS_RUNNING(hlua_sub->hlua)) {
9125 /* we just finished the processing of one event..
9126 * check for new events before becoming idle
9127 */
9128 if (!event_hdl_async_equeue_isempty(&hlua_sub->equeue)) {
9129 /* more events to process, make sure the task
9130 * will be resumed ASAP to process pending events
9131 */
9132 task_wakeup(task, TASK_WOKEN_OTHER);
9133 }
9134 else if (hlua_sub->paused) {
9135 /* empty queue, the handler catched up: resume the subscription */
9136 event_hdl_resume(hlua_sub->sub);
9137 hlua_sub->paused = 0;
9138 }
9139 }
9140
9141 return task;
9142}
9143
9144/* Must be called directly under lua protected/safe environment
9145 * (not from external callback)
9146 * <fcn_ref> should NOT be dropped after the function successfully returns:
9147 * it will be done automatically in hlua_event_subscription_destroy() when the
9148 * subscription ends.
9149 *
9150 * Returns the new subscription on success and NULL on failure (memory error)
9151 */
9152static struct event_hdl_sub *hlua_event_subscribe(event_hdl_sub_list *list, struct event_hdl_sub_type e_type,
9153 int state_id, int fcn_ref)
9154{
9155 struct hlua_event_sub *hlua_sub;
9156 struct task *task = NULL;
9157
9158 hlua_sub = pool_alloc(pool_head_hlua_event_sub);
9159 if (!hlua_sub)
9160 goto mem_error;
9161 hlua_sub->task = NULL;
9162 hlua_sub->hlua = NULL;
9163 hlua_sub->paused = 0;
9164 if ((task = task_new_here()) == NULL) {
9165 ha_alert("out of memory while allocating hlua event task");
9166 goto mem_error;
9167 }
9168 task->process = hlua_event_runner;
9169 task->context = hlua_sub;
9170 event_hdl_async_equeue_init(&hlua_sub->equeue);
9171 hlua_sub->task = task;
9172 hlua_sub->fcn_ref = fcn_ref;
9173 hlua_sub->state_id = state_id;
9174 hlua_sub->hlua = pool_alloc(pool_head_hlua);
9175 if (!hlua_sub->hlua)
9176 goto mem_error;
9177 HLUA_INIT(hlua_sub->hlua);
9178 if (!hlua_ctx_init(hlua_sub->hlua, hlua_sub->state_id, task))
9179 goto mem_error;
9180
9181 hlua_sub->sub = event_hdl_subscribe_ptr(list, e_type,
9182 EVENT_HDL_ASYNC_TASK(&hlua_sub->equeue,
9183 task,
9184 hlua_sub,
9185 NULL));
9186 if (!hlua_sub->sub)
9187 goto mem_error;
9188
9189 return hlua_sub->sub; /* returns pointer to event_hdl_sub struct */
9190
9191 mem_error:
9192 if (hlua_sub) {
9193 if (hlua_sub->task)
9194 task_destroy(hlua_sub->task);
9195 if (hlua_sub->hlua)
9196 hlua_ctx_destroy(hlua_sub->hlua);
9197 pool_free(pool_head_hlua_event_sub, hlua_sub);
9198 }
9199
9200 return NULL;
9201}
9202
9203/* looks for an array of strings referring to a composition of event_hdl subscription
9204 * types at <index> in <L> stack
9205 */
9206__LJMP static struct event_hdl_sub_type hlua_check_event_sub_types(lua_State *L, int index)
9207{
9208 struct event_hdl_sub_type subscriptions;
9209 const char *msg;
9210
9211 if (lua_type(L, index) != LUA_TTABLE) {
9212 msg = lua_pushfstring(L, "table of strings expected, got %s", luaL_typename(L, index));
9213 luaL_argerror(L, index, msg);
9214 }
9215
9216 subscriptions = EVENT_HDL_SUB_NONE;
9217
9218 /* browse the argument as an array. */
9219 lua_pushnil(L);
9220 while (lua_next(L, index) != 0) {
9221 if (lua_type(L, -1) != LUA_TSTRING) {
9222 msg = lua_pushfstring(L, "table of strings expected, got %s", luaL_typename(L, index));
9223 luaL_argerror(L, index, msg);
9224 }
9225
9226 if (event_hdl_sub_type_equal(EVENT_HDL_SUB_NONE, event_hdl_string_to_sub_type(lua_tostring(L, -1)))) {
9227 msg = lua_pushfstring(L, "'%s' event type is unknown", lua_tostring(L, -1));
9228 luaL_argerror(L, index, msg);
9229 }
9230
9231 /* perform subscriptions |= current sub */
9232 subscriptions = event_hdl_sub_type_add(subscriptions, event_hdl_string_to_sub_type(lua_tostring(L, -1)));
9233
9234 /* pop the current value. */
9235 lua_pop(L, 1);
9236 }
9237
9238 return subscriptions;
9239}
9240
9241/* Wrapper for hlua_fcn_new_event_sub(): catch errors raised by
9242 * the function to prevent LJMP
9243 *
9244 * If no error occured, the function returns 1, else it returns 0 and
9245 * the error message is pushed at the top of the stack
9246 */
9247__LJMP static int _hlua_new_event_sub_safe(lua_State *L)
9248{
9249 struct event_hdl_sub *sub = lua_touserdata(L, 1);
9250
9251 /* this function may raise errors */
9252 return MAY_LJMP(hlua_fcn_new_event_sub(L, sub));
9253}
9254static int hlua_new_event_sub_safe(lua_State *L, struct event_hdl_sub *sub)
9255{
9256 if (!lua_checkstack(L, 2))
9257 return 0;
9258 lua_pushcfunction(L, _hlua_new_event_sub_safe);
9259 lua_pushlightuserdata(L, sub);
9260 switch (lua_pcall(L, 1, 1, 0)) {
9261 case LUA_OK:
9262 return 1;
9263 default:
9264 /* error was catched */
9265 return 0;
9266 }
9267}
9268
9269/* This function is a LUA helper used for registering lua event callbacks.
9270 * It expects an event subscription array and the function to be executed
9271 * when subscribed events occur (stack arguments).
9272 * It can be called from the "init" section, "post init" or during the runtime.
9273 *
9274 * <sub_list> is the subscription list where the subscription will be attempted
9275 *
9276 * Pushes the newly allocated subscription on the stack on success
9277 */
9278__LJMP int hlua_event_sub(lua_State *L, event_hdl_sub_list *sub_list)
9279{
9280 struct hlua *hlua;
9281 struct event_hdl_sub *sub;
9282 struct event_hdl_sub_type subscriptions;
9283 int fcn_ref;
9284 int state_id;
9285
9286 MAY_LJMP(check_args(L, 2, "event_sub"));
9287
9288 /* Get the reference state */
9289 hlua = hlua_gethlua(L);
9290 if (hlua)
9291 /* we are in runtime processing, any thread may subscribe to events:
9292 * subscription events will be handled by the thread who performed
9293 * the registration.
9294 */
9295 state_id = hlua->state_id;
9296 else {
9297 /* we are in initialization mode, only thread 0 (actual calling thread)
9298 * may subscribe to events to prevent the same handler (from different lua
9299 * stacks) from being registered multiple times
9300 *
9301 * hlua_state_id == 0: monostack (lua-load)
9302 * hlua_state_id > 0: hlua_state_id=tid+1, multi-stack (lua-load-per-thread)
9303 * (thus if hlua_state_id > 1, it means we are not in primary thread ctx)
9304 */
9305 if (hlua_state_id > 1)
9306 return 0; /* skip registration */
9307 state_id = hlua_state_id;
9308 }
9309
9310 /* First argument : event subscriptions. */
9311 subscriptions = MAY_LJMP(hlua_check_event_sub_types(L, 1));
9312
9313 if (event_hdl_sub_type_equal(subscriptions, EVENT_HDL_SUB_NONE)) {
9314 WILL_LJMP(luaL_error(L, "event_sub: no valid event types were provided"));
9315 return 0; /* Never reached */
9316 }
9317
9318 /* Second argument : lua function. */
9319 fcn_ref = MAY_LJMP(hlua_checkfunction(L, 2));
9320
9321 /* try to subscribe */
9322 sub = hlua_event_subscribe(sub_list, subscriptions, state_id, fcn_ref);
9323 if (!sub) {
9324 hlua_unref(L, fcn_ref);
9325 WILL_LJMP(luaL_error(L, "event_sub: lua out of memory error"));
9326 return 0; /* Never reached */
9327 }
9328
9329 /* push the subscription to the stack
9330 *
9331 * Here we use the safe function so that lua errors will be
9332 * handled explicitly to prevent 'sub' from being lost
9333 */
9334 if (!hlua_new_event_sub_safe(L, sub)) {
9335 /* Some events could already be pending in the handler's queue.
9336 * However it is wiser to cancel the subscription since we are unable to
9337 * provide a valid reference to it.
9338 * Pending events will be delivered (unless lua keeps raising errors).
9339 */
9340 event_hdl_unsubscribe(sub); /* cancel the subscription */
9341 WILL_LJMP(luaL_error(L, "event_sub: cannot push the subscription (%s)", lua_tostring(L, -1)));
9342 return 0; /* Never reached */
9343 }
9344 event_hdl_drop(sub); /* sub has been duplicated, discard old ref */
9345
9346 return 1;
9347}
9348
9349/* This function is a LUA wrapper used for registering global lua event callbacks
9350 * The new subscription is pushed onto the stack on success
9351 * Returns the number of arguments pushed to the stack (1 for success)
9352 */
9353__LJMP static int hlua_event_global_sub(lua_State *L)
9354{
9355 /* NULL <sub_list> = global subscription list */
9356 return MAY_LJMP(hlua_event_sub(L, NULL));
9357}
9358
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009359/* Wrapper called by HAProxy to execute an LUA converter. This wrapper
9360 * doesn't allow "yield" functions because the HAProxy engine cannot
9361 * resume converters.
9362 */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02009363static int hlua_sample_conv_wrapper(const struct arg *arg_p, struct sample *smp, void *private)
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009364{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02009365 struct hlua_function *fcn = private;
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02009366 struct stream *stream = smp->strm;
Thierry Fournierfd107a22016-02-19 19:57:23 +01009367 const char *error;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009368
Willy Tarreaube508f12016-03-10 11:47:01 +01009369 if (!stream)
9370 return 0;
9371
Willy Tarreau87b09662015-04-03 00:22:06 +02009372 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01009373 * Lua context can be not initialized. This behavior
9374 * permits to save performances because a systematic
9375 * Lua initialization cause 5% performances loss.
9376 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009377 if (!stream->hlua) {
Christopher Faulet1e8433f2021-03-24 15:03:01 +01009378 struct hlua *hlua;
9379
9380 hlua = pool_alloc(pool_head_hlua);
9381 if (!hlua) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009382 SEND_ERR(stream->be, "Lua converter '%s': can't initialize Lua context.\n", fcn->name);
9383 return 0;
9384 }
Christopher Faulet1e8433f2021-03-24 15:03:01 +01009385 HLUA_INIT(hlua);
9386 stream->hlua = hlua;
Aurelien DARRAGON6b0b9bd2023-03-21 14:02:16 +01009387 if (!hlua_ctx_init(stream->hlua, fcn_ref_to_stack_id(fcn), stream->task)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009388 SEND_ERR(stream->be, "Lua converter '%s': can't initialize Lua context.\n", fcn->name);
9389 return 0;
9390 }
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01009391 }
9392
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009393 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009394 if (!HLUA_IS_RUNNING(stream->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02009395
9396 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009397 if (!SET_SAFE_LJMP(stream->hlua)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009398 if (lua_type(stream->hlua->T, -1) == LUA_TSTRING)
9399 error = lua_tostring(stream->hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +01009400 else
9401 error = "critical error";
9402 SEND_ERR(stream->be, "Lua converter '%s': %s.\n", fcn->name, error);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02009403 return 0;
9404 }
9405
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009406 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009407 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009408 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009409 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009410 return 0;
9411 }
9412
9413 /* Restore the function in the stack. */
Aurelien DARRAGON4fdf8b52023-03-20 17:22:37 +01009414 hlua_pushref(stream->hlua->T, fcn->function_ref[stream->hlua->state_id]);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009415
9416 /* convert input sample and pust-it in the stack. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009417 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009418 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009419 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009420 return 0;
9421 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009422 hlua_smp2lua(stream->hlua->T, smp);
9423 stream->hlua->nargs = 1;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009424
9425 /* push keywords in the stack. */
9426 if (arg_p) {
9427 for (; arg_p->type != ARGT_STOP; arg_p++) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009428 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009429 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009430 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009431 return 0;
9432 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009433 hlua_arg2lua(stream->hlua->T, arg_p);
9434 stream->hlua->nargs++;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009435 }
9436 }
9437
Thierry FOURNIERbd413492015-03-03 16:52:26 +01009438 /* We must initialize the execution timeouts. */
Aurelien DARRAGONda9503c2022-11-25 09:10:07 +01009439 hlua_timer_init(&stream->hlua->timer, hlua_timeout_session);
Thierry FOURNIERbd413492015-03-03 16:52:26 +01009440
Thierry FOURNIERbabae282015-09-17 11:36:37 +02009441 /* At this point the execution is safe. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009442 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009443 }
9444
9445 /* Execute the function. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009446 switch (hlua_ctx_resume(stream->hlua, 0)) {
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009447 /* finished. */
9448 case HLUA_E_OK:
Thierry FOURNIERfd80df12017-05-12 16:32:20 +02009449 /* If the stack is empty, the function fails. */
9450 if (lua_gettop(stream->hlua->T) <= 0)
9451 return 0;
9452
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009453 /* Convert the returned value in sample. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009454 hlua_lua2smp(stream->hlua->T, -1, smp);
9455 lua_pop(stream->hlua->T, 1);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009456 return 1;
9457
9458 /* yield. */
9459 case HLUA_E_AGAIN:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009460 SEND_ERR(stream->be, "Lua converter '%s': cannot use yielded functions.\n", fcn->name);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009461 return 0;
9462
9463 /* finished with error. */
9464 case HLUA_E_ERRMSG:
9465 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009466 SEND_ERR(stream->be, "Lua converter '%s': %s.\n",
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009467 fcn->name, lua_tostring(stream->hlua->T, -1));
9468 lua_pop(stream->hlua->T, 1);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009469 return 0;
9470
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009471 case HLUA_E_ETMOUT:
9472 SEND_ERR(stream->be, "Lua converter '%s': execution timeout.\n", fcn->name);
9473 return 0;
9474
9475 case HLUA_E_NOMEM:
9476 SEND_ERR(stream->be, "Lua converter '%s': out of memory error.\n", fcn->name);
9477 return 0;
9478
9479 case HLUA_E_YIELD:
9480 SEND_ERR(stream->be, "Lua converter '%s': yield functions like core.tcp() or core.sleep() are not allowed.\n", fcn->name);
9481 return 0;
9482
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009483 case HLUA_E_ERR:
9484 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009485 SEND_ERR(stream->be, "Lua converter '%s' returns an unknown error.\n", fcn->name);
Willy Tarreau14de3952022-11-14 07:08:28 +01009486 __fallthrough;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009487
9488 default:
9489 return 0;
9490 }
9491}
9492
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009493/* Wrapper called by HAProxy to execute a sample-fetch. this wrapper
9494 * doesn't allow "yield" functions because the HAProxy engine cannot
Willy Tarreaube508f12016-03-10 11:47:01 +01009495 * resume sample-fetches. This function will be called by the sample
9496 * fetch engine to call lua-based fetch operations.
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009497 */
Thierry FOURNIER0786d052015-05-11 15:42:45 +02009498static int hlua_sample_fetch_wrapper(const struct arg *arg_p, struct sample *smp,
9499 const char *kw, void *private)
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009500{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02009501 struct hlua_function *fcn = private;
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02009502 struct stream *stream = smp->strm;
Thierry Fournierfd107a22016-02-19 19:57:23 +01009503 const char *error;
Christopher Faulet8c9e6bb2021-08-06 16:29:41 +02009504 unsigned int hflags = HLUA_TXN_NOTERM | HLUA_TXN_SMP_CTX;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009505
Willy Tarreaube508f12016-03-10 11:47:01 +01009506 if (!stream)
9507 return 0;
Christopher Fauletafd8f102018-11-08 11:34:21 +01009508
Willy Tarreau87b09662015-04-03 00:22:06 +02009509 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01009510 * Lua context can be not initialized. This behavior
9511 * permits to save performances because a systematic
9512 * Lua initialization cause 5% performances loss.
9513 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009514 if (!stream->hlua) {
Christopher Faulet1e8433f2021-03-24 15:03:01 +01009515 struct hlua *hlua;
9516
9517 hlua = pool_alloc(pool_head_hlua);
9518 if (!hlua) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009519 SEND_ERR(stream->be, "Lua sample-fetch '%s': can't initialize Lua context.\n", fcn->name);
9520 return 0;
9521 }
Christopher Faulet1e8433f2021-03-24 15:03:01 +01009522 hlua->T = NULL;
9523 stream->hlua = hlua;
Aurelien DARRAGON6b0b9bd2023-03-21 14:02:16 +01009524 if (!hlua_ctx_init(stream->hlua, fcn_ref_to_stack_id(fcn), stream->task)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009525 SEND_ERR(stream->be, "Lua sample-fetch '%s': can't initialize Lua context.\n", fcn->name);
9526 return 0;
9527 }
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01009528 }
9529
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009530 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009531 if (!HLUA_IS_RUNNING(stream->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02009532
9533 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009534 if (!SET_SAFE_LJMP(stream->hlua)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009535 if (lua_type(stream->hlua->T, -1) == LUA_TSTRING)
9536 error = lua_tostring(stream->hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +01009537 else
9538 error = "critical error";
9539 SEND_ERR(smp->px, "Lua sample-fetch '%s': %s.\n", fcn->name, error);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02009540 return 0;
9541 }
9542
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009543 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009544 if (!lua_checkstack(stream->hlua->T, 2)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009545 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009546 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009547 return 0;
9548 }
9549
9550 /* Restore the function in the stack. */
Aurelien DARRAGON4fdf8b52023-03-20 17:22:37 +01009551 hlua_pushref(stream->hlua->T, fcn->function_ref[stream->hlua->state_id]);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009552
9553 /* push arguments in the stack. */
Christopher Fauletbfab2dd2019-07-26 15:09:53 +02009554 if (!hlua_txn_new(stream->hlua->T, stream, smp->px, smp->opt & SMP_OPT_DIR, hflags)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009555 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009556 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009557 return 0;
9558 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009559 stream->hlua->nargs = 1;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009560
9561 /* push keywords in the stack. */
9562 for (; arg_p && arg_p->type != ARGT_STOP; arg_p++) {
9563 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009564 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009565 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009566 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009567 return 0;
9568 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009569 hlua_arg2lua(stream->hlua->T, arg_p);
9570 stream->hlua->nargs++;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009571 }
9572
Thierry FOURNIERbd413492015-03-03 16:52:26 +01009573 /* We must initialize the execution timeouts. */
Aurelien DARRAGONda9503c2022-11-25 09:10:07 +01009574 hlua_timer_init(&stream->hlua->timer, hlua_timeout_session);
Thierry FOURNIERbd413492015-03-03 16:52:26 +01009575
Thierry FOURNIERbabae282015-09-17 11:36:37 +02009576 /* At this point the execution is safe. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009577 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009578 }
9579
9580 /* Execute the function. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009581 switch (hlua_ctx_resume(stream->hlua, 0)) {
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009582 /* finished. */
9583 case HLUA_E_OK:
Thierry FOURNIERfd80df12017-05-12 16:32:20 +02009584 /* If the stack is empty, the function fails. */
9585 if (lua_gettop(stream->hlua->T) <= 0)
9586 return 0;
9587
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009588 /* Convert the returned value in sample. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009589 hlua_lua2smp(stream->hlua->T, -1, smp);
9590 lua_pop(stream->hlua->T, 1);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009591
9592 /* Set the end of execution flag. */
9593 smp->flags &= ~SMP_F_MAY_CHANGE;
9594 return 1;
9595
9596 /* yield. */
9597 case HLUA_E_AGAIN:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009598 SEND_ERR(smp->px, "Lua sample-fetch '%s': cannot use yielded functions.\n", fcn->name);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009599 return 0;
9600
9601 /* finished with error. */
9602 case HLUA_E_ERRMSG:
9603 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009604 SEND_ERR(smp->px, "Lua sample-fetch '%s': %s.\n",
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009605 fcn->name, lua_tostring(stream->hlua->T, -1));
9606 lua_pop(stream->hlua->T, 1);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009607 return 0;
9608
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009609 case HLUA_E_ETMOUT:
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009610 SEND_ERR(smp->px, "Lua sample-fetch '%s': execution timeout.\n", fcn->name);
9611 return 0;
9612
9613 case HLUA_E_NOMEM:
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009614 SEND_ERR(smp->px, "Lua sample-fetch '%s': out of memory error.\n", fcn->name);
9615 return 0;
9616
9617 case HLUA_E_YIELD:
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009618 SEND_ERR(smp->px, "Lua sample-fetch '%s': yield not allowed.\n", fcn->name);
9619 return 0;
9620
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009621 case HLUA_E_ERR:
9622 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009623 SEND_ERR(smp->px, "Lua sample-fetch '%s' returns an unknown error.\n", fcn->name);
Willy Tarreau14de3952022-11-14 07:08:28 +01009624 __fallthrough;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009625
9626 default:
9627 return 0;
9628 }
9629}
9630
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009631/* This function is an LUA binding used for registering
9632 * "sample-conv" functions. It expects a converter name used
9633 * in the haproxy configuration file, and an LUA function.
9634 */
9635__LJMP static int hlua_register_converters(lua_State *L)
9636{
9637 struct sample_conv_kw_list *sck;
9638 const char *name;
9639 int ref;
9640 int len;
Christopher Fauletaa224302021-04-12 14:08:21 +02009641 struct hlua_function *fcn = NULL;
Thierry Fournierf67442e2020-11-28 20:41:07 +01009642 struct sample_conv *sc;
9643 struct buffer *trash;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009644
9645 MAY_LJMP(check_args(L, 2, "register_converters"));
9646
Aurelien DARRAGON87f52972023-02-24 09:43:54 +01009647 if (hlua_gethlua(L)) {
9648 /* runtime processing */
9649 WILL_LJMP(luaL_error(L, "register_converters: not available outside of body context"));
9650 }
9651
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009652 /* First argument : converter name. */
9653 name = MAY_LJMP(luaL_checkstring(L, 1));
9654
9655 /* Second argument : lua function. */
9656 ref = MAY_LJMP(hlua_checkfunction(L, 2));
9657
Thierry Fournierf67442e2020-11-28 20:41:07 +01009658 /* Check if the converter is already registered */
9659 trash = get_trash_chunk();
9660 chunk_printf(trash, "lua.%s", name);
9661 sc = find_sample_conv(trash->area, trash->data);
9662 if (sc != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +01009663 fcn = sc->private;
9664 if (fcn->function_ref[hlua_state_id] != -1) {
9665 ha_warning("Trying to register converter 'lua.%s' more than once. "
9666 "This will become a hard error in version 2.5.\n", name);
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +01009667 hlua_unref(L, fcn->function_ref[hlua_state_id]);
Thierry Fournier59f11be2020-11-29 00:37:41 +01009668 }
9669 fcn->function_ref[hlua_state_id] = ref;
9670 return 0;
Thierry Fournierf67442e2020-11-28 20:41:07 +01009671 }
9672
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009673 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02009674 sck = calloc(1, sizeof(*sck) + sizeof(struct sample_conv) * 2);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009675 if (!sck)
Christopher Fauletaa224302021-04-12 14:08:21 +02009676 goto alloc_error;
Thierry Fournier62a22aa2020-11-28 21:06:35 +01009677 fcn = new_hlua_function();
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009678 if (!fcn)
Christopher Fauletaa224302021-04-12 14:08:21 +02009679 goto alloc_error;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009680
9681 /* Fill fcn. */
9682 fcn->name = strdup(name);
9683 if (!fcn->name)
Christopher Fauletaa224302021-04-12 14:08:21 +02009684 goto alloc_error;
Thierry Fournierc7492592020-11-28 23:57:24 +01009685 fcn->function_ref[hlua_state_id] = ref;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009686
9687 /* List head */
9688 sck->list.n = sck->list.p = NULL;
9689
9690 /* converter keyword. */
9691 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02009692 sck->kw[0].kw = calloc(1, len);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009693 if (!sck->kw[0].kw)
Christopher Fauletaa224302021-04-12 14:08:21 +02009694 goto alloc_error;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009695
9696 snprintf((char *)sck->kw[0].kw, len, "lua.%s", name);
9697 sck->kw[0].process = hlua_sample_conv_wrapper;
David Carlier0c437f42016-04-27 16:21:56 +01009698 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 +01009699 sck->kw[0].val_args = NULL;
9700 sck->kw[0].in_type = SMP_T_STR;
9701 sck->kw[0].out_type = SMP_T_STR;
9702 sck->kw[0].private = fcn;
9703
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009704 /* Register this new converter */
9705 sample_register_convs(sck);
9706
9707 return 0;
Christopher Fauletaa224302021-04-12 14:08:21 +02009708
9709 alloc_error:
9710 release_hlua_function(fcn);
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +01009711 hlua_unref(L, ref);
Christopher Fauletaa224302021-04-12 14:08:21 +02009712 ha_free(&sck);
9713 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
9714 return 0; /* Never reached */
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009715}
9716
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08009717/* This function is an LUA binding used for registering
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009718 * "sample-fetch" functions. It expects a converter name used
9719 * in the haproxy configuration file, and an LUA function.
9720 */
9721__LJMP static int hlua_register_fetches(lua_State *L)
9722{
9723 const char *name;
9724 int ref;
9725 int len;
9726 struct sample_fetch_kw_list *sfk;
Christopher Faulet2567f182021-04-12 14:11:50 +02009727 struct hlua_function *fcn = NULL;
Thierry Fournierf67442e2020-11-28 20:41:07 +01009728 struct sample_fetch *sf;
9729 struct buffer *trash;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009730
9731 MAY_LJMP(check_args(L, 2, "register_fetches"));
9732
Aurelien DARRAGON87f52972023-02-24 09:43:54 +01009733 if (hlua_gethlua(L)) {
9734 /* runtime processing */
9735 WILL_LJMP(luaL_error(L, "register_fetches: not available outside of body context"));
9736 }
9737
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009738 /* First argument : sample-fetch name. */
9739 name = MAY_LJMP(luaL_checkstring(L, 1));
9740
9741 /* Second argument : lua function. */
9742 ref = MAY_LJMP(hlua_checkfunction(L, 2));
9743
Thierry Fournierf67442e2020-11-28 20:41:07 +01009744 /* Check if the sample-fetch is already registered */
9745 trash = get_trash_chunk();
9746 chunk_printf(trash, "lua.%s", name);
9747 sf = find_sample_fetch(trash->area, trash->data);
9748 if (sf != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +01009749 fcn = sf->private;
9750 if (fcn->function_ref[hlua_state_id] != -1) {
9751 ha_warning("Trying to register sample-fetch 'lua.%s' more than once. "
9752 "This will become a hard error in version 2.5.\n", name);
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +01009753 hlua_unref(L, fcn->function_ref[hlua_state_id]);
Thierry Fournier59f11be2020-11-29 00:37:41 +01009754 }
9755 fcn->function_ref[hlua_state_id] = ref;
9756 return 0;
Thierry Fournierf67442e2020-11-28 20:41:07 +01009757 }
9758
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009759 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02009760 sfk = calloc(1, sizeof(*sfk) + sizeof(struct sample_fetch) * 2);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009761 if (!sfk)
Christopher Faulet2567f182021-04-12 14:11:50 +02009762 goto alloc_error;
Thierry Fournier62a22aa2020-11-28 21:06:35 +01009763 fcn = new_hlua_function();
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009764 if (!fcn)
Christopher Faulet2567f182021-04-12 14:11:50 +02009765 goto alloc_error;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009766
9767 /* Fill fcn. */
9768 fcn->name = strdup(name);
9769 if (!fcn->name)
Christopher Faulet2567f182021-04-12 14:11:50 +02009770 goto alloc_error;
Thierry Fournierc7492592020-11-28 23:57:24 +01009771 fcn->function_ref[hlua_state_id] = ref;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009772
9773 /* List head */
9774 sfk->list.n = sfk->list.p = NULL;
9775
9776 /* sample-fetch keyword. */
9777 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02009778 sfk->kw[0].kw = calloc(1, len);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009779 if (!sfk->kw[0].kw)
Christopher Faulet2567f182021-04-12 14:11:50 +02009780 goto alloc_error;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009781
9782 snprintf((char *)sfk->kw[0].kw, len, "lua.%s", name);
9783 sfk->kw[0].process = hlua_sample_fetch_wrapper;
David Carlier0c437f42016-04-27 16:21:56 +01009784 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 +01009785 sfk->kw[0].val_args = NULL;
9786 sfk->kw[0].out_type = SMP_T_STR;
9787 sfk->kw[0].use = SMP_USE_HTTP_ANY;
9788 sfk->kw[0].val = 0;
9789 sfk->kw[0].private = fcn;
9790
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009791 /* Register this new fetch. */
9792 sample_register_fetches(sfk);
9793
9794 return 0;
Christopher Faulet2567f182021-04-12 14:11:50 +02009795
9796 alloc_error:
9797 release_hlua_function(fcn);
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +01009798 hlua_unref(L, ref);
Christopher Faulet2567f182021-04-12 14:11:50 +02009799 ha_free(&sfk);
9800 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
9801 return 0; /* Never reached */
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009802}
9803
Christopher Faulet501465d2020-02-26 14:54:16 +01009804/* This function is a lua binding to set the wake_time.
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01009805 */
Christopher Faulet501465d2020-02-26 14:54:16 +01009806__LJMP static int hlua_set_wake_time(lua_State *L)
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01009807{
Thierry Fournier4234dbd2020-11-28 13:18:23 +01009808 struct hlua *hlua;
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01009809 unsigned int delay;
9810 unsigned int wakeup_ms;
9811
Thierry Fournier4234dbd2020-11-28 13:18:23 +01009812 /* Get hlua struct, or NULL if we execute from main lua state */
9813 hlua = hlua_gethlua(L);
9814 if (!hlua) {
9815 return 0;
9816 }
9817
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01009818 MAY_LJMP(check_args(L, 1, "wake_time"));
9819
9820 delay = MAY_LJMP(luaL_checkinteger(L, 1));
9821 wakeup_ms = tick_add(now_ms, delay);
9822 hlua->wake_time = wakeup_ms;
9823 return 0;
9824}
9825
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009826/* This function is a wrapper to execute each LUA function declared as an action
9827 * wrapper during the initialisation period. This function may return any
9828 * ACT_RET_* value. On error ACT_RET_CONT is returned and the action is
9829 * ignored. If the lua action yields, ACT_RET_YIELD is returned. On success, the
9830 * return value is the first element on the stack.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009831 */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009832static enum act_return hlua_action(struct act_rule *rule, struct proxy *px,
Willy Tarreau658b85b2015-09-27 10:00:49 +02009833 struct session *sess, struct stream *s, int flags)
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009834{
9835 char **arg;
Christopher Faulet8c9e6bb2021-08-06 16:29:41 +02009836 unsigned int hflags = HLUA_TXN_ACT_CTX;
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009837 int dir, act_ret = ACT_RET_CONT;
Thierry Fournierfd107a22016-02-19 19:57:23 +01009838 const char *error;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009839
9840 switch (rule->from) {
Christopher Fauletd8f0e072020-02-25 09:45:51 +01009841 case ACT_F_TCP_REQ_CNT: dir = SMP_OPT_DIR_REQ; break;
9842 case ACT_F_TCP_RES_CNT: dir = SMP_OPT_DIR_RES; break;
9843 case ACT_F_HTTP_REQ: dir = SMP_OPT_DIR_REQ; break;
9844 case ACT_F_HTTP_RES: dir = SMP_OPT_DIR_RES; break;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009845 default:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009846 SEND_ERR(px, "Lua: internal error while execute action.\n");
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009847 goto end;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009848 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009849
Willy Tarreau87b09662015-04-03 00:22:06 +02009850 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01009851 * Lua context can be not initialized. This behavior
9852 * permits to save performances because a systematic
9853 * Lua initialization cause 5% performances loss.
9854 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009855 if (!s->hlua) {
Christopher Faulet1e8433f2021-03-24 15:03:01 +01009856 struct hlua *hlua;
9857
9858 hlua = pool_alloc(pool_head_hlua);
9859 if (!hlua) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009860 SEND_ERR(px, "Lua action '%s': can't initialize Lua context.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009861 rule->arg.hlua_rule->fcn->name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009862 goto end;
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009863 }
Christopher Faulet1e8433f2021-03-24 15:03:01 +01009864 HLUA_INIT(hlua);
9865 s->hlua = hlua;
Aurelien DARRAGON6b0b9bd2023-03-21 14:02:16 +01009866 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 +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 }
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01009871 }
9872
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009873 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009874 if (!HLUA_IS_RUNNING(s->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02009875
9876 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009877 if (!SET_SAFE_LJMP(s->hlua)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009878 if (lua_type(s->hlua->T, -1) == LUA_TSTRING)
9879 error = lua_tostring(s->hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +01009880 else
9881 error = "critical error";
9882 SEND_ERR(px, "Lua function '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009883 rule->arg.hlua_rule->fcn->name, error);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009884 goto end;
Thierry FOURNIERbabae282015-09-17 11:36:37 +02009885 }
9886
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009887 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009888 if (!lua_checkstack(s->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009889 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009890 rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009891 RESET_SAFE_LJMP(s->hlua);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009892 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009893 }
9894
9895 /* Restore the function in the stack. */
Aurelien DARRAGON4fdf8b52023-03-20 17:22:37 +01009896 hlua_pushref(s->hlua->T, rule->arg.hlua_rule->fcn->function_ref[s->hlua->state_id]);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009897
Willy Tarreau87b09662015-04-03 00:22:06 +02009898 /* Create and and push object stream in the stack. */
Christopher Fauletbfab2dd2019-07-26 15:09:53 +02009899 if (!hlua_txn_new(s->hlua->T, s, px, dir, hflags)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009900 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009901 rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009902 RESET_SAFE_LJMP(s->hlua);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009903 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009904 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009905 s->hlua->nargs = 1;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009906
9907 /* push keywords in the stack. */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009908 for (arg = rule->arg.hlua_rule->args; arg && *arg; arg++) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009909 if (!lua_checkstack(s->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009910 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009911 rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009912 RESET_SAFE_LJMP(s->hlua);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009913 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009914 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009915 lua_pushstring(s->hlua->T, *arg);
9916 s->hlua->nargs++;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009917 }
9918
Thierry FOURNIERbabae282015-09-17 11:36:37 +02009919 /* Now the execution is safe. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009920 RESET_SAFE_LJMP(s->hlua);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02009921
Thierry FOURNIERbd413492015-03-03 16:52:26 +01009922 /* We must initialize the execution timeouts. */
Aurelien DARRAGONda9503c2022-11-25 09:10:07 +01009923 hlua_timer_init(&s->hlua->timer, hlua_timeout_session);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009924 }
9925
9926 /* Execute the function. */
Christopher Faulet105ba6c2019-12-18 14:41:51 +01009927 switch (hlua_ctx_resume(s->hlua, !(flags & ACT_OPT_FINAL))) {
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009928 /* finished. */
9929 case HLUA_E_OK:
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009930 /* Catch the return value */
9931 if (lua_gettop(s->hlua->T) > 0)
9932 act_ret = lua_tointeger(s->hlua->T, -1);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009933
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01009934 /* Set timeout in the required channel. */
Christopher Faulet498c4832020-07-28 11:59:58 +02009935 if (act_ret == ACT_RET_YIELD) {
9936 if (flags & ACT_OPT_FINAL)
9937 goto err_yield;
9938
Christopher Faulet8f587ea2020-07-28 12:01:55 +02009939 if (dir == SMP_OPT_DIR_REQ)
9940 s->req.analyse_exp = tick_first((tick_is_expired(s->req.analyse_exp, now_ms) ? 0 : s->req.analyse_exp),
9941 s->hlua->wake_time);
9942 else
9943 s->res.analyse_exp = tick_first((tick_is_expired(s->res.analyse_exp, now_ms) ? 0 : s->res.analyse_exp),
9944 s->hlua->wake_time);
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01009945 }
9946 goto end;
9947
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009948 /* yield. */
9949 case HLUA_E_AGAIN:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01009950 /* Set timeout in the required channel. */
Christopher Faulet8f587ea2020-07-28 12:01:55 +02009951 if (dir == SMP_OPT_DIR_REQ)
9952 s->req.analyse_exp = tick_first((tick_is_expired(s->req.analyse_exp, now_ms) ? 0 : s->req.analyse_exp),
9953 s->hlua->wake_time);
9954 else
9955 s->res.analyse_exp = tick_first((tick_is_expired(s->res.analyse_exp, now_ms) ? 0 : s->res.analyse_exp),
9956 s->hlua->wake_time);
9957
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009958 /* Some actions can be wake up when a "write" event
9959 * is detected on a response channel. This is useful
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08009960 * only for actions targeted on the requests.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009961 */
Christopher Faulet51fa3582019-07-26 14:54:52 +02009962 if (HLUA_IS_WAKERESWR(s->hlua))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01009963 s->res.flags |= CF_WAKE_WRITE;
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009964 if (HLUA_IS_WAKEREQWR(s->hlua))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01009965 s->req.flags |= CF_WAKE_WRITE;
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009966 act_ret = ACT_RET_YIELD;
9967 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009968
9969 /* finished with error. */
9970 case HLUA_E_ERRMSG:
9971 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009972 SEND_ERR(px, "Lua function '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009973 rule->arg.hlua_rule->fcn->name, lua_tostring(s->hlua->T, -1));
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009974 lua_pop(s->hlua->T, 1);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009975 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009976
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009977 case HLUA_E_ETMOUT:
Thierry Fournierad5345f2020-11-29 02:05:57 +01009978 SEND_ERR(px, "Lua function '%s': execution timeout.\n", rule->arg.hlua_rule->fcn->name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009979 goto end;
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009980
9981 case HLUA_E_NOMEM:
Thierry Fournierad5345f2020-11-29 02:05:57 +01009982 SEND_ERR(px, "Lua function '%s': out of memory error.\n", rule->arg.hlua_rule->fcn->name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009983 goto end;
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009984
9985 case HLUA_E_YIELD:
Christopher Faulet498c4832020-07-28 11:59:58 +02009986 err_yield:
9987 act_ret = ACT_RET_CONT;
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009988 SEND_ERR(px, "Lua function '%s': aborting Lua processing on expired timeout.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009989 rule->arg.hlua_rule->fcn->name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009990 goto end;
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009991
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009992 case HLUA_E_ERR:
9993 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009994 SEND_ERR(px, "Lua function '%s' return an unknown error.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009995 rule->arg.hlua_rule->fcn->name);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009996
9997 default:
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009998 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009999 }
Christopher Faulet7716cdf2020-01-29 11:53:30 +010010000
10001 end:
Christopher Faulet2361fd92020-07-30 10:40:58 +020010002 if (act_ret != ACT_RET_YIELD && s->hlua)
Christopher Faulet8f587ea2020-07-28 12:01:55 +020010003 s->hlua->wake_time = TICK_ETERNITY;
Christopher Faulet7716cdf2020-01-29 11:53:30 +010010004 return act_ret;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +010010005}
10006
Willy Tarreau144f84a2021-03-02 16:09:26 +010010007struct task *hlua_applet_wakeup(struct task *t, void *context, unsigned int state)
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010008{
Olivier Houchard9f6af332018-05-25 14:04:04 +020010009 struct appctx *ctx = context;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010010
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010011 appctx_wakeup(ctx);
Willy Tarreaud9587412017-08-23 16:07:33 +020010012 t->expire = TICK_ETERNITY;
Willy Tarreaud1aa41f2017-07-21 16:41:56 +020010013 return t;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010014}
10015
Christopher Faulet4aa1d282022-01-13 16:01:35 +010010016static int hlua_applet_tcp_init(struct appctx *ctx)
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010017{
Willy Tarreaue23f33b2022-05-06 14:07:13 +020010018 struct hlua_tcp_ctx *tcp_ctx = applet_reserve_svcctx(ctx, sizeof(*tcp_ctx));
Willy Tarreauc12b3212022-05-27 11:08:15 +020010019 struct stconn *sc = appctx_sc(ctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +020010020 struct stream *strm = __sc_strm(sc);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +010010021 struct hlua *hlua;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010022 struct task *task;
10023 char **arg;
Thierry Fournierfd107a22016-02-19 19:57:23 +010010024 const char *error;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010025
Willy Tarreaubafbe012017-11-24 17:34:44 +010010026 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +010010027 if (!hlua) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +010010028 SEND_ERR(strm->be, "Lua applet tcp '%s': out of memory.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010029 ctx->rule->arg.hlua_rule->fcn->name);
Christopher Fauletc9929382022-05-12 11:52:27 +020010030 return -1;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +010010031 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010032 HLUA_INIT(hlua);
Willy Tarreaue23f33b2022-05-06 14:07:13 +020010033 tcp_ctx->hlua = hlua;
10034 tcp_ctx->flags = 0;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010035
10036 /* Create task used by signal to wakeup applets. */
Willy Tarreaubeeabf52021-10-01 18:23:30 +020010037 task = task_new_here();
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010038 if (!task) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +010010039 SEND_ERR(strm->be, "Lua applet tcp '%s': out of memory.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010040 ctx->rule->arg.hlua_rule->fcn->name);
Christopher Fauletc9929382022-05-12 11:52:27 +020010041 return -1;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010042 }
10043 task->nice = 0;
10044 task->context = ctx;
10045 task->process = hlua_applet_wakeup;
Willy Tarreaue23f33b2022-05-06 14:07:13 +020010046 tcp_ctx->task = task;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010047
10048 /* In the execution wrappers linked with a stream, the
10049 * Lua context can be not initialized. This behavior
10050 * permits to save performances because a systematic
10051 * Lua initialization cause 5% performances loss.
10052 */
Aurelien DARRAGON6b0b9bd2023-03-21 14:02:16 +010010053 if (!hlua_ctx_init(hlua, fcn_ref_to_stack_id(ctx->rule->arg.hlua_rule->fcn), task)) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +010010054 SEND_ERR(strm->be, "Lua applet tcp '%s': can't initialize Lua context.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010055 ctx->rule->arg.hlua_rule->fcn->name);
Christopher Fauletc9929382022-05-12 11:52:27 +020010056 return -1;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010057 }
10058
10059 /* Set timeout according with the applet configuration. */
Aurelien DARRAGONda9503c2022-11-25 09:10:07 +010010060 hlua_timer_init(&hlua->timer, ctx->applet->timeout);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010061
10062 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010063 if (!SET_SAFE_LJMP(hlua)) {
Thierry Fournierfd107a22016-02-19 19:57:23 +010010064 if (lua_type(hlua->T, -1) == LUA_TSTRING)
10065 error = lua_tostring(hlua->T, -1);
10066 else
10067 error = "critical error";
Christopher Faulet4aa1d282022-01-13 16:01:35 +010010068 SEND_ERR(strm->be, "Lua applet tcp '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010069 ctx->rule->arg.hlua_rule->fcn->name, error);
Christopher Fauletc9929382022-05-12 11:52:27 +020010070 return -1;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010071 }
10072
10073 /* Check stack available size. */
10074 if (!lua_checkstack(hlua->T, 1)) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +010010075 SEND_ERR(strm->be, "Lua applet tcp '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010076 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010077 RESET_SAFE_LJMP(hlua);
Christopher Fauletc9929382022-05-12 11:52:27 +020010078 return -1;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010079 }
10080
10081 /* Restore the function in the stack. */
Aurelien DARRAGON4fdf8b52023-03-20 17:22:37 +010010082 hlua_pushref(hlua->T, ctx->rule->arg.hlua_rule->fcn->function_ref[hlua->state_id]);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010083
10084 /* Create and and push object stream in the stack. */
10085 if (!hlua_applet_tcp_new(hlua->T, ctx)) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +010010086 SEND_ERR(strm->be, "Lua applet tcp '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010087 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010088 RESET_SAFE_LJMP(hlua);
Christopher Fauletc9929382022-05-12 11:52:27 +020010089 return -1;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010090 }
10091 hlua->nargs = 1;
10092
10093 /* push keywords in the stack. */
10094 for (arg = ctx->rule->arg.hlua_rule->args; arg && *arg; arg++) {
10095 if (!lua_checkstack(hlua->T, 1)) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +010010096 SEND_ERR(strm->be, "Lua applet tcp '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010097 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010098 RESET_SAFE_LJMP(hlua);
Christopher Fauletc9929382022-05-12 11:52:27 +020010099 return -1;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010100 }
10101 lua_pushstring(hlua->T, *arg);
10102 hlua->nargs++;
10103 }
10104
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010105 RESET_SAFE_LJMP(hlua);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010106
10107 /* Wakeup the applet ASAP. */
Willy Tarreau90e8b452022-05-25 18:21:43 +020010108 applet_need_more_data(ctx);
Willy Tarreau4164eb92022-05-25 15:42:03 +020010109 applet_have_more_data(ctx);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010110
Christopher Fauletc9929382022-05-12 11:52:27 +020010111 return 0;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010112}
10113
Willy Tarreau60409db2019-08-21 14:14:50 +020010114void hlua_applet_tcp_fct(struct appctx *ctx)
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010115{
Willy Tarreaue23f33b2022-05-06 14:07:13 +020010116 struct hlua_tcp_ctx *tcp_ctx = ctx->svcctx;
Willy Tarreauc12b3212022-05-27 11:08:15 +020010117 struct stconn *sc = appctx_sc(ctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +020010118 struct stream *strm = __sc_strm(sc);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010119 struct act_rule *rule = ctx->rule;
10120 struct proxy *px = strm->be;
Willy Tarreaue23f33b2022-05-06 14:07:13 +020010121 struct hlua *hlua = tcp_ctx->hlua;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010122
Christopher Faulet31572222023-03-31 11:13:48 +020010123 if (unlikely(se_fl_test(ctx->sedesc, (SE_FL_EOS|SE_FL_ERROR|SE_FL_SHR|SE_FL_SHW))))
10124 goto out;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010125
Christopher Faulet31572222023-03-31 11:13:48 +020010126 /* The applet execution is already done. */
10127 if (tcp_ctx->flags & APPLET_DONE)
10128 goto out;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010129
10130 /* Execute the function. */
10131 switch (hlua_ctx_resume(hlua, 1)) {
10132 /* finished. */
10133 case HLUA_E_OK:
Willy Tarreaue23f33b2022-05-06 14:07:13 +020010134 tcp_ctx->flags |= APPLET_DONE;
Christopher Faulet31572222023-03-31 11:13:48 +020010135 se_fl_set(ctx->sedesc, SE_FL_EOI|SE_FL_EOS);
10136 break;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010137
10138 /* yield. */
10139 case HLUA_E_AGAIN:
Thierry Fournier0164f202016-02-20 17:47:43 +010010140 if (hlua->wake_time != TICK_ETERNITY)
Willy Tarreaue23f33b2022-05-06 14:07:13 +020010141 task_schedule(tcp_ctx->task, hlua->wake_time);
Christopher Faulet31572222023-03-31 11:13:48 +020010142 break;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010143
10144 /* finished with error. */
10145 case HLUA_E_ERRMSG:
10146 /* Display log. */
10147 SEND_ERR(px, "Lua applet tcp '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010148 rule->arg.hlua_rule->fcn->name, lua_tostring(hlua->T, -1));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010149 lua_pop(hlua->T, 1);
10150 goto error;
10151
Thierry Fournierd5b073c2018-05-21 19:42:47 +020010152 case HLUA_E_ETMOUT:
10153 SEND_ERR(px, "Lua applet tcp '%s': execution timeout.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010154 rule->arg.hlua_rule->fcn->name);
Thierry Fournierd5b073c2018-05-21 19:42:47 +020010155 goto error;
10156
10157 case HLUA_E_NOMEM:
10158 SEND_ERR(px, "Lua applet tcp '%s': out of memory error.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010159 rule->arg.hlua_rule->fcn->name);
Thierry Fournierd5b073c2018-05-21 19:42:47 +020010160 goto error;
10161
10162 case HLUA_E_YIELD: /* unexpected */
10163 SEND_ERR(px, "Lua applet tcp '%s': yield not allowed.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010164 rule->arg.hlua_rule->fcn->name);
Thierry Fournierd5b073c2018-05-21 19:42:47 +020010165 goto error;
10166
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010167 case HLUA_E_ERR:
10168 /* Display log. */
10169 SEND_ERR(px, "Lua applet tcp '%s' return an unknown error.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010170 rule->arg.hlua_rule->fcn->name);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010171 goto error;
10172
10173 default:
10174 goto error;
10175 }
10176
Christopher Faulet31572222023-03-31 11:13:48 +020010177out:
10178 /* eat the whole request */
10179 co_skip(sc_oc(sc), co_data(sc_oc(sc)));
10180 return;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010181
Christopher Faulet31572222023-03-31 11:13:48 +020010182error:
10183 se_fl_set(ctx->sedesc, SE_FL_ERROR);
Willy Tarreaue23f33b2022-05-06 14:07:13 +020010184 tcp_ctx->flags |= APPLET_DONE;
Christopher Faulet31572222023-03-31 11:13:48 +020010185 goto out;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010186}
10187
10188static void hlua_applet_tcp_release(struct appctx *ctx)
10189{
Willy Tarreaue23f33b2022-05-06 14:07:13 +020010190 struct hlua_tcp_ctx *tcp_ctx = ctx->svcctx;
10191
10192 task_destroy(tcp_ctx->task);
10193 tcp_ctx->task = NULL;
10194 hlua_ctx_destroy(tcp_ctx->hlua);
10195 tcp_ctx->hlua = NULL;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010196}
10197
Christopher Fauletc9929382022-05-12 11:52:27 +020010198/* The function returns 0 if the initialisation is complete or -1 if
10199 * an errors occurs. It also reserves the appctx for an hlua_http_ctx.
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010200 */
Christopher Faulet4aa1d282022-01-13 16:01:35 +010010201static int hlua_applet_http_init(struct appctx *ctx)
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010202{
Willy Tarreauaa229cc2022-05-06 14:26:10 +020010203 struct hlua_http_ctx *http_ctx = applet_reserve_svcctx(ctx, sizeof(*http_ctx));
Willy Tarreauc12b3212022-05-27 11:08:15 +020010204 struct stconn *sc = appctx_sc(ctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +020010205 struct stream *strm = __sc_strm(sc);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010206 struct http_txn *txn;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +010010207 struct hlua *hlua;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010208 char **arg;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010209 struct task *task;
Thierry Fournierfd107a22016-02-19 19:57:23 +010010210 const char *error;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010211
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010212 txn = strm->txn;
Willy Tarreaubafbe012017-11-24 17:34:44 +010010213 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +010010214 if (!hlua) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +010010215 SEND_ERR(strm->be, "Lua applet http '%s': out of memory.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010216 ctx->rule->arg.hlua_rule->fcn->name);
Christopher Fauletc9929382022-05-12 11:52:27 +020010217 return -1;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +010010218 }
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010219 HLUA_INIT(hlua);
Willy Tarreauaa229cc2022-05-06 14:26:10 +020010220 http_ctx->hlua = hlua;
10221 http_ctx->left_bytes = -1;
10222 http_ctx->flags = 0;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010223
Thierry FOURNIERd93ea2b2015-12-20 19:14:52 +010010224 if (txn->req.flags & HTTP_MSGF_VER_11)
Willy Tarreauaa229cc2022-05-06 14:26:10 +020010225 http_ctx->flags |= APPLET_HTTP11;
Thierry FOURNIERd93ea2b2015-12-20 19:14:52 +010010226
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010227 /* Create task used by signal to wakeup applets. */
Willy Tarreaubeeabf52021-10-01 18:23:30 +020010228 task = task_new_here();
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010229 if (!task) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +010010230 SEND_ERR(strm->be, "Lua applet http '%s': out of memory.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010231 ctx->rule->arg.hlua_rule->fcn->name);
Christopher Fauletc9929382022-05-12 11:52:27 +020010232 return -1;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010233 }
10234 task->nice = 0;
10235 task->context = ctx;
10236 task->process = hlua_applet_wakeup;
Willy Tarreauaa229cc2022-05-06 14:26:10 +020010237 http_ctx->task = task;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010238
10239 /* In the execution wrappers linked with a stream, the
10240 * Lua context can be not initialized. This behavior
10241 * permits to save performances because a systematic
10242 * Lua initialization cause 5% performances loss.
10243 */
Aurelien DARRAGON6b0b9bd2023-03-21 14:02:16 +010010244 if (!hlua_ctx_init(hlua, fcn_ref_to_stack_id(ctx->rule->arg.hlua_rule->fcn), task)) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +010010245 SEND_ERR(strm->be, "Lua applet http '%s': can't initialize Lua context.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010246 ctx->rule->arg.hlua_rule->fcn->name);
Christopher Fauletc9929382022-05-12 11:52:27 +020010247 return -1;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010248 }
10249
10250 /* Set timeout according with the applet configuration. */
Aurelien DARRAGONda9503c2022-11-25 09:10:07 +010010251 hlua_timer_init(&hlua->timer, ctx->applet->timeout);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010252
10253 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010254 if (!SET_SAFE_LJMP(hlua)) {
Thierry Fournierfd107a22016-02-19 19:57:23 +010010255 if (lua_type(hlua->T, -1) == LUA_TSTRING)
10256 error = lua_tostring(hlua->T, -1);
10257 else
10258 error = "critical error";
Christopher Faulet4aa1d282022-01-13 16:01:35 +010010259 SEND_ERR(strm->be, "Lua applet http '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010260 ctx->rule->arg.hlua_rule->fcn->name, error);
Christopher Fauletc9929382022-05-12 11:52:27 +020010261 return -1;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010262 }
10263
10264 /* Check stack available size. */
10265 if (!lua_checkstack(hlua->T, 1)) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +010010266 SEND_ERR(strm->be, "Lua applet http '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010267 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010268 RESET_SAFE_LJMP(hlua);
Christopher Fauletc9929382022-05-12 11:52:27 +020010269 return -1;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010270 }
10271
10272 /* Restore the function in the stack. */
Aurelien DARRAGON4fdf8b52023-03-20 17:22:37 +010010273 hlua_pushref(hlua->T, ctx->rule->arg.hlua_rule->fcn->function_ref[hlua->state_id]);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010274
10275 /* Create and and push object stream in the stack. */
10276 if (!hlua_applet_http_new(hlua->T, ctx)) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +010010277 SEND_ERR(strm->be, "Lua applet http '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010278 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010279 RESET_SAFE_LJMP(hlua);
Christopher Fauletc9929382022-05-12 11:52:27 +020010280 return -1;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010281 }
10282 hlua->nargs = 1;
10283
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010284 /* push keywords in the stack. */
10285 for (arg = ctx->rule->arg.hlua_rule->args; arg && *arg; arg++) {
10286 if (!lua_checkstack(hlua->T, 1)) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +010010287 SEND_ERR(strm->be, "Lua applet http '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010288 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010289 RESET_SAFE_LJMP(hlua);
Christopher Fauletc9929382022-05-12 11:52:27 +020010290 return -1;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010291 }
10292 lua_pushstring(hlua->T, *arg);
10293 hlua->nargs++;
10294 }
10295
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010296 RESET_SAFE_LJMP(hlua);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010297
10298 /* Wakeup the applet when data is ready for read. */
Willy Tarreau90e8b452022-05-25 18:21:43 +020010299 applet_need_more_data(ctx);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010300
Christopher Fauletc9929382022-05-12 11:52:27 +020010301 return 0;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010302}
10303
Willy Tarreau60409db2019-08-21 14:14:50 +020010304void hlua_applet_http_fct(struct appctx *ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010305{
Willy Tarreauaa229cc2022-05-06 14:26:10 +020010306 struct hlua_http_ctx *http_ctx = ctx->svcctx;
Willy Tarreauc12b3212022-05-27 11:08:15 +020010307 struct stconn *sc = appctx_sc(ctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +020010308 struct stream *strm = __sc_strm(sc);
10309 struct channel *req = sc_oc(sc);
10310 struct channel *res = sc_ic(sc);
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010311 struct act_rule *rule = ctx->rule;
10312 struct proxy *px = strm->be;
Willy Tarreauaa229cc2022-05-06 14:26:10 +020010313 struct hlua *hlua = http_ctx->hlua;
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010314 struct htx *req_htx, *res_htx;
10315
10316 res_htx = htx_from_buf(&res->buf);
10317
Christopher Faulet31572222023-03-31 11:13:48 +020010318 if (unlikely(se_fl_test(ctx->sedesc, (SE_FL_EOS|SE_FL_ERROR|SE_FL_SHR|SE_FL_SHW))))
10319 goto out;
10320
10321 /* The applet execution is already done. */
10322 if (http_ctx->flags & APPLET_DONE)
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010323 goto out;
10324
Ilya Shipitsin856aabc2020-04-16 23:51:34 +050010325 /* Check if the input buffer is available. */
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010326 if (!b_size(&res->buf)) {
Willy Tarreau3e7be362022-05-27 10:35:27 +020010327 sc_need_room(sc);
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010328 goto out;
10329 }
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010330
10331 /* Set the currently running flag. */
10332 if (!HLUA_IS_RUNNING(hlua) &&
Willy Tarreauaa229cc2022-05-06 14:26:10 +020010333 !(http_ctx->flags & APPLET_DONE)) {
Christopher Fauletbd878d22021-04-28 10:50:21 +020010334 if (!co_data(req)) {
Willy Tarreau90e8b452022-05-25 18:21:43 +020010335 applet_need_more_data(ctx);
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010336 goto out;
10337 }
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010338 }
10339
Christopher Faulet31572222023-03-31 11:13:48 +020010340 /* Execute the function. */
10341 switch (hlua_ctx_resume(hlua, 1)) {
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010342 /* finished. */
10343 case HLUA_E_OK:
Willy Tarreauaa229cc2022-05-06 14:26:10 +020010344 http_ctx->flags |= APPLET_DONE;
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010345 break;
10346
10347 /* yield. */
10348 case HLUA_E_AGAIN:
10349 if (hlua->wake_time != TICK_ETERNITY)
Willy Tarreauaa229cc2022-05-06 14:26:10 +020010350 task_schedule(http_ctx->task, hlua->wake_time);
Christopher Faulet56a3d6e2019-02-27 22:06:23 +010010351 goto out;
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010352
10353 /* finished with error. */
10354 case HLUA_E_ERRMSG:
10355 /* Display log. */
10356 SEND_ERR(px, "Lua applet http '%s': %s.\n",
Christopher Faulet31572222023-03-31 11:13:48 +020010357 rule->arg.hlua_rule->fcn->name, lua_tostring(hlua->T, -1));
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010358 lua_pop(hlua->T, 1);
10359 goto error;
10360
10361 case HLUA_E_ETMOUT:
10362 SEND_ERR(px, "Lua applet http '%s': execution timeout.\n",
Christopher Faulet31572222023-03-31 11:13:48 +020010363 rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010364 goto error;
10365
10366 case HLUA_E_NOMEM:
10367 SEND_ERR(px, "Lua applet http '%s': out of memory error.\n",
Christopher Faulet31572222023-03-31 11:13:48 +020010368 rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010369 goto error;
10370
10371 case HLUA_E_YIELD: /* unexpected */
10372 SEND_ERR(px, "Lua applet http '%s': yield not allowed.\n",
Christopher Faulet31572222023-03-31 11:13:48 +020010373 rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010374 goto error;
10375
10376 case HLUA_E_ERR:
10377 /* Display log. */
10378 SEND_ERR(px, "Lua applet http '%s' return an unknown error.\n",
Christopher Faulet31572222023-03-31 11:13:48 +020010379 rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010380 goto error;
10381
10382 default:
10383 goto error;
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010384 }
10385
Willy Tarreauaa229cc2022-05-06 14:26:10 +020010386 if (http_ctx->flags & APPLET_DONE) {
10387 if (http_ctx->flags & APPLET_RSP_SENT)
Christopher Faulet31572222023-03-31 11:13:48 +020010388 goto out;
Christopher Faulet56a3d6e2019-02-27 22:06:23 +010010389
Willy Tarreauaa229cc2022-05-06 14:26:10 +020010390 if (!(http_ctx->flags & APPLET_HDR_SENT))
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010391 goto error;
10392
Christopher Fauletf89af9c2022-04-07 10:07:18 +020010393 /* no more data are expected. If the response buffer is empty
10394 * for a chunked message, be sure to add something (EOT block in
10395 * this case) to have something to send. It is important to be
10396 * sure the EOM flags will be handled by the endpoint.
10397 */
10398 if (htx_is_empty(res_htx) && (strm->txn->rsp.flags & (HTTP_MSGF_XFER_LEN|HTTP_MSGF_CNT_LEN)) == HTTP_MSGF_XFER_LEN) {
10399 if (!htx_add_endof(res_htx, HTX_BLK_EOT)) {
Willy Tarreau3e7be362022-05-27 10:35:27 +020010400 sc_need_room(sc);
Christopher Fauletf89af9c2022-04-07 10:07:18 +020010401 goto out;
10402 }
10403 channel_add_input(res, 1);
10404 }
10405
Christopher Fauletd1ac2b92020-12-02 19:12:22 +010010406 res_htx->flags |= HTX_FL_EOM;
Christopher Faulet31572222023-03-31 11:13:48 +020010407 se_fl_set(ctx->sedesc, SE_FL_EOI|SE_FL_EOS);
Willy Tarreauaa229cc2022-05-06 14:26:10 +020010408 strm->txn->status = http_ctx->status;
10409 http_ctx->flags |= APPLET_RSP_SENT;
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010410 }
10411
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010412 out:
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010413 htx_to_buf(res_htx, &res->buf);
Christopher Faulet31572222023-03-31 11:13:48 +020010414 /* eat the whole request */
10415 if (co_data(req)) {
10416 req_htx = htx_from_buf(&req->buf);
10417 co_htx_skip(req, req_htx, co_data(req));
10418 htx_to_buf(req_htx, &req->buf);
10419 }
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010420 return;
10421
10422 error:
10423
10424 /* If we are in HTTP mode, and we are not send any
10425 * data, return a 500 server error in best effort:
10426 * if there is no room available in the buffer,
10427 * just close the connection.
10428 */
Willy Tarreauaa229cc2022-05-06 14:26:10 +020010429 if (!(http_ctx->flags & APPLET_HDR_SENT)) {
Christopher Fauletf7346382019-07-17 22:02:08 +020010430 struct buffer *err = &http_err_chunks[HTTP_ERR_500];
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010431
10432 channel_erase(res);
10433 res->buf.data = b_data(err);
10434 memcpy(res->buf.area, b_head(err), b_data(err));
10435 res_htx = htx_from_buf(&res->buf);
Christopher Fauletf6cce3f2019-02-27 21:20:09 +010010436 channel_add_input(res, res_htx->data);
Christopher Faulet31572222023-03-31 11:13:48 +020010437 se_fl_set(ctx->sedesc, SE_FL_EOI|SE_FL_EOS);
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010438 }
Christopher Faulet31572222023-03-31 11:13:48 +020010439 else
10440 se_fl_set(ctx->sedesc, SE_FL_ERROR);
10441
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010442 if (!(strm->flags & SF_ERR_MASK))
10443 strm->flags |= SF_ERR_RESOURCE;
Willy Tarreauaa229cc2022-05-06 14:26:10 +020010444 http_ctx->flags |= APPLET_DONE;
Christopher Faulet31572222023-03-31 11:13:48 +020010445 goto out;
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010446}
10447
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010448static void hlua_applet_http_release(struct appctx *ctx)
10449{
Willy Tarreauaa229cc2022-05-06 14:26:10 +020010450 struct hlua_http_ctx *http_ctx = ctx->svcctx;
10451
10452 task_destroy(http_ctx->task);
10453 http_ctx->task = NULL;
10454 hlua_ctx_destroy(http_ctx->hlua);
10455 http_ctx->hlua = NULL;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010456}
10457
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +020010458/* global {tcp|http}-request parser. Return ACT_RET_PRS_OK in
Ilya Shipitsin856aabc2020-04-16 23:51:34 +050010459 * success case, else return ACT_RET_PRS_ERR.
Thierry FOURNIERbabae282015-09-17 11:36:37 +020010460 *
10461 * This function can fail with an abort() due to an Lua critical error.
10462 * We are in the configuration parsing process of HAProxy, this abort() is
10463 * tolerated.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +010010464 */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +020010465static enum act_parse_ret action_register_lua(const char **args, int *cur_arg, struct proxy *px,
10466 struct act_rule *rule, char **err)
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +010010467{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +020010468 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +010010469 int i;
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010470
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +020010471 /* Memory for the rule. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +020010472 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +020010473 if (!rule->arg.hlua_rule) {
10474 memprintf(err, "out of memory error");
Christopher Faulet528526f2021-04-12 14:37:32 +020010475 goto error;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +020010476 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +010010477
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +010010478 /* Memory for arguments. */
Tim Duesterhuse52b6e52020-09-12 20:26:43 +020010479 rule->arg.hlua_rule->args = calloc(fcn->nargs + 1,
10480 sizeof(*rule->arg.hlua_rule->args));
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +010010481 if (!rule->arg.hlua_rule->args) {
10482 memprintf(err, "out of memory error");
Christopher Faulet528526f2021-04-12 14:37:32 +020010483 goto error;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +010010484 }
10485
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +020010486 /* Reference the Lua function and store the reference. */
Thierry Fournierad5345f2020-11-29 02:05:57 +010010487 rule->arg.hlua_rule->fcn = fcn;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +020010488
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +010010489 /* Expect some arguments */
10490 for (i = 0; i < fcn->nargs; i++) {
Thierry FOURNIER1725c2e2019-01-06 19:38:49 +010010491 if (*args[*cur_arg] == '\0') {
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +010010492 memprintf(err, "expect %d arguments", fcn->nargs);
Christopher Faulet528526f2021-04-12 14:37:32 +020010493 goto error;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +010010494 }
Thierry FOURNIER1725c2e2019-01-06 19:38:49 +010010495 rule->arg.hlua_rule->args[i] = strdup(args[*cur_arg]);
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +010010496 if (!rule->arg.hlua_rule->args[i]) {
10497 memprintf(err, "out of memory error");
Christopher Faulet528526f2021-04-12 14:37:32 +020010498 goto error;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +010010499 }
10500 (*cur_arg)++;
10501 }
10502 rule->arg.hlua_rule->args[i] = NULL;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +020010503
Thierry FOURNIER42148732015-09-02 17:17:33 +020010504 rule->action = ACT_CUSTOM;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +020010505 rule->action_ptr = hlua_action;
Thierry FOURNIERafa80492015-08-19 09:04:15 +020010506 return ACT_RET_PRS_OK;
Christopher Faulet528526f2021-04-12 14:37:32 +020010507
10508 error:
10509 if (rule->arg.hlua_rule) {
10510 if (rule->arg.hlua_rule->args) {
10511 for (i = 0; i < fcn->nargs; i++)
10512 ha_free(&rule->arg.hlua_rule->args[i]);
10513 ha_free(&rule->arg.hlua_rule->args);
10514 }
10515 ha_free(&rule->arg.hlua_rule);
10516 }
10517 return ACT_RET_PRS_ERR;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +010010518}
10519
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010520static enum act_parse_ret action_register_service_http(const char **args, int *cur_arg, struct proxy *px,
10521 struct act_rule *rule, char **err)
10522{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +020010523 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010524
Thierry FOURNIER718e2a72015-12-20 20:13:14 +010010525 /* HTTP applets are forbidden in tcp-request rules.
Ilya Shipitsin856aabc2020-04-16 23:51:34 +050010526 * HTTP applet request requires everything initialized by
Thierry FOURNIER718e2a72015-12-20 20:13:14 +010010527 * "http_process_request" (analyzer flag AN_REQ_HTTP_INNER).
Ilya Shipitsin856aabc2020-04-16 23:51:34 +050010528 * The applet will be immediately initialized, but its before
Thierry FOURNIER718e2a72015-12-20 20:13:14 +010010529 * the call of this analyzer.
10530 */
10531 if (rule->from != ACT_F_HTTP_REQ) {
10532 memprintf(err, "HTTP applets are forbidden from 'tcp-request' rulesets");
10533 return ACT_RET_PRS_ERR;
10534 }
10535
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010536 /* Memory for the rule. */
10537 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
10538 if (!rule->arg.hlua_rule) {
10539 memprintf(err, "out of memory error");
10540 return ACT_RET_PRS_ERR;
10541 }
10542
10543 /* Reference the Lua function and store the reference. */
Thierry Fournierad5345f2020-11-29 02:05:57 +010010544 rule->arg.hlua_rule->fcn = fcn;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010545
10546 /* TODO: later accept arguments. */
10547 rule->arg.hlua_rule->args = NULL;
10548
10549 /* Add applet pointer in the rule. */
10550 rule->applet.obj_type = OBJ_TYPE_APPLET;
10551 rule->applet.name = fcn->name;
10552 rule->applet.init = hlua_applet_http_init;
10553 rule->applet.fct = hlua_applet_http_fct;
10554 rule->applet.release = hlua_applet_http_release;
10555 rule->applet.timeout = hlua_timeout_applet;
10556
10557 return ACT_RET_PRS_OK;
10558}
10559
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010560/* This function is an LUA binding used for registering
10561 * "sample-conv" functions. It expects a converter name used
10562 * in the haproxy configuration file, and an LUA function.
10563 */
10564__LJMP static int hlua_register_action(lua_State *L)
10565{
Christopher Faulet4fc9da02021-04-12 15:08:12 +020010566 struct action_kw_list *akl = NULL;
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010567 const char *name;
10568 int ref;
10569 int len;
Christopher Faulet4fc9da02021-04-12 15:08:12 +020010570 struct hlua_function *fcn = NULL;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +010010571 int nargs;
Thierry Fournierf67442e2020-11-28 20:41:07 +010010572 struct buffer *trash;
10573 struct action_kw *akw;
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010574
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +010010575 /* Initialise the number of expected arguments at 0. */
10576 nargs = 0;
10577
10578 if (lua_gettop(L) < 3 || lua_gettop(L) > 4)
10579 WILL_LJMP(luaL_error(L, "'register_action' needs between 3 and 4 arguments"));
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010580
Aurelien DARRAGON87f52972023-02-24 09:43:54 +010010581 if (hlua_gethlua(L)) {
10582 /* runtime processing */
10583 WILL_LJMP(luaL_error(L, "register_action: not available outside of body context"));
10584 }
10585
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010586 /* First argument : converter name. */
10587 name = MAY_LJMP(luaL_checkstring(L, 1));
10588
10589 /* Second argument : environment. */
10590 if (lua_type(L, 2) != LUA_TTABLE)
10591 WILL_LJMP(luaL_error(L, "register_action: second argument must be a table of strings"));
10592
10593 /* Third argument : lua function. */
10594 ref = MAY_LJMP(hlua_checkfunction(L, 3));
10595
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -080010596 /* Fourth argument : number of mandatory arguments expected on the configuration line. */
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +010010597 if (lua_gettop(L) >= 4)
10598 nargs = MAY_LJMP(luaL_checkinteger(L, 4));
10599
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -080010600 /* browse the second argument as an array. */
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010601 lua_pushnil(L);
10602 while (lua_next(L, 2) != 0) {
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +010010603 if (lua_type(L, -1) != LUA_TSTRING) {
10604 hlua_unref(L, ref);
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010605 WILL_LJMP(luaL_error(L, "register_action: second argument must be a table of strings"));
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +010010606 }
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010607
Thierry Fournierf67442e2020-11-28 20:41:07 +010010608 /* Check if action exists */
10609 trash = get_trash_chunk();
10610 chunk_printf(trash, "lua.%s", name);
10611 if (strcmp(lua_tostring(L, -1), "tcp-req") == 0) {
10612 akw = tcp_req_cont_action(trash->area);
10613 } else if (strcmp(lua_tostring(L, -1), "tcp-res") == 0) {
10614 akw = tcp_res_cont_action(trash->area);
10615 } else if (strcmp(lua_tostring(L, -1), "http-req") == 0) {
10616 akw = action_http_req_custom(trash->area);
10617 } else if (strcmp(lua_tostring(L, -1), "http-res") == 0) {
10618 akw = action_http_res_custom(trash->area);
10619 } else {
10620 akw = NULL;
10621 }
10622 if (akw != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +010010623 fcn = akw->private;
10624 if (fcn->function_ref[hlua_state_id] != -1) {
10625 ha_warning("Trying to register action 'lua.%s' more than once. "
10626 "This will become a hard error in version 2.5.\n", name);
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +010010627 hlua_unref(L, fcn->function_ref[hlua_state_id]);
Thierry Fournier59f11be2020-11-29 00:37:41 +010010628 }
10629 fcn->function_ref[hlua_state_id] = ref;
10630
10631 /* pop the environment string. */
10632 lua_pop(L, 1);
10633 continue;
Thierry Fournierf67442e2020-11-28 20:41:07 +010010634 }
10635
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010636 /* Check required environment. Only accepted "http" or "tcp". */
10637 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +020010638 akl = calloc(1, sizeof(*akl) + sizeof(struct action_kw) * 2);
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010639 if (!akl)
Christopher Faulet4fc9da02021-04-12 15:08:12 +020010640 goto alloc_error;;
Thierry Fournier62a22aa2020-11-28 21:06:35 +010010641 fcn = new_hlua_function();
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010642 if (!fcn)
Christopher Faulet4fc9da02021-04-12 15:08:12 +020010643 goto alloc_error;
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010644
10645 /* Fill fcn. */
10646 fcn->name = strdup(name);
10647 if (!fcn->name)
Christopher Faulet4fc9da02021-04-12 15:08:12 +020010648 goto alloc_error;
Thierry Fournierc7492592020-11-28 23:57:24 +010010649 fcn->function_ref[hlua_state_id] = ref;
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010650
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -070010651 /* Set the expected number of arguments. */
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +010010652 fcn->nargs = nargs;
10653
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010654 /* List head */
10655 akl->list.n = akl->list.p = NULL;
10656
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010657 /* action keyword. */
10658 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +020010659 akl->kw[0].kw = calloc(1, len);
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010660 if (!akl->kw[0].kw)
Christopher Faulet4fc9da02021-04-12 15:08:12 +020010661 goto alloc_error;
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010662
10663 snprintf((char *)akl->kw[0].kw, len, "lua.%s", name);
10664
Amaury Denoyellee4a617c2021-05-06 15:33:09 +020010665 akl->kw[0].flags = 0;
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010666 akl->kw[0].private = fcn;
10667 akl->kw[0].parse = action_register_lua;
10668
10669 /* select the action registering point. */
10670 if (strcmp(lua_tostring(L, -1), "tcp-req") == 0)
10671 tcp_req_cont_keywords_register(akl);
10672 else if (strcmp(lua_tostring(L, -1), "tcp-res") == 0)
10673 tcp_res_cont_keywords_register(akl);
10674 else if (strcmp(lua_tostring(L, -1), "http-req") == 0)
10675 http_req_keywords_register(akl);
10676 else if (strcmp(lua_tostring(L, -1), "http-res") == 0)
10677 http_res_keywords_register(akl);
Christopher Faulet4fc9da02021-04-12 15:08:12 +020010678 else {
10679 release_hlua_function(fcn);
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +010010680 hlua_unref(L, ref);
Christopher Faulet4fc9da02021-04-12 15:08:12 +020010681 if (akl)
10682 ha_free((char **)&(akl->kw[0].kw));
10683 ha_free(&akl);
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +010010684 WILL_LJMP(luaL_error(L, "Lua action environment '%s' is unknown. "
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010685 "'tcp-req', 'tcp-res', 'http-req' or 'http-res' "
10686 "are expected.", lua_tostring(L, -1)));
Christopher Faulet4fc9da02021-04-12 15:08:12 +020010687 }
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010688
10689 /* pop the environment string. */
10690 lua_pop(L, 1);
Christopher Faulet4fc9da02021-04-12 15:08:12 +020010691
10692 /* reset for next loop */
10693 akl = NULL;
10694 fcn = NULL;
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010695 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010696 return ACT_RET_PRS_OK;
Christopher Faulet4fc9da02021-04-12 15:08:12 +020010697
10698 alloc_error:
10699 release_hlua_function(fcn);
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +010010700 hlua_unref(L, ref);
Christopher Faulet4fc9da02021-04-12 15:08:12 +020010701 ha_free(&akl);
10702 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
10703 return 0; /* Never reached */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010704}
10705
10706static enum act_parse_ret action_register_service_tcp(const char **args, int *cur_arg, struct proxy *px,
10707 struct act_rule *rule, char **err)
10708{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +020010709 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010710
Christopher Faulet280f85b2019-07-15 15:02:04 +020010711 if (px->mode == PR_MODE_HTTP) {
10712 memprintf(err, "Lua TCP services cannot be used on HTTP proxies");
Christopher Fauletafd8f102018-11-08 11:34:21 +010010713 return ACT_RET_PRS_ERR;
10714 }
10715
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010716 /* Memory for the rule. */
10717 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
10718 if (!rule->arg.hlua_rule) {
10719 memprintf(err, "out of memory error");
10720 return ACT_RET_PRS_ERR;
10721 }
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010722
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010723 /* Reference the Lua function and store the reference. */
Thierry Fournierad5345f2020-11-29 02:05:57 +010010724 rule->arg.hlua_rule->fcn = fcn;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010725
10726 /* TODO: later accept arguments. */
10727 rule->arg.hlua_rule->args = NULL;
10728
10729 /* Add applet pointer in the rule. */
10730 rule->applet.obj_type = OBJ_TYPE_APPLET;
10731 rule->applet.name = fcn->name;
10732 rule->applet.init = hlua_applet_tcp_init;
10733 rule->applet.fct = hlua_applet_tcp_fct;
10734 rule->applet.release = hlua_applet_tcp_release;
10735 rule->applet.timeout = hlua_timeout_applet;
10736
10737 return 0;
10738}
10739
10740/* This function is an LUA binding used for registering
10741 * "sample-conv" functions. It expects a converter name used
10742 * in the haproxy configuration file, and an LUA function.
10743 */
10744__LJMP static int hlua_register_service(lua_State *L)
10745{
10746 struct action_kw_list *akl;
10747 const char *name;
10748 const char *env;
10749 int ref;
10750 int len;
Christopher Faulet5c028d72021-04-12 15:11:44 +020010751 struct hlua_function *fcn = NULL;
Thierry Fournierf67442e2020-11-28 20:41:07 +010010752 struct buffer *trash;
10753 struct action_kw *akw;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010754
10755 MAY_LJMP(check_args(L, 3, "register_service"));
10756
Aurelien DARRAGON87f52972023-02-24 09:43:54 +010010757 if (hlua_gethlua(L)) {
10758 /* runtime processing */
10759 WILL_LJMP(luaL_error(L, "register_service: not available outside of body context"));
10760 }
10761
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010762 /* First argument : converter name. */
10763 name = MAY_LJMP(luaL_checkstring(L, 1));
10764
10765 /* Second argument : environment. */
10766 env = MAY_LJMP(luaL_checkstring(L, 2));
10767
10768 /* Third argument : lua function. */
10769 ref = MAY_LJMP(hlua_checkfunction(L, 3));
10770
Thierry Fournierf67442e2020-11-28 20:41:07 +010010771 /* Check for service already registered */
10772 trash = get_trash_chunk();
10773 chunk_printf(trash, "lua.%s", name);
10774 akw = service_find(trash->area);
10775 if (akw != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +010010776 fcn = akw->private;
10777 if (fcn->function_ref[hlua_state_id] != -1) {
10778 ha_warning("Trying to register service 'lua.%s' more than once. "
10779 "This will become a hard error in version 2.5.\n", name);
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +010010780 hlua_unref(L, fcn->function_ref[hlua_state_id]);
Thierry Fournier59f11be2020-11-29 00:37:41 +010010781 }
10782 fcn->function_ref[hlua_state_id] = ref;
10783 return 0;
Thierry Fournierf67442e2020-11-28 20:41:07 +010010784 }
10785
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010786 /* Allocate and fill the sample fetch keyword struct. */
10787 akl = calloc(1, sizeof(*akl) + sizeof(struct action_kw) * 2);
10788 if (!akl)
Christopher Faulet5c028d72021-04-12 15:11:44 +020010789 goto alloc_error;
Thierry Fournier62a22aa2020-11-28 21:06:35 +010010790 fcn = new_hlua_function();
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010791 if (!fcn)
Christopher Faulet5c028d72021-04-12 15:11:44 +020010792 goto alloc_error;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010793
10794 /* Fill fcn. */
10795 len = strlen("<lua.>") + strlen(name) + 1;
10796 fcn->name = calloc(1, len);
10797 if (!fcn->name)
Christopher Faulet5c028d72021-04-12 15:11:44 +020010798 goto alloc_error;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010799 snprintf((char *)fcn->name, len, "<lua.%s>", name);
Thierry Fournierc7492592020-11-28 23:57:24 +010010800 fcn->function_ref[hlua_state_id] = ref;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010801
10802 /* List head */
10803 akl->list.n = akl->list.p = NULL;
10804
10805 /* converter keyword. */
10806 len = strlen("lua.") + strlen(name) + 1;
10807 akl->kw[0].kw = calloc(1, len);
10808 if (!akl->kw[0].kw)
Christopher Faulet5c028d72021-04-12 15:11:44 +020010809 goto alloc_error;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010810
10811 snprintf((char *)akl->kw[0].kw, len, "lua.%s", name);
10812
Thierry FOURNIER / OZON.IO02564fd2016-11-12 11:07:05 +010010813 /* Check required environment. Only accepted "http" or "tcp". */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010814 if (strcmp(env, "tcp") == 0)
10815 akl->kw[0].parse = action_register_service_tcp;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010816 else if (strcmp(env, "http") == 0)
10817 akl->kw[0].parse = action_register_service_http;
Christopher Faulet5c028d72021-04-12 15:11:44 +020010818 else {
10819 release_hlua_function(fcn);
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +010010820 hlua_unref(L, ref);
Christopher Faulet5c028d72021-04-12 15:11:44 +020010821 if (akl)
10822 ha_free((char **)&(akl->kw[0].kw));
10823 ha_free(&akl);
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +010010824 WILL_LJMP(luaL_error(L, "Lua service environment '%s' is unknown. "
Eric Salamafe7456f2017-12-21 14:30:07 +010010825 "'tcp' or 'http' are expected.", env));
Christopher Faulet5c028d72021-04-12 15:11:44 +020010826 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010827
Amaury Denoyellee4a617c2021-05-06 15:33:09 +020010828 akl->kw[0].flags = 0;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010829 akl->kw[0].private = fcn;
10830
10831 /* End of array. */
10832 memset(&akl->kw[1], 0, sizeof(*akl->kw));
10833
10834 /* Register this new converter */
10835 service_keywords_register(akl);
10836
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010837 return 0;
Christopher Faulet5c028d72021-04-12 15:11:44 +020010838
10839 alloc_error:
10840 release_hlua_function(fcn);
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +010010841 hlua_unref(L, ref);
Christopher Faulet5c028d72021-04-12 15:11:44 +020010842 ha_free(&akl);
10843 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
10844 return 0; /* Never reached */
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010845}
10846
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010847/* This function initialises Lua cli handler. It copies the
10848 * arguments in the Lua stack and create channel IO objects.
10849 */
Aurélien Nephtaliabbf6072018-04-18 13:26:46 +020010850static int hlua_cli_parse_fct(char **args, char *payload, struct appctx *appctx, void *private)
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010851{
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010852 struct hlua_cli_ctx *ctx = applet_reserve_svcctx(appctx, sizeof(*ctx));
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010853 struct hlua *hlua;
10854 struct hlua_function *fcn;
10855 int i;
10856 const char *error;
10857
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010858 fcn = private;
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010859 ctx->fcn = private;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +010010860
Willy Tarreaubafbe012017-11-24 17:34:44 +010010861 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +010010862 if (!hlua) {
10863 SEND_ERR(NULL, "Lua cli '%s': out of memory.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +010010864 return 1;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +010010865 }
10866 HLUA_INIT(hlua);
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010867 ctx->hlua = hlua;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010868
10869 /* Create task used by signal to wakeup applets.
Ilya Shipitsind4259502020-04-08 01:07:56 +050010870 * We use the same wakeup function than the Lua applet_tcp and
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010871 * applet_http. It is absolutely compatible.
10872 */
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010873 ctx->task = task_new_here();
10874 if (!ctx->task) {
Thierry FOURNIERffbf5692016-12-16 11:14:06 +010010875 SEND_ERR(NULL, "Lua cli '%s': out of memory.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +010010876 goto error;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010877 }
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010878 ctx->task->nice = 0;
10879 ctx->task->context = appctx;
10880 ctx->task->process = hlua_applet_wakeup;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010881
10882 /* Initialises the Lua context */
Aurelien DARRAGON6b0b9bd2023-03-21 14:02:16 +010010883 if (!hlua_ctx_init(hlua, fcn_ref_to_stack_id(fcn), ctx->task)) {
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010884 SEND_ERR(NULL, "Lua cli '%s': can't initialize Lua context.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +010010885 goto error;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010886 }
10887
10888 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010889 if (!SET_SAFE_LJMP(hlua)) {
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010890 if (lua_type(hlua->T, -1) == LUA_TSTRING)
10891 error = lua_tostring(hlua->T, -1);
10892 else
10893 error = "critical error";
10894 SEND_ERR(NULL, "Lua cli '%s': %s.\n", fcn->name, error);
10895 goto error;
10896 }
10897
10898 /* Check stack available size. */
10899 if (!lua_checkstack(hlua->T, 2)) {
10900 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
10901 goto error;
10902 }
10903
10904 /* Restore the function in the stack. */
Aurelien DARRAGON4fdf8b52023-03-20 17:22:37 +010010905 hlua_pushref(hlua->T, fcn->function_ref[hlua->state_id]);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010906
10907 /* Once the arguments parsed, the CLI is like an AppletTCP,
10908 * so push AppletTCP in the stack.
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010909 */
10910 if (!hlua_applet_tcp_new(hlua->T, appctx)) {
10911 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
10912 goto error;
10913 }
10914 hlua->nargs = 1;
10915
10916 /* push keywords in the stack. */
10917 for (i = 0; *args[i]; i++) {
10918 /* Check stack available size. */
10919 if (!lua_checkstack(hlua->T, 1)) {
10920 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
10921 goto error;
10922 }
10923 lua_pushstring(hlua->T, args[i]);
10924 hlua->nargs++;
10925 }
10926
10927 /* We must initialize the execution timeouts. */
Aurelien DARRAGONda9503c2022-11-25 09:10:07 +010010928 hlua_timer_init(&hlua->timer, hlua_timeout_session);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010929
10930 /* At this point the execution is safe. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010931 RESET_SAFE_LJMP(hlua);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010932
10933 /* It's ok */
10934 return 0;
10935
10936 /* It's not ok. */
10937error:
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010938 RESET_SAFE_LJMP(hlua);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010939 hlua_ctx_destroy(hlua);
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010940 ctx->hlua = NULL;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010941 return 1;
10942}
10943
10944static int hlua_cli_io_handler_fct(struct appctx *appctx)
10945{
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010946 struct hlua_cli_ctx *ctx = appctx->svcctx;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010947 struct hlua *hlua;
Willy Tarreau475e4632022-05-27 10:26:46 +020010948 struct stconn *sc;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010949 struct hlua_function *fcn;
10950
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010951 hlua = ctx->hlua;
Willy Tarreauc12b3212022-05-27 11:08:15 +020010952 sc = appctx_sc(appctx);
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010953 fcn = ctx->fcn;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010954
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010955 /* Execute the function. */
10956 switch (hlua_ctx_resume(hlua, 1)) {
10957
10958 /* finished. */
10959 case HLUA_E_OK:
10960 return 1;
10961
10962 /* yield. */
10963 case HLUA_E_AGAIN:
10964 /* We want write. */
10965 if (HLUA_IS_WAKERESWR(hlua))
Willy Tarreau475e4632022-05-27 10:26:46 +020010966 sc_need_room(sc);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010967 /* Set the timeout. */
10968 if (hlua->wake_time != TICK_ETERNITY)
10969 task_schedule(hlua->task, hlua->wake_time);
10970 return 0;
10971
10972 /* finished with error. */
10973 case HLUA_E_ERRMSG:
10974 /* Display log. */
10975 SEND_ERR(NULL, "Lua cli '%s': %s.\n",
10976 fcn->name, lua_tostring(hlua->T, -1));
10977 lua_pop(hlua->T, 1);
10978 return 1;
10979
Thierry Fournierd5b073c2018-05-21 19:42:47 +020010980 case HLUA_E_ETMOUT:
10981 SEND_ERR(NULL, "Lua converter '%s': execution timeout.\n",
10982 fcn->name);
10983 return 1;
10984
10985 case HLUA_E_NOMEM:
10986 SEND_ERR(NULL, "Lua converter '%s': out of memory error.\n",
10987 fcn->name);
10988 return 1;
10989
10990 case HLUA_E_YIELD: /* unexpected */
10991 SEND_ERR(NULL, "Lua converter '%s': yield not allowed.\n",
10992 fcn->name);
10993 return 1;
10994
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010995 case HLUA_E_ERR:
10996 /* Display log. */
10997 SEND_ERR(NULL, "Lua cli '%s' return an unknown error.\n",
10998 fcn->name);
10999 return 1;
11000
11001 default:
11002 return 1;
11003 }
11004
11005 return 1;
11006}
11007
11008static void hlua_cli_io_release_fct(struct appctx *appctx)
11009{
Willy Tarreaubcda5f62022-05-03 18:13:39 +020011010 struct hlua_cli_ctx *ctx = appctx->svcctx;
11011
11012 hlua_ctx_destroy(ctx->hlua);
11013 ctx->hlua = NULL;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011014}
11015
11016/* This function is an LUA binding used for registering
11017 * new keywords in the cli. It expects a list of keywords
11018 * which are the "path". It is limited to 5 keywords. A
11019 * description of the command, a function to be executed
11020 * for the parsing and a function for io handlers.
11021 */
11022__LJMP static int hlua_register_cli(lua_State *L)
11023{
11024 struct cli_kw_list *cli_kws;
11025 const char *message;
11026 int ref_io;
11027 int len;
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020011028 struct hlua_function *fcn = NULL;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011029 int index;
11030 int i;
Thierry Fournierf67442e2020-11-28 20:41:07 +010011031 struct buffer *trash;
11032 const char *kw[5];
11033 struct cli_kw *cli_kw;
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020011034 const char *errmsg;
Willy Tarreau22450af2023-04-07 15:27:55 +020011035 char *end;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011036
11037 MAY_LJMP(check_args(L, 3, "register_cli"));
11038
Aurelien DARRAGON87f52972023-02-24 09:43:54 +010011039 if (hlua_gethlua(L)) {
11040 /* runtime processing */
11041 WILL_LJMP(luaL_error(L, "register_cli: not available outside of body context"));
11042 }
11043
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011044 /* First argument : an array of maximum 5 keywords. */
11045 if (!lua_istable(L, 1))
11046 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table"));
11047
11048 /* Second argument : string with contextual message. */
11049 message = MAY_LJMP(luaL_checkstring(L, 2));
11050
11051 /* Third and fourth argument : lua function. */
11052 ref_io = MAY_LJMP(hlua_checkfunction(L, 3));
11053
Thierry Fournierf67442e2020-11-28 20:41:07 +010011054 /* Check for CLI service already registered */
11055 trash = get_trash_chunk();
11056 index = 0;
11057 lua_pushnil(L);
11058 memset(kw, 0, sizeof(kw));
11059 while (lua_next(L, 1) != 0) {
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +010011060 if (index >= CLI_PREFIX_KW_NB) {
11061 hlua_unref(L, ref_io);
Thierry Fournierf67442e2020-11-28 20:41:07 +010011062 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 +010011063 }
11064 if (lua_type(L, -1) != LUA_TSTRING) {
11065 hlua_unref(L, ref_io);
Thierry Fournierf67442e2020-11-28 20:41:07 +010011066 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table filled with strings"));
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +010011067 }
Thierry Fournierf67442e2020-11-28 20:41:07 +010011068 kw[index] = lua_tostring(L, -1);
11069 if (index == 0)
11070 chunk_printf(trash, "%s", kw[index]);
11071 else
11072 chunk_appendf(trash, " %s", kw[index]);
11073 index++;
11074 lua_pop(L, 1);
11075 }
11076 cli_kw = cli_find_kw_exact((char **)kw);
11077 if (cli_kw != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +010011078 fcn = cli_kw->private;
11079 if (fcn->function_ref[hlua_state_id] != -1) {
11080 ha_warning("Trying to register CLI keyword 'lua.%s' more than once. "
11081 "This will become a hard error in version 2.5.\n", trash->area);
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +010011082 hlua_unref(L, fcn->function_ref[hlua_state_id]);
Thierry Fournier59f11be2020-11-29 00:37:41 +010011083 }
11084 fcn->function_ref[hlua_state_id] = ref_io;
11085 return 0;
Thierry Fournierf67442e2020-11-28 20:41:07 +010011086 }
11087
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011088 /* Allocate and fill the sample fetch keyword struct. */
11089 cli_kws = calloc(1, sizeof(*cli_kws) + sizeof(struct cli_kw) * 2);
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020011090 if (!cli_kws) {
11091 errmsg = "Lua out of memory error.";
11092 goto error;
11093 }
Thierry Fournier62a22aa2020-11-28 21:06:35 +010011094 fcn = new_hlua_function();
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020011095 if (!fcn) {
11096 errmsg = "Lua out of memory error.";
11097 goto error;
11098 }
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011099
11100 /* Fill path. */
11101 index = 0;
11102 lua_pushnil(L);
11103 while(lua_next(L, 1) != 0) {
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020011104 if (index >= 5) {
11105 errmsg = "1st argument must be a table with a maximum of 5 entries";
11106 goto error;
11107 }
11108 if (lua_type(L, -1) != LUA_TSTRING) {
11109 errmsg = "1st argument must be a table filled with strings";
11110 goto error;
11111 }
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011112 cli_kws->kw[0].str_kw[index] = strdup(lua_tostring(L, -1));
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020011113 if (!cli_kws->kw[0].str_kw[index]) {
11114 errmsg = "Lua out of memory error.";
11115 goto error;
11116 }
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011117 index++;
11118 lua_pop(L, 1);
11119 }
11120
11121 /* Copy help message. */
11122 cli_kws->kw[0].usage = strdup(message);
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020011123 if (!cli_kws->kw[0].usage) {
11124 errmsg = "Lua out of memory error.";
11125 goto error;
11126 }
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011127
11128 /* Fill fcn io handler. */
11129 len = strlen("<lua.cli>") + 1;
11130 for (i = 0; i < index; i++)
11131 len += strlen(cli_kws->kw[0].str_kw[i]) + 1;
11132 fcn->name = calloc(1, len);
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020011133 if (!fcn->name) {
11134 errmsg = "Lua out of memory error.";
11135 goto error;
11136 }
Willy Tarreau22450af2023-04-07 15:27:55 +020011137
11138 end = fcn->name;
11139 len = 8;
11140 memcpy(end, "<lua.cli", len);
11141 end += len;
11142
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011143 for (i = 0; i < index; i++) {
Willy Tarreau22450af2023-04-07 15:27:55 +020011144 *(end++) = '.';
11145 len = strlen(cli_kws->kw[0].str_kw[i]);
11146 memcpy(end, cli_kws->kw[0].str_kw[i], len);
11147 end += len;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011148 }
Willy Tarreau22450af2023-04-07 15:27:55 +020011149 *(end++) = '>';
11150 *(end++) = 0;
11151
Thierry Fournierc7492592020-11-28 23:57:24 +010011152 fcn->function_ref[hlua_state_id] = ref_io;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011153
11154 /* Fill last entries. */
11155 cli_kws->kw[0].private = fcn;
11156 cli_kws->kw[0].parse = hlua_cli_parse_fct;
11157 cli_kws->kw[0].io_handler = hlua_cli_io_handler_fct;
11158 cli_kws->kw[0].io_release = hlua_cli_io_release_fct;
11159
11160 /* Register this new converter */
11161 cli_register_kw(cli_kws);
11162
11163 return 0;
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020011164
11165 error:
11166 release_hlua_function(fcn);
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +010011167 hlua_unref(L, ref_io);
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020011168 if (cli_kws) {
11169 for (i = 0; i < index; i++)
11170 ha_free((char **)&(cli_kws->kw[0].str_kw[i]));
11171 ha_free((char **)&(cli_kws->kw[0].usage));
11172 }
11173 ha_free(&cli_kws);
11174 WILL_LJMP(luaL_error(L, errmsg));
11175 return 0; /* Never reached */
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011176}
11177
Christopher Faulet69c581a2021-05-31 08:54:04 +020011178static int hlua_filter_init_per_thread(struct proxy *px, struct flt_conf *fconf)
11179{
11180 struct hlua_flt_config *conf = fconf->conf;
11181 lua_State *L;
11182 int error, pos, state_id, flt_ref;
11183
11184 state_id = reg_flt_to_stack_id(conf->reg);
11185 L = hlua_states[state_id];
11186 pos = lua_gettop(L);
11187
11188 /* The filter parsing function */
Aurelien DARRAGON4fdf8b52023-03-20 17:22:37 +010011189 hlua_pushref(L, conf->reg->fun_ref[state_id]);
Christopher Faulet69c581a2021-05-31 08:54:04 +020011190
11191 /* Push the filter class on the stack and resolve all callbacks */
Aurelien DARRAGON4fdf8b52023-03-20 17:22:37 +010011192 hlua_pushref(L, conf->reg->flt_ref[state_id]);
Christopher Faulet69c581a2021-05-31 08:54:04 +020011193
11194 /* Duplicate the filter class so each filter will have its own copy */
11195 lua_newtable(L);
11196 lua_pushnil(L);
11197
11198 while (lua_next(L, pos+2)) {
11199 lua_pushvalue(L, -2);
11200 lua_insert(L, -2);
11201 lua_settable(L, -4);
11202 }
Aurelien DARRAGON73d1a982023-03-20 17:42:08 +010011203 flt_ref = hlua_ref(L);
Christopher Faulet69c581a2021-05-31 08:54:04 +020011204
11205 /* Remove the original lua filter class from the stack */
11206 lua_pop(L, 1);
11207
11208 /* Push the copy on the stack */
Aurelien DARRAGON4fdf8b52023-03-20 17:22:37 +010011209 hlua_pushref(L, flt_ref);
Christopher Faulet69c581a2021-05-31 08:54:04 +020011210
11211 /* extra args are pushed in a table */
11212 lua_newtable(L);
11213 for (pos = 0; conf->args[pos]; pos++) {
11214 /* Check stack available size. */
11215 if (!lua_checkstack(L, 1)) {
11216 ha_alert("Lua filter '%s' : Lua error : full stack.", conf->reg->name);
11217 goto error;
11218 }
11219 lua_pushstring(L, conf->args[pos]);
11220 lua_rawseti(L, -2, lua_rawlen(L, -2) + 1);
11221 }
11222
11223 error = lua_pcall(L, 2, LUA_MULTRET, 0);
11224 switch (error) {
11225 case LUA_OK:
11226 /* replace the filter ref */
11227 conf->ref[state_id] = flt_ref;
11228 break;
11229 case LUA_ERRRUN:
11230 ha_alert("Lua filter '%s' : runtime error : %s", conf->reg->name, lua_tostring(L, -1));
11231 goto error;
11232 case LUA_ERRMEM:
11233 ha_alert("Lua filter '%s' : out of memory error", conf->reg->name);
11234 goto error;
11235 case LUA_ERRERR:
11236 ha_alert("Lua filter '%s' : message handler error : %s", conf->reg->name, lua_tostring(L, -1));
11237 goto error;
11238#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM <= 503
11239 case LUA_ERRGCMM:
11240 ha_alert("Lua filter '%s' : garbage collector error : %s", conf->reg->name, lua_tostring(L, -1));
11241 goto error;
11242#endif
11243 default:
Ilya Shipitsinff0f2782021-08-22 22:18:07 +050011244 ha_alert("Lua filter '%s' : unknown error : %s", conf->reg->name, lua_tostring(L, -1));
Christopher Faulet69c581a2021-05-31 08:54:04 +020011245 goto error;
11246 }
11247
11248 lua_settop(L, 0);
11249 return 0;
11250
11251 error:
11252 lua_settop(L, 0);
11253 return -1;
11254}
11255
11256static void hlua_filter_deinit_per_thread(struct proxy *px, struct flt_conf *fconf)
11257{
11258 struct hlua_flt_config *conf = fconf->conf;
11259 lua_State *L;
11260 int state_id;
11261
11262 if (!conf)
11263 return;
11264
11265 state_id = reg_flt_to_stack_id(conf->reg);
11266 L = hlua_states[state_id];
Aurelien DARRAGONfde199d2023-03-20 15:09:33 +010011267 hlua_unref(L, conf->ref[state_id]);
Christopher Faulet69c581a2021-05-31 08:54:04 +020011268}
11269
11270static int hlua_filter_init(struct proxy *px, struct flt_conf *fconf)
11271{
11272 struct hlua_flt_config *conf = fconf->conf;
11273 int state_id = reg_flt_to_stack_id(conf->reg);
11274
11275 /* Rely on per-thread init for global scripts */
11276 if (!state_id)
11277 return hlua_filter_init_per_thread(px, fconf);
11278 return 0;
11279}
11280
11281static void hlua_filter_deinit(struct proxy *px, struct flt_conf *fconf)
11282{
11283
11284 if (fconf->conf) {
11285 struct hlua_flt_config *conf = fconf->conf;
11286 int state_id = reg_flt_to_stack_id(conf->reg);
11287 int pos;
11288
11289 /* Rely on per-thread deinit for global scripts */
11290 if (!state_id)
11291 hlua_filter_deinit_per_thread(px, fconf);
11292
11293 for (pos = 0; conf->args[pos]; pos++)
11294 free(conf->args[pos]);
11295 free(conf->args);
11296 }
11297 ha_free(&fconf->conf);
11298 ha_free((char **)&fconf->id);
11299 ha_free(&fconf->ops);
11300}
11301
11302static int hlua_filter_new(struct stream *s, struct filter *filter)
11303{
11304 struct hlua_flt_config *conf = FLT_CONF(filter);
11305 struct hlua_flt_ctx *flt_ctx = NULL;
11306 int ret = 1;
11307
11308 /* In the execution wrappers linked with a stream, the
11309 * Lua context can be not initialized. This behavior
11310 * permits to save performances because a systematic
11311 * Lua initialization cause 5% performances loss.
11312 */
11313 if (!s->hlua) {
11314 struct hlua *hlua;
11315
11316 hlua = pool_alloc(pool_head_hlua);
11317 if (!hlua) {
11318 SEND_ERR(s->be, "Lua filter '%s': can't initialize Lua context.\n",
11319 conf->reg->name);
11320 ret = 0;
11321 goto end;
11322 }
11323 HLUA_INIT(hlua);
11324 s->hlua = hlua;
Aurelien DARRAGON6b0b9bd2023-03-21 14:02:16 +010011325 if (!hlua_ctx_init(s->hlua, reg_flt_to_stack_id(conf->reg), s->task)) {
Christopher Faulet69c581a2021-05-31 08:54:04 +020011326 SEND_ERR(s->be, "Lua filter '%s': can't initialize Lua context.\n",
11327 conf->reg->name);
11328 ret = 0;
11329 goto end;
11330 }
11331 }
11332
11333 flt_ctx = pool_zalloc(pool_head_hlua_flt_ctx);
11334 if (!flt_ctx) {
11335 SEND_ERR(s->be, "Lua filter '%s': can't initialize filter Lua context.\n",
11336 conf->reg->name);
11337 ret = 0;
11338 goto end;
11339 }
11340 flt_ctx->hlua[0] = pool_alloc(pool_head_hlua);
11341 flt_ctx->hlua[1] = pool_alloc(pool_head_hlua);
11342 if (!flt_ctx->hlua[0] || !flt_ctx->hlua[1]) {
11343 SEND_ERR(s->be, "Lua filter '%s': can't initialize filter Lua context.\n",
11344 conf->reg->name);
11345 ret = 0;
11346 goto end;
11347 }
11348 HLUA_INIT(flt_ctx->hlua[0]);
11349 HLUA_INIT(flt_ctx->hlua[1]);
Aurelien DARRAGON6b0b9bd2023-03-21 14:02:16 +010011350 if (!hlua_ctx_init(flt_ctx->hlua[0], reg_flt_to_stack_id(conf->reg), s->task) ||
11351 !hlua_ctx_init(flt_ctx->hlua[1], reg_flt_to_stack_id(conf->reg), s->task)) {
Christopher Faulet69c581a2021-05-31 08:54:04 +020011352 SEND_ERR(s->be, "Lua filter '%s': can't initialize filter Lua context.\n",
11353 conf->reg->name);
11354 ret = 0;
11355 goto end;
11356 }
11357
11358 if (!HLUA_IS_RUNNING(s->hlua)) {
11359 /* The following Lua calls can fail. */
11360 if (!SET_SAFE_LJMP(s->hlua)) {
11361 const char *error;
11362
11363 if (lua_type(s->hlua->T, -1) == LUA_TSTRING)
11364 error = lua_tostring(s->hlua->T, -1);
11365 else
11366 error = "critical error";
11367 SEND_ERR(s->be, "Lua filter '%s': %s.\n", conf->reg->name, error);
11368 ret = 0;
11369 goto end;
11370 }
11371
11372 /* Check stack size. */
11373 if (!lua_checkstack(s->hlua->T, 1)) {
11374 SEND_ERR(s->be, "Lua filter '%s': full stack.\n", conf->reg->name);
Tim Duesterhus22817382021-09-11 23:17:25 +020011375 RESET_SAFE_LJMP(s->hlua);
Christopher Faulet69c581a2021-05-31 08:54:04 +020011376 ret = 0;
11377 goto end;
11378 }
11379
Aurelien DARRAGON4fdf8b52023-03-20 17:22:37 +010011380 hlua_pushref(s->hlua->T, conf->ref[s->hlua->state_id]);
Christopher Faulet69c581a2021-05-31 08:54:04 +020011381 if (lua_getfield(s->hlua->T, -1, "new") != LUA_TFUNCTION) {
11382 SEND_ERR(s->be, "Lua filter '%s': 'new' field is not a function.\n",
11383 conf->reg->name);
11384 RESET_SAFE_LJMP(s->hlua);
11385 ret = 0;
11386 goto end;
11387 }
11388 lua_insert(s->hlua->T, -2);
11389
11390 /* Push the copy on the stack */
11391 s->hlua->nargs = 1;
11392
11393 /* We must initialize the execution timeouts. */
Aurelien DARRAGONda9503c2022-11-25 09:10:07 +010011394 hlua_timer_init(&s->hlua->timer, hlua_timeout_session);
Christopher Faulet69c581a2021-05-31 08:54:04 +020011395
11396 /* At this point the execution is safe. */
11397 RESET_SAFE_LJMP(s->hlua);
11398 }
11399
11400 switch (hlua_ctx_resume(s->hlua, 0)) {
11401 case HLUA_E_OK:
11402 /* Nothing returned or not a table, ignore the filter for current stream */
11403 if (!lua_gettop(s->hlua->T) || !lua_istable(s->hlua->T, 1)) {
11404 ret = 0;
11405 goto end;
11406 }
11407
11408 /* Attached the filter pointer to the ctx */
11409 lua_pushstring(s->hlua->T, "__filter");
11410 lua_pushlightuserdata(s->hlua->T, filter);
11411 lua_settable(s->hlua->T, -3);
11412
11413 /* Save a ref on the filter ctx */
11414 lua_pushvalue(s->hlua->T, 1);
Aurelien DARRAGON73d1a982023-03-20 17:42:08 +010011415 flt_ctx->ref = hlua_ref(s->hlua->T);
Christopher Faulet69c581a2021-05-31 08:54:04 +020011416 filter->ctx = flt_ctx;
11417 break;
11418 case HLUA_E_ERRMSG:
11419 SEND_ERR(s->be, "Lua filter '%s' : %s.\n", conf->reg->name, lua_tostring(s->hlua->T, -1));
11420 ret = -1;
11421 goto end;
11422 case HLUA_E_ETMOUT:
11423 SEND_ERR(s->be, "Lua filter '%s' : 'new' execution timeout.\n", conf->reg->name);
11424 ret = 0;
11425 goto end;
11426 case HLUA_E_NOMEM:
11427 SEND_ERR(s->be, "Lua filter '%s' : out of memory error.\n", conf->reg->name);
11428 ret = 0;
11429 goto end;
11430 case HLUA_E_AGAIN:
11431 case HLUA_E_YIELD:
11432 SEND_ERR(s->be, "Lua filter '%s': yield functions like core.tcp() or core.sleep()"
11433 " are not allowed from 'new' function.\n", conf->reg->name);
11434 ret = 0;
11435 goto end;
11436 case HLUA_E_ERR:
11437 SEND_ERR(s->be, "Lua filter '%s': 'new' returns an unknown error.\n", conf->reg->name);
11438 ret = 0;
11439 goto end;
11440 default:
11441 ret = 0;
11442 goto end;
11443 }
11444
11445 end:
11446 if (s->hlua)
11447 lua_settop(s->hlua->T, 0);
11448 if (ret <= 0) {
11449 if (flt_ctx) {
11450 hlua_ctx_destroy(flt_ctx->hlua[0]);
11451 hlua_ctx_destroy(flt_ctx->hlua[1]);
11452 pool_free(pool_head_hlua_flt_ctx, flt_ctx);
11453 }
11454 }
11455 return ret;
11456}
11457
11458static void hlua_filter_delete(struct stream *s, struct filter *filter)
11459{
11460 struct hlua_flt_ctx *flt_ctx = filter->ctx;
11461
Aurelien DARRAGONfde199d2023-03-20 15:09:33 +010011462 hlua_unref(s->hlua->T, flt_ctx->ref);
Christopher Faulet69c581a2021-05-31 08:54:04 +020011463 hlua_ctx_destroy(flt_ctx->hlua[0]);
11464 hlua_ctx_destroy(flt_ctx->hlua[1]);
11465 pool_free(pool_head_hlua_flt_ctx, flt_ctx);
11466 filter->ctx = NULL;
11467}
11468
Christopher Faulet9f55a502020-02-25 15:21:02 +010011469static int hlua_filter_from_payload(struct filter *filter)
11470{
11471 struct hlua_flt_ctx *flt_ctx = filter->ctx;
11472
11473 return (flt_ctx && !!(flt_ctx->flags & HLUA_FLT_CTX_FL_PAYLOAD));
11474}
11475
Christopher Fauletc404f112020-02-26 15:03:09 +010011476static int hlua_filter_callback(struct stream *s, struct filter *filter, const char *fun,
11477 int dir, unsigned int flags)
11478{
11479 struct hlua *flt_hlua;
11480 struct hlua_flt_config *conf = FLT_CONF(filter);
11481 struct hlua_flt_ctx *flt_ctx = filter->ctx;
11482 unsigned int hflags = HLUA_TXN_FLT_CTX;
11483 int ret = 1;
11484
11485 flt_hlua = flt_ctx->hlua[(dir == SMP_OPT_DIR_REQ ? 0 : 1)];
11486 if (!flt_hlua)
11487 goto end;
11488
11489 if (!HLUA_IS_RUNNING(flt_hlua)) {
11490 int extra_idx = lua_gettop(flt_hlua->T);
11491
11492 /* The following Lua calls can fail. */
11493 if (!SET_SAFE_LJMP(flt_hlua)) {
11494 const char *error;
11495
11496 if (lua_type(flt_hlua->T, -1) == LUA_TSTRING)
11497 error = lua_tostring(flt_hlua->T, -1);
11498 else
11499 error = "critical error";
11500 SEND_ERR(s->be, "Lua filter '%s': %s.\n", conf->reg->name, error);
11501 goto end;
11502 }
11503
11504 /* Check stack size. */
11505 if (!lua_checkstack(flt_hlua->T, 3)) {
11506 SEND_ERR(s->be, "Lua filter '%s': full stack.\n", conf->reg->name);
11507 RESET_SAFE_LJMP(flt_hlua);
11508 goto end;
11509 }
11510
Aurelien DARRAGON4fdf8b52023-03-20 17:22:37 +010011511 hlua_pushref(flt_hlua->T, flt_ctx->ref);
Christopher Fauletc404f112020-02-26 15:03:09 +010011512 if (lua_getfield(flt_hlua->T, -1, fun) != LUA_TFUNCTION) {
11513 RESET_SAFE_LJMP(flt_hlua);
11514 goto end;
11515 }
11516 lua_insert(flt_hlua->T, -2);
11517
11518 if (!hlua_txn_new(flt_hlua->T, s, s->be, dir, hflags)) {
11519 SEND_ERR(s->be, "Lua filter '%s': full stack.\n", conf->reg->name);
11520 RESET_SAFE_LJMP(flt_hlua);
11521 goto end;
11522 }
11523 flt_hlua->nargs = 2;
11524
11525 if (flags & HLUA_FLT_CB_ARG_CHN) {
11526 if (dir == SMP_OPT_DIR_REQ)
11527 lua_getfield(flt_hlua->T, -1, "req");
11528 else
11529 lua_getfield(flt_hlua->T, -1, "res");
11530 if (lua_type(flt_hlua->T, -1) == LUA_TTABLE) {
11531 lua_pushstring(flt_hlua->T, "__filter");
11532 lua_pushlightuserdata(flt_hlua->T, filter);
11533 lua_settable(flt_hlua->T, -3);
11534 }
11535 flt_hlua->nargs++;
11536 }
11537 else if (flags & HLUA_FLT_CB_ARG_HTTP_MSG) {
Christopher Fauleteae8afa2020-02-26 17:15:48 +010011538 if (dir == SMP_OPT_DIR_REQ)
11539 lua_getfield(flt_hlua->T, -1, "http_req");
11540 else
11541 lua_getfield(flt_hlua->T, -1, "http_res");
11542 if (lua_type(flt_hlua->T, -1) == LUA_TTABLE) {
11543 lua_pushstring(flt_hlua->T, "__filter");
11544 lua_pushlightuserdata(flt_hlua->T, filter);
11545 lua_settable(flt_hlua->T, -3);
11546 }
11547 flt_hlua->nargs++;
Christopher Fauletc404f112020-02-26 15:03:09 +010011548 }
11549
11550 /* Check stack size. */
11551 if (!lua_checkstack(flt_hlua->T, 1)) {
11552 SEND_ERR(s->be, "Lua filter '%s': full stack.\n", conf->reg->name);
11553 RESET_SAFE_LJMP(flt_hlua);
11554 goto end;
11555 }
11556
11557 while (extra_idx--) {
11558 lua_pushvalue(flt_hlua->T, 1);
11559 lua_remove(flt_hlua->T, 1);
11560 flt_hlua->nargs++;
11561 }
11562
11563 /* We must initialize the execution timeouts. */
Aurelien DARRAGONda9503c2022-11-25 09:10:07 +010011564 hlua_timer_init(&flt_hlua->timer, hlua_timeout_session);
Christopher Fauletc404f112020-02-26 15:03:09 +010011565
11566 /* At this point the execution is safe. */
11567 RESET_SAFE_LJMP(flt_hlua);
11568 }
11569
11570 switch (hlua_ctx_resume(flt_hlua, !(flags & HLUA_FLT_CB_FINAL))) {
11571 case HLUA_E_OK:
11572 /* Catch the return value if it required */
11573 if ((flags & HLUA_FLT_CB_RETVAL) && lua_gettop(flt_hlua->T) > 0) {
11574 ret = lua_tointeger(flt_hlua->T, -1);
11575 lua_settop(flt_hlua->T, 0); /* Empty the stack. */
11576 }
11577
11578 /* Set timeout in the required channel. */
11579 if (flt_hlua->wake_time != TICK_ETERNITY) {
11580 if (dir == SMP_OPT_DIR_REQ)
11581 s->req.analyse_exp = flt_hlua->wake_time;
11582 else
11583 s->res.analyse_exp = flt_hlua->wake_time;
11584 }
11585 break;
11586 case HLUA_E_AGAIN:
11587 /* Set timeout in the required channel. */
11588 if (flt_hlua->wake_time != TICK_ETERNITY) {
11589 if (dir == SMP_OPT_DIR_REQ)
11590 s->req.analyse_exp = flt_hlua->wake_time;
11591 else
11592 s->res.analyse_exp = flt_hlua->wake_time;
11593 }
11594 /* Some actions can be wake up when a "write" event
11595 * is detected on a response channel. This is useful
11596 * only for actions targeted on the requests.
11597 */
11598 if (HLUA_IS_WAKERESWR(flt_hlua))
11599 s->res.flags |= CF_WAKE_WRITE;
11600 if (HLUA_IS_WAKEREQWR(flt_hlua))
11601 s->req.flags |= CF_WAKE_WRITE;
11602 ret = 0;
11603 goto end;
11604 case HLUA_E_ERRMSG:
11605 SEND_ERR(s->be, "Lua filter '%s' : %s.\n", conf->reg->name, lua_tostring(flt_hlua->T, -1));
11606 ret = -1;
11607 goto end;
11608 case HLUA_E_ETMOUT:
11609 SEND_ERR(s->be, "Lua filter '%s' : '%s' callback execution timeout.\n", conf->reg->name, fun);
11610 goto end;
11611 case HLUA_E_NOMEM:
11612 SEND_ERR(s->be, "Lua filter '%s' : out of memory error.\n", conf->reg->name);
11613 goto end;
11614 case HLUA_E_YIELD:
11615 SEND_ERR(s->be, "Lua filter '%s': yield functions like core.tcp() or core.sleep()"
11616 " are not allowed from '%s' callback.\n", conf->reg->name, fun);
11617 goto end;
11618 case HLUA_E_ERR:
11619 SEND_ERR(s->be, "Lua filter '%s': '%s' returns an unknown error.\n", conf->reg->name, fun);
11620 goto end;
11621 default:
11622 goto end;
11623 }
11624
11625
11626 end:
11627 return ret;
11628}
11629
11630static int hlua_filter_start_analyze(struct stream *s, struct filter *filter, struct channel *chn)
11631{
11632 struct hlua_flt_ctx *flt_ctx = filter->ctx;
11633
11634 flt_ctx->flags = 0;
11635 return hlua_filter_callback(s, filter, "start_analyze",
11636 (!(chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES),
11637 (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_RETVAL | HLUA_FLT_CB_ARG_CHN));
11638}
11639
11640static int hlua_filter_end_analyze(struct stream *s, struct filter *filter, struct channel *chn)
11641{
11642 struct hlua_flt_ctx *flt_ctx = filter->ctx;
11643
11644 flt_ctx->flags &= ~HLUA_FLT_CTX_FL_PAYLOAD;
11645 return hlua_filter_callback(s, filter, "end_analyze",
11646 (!(chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES),
11647 (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_RETVAL | HLUA_FLT_CB_ARG_CHN));
11648}
11649
Christopher Fauleteae8afa2020-02-26 17:15:48 +010011650static int hlua_filter_http_headers(struct stream *s, struct filter *filter, struct http_msg *msg)
11651{
11652 struct hlua_flt_ctx *flt_ctx = filter->ctx;
11653
11654 flt_ctx->flags &= ~HLUA_FLT_CTX_FL_PAYLOAD;
11655 return hlua_filter_callback(s, filter, "http_headers",
11656 (!(msg->chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES),
11657 (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_RETVAL | HLUA_FLT_CB_ARG_HTTP_MSG));
11658}
11659
11660static int hlua_filter_http_payload(struct stream *s, struct filter *filter, struct http_msg *msg,
11661 unsigned int offset, unsigned int len)
11662{
11663 struct hlua_flt_ctx *flt_ctx = filter->ctx;
11664 struct hlua *flt_hlua;
11665 int dir = (!(msg->chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES);
11666 int idx = (dir == SMP_OPT_DIR_REQ ? 0 : 1);
11667 int ret;
11668
11669 flt_hlua = flt_ctx->hlua[idx];
11670 flt_ctx->cur_off[idx] = offset;
11671 flt_ctx->cur_len[idx] = len;
11672 flt_ctx->flags |= HLUA_FLT_CTX_FL_PAYLOAD;
11673 ret = hlua_filter_callback(s, filter, "http_payload", dir, (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_ARG_HTTP_MSG));
11674 if (ret != -1) {
11675 ret = flt_ctx->cur_len[idx];
11676 if (lua_gettop(flt_hlua->T) > 0) {
11677 ret = lua_tointeger(flt_hlua->T, -1);
11678 if (ret > flt_ctx->cur_len[idx])
11679 ret = flt_ctx->cur_len[idx];
11680 lua_settop(flt_hlua->T, 0); /* Empty the stack. */
11681 }
11682 }
11683 return ret;
11684}
11685
11686static int hlua_filter_http_end(struct stream *s, struct filter *filter, struct http_msg *msg)
11687{
11688 struct hlua_flt_ctx *flt_ctx = filter->ctx;
11689
11690 flt_ctx->flags &= ~HLUA_FLT_CTX_FL_PAYLOAD;
11691 return hlua_filter_callback(s, filter, "http_end",
11692 (!(msg->chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES),
11693 (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_RETVAL | HLUA_FLT_CB_ARG_HTTP_MSG));
11694}
11695
Christopher Fauletc404f112020-02-26 15:03:09 +010011696static int hlua_filter_tcp_payload(struct stream *s, struct filter *filter, struct channel *chn,
11697 unsigned int offset, unsigned int len)
11698{
11699 struct hlua_flt_ctx *flt_ctx = filter->ctx;
11700 struct hlua *flt_hlua;
11701 int dir = (!(chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES);
11702 int idx = (dir == SMP_OPT_DIR_REQ ? 0 : 1);
11703 int ret;
11704
11705 flt_hlua = flt_ctx->hlua[idx];
11706 flt_ctx->cur_off[idx] = offset;
11707 flt_ctx->cur_len[idx] = len;
11708 flt_ctx->flags |= HLUA_FLT_CTX_FL_PAYLOAD;
11709 ret = hlua_filter_callback(s, filter, "tcp_payload", dir, (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_ARG_CHN));
11710 if (ret != -1) {
11711 ret = flt_ctx->cur_len[idx];
11712 if (lua_gettop(flt_hlua->T) > 0) {
11713 ret = lua_tointeger(flt_hlua->T, -1);
11714 if (ret > flt_ctx->cur_len[idx])
11715 ret = flt_ctx->cur_len[idx];
11716 lua_settop(flt_hlua->T, 0); /* Empty the stack. */
11717 }
11718 }
11719 return ret;
11720}
11721
Christopher Faulet69c581a2021-05-31 08:54:04 +020011722static int hlua_filter_parse_fct(char **args, int *cur_arg, struct proxy *px,
11723 struct flt_conf *fconf, char **err, void *private)
11724{
11725 struct hlua_reg_filter *reg_flt = private;
11726 lua_State *L;
11727 struct hlua_flt_config *conf = NULL;
11728 const char *flt_id = NULL;
11729 int state_id, pos, flt_flags = 0;
11730 struct flt_ops *hlua_flt_ops = NULL;
11731
11732 state_id = reg_flt_to_stack_id(reg_flt);
11733 L = hlua_states[state_id];
11734
11735 /* Initialize the filter ops with default callbacks */
11736 hlua_flt_ops = calloc(1, sizeof(*hlua_flt_ops));
Christopher Fauletc86bb872021-08-13 08:33:57 +020011737 if (!hlua_flt_ops)
11738 goto error;
Christopher Faulet69c581a2021-05-31 08:54:04 +020011739 hlua_flt_ops->init = hlua_filter_init;
11740 hlua_flt_ops->deinit = hlua_filter_deinit;
11741 if (state_id) {
11742 /* Set per-thread callback if script is loaded per-thread */
11743 hlua_flt_ops->init_per_thread = hlua_filter_init_per_thread;
11744 hlua_flt_ops->deinit_per_thread = hlua_filter_deinit_per_thread;
11745 }
11746 hlua_flt_ops->attach = hlua_filter_new;
11747 hlua_flt_ops->detach = hlua_filter_delete;
11748
11749 /* Push the filter class on the stack and resolve all callbacks */
Aurelien DARRAGON4fdf8b52023-03-20 17:22:37 +010011750 hlua_pushref(L, reg_flt->flt_ref[state_id]);
Christopher Faulet69c581a2021-05-31 08:54:04 +020011751
Christopher Fauletc404f112020-02-26 15:03:09 +010011752 if (lua_getfield(L, -1, "start_analyze") == LUA_TFUNCTION)
11753 hlua_flt_ops->channel_start_analyze = hlua_filter_start_analyze;
11754 lua_pop(L, 1);
11755 if (lua_getfield(L, -1, "end_analyze") == LUA_TFUNCTION)
11756 hlua_flt_ops->channel_end_analyze = hlua_filter_end_analyze;
11757 lua_pop(L, 1);
Christopher Fauleteae8afa2020-02-26 17:15:48 +010011758 if (lua_getfield(L, -1, "http_headers") == LUA_TFUNCTION)
11759 hlua_flt_ops->http_headers = hlua_filter_http_headers;
11760 lua_pop(L, 1);
11761 if (lua_getfield(L, -1, "http_payload") == LUA_TFUNCTION)
11762 hlua_flt_ops->http_payload = hlua_filter_http_payload;
11763 lua_pop(L, 1);
11764 if (lua_getfield(L, -1, "http_end") == LUA_TFUNCTION)
11765 hlua_flt_ops->http_end = hlua_filter_http_end;
11766 lua_pop(L, 1);
Christopher Fauletc404f112020-02-26 15:03:09 +010011767 if (lua_getfield(L, -1, "tcp_payload") == LUA_TFUNCTION)
11768 hlua_flt_ops->tcp_payload = hlua_filter_tcp_payload;
11769 lua_pop(L, 1);
Christopher Faulet69c581a2021-05-31 08:54:04 +020011770
11771 /* Get id and flags of the filter class */
11772 if (lua_getfield(L, -1, "id") == LUA_TSTRING)
11773 flt_id = lua_tostring(L, -1);
11774 lua_pop(L, 1);
11775 if (lua_getfield(L, -1, "flags") == LUA_TNUMBER)
11776 flt_flags = lua_tointeger(L, -1);
11777 lua_pop(L, 1);
11778
11779 /* Create the filter config */
11780 conf = calloc(1, sizeof(*conf));
Christopher Fauletc86bb872021-08-13 08:33:57 +020011781 if (!conf)
Christopher Faulet69c581a2021-05-31 08:54:04 +020011782 goto error;
Christopher Faulet69c581a2021-05-31 08:54:04 +020011783 conf->reg = reg_flt;
11784
11785 /* duplicate args */
11786 for (pos = 0; *args[*cur_arg + 1 + pos]; pos++);
11787 conf->args = calloc(pos + 1, sizeof(*conf->args));
Christopher Fauletc86bb872021-08-13 08:33:57 +020011788 if (!conf->args)
11789 goto error;
11790 for (pos = 0; *args[*cur_arg + 1 + pos]; pos++) {
Christopher Faulet69c581a2021-05-31 08:54:04 +020011791 conf->args[pos] = strdup(args[*cur_arg + 1 + pos]);
Christopher Fauletc86bb872021-08-13 08:33:57 +020011792 if (!conf->args[pos])
11793 goto error;
11794 }
Christopher Faulet69c581a2021-05-31 08:54:04 +020011795 conf->args[pos] = NULL;
11796 *cur_arg += pos + 1;
11797
Christopher Fauletc86bb872021-08-13 08:33:57 +020011798 if (flt_id) {
11799 fconf->id = strdup(flt_id);
11800 if (!fconf->id)
11801 goto error;
11802 }
Christopher Faulet69c581a2021-05-31 08:54:04 +020011803 fconf->flags = flt_flags;
11804 fconf->conf = conf;
11805 fconf->ops = hlua_flt_ops;
11806
11807 lua_settop(L, 0);
11808 return 0;
11809
11810 error:
Christopher Fauletc86bb872021-08-13 08:33:57 +020011811 memprintf(err, "Lua filter '%s' : Lua out of memory error", reg_flt->name);
Christopher Faulet69c581a2021-05-31 08:54:04 +020011812 free(hlua_flt_ops);
Christopher Fauletc86bb872021-08-13 08:33:57 +020011813 if (conf && conf->args) {
11814 for (pos = 0; conf->args[pos]; pos++)
11815 free(conf->args[pos]);
11816 free(conf->args);
11817 }
Christopher Faulet69c581a2021-05-31 08:54:04 +020011818 free(conf);
Christopher Fauletc86bb872021-08-13 08:33:57 +020011819 free((char *)fconf->id);
Christopher Faulet69c581a2021-05-31 08:54:04 +020011820 lua_settop(L, 0);
11821 return -1;
11822}
11823
Christopher Fauletc404f112020-02-26 15:03:09 +010011824__LJMP static int hlua_register_data_filter(lua_State *L)
11825{
11826 struct filter *filter;
11827 struct channel *chn;
11828
11829 MAY_LJMP(check_args(L, 2, "register_data_filter"));
11830 MAY_LJMP(luaL_checktype(L, 1, LUA_TTABLE));
11831 chn = MAY_LJMP(hlua_checkchannel(L, 2));
11832
11833 lua_getfield(L, 1, "__filter");
11834 MAY_LJMP(luaL_checktype(L, -1, LUA_TLIGHTUSERDATA));
11835 filter = lua_touserdata (L, -1);
11836 lua_pop(L, 1);
11837
11838 register_data_filter(chn_strm(chn), chn, filter);
11839 return 1;
11840}
11841
11842__LJMP static int hlua_unregister_data_filter(lua_State *L)
11843{
11844 struct filter *filter;
11845 struct channel *chn;
11846
11847 MAY_LJMP(check_args(L, 2, "unregister_data_filter"));
11848 MAY_LJMP(luaL_checktype(L, 1, LUA_TTABLE));
11849 chn = MAY_LJMP(hlua_checkchannel(L, 2));
11850
11851 lua_getfield(L, 1, "__filter");
11852 MAY_LJMP(luaL_checktype(L, -1, LUA_TLIGHTUSERDATA));
11853 filter = lua_touserdata (L, -1);
11854 lua_pop(L, 1);
11855
11856 unregister_data_filter(chn_strm(chn), chn, filter);
11857 return 1;
11858}
11859
Christopher Faulet69c581a2021-05-31 08:54:04 +020011860/* This function is an LUA binding used for registering a filter. It expects a
Ilya Shipitsinff0f2782021-08-22 22:18:07 +050011861 * filter name used in the haproxy configuration file and a LUA function to
Christopher Faulet69c581a2021-05-31 08:54:04 +020011862 * parse configuration arguments.
11863 */
11864__LJMP static int hlua_register_filter(lua_State *L)
11865{
11866 struct buffer *trash;
11867 struct flt_kw_list *fkl;
11868 struct flt_kw *fkw;
11869 const char *name;
11870 struct hlua_reg_filter *reg_flt= NULL;
11871 int flt_ref, fun_ref;
11872 int len;
11873
11874 MAY_LJMP(check_args(L, 3, "register_filter"));
11875
Aurelien DARRAGON87f52972023-02-24 09:43:54 +010011876 if (hlua_gethlua(L)) {
11877 /* runtime processing */
11878 WILL_LJMP(luaL_error(L, "register_filter: not available outside of body context"));
11879 }
11880
Christopher Faulet69c581a2021-05-31 08:54:04 +020011881 /* First argument : filter name. */
11882 name = MAY_LJMP(luaL_checkstring(L, 1));
11883
11884 /* Second argument : The filter class */
11885 flt_ref = MAY_LJMP(hlua_checktable(L, 2));
11886
11887 /* Third argument : lua function. */
11888 fun_ref = MAY_LJMP(hlua_checkfunction(L, 3));
11889
11890 trash = get_trash_chunk();
11891 chunk_printf(trash, "lua.%s", name);
11892 fkw = flt_find_kw(trash->area);
11893 if (fkw != NULL) {
11894 reg_flt = fkw->private;
11895 if (reg_flt->flt_ref[hlua_state_id] != -1 || reg_flt->fun_ref[hlua_state_id] != -1) {
11896 ha_warning("Trying to register filter 'lua.%s' more than once. "
11897 "This will become a hard error in version 2.5.\n", name);
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +010011898 if (reg_flt->flt_ref[hlua_state_id] != -1)
11899 hlua_unref(L, reg_flt->flt_ref[hlua_state_id]);
11900 if (reg_flt->fun_ref[hlua_state_id] != -1)
11901 hlua_unref(L, reg_flt->fun_ref[hlua_state_id]);
Christopher Faulet69c581a2021-05-31 08:54:04 +020011902 }
11903 reg_flt->flt_ref[hlua_state_id] = flt_ref;
11904 reg_flt->fun_ref[hlua_state_id] = fun_ref;
11905 return 0;
11906 }
11907
11908 fkl = calloc(1, sizeof(*fkl) + sizeof(struct flt_kw) * 2);
11909 if (!fkl)
11910 goto alloc_error;
11911 fkl->scope = "HLUA";
11912
11913 reg_flt = new_hlua_reg_filter(name);
11914 if (!reg_flt)
11915 goto alloc_error;
11916
11917 reg_flt->flt_ref[hlua_state_id] = flt_ref;
11918 reg_flt->fun_ref[hlua_state_id] = fun_ref;
11919
11920 /* The filter keyword */
11921 len = strlen("lua.") + strlen(name) + 1;
11922 fkl->kw[0].kw = calloc(1, len);
11923 if (!fkl->kw[0].kw)
11924 goto alloc_error;
11925
11926 snprintf((char *)fkl->kw[0].kw, len, "lua.%s", name);
11927
11928 fkl->kw[0].parse = hlua_filter_parse_fct;
11929 fkl->kw[0].private = reg_flt;
11930 memset(&fkl->kw[1], 0, sizeof(*fkl->kw));
11931
11932 /* Register this new filter */
11933 flt_register_keywords(fkl);
11934
11935 return 0;
11936
11937 alloc_error:
11938 release_hlua_reg_filter(reg_flt);
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +010011939 hlua_unref(L, flt_ref);
11940 hlua_unref(L, fun_ref);
Christopher Faulet69c581a2021-05-31 08:54:04 +020011941 ha_free(&fkl);
11942 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
11943 return 0; /* Never reached */
11944}
11945
Thierry FOURNIERbd413492015-03-03 16:52:26 +010011946static int hlua_read_timeout(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011947 const struct proxy *defpx, const char *file, int line,
Thierry FOURNIERbd413492015-03-03 16:52:26 +010011948 char **err, unsigned int *timeout)
11949{
11950 const char *error;
11951
11952 error = parse_time_err(args[1], timeout, TIME_UNIT_MS);
Willy Tarreau9faebe32019-06-07 19:00:37 +020011953 if (error == PARSE_TIME_OVER) {
11954 memprintf(err, "timer overflow in argument <%s> to <%s> (maximum value is 2147483647 ms or ~24.8 days)",
11955 args[1], args[0]);
11956 return -1;
11957 }
11958 else if (error == PARSE_TIME_UNDER) {
11959 memprintf(err, "timer underflow in argument <%s> to <%s> (minimum non-null value is 1 ms)",
11960 args[1], args[0]);
11961 return -1;
11962 }
11963 else if (error) {
Thierry FOURNIERbd413492015-03-03 16:52:26 +010011964 memprintf(err, "%s: invalid timeout", args[0]);
11965 return -1;
11966 }
11967 return 0;
11968}
11969
11970static int hlua_session_timeout(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011971 const struct proxy *defpx, const char *file, int line,
Thierry FOURNIERbd413492015-03-03 16:52:26 +010011972 char **err)
11973{
11974 return hlua_read_timeout(args, section_type, curpx, defpx,
11975 file, line, err, &hlua_timeout_session);
11976}
11977
11978static int hlua_task_timeout(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011979 const struct proxy *defpx, const char *file, int line,
Thierry FOURNIERbd413492015-03-03 16:52:26 +010011980 char **err)
11981{
11982 return hlua_read_timeout(args, section_type, curpx, defpx,
11983 file, line, err, &hlua_timeout_task);
11984}
11985
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020011986static int hlua_applet_timeout(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011987 const struct proxy *defpx, const char *file, int line,
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020011988 char **err)
11989{
11990 return hlua_read_timeout(args, section_type, curpx, defpx,
11991 file, line, err, &hlua_timeout_applet);
11992}
11993
Thierry FOURNIERee9f8022015-03-03 17:37:37 +010011994static int hlua_forced_yield(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011995 const struct proxy *defpx, const char *file, int line,
Thierry FOURNIERee9f8022015-03-03 17:37:37 +010011996 char **err)
11997{
11998 char *error;
11999
12000 hlua_nb_instruction = strtoll(args[1], &error, 10);
12001 if (*error != '\0') {
12002 memprintf(err, "%s: invalid number", args[0]);
12003 return -1;
12004 }
12005 return 0;
12006}
12007
Willy Tarreau32f61e22015-03-18 17:54:59 +010012008static int hlua_parse_maxmem(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010012009 const struct proxy *defpx, const char *file, int line,
Willy Tarreau32f61e22015-03-18 17:54:59 +010012010 char **err)
12011{
12012 char *error;
12013
12014 if (*(args[1]) == 0) {
Thierry Fournier70e38e92022-09-19 09:01:53 +020012015 memprintf(err, "'%s' expects an integer argument (Lua memory size in MB).", args[0]);
Willy Tarreau32f61e22015-03-18 17:54:59 +010012016 return -1;
12017 }
12018 hlua_global_allocator.limit = strtoll(args[1], &error, 10) * 1024L * 1024L;
12019 if (*error != '\0') {
12020 memprintf(err, "%s: invalid number %s (error at '%c')", args[0], args[1], *error);
12021 return -1;
12022 }
12023 return 0;
12024}
12025
12026
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010012027/* This function is called by the main configuration key "lua-load". It loads and
12028 * execute an lua file during the parsing of the HAProxy configuration file. It is
12029 * the main lua entry point.
12030 *
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -080012031 * This function runs with the HAProxy keywords API. It returns -1 if an error
12032 * occurs, otherwise it returns 0.
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010012033 *
12034 * In some error case, LUA set an error message in top of the stack. This function
12035 * returns this error message in the HAProxy logs and pop it from the stack.
Thierry FOURNIERbabae282015-09-17 11:36:37 +020012036 *
12037 * This function can fail with an abort() due to an Lua critical error.
12038 * We are in the configuration parsing process of HAProxy, this abort() is
12039 * tolerated.
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010012040 */
Thierry Fournierae6b5682022-09-19 09:04:16 +020012041static int hlua_load_state(char **args, lua_State *L, char **err)
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010012042{
12043 int error;
Thierry Fournierae6b5682022-09-19 09:04:16 +020012044 int nargs;
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010012045
12046 /* Just load and compile the file. */
Thierry Fournierae6b5682022-09-19 09:04:16 +020012047 error = luaL_loadfile(L, args[0]);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010012048 if (error) {
Thierry Fournierae6b5682022-09-19 09:04:16 +020012049 memprintf(err, "error in Lua file '%s': %s", args[0], lua_tostring(L, -1));
Thierry Fournierc93c15c2020-11-28 15:02:13 +010012050 lua_pop(L, 1);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010012051 return -1;
12052 }
Thierry Fournierae6b5682022-09-19 09:04:16 +020012053
12054 /* Push args in the Lua stack, except the first one which is the filename */
12055 for (nargs = 1; *(args[nargs]) != 0; nargs++) {
Aurelien DARRAGON4d7aefe2022-09-23 10:22:14 +020012056 /* Check stack size. */
12057 if (!lua_checkstack(L, 1)) {
12058 memprintf(err, "Lua runtime error while loading arguments: stack is full.");
12059 return -1;
12060 }
Thierry Fournierae6b5682022-09-19 09:04:16 +020012061 lua_pushstring(L, args[nargs]);
12062 }
12063 nargs--;
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010012064
12065 /* If no syntax error where detected, execute the code. */
Thierry Fournierae6b5682022-09-19 09:04:16 +020012066 error = lua_pcall(L, nargs, LUA_MULTRET, 0);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010012067 switch (error) {
12068 case LUA_OK:
12069 break;
12070 case LUA_ERRRUN:
Thierry Fournier70e38e92022-09-19 09:01:53 +020012071 memprintf(err, "Lua runtime error: %s", lua_tostring(L, -1));
Thierry Fournierc93c15c2020-11-28 15:02:13 +010012072 lua_pop(L, 1);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010012073 return -1;
12074 case LUA_ERRMEM:
Thierry Fournier70e38e92022-09-19 09:01:53 +020012075 memprintf(err, "Lua out of memory error");
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010012076 return -1;
12077 case LUA_ERRERR:
Thierry Fournier70e38e92022-09-19 09:01:53 +020012078 memprintf(err, "Lua message handler error: %s", lua_tostring(L, -1));
Thierry Fournierc93c15c2020-11-28 15:02:13 +010012079 lua_pop(L, 1);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010012080 return -1;
Christopher Faulet08ed98f2020-07-28 10:33:25 +020012081#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM <= 503
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010012082 case LUA_ERRGCMM:
Thierry Fournier70e38e92022-09-19 09:01:53 +020012083 memprintf(err, "Lua garbage collector error: %s", lua_tostring(L, -1));
Thierry Fournierc93c15c2020-11-28 15:02:13 +010012084 lua_pop(L, 1);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010012085 return -1;
Christopher Faulet08ed98f2020-07-28 10:33:25 +020012086#endif
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010012087 default:
Thierry Fournier70e38e92022-09-19 09:01:53 +020012088 memprintf(err, "Lua unknown error: %s", lua_tostring(L, -1));
Thierry Fournierc93c15c2020-11-28 15:02:13 +010012089 lua_pop(L, 1);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010012090 return -1;
12091 }
12092
12093 return 0;
12094}
12095
Thierry Fournierc93c15c2020-11-28 15:02:13 +010012096static int hlua_load(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010012097 const struct proxy *defpx, const char *file, int line,
Thierry Fournierc93c15c2020-11-28 15:02:13 +010012098 char **err)
12099{
12100 if (*(args[1]) == 0) {
Thierry Fournier70e38e92022-09-19 09:01:53 +020012101 memprintf(err, "'%s' expects a file name as parameter.", args[0]);
Thierry Fournierc93c15c2020-11-28 15:02:13 +010012102 return -1;
12103 }
12104
Thierry Fournier59f11be2020-11-29 00:37:41 +010012105 /* loading for global state */
Thierry Fournierc7492592020-11-28 23:57:24 +010012106 hlua_state_id = 0;
Willy Tarreau43ab05b2021-09-28 09:43:11 +020012107 ha_set_thread(NULL);
Thierry Fournierae6b5682022-09-19 09:04:16 +020012108 return hlua_load_state(&args[1], hlua_states[0], err);
Thierry Fournierc93c15c2020-11-28 15:02:13 +010012109}
12110
Thierry Fournier59f11be2020-11-29 00:37:41 +010012111static int hlua_load_per_thread(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 Fournier59f11be2020-11-29 00:37:41 +010012113 char **err)
12114{
12115 int len;
Thierry Fournierae6b5682022-09-19 09:04:16 +020012116 int i;
Thierry Fournier59f11be2020-11-29 00:37:41 +010012117
12118 if (*(args[1]) == 0) {
Thierry Fournier70e38e92022-09-19 09:01:53 +020012119 memprintf(err, "'%s' expects a file as parameter.", args[0]);
Thierry Fournier59f11be2020-11-29 00:37:41 +010012120 return -1;
12121 }
12122
12123 if (per_thread_load == NULL) {
12124 /* allocate the first entry large enough to store the final NULL */
12125 per_thread_load = calloc(1, sizeof(*per_thread_load));
12126 if (per_thread_load == NULL) {
12127 memprintf(err, "out of memory error");
12128 return -1;
12129 }
12130 }
12131
12132 /* count used entries */
12133 for (len = 0; per_thread_load[len] != NULL; len++)
12134 ;
12135
12136 per_thread_load = realloc(per_thread_load, (len + 2) * sizeof(*per_thread_load));
12137 if (per_thread_load == NULL) {
12138 memprintf(err, "out of memory error");
12139 return -1;
12140 }
Thierry Fournier59f11be2020-11-29 00:37:41 +010012141 per_thread_load[len + 1] = NULL;
12142
Thierry Fournierae6b5682022-09-19 09:04:16 +020012143 /* count args excepting the first, allocate array and copy args */
12144 for (i = 0; *(args[i + 1]) != 0; i++);
Aurelien DARRAGONb12d1692022-09-23 08:48:34 +020012145 per_thread_load[len] = calloc(i + 1, sizeof(*per_thread_load[len]));
Thierry Fournier59f11be2020-11-29 00:37:41 +010012146 if (per_thread_load[len] == NULL) {
12147 memprintf(err, "out of memory error");
12148 return -1;
12149 }
Thierry Fournierae6b5682022-09-19 09:04:16 +020012150 for (i = 1; *(args[i]) != 0; i++) {
12151 per_thread_load[len][i - 1] = strdup(args[i]);
12152 if (per_thread_load[len][i - 1] == NULL) {
12153 memprintf(err, "out of memory error");
12154 return -1;
12155 }
12156 }
12157 per_thread_load[len][i - 1] = strdup("");
12158 if (per_thread_load[len][i - 1] == NULL) {
12159 memprintf(err, "out of memory error");
12160 return -1;
12161 }
Thierry Fournier59f11be2020-11-29 00:37:41 +010012162
12163 /* loading for thread 1 only */
12164 hlua_state_id = 1;
Willy Tarreau43ab05b2021-09-28 09:43:11 +020012165 ha_set_thread(NULL);
Thierry Fournierae6b5682022-09-19 09:04:16 +020012166 return hlua_load_state(per_thread_load[len], hlua_states[1], err);
Thierry Fournier59f11be2020-11-29 00:37:41 +010012167}
12168
Tim Duesterhusc9fc9f22020-01-12 13:55:39 +010012169/* Prepend the given <path> followed by a semicolon to the `package.<type>` variable
12170 * in the given <ctx>.
12171 */
Thierry Fournier3fb9e512020-11-28 10:13:12 +010012172static int hlua_prepend_path(lua_State *L, char *type, char *path)
Tim Duesterhusc9fc9f22020-01-12 13:55:39 +010012173{
Thierry Fournier3fb9e512020-11-28 10:13:12 +010012174 lua_getglobal(L, "package"); /* push package variable */
12175 lua_pushstring(L, path); /* push given path */
12176 lua_pushstring(L, ";"); /* push semicolon */
12177 lua_getfield(L, -3, type); /* push old path */
12178 lua_concat(L, 3); /* concatenate to new path */
12179 lua_setfield(L, -2, type); /* store new path */
12180 lua_pop(L, 1); /* pop package variable */
Tim Duesterhusc9fc9f22020-01-12 13:55:39 +010012181
12182 return 0;
12183}
12184
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010012185static int hlua_config_prepend_path(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010012186 const struct proxy *defpx, const char *file, int line,
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010012187 char **err)
12188{
12189 char *path;
12190 char *type = "path";
Tim Duesterhus621e74a2021-01-03 20:04:36 +010012191 struct prepend_path *p = NULL;
Bertrand Jacquin7fbc7702021-11-24 21:16:06 +000012192 size_t i;
Thierry Fournier59f11be2020-11-29 00:37:41 +010012193
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010012194 if (too_many_args(2, args, err, NULL)) {
Tim Duesterhus621e74a2021-01-03 20:04:36 +010012195 goto err;
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010012196 }
12197
12198 if (!(*args[1])) {
12199 memprintf(err, "'%s' expects to receive a <path> as argument", args[0]);
Tim Duesterhus621e74a2021-01-03 20:04:36 +010012200 goto err;
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010012201 }
12202 path = args[1];
12203
12204 if (*args[2]) {
12205 if (strcmp(args[2], "path") != 0 && strcmp(args[2], "cpath") != 0) {
12206 memprintf(err, "'%s' expects <type> to either be 'path' or 'cpath'", args[0]);
Tim Duesterhus621e74a2021-01-03 20:04:36 +010012207 goto err;
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010012208 }
12209 type = args[2];
12210 }
12211
Thierry Fournier59f11be2020-11-29 00:37:41 +010012212 p = calloc(1, sizeof(*p));
12213 if (p == NULL) {
Tim Duesterhusf89d43a2021-01-03 20:04:37 +010012214 memprintf(err, "memory allocation failed");
Tim Duesterhus621e74a2021-01-03 20:04:36 +010012215 goto err;
Thierry Fournier59f11be2020-11-29 00:37:41 +010012216 }
12217 p->path = strdup(path);
12218 if (p->path == NULL) {
Tim Duesterhusf89d43a2021-01-03 20:04:37 +010012219 memprintf(err, "memory allocation failed");
Tim Duesterhus621e74a2021-01-03 20:04:36 +010012220 goto err2;
Thierry Fournier59f11be2020-11-29 00:37:41 +010012221 }
12222 p->type = strdup(type);
12223 if (p->type == NULL) {
Tim Duesterhusf89d43a2021-01-03 20:04:37 +010012224 memprintf(err, "memory allocation failed");
Tim Duesterhus621e74a2021-01-03 20:04:36 +010012225 goto err2;
Thierry Fournier59f11be2020-11-29 00:37:41 +010012226 }
Willy Tarreau2b718102021-04-21 07:32:39 +020012227 LIST_APPEND(&prepend_path_list, &p->l);
Thierry Fournier59f11be2020-11-29 00:37:41 +010012228
Tim Duesterhus9e5e5862021-10-11 18:51:08 +020012229 /* Handle the global state and the per-thread state for the first
12230 * thread. The remaining threads will be initialized based on
12231 * prepend_path_list.
12232 */
Bertrand Jacquin7fbc7702021-11-24 21:16:06 +000012233 for (i = 0; i < 2; i++) {
Tim Duesterhus9e5e5862021-10-11 18:51:08 +020012234 lua_State *L = hlua_states[i];
12235 const char *error;
12236
12237 if (setjmp(safe_ljmp_env) != 0) {
12238 lua_atpanic(L, hlua_panic_safe);
12239 if (lua_type(L, -1) == LUA_TSTRING)
12240 error = lua_tostring(L, -1);
12241 else
12242 error = "critical error";
12243 fprintf(stderr, "lua-prepend-path: %s.\n", error);
12244 exit(1);
12245 } else {
12246 lua_atpanic(L, hlua_panic_ljmp);
12247 }
12248
12249 hlua_prepend_path(L, type, path);
12250
12251 lua_atpanic(L, hlua_panic_safe);
12252 }
12253
Thierry Fournier59f11be2020-11-29 00:37:41 +010012254 return 0;
Tim Duesterhus621e74a2021-01-03 20:04:36 +010012255
12256err2:
12257 free(p->type);
12258 free(p->path);
12259err:
12260 free(p);
12261 return -1;
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010012262}
12263
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010012264/* configuration keywords declaration */
12265static struct cfg_kw_list cfg_kws = {{ },{
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010012266 { CFG_GLOBAL, "lua-prepend-path", hlua_config_prepend_path },
Thierry FOURNIERbd413492015-03-03 16:52:26 +010012267 { CFG_GLOBAL, "lua-load", hlua_load },
Thierry Fournier59f11be2020-11-29 00:37:41 +010012268 { CFG_GLOBAL, "lua-load-per-thread", hlua_load_per_thread },
Thierry FOURNIERbd413492015-03-03 16:52:26 +010012269 { CFG_GLOBAL, "tune.lua.session-timeout", hlua_session_timeout },
12270 { CFG_GLOBAL, "tune.lua.task-timeout", hlua_task_timeout },
Thierry FOURNIER56da1012015-10-01 08:42:31 +020012271 { CFG_GLOBAL, "tune.lua.service-timeout", hlua_applet_timeout },
Thierry FOURNIERee9f8022015-03-03 17:37:37 +010012272 { CFG_GLOBAL, "tune.lua.forced-yield", hlua_forced_yield },
Willy Tarreau32f61e22015-03-18 17:54:59 +010012273 { CFG_GLOBAL, "tune.lua.maxmem", hlua_parse_maxmem },
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010012274 { 0, NULL, NULL },
12275}};
12276
Willy Tarreau0108d902018-11-25 19:14:37 +010012277INITCALL1(STG_REGISTER, cfg_register_keywords, &cfg_kws);
12278
William Lallemand52139182022-03-30 15:05:42 +020012279#ifdef USE_OPENSSL
Christopher Fauletafd8f102018-11-08 11:34:21 +010012280
William Lallemand30fcca12022-03-30 12:03:12 +020012281/*
12282 * This function replace a ckch_store by another one, and rebuild the ckch_inst and all its dependencies.
12283 * It does the sam as "cli_io_handler_commit_cert" but for lua, the major
12284 * difference is that the yield in lua and for the CLI is not handled the same
12285 * way.
12286 */
12287__LJMP static int hlua_ckch_commit_yield(lua_State *L, int status, lua_KContext ctx)
12288{
12289 struct ckch_inst **lua_ckchi = lua_touserdata(L, -1);
12290 struct ckch_store **lua_ckchs = lua_touserdata(L, -2);
12291 struct ckch_inst *ckchi = *lua_ckchi;
12292 struct ckch_store *old_ckchs = lua_ckchs[0];
12293 struct ckch_store *new_ckchs = lua_ckchs[1];
12294 struct hlua *hlua;
12295 char *err = NULL;
12296 int y = 1;
12297
12298 hlua = hlua_gethlua(L);
12299
12300 /* get the first ckchi to copy */
12301 if (ckchi == NULL)
12302 ckchi = LIST_ELEM(old_ckchs->ckch_inst.n, typeof(ckchi), by_ckchs);
12303
12304 /* walk through the old ckch_inst and creates new ckch_inst using the updated ckchs */
12305 list_for_each_entry_from(ckchi, &old_ckchs->ckch_inst, by_ckchs) {
12306 struct ckch_inst *new_inst;
12307
12308 /* it takes a lot of CPU to creates SSL_CTXs, so we yield every 10 CKCH instances */
12309 if (y % 10 == 0) {
12310
12311 *lua_ckchi = ckchi;
12312
12313 task_wakeup(hlua->task, TASK_WOKEN_MSG);
12314 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_ckch_commit_yield, TICK_ETERNITY, 0));
12315 }
12316
12317 if (ckch_inst_rebuild(new_ckchs, ckchi, &new_inst, &err))
12318 goto error;
12319
12320 /* link the new ckch_inst to the duplicate */
12321 LIST_APPEND(&new_ckchs->ckch_inst, &new_inst->by_ckchs);
12322 y++;
12323 }
12324
12325 /* The generation is finished, we can insert everything */
12326 ckch_store_replace(old_ckchs, new_ckchs);
12327
12328 lua_pop(L, 2); /* pop the lua_ckchs and ckchi */
12329
12330 HA_SPIN_UNLOCK(CKCH_LOCK, &ckch_lock);
12331
12332 return 0;
12333
12334error:
12335 ckch_store_free(new_ckchs);
12336 HA_SPIN_UNLOCK(CKCH_LOCK, &ckch_lock);
12337 WILL_LJMP(luaL_error(L, "%s", err));
12338 free(err);
12339
12340 return 0;
12341}
12342
12343/*
12344 * Replace a ckch_store <filename> in the ckchs_tree with a ckch_store created
12345 * from the table in parameter.
12346 *
12347 * This is equivalent to "set ssl cert" + "commit ssl cert" over the CLI, which
12348 * means it does not need to have a transaction since everything is done in the
12349 * same function.
12350 *
12351 * CertCache.set{filename="", crt="", key="", sctl="", ocsp="", issuer=""}
12352 *
12353 */
12354__LJMP static int hlua_ckch_set(lua_State *L)
12355{
12356 struct hlua *hlua;
12357 struct ckch_inst **lua_ckchi;
12358 struct ckch_store **lua_ckchs;
12359 struct ckch_store *old_ckchs = NULL;
12360 struct ckch_store *new_ckchs = NULL;
12361 int errcode = 0;
12362 char *err = NULL;
12363 struct cert_exts *cert_ext = NULL;
12364 char *filename;
William Lallemand52ddd992022-11-22 11:51:53 +010012365 struct ckch_data *data;
William Lallemand30fcca12022-03-30 12:03:12 +020012366 int ret;
12367
12368 if (lua_type(L, -1) != LUA_TTABLE)
12369 WILL_LJMP(luaL_error(L, "'CertCache.set' needs a table as argument"));
12370
12371 hlua = hlua_gethlua(L);
12372
12373 /* FIXME: this should not return an error but should come back later */
12374 if (HA_SPIN_TRYLOCK(CKCH_LOCK, &ckch_lock))
12375 WILL_LJMP(luaL_error(L, "CertCache already under lock"));
12376
12377 ret = lua_getfield(L, -1, "filename");
12378 if (ret != LUA_TSTRING) {
Thierry Fournier70e38e92022-09-19 09:01:53 +020012379 memprintf(&err, "%sNo filename specified!", err ? err : "");
William Lallemand30fcca12022-03-30 12:03:12 +020012380 errcode |= ERR_ALERT | ERR_FATAL;
12381 goto end;
12382 }
12383 filename = (char *)lua_tostring(L, -1);
12384
12385
12386 /* look for the filename in the tree */
12387 old_ckchs = ckchs_lookup(filename);
12388 if (!old_ckchs) {
Thierry Fournier70e38e92022-09-19 09:01:53 +020012389 memprintf(&err, "%sCan't replace a certificate which is not referenced by the configuration!", err ? err : "");
William Lallemand30fcca12022-03-30 12:03:12 +020012390 errcode |= ERR_ALERT | ERR_FATAL;
12391 goto end;
12392 }
12393 /* TODO: handle extra_files_noext */
12394
12395 new_ckchs = ckchs_dup(old_ckchs);
12396 if (!new_ckchs) {
Thierry Fournier70e38e92022-09-19 09:01:53 +020012397 memprintf(&err, "%sCannot allocate memory!", err ? err : "");
William Lallemand30fcca12022-03-30 12:03:12 +020012398 errcode |= ERR_ALERT | ERR_FATAL;
12399 goto end;
12400 }
12401
William Lallemand52ddd992022-11-22 11:51:53 +010012402 data = new_ckchs->data;
William Lallemand30fcca12022-03-30 12:03:12 +020012403
12404 /* loop on the field in the table, which have the same name as the
12405 * possible extensions of files */
12406 lua_pushnil(L);
12407 while (lua_next(L, 1)) {
12408 int i;
12409 const char *field = lua_tostring(L, -2);
12410 char *payload = (char *)lua_tostring(L, -1);
12411
12412 if (!field || strcmp(field, "filename") == 0) {
12413 lua_pop(L, 1);
12414 continue;
12415 }
12416
12417 for (i = 0; field && cert_exts[i].ext != NULL; i++) {
12418 if (strcmp(field, cert_exts[i].ext) == 0) {
12419 cert_ext = &cert_exts[i];
12420 break;
12421 }
12422 }
12423
12424 /* this is the default type, the field is not supported */
12425 if (cert_ext == NULL) {
Thierry Fournier70e38e92022-09-19 09:01:53 +020012426 memprintf(&err, "%sUnsupported field '%s'", err ? err : "", field);
William Lallemand30fcca12022-03-30 12:03:12 +020012427 errcode |= ERR_ALERT | ERR_FATAL;
12428 goto end;
12429 }
12430
12431 /* appply the change on the duplicate */
William Lallemand52ddd992022-11-22 11:51:53 +010012432 if (cert_ext->load(filename, payload, data, &err) != 0) {
Thierry Fournier70e38e92022-09-19 09:01:53 +020012433 memprintf(&err, "%sCan't load the payload for '%s'", err ? err : "", cert_ext->ext);
William Lallemand30fcca12022-03-30 12:03:12 +020012434 errcode |= ERR_ALERT | ERR_FATAL;
12435 goto end;
12436 }
12437 lua_pop(L, 1);
12438 }
12439
12440 /* store the pointers on the lua stack */
12441 lua_ckchs = lua_newuserdata(L, sizeof(struct ckch_store *) * 2);
12442 lua_ckchs[0] = old_ckchs;
12443 lua_ckchs[1] = new_ckchs;
12444 lua_ckchi = lua_newuserdata(L, sizeof(struct ckch_inst *));
12445 *lua_ckchi = NULL;
12446
12447 task_wakeup(hlua->task, TASK_WOKEN_MSG);
12448 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_ckch_commit_yield, TICK_ETERNITY, 0));
12449
12450end:
12451 HA_SPIN_UNLOCK(CKCH_LOCK, &ckch_lock);
12452
12453 if (errcode & ERR_CODE) {
12454 ckch_store_free(new_ckchs);
12455 WILL_LJMP(luaL_error(L, "%s", err));
12456 }
12457 free(err);
12458
12459 return 0;
12460}
12461
William Lallemand52139182022-03-30 15:05:42 +020012462#else
12463
12464__LJMP static int hlua_ckch_set(lua_State *L)
12465{
12466 WILL_LJMP(luaL_error(L, "'CertCache.set' needs an HAProxy built with OpenSSL"));
12467
12468 return 0;
12469}
12470#endif /* ! USE_OPENSSL */
12471
12472
12473
Thierry FOURNIERbabae282015-09-17 11:36:37 +020012474/* This function can fail with an abort() due to an Lua critical error.
12475 * We are in the initialisation process of HAProxy, this abort() is
12476 * tolerated.
12477 */
Thierry Fournierb8cef172020-11-28 15:37:17 +010012478int hlua_post_init_state(lua_State *L)
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010012479{
12480 struct hlua_init_function *init;
12481 const char *msg;
12482 enum hlua_exec ret;
Thierry Fournierfd107a22016-02-19 19:57:23 +010012483 const char *error;
Thierry Fournier670db242020-11-28 10:49:59 +010012484 const char *kind;
12485 const char *trace;
12486 int return_status = 1;
12487#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM >= 504
12488 int nres;
12489#endif
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010012490
Willy Tarreaucdb53462020-12-02 12:12:00 +010012491 /* disable memory limit checks if limit is not set */
12492 if (!hlua_global_allocator.limit)
12493 hlua_global_allocator.limit = ~hlua_global_allocator.limit;
12494
Ilya Shipitsin856aabc2020-04-16 23:51:34 +050012495 /* Call post initialisation function in safe environment. */
Thierry Fournier3c539322020-11-28 16:05:05 +010012496 if (setjmp(safe_ljmp_env) != 0) {
12497 lua_atpanic(L, hlua_panic_safe);
Thierry Fournierb8cef172020-11-28 15:37:17 +010012498 if (lua_type(L, -1) == LUA_TSTRING)
12499 error = lua_tostring(L, -1);
Thierry Fournier3d4a6752016-02-19 20:53:30 +010012500 else
12501 error = "critical error";
12502 fprintf(stderr, "Lua post-init: %s.\n", error);
12503 exit(1);
Thierry Fournier3c539322020-11-28 16:05:05 +010012504 } else {
12505 lua_atpanic(L, hlua_panic_ljmp);
Thierry Fournier3d4a6752016-02-19 20:53:30 +010012506 }
Frédéric Lécaille54f2bcf2018-08-29 13:46:24 +020012507
Thierry Fournierc7492592020-11-28 23:57:24 +010012508 list_for_each_entry(init, &hlua_init_functions[hlua_state_id], l) {
Aurelien DARRAGON4fdf8b52023-03-20 17:22:37 +010012509 hlua_pushref(L, init->function_ref);
Aurelien DARRAGON16d047b2023-03-20 16:29:55 +010012510 /* function ref should be released right away since it was pushed
12511 * on the stack and will not be used anymore
12512 */
12513 hlua_unref(L, init->function_ref);
Thierry Fournier670db242020-11-28 10:49:59 +010012514
12515#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM >= 504
Thierry Fournierb8cef172020-11-28 15:37:17 +010012516 ret = lua_resume(L, L, 0, &nres);
Thierry Fournier670db242020-11-28 10:49:59 +010012517#else
Thierry Fournierb8cef172020-11-28 15:37:17 +010012518 ret = lua_resume(L, L, 0);
Thierry Fournier670db242020-11-28 10:49:59 +010012519#endif
12520 kind = NULL;
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010012521 switch (ret) {
Thierry Fournier670db242020-11-28 10:49:59 +010012522
12523 case LUA_OK:
Thierry Fournierb8cef172020-11-28 15:37:17 +010012524 lua_pop(L, -1);
Thierry Fournier13d08b72020-11-28 11:02:58 +010012525 break;
Thierry Fournier670db242020-11-28 10:49:59 +010012526
12527 case LUA_ERRERR:
12528 kind = "message handler error";
Willy Tarreau14de3952022-11-14 07:08:28 +010012529 __fallthrough;
Thierry Fournier670db242020-11-28 10:49:59 +010012530 case LUA_ERRRUN:
12531 if (!kind)
12532 kind = "runtime error";
Thierry Fournierb8cef172020-11-28 15:37:17 +010012533 msg = lua_tostring(L, -1);
12534 lua_settop(L, 0); /* Empty the stack. */
12535 lua_pop(L, 1);
Christopher Fauletd09cc512021-03-24 14:48:45 +010012536 trace = hlua_traceback(L, ", ");
Thierry Fournier670db242020-11-28 10:49:59 +010012537 if (msg)
12538 ha_alert("Lua init: %s: '%s' from %s\n", kind, msg, trace);
12539 else
12540 ha_alert("Lua init: unknown %s from %s\n", kind, trace);
12541 return_status = 0;
12542 break;
12543
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010012544 default:
Thierry Fournier670db242020-11-28 10:49:59 +010012545 /* Unknown error */
12546 kind = "Unknown error";
Willy Tarreau14de3952022-11-14 07:08:28 +010012547 __fallthrough;
Thierry Fournier670db242020-11-28 10:49:59 +010012548 case LUA_YIELD:
12549 /* yield is not configured at this step, this state doesn't happen */
12550 if (!kind)
12551 kind = "yield not allowed";
Willy Tarreau14de3952022-11-14 07:08:28 +010012552 __fallthrough;
Thierry Fournier670db242020-11-28 10:49:59 +010012553 case LUA_ERRMEM:
12554 if (!kind)
12555 kind = "out of memory error";
Thierry Fournierb8cef172020-11-28 15:37:17 +010012556 lua_settop(L, 0);
12557 lua_pop(L, 1);
Christopher Fauletd09cc512021-03-24 14:48:45 +010012558 trace = hlua_traceback(L, ", ");
Thierry Fournier670db242020-11-28 10:49:59 +010012559 ha_alert("Lua init: %s: %s\n", kind, trace);
12560 return_status = 0;
12561 break;
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010012562 }
Thierry Fournier670db242020-11-28 10:49:59 +010012563 if (!return_status)
12564 break;
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010012565 }
Thierry Fournier3c539322020-11-28 16:05:05 +010012566
12567 lua_atpanic(L, hlua_panic_safe);
Thierry Fournier670db242020-11-28 10:49:59 +010012568 return return_status;
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010012569}
12570
Thierry Fournierb8cef172020-11-28 15:37:17 +010012571int hlua_post_init()
12572{
Thierry Fournier59f11be2020-11-29 00:37:41 +010012573 int ret;
12574 int i;
12575 int errors;
12576 char *err = NULL;
12577 struct hlua_function *fcn;
Christopher Faulet69c581a2021-05-31 08:54:04 +020012578 struct hlua_reg_filter *reg_flt;
Thierry Fournier59f11be2020-11-29 00:37:41 +010012579
Willy Tarreaub1310492021-08-30 09:35:18 +020012580#if defined(USE_OPENSSL)
Thierry Fournierb8cef172020-11-28 15:37:17 +010012581 /* Initialize SSL server. */
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010012582 if (socket_ssl->xprt->prepare_srv) {
Thierry Fournierb8cef172020-11-28 15:37:17 +010012583 int saved_used_backed = global.ssl_used_backend;
12584 // don't affect maxconn automatic computation
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010012585 socket_ssl->xprt->prepare_srv(socket_ssl);
Thierry Fournierb8cef172020-11-28 15:37:17 +010012586 global.ssl_used_backend = saved_used_backed;
12587 }
12588#endif
12589
Thierry Fournierc7492592020-11-28 23:57:24 +010012590 /* Perform post init of common thread */
12591 hlua_state_id = 0;
Willy Tarreau43ab05b2021-09-28 09:43:11 +020012592 ha_set_thread(&ha_thread_info[0]);
Thierry Fournier59f11be2020-11-29 00:37:41 +010012593 ret = hlua_post_init_state(hlua_states[hlua_state_id]);
12594 if (ret == 0)
12595 return 0;
12596
12597 /* init remaining lua states and load files */
12598 for (hlua_state_id = 2; hlua_state_id < global.nbthread + 1; hlua_state_id++) {
12599
12600 /* set thread context */
Willy Tarreau43ab05b2021-09-28 09:43:11 +020012601 ha_set_thread(&ha_thread_info[hlua_state_id - 1]);
Thierry Fournier59f11be2020-11-29 00:37:41 +010012602
12603 /* Init lua state */
12604 hlua_states[hlua_state_id] = hlua_init_state(hlua_state_id);
12605
12606 /* Load lua files */
12607 for (i = 0; per_thread_load && per_thread_load[i]; i++) {
12608 ret = hlua_load_state(per_thread_load[i], hlua_states[hlua_state_id], &err);
12609 if (ret != 0) {
12610 ha_alert("Lua init: %s\n", err);
12611 return 0;
12612 }
12613 }
12614 }
12615
12616 /* Reset thread context */
Willy Tarreau43ab05b2021-09-28 09:43:11 +020012617 ha_set_thread(NULL);
Thierry Fournier59f11be2020-11-29 00:37:41 +010012618
12619 /* Execute post init for all states */
12620 for (hlua_state_id = 1; hlua_state_id < global.nbthread + 1; hlua_state_id++) {
12621
12622 /* set thread context */
Willy Tarreau43ab05b2021-09-28 09:43:11 +020012623 ha_set_thread(&ha_thread_info[hlua_state_id - 1]);
Thierry Fournier59f11be2020-11-29 00:37:41 +010012624
12625 /* run post init */
12626 ret = hlua_post_init_state(hlua_states[hlua_state_id]);
12627 if (ret == 0)
12628 return 0;
12629 }
12630
12631 /* Reset thread context */
Willy Tarreau43ab05b2021-09-28 09:43:11 +020012632 ha_set_thread(NULL);
Thierry Fournier59f11be2020-11-29 00:37:41 +010012633
12634 /* control functions registering. Each function must have:
12635 * - only the function_ref[0] set positive and all other to -1
12636 * - only the function_ref[0] set to -1 and all other positive
12637 * This ensure a same reference is not used both in shared
12638 * lua state and thread dedicated lua state. Note: is the case
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +050012639 * reach, the shared state is priority, but the bug will be
Thierry Fournier59f11be2020-11-29 00:37:41 +010012640 * complicated to found for the end user.
12641 */
12642 errors = 0;
12643 list_for_each_entry(fcn, &referenced_functions, l) {
12644 ret = 0;
12645 for (i = 1; i < global.nbthread + 1; i++) {
12646 if (fcn->function_ref[i] == -1)
12647 ret--;
12648 else
12649 ret++;
12650 }
12651 if (abs(ret) != global.nbthread) {
12652 ha_alert("Lua function '%s' is not referenced in all thread. "
12653 "Expect function in all thread or in none thread.\n", fcn->name);
12654 errors++;
12655 continue;
12656 }
12657
12658 if ((fcn->function_ref[0] == -1) == (ret < 0)) {
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +050012659 ha_alert("Lua function '%s' is referenced both ins shared Lua context (through lua-load) "
12660 "and per-thread Lua context (through lua-load-per-thread). these two context "
Thierry Fournier59f11be2020-11-29 00:37:41 +010012661 "exclusive.\n", fcn->name);
12662 errors++;
12663 }
12664 }
12665
Christopher Faulet69c581a2021-05-31 08:54:04 +020012666 /* Do the same with registered filters */
12667 list_for_each_entry(reg_flt, &referenced_filters, l) {
12668 ret = 0;
12669 for (i = 1; i < global.nbthread + 1; i++) {
12670 if (reg_flt->flt_ref[i] == -1)
12671 ret--;
12672 else
12673 ret++;
12674 }
12675 if (abs(ret) != global.nbthread) {
12676 ha_alert("Lua filter '%s' is not referenced in all thread. "
12677 "Expect function in all thread or in none thread.\n", reg_flt->name);
12678 errors++;
12679 continue;
12680 }
12681
12682 if ((reg_flt->flt_ref[0] == -1) == (ret < 0)) {
12683 ha_alert("Lua filter '%s' is referenced both ins shared Lua context (through lua-load) "
12684 "and per-thread Lua context (through lua-load-per-thread). these two context "
12685 "exclusive.\n", fcn->name);
12686 errors++;
12687 }
12688 }
12689
12690
Thierry Fournier59f11be2020-11-29 00:37:41 +010012691 if (errors > 0)
12692 return 0;
12693
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +050012694 /* after this point, this global will no longer be used, so set to
Thierry Fournier59f11be2020-11-29 00:37:41 +010012695 * -1 in order to have probably a segfault if someone use it
12696 */
12697 hlua_state_id = -1;
12698
12699 return 1;
Thierry Fournierb8cef172020-11-28 15:37:17 +010012700}
12701
Willy Tarreau32f61e22015-03-18 17:54:59 +010012702/* The memory allocator used by the Lua stack. <ud> is a pointer to the
12703 * allocator's context. <ptr> is the pointer to alloc/free/realloc. <osize>
12704 * is the previously allocated size or the kind of object in case of a new
Willy Tarreaud36c7fa2020-12-02 12:26:29 +010012705 * allocation. <nsize> is the requested new size. A new allocation is
12706 * indicated by <ptr> being NULL. A free is indicated by <nsize> being
Willy Tarreaucdb53462020-12-02 12:12:00 +010012707 * zero. This one verifies that the limits are respected but is optimized
12708 * for the fast case where limits are not used, hence stats are not updated.
Willy Tarreaua5efdff2021-10-22 16:00:02 +020012709 *
12710 * Warning: while this API ressembles glibc's realloc() a lot, glibc surpasses
12711 * POSIX by making realloc(ptr,0) an effective free(), but others do not do
12712 * that and will simply allocate zero as if it were the result of malloc(0),
12713 * so mapping this onto realloc() will lead to memory leaks on non-glibc
12714 * systems.
Willy Tarreau32f61e22015-03-18 17:54:59 +010012715 */
12716static void *hlua_alloc(void *ud, void *ptr, size_t osize, size_t nsize)
12717{
12718 struct hlua_mem_allocator *zone = ud;
Willy Tarreaucdb53462020-12-02 12:12:00 +010012719 size_t limit, old, new;
12720
12721 /* a limit of ~0 means unlimited and boot complete, so there's no need
12722 * for accounting anymore.
12723 */
Willy Tarreaua5efdff2021-10-22 16:00:02 +020012724 if (likely(~zone->limit == 0)) {
12725 if (!nsize)
12726 ha_free(&ptr);
12727 else
12728 ptr = realloc(ptr, nsize);
12729 return ptr;
12730 }
Willy Tarreau32f61e22015-03-18 17:54:59 +010012731
Willy Tarreaud36c7fa2020-12-02 12:26:29 +010012732 if (!ptr)
12733 osize = 0;
Willy Tarreau32f61e22015-03-18 17:54:59 +010012734
Willy Tarreaucdb53462020-12-02 12:12:00 +010012735 /* enforce strict limits across all threads */
12736 limit = zone->limit;
12737 old = _HA_ATOMIC_LOAD(&zone->allocated);
12738 do {
12739 new = old + nsize - osize;
12740 if (unlikely(nsize && limit && new > limit))
12741 return NULL;
12742 } while (!_HA_ATOMIC_CAS(&zone->allocated, &old, new));
Willy Tarreau32f61e22015-03-18 17:54:59 +010012743
Willy Tarreaua5efdff2021-10-22 16:00:02 +020012744 if (!nsize)
12745 ha_free(&ptr);
12746 else
12747 ptr = realloc(ptr, nsize);
Willy Tarreaucdb53462020-12-02 12:12:00 +010012748
12749 if (unlikely(!ptr && nsize)) // failed
12750 _HA_ATOMIC_SUB(&zone->allocated, nsize - osize);
12751
12752 __ha_barrier_atomic_store();
Willy Tarreau32f61e22015-03-18 17:54:59 +010012753 return ptr;
12754}
12755
Thierry Fournierecb83c22020-11-28 15:49:44 +010012756/* This function can fail with an abort() due to a Lua critical error.
Thierry FOURNIERbabae282015-09-17 11:36:37 +020012757 * We are in the initialisation process of HAProxy, this abort() is
12758 * tolerated.
12759 */
Thierry Fournierecb83c22020-11-28 15:49:44 +010012760lua_State *hlua_init_state(int thread_num)
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +010012761{
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010012762 int i;
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010012763 int idx;
12764 struct sample_fetch *sf;
Thierry FOURNIER594afe72015-03-10 23:58:30 +010012765 struct sample_conv *sc;
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010012766 char *p;
Thierry Fournierfd107a22016-02-19 19:57:23 +010012767 const char *error_msg;
Thierry Fournier4234dbd2020-11-28 13:18:23 +010012768 void **context;
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012769 lua_State *L;
Thierry Fournier59f11be2020-11-29 00:37:41 +010012770 struct prepend_path *pp;
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010012771
Thierry FOURNIER380d0932015-01-23 14:27:52 +010012772 /* Init main lua stack. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012773 L = lua_newstate(hlua_alloc, &hlua_global_allocator);
Thierry FOURNIER380d0932015-01-23 14:27:52 +010012774
Thierry Fournier4234dbd2020-11-28 13:18:23 +010012775 /* Initialise Lua context to NULL */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012776 context = lua_getextraspace(L);
Thierry Fournier4234dbd2020-11-28 13:18:23 +010012777 *context = NULL;
12778
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -080012779 /* From this point, until the end of the initialisation function,
Thierry FOURNIERbabae282015-09-17 11:36:37 +020012780 * the Lua function can fail with an abort. We are in the initialisation
12781 * process of HAProxy, this abort() is tolerated.
12782 */
12783
Thierry Fournier3c539322020-11-28 16:05:05 +010012784 /* Call post initialisation function in safe environment. */
12785 if (setjmp(safe_ljmp_env) != 0) {
12786 lua_atpanic(L, hlua_panic_safe);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012787 if (lua_type(L, -1) == LUA_TSTRING)
12788 error_msg = lua_tostring(L, -1);
Thierry Fournier2f05cc62020-11-28 16:08:02 +010012789 else
12790 error_msg = "critical error";
12791 fprintf(stderr, "Lua init: %s.\n", error_msg);
12792 exit(1);
Thierry Fournier3c539322020-11-28 16:05:05 +010012793 } else {
12794 lua_atpanic(L, hlua_panic_ljmp);
Thierry Fournier2f05cc62020-11-28 16:08:02 +010012795 }
12796
Thierry FOURNIER380d0932015-01-23 14:27:52 +010012797 /* Initialise lua. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012798 luaL_openlibs(L);
Tim Duesterhus541fe1e2020-01-12 13:55:41 +010012799#define HLUA_PREPEND_PATH_TOSTRING1(x) #x
12800#define HLUA_PREPEND_PATH_TOSTRING(x) HLUA_PREPEND_PATH_TOSTRING1(x)
12801#ifdef HLUA_PREPEND_PATH
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012802 hlua_prepend_path(L, "path", HLUA_PREPEND_PATH_TOSTRING(HLUA_PREPEND_PATH));
Tim Duesterhus541fe1e2020-01-12 13:55:41 +010012803#endif
12804#ifdef HLUA_PREPEND_CPATH
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012805 hlua_prepend_path(L, "cpath", HLUA_PREPEND_PATH_TOSTRING(HLUA_PREPEND_CPATH));
Tim Duesterhus541fe1e2020-01-12 13:55:41 +010012806#endif
12807#undef HLUA_PREPEND_PATH_TOSTRING
12808#undef HLUA_PREPEND_PATH_TOSTRING1
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010012809
Thierry Fournier59f11be2020-11-29 00:37:41 +010012810 /* Apply configured prepend path */
12811 list_for_each_entry(pp, &prepend_path_list, l)
12812 hlua_prepend_path(L, pp->type, pp->path);
12813
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010012814 /*
12815 *
12816 * Create "core" object.
12817 *
12818 */
12819
Thierry FOURNIERa2d8c652015-03-11 17:29:39 +010012820 /* This table entry is the object "core" base. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012821 lua_newtable(L);
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010012822
Thierry Fournierecb83c22020-11-28 15:49:44 +010012823 /* set the thread id */
12824 hlua_class_const_int(L, "thread", thread_num);
12825
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010012826 /* Push the loglevel constants. */
Willy Tarreau80f5fae2015-02-27 16:38:20 +010012827 for (i = 0; i < NB_LOG_LEVELS; i++)
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012828 hlua_class_const_int(L, log_levels[i], i);
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010012829
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010012830 /* Register special functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012831 hlua_class_function(L, "register_init", hlua_register_init);
12832 hlua_class_function(L, "register_task", hlua_register_task);
12833 hlua_class_function(L, "register_fetches", hlua_register_fetches);
12834 hlua_class_function(L, "register_converters", hlua_register_converters);
12835 hlua_class_function(L, "register_action", hlua_register_action);
12836 hlua_class_function(L, "register_service", hlua_register_service);
12837 hlua_class_function(L, "register_cli", hlua_register_cli);
Christopher Faulet69c581a2021-05-31 08:54:04 +020012838 hlua_class_function(L, "register_filter", hlua_register_filter);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012839 hlua_class_function(L, "yield", hlua_yield);
12840 hlua_class_function(L, "set_nice", hlua_set_nice);
12841 hlua_class_function(L, "sleep", hlua_sleep);
12842 hlua_class_function(L, "msleep", hlua_msleep);
12843 hlua_class_function(L, "add_acl", hlua_add_acl);
12844 hlua_class_function(L, "del_acl", hlua_del_acl);
12845 hlua_class_function(L, "set_map", hlua_set_map);
12846 hlua_class_function(L, "del_map", hlua_del_map);
12847 hlua_class_function(L, "tcp", hlua_socket_new);
William Lallemand3956c4e2021-09-21 16:25:15 +020012848 hlua_class_function(L, "httpclient", hlua_httpclient_new);
Aurelien DARRAGONc84899c2023-02-20 18:18:59 +010012849 hlua_class_function(L, "event_sub", hlua_event_global_sub);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012850 hlua_class_function(L, "log", hlua_log);
12851 hlua_class_function(L, "Debug", hlua_log_debug);
12852 hlua_class_function(L, "Info", hlua_log_info);
12853 hlua_class_function(L, "Warning", hlua_log_warning);
12854 hlua_class_function(L, "Alert", hlua_log_alert);
12855 hlua_class_function(L, "done", hlua_done);
12856 hlua_fcn_reg_core_fcn(L);
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010012857
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012858 lua_setglobal(L, "core");
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010012859
12860 /*
12861 *
Christopher Faulet0f3c8902020-01-31 18:57:12 +010012862 * Create "act" object.
12863 *
12864 */
12865
12866 /* This table entry is the object "act" base. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012867 lua_newtable(L);
Christopher Faulet0f3c8902020-01-31 18:57:12 +010012868
12869 /* push action return constants */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012870 hlua_class_const_int(L, "CONTINUE", ACT_RET_CONT);
12871 hlua_class_const_int(L, "STOP", ACT_RET_STOP);
12872 hlua_class_const_int(L, "YIELD", ACT_RET_YIELD);
12873 hlua_class_const_int(L, "ERROR", ACT_RET_ERR);
12874 hlua_class_const_int(L, "DONE", ACT_RET_DONE);
12875 hlua_class_const_int(L, "DENY", ACT_RET_DENY);
12876 hlua_class_const_int(L, "ABORT", ACT_RET_ABRT);
12877 hlua_class_const_int(L, "INVALID", ACT_RET_INV);
Christopher Faulet0f3c8902020-01-31 18:57:12 +010012878
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012879 hlua_class_function(L, "wake_time", hlua_set_wake_time);
Christopher Faulet2c2c2e32020-01-31 19:07:52 +010012880
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012881 lua_setglobal(L, "act");
Christopher Faulet0f3c8902020-01-31 18:57:12 +010012882
12883 /*
12884 *
Christopher Faulet69c581a2021-05-31 08:54:04 +020012885 * Create "Filter" object.
12886 *
12887 */
12888
12889 /* This table entry is the object "filter" base. */
12890 lua_newtable(L);
12891
12892 /* push flags and constants */
12893 hlua_class_const_int(L, "CONTINUE", 1);
12894 hlua_class_const_int(L, "WAIT", 0);
12895 hlua_class_const_int(L, "ERROR", -1);
12896
12897 hlua_class_const_int(L, "FLT_CFG_FL_HTX", FLT_CFG_FL_HTX);
12898
Christopher Fauletc404f112020-02-26 15:03:09 +010012899 hlua_class_function(L, "wake_time", hlua_set_wake_time);
12900 hlua_class_function(L, "register_data_filter", hlua_register_data_filter);
12901 hlua_class_function(L, "unregister_data_filter", hlua_unregister_data_filter);
12902
Christopher Faulet69c581a2021-05-31 08:54:04 +020012903 lua_setglobal(L, "filter");
12904
12905 /*
12906 *
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012907 * Register class Map
12908 *
12909 */
12910
12911 /* This table entry is the object "Map" base. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012912 lua_newtable(L);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012913
12914 /* register pattern types. */
12915 for (i=0; i<PAT_MATCH_NUM; i++)
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012916 hlua_class_const_int(L, pat_match_names[i], i);
Thierry FOURNIER4dc71972017-01-28 08:33:08 +010012917 for (i=0; i<PAT_MATCH_NUM; i++) {
Willy Tarreau843b7cb2018-07-13 10:54:26 +020012918 snprintf(trash.area, trash.size, "_%s", pat_match_names[i]);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012919 hlua_class_const_int(L, trash.area, i);
Thierry FOURNIER4dc71972017-01-28 08:33:08 +010012920 }
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012921
12922 /* register constructor. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012923 hlua_class_function(L, "new", hlua_map_new);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012924
12925 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012926 lua_newtable(L);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012927
Ilya Shipitsind4259502020-04-08 01:07:56 +050012928 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012929 lua_pushstring(L, "__index");
12930 lua_newtable(L);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012931
12932 /* Register . */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012933 hlua_class_function(L, "lookup", hlua_map_lookup);
12934 hlua_class_function(L, "slookup", hlua_map_slookup);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012935
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012936 lua_rawset(L, -3);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012937
Thierry Fournier45e78d72016-02-19 18:34:46 +010012938 /* Register previous table in the registry with reference and named entry.
12939 * The function hlua_register_metatable() pops the stack, so we
12940 * previously create a copy of the table.
12941 */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012942 lua_pushvalue(L, -1); /* Copy the -1 entry and push it on the stack. */
12943 class_map_ref = hlua_register_metatable(L, CLASS_MAP);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012944
12945 /* Assign the metatable to the mai Map object. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012946 lua_setmetatable(L, -2);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012947
12948 /* Set a name to the table. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012949 lua_setglobal(L, "Map");
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012950
12951 /*
12952 *
William Lallemand30fcca12022-03-30 12:03:12 +020012953 * Register "CertCache" class
12954 *
12955 */
12956
12957 /* Create and fill the metatable. */
12958 lua_newtable(L);
12959 /* Register */
12960 hlua_class_function(L, "set", hlua_ckch_set);
12961 lua_setglobal(L, CLASS_CERTCACHE); /* Create global object called Regex */
12962
12963 /*
12964 *
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010012965 * Register class Channel
12966 *
12967 */
12968
12969 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012970 lua_newtable(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010012971
Ilya Shipitsind4259502020-04-08 01:07:56 +050012972 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012973 lua_pushstring(L, "__index");
12974 lua_newtable(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010012975
12976 /* Register . */
Christopher Faulet6a79fc12021-08-06 16:02:36 +020012977 hlua_class_function(L, "data", hlua_channel_get_data);
12978 hlua_class_function(L, "line", hlua_channel_get_line);
12979 hlua_class_function(L, "set", hlua_channel_set_data);
12980 hlua_class_function(L, "remove", hlua_channel_del_data);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012981 hlua_class_function(L, "append", hlua_channel_append);
Christopher Faulet6a79fc12021-08-06 16:02:36 +020012982 hlua_class_function(L, "prepend", hlua_channel_prepend);
12983 hlua_class_function(L, "insert", hlua_channel_insert_data);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012984 hlua_class_function(L, "send", hlua_channel_send);
12985 hlua_class_function(L, "forward", hlua_channel_forward);
Christopher Faulet6a79fc12021-08-06 16:02:36 +020012986 hlua_class_function(L, "input", hlua_channel_get_in_len);
12987 hlua_class_function(L, "output", hlua_channel_get_out_len);
12988 hlua_class_function(L, "may_recv", hlua_channel_may_recv);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012989 hlua_class_function(L, "is_full", hlua_channel_is_full);
12990 hlua_class_function(L, "is_resp", hlua_channel_is_resp);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010012991
Christopher Faulet6a79fc12021-08-06 16:02:36 +020012992 /* Deprecated API */
12993 hlua_class_function(L, "get", hlua_channel_get);
12994 hlua_class_function(L, "dup", hlua_channel_dup);
12995 hlua_class_function(L, "getline", hlua_channel_getline);
12996 hlua_class_function(L, "get_in_len", hlua_channel_get_in_len);
12997 hlua_class_function(L, "get_out_len", hlua_channel_get_out_len);
12998
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012999 lua_rawset(L, -3);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010013000
13001 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013002 class_channel_ref = hlua_register_metatable(L, CLASS_CHANNEL);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010013003
13004 /*
13005 *
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010013006 * Register class Fetches
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010013007 *
13008 */
13009
13010 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013011 lua_newtable(L);
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010013012
Ilya Shipitsind4259502020-04-08 01:07:56 +050013013 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013014 lua_pushstring(L, "__index");
13015 lua_newtable(L);
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010013016
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010013017 /* Browse existing fetches and create the associated
13018 * object method.
13019 */
13020 sf = NULL;
13021 while ((sf = sample_fetch_getnext(sf, &idx)) != NULL) {
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010013022 /* gL.Tua doesn't support '.' and '-' in the function names, replace it
13023 * by an underscore.
13024 */
Willy Tarreau5ef96562021-08-26 16:48:53 +020013025 strlcpy2(trash.area, sf->kw, trash.size);
Willy Tarreau843b7cb2018-07-13 10:54:26 +020013026 for (p = trash.area; *p; p++)
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010013027 if (*p == '.' || *p == '-' || *p == '+')
13028 *p = '_';
13029
13030 /* Register the function. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013031 lua_pushstring(L, trash.area);
13032 lua_pushlightuserdata(L, sf);
13033 lua_pushcclosure(L, hlua_run_sample_fetch, 1);
13034 lua_rawset(L, -3);
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010013035 }
13036
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013037 lua_rawset(L, -3);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010013038
13039 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013040 class_fetches_ref = hlua_register_metatable(L, CLASS_FETCHES);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010013041
13042 /*
13043 *
Thierry FOURNIER594afe72015-03-10 23:58:30 +010013044 * Register class Converters
13045 *
13046 */
13047
13048 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013049 lua_newtable(L);
Thierry FOURNIER594afe72015-03-10 23:58:30 +010013050
13051 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013052 lua_pushstring(L, "__index");
13053 lua_newtable(L);
Thierry FOURNIER594afe72015-03-10 23:58:30 +010013054
13055 /* Browse existing converters and create the associated
13056 * object method.
13057 */
13058 sc = NULL;
13059 while ((sc = sample_conv_getnext(sc, &idx)) != NULL) {
Thierry FOURNIER594afe72015-03-10 23:58:30 +010013060 /* gL.Tua doesn't support '.' and '-' in the function names, replace it
13061 * by an underscore.
13062 */
Willy Tarreau5ef96562021-08-26 16:48:53 +020013063 strlcpy2(trash.area, sc->kw, trash.size);
Willy Tarreau843b7cb2018-07-13 10:54:26 +020013064 for (p = trash.area; *p; p++)
Thierry FOURNIER594afe72015-03-10 23:58:30 +010013065 if (*p == '.' || *p == '-' || *p == '+')
13066 *p = '_';
13067
13068 /* Register the function. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013069 lua_pushstring(L, trash.area);
13070 lua_pushlightuserdata(L, sc);
13071 lua_pushcclosure(L, hlua_run_sample_conv, 1);
13072 lua_rawset(L, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +010013073 }
13074
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013075 lua_rawset(L, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +010013076
13077 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013078 class_converters_ref = hlua_register_metatable(L, CLASS_CONVERTERS);
Thierry FOURNIER594afe72015-03-10 23:58:30 +010013079
13080 /*
13081 *
Thierry FOURNIER08504f42015-03-16 14:17:08 +010013082 * Register class HTTP
13083 *
13084 */
13085
13086 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013087 lua_newtable(L);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010013088
Ilya Shipitsind4259502020-04-08 01:07:56 +050013089 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013090 lua_pushstring(L, "__index");
13091 lua_newtable(L);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010013092
13093 /* Register Lua functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013094 hlua_class_function(L, "req_get_headers",hlua_http_req_get_headers);
13095 hlua_class_function(L, "req_del_header", hlua_http_req_del_hdr);
13096 hlua_class_function(L, "req_rep_header", hlua_http_req_rep_hdr);
13097 hlua_class_function(L, "req_rep_value", hlua_http_req_rep_val);
13098 hlua_class_function(L, "req_add_header", hlua_http_req_add_hdr);
13099 hlua_class_function(L, "req_set_header", hlua_http_req_set_hdr);
13100 hlua_class_function(L, "req_set_method", hlua_http_req_set_meth);
13101 hlua_class_function(L, "req_set_path", hlua_http_req_set_path);
13102 hlua_class_function(L, "req_set_query", hlua_http_req_set_query);
13103 hlua_class_function(L, "req_set_uri", hlua_http_req_set_uri);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010013104
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013105 hlua_class_function(L, "res_get_headers",hlua_http_res_get_headers);
13106 hlua_class_function(L, "res_del_header", hlua_http_res_del_hdr);
13107 hlua_class_function(L, "res_rep_header", hlua_http_res_rep_hdr);
13108 hlua_class_function(L, "res_rep_value", hlua_http_res_rep_val);
13109 hlua_class_function(L, "res_add_header", hlua_http_res_add_hdr);
13110 hlua_class_function(L, "res_set_header", hlua_http_res_set_hdr);
13111 hlua_class_function(L, "res_set_status", hlua_http_res_set_status);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010013112
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013113 lua_rawset(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010013114
13115 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013116 class_http_ref = hlua_register_metatable(L, CLASS_HTTP);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010013117
Christopher Fauletdf97ac42020-02-26 16:57:19 +010013118 /*
13119 *
13120 * Register class HTTPMessage
13121 *
13122 */
13123
13124 /* Create and fill the metatable. */
13125 lua_newtable(L);
13126
Ilya Shipitsinff0f2782021-08-22 22:18:07 +050013127 /* Create and fill the __index entry. */
Christopher Fauletdf97ac42020-02-26 16:57:19 +010013128 lua_pushstring(L, "__index");
13129 lua_newtable(L);
13130
13131 /* Register Lua functions. */
13132 hlua_class_function(L, "is_resp", hlua_http_msg_is_resp);
13133 hlua_class_function(L, "get_stline", hlua_http_msg_get_stline);
13134 hlua_class_function(L, "get_headers", hlua_http_msg_get_headers);
13135 hlua_class_function(L, "del_header", hlua_http_msg_del_hdr);
13136 hlua_class_function(L, "rep_header", hlua_http_msg_rep_hdr);
13137 hlua_class_function(L, "rep_value", hlua_http_msg_rep_val);
13138 hlua_class_function(L, "add_header", hlua_http_msg_add_hdr);
13139 hlua_class_function(L, "set_header", hlua_http_msg_set_hdr);
13140 hlua_class_function(L, "set_method", hlua_http_msg_set_meth);
13141 hlua_class_function(L, "set_path", hlua_http_msg_set_path);
13142 hlua_class_function(L, "set_query", hlua_http_msg_set_query);
13143 hlua_class_function(L, "set_uri", hlua_http_msg_set_uri);
13144 hlua_class_function(L, "set_status", hlua_http_msg_set_status);
13145 hlua_class_function(L, "is_full", hlua_http_msg_is_full);
13146 hlua_class_function(L, "may_recv", hlua_http_msg_may_recv);
13147 hlua_class_function(L, "eom", hlua_http_msg_is_eom);
13148 hlua_class_function(L, "input", hlua_http_msg_get_in_len);
13149 hlua_class_function(L, "output", hlua_http_msg_get_out_len);
13150
13151 hlua_class_function(L, "body", hlua_http_msg_get_body);
13152 hlua_class_function(L, "set", hlua_http_msg_set_data);
13153 hlua_class_function(L, "remove", hlua_http_msg_del_data);
13154 hlua_class_function(L, "append", hlua_http_msg_append);
13155 hlua_class_function(L, "prepend", hlua_http_msg_prepend);
13156 hlua_class_function(L, "insert", hlua_http_msg_insert_data);
13157 hlua_class_function(L, "set_eom", hlua_http_msg_set_eom);
13158 hlua_class_function(L, "unset_eom", hlua_http_msg_unset_eom);
13159
13160 hlua_class_function(L, "send", hlua_http_msg_send);
13161 hlua_class_function(L, "forward", hlua_http_msg_forward);
13162
13163 lua_rawset(L, -3);
13164
13165 /* Register previous table in the registry with reference and named entry. */
13166 class_http_msg_ref = hlua_register_metatable(L, CLASS_HTTP_MSG);
William Lallemand3956c4e2021-09-21 16:25:15 +020013167
13168 /*
13169 *
13170 * Register class HTTPClient
13171 *
13172 */
13173
13174 /* Create and fill the metatable. */
13175 lua_newtable(L);
13176 lua_pushstring(L, "__index");
13177 lua_newtable(L);
13178 hlua_class_function(L, "get", hlua_httpclient_get);
William Lallemanddc2cc902021-10-26 11:43:26 +020013179 hlua_class_function(L, "head", hlua_httpclient_head);
13180 hlua_class_function(L, "put", hlua_httpclient_put);
13181 hlua_class_function(L, "post", hlua_httpclient_post);
13182 hlua_class_function(L, "delete", hlua_httpclient_delete);
William Lallemand3956c4e2021-09-21 16:25:15 +020013183 lua_settable(L, -3); /* Sets the __index entry. */
William Lallemandf77f1de2021-09-28 19:10:38 +020013184 /* Register the garbage collector entry. */
13185 lua_pushstring(L, "__gc");
13186 lua_pushcclosure(L, hlua_httpclient_gc, 0);
13187 lua_settable(L, -3); /* Push the last 2 entries in the table at index -3 */
13188
William Lallemand3956c4e2021-09-21 16:25:15 +020013189
13190
13191 class_httpclient_ref = hlua_register_metatable(L, CLASS_HTTPCLIENT);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010013192 /*
13193 *
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020013194 * Register class AppletTCP
13195 *
13196 */
13197
13198 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013199 lua_newtable(L);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020013200
Ilya Shipitsind4259502020-04-08 01:07:56 +050013201 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013202 lua_pushstring(L, "__index");
13203 lua_newtable(L);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020013204
13205 /* Register Lua functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013206 hlua_class_function(L, "getline", hlua_applet_tcp_getline);
13207 hlua_class_function(L, "receive", hlua_applet_tcp_recv);
13208 hlua_class_function(L, "send", hlua_applet_tcp_send);
13209 hlua_class_function(L, "set_priv", hlua_applet_tcp_set_priv);
13210 hlua_class_function(L, "get_priv", hlua_applet_tcp_get_priv);
13211 hlua_class_function(L, "set_var", hlua_applet_tcp_set_var);
13212 hlua_class_function(L, "unset_var", hlua_applet_tcp_unset_var);
13213 hlua_class_function(L, "get_var", hlua_applet_tcp_get_var);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020013214
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013215 lua_settable(L, -3);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020013216
13217 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013218 class_applet_tcp_ref = hlua_register_metatable(L, CLASS_APPLET_TCP);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020013219
13220 /*
13221 *
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020013222 * Register class AppletHTTP
13223 *
13224 */
13225
13226 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013227 lua_newtable(L);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020013228
Ilya Shipitsind4259502020-04-08 01:07:56 +050013229 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013230 lua_pushstring(L, "__index");
13231 lua_newtable(L);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020013232
13233 /* Register Lua functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013234 hlua_class_function(L, "set_priv", hlua_applet_http_set_priv);
13235 hlua_class_function(L, "get_priv", hlua_applet_http_get_priv);
13236 hlua_class_function(L, "set_var", hlua_applet_http_set_var);
13237 hlua_class_function(L, "unset_var", hlua_applet_http_unset_var);
13238 hlua_class_function(L, "get_var", hlua_applet_http_get_var);
13239 hlua_class_function(L, "getline", hlua_applet_http_getline);
13240 hlua_class_function(L, "receive", hlua_applet_http_recv);
13241 hlua_class_function(L, "send", hlua_applet_http_send);
13242 hlua_class_function(L, "add_header", hlua_applet_http_addheader);
13243 hlua_class_function(L, "set_status", hlua_applet_http_status);
13244 hlua_class_function(L, "start_response", hlua_applet_http_start_response);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020013245
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013246 lua_settable(L, -3);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020013247
13248 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013249 class_applet_http_ref = hlua_register_metatable(L, CLASS_APPLET_HTTP);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020013250
13251 /*
13252 *
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010013253 * Register class TXN
13254 *
13255 */
13256
13257 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013258 lua_newtable(L);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010013259
Ilya Shipitsind4259502020-04-08 01:07:56 +050013260 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013261 lua_pushstring(L, "__index");
13262 lua_newtable(L);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010013263
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +010013264 /* Register Lua functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013265 hlua_class_function(L, "set_priv", hlua_set_priv);
13266 hlua_class_function(L, "get_priv", hlua_get_priv);
13267 hlua_class_function(L, "set_var", hlua_set_var);
13268 hlua_class_function(L, "unset_var", hlua_unset_var);
13269 hlua_class_function(L, "get_var", hlua_get_var);
13270 hlua_class_function(L, "done", hlua_txn_done);
13271 hlua_class_function(L, "reply", hlua_txn_reply_new);
13272 hlua_class_function(L, "set_loglevel", hlua_txn_set_loglevel);
13273 hlua_class_function(L, "set_tos", hlua_txn_set_tos);
13274 hlua_class_function(L, "set_mark", hlua_txn_set_mark);
13275 hlua_class_function(L, "set_priority_class", hlua_txn_set_priority_class);
13276 hlua_class_function(L, "set_priority_offset", hlua_txn_set_priority_offset);
13277 hlua_class_function(L, "deflog", hlua_txn_deflog);
13278 hlua_class_function(L, "log", hlua_txn_log);
13279 hlua_class_function(L, "Debug", hlua_txn_log_debug);
13280 hlua_class_function(L, "Info", hlua_txn_log_info);
13281 hlua_class_function(L, "Warning", hlua_txn_log_warning);
13282 hlua_class_function(L, "Alert", hlua_txn_log_alert);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +010013283
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013284 lua_rawset(L, -3);
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010013285
13286 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013287 class_txn_ref = hlua_register_metatable(L, CLASS_TXN);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010013288
13289 /*
13290 *
Christopher Faulet700d9e82020-01-31 12:21:52 +010013291 * Register class reply
13292 *
13293 */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013294 lua_newtable(L);
13295 lua_pushstring(L, "__index");
13296 lua_newtable(L);
13297 hlua_class_function(L, "set_status", hlua_txn_reply_set_status);
13298 hlua_class_function(L, "add_header", hlua_txn_reply_add_header);
13299 hlua_class_function(L, "del_header", hlua_txn_reply_del_header);
13300 hlua_class_function(L, "set_body", hlua_txn_reply_set_body);
13301 lua_settable(L, -3); /* Sets the __index entry. */
13302 class_txn_reply_ref = luaL_ref(L, LUA_REGISTRYINDEX);
Christopher Faulet700d9e82020-01-31 12:21:52 +010013303
13304
13305 /*
13306 *
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010013307 * Register class Socket
13308 *
13309 */
13310
13311 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013312 lua_newtable(L);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010013313
Ilya Shipitsind4259502020-04-08 01:07:56 +050013314 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013315 lua_pushstring(L, "__index");
13316 lua_newtable(L);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010013317
Baptiste Assmann84bb4932015-03-02 21:40:06 +010013318#ifdef USE_OPENSSL
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013319 hlua_class_function(L, "connect_ssl", hlua_socket_connect_ssl);
Baptiste Assmann84bb4932015-03-02 21:40:06 +010013320#endif
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013321 hlua_class_function(L, "connect", hlua_socket_connect);
13322 hlua_class_function(L, "send", hlua_socket_send);
13323 hlua_class_function(L, "receive", hlua_socket_receive);
13324 hlua_class_function(L, "close", hlua_socket_close);
13325 hlua_class_function(L, "getpeername", hlua_socket_getpeername);
13326 hlua_class_function(L, "getsockname", hlua_socket_getsockname);
13327 hlua_class_function(L, "setoption", hlua_socket_setoption);
13328 hlua_class_function(L, "settimeout", hlua_socket_settimeout);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010013329
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013330 lua_rawset(L, -3); /* Push the last 2 entries in the table at index -3 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010013331
13332 /* Register the garbage collector entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013333 lua_pushstring(L, "__gc");
13334 lua_pushcclosure(L, hlua_socket_gc, 0);
13335 lua_rawset(L, -3); /* Push the last 2 entries in the table at index -3 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010013336
13337 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013338 class_socket_ref = hlua_register_metatable(L, CLASS_SOCKET);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010013339
Thierry Fournieraafc7772020-12-04 11:47:47 +010013340 lua_atpanic(L, hlua_panic_safe);
13341
13342 return L;
13343}
13344
13345void hlua_init(void) {
13346 int i;
Amaury Denoyelle239fdbf2021-03-24 10:22:03 +010013347 char *errmsg;
Thierry Fournieraafc7772020-12-04 11:47:47 +010013348#ifdef USE_OPENSSL
13349 struct srv_kw *kw;
13350 int tmp_error;
13351 char *error;
13352 char *args[] = { /* SSL client configuration. */
13353 "ssl",
13354 "verify",
13355 "none",
13356 NULL
13357 };
13358#endif
13359
13360 /* Init post init function list head */
13361 for (i = 0; i < MAX_THREADS + 1; i++)
13362 LIST_INIT(&hlua_init_functions[i]);
13363
13364 /* Init state for common/shared lua parts */
13365 hlua_state_id = 0;
Willy Tarreau43ab05b2021-09-28 09:43:11 +020013366 ha_set_thread(NULL);
Thierry Fournieraafc7772020-12-04 11:47:47 +010013367 hlua_states[0] = hlua_init_state(0);
13368
13369 /* Init state 1 for thread 0. We have at least one thread. */
13370 hlua_state_id = 1;
Willy Tarreau43ab05b2021-09-28 09:43:11 +020013371 ha_set_thread(NULL);
Thierry Fournieraafc7772020-12-04 11:47:47 +010013372 hlua_states[1] = hlua_init_state(1);
13373
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010013374 /* Proxy and server configuration initialisation. */
William Lallemand6bb77b92021-07-28 15:48:16 +020013375 socket_proxy = alloc_new_proxy("LUA-SOCKET", PR_CAP_FE|PR_CAP_BE|PR_CAP_INT, &errmsg);
Amaury Denoyelle239fdbf2021-03-24 10:22:03 +010013376 if (!socket_proxy) {
13377 fprintf(stderr, "Lua init: %s\n", errmsg);
13378 exit(1);
13379 }
13380 proxy_preset_defaults(socket_proxy);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010013381
13382 /* Init TCP server: unchanged parameters */
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010013383 socket_tcp = new_server(socket_proxy);
13384 if (!socket_tcp) {
13385 fprintf(stderr, "Lua init: failed to allocate tcp server socket\n");
13386 exit(1);
13387 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010013388
13389#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010013390 /* Init TCP server: unchanged parameters */
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010013391 socket_ssl = new_server(socket_proxy);
13392 if (!socket_ssl) {
13393 fprintf(stderr, "Lua init: failed to allocate ssl server socket\n");
13394 exit(1);
13395 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010013396
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010013397 socket_ssl->use_ssl = 1;
13398 socket_ssl->xprt = xprt_get(XPRT_SSL);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010013399
Bertrand Jacquin80839ff2021-01-21 19:14:46 +000013400 for (i = 0; args[i] != NULL; i++) {
13401 if ((kw = srv_find_kw(args[i])) != NULL) { /* Maybe it's registered server keyword */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010013402 /*
13403 *
13404 * If the keyword is not known, we can search in the registered
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -080013405 * server keywords. This is useful to configure special SSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010013406 * features like client certificates and ssl_verify.
13407 *
13408 */
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010013409 tmp_error = kw->parse(args, &i, socket_proxy, socket_ssl, &error);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010013410 if (tmp_error != 0) {
13411 fprintf(stderr, "INTERNAL ERROR: %s\n", error);
13412 abort(); /* This must be never arrives because the command line
13413 not editable by the user. */
13414 }
Bertrand Jacquin80839ff2021-01-21 19:14:46 +000013415 i += kw->skip;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010013416 }
13417 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010013418#endif
Thierry Fournier75933d42016-01-21 09:30:18 +010013419
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +010013420}
Willy Tarreaubb57d942016-12-21 19:04:56 +010013421
Tim Duesterhusd0c0ca22020-07-04 11:53:26 +020013422static void hlua_deinit()
13423{
Willy Tarreau186f3762020-12-04 11:48:12 +010013424 int thr;
Christopher Faulet69c581a2021-05-31 08:54:04 +020013425 struct hlua_reg_filter *reg_flt, *reg_flt_bck;
13426
13427 list_for_each_entry_safe(reg_flt, reg_flt_bck, &referenced_filters, l)
13428 release_hlua_reg_filter(reg_flt);
Willy Tarreau186f3762020-12-04 11:48:12 +010013429
13430 for (thr = 0; thr < MAX_THREADS+1; thr++) {
13431 if (hlua_states[thr])
13432 lua_close(hlua_states[thr]);
13433 }
Willy Tarreau430bf4a2021-03-04 09:45:32 +010013434
Amaury Denoyellebc2ebfa2021-08-25 15:34:53 +020013435 srv_drop(socket_tcp);
Willy Tarreau430bf4a2021-03-04 09:45:32 +010013436
Willy Tarreau0f143af2021-03-05 10:41:48 +010013437#ifdef USE_OPENSSL
Amaury Denoyellebc2ebfa2021-08-25 15:34:53 +020013438 srv_drop(socket_ssl);
Willy Tarreau0f143af2021-03-05 10:41:48 +010013439#endif
Amaury Denoyelle239fdbf2021-03-24 10:22:03 +010013440
13441 free_proxy(socket_proxy);
Tim Duesterhusd0c0ca22020-07-04 11:53:26 +020013442}
13443
13444REGISTER_POST_DEINIT(hlua_deinit);
13445
Willy Tarreau80713382018-11-26 10:19:54 +010013446static void hlua_register_build_options(void)
13447{
Willy Tarreaubb57d942016-12-21 19:04:56 +010013448 char *ptr = NULL;
Willy Tarreau80713382018-11-26 10:19:54 +010013449
Willy Tarreaubb57d942016-12-21 19:04:56 +010013450 memprintf(&ptr, "Built with Lua version : %s", LUA_RELEASE);
13451 hap_register_build_opts(ptr, 1);
13452}
Willy Tarreau80713382018-11-26 10:19:54 +010013453
13454INITCALL0(STG_REGISTER, hlua_register_build_options);