blob: 98ee44170a0aaea33d1a0697b1e173178862be96 [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>
Aurelien DARRAGONc99f3ad2023-04-12 15:47:16 +020069#include <haproxy/check.h>
Aurelien DARRAGON5bed48f2023-04-21 17:32:46 +020070#include <haproxy/mailers.h>
Thierry FOURNIER380d0932015-01-23 14:27:52 +010071
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +010072/* Lua uses longjmp to perform yield or throwing errors. This
73 * macro is used only for identifying the function that can
74 * not return because a longjmp is executed.
75 * __LJMP marks a prototype of hlua file that can use longjmp.
76 * WILL_LJMP() marks an lua function that will use longjmp.
77 * MAY_LJMP() marks an lua function that may use longjmp.
78 */
79#define __LJMP
Willy Tarreau4e7cc332018-10-20 17:45:48 +020080#define WILL_LJMP(func) do { func; my_unreachable(); } while(0)
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +010081#define MAY_LJMP(func) func
82
Thierry FOURNIERbabae282015-09-17 11:36:37 +020083/* This couple of function executes securely some Lua calls outside of
84 * the lua runtime environment. Each Lua call can return a longjmp
85 * if it encounter a memory error.
86 *
87 * Lua documentation extract:
88 *
89 * If an error happens outside any protected environment, Lua calls
90 * a panic function (see lua_atpanic) and then calls abort, thus
91 * exiting the host application. Your panic function can avoid this
92 * exit by never returning (e.g., doing a long jump to your own
93 * recovery point outside Lua).
94 *
95 * The panic function runs as if it were a message handler (see
Willy Tarreau3dfb7da2022-03-02 22:33:39 +010096 * #2.3); in particular, the error message is at the top of the
Thierry FOURNIERbabae282015-09-17 11:36:37 +020097 * stack. However, there is no guarantee about stack space. To push
98 * anything on the stack, the panic function must first check the
Willy Tarreau3dfb7da2022-03-02 22:33:39 +010099 * available space (see #4.2).
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200100 *
101 * We must check all the Lua entry point. This includes:
102 * - The include/proto/hlua.h exported functions
103 * - the task wrapper function
104 * - The action wrapper function
105 * - The converters wrapper function
106 * - The sample-fetch wrapper functions
107 *
Ilya Shipitsin46a030c2020-07-05 16:36:08 +0500108 * It is tolerated that the initialisation function returns an abort.
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -0800109 * Before each Lua abort, an error message is written on stderr.
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200110 *
111 * The macro SET_SAFE_LJMP initialise the longjmp. The Macro
112 * RESET_SAFE_LJMP reset the longjmp. These function must be macro
113 * because they must be exists in the program stack when the longjmp
114 * is called.
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +0200115 *
116 * Note that the Lua processing is not really thread safe. It provides
117 * heavy system which consists to add our own lock function in the Lua
118 * code and recompile the library. This system will probably not accepted
119 * by maintainers of various distribs.
120 *
Ilya Shipitsin856aabc2020-04-16 23:51:34 +0500121 * Our main execution point of the Lua is the function lua_resume(). A
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +0200122 * quick looking on the Lua sources displays a lua_lock() a the start
123 * of function and a lua_unlock() at the end of the function. So I
124 * conclude that the Lua thread safe mode just perform a mutex around
125 * all execution. So I prefer to do this in the HAProxy code, it will be
126 * easier for distro maintainers.
127 *
128 * Note that the HAProxy lua functions rounded by the macro SET_SAFE_LJMP
129 * and RESET_SAFE_LJMP manipulates the Lua stack, so it will be careful
130 * to set mutex around these functions.
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200131 */
Willy Tarreau86abe442018-11-25 20:12:18 +0100132__decl_spinlock(hlua_global_lock);
Thierry FOURNIERffbad792017-07-12 11:39:04 +0200133THREAD_LOCAL jmp_buf safe_ljmp_env;
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200134static int hlua_panic_safe(lua_State *L) { return 0; }
Willy Tarreau6a510902021-07-14 19:41:25 +0200135static int hlua_panic_ljmp(lua_State *L) { WILL_LJMP(longjmp(safe_ljmp_env, 1)); return 0; }
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200136
Thierry Fournier62a22aa2020-11-28 21:06:35 +0100137/* This is the chained list of struct hlua_function referenced
138 * for haproxy action, sample-fetches, converters, cli and
139 * applet bindings. It is used for a post-initialisation control.
140 */
141static struct list referenced_functions = LIST_HEAD_INIT(referenced_functions);
142
Thierry Fournierc7492592020-11-28 23:57:24 +0100143/* This variable is used only during initialization to identify the Lua state
144 * currently being initialized. 0 is the common lua state, 1 to n are the Lua
145 * states dedicated to each thread (in this case hlua_state_id==tid+1).
146 */
147static int hlua_state_id;
148
Thierry Fournier59f11be2020-11-29 00:37:41 +0100149/* This is a NULL-terminated list of lua file which are referenced to load per thread */
Thierry Fournierae6b5682022-09-19 09:04:16 +0200150static char ***per_thread_load = NULL;
Thierry Fournier59f11be2020-11-29 00:37:41 +0100151
152lua_State *hlua_init_state(int thread_id);
153
Willy Tarreau1e7bef12021-08-20 15:47:25 +0200154/* This function takes the Lua global lock. Keep this function's visibility
155 * global so that it can appear in stack dumps and performance profiles!
156 */
Aurelien DARRAGONe36f8032023-03-21 13:22:33 +0100157static inline void lua_take_global_lock()
Willy Tarreau1e7bef12021-08-20 15:47:25 +0200158{
159 HA_SPIN_LOCK(LUA_LOCK, &hlua_global_lock);
160}
161
162static inline void lua_drop_global_lock()
163{
164 HA_SPIN_UNLOCK(LUA_LOCK, &hlua_global_lock);
165}
166
Aurelien DARRAGON6b0b9bd2023-03-21 14:02:16 +0100167/* lua lock helpers: only lock when required
168 *
169 * state_id == 0: we're operating on the main lua stack (shared between
170 * os threads), so we need to acquire the main lock
171 *
172 * If the thread already owns the lock (_hlua_locked != 0), skip the lock
173 * attempt. This could happen if we run under protected lua environment.
174 * Not doing this could result in deadlocks because of nested locking
175 * attempts from the same thread
176 */
177static THREAD_LOCAL int _hlua_locked = 0;
Aurelien DARRAGONe36f8032023-03-21 13:22:33 +0100178static inline void hlua_lock(struct hlua *hlua)
179{
Aurelien DARRAGON6b0b9bd2023-03-21 14:02:16 +0100180 if (hlua->state_id != 0)
181 return;
182 if (!_hlua_locked)
Aurelien DARRAGONe36f8032023-03-21 13:22:33 +0100183 lua_take_global_lock();
Aurelien DARRAGON6b0b9bd2023-03-21 14:02:16 +0100184 _hlua_locked += 1;
Aurelien DARRAGONe36f8032023-03-21 13:22:33 +0100185}
186static inline void hlua_unlock(struct hlua *hlua)
187{
Aurelien DARRAGON6b0b9bd2023-03-21 14:02:16 +0100188 if (hlua->state_id != 0)
189 return;
190 BUG_ON(_hlua_locked <= 0);
191 _hlua_locked--;
192 /* drop the lock once the lock count reaches 0 */
193 if (!_hlua_locked)
Aurelien DARRAGONe36f8032023-03-21 13:22:33 +0100194 lua_drop_global_lock();
195}
196
Thierry Fournier7cbe5042020-11-28 17:02:21 +0100197#define SET_SAFE_LJMP_L(__L, __HLUA) \
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200198 ({ \
199 int ret; \
Aurelien DARRAGONe36f8032023-03-21 13:22:33 +0100200 hlua_lock(__HLUA); \
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200201 if (setjmp(safe_ljmp_env) != 0) { \
202 lua_atpanic(__L, hlua_panic_safe); \
203 ret = 0; \
Aurelien DARRAGONe36f8032023-03-21 13:22:33 +0100204 hlua_unlock(__HLUA); \
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200205 } else { \
206 lua_atpanic(__L, hlua_panic_ljmp); \
207 ret = 1; \
208 } \
209 ret; \
210 })
211
212/* If we are the last function catching Lua errors, we
213 * must reset the panic function.
214 */
Thierry Fournier7cbe5042020-11-28 17:02:21 +0100215#define RESET_SAFE_LJMP_L(__L, __HLUA) \
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200216 do { \
217 lua_atpanic(__L, hlua_panic_safe); \
Aurelien DARRAGONe36f8032023-03-21 13:22:33 +0100218 hlua_unlock(__HLUA); \
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200219 } while(0)
220
Thierry Fournier7cbe5042020-11-28 17:02:21 +0100221#define SET_SAFE_LJMP(__HLUA) \
222 SET_SAFE_LJMP_L((__HLUA)->T, __HLUA)
223
224#define RESET_SAFE_LJMP(__HLUA) \
225 RESET_SAFE_LJMP_L((__HLUA)->T, __HLUA)
226
227#define SET_SAFE_LJMP_PARENT(__HLUA) \
Thierry Fournier021d9862020-11-28 23:42:03 +0100228 SET_SAFE_LJMP_L(hlua_states[(__HLUA)->state_id], __HLUA)
Thierry Fournier7cbe5042020-11-28 17:02:21 +0100229
230#define RESET_SAFE_LJMP_PARENT(__HLUA) \
Thierry Fournier021d9862020-11-28 23:42:03 +0100231 RESET_SAFE_LJMP_L(hlua_states[(__HLUA)->state_id], __HLUA)
Thierry Fournier7cbe5042020-11-28 17:02:21 +0100232
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +0200233/* Applet status flags */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200234#define APPLET_DONE 0x01 /* applet processing is done. */
Christopher Faulet18c2e8d2019-03-01 12:02:08 +0100235/* unused: 0x02 */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200236#define APPLET_HDR_SENT 0x04 /* Response header sent. */
Christopher Fauleta2097962019-07-15 16:25:33 +0200237/* unused: 0x08, 0x10 */
Thierry FOURNIERd93ea2b2015-12-20 19:14:52 +0100238#define APPLET_HTTP11 0x20 /* Last chunk sent. */
Christopher Faulet56a3d6e2019-02-27 22:06:23 +0100239#define APPLET_RSP_SENT 0x40 /* The response was fully sent */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200240
Thierry Fournierafc63e22020-11-28 17:06:51 +0100241/* The main Lua execution context. The 0 index is the
242 * common state shared by all threads.
243 */
Willy Tarreau186f3762020-12-04 11:48:12 +0100244static lua_State *hlua_states[MAX_THREADS + 1];
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100245
Christopher Fauletc404f112020-02-26 15:03:09 +0100246#define HLUA_FLT_CB_FINAL 0x00000001
247#define HLUA_FLT_CB_RETVAL 0x00000002
248#define HLUA_FLT_CB_ARG_CHN 0x00000004
249#define HLUA_FLT_CB_ARG_HTTP_MSG 0x00000008
250
Christopher Faulet9f55a502020-02-25 15:21:02 +0100251#define HLUA_FLT_CTX_FL_PAYLOAD 0x00000001
252
Christopher Faulet69c581a2021-05-31 08:54:04 +0200253struct hlua_reg_filter {
254 char *name;
255 int flt_ref[MAX_THREADS + 1];
256 int fun_ref[MAX_THREADS + 1];
257 struct list l;
258};
259
260struct hlua_flt_config {
261 struct hlua_reg_filter *reg;
262 int ref[MAX_THREADS + 1];
263 char **args;
264};
265
266struct hlua_flt_ctx {
267 int ref; /* ref to the filter lua object */
268 struct hlua *hlua[2]; /* lua runtime context (0: request, 1: response) */
269 unsigned int cur_off[2]; /* current offset (0: request, 1: response) */
270 unsigned int cur_len[2]; /* current forwardable length (0: request, 1: response) */
271 unsigned int flags; /* HLUA_FLT_CTX_FL_* */
272};
273
Willy Tarreau5321da92022-05-06 11:57:34 +0200274/* appctx context used by the cosockets */
275struct hlua_csk_ctx {
276 int connected;
277 struct xref xref; /* cross reference with the Lua object owner. */
278 struct list wake_on_read;
279 struct list wake_on_write;
280 struct appctx *appctx;
281 int die;
282};
283
Willy Tarreaue23f33b2022-05-06 14:07:13 +0200284/* appctx context used by TCP services */
285struct hlua_tcp_ctx {
286 struct hlua *hlua;
287 int flags;
288 struct task *task;
289};
290
Willy Tarreauaa229cc2022-05-06 14:26:10 +0200291/* appctx context used by HTTP services */
292struct hlua_http_ctx {
293 struct hlua *hlua;
294 int left_bytes; /* The max amount of bytes that we can read. */
295 int flags;
296 int status;
297 const char *reason;
298 struct task *task;
299};
300
Willy Tarreaubcda5f62022-05-03 18:13:39 +0200301/* used by registered CLI keywords */
302struct hlua_cli_ctx {
303 struct hlua *hlua;
304 struct task *task;
305 struct hlua_function *fcn;
306};
307
Christopher Faulet69c581a2021-05-31 08:54:04 +0200308DECLARE_STATIC_POOL(pool_head_hlua_flt_ctx, "hlua_flt_ctx", sizeof(struct hlua_flt_ctx));
309
Christopher Faulet9f55a502020-02-25 15:21:02 +0100310static int hlua_filter_from_payload(struct filter *filter);
311
Christopher Faulet69c581a2021-05-31 08:54:04 +0200312/* This is the chained list of struct hlua_flt referenced
313 * for haproxy filters. It is used for a post-initialisation control.
314 */
315static struct list referenced_filters = LIST_HEAD_INIT(referenced_filters);
316
317
Thierry FOURNIERebed6e92016-12-16 11:54:07 +0100318/* This is the memory pool containing struct lua for applets
319 * (including cli).
320 */
Willy Tarreau8ceae722018-11-26 11:58:30 +0100321DECLARE_STATIC_POOL(pool_head_hlua, "hlua", sizeof(struct hlua));
Thierry FOURNIERebed6e92016-12-16 11:54:07 +0100322
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +0100323/* Used for Socket connection. */
Amaury Denoyelle239fdbf2021-03-24 10:22:03 +0100324static struct proxy *socket_proxy;
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +0100325static struct server *socket_tcp;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +0100326#ifdef USE_OPENSSL
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +0100327static struct server *socket_ssl;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +0100328#endif
329
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +0100330/* List head of the function called at the initialisation time. */
Thierry Fournierc7492592020-11-28 23:57:24 +0100331struct list hlua_init_functions[MAX_THREADS + 1];
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +0100332
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +0100333/* The following variables contains the reference of the different
334 * Lua classes. These references are useful for identify metadata
335 * associated with an object.
336 */
Thierry FOURNIER65f34c62015-02-16 20:11:43 +0100337static int class_txn_ref;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +0100338static int class_socket_ref;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +0100339static int class_channel_ref;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +0100340static int class_fetches_ref;
Thierry FOURNIER594afe72015-03-10 23:58:30 +0100341static int class_converters_ref;
Thierry FOURNIER08504f42015-03-16 14:17:08 +0100342static int class_http_ref;
Christopher Fauletdf97ac42020-02-26 16:57:19 +0100343static int class_http_msg_ref;
William Lallemand3956c4e2021-09-21 16:25:15 +0200344static int class_httpclient_ref;
Thierry FOURNIER3def3932015-04-07 11:27:54 +0200345static int class_map_ref;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +0200346static int class_applet_tcp_ref;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200347static int class_applet_http_ref;
Christopher Faulet700d9e82020-01-31 12:21:52 +0100348static int class_txn_reply_ref;
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +0100349
Aurelien DARRAGONda9503c2022-11-25 09:10:07 +0100350/* Lua max execution timeouts. By default, stream-related
351 * lua coroutines (e.g.: actions) have a short timeout.
352 * On the other hand tasks coroutines don't have a timeout because
353 * a task may remain alive during all the haproxy execution.
354 *
355 * Timeouts are expressed in milliseconds, they are meant to be used
356 * with hlua timer's API exclusively.
357 * 0 means no timeout
358 */
Aurelien DARRAGON58e36e52023-04-06 22:51:56 +0200359static uint32_t hlua_timeout_burst = 1000; /* burst timeout. */
Aurelien DARRAGONda9503c2022-11-25 09:10:07 +0100360static uint32_t hlua_timeout_session = 4000; /* session timeout. */
361static uint32_t hlua_timeout_task = 0; /* task timeout. */
362static uint32_t hlua_timeout_applet = 4000; /* applet timeout. */
363
364/* hlua multipurpose timer:
365 * used to compute burst lua time (within a single hlua_ctx_resume())
366 * and cumulative lua time for a given coroutine, and to check
367 * the lua coroutine against the configured timeouts
368 */
369
370/* fetch per-thread cpu_time with ms precision (may wrap) */
371static inline uint32_t _hlua_time_ms()
372{
373 /* We're interested in the current cpu time in ms, which will be returned
374 * as a uint32_t to save some space.
375 * We must take the following into account:
376 *
377 * - now_cpu_time_fast() which returns the time in nanoseconds as a uint64_t
378 * will wrap every 585 years.
379 * - uint32_t may only contain 4294967295ms (~=49.7 days), so _hlua_time_ms()
380 * itself will also wrap every 49.7 days.
381 *
382 * While we can safely ignore the now_cpu_time_fast() wrap, we must
383 * take care of the uint32_t wrap by making sure to exclusively
384 * manipulate the time using uint32_t everywhere _hlua_time_ms()
385 * is involved.
386 */
387 return (uint32_t)(now_cpu_time_fast() / 1000000ULL);
388}
389
390/* computes time spent in a single lua execution (in ms) */
391static inline uint32_t _hlua_time_burst(const struct hlua_timer *timer)
392{
393 uint32_t burst_ms;
394
395 /* wrapping is expected and properly
396 * handled thanks to _hlua_time_ms() and burst_ms
397 * being of the same type
398 */
399 burst_ms = _hlua_time_ms() - timer->start;
400 return burst_ms;
401}
402
403static inline void hlua_timer_init(struct hlua_timer *timer, unsigned int max)
404{
405 timer->cumulative = 0;
406 timer->burst = 0;
407 timer->max = max;
408}
409
410/* reset the timer ctx between 2 yields */
411static inline void hlua_timer_reset(struct hlua_timer *timer)
412{
413 timer->cumulative += timer->burst;
414 timer->burst = 0;
415}
416
417/* start the timer right before a new execution */
418static inline void hlua_timer_start(struct hlua_timer *timer)
419{
420 timer->start = _hlua_time_ms();
421}
422
423/* update hlua timer when finishing an execution */
424static inline void hlua_timer_stop(struct hlua_timer *timer)
425{
426 timer->burst += _hlua_time_burst(timer);
427}
428
Aurelien DARRAGON58e36e52023-04-06 22:51:56 +0200429/* check the timers for current hlua context:
430 * - first check for burst timeout (max execution time for the current
431 hlua resume, ie: time between effective yields)
432 * - then check for yield cumulative timeout
433 *
Aurelien DARRAGONda9503c2022-11-25 09:10:07 +0100434 * Returns 1 if the check succeeded and 0 if it failed
435 * (ie: timeout exceeded)
Thierry FOURNIERbd413492015-03-03 16:52:26 +0100436 */
Aurelien DARRAGONda9503c2022-11-25 09:10:07 +0100437static inline int hlua_timer_check(const struct hlua_timer *timer)
438{
439 uint32_t pburst = _hlua_time_burst(timer); /* pending burst time in ms */
440
Aurelien DARRAGON58e36e52023-04-06 22:51:56 +0200441 if (hlua_timeout_burst && (timer->burst + pburst) > hlua_timeout_burst)
442 return 0; /* burst timeout exceeded */
Aurelien DARRAGONda9503c2022-11-25 09:10:07 +0100443 if (timer->max && (timer->cumulative + timer->burst + pburst) > timer->max)
444 return 0; /* cumulative timeout exceeded */
445 return 1; /* ok */
446}
Thierry FOURNIERbd413492015-03-03 16:52:26 +0100447
Thierry FOURNIERee9f8022015-03-03 17:37:37 +0100448/* Interrupts the Lua processing each "hlua_nb_instruction" instructions.
449 * it is used for preventing infinite loops.
450 *
451 * I test the scheer with an infinite loop containing one incrementation
452 * and one test. I run this loop between 10 seconds, I raise a ceil of
453 * 710M loops from one interrupt each 9000 instructions, so I fix the value
454 * to one interrupt each 10 000 instructions.
455 *
456 * configured | Number of
457 * instructions | loops executed
458 * between two | in milions
459 * forced yields |
460 * ---------------+---------------
461 * 10 | 160
462 * 500 | 670
463 * 1000 | 680
464 * 5000 | 700
465 * 7000 | 700
466 * 8000 | 700
467 * 9000 | 710 <- ceil
468 * 10000 | 710
469 * 100000 | 710
470 * 1000000 | 710
471 *
472 */
473static unsigned int hlua_nb_instruction = 10000;
474
Willy Tarreaucdb53462020-12-02 12:12:00 +0100475/* Descriptor for the memory allocation state. The limit is pre-initialised to
476 * 0 until it is replaced by "tune.lua.maxmem" during the config parsing, or it
477 * is replaced with ~0 during post_init after everything was loaded. This way
478 * it is guaranteed that if limit is ~0 the boot is complete and that if it's
479 * zero it's not yet limited and proper accounting is required.
Willy Tarreau32f61e22015-03-18 17:54:59 +0100480 */
481struct hlua_mem_allocator {
482 size_t allocated;
483 size_t limit;
484};
485
Willy Tarreaucdb53462020-12-02 12:12:00 +0100486static struct hlua_mem_allocator hlua_global_allocator THREAD_ALIGNED(64);
Willy Tarreau32f61e22015-03-18 17:54:59 +0100487
Aurelien DARRAGONc84899c2023-02-20 18:18:59 +0100488/* hlua event subscription */
489struct hlua_event_sub {
490 int fcn_ref;
491 int state_id;
492 struct hlua *hlua;
493 struct task *task;
494 event_hdl_async_equeue equeue;
495 struct event_hdl_sub *sub;
496 uint8_t paused;
497};
498
499/* This is the memory pool containing struct hlua_event_sub
500 * for event subscriptions from lua
501 */
502DECLARE_STATIC_POOL(pool_head_hlua_event_sub, "hlua_esub", sizeof(struct hlua_event_sub));
503
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100504/* These functions converts types between HAProxy internal args or
505 * sample and LUA types. Another function permits to check if the
506 * LUA stack contains arguments according with an required ARG_T
507 * format.
508 */
509static int hlua_arg2lua(lua_State *L, const struct arg *arg);
510static int hlua_lua2arg(lua_State *L, int ud, struct arg *arg);
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100511__LJMP static int hlua_lua2arg_check(lua_State *L, int first, struct arg *argp,
David Carlier0c437f42016-04-27 16:21:56 +0100512 uint64_t mask, struct proxy *p);
Willy Tarreau5eadada2015-03-10 17:28:54 +0100513static int hlua_smp2lua(lua_State *L, struct sample *smp);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100514static int hlua_smp2lua_str(lua_State *L, struct sample *smp);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100515static int hlua_lua2smp(lua_State *L, int ud, struct sample *smp);
516
Christopher Faulet9d1332b2020-02-24 16:46:16 +0100517__LJMP static int hlua_http_get_headers(lua_State *L, struct http_msg *msg);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200518
Thierry Fournier59f11be2020-11-29 00:37:41 +0100519struct prepend_path {
520 struct list l;
521 char *type;
522 char *path;
523};
524
525static struct list prepend_path_list = LIST_HEAD_INIT(prepend_path_list);
526
Thierry FOURNIER23bc3752015-09-11 19:15:43 +0200527#define SEND_ERR(__be, __fmt, __args...) \
528 do { \
529 send_log(__be, LOG_ERR, __fmt, ## __args); \
530 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE)) \
Christopher Faulet767a84b2017-11-24 16:50:31 +0100531 ha_alert(__fmt, ## __args); \
Thierry FOURNIER23bc3752015-09-11 19:15:43 +0200532 } while (0)
533
Thierry Fournier62a22aa2020-11-28 21:06:35 +0100534static inline struct hlua_function *new_hlua_function()
535{
536 struct hlua_function *fcn;
Thierry Fournierc7492592020-11-28 23:57:24 +0100537 int i;
Thierry Fournier62a22aa2020-11-28 21:06:35 +0100538
539 fcn = calloc(1, sizeof(*fcn));
540 if (!fcn)
541 return NULL;
Willy Tarreau2b718102021-04-21 07:32:39 +0200542 LIST_APPEND(&referenced_functions, &fcn->l);
Thierry Fournierc7492592020-11-28 23:57:24 +0100543 for (i = 0; i < MAX_THREADS + 1; i++)
544 fcn->function_ref[i] = -1;
Thierry Fournier62a22aa2020-11-28 21:06:35 +0100545 return fcn;
546}
547
Christopher Fauletdda44442021-04-12 14:05:43 +0200548static inline void release_hlua_function(struct hlua_function *fcn)
549{
550 if (!fcn)
551 return;
552 if (fcn->name)
553 ha_free(&fcn->name);
Willy Tarreau2b718102021-04-21 07:32:39 +0200554 LIST_DELETE(&fcn->l);
Christopher Fauletdda44442021-04-12 14:05:43 +0200555 ha_free(&fcn);
556}
557
Thierry Fournierc7492592020-11-28 23:57:24 +0100558/* If the common state is set, the stack id is 0, otherwise it is the tid + 1 */
559static inline int fcn_ref_to_stack_id(struct hlua_function *fcn)
560{
561 if (fcn->function_ref[0] == -1)
562 return tid + 1;
563 return 0;
564}
565
Christopher Faulet69c581a2021-05-31 08:54:04 +0200566/* Create a new registered filter. Only its name is filled */
567static inline struct hlua_reg_filter *new_hlua_reg_filter(const char *name)
568{
569 struct hlua_reg_filter *reg_flt;
570 int i;
571
572 reg_flt = calloc(1, sizeof(*reg_flt));
573 if (!reg_flt)
574 return NULL;
575 reg_flt->name = strdup(name);
576 if (!reg_flt->name) {
577 free(reg_flt);
578 return NULL;
579 }
580 LIST_APPEND(&referenced_filters, &reg_flt->l);
581 for (i = 0; i < MAX_THREADS + 1; i++) {
582 reg_flt->flt_ref[i] = -1;
583 reg_flt->fun_ref[i] = -1;
584 }
585 return reg_flt;
586}
587
588/* Release a registered filter */
589static inline void release_hlua_reg_filter(struct hlua_reg_filter *reg_flt)
590{
591 if (!reg_flt)
592 return;
593 if (reg_flt->name)
594 ha_free(&reg_flt->name);
595 LIST_DELETE(&reg_flt->l);
596 ha_free(&reg_flt);
597}
598
599/* If the common state is set, the stack id is 0, otherwise it is the tid + 1 */
600static inline int reg_flt_to_stack_id(struct hlua_reg_filter *reg_flt)
601{
602 if (reg_flt->fun_ref[0] == -1)
603 return tid + 1;
604 return 0;
605}
606
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100607/* Used to check an Lua function type in the stack. It creates and
608 * returns a reference of the function. This function throws an
Aurelien DARRAGONf8f8a2b2023-03-02 17:50:49 +0100609 * error if the argument is not a "function".
610 * When no longer used, the ref must be released with hlua_unref()
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100611 */
Aurelien DARRAGON9ee0d042023-03-20 18:36:08 +0100612__LJMP int hlua_checkfunction(lua_State *L, int argno)
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100613{
614 if (!lua_isfunction(L, argno)) {
Thierry FOURNIERfd1e9552018-02-23 18:41:18 +0100615 const char *msg = lua_pushfstring(L, "function expected, got %s", luaL_typename(L, argno));
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100616 WILL_LJMP(luaL_argerror(L, argno, msg));
617 }
618 lua_pushvalue(L, argno);
619 return luaL_ref(L, LUA_REGISTRYINDEX);
620}
621
Christopher Fauletba9e21d2020-02-25 10:20:04 +0100622/* Used to check an Lua table type in the stack. It creates and
623 * returns a reference of the table. This function throws an
Aurelien DARRAGONf8f8a2b2023-03-02 17:50:49 +0100624 * error if the argument is not a "table".
625 * When no longer used, the ref must be released with hlua_unref()
Christopher Fauletba9e21d2020-02-25 10:20:04 +0100626 */
Aurelien DARRAGON9ee0d042023-03-20 18:36:08 +0100627__LJMP int hlua_checktable(lua_State *L, int argno)
Christopher Fauletba9e21d2020-02-25 10:20:04 +0100628{
629 if (!lua_istable(L, argno)) {
630 const char *msg = lua_pushfstring(L, "table expected, got %s", luaL_typename(L, argno));
631 WILL_LJMP(luaL_argerror(L, argno, msg));
632 }
633 lua_pushvalue(L, argno);
634 return luaL_ref(L, LUA_REGISTRYINDEX);
635}
636
Aurelien DARRAGONf8f8a2b2023-03-02 17:50:49 +0100637/* Get a reference to the object that is at the top of the stack
638 * The referenced object will be popped from the stack
639 *
640 * The function returns the reference to the object which must
641 * be cleared using hlua_unref() when no longer used
642 */
643__LJMP int hlua_ref(lua_State *L)
644{
645 return MAY_LJMP(luaL_ref(L, LUA_REGISTRYINDEX));
646}
647
648/* Pushes a reference previously created using luaL_ref(L, LUA_REGISTRYINDEX)
649 * on <L> stack
650 * (ie: hlua_checkfunction(), hlua_checktable() or hlua_ref())
651 *
652 * When the reference is no longer used, it should be released by calling
653 * hlua_unref()
654 *
655 * <L> can be from any co-routine as long as it belongs to the same lua
656 * parent state that the one used to get the reference.
657 */
658void hlua_pushref(lua_State *L, int ref)
659{
660 lua_rawgeti(L, LUA_REGISTRYINDEX, ref);
661}
662
663/* Releases a reference previously created using luaL_ref(L, LUA_REGISTRYINDEX)
664 * (ie: hlua_checkfunction(), hlua_checktable() or hlua_ref())
665 *
666 * This will allow the reference to be reused and the referred object
667 * to be garbage collected.
668 *
669 * <L> can be from any co-routine as long as it belongs to the same lua
670 * parent state that the one used to get the reference.
671 */
672void hlua_unref(lua_State *L, int ref)
673{
674 luaL_unref(L, LUA_REGISTRYINDEX, ref);
675}
676
Christopher Fauletd09cc512021-03-24 14:48:45 +0100677__LJMP const char *hlua_traceback(lua_State *L, const char* sep)
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200678{
679 lua_Debug ar;
680 int level = 0;
Willy Tarreau83061a82018-07-13 11:56:34 +0200681 struct buffer *msg = get_trash_chunk();
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200682
683 while (lua_getstack(L, level++, &ar)) {
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200684 /* Fill fields:
685 * 'S': fills in the fields source, short_src, linedefined, lastlinedefined, and what;
686 * 'l': fills in the field currentline;
687 * 'n': fills in the field name and namewhat;
688 * 't': fills in the field istailcall;
689 */
690 lua_getinfo(L, "Slnt", &ar);
691
Willy Tarreau5c143402022-06-19 17:35:53 +0200692 /* skip these empty entries, usually they come from deep C functions */
693 if (ar.currentline < 0 && *ar.what == 'C' && !*ar.namewhat && !ar.name)
694 continue;
695
696 /* Add separator */
697 if (b_data(msg))
698 chunk_appendf(msg, "%s", sep);
699
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200700 /* Append code localisation */
701 if (ar.currentline > 0)
Christopher Fauletd09cc512021-03-24 14:48:45 +0100702 chunk_appendf(msg, "%s:%d: ", ar.short_src, ar.currentline);
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200703 else
Christopher Fauletd09cc512021-03-24 14:48:45 +0100704 chunk_appendf(msg, "%s: ", ar.short_src);
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200705
706 /*
707 * Get function name
708 *
709 * if namewhat is no empty, name is defined.
710 * what contains "Lua" for Lua function, "C" for C function,
711 * or "main" for main code.
712 */
713 if (*ar.namewhat != '\0' && ar.name != NULL) /* is there a name from code? */
Christopher Fauletd09cc512021-03-24 14:48:45 +0100714 chunk_appendf(msg, "in %s '%s'", ar.namewhat, ar.name); /* use it */
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200715
716 else if (*ar.what == 'm') /* "main", the code is not executed in a function */
Christopher Fauletd09cc512021-03-24 14:48:45 +0100717 chunk_appendf(msg, "in main chunk");
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200718
719 else if (*ar.what != 'C') /* for Lua functions, use <file:line> */
Christopher Fauletd09cc512021-03-24 14:48:45 +0100720 chunk_appendf(msg, "in function line %d", ar.linedefined);
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200721
722 else /* nothing left... */
723 chunk_appendf(msg, "?");
724
725
726 /* Display tailed call */
727 if (ar.istailcall)
728 chunk_appendf(msg, " ...");
729 }
730
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200731 return msg->area;
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200732}
733
734
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100735/* This function check the number of arguments available in the
736 * stack. If the number of arguments available is not the same
Ilya Shipitsinc02a23f2020-05-06 00:53:22 +0500737 * then <nb> an error is thrown.
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100738 */
739__LJMP static inline void check_args(lua_State *L, int nb, char *fcn)
740{
741 if (lua_gettop(L) == nb)
742 return;
743 WILL_LJMP(luaL_error(L, "'%s' needs %d arguments", fcn, nb));
744}
745
Mark Lakes22154b42018-01-29 14:38:40 -0800746/* This function pushes an error string prefixed by the file name
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100747 * and the line number where the error is encountered.
748 */
749static int hlua_pusherror(lua_State *L, const char *fmt, ...)
750{
751 va_list argp;
752 va_start(argp, fmt);
753 luaL_where(L, 1);
754 lua_pushvfstring(L, fmt, argp);
755 va_end(argp);
756 lua_concat(L, 2);
757 return 1;
758}
759
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100760/* This functions is used with sample fetch and converters. It
761 * converts the HAProxy configuration argument in a lua stack
762 * values.
763 *
764 * It takes an array of "arg", and each entry of the array is
765 * converted and pushed in the LUA stack.
766 */
767static int hlua_arg2lua(lua_State *L, const struct arg *arg)
768{
769 switch (arg->type) {
770 case ARGT_SINT:
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100771 case ARGT_TIME:
772 case ARGT_SIZE:
Thierry FOURNIERf90838b2015-03-06 13:48:32 +0100773 lua_pushinteger(L, arg->data.sint);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100774 break;
775
776 case ARGT_STR:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200777 lua_pushlstring(L, arg->data.str.area, arg->data.str.data);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100778 break;
779
780 case ARGT_IPV4:
781 case ARGT_IPV6:
782 case ARGT_MSK4:
783 case ARGT_MSK6:
784 case ARGT_FE:
785 case ARGT_BE:
786 case ARGT_TAB:
787 case ARGT_SRV:
788 case ARGT_USR:
789 case ARGT_MAP:
790 default:
791 lua_pushnil(L);
792 break;
793 }
794 return 1;
795}
796
Ilya Shipitsinc02a23f2020-05-06 00:53:22 +0500797/* This function take one entry in an LUA stack at the index "ud",
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100798 * and try to convert it in an HAProxy argument entry. This is useful
Ilya Shipitsind4259502020-04-08 01:07:56 +0500799 * with sample fetch wrappers. The input arguments are given to the
800 * lua wrapper and converted as arg list by the function.
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100801 */
802static int hlua_lua2arg(lua_State *L, int ud, struct arg *arg)
803{
804 switch (lua_type(L, ud)) {
805
806 case LUA_TNUMBER:
807 case LUA_TBOOLEAN:
808 arg->type = ARGT_SINT;
809 arg->data.sint = lua_tointeger(L, ud);
810 break;
811
812 case LUA_TSTRING:
813 arg->type = ARGT_STR;
Tim Duesterhus2e89dec2019-09-29 23:03:08 +0200814 arg->data.str.area = (char *)lua_tolstring(L, ud, &arg->data.str.data);
Tim Duesterhus29d2e8a2019-09-29 23:03:07 +0200815 /* We don't know the actual size of the underlying allocation, so be conservative. */
Christopher Fauletfdea1b62020-08-06 08:29:18 +0200816 arg->data.str.size = arg->data.str.data+1; /* count the terminating null byte */
Tim Duesterhus29d2e8a2019-09-29 23:03:07 +0200817 arg->data.str.head = 0;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100818 break;
819
820 case LUA_TUSERDATA:
821 case LUA_TNIL:
822 case LUA_TTABLE:
823 case LUA_TFUNCTION:
824 case LUA_TTHREAD:
825 case LUA_TLIGHTUSERDATA:
826 arg->type = ARGT_SINT;
Thierry FOURNIERbf65cd42015-07-20 17:45:02 +0200827 arg->data.sint = 0;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100828 break;
829 }
830 return 1;
831}
832
833/* the following functions are used to convert a struct sample
834 * in Lua type. This useful to convert the return of the
Ilya Shipitsind4259502020-04-08 01:07:56 +0500835 * fetches or converters.
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100836 */
Willy Tarreau5eadada2015-03-10 17:28:54 +0100837static int hlua_smp2lua(lua_State *L, struct sample *smp)
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100838{
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200839 switch (smp->data.type) {
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100840 case SMP_T_SINT:
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100841 case SMP_T_BOOL:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200842 lua_pushinteger(L, smp->data.u.sint);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100843 break;
844
845 case SMP_T_BIN:
846 case SMP_T_STR:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200847 lua_pushlstring(L, smp->data.u.str.area, smp->data.u.str.data);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100848 break;
849
850 case SMP_T_METH:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200851 switch (smp->data.u.meth.meth) {
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100852 case HTTP_METH_OPTIONS: lua_pushstring(L, "OPTIONS"); break;
853 case HTTP_METH_GET: lua_pushstring(L, "GET"); break;
854 case HTTP_METH_HEAD: lua_pushstring(L, "HEAD"); break;
855 case HTTP_METH_POST: lua_pushstring(L, "POST"); break;
856 case HTTP_METH_PUT: lua_pushstring(L, "PUT"); break;
857 case HTTP_METH_DELETE: lua_pushstring(L, "DELETE"); break;
858 case HTTP_METH_TRACE: lua_pushstring(L, "TRACE"); break;
859 case HTTP_METH_CONNECT: lua_pushstring(L, "CONNECT"); break;
860 case HTTP_METH_OTHER:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200861 lua_pushlstring(L, smp->data.u.meth.str.area, smp->data.u.meth.str.data);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100862 break;
863 default:
864 lua_pushnil(L);
865 break;
866 }
867 break;
868
869 case SMP_T_IPV4:
870 case SMP_T_IPV6:
871 case SMP_T_ADDR: /* This type is never used to qualify a sample. */
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200872 if (sample_casts[smp->data.type][SMP_T_STR] &&
873 sample_casts[smp->data.type][SMP_T_STR](smp))
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200874 lua_pushlstring(L, smp->data.u.str.area, smp->data.u.str.data);
Willy Tarreau5eadada2015-03-10 17:28:54 +0100875 else
876 lua_pushnil(L);
877 break;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100878 default:
879 lua_pushnil(L);
880 break;
881 }
882 return 1;
883}
884
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100885/* the following functions are used to convert a struct sample
886 * in Lua strings. This is useful to convert the return of the
Ilya Shipitsind4259502020-04-08 01:07:56 +0500887 * fetches or converters.
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100888 */
889static int hlua_smp2lua_str(lua_State *L, struct sample *smp)
890{
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200891 switch (smp->data.type) {
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100892
893 case SMP_T_BIN:
894 case SMP_T_STR:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200895 lua_pushlstring(L, smp->data.u.str.area, smp->data.u.str.data);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100896 break;
897
898 case SMP_T_METH:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200899 switch (smp->data.u.meth.meth) {
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100900 case HTTP_METH_OPTIONS: lua_pushstring(L, "OPTIONS"); break;
901 case HTTP_METH_GET: lua_pushstring(L, "GET"); break;
902 case HTTP_METH_HEAD: lua_pushstring(L, "HEAD"); break;
903 case HTTP_METH_POST: lua_pushstring(L, "POST"); break;
904 case HTTP_METH_PUT: lua_pushstring(L, "PUT"); break;
905 case HTTP_METH_DELETE: lua_pushstring(L, "DELETE"); break;
906 case HTTP_METH_TRACE: lua_pushstring(L, "TRACE"); break;
907 case HTTP_METH_CONNECT: lua_pushstring(L, "CONNECT"); break;
908 case HTTP_METH_OTHER:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200909 lua_pushlstring(L, smp->data.u.meth.str.area, smp->data.u.meth.str.data);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100910 break;
911 default:
912 lua_pushstring(L, "");
913 break;
914 }
915 break;
916
917 case SMP_T_SINT:
918 case SMP_T_BOOL:
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100919 case SMP_T_IPV4:
920 case SMP_T_IPV6:
921 case SMP_T_ADDR: /* This type is never used to qualify a sample. */
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200922 if (sample_casts[smp->data.type][SMP_T_STR] &&
923 sample_casts[smp->data.type][SMP_T_STR](smp))
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200924 lua_pushlstring(L, smp->data.u.str.area, smp->data.u.str.data);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100925 else
926 lua_pushstring(L, "");
927 break;
928 default:
929 lua_pushstring(L, "");
930 break;
931 }
932 return 1;
933}
934
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100935/* the following functions are used to convert an Lua type in a
936 * struct sample. This is useful to provide data from a converter
937 * to the LUA code.
938 */
939static int hlua_lua2smp(lua_State *L, int ud, struct sample *smp)
940{
941 switch (lua_type(L, ud)) {
942
943 case LUA_TNUMBER:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200944 smp->data.type = SMP_T_SINT;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200945 smp->data.u.sint = lua_tointeger(L, ud);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100946 break;
947
948
949 case LUA_TBOOLEAN:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200950 smp->data.type = SMP_T_BOOL;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200951 smp->data.u.sint = lua_toboolean(L, ud);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100952 break;
953
954 case LUA_TSTRING:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200955 smp->data.type = SMP_T_STR;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100956 smp->flags |= SMP_F_CONST;
Tim Duesterhus2e89dec2019-09-29 23:03:08 +0200957 smp->data.u.str.area = (char *)lua_tolstring(L, ud, &smp->data.u.str.data);
Tim Duesterhus29d2e8a2019-09-29 23:03:07 +0200958 /* We don't know the actual size of the underlying allocation, so be conservative. */
Christopher Fauletfdea1b62020-08-06 08:29:18 +0200959 smp->data.u.str.size = smp->data.u.str.data+1; /* count the terminating null byte */
Tim Duesterhus29d2e8a2019-09-29 23:03:07 +0200960 smp->data.u.str.head = 0;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100961 break;
962
963 case LUA_TUSERDATA:
964 case LUA_TNIL:
965 case LUA_TTABLE:
966 case LUA_TFUNCTION:
967 case LUA_TTHREAD:
968 case LUA_TLIGHTUSERDATA:
Thierry FOURNIER93405e12015-08-26 14:19:03 +0200969 case LUA_TNONE:
970 default:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200971 smp->data.type = SMP_T_BOOL;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200972 smp->data.u.sint = 0;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100973 break;
974 }
975 return 1;
976}
977
Ilya Shipitsind4259502020-04-08 01:07:56 +0500978/* This function check the "argp" built by another conversion function
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -0800979 * is in accord with the expected argp defined by the "mask". The function
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100980 * returns true or false. It can be adjust the types if there compatibles.
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100981 *
Ilya Shipitsinc02a23f2020-05-06 00:53:22 +0500982 * This function assumes that the argp argument contains ARGM_NBARGS + 1
Willy Tarreauee0d7272021-07-16 10:26:56 +0200983 * entries and that there is at least one stop at the last position.
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100984 */
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100985__LJMP int hlua_lua2arg_check(lua_State *L, int first, struct arg *argp,
David Carlier0c437f42016-04-27 16:21:56 +0100986 uint64_t mask, struct proxy *p)
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100987{
988 int min_arg;
Willy Tarreauee0d7272021-07-16 10:26:56 +0200989 int idx;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100990 struct proxy *px;
Christopher Fauletd25d9262020-08-06 11:04:46 +0200991 struct userlist *ul;
Christopher Fauletfd2e9062020-08-06 11:10:57 +0200992 struct my_regex *reg;
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200993 const char *msg = NULL;
Christopher Fauletfd2e9062020-08-06 11:10:57 +0200994 char *sname, *pname, *err = NULL;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100995
996 idx = 0;
997 min_arg = ARGM(mask);
998 mask >>= ARGM_BITS;
999
1000 while (1) {
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001001 struct buffer tmp = BUF_NULL;
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001002
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001003 /* Check for mandatory arguments. */
1004 if (argp[idx].type == ARGT_STOP) {
Thierry FOURNIER3caa0392015-03-13 13:38:17 +01001005 if (idx < min_arg) {
1006
1007 /* If miss other argument than the first one, we return an error. */
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001008 if (idx > 0) {
1009 msg = "Mandatory argument expected";
1010 goto error;
1011 }
Thierry FOURNIER3caa0392015-03-13 13:38:17 +01001012
1013 /* If first argument have a certain type, some default values
1014 * may be used. See the function smp_resolve_args().
1015 */
1016 switch (mask & ARGT_MASK) {
1017
1018 case ARGT_FE:
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001019 if (!(p->cap & PR_CAP_FE)) {
1020 msg = "Mandatory argument expected";
1021 goto error;
1022 }
Thierry FOURNIER3caa0392015-03-13 13:38:17 +01001023 argp[idx].data.prx = p;
1024 argp[idx].type = ARGT_FE;
1025 argp[idx+1].type = ARGT_STOP;
1026 break;
1027
1028 case ARGT_BE:
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001029 if (!(p->cap & PR_CAP_BE)) {
1030 msg = "Mandatory argument expected";
1031 goto error;
1032 }
Thierry FOURNIER3caa0392015-03-13 13:38:17 +01001033 argp[idx].data.prx = p;
1034 argp[idx].type = ARGT_BE;
1035 argp[idx+1].type = ARGT_STOP;
1036 break;
1037
1038 case ARGT_TAB:
Olivier Houchard14f62682022-09-13 00:35:53 +02001039 if (!p->table) {
1040 msg = "Mandatory argument expected";
1041 goto error;
1042 }
1043 argp[idx].data.t = p->table;
Thierry FOURNIER3caa0392015-03-13 13:38:17 +01001044 argp[idx].type = ARGT_TAB;
1045 argp[idx+1].type = ARGT_STOP;
1046 break;
1047
1048 default:
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001049 msg = "Mandatory argument expected";
1050 goto error;
Thierry FOURNIER3caa0392015-03-13 13:38:17 +01001051 break;
1052 }
1053 }
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001054 break;
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001055 }
1056
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001057 /* Check for exceed the number of required argument. */
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001058 if ((mask & ARGT_MASK) == ARGT_STOP &&
1059 argp[idx].type != ARGT_STOP) {
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001060 msg = "Last argument expected";
1061 goto error;
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001062 }
1063
1064 if ((mask & ARGT_MASK) == ARGT_STOP &&
1065 argp[idx].type == ARGT_STOP) {
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001066 break;
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001067 }
1068
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001069 /* Convert some argument types. All string in argp[] are for not
1070 * duplicated yet.
1071 */
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001072 switch (mask & ARGT_MASK) {
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001073 case ARGT_SINT:
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001074 if (argp[idx].type != ARGT_SINT) {
1075 msg = "integer expected";
1076 goto error;
1077 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001078 argp[idx].type = ARGT_SINT;
1079 break;
1080
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001081 case ARGT_TIME:
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001082 if (argp[idx].type != ARGT_SINT) {
1083 msg = "integer expected";
1084 goto error;
1085 }
Thierry FOURNIER29176f32015-07-07 00:41:29 +02001086 argp[idx].type = ARGT_TIME;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001087 break;
1088
1089 case ARGT_SIZE:
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001090 if (argp[idx].type != ARGT_SINT) {
1091 msg = "integer expected";
1092 goto error;
1093 }
Thierry FOURNIER29176f32015-07-07 00:41:29 +02001094 argp[idx].type = ARGT_SIZE;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001095 break;
1096
1097 case ARGT_FE:
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001098 if (argp[idx].type != ARGT_STR) {
1099 msg = "string expected";
1100 goto error;
1101 }
Christopher Fauletfdea1b62020-08-06 08:29:18 +02001102 argp[idx].data.prx = proxy_fe_by_name(argp[idx].data.str.area);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001103 if (!argp[idx].data.prx) {
1104 msg = "frontend doesn't exist";
1105 goto error;
1106 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001107 argp[idx].type = ARGT_FE;
1108 break;
1109
1110 case ARGT_BE:
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001111 if (argp[idx].type != ARGT_STR) {
1112 msg = "string expected";
1113 goto error;
1114 }
Christopher Fauletfdea1b62020-08-06 08:29:18 +02001115 argp[idx].data.prx = proxy_be_by_name(argp[idx].data.str.area);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001116 if (!argp[idx].data.prx) {
1117 msg = "backend doesn't exist";
1118 goto error;
1119 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001120 argp[idx].type = ARGT_BE;
1121 break;
1122
1123 case ARGT_TAB:
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001124 if (argp[idx].type != ARGT_STR) {
1125 msg = "string expected";
1126 goto error;
1127 }
Christopher Fauletfdea1b62020-08-06 08:29:18 +02001128 argp[idx].data.t = stktable_find_by_name(argp[idx].data.str.area);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001129 if (!argp[idx].data.t) {
1130 msg = "table doesn't exist";
1131 goto error;
1132 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001133 argp[idx].type = ARGT_TAB;
1134 break;
1135
1136 case ARGT_SRV:
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001137 if (argp[idx].type != ARGT_STR) {
1138 msg = "string expected";
1139 goto error;
1140 }
Christopher Fauletfdea1b62020-08-06 08:29:18 +02001141 sname = strrchr(argp[idx].data.str.area, '/');
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001142 if (sname) {
1143 *sname++ = '\0';
Christopher Fauletfdea1b62020-08-06 08:29:18 +02001144 pname = argp[idx].data.str.area;
Willy Tarreau9e0bb102015-05-26 11:24:42 +02001145 px = proxy_be_by_name(pname);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001146 if (!px) {
1147 msg = "backend doesn't exist";
1148 goto error;
1149 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001150 }
1151 else {
Christopher Fauletfdea1b62020-08-06 08:29:18 +02001152 sname = argp[idx].data.str.area;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001153 px = p;
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001154 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001155 argp[idx].data.srv = findserver(px, sname);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001156 if (!argp[idx].data.srv) {
1157 msg = "server doesn't exist";
1158 goto error;
1159 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001160 argp[idx].type = ARGT_SRV;
1161 break;
1162
1163 case ARGT_IPV4:
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001164 if (argp[idx].type != ARGT_STR) {
1165 msg = "string expected";
1166 goto error;
1167 }
1168 if (inet_pton(AF_INET, argp[idx].data.str.area, &argp[idx].data.ipv4)) {
1169 msg = "invalid IPv4 address";
1170 goto error;
1171 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001172 argp[idx].type = ARGT_IPV4;
1173 break;
1174
1175 case ARGT_MSK4:
Christopher Faulete663a6e2020-08-07 09:11:22 +02001176 if (argp[idx].type == ARGT_SINT)
1177 len2mask4(argp[idx].data.sint, &argp[idx].data.ipv4);
1178 else if (argp[idx].type == ARGT_STR) {
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001179 if (!str2mask(argp[idx].data.str.area, &argp[idx].data.ipv4)) {
1180 msg = "invalid IPv4 mask";
1181 goto error;
1182 }
1183 }
1184 else {
1185 msg = "integer or string expected";
1186 goto error;
Christopher Faulete663a6e2020-08-07 09:11:22 +02001187 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001188 argp[idx].type = ARGT_MSK4;
1189 break;
1190
1191 case ARGT_IPV6:
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001192 if (argp[idx].type != ARGT_STR) {
1193 msg = "string expected";
1194 goto error;
1195 }
1196 if (inet_pton(AF_INET6, argp[idx].data.str.area, &argp[idx].data.ipv6)) {
1197 msg = "invalid IPv6 address";
1198 goto error;
1199 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001200 argp[idx].type = ARGT_IPV6;
1201 break;
1202
1203 case ARGT_MSK6:
Christopher Faulete663a6e2020-08-07 09:11:22 +02001204 if (argp[idx].type == ARGT_SINT)
1205 len2mask6(argp[idx].data.sint, &argp[idx].data.ipv6);
1206 else if (argp[idx].type == ARGT_STR) {
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001207 if (!str2mask6(argp[idx].data.str.area, &argp[idx].data.ipv6)) {
1208 msg = "invalid IPv6 mask";
1209 goto error;
1210 }
1211 }
1212 else {
1213 msg = "integer or string expected";
1214 goto error;
Christopher Faulete663a6e2020-08-07 09:11:22 +02001215 }
Tim Duesterhusb814da62018-01-25 16:24:50 +01001216 argp[idx].type = ARGT_MSK6;
1217 break;
1218
Christopher Fauletfd2e9062020-08-06 11:10:57 +02001219 case ARGT_REG:
1220 if (argp[idx].type != ARGT_STR) {
1221 msg = "string expected";
1222 goto error;
1223 }
1224 reg = regex_comp(argp[idx].data.str.area, !(argp[idx].type_flags & ARGF_REG_ICASE), 1, &err);
1225 if (!reg) {
1226 msg = lua_pushfstring(L, "error compiling regex '%s' : '%s'",
1227 argp[idx].data.str.area, err);
1228 free(err);
1229 goto error;
1230 }
1231 argp[idx].type = ARGT_REG;
1232 argp[idx].data.reg = reg;
1233 break;
1234
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001235 case ARGT_USR:
Christopher Fauletd25d9262020-08-06 11:04:46 +02001236 if (argp[idx].type != ARGT_STR) {
1237 msg = "string expected";
1238 goto error;
1239 }
1240 if (p->uri_auth && p->uri_auth->userlist &&
Tim Duesterhuse5ff1412021-01-02 22:31:53 +01001241 strcmp(p->uri_auth->userlist->name, argp[idx].data.str.area) == 0)
Christopher Fauletd25d9262020-08-06 11:04:46 +02001242 ul = p->uri_auth->userlist;
1243 else
1244 ul = auth_find_userlist(argp[idx].data.str.area);
1245
1246 if (!ul) {
1247 msg = lua_pushfstring(L, "unable to find userlist '%s'", argp[idx].data.str.area);
1248 goto error;
1249 }
1250 argp[idx].type = ARGT_USR;
1251 argp[idx].data.usr = ul;
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001252 break;
1253
1254 case ARGT_STR:
1255 if (!chunk_dup(&tmp, &argp[idx].data.str)) {
1256 msg = "unable to duplicate string arg";
1257 goto error;
1258 }
1259 argp[idx].data.str = tmp;
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001260 break;
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001261
Christopher Fauletd25d9262020-08-06 11:04:46 +02001262 case ARGT_MAP:
Christopher Fauletd25d9262020-08-06 11:04:46 +02001263 msg = "type not yet supported";
1264 goto error;
1265 break;
1266
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001267 }
1268
1269 /* Check for type of argument. */
1270 if ((mask & ARGT_MASK) != argp[idx].type) {
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001271 msg = lua_pushfstring(L, "'%s' expected, got '%s'",
1272 arg_type_names[(mask & ARGT_MASK)],
1273 arg_type_names[argp[idx].type & ARGT_MASK]);
1274 goto error;
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001275 }
1276
1277 /* Next argument. */
1278 mask >>= ARGT_BITS;
1279 idx++;
1280 }
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001281 return 0;
1282
1283 error:
Olivier Houchardca431612022-09-13 00:31:17 +02001284 argp[idx].type = ARGT_STOP;
Willy Tarreauee0d7272021-07-16 10:26:56 +02001285 free_args(argp);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001286 WILL_LJMP(luaL_argerror(L, first + idx, msg));
1287 return 0; /* Never reached */
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001288}
1289
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001290/*
Ilya Shipitsinc02a23f2020-05-06 00:53:22 +05001291 * The following functions are used to make correspondence between the the
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001292 * executed lua pointer and the "struct hlua *" that contain the context.
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001293 *
1294 * - hlua_gethlua : return the hlua context associated with an lua_State.
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001295 * - hlua_sethlua : create the association between hlua context and lua_state.
1296 */
Aurelien DARRAGON40cd44f2023-05-04 13:59:48 +02001297inline struct hlua *hlua_gethlua(lua_State *L)
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001298{
Thierry FOURNIER38c5fd62015-03-10 02:40:29 +01001299 struct hlua **hlua = lua_getextraspace(L);
1300 return *hlua;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001301}
1302static inline void hlua_sethlua(struct hlua *hlua)
1303{
Thierry FOURNIER38c5fd62015-03-10 02:40:29 +01001304 struct hlua **hlua_store = lua_getextraspace(hlua->T);
1305 *hlua_store = hlua;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001306}
1307
Willy Tarreau0b7b6392022-06-19 17:39:33 +02001308/* Will return a non-NULL string indicating the Lua call trace if the caller
1309 * currently is executing from within a Lua function. One line per entry will
1310 * be emitted, and each extra line will be prefixed with <pfx>. If a current
1311 * Lua function is not detected, NULL is returned.
1312 */
1313const char *hlua_show_current_location(const char *pfx)
1314{
1315 lua_State *L;
1316 lua_Debug ar;
1317
1318 /* global or per-thread stack initializing ? */
1319 if (hlua_state_id != -1 && (L = hlua_states[hlua_state_id]) && lua_getstack(L, 0, &ar))
1320 return hlua_traceback(L, pfx);
1321
1322 /* per-thread stack running ? */
1323 if (hlua_states[tid + 1] && (L = hlua_states[tid + 1]) && lua_getstack(L, 0, &ar))
1324 return hlua_traceback(L, pfx);
1325
1326 /* global stack running ? */
1327 if (hlua_states[0] && (L = hlua_states[0]) && lua_getstack(L, 0, &ar))
1328 return hlua_traceback(L, pfx);
1329
1330 return NULL;
1331}
1332
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01001333/* This function is used to send logs. It try to send on screen (stderr)
1334 * and on the default syslog server.
1335 */
1336static inline void hlua_sendlog(struct proxy *px, int level, const char *msg)
1337{
1338 struct tm tm;
1339 char *p;
1340
1341 /* Cleanup the log message. */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001342 p = trash.area;
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01001343 for (; *msg != '\0'; msg++, p++) {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001344 if (p >= trash.area + trash.size - 1) {
Thierry FOURNIERccf00632015-09-16 12:47:03 +02001345 /* Break the message if exceed the buffer size. */
1346 *(p-4) = ' ';
1347 *(p-3) = '.';
1348 *(p-2) = '.';
1349 *(p-1) = '.';
1350 break;
1351 }
Willy Tarreau90807112020-02-25 08:16:33 +01001352 if (isprint((unsigned char)*msg))
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01001353 *p = *msg;
1354 else
1355 *p = '.';
1356 }
1357 *p = '\0';
1358
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001359 send_log(px, level, "%s\n", trash.area);
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01001360 if (!(global.mode & MODE_QUIET) || (global.mode & (MODE_VERBOSE | MODE_STARTING))) {
Christopher Fauletf98d8212020-10-02 18:13:52 +02001361 if (level == LOG_DEBUG && !(global.mode & MODE_DEBUG))
1362 return;
1363
Willy Tarreaua678b432015-08-28 10:14:59 +02001364 get_localtime(date.tv_sec, &tm);
1365 fprintf(stderr, "[%s] %03d/%02d%02d%02d (%d) : %s\n",
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01001366 log_levels[level], tm.tm_yday, tm.tm_hour, tm.tm_min, tm.tm_sec,
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001367 (int)getpid(), trash.area);
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01001368 fflush(stderr);
1369 }
1370}
1371
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001372/* This function just ensure that the yield will be always
1373 * returned with a timeout and permit to set some flags
Aurelien DARRAGON2a9764b2023-04-04 18:41:04 +02001374 * <timeout> is a tick value
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001375 */
1376__LJMP void hlua_yieldk(lua_State *L, int nresults, int ctx,
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001377 lua_KFunction k, int timeout, unsigned int flags)
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001378{
Thierry Fournier4234dbd2020-11-28 13:18:23 +01001379 struct hlua *hlua;
1380
1381 /* Get hlua struct, or NULL if we execute from main lua state */
1382 hlua = hlua_gethlua(L);
1383 if (!hlua) {
1384 return;
1385 }
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001386
1387 /* Set the wake timeout. If timeout is required, we set
1388 * the expiration time.
1389 */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001390 hlua->wake_time = timeout;
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001391
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01001392 hlua->flags |= flags;
1393
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001394 /* Process the yield. */
Willy Tarreau9635e032018-10-16 17:52:55 +02001395 MAY_LJMP(lua_yieldk(L, nresults, ctx, k));
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001396}
1397
Willy Tarreau87b09662015-04-03 00:22:06 +02001398/* This function initialises the Lua environment stored in the stream.
1399 * It must be called at the start of the stream. This function creates
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001400 * an LUA coroutine. It can not be use to crete the main LUA context.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02001401 *
1402 * This function is particular. it initialises a new Lua thread. If the
1403 * initialisation fails (example: out of memory error), the lua function
1404 * throws an error (longjmp).
1405 *
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001406 * This function manipulates two Lua stacks: the main and the thread. Only
Thierry FOURNIERbabae282015-09-17 11:36:37 +02001407 * the main stack can fail. The thread is not manipulated. This function
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001408 * MUST NOT manipulate the created thread stack state, because it is not
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001409 * protected against errors thrown by the thread stack.
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001410 */
Aurelien DARRAGON6b0b9bd2023-03-21 14:02:16 +01001411int hlua_ctx_init(struct hlua *lua, int state_id, struct task *task)
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001412{
1413 lua->Mref = LUA_REFNIL;
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001414 lua->flags = 0;
Willy Tarreauf31af932020-01-14 09:59:38 +01001415 lua->gc_count = 0;
Christopher Fauletbc275a92020-02-26 14:55:16 +01001416 lua->wake_time = TICK_ETERNITY;
Thierry Fournier021d9862020-11-28 23:42:03 +01001417 lua->state_id = state_id;
Aurelien DARRAGONda9503c2022-11-25 09:10:07 +01001418 hlua_timer_init(&lua->timer, 0); /* default value, no timeout */
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01001419 LIST_INIT(&lua->com);
Aurelien DARRAGON3ffbf382023-02-09 17:02:57 +01001420 MT_LIST_INIT(&lua->hc_list);
Aurelien DARRAGON6b0b9bd2023-03-21 14:02:16 +01001421 if (!SET_SAFE_LJMP_PARENT(lua)) {
1422 lua->Tref = LUA_REFNIL;
1423 return 0;
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001424 }
Thierry Fournier021d9862020-11-28 23:42:03 +01001425 lua->T = lua_newthread(hlua_states[state_id]);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001426 if (!lua->T) {
1427 lua->Tref = LUA_REFNIL;
Aurelien DARRAGON6b0b9bd2023-03-21 14:02:16 +01001428 RESET_SAFE_LJMP_PARENT(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001429 return 0;
1430 }
1431 hlua_sethlua(lua);
Thierry Fournier021d9862020-11-28 23:42:03 +01001432 lua->Tref = luaL_ref(hlua_states[state_id], LUA_REGISTRYINDEX);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001433 lua->task = task;
Aurelien DARRAGON6b0b9bd2023-03-21 14:02:16 +01001434 RESET_SAFE_LJMP_PARENT(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001435 return 1;
1436}
1437
Aurelien DARRAGON3ffbf382023-02-09 17:02:57 +01001438/* kill all associated httpclient to this hlua task
1439 * We must take extra precautions as we're manipulating lua-exposed
1440 * objects without the main lua lock.
1441 */
William Lallemandbb581422022-10-20 10:57:28 +02001442static void hlua_httpclient_destroy_all(struct hlua *hlua)
1443{
Aurelien DARRAGON3ffbf382023-02-09 17:02:57 +01001444 struct hlua_httpclient *hlua_hc;
William Lallemandbb581422022-10-20 10:57:28 +02001445
Aurelien DARRAGON3ffbf382023-02-09 17:02:57 +01001446 /* use thread-safe accessors for hc_list since GC cycle initiated by
1447 * another thread sharing the same main lua stack (lua coroutine)
1448 * could execute hlua_httpclient_gc() on the hlua->hc_list items
1449 * in parallel: Lua GC applies on the main stack, it is not limited to
1450 * a single coroutine stack, see Github issue #2037 for reference.
1451 * Remember, coroutines created using lua_newthread() are not meant to
1452 * be thread safe in Lua. (From lua co-author:
1453 * http://lua-users.org/lists/lua-l/2011-07/msg00072.html)
1454 *
1455 * This security measure is superfluous when 'lua-load-per-thread' is used
1456 * since in this case coroutines exclusively run on the same thread
1457 * (main stack is not shared between OS threads).
1458 */
1459 while ((hlua_hc = MT_LIST_POP(&hlua->hc_list, typeof(hlua_hc), by_hlua))) {
1460 httpclient_stop_and_destroy(hlua_hc->hc);
William Lallemandbb581422022-10-20 10:57:28 +02001461 hlua_hc->hc = NULL;
William Lallemandbb581422022-10-20 10:57:28 +02001462 }
1463}
1464
1465
Willy Tarreau87b09662015-04-03 00:22:06 +02001466/* Used to destroy the Lua coroutine when the attached stream or task
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001467 * is destroyed. The destroy also the memory context. The struct "lua"
Aurelien DARRAGON60ab0f72023-03-01 16:45:50 +01001468 * will be freed.
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001469 */
1470void hlua_ctx_destroy(struct hlua *lua)
1471{
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01001472 if (!lua)
Thierry FOURNIERa718b292015-03-04 16:48:34 +01001473 return;
1474
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01001475 if (!lua->T)
1476 goto end;
1477
William Lallemandbb581422022-10-20 10:57:28 +02001478 /* clean all running httpclient */
1479 hlua_httpclient_destroy_all(lua);
1480
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01001481 /* Purge all the pending signals. */
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001482 notification_purge(&lua->com);
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01001483
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001484 if (!SET_SAFE_LJMP(lua))
Thierry FOURNIER75d02082017-07-12 13:41:33 +02001485 return;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001486 luaL_unref(lua->T, LUA_REGISTRYINDEX, lua->Mref);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001487 RESET_SAFE_LJMP(lua);
Thierry FOURNIER5a50a852015-09-23 16:59:28 +02001488
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001489 if (!SET_SAFE_LJMP_PARENT(lua))
Thierry FOURNIER75d02082017-07-12 13:41:33 +02001490 return;
Thierry Fournier021d9862020-11-28 23:42:03 +01001491 luaL_unref(hlua_states[lua->state_id], LUA_REGISTRYINDEX, lua->Tref);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001492 RESET_SAFE_LJMP_PARENT(lua);
Thierry FOURNIER5a50a852015-09-23 16:59:28 +02001493 /* Forces a garbage collecting process. If the Lua program is finished
1494 * without error, we run the GC on the thread pointer. Its freed all
1495 * the unused memory.
1496 * If the thread is finnish with an error or is currently yielded,
1497 * it seems that the GC applied on the thread doesn't clean anything,
1498 * so e run the GC on the main thread.
1499 * NOTE: maybe this action locks all the Lua threads untiml the en of
1500 * the garbage collection.
1501 */
Willy Tarreauf31af932020-01-14 09:59:38 +01001502 if (lua->gc_count) {
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001503 if (!SET_SAFE_LJMP_PARENT(lua))
Thierry FOURNIER75d02082017-07-12 13:41:33 +02001504 return;
Thierry Fournier021d9862020-11-28 23:42:03 +01001505 lua_gc(hlua_states[lua->state_id], LUA_GCCOLLECT, 0);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001506 RESET_SAFE_LJMP_PARENT(lua);
Thierry FOURNIER7c39ab42015-09-27 22:53:33 +02001507 }
Thierry FOURNIER5a50a852015-09-23 16:59:28 +02001508
Thierry FOURNIERa7b536b2015-09-21 22:50:24 +02001509 lua->T = NULL;
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01001510
1511end:
Willy Tarreaubafbe012017-11-24 17:34:44 +01001512 pool_free(pool_head_hlua, lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001513}
1514
1515/* This function is used to restore the Lua context when a coroutine
1516 * fails. This function copy the common memory between old coroutine
1517 * and the new coroutine. The old coroutine is destroyed, and its
1518 * replaced by the new coroutine.
1519 * If the flag "keep_msg" is set, the last entry of the old is assumed
1520 * as string error message and it is copied in the new stack.
1521 */
1522static int hlua_ctx_renew(struct hlua *lua, int keep_msg)
1523{
1524 lua_State *T;
1525 int new_ref;
1526
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001527 /* New Lua coroutine. */
Thierry Fournier021d9862020-11-28 23:42:03 +01001528 T = lua_newthread(hlua_states[lua->state_id]);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001529 if (!T)
1530 return 0;
1531
1532 /* Copy last error message. */
1533 if (keep_msg)
1534 lua_xmove(lua->T, T, 1);
1535
1536 /* Copy data between the coroutines. */
1537 lua_rawgeti(lua->T, LUA_REGISTRYINDEX, lua->Mref);
1538 lua_xmove(lua->T, T, 1);
Ilya Shipitsin46a030c2020-07-05 16:36:08 +05001539 new_ref = luaL_ref(T, LUA_REGISTRYINDEX); /* Value popped. */
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001540
1541 /* Destroy old data. */
1542 luaL_unref(lua->T, LUA_REGISTRYINDEX, lua->Mref);
1543
1544 /* The thread is garbage collected by Lua. */
Thierry Fournier021d9862020-11-28 23:42:03 +01001545 luaL_unref(hlua_states[lua->state_id], LUA_REGISTRYINDEX, lua->Tref);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001546
1547 /* Fill the struct with the new coroutine values. */
1548 lua->Mref = new_ref;
1549 lua->T = T;
Thierry Fournier021d9862020-11-28 23:42:03 +01001550 lua->Tref = luaL_ref(hlua_states[lua->state_id], LUA_REGISTRYINDEX);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001551
1552 /* Set context. */
1553 hlua_sethlua(lua);
1554
1555 return 1;
1556}
1557
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001558void hlua_hook(lua_State *L, lua_Debug *ar)
1559{
Thierry Fournier4234dbd2020-11-28 13:18:23 +01001560 struct hlua *hlua;
1561
1562 /* Get hlua struct, or NULL if we execute from main lua state */
1563 hlua = hlua_gethlua(L);
1564 if (!hlua)
1565 return;
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001566
Aurelien DARRAGONcf0f7922023-04-07 16:34:20 +02001567 if (hlua->T != L) {
1568 /* We don't want to enforce a yield on a sub coroutine, since
1569 * we have no guarantees that the yield will be handled properly.
1570 * Indeed, only the hlua->T coroutine is being handled through
1571 * hlua_ctx_resume() function.
1572 *
1573 * Instead, we simply check for timeouts and wait for the sub
1574 * coroutine to finish..
1575 */
1576 goto check_timeout;
1577 }
1578
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001579 /* Lua cannot yield when its returning from a function,
1580 * so, we can fix the interrupt hook to 1 instruction,
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001581 * expecting that the function is finished.
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001582 */
1583 if (lua_gethookmask(L) & LUA_MASKRET) {
1584 lua_sethook(hlua->T, hlua_hook, LUA_MASKCOUNT, 1);
1585 return;
1586 }
1587
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001588 /* If we interrupt the Lua processing in yieldable state, we yield.
1589 * If the state is not yieldable, trying yield causes an error.
1590 */
Aurelien DARRAGON0ebd41f2022-11-24 09:51:40 +01001591 if (lua_isyieldable(L)) {
1592 /* note: for converters/fetches.. where yielding is not allowed
1593 * hlua_ctx_resume() will simply perform a goto resume_execution
1594 * instead of rescheduling hlua->task.
1595 * also: hlua_ctx_resume() will take care of checking execution
1596 * timeout and re-applying the hook as needed.
1597 */
Willy Tarreau9635e032018-10-16 17:52:55 +02001598 MAY_LJMP(hlua_yieldk(L, 0, 0, NULL, TICK_ETERNITY, HLUA_CTRLYIELD));
Aurelien DARRAGON0ebd41f2022-11-24 09:51:40 +01001599 /* lua docs says that the hook should return immediately after lua_yieldk
1600 *
1601 * From: https://www.lua.org/manual/5.3/manual.html#lua_yieldk
1602 *
1603 * Moreover, it seems that we don't want to continue after the yield
1604 * because the end of the function is about handling unyieldable function,
1605 * which is not the case here.
1606 *
1607 * ->if we don't return lua_sethook gets incorrectly set with MASKRET later
1608 * in the function.
1609 */
1610 return;
1611 }
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001612
Aurelien DARRAGONcf0f7922023-04-07 16:34:20 +02001613 check_timeout:
Aurelien DARRAGONda9503c2022-11-25 09:10:07 +01001614 /* If we cannot yield, check the timeout. */
1615 if (!hlua_timer_check(&hlua->timer)) {
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001616 lua_pushfstring(L, "execution timeout");
1617 WILL_LJMP(lua_error(L));
1618 }
1619
1620 /* Try to interrupt the process at the end of the current
1621 * unyieldable function.
1622 */
1623 lua_sethook(hlua->T, hlua_hook, LUA_MASKRET|LUA_MASKCOUNT, hlua_nb_instruction);
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001624}
1625
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001626/* This function start or resumes the Lua stack execution. If the flag
1627 * "yield_allowed" if no set and the LUA stack execution returns a yield
1628 * The function return an error.
1629 *
1630 * The function can returns 4 values:
1631 * - HLUA_E_OK : The execution is terminated without any errors.
1632 * - HLUA_E_AGAIN : The execution must continue at the next associated
1633 * task wakeup.
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001634 * - HLUA_E_ERRMSG : An error has occurred, an error message is set in
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001635 * the top of the stack.
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001636 * - HLUA_E_ERR : An error has occurred without error message.
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001637 *
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001638 * If an error occurred, the stack is renewed and it is ready to run new
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001639 * LUA code.
1640 */
1641static enum hlua_exec hlua_ctx_resume(struct hlua *lua, int yield_allowed)
1642{
Christopher Faulet08ed98f2020-07-28 10:33:25 +02001643#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM >= 504
1644 int nres;
1645#endif
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001646 int ret;
1647 const char *msg;
Thierry FOURNIERfc044c92018-06-07 14:40:48 +02001648 const char *trace;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001649
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +02001650 /* Lock the whole Lua execution. This lock must be before the
1651 * label "resume_execution".
1652 */
Aurelien DARRAGONe36f8032023-03-21 13:22:33 +01001653 hlua_lock(lua);
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +02001654
Aurelien DARRAGONda9503c2022-11-25 09:10:07 +01001655 /* reset the timer as we might be re-entering the function to
1656 * resume the coroutine after a successful yield
1657 * (cumulative time will be updated)
1658 */
1659 hlua_timer_reset(&lua->timer);
1660
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001661resume_execution:
1662
1663 /* This hook interrupts the Lua processing each 'hlua_nb_instruction'
1664 * instructions. it is used for preventing infinite loops.
1665 */
1666 lua_sethook(lua->T, hlua_hook, LUA_MASKCOUNT, hlua_nb_instruction);
1667
Thierry FOURNIER1bfc09b2015-03-05 17:10:14 +01001668 /* Remove all flags except the running flags. */
Thierry FOURNIER2f3867f2015-09-28 01:02:01 +02001669 HLUA_SET_RUN(lua);
1670 HLUA_CLR_CTRLYIELD(lua);
1671 HLUA_CLR_WAKERESWR(lua);
1672 HLUA_CLR_WAKEREQWR(lua);
Christopher Faulet1f43a342021-08-04 17:58:21 +02001673 HLUA_CLR_NOYIELD(lua);
1674 if (!yield_allowed)
1675 HLUA_SET_NOYIELD(lua);
Thierry FOURNIER1bfc09b2015-03-05 17:10:14 +01001676
Aurelien DARRAGONda9503c2022-11-25 09:10:07 +01001677 /* reset wake_time. */
Christopher Fauletbc275a92020-02-26 14:55:16 +01001678 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001679
Aurelien DARRAGONda9503c2022-11-25 09:10:07 +01001680 /* start the timer as we're about to start lua processing */
1681 hlua_timer_start(&lua->timer);
1682
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001683 /* Call the function. */
Christopher Faulet08ed98f2020-07-28 10:33:25 +02001684#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM >= 504
Thierry Fournier021d9862020-11-28 23:42:03 +01001685 ret = lua_resume(lua->T, hlua_states[lua->state_id], lua->nargs, &nres);
Christopher Faulet08ed98f2020-07-28 10:33:25 +02001686#else
Thierry Fournier021d9862020-11-28 23:42:03 +01001687 ret = lua_resume(lua->T, hlua_states[lua->state_id], lua->nargs);
Christopher Faulet08ed98f2020-07-28 10:33:25 +02001688#endif
Aurelien DARRAGONda9503c2022-11-25 09:10:07 +01001689
1690 /* out of lua processing, stop the timer */
1691 hlua_timer_stop(&lua->timer);
1692
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001693 switch (ret) {
1694
1695 case LUA_OK:
1696 ret = HLUA_E_OK;
1697 break;
1698
1699 case LUA_YIELD:
Aurelien DARRAGONda9503c2022-11-25 09:10:07 +01001700 /* Check if the execution timeout is expired. If it is the case, we
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001701 * break the Lua execution.
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001702 */
Aurelien DARRAGONda9503c2022-11-25 09:10:07 +01001703 if (!hlua_timer_check(&lua->timer)) {
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001704 lua_settop(lua->T, 0); /* Empty the stack. */
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001705 ret = HLUA_E_ETMOUT;
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001706 break;
1707 }
1708 /* Process the forced yield. if the general yield is not allowed or
1709 * if no task were associated this the current Lua execution
1710 * coroutine, we resume the execution. Else we want to return in the
1711 * scheduler and we want to be waked up again, to continue the
1712 * current Lua execution. So we schedule our own task.
1713 */
1714 if (HLUA_IS_CTRLYIELDING(lua)) {
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001715 if (!yield_allowed || !lua->task)
1716 goto resume_execution;
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001717 task_wakeup(lua->task, TASK_WOKEN_MSG);
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001718 }
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001719 if (!yield_allowed) {
1720 lua_settop(lua->T, 0); /* Empty the stack. */
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001721 ret = HLUA_E_YIELD;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001722 break;
1723 }
1724 ret = HLUA_E_AGAIN;
1725 break;
1726
1727 case LUA_ERRRUN:
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001728
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001729 /* Special exit case. The traditional exit is returned as an error
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001730 * because the errors ares the only one mean to return immediately
1731 * from and lua execution.
1732 */
1733 if (lua->flags & HLUA_EXIT) {
1734 ret = HLUA_E_OK;
Christopher Faulet7716cdf2020-01-29 11:53:30 +01001735 hlua_ctx_renew(lua, 1);
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001736 break;
1737 }
1738
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);
Christopher Fauletd09cc512021-03-24 14:48:45 +01001747 trace = hlua_traceback(lua->T, ", ");
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001748 if (msg)
Thierry Fournier46278ff2020-11-29 11:48:12 +01001749 lua_pushfstring(lua->T, "[state-id %d] runtime error: %s from %s", lua->state_id, msg, trace);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001750 else
Thierry Fournier46278ff2020-11-29 11:48:12 +01001751 lua_pushfstring(lua->T, "[state-id %d] unknown runtime error from %s", lua->state_id, trace);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001752 ret = HLUA_E_ERRMSG;
1753 break;
1754
1755 case LUA_ERRMEM:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001756 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001757 lua_settop(lua->T, 0); /* Empty the stack. */
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001758 ret = HLUA_E_NOMEM;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001759 break;
1760
1761 case LUA_ERRERR:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001762 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001763 if (!lua_checkstack(lua->T, 1)) {
1764 ret = HLUA_E_ERR;
1765 break;
1766 }
1767 msg = lua_tostring(lua->T, -1);
1768 lua_settop(lua->T, 0); /* Empty the stack. */
1769 lua_pop(lua->T, 1);
1770 if (msg)
Thierry Fournier46278ff2020-11-29 11:48:12 +01001771 lua_pushfstring(lua->T, "[state-id %d] message handler error: %s", lua->state_id, msg);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001772 else
Thierry Fournier46278ff2020-11-29 11:48:12 +01001773 lua_pushfstring(lua->T, "[state-id %d] message handler error", lua->state_id);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001774 ret = HLUA_E_ERRMSG;
1775 break;
1776
1777 default:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001778 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001779 lua_settop(lua->T, 0); /* Empty the stack. */
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001780 ret = HLUA_E_ERR;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001781 break;
1782 }
1783
1784 switch (ret) {
1785 case HLUA_E_AGAIN:
1786 break;
1787
1788 case HLUA_E_ERRMSG:
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001789 notification_purge(&lua->com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001790 hlua_ctx_renew(lua, 1);
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001791 HLUA_CLR_RUN(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001792 break;
1793
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001794 case HLUA_E_ETMOUT:
1795 case HLUA_E_NOMEM:
1796 case HLUA_E_YIELD:
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001797 case HLUA_E_ERR:
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001798 HLUA_CLR_RUN(lua);
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001799 notification_purge(&lua->com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001800 hlua_ctx_renew(lua, 0);
1801 break;
1802
1803 case HLUA_E_OK:
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001804 HLUA_CLR_RUN(lua);
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001805 notification_purge(&lua->com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001806 break;
1807 }
1808
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +02001809 /* This is the main exit point, remove the Lua lock. */
Aurelien DARRAGONe36f8032023-03-21 13:22:33 +01001810 hlua_unlock(lua);
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +02001811
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001812 return ret;
1813}
1814
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001815/* This function exit the current code. */
1816__LJMP static int hlua_done(lua_State *L)
1817{
Thierry Fournier4234dbd2020-11-28 13:18:23 +01001818 struct hlua *hlua;
1819
1820 /* Get hlua struct, or NULL if we execute from main lua state */
1821 hlua = hlua_gethlua(L);
1822 if (!hlua)
1823 return 0;
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001824
1825 hlua->flags |= HLUA_EXIT;
1826 WILL_LJMP(lua_error(L));
1827
1828 return 0;
1829}
1830
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001831/* This function is an LUA binding. It provides a function
1832 * for deleting ACL from a referenced ACL file.
1833 */
1834__LJMP static int hlua_del_acl(lua_State *L)
1835{
1836 const char *name;
1837 const char *key;
1838 struct pat_ref *ref;
1839
1840 MAY_LJMP(check_args(L, 2, "del_acl"));
1841
1842 name = MAY_LJMP(luaL_checkstring(L, 1));
1843 key = MAY_LJMP(luaL_checkstring(L, 2));
1844
1845 ref = pat_ref_lookup(name);
1846 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001847 WILL_LJMP(luaL_error(L, "'del_acl': unknown acl file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001848
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001849 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001850 pat_ref_delete(ref, key);
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001851 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001852 return 0;
1853}
1854
1855/* This function is an LUA binding. It provides a function
1856 * for deleting map entry from a referenced map file.
1857 */
1858static int hlua_del_map(lua_State *L)
1859{
1860 const char *name;
1861 const char *key;
1862 struct pat_ref *ref;
1863
1864 MAY_LJMP(check_args(L, 2, "del_map"));
1865
1866 name = MAY_LJMP(luaL_checkstring(L, 1));
1867 key = MAY_LJMP(luaL_checkstring(L, 2));
1868
1869 ref = pat_ref_lookup(name);
1870 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001871 WILL_LJMP(luaL_error(L, "'del_map': unknown acl file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001872
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001873 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001874 pat_ref_delete(ref, key);
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001875 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001876 return 0;
1877}
1878
1879/* This function is an LUA binding. It provides a function
1880 * for adding ACL pattern from a referenced ACL file.
1881 */
1882static int hlua_add_acl(lua_State *L)
1883{
1884 const char *name;
1885 const char *key;
1886 struct pat_ref *ref;
1887
1888 MAY_LJMP(check_args(L, 2, "add_acl"));
1889
1890 name = MAY_LJMP(luaL_checkstring(L, 1));
1891 key = MAY_LJMP(luaL_checkstring(L, 2));
1892
1893 ref = pat_ref_lookup(name);
1894 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001895 WILL_LJMP(luaL_error(L, "'add_acl': unknown acl file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001896
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001897 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001898 if (pat_ref_find_elt(ref, key) == NULL)
1899 pat_ref_add(ref, key, NULL, NULL);
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001900 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001901 return 0;
1902}
1903
1904/* This function is an LUA binding. It provides a function
1905 * for setting map pattern and sample from a referenced map
1906 * file.
1907 */
1908static int hlua_set_map(lua_State *L)
1909{
1910 const char *name;
1911 const char *key;
1912 const char *value;
1913 struct pat_ref *ref;
1914
1915 MAY_LJMP(check_args(L, 3, "set_map"));
1916
1917 name = MAY_LJMP(luaL_checkstring(L, 1));
1918 key = MAY_LJMP(luaL_checkstring(L, 2));
1919 value = MAY_LJMP(luaL_checkstring(L, 3));
1920
1921 ref = pat_ref_lookup(name);
1922 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001923 WILL_LJMP(luaL_error(L, "'set_map': unknown map file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001924
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001925 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001926 if (pat_ref_find_elt(ref, key) != NULL)
1927 pat_ref_set(ref, key, value, NULL);
1928 else
1929 pat_ref_add(ref, key, value, NULL);
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001930 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001931 return 0;
1932}
1933
Aurelien DARRAGON5bed48f2023-04-21 17:32:46 +02001934/* This function disables the sending of email through the
1935 * legacy email sending function which is implemented using
1936 * checks.
1937 *
1938 * It may not be used during runtime.
1939 */
1940__LJMP static int hlua_disable_legacy_mailers(lua_State *L)
1941{
1942 if (hlua_gethlua(L))
1943 WILL_LJMP(luaL_error(L, "disable_legacy_mailers: "
1944 "not available outside of init or body context"));
1945 send_email_disabled = 1;
1946 return 0;
1947}
1948
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01001949/* A class is a lot of memory that contain data. This data can be a table,
1950 * an integer or user data. This data is associated with a metatable. This
Ilya Shipitsinc02a23f2020-05-06 00:53:22 +05001951 * metatable have an original version registered in the global context with
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01001952 * the name of the object (_G[<name>] = <metable> ).
1953 *
1954 * A metable is a table that modify the standard behavior of a standard
1955 * access to the associated data. The entries of this new metatable are
1956 * defined as is:
1957 *
1958 * http://lua-users.org/wiki/MetatableEvents
1959 *
1960 * __index
1961 *
1962 * we access an absent field in a table, the result is nil. This is
1963 * true, but it is not the whole truth. Actually, such access triggers
1964 * the interpreter to look for an __index metamethod: If there is no
1965 * such method, as usually happens, then the access results in nil;
1966 * otherwise, the metamethod will provide the result.
1967 *
1968 * Control 'prototype' inheritance. When accessing "myTable[key]" and
1969 * the key does not appear in the table, but the metatable has an __index
1970 * property:
1971 *
1972 * - if the value is a function, the function is called, passing in the
1973 * table and the key; the return value of that function is returned as
1974 * the result.
1975 *
1976 * - if the value is another table, the value of the key in that table is
1977 * asked for and returned (and if it doesn't exist in that table, but that
1978 * table's metatable has an __index property, then it continues on up)
1979 *
1980 * - Use "rawget(myTable,key)" to skip this metamethod.
1981 *
1982 * http://www.lua.org/pil/13.4.1.html
1983 *
1984 * __newindex
1985 *
1986 * Like __index, but control property assignment.
1987 *
1988 * __mode - Control weak references. A string value with one or both
1989 * of the characters 'k' and 'v' which specifies that the the
1990 * keys and/or values in the table are weak references.
1991 *
1992 * __call - Treat a table like a function. When a table is followed by
1993 * parenthesis such as "myTable( 'foo' )" and the metatable has
1994 * a __call key pointing to a function, that function is invoked
1995 * (passing any specified arguments) and the return value is
1996 * returned.
1997 *
1998 * __metatable - Hide the metatable. When "getmetatable( myTable )" is
1999 * called, if the metatable for myTable has a __metatable
2000 * key, the value of that key is returned instead of the
2001 * actual metatable.
2002 *
2003 * __tostring - Control string representation. When the builtin
2004 * "tostring( myTable )" function is called, if the metatable
2005 * for myTable has a __tostring property set to a function,
2006 * that function is invoked (passing myTable to it) and the
2007 * return value is used as the string representation.
2008 *
2009 * __len - Control table length. When the table length is requested using
2010 * the length operator ( '#' ), if the metatable for myTable has
2011 * a __len key pointing to a function, that function is invoked
2012 * (passing myTable to it) and the return value used as the value
2013 * of "#myTable".
2014 *
2015 * __gc - Userdata finalizer code. When userdata is set to be garbage
2016 * collected, if the metatable has a __gc field pointing to a
2017 * function, that function is first invoked, passing the userdata
2018 * to it. The __gc metamethod is not called for tables.
2019 * (See http://lua-users.org/lists/lua-l/2006-11/msg00508.html)
2020 *
2021 * Special metamethods for redefining standard operators:
2022 * http://www.lua.org/pil/13.1.html
2023 *
2024 * __add "+"
2025 * __sub "-"
2026 * __mul "*"
2027 * __div "/"
2028 * __unm "!"
2029 * __pow "^"
2030 * __concat ".."
2031 *
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05002032 * Special methods for redefining standard relations
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01002033 * http://www.lua.org/pil/13.2.html
2034 *
2035 * __eq "=="
2036 * __lt "<"
2037 * __le "<="
2038 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002039
2040/*
2041 *
2042 *
Thierry FOURNIER3def3932015-04-07 11:27:54 +02002043 * Class Map
2044 *
2045 *
2046 */
2047
2048/* Returns a struct hlua_map if the stack entry "ud" is
2049 * a class session, otherwise it throws an error.
2050 */
2051__LJMP static struct map_descriptor *hlua_checkmap(lua_State *L, int ud)
2052{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02002053 return MAY_LJMP(hlua_checkudata(L, ud, class_map_ref));
Thierry FOURNIER3def3932015-04-07 11:27:54 +02002054}
2055
2056/* This function is the map constructor. It don't need
2057 * the class Map object. It creates and return a new Map
2058 * object. It must be called only during "body" or "init"
2059 * context because it process some filesystem accesses.
2060 */
2061__LJMP static int hlua_map_new(struct lua_State *L)
2062{
2063 const char *fn;
2064 int match = PAT_MATCH_STR;
2065 struct sample_conv conv;
2066 const char *file = "";
2067 int line = 0;
2068 lua_Debug ar;
2069 char *err = NULL;
2070 struct arg args[2];
2071
2072 if (lua_gettop(L) < 1 || lua_gettop(L) > 2)
2073 WILL_LJMP(luaL_error(L, "'new' needs at least 1 argument."));
2074
2075 fn = MAY_LJMP(luaL_checkstring(L, 1));
2076
2077 if (lua_gettop(L) >= 2) {
2078 match = MAY_LJMP(luaL_checkinteger(L, 2));
2079 if (match < 0 || match >= PAT_MATCH_NUM)
2080 WILL_LJMP(luaL_error(L, "'new' needs a valid match method."));
2081 }
2082
2083 /* Get Lua filename and line number. */
2084 if (lua_getstack(L, 1, &ar)) { /* check function at level */
2085 lua_getinfo(L, "Sl", &ar); /* get info about it */
2086 if (ar.currentline > 0) { /* is there info? */
2087 file = ar.short_src;
2088 line = ar.currentline;
2089 }
2090 }
2091
2092 /* fill fake sample_conv struct. */
2093 conv.kw = ""; /* unused. */
2094 conv.process = NULL; /* unused. */
2095 conv.arg_mask = 0; /* unused. */
2096 conv.val_args = NULL; /* unused. */
2097 conv.out_type = SMP_T_STR;
2098 conv.private = (void *)(long)match;
2099 switch (match) {
2100 case PAT_MATCH_STR: conv.in_type = SMP_T_STR; break;
2101 case PAT_MATCH_BEG: conv.in_type = SMP_T_STR; break;
2102 case PAT_MATCH_SUB: conv.in_type = SMP_T_STR; break;
2103 case PAT_MATCH_DIR: conv.in_type = SMP_T_STR; break;
2104 case PAT_MATCH_DOM: conv.in_type = SMP_T_STR; break;
2105 case PAT_MATCH_END: conv.in_type = SMP_T_STR; break;
2106 case PAT_MATCH_REG: conv.in_type = SMP_T_STR; break;
Thierry FOURNIER07ee64e2015-07-06 23:43:03 +02002107 case PAT_MATCH_INT: conv.in_type = SMP_T_SINT; break;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02002108 case PAT_MATCH_IP: conv.in_type = SMP_T_ADDR; break;
2109 default:
2110 WILL_LJMP(luaL_error(L, "'new' doesn't support this match mode."));
2111 }
2112
2113 /* fill fake args. */
2114 args[0].type = ARGT_STR;
Christopher Faulet73292e92020-08-06 08:40:09 +02002115 args[0].data.str.area = strdup(fn);
2116 args[0].data.str.data = strlen(fn);
2117 args[0].data.str.size = args[0].data.str.data+1;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02002118 args[1].type = ARGT_STOP;
2119
2120 /* load the map. */
2121 if (!sample_load_map(args, &conv, file, line, &err)) {
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +05002122 /* error case: we can't use luaL_error because we must
Thierry FOURNIER3def3932015-04-07 11:27:54 +02002123 * free the err variable.
2124 */
2125 luaL_where(L, 1);
2126 lua_pushfstring(L, "'new': %s.", err);
2127 lua_concat(L, 2);
2128 free(err);
Christopher Faulet6ad7df42020-08-07 11:45:18 +02002129 chunk_destroy(&args[0].data.str);
Thierry FOURNIER3def3932015-04-07 11:27:54 +02002130 WILL_LJMP(lua_error(L));
2131 }
2132
2133 /* create the lua object. */
2134 lua_newtable(L);
2135 lua_pushlightuserdata(L, args[0].data.map);
2136 lua_rawseti(L, -2, 0);
2137
2138 /* Pop a class Map metatable and affect it to the userdata. */
2139 lua_rawgeti(L, LUA_REGISTRYINDEX, class_map_ref);
2140 lua_setmetatable(L, -2);
2141
2142
2143 return 1;
2144}
2145
2146__LJMP static inline int _hlua_map_lookup(struct lua_State *L, int str)
2147{
2148 struct map_descriptor *desc;
2149 struct pattern *pat;
2150 struct sample smp;
2151
2152 MAY_LJMP(check_args(L, 2, "lookup"));
2153 desc = MAY_LJMP(hlua_checkmap(L, 1));
Thierry FOURNIER07ee64e2015-07-06 23:43:03 +02002154 if (desc->pat.expect_type == SMP_T_SINT) {
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02002155 smp.data.type = SMP_T_SINT;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +02002156 smp.data.u.sint = MAY_LJMP(luaL_checkinteger(L, 2));
Thierry FOURNIER3def3932015-04-07 11:27:54 +02002157 }
2158 else {
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02002159 smp.data.type = SMP_T_STR;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02002160 smp.flags = SMP_F_CONST;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02002161 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 +01002162 smp.data.u.str.size = smp.data.u.str.data + 1;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02002163 }
2164
2165 pat = pattern_exec_match(&desc->pat, &smp, 1);
Thierry FOURNIER503bb092015-08-19 08:35:43 +02002166 if (!pat || !pat->data) {
Thierry FOURNIER3def3932015-04-07 11:27:54 +02002167 if (str)
2168 lua_pushstring(L, "");
2169 else
2170 lua_pushnil(L);
2171 return 1;
2172 }
2173
2174 /* The Lua pattern must return a string, so we can't check the returned type */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02002175 lua_pushlstring(L, pat->data->u.str.area, pat->data->u.str.data);
Thierry FOURNIER3def3932015-04-07 11:27:54 +02002176 return 1;
2177}
2178
2179__LJMP static int hlua_map_lookup(struct lua_State *L)
2180{
2181 return _hlua_map_lookup(L, 0);
2182}
2183
2184__LJMP static int hlua_map_slookup(struct lua_State *L)
2185{
2186 return _hlua_map_lookup(L, 1);
2187}
2188
2189/*
2190 *
2191 *
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002192 * Class Socket
2193 *
2194 *
2195 */
2196
2197__LJMP static struct hlua_socket *hlua_checksocket(lua_State *L, int ud)
2198{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02002199 return MAY_LJMP(hlua_checkudata(L, ud, class_socket_ref));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002200}
2201
2202/* This function is the handler called for each I/O on the established
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002203 * connection. It is used for notify space available to send or data
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002204 * received.
2205 */
Willy Tarreau00a37f02015-04-13 12:05:19 +02002206static void hlua_socket_handler(struct appctx *appctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002207{
Willy Tarreau5321da92022-05-06 11:57:34 +02002208 struct hlua_csk_ctx *ctx = appctx->svcctx;
Willy Tarreauc12b3212022-05-27 11:08:15 +02002209 struct stconn *sc = appctx_sc(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002210
Christopher Faulet31572222023-03-31 11:13:48 +02002211 if (unlikely(se_fl_test(appctx->sedesc, (SE_FL_EOS|SE_FL_ERROR|SE_FL_SHR|SE_FL_SHW)))) {
Aurelien DARRAGONa2c53212023-05-02 19:10:24 +02002212 co_skip(sc_oc(sc), co_data(sc_oc(sc)));
Christopher Faulet31572222023-03-31 11:13:48 +02002213 notification_wake(&ctx->wake_on_read);
2214 notification_wake(&ctx->wake_on_write);
2215 return;
2216 }
2217
Willy Tarreau5321da92022-05-06 11:57:34 +02002218 if (ctx->die) {
Christopher Faulet31572222023-03-31 11:13:48 +02002219 se_fl_set(appctx->sedesc, SE_FL_EOI|SE_FL_EOS);
Willy Tarreau5321da92022-05-06 11:57:34 +02002220 notification_wake(&ctx->wake_on_read);
2221 notification_wake(&ctx->wake_on_write);
Christopher Faulet31572222023-03-31 11:13:48 +02002222 return;
Thierry FOURNIERb13b20a2017-07-16 20:48:54 +02002223 }
2224
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +05002225 /* If we can't write, wakeup the pending write signals. */
Willy Tarreau3e7be362022-05-27 10:35:27 +02002226 if (channel_output_closed(sc_ic(sc)))
Willy Tarreau5321da92022-05-06 11:57:34 +02002227 notification_wake(&ctx->wake_on_write);
Thierry FOURNIER6d695e62015-09-27 19:29:38 +02002228
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +05002229 /* If we can't read, wakeup the pending read signals. */
Willy Tarreau3e7be362022-05-27 10:35:27 +02002230 if (channel_input_closed(sc_oc(sc)))
Willy Tarreau5321da92022-05-06 11:57:34 +02002231 notification_wake(&ctx->wake_on_read);
Thierry FOURNIER6d695e62015-09-27 19:29:38 +02002232
Willy Tarreau5a0b25d2019-07-18 18:01:14 +02002233 /* if the connection is not established, inform the stream that we want
Thierry FOURNIER316e3192015-09-04 18:25:53 +02002234 * to be notified whenever the connection completes.
2235 */
Willy Tarreau3e7be362022-05-27 10:35:27 +02002236 if (sc_opposite(sc)->state < SC_ST_EST) {
Willy Tarreau90e8b452022-05-25 18:21:43 +02002237 applet_need_more_data(appctx);
Willy Tarreaub23edc82022-05-24 16:49:03 +02002238 se_need_remote_conn(appctx->sedesc);
Willy Tarreau4164eb92022-05-25 15:42:03 +02002239 applet_have_more_data(appctx);
Willy Tarreaud4da1962015-04-20 01:31:23 +02002240 return;
Thierry FOURNIER316e3192015-09-04 18:25:53 +02002241 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002242
2243 /* This function is called after the connect. */
Willy Tarreau5321da92022-05-06 11:57:34 +02002244 ctx->connected = 1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002245
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002246 /* Wake the tasks which wants to write if the buffer have available space. */
Willy Tarreau3e7be362022-05-27 10:35:27 +02002247 if (channel_may_recv(sc_ic(sc)))
Willy Tarreau5321da92022-05-06 11:57:34 +02002248 notification_wake(&ctx->wake_on_write);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002249
2250 /* Wake the tasks which wants to read if the buffer contains data. */
Willy Tarreau3e7be362022-05-27 10:35:27 +02002251 if (!channel_is_empty(sc_oc(sc)))
Willy Tarreau5321da92022-05-06 11:57:34 +02002252 notification_wake(&ctx->wake_on_read);
Thierry FOURNIER101b9762018-05-27 01:27:40 +02002253
Thierry FOURNIER101b9762018-05-27 01:27:40 +02002254 /* If write notifications are registered, we considers we want
Willy Tarreau3367d412018-11-15 10:57:41 +01002255 * to write, so we clear the blocking flag.
Thierry FOURNIER101b9762018-05-27 01:27:40 +02002256 */
Willy Tarreau5321da92022-05-06 11:57:34 +02002257 if (notification_registered(&ctx->wake_on_write))
Willy Tarreau4164eb92022-05-25 15:42:03 +02002258 applet_have_more_data(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002259}
2260
Christopher Faulet5f35a3e2022-05-12 15:31:05 +02002261static int hlua_socket_init(struct appctx *appctx)
2262{
2263 struct hlua_csk_ctx *ctx = appctx->svcctx;
2264 struct stream *s;
2265
2266 if (appctx_finalize_startup(appctx, socket_proxy, &BUF_NULL) == -1)
2267 goto error;
2268
2269 s = appctx_strm(appctx);
2270
Willy Tarreau4596fe22022-05-17 19:07:51 +02002271 /* Configure "right" stream connector. This stconn is used to connect
Christopher Faulet5f35a3e2022-05-12 15:31:05 +02002272 * and retrieve data from the server. The connection is initialized
2273 * with the "struct server".
2274 */
Willy Tarreau74568cf2022-05-27 09:03:30 +02002275 sc_set_state(s->scb, SC_ST_ASS);
Christopher Faulet5f35a3e2022-05-12 15:31:05 +02002276
2277 /* Force destination server. */
2278 s->flags |= SF_DIRECT | SF_ASSIGNED | SF_BE_ASSIGNED;
2279 s->target = &socket_tcp->obj_type;
2280
2281 ctx->appctx = appctx;
2282 return 0;
2283
2284 error:
2285 return -1;
2286}
2287
Willy Tarreau87b09662015-04-03 00:22:06 +02002288/* This function is called when the "struct stream" is destroyed.
2289 * Remove the link from the object to this stream.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002290 * Wake all the pending signals.
2291 */
Willy Tarreau00a37f02015-04-13 12:05:19 +02002292static void hlua_socket_release(struct appctx *appctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002293{
Willy Tarreau5321da92022-05-06 11:57:34 +02002294 struct hlua_csk_ctx *ctx = appctx->svcctx;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002295 struct xref *peer;
2296
Christopher Faulet5f35a3e2022-05-12 15:31:05 +02002297 /* Remove my link in the original objects. */
Willy Tarreau5321da92022-05-06 11:57:34 +02002298 peer = xref_get_peer_and_lock(&ctx->xref);
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002299 if (peer)
Willy Tarreau5321da92022-05-06 11:57:34 +02002300 xref_disconnect(&ctx->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002301
2302 /* Wake all the task waiting for me. */
Willy Tarreau5321da92022-05-06 11:57:34 +02002303 notification_wake(&ctx->wake_on_read);
2304 notification_wake(&ctx->wake_on_write);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002305}
2306
2307/* If the garbage collectio of the object is launch, nobody
Willy Tarreau87b09662015-04-03 00:22:06 +02002308 * uses this object. If the stream does not exists, just quit.
2309 * Send the shutdown signal to the stream. In some cases,
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002310 * pending signal can rest in the read and write lists. destroy
2311 * it.
2312 */
2313__LJMP static int hlua_socket_gc(lua_State *L)
2314{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002315 struct hlua_socket *socket;
Willy Tarreau5321da92022-05-06 11:57:34 +02002316 struct hlua_csk_ctx *ctx;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002317 struct xref *peer;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002318
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002319 MAY_LJMP(check_args(L, 1, "__gc"));
2320
2321 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002322 peer = xref_get_peer_and_lock(&socket->xref);
2323 if (!peer)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002324 return 0;
Willy Tarreau5321da92022-05-06 11:57:34 +02002325
2326 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
2337/* The close function send shutdown signal and break the
Willy Tarreau87b09662015-04-03 00:22:06 +02002338 * links between the stream and the object.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002339 */
sada05ed3302018-05-11 11:48:18 -07002340__LJMP static int hlua_socket_close_helper(lua_State *L)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002341{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002342 struct hlua_socket *socket;
Willy Tarreau5321da92022-05-06 11:57:34 +02002343 struct hlua_csk_ctx *ctx;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002344 struct xref *peer;
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002345 struct hlua *hlua;
2346
2347 /* Get hlua struct, or NULL if we execute from main lua state */
2348 hlua = hlua_gethlua(L);
2349 if (!hlua)
2350 return 0;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002351
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002352 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002353
2354 /* Check if we run on the same thread than the xreator thread.
2355 * We cannot access to the socket if the thread is different.
2356 */
2357 if (socket->tid != tid)
2358 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2359
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002360 peer = xref_get_peer_and_lock(&socket->xref);
2361 if (!peer)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002362 return 0;
Willy Tarreauf31af932020-01-14 09:59:38 +01002363
2364 hlua->gc_count--;
Willy Tarreau5321da92022-05-06 11:57:34 +02002365 ctx = container_of(peer, struct hlua_csk_ctx, xref);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002366
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002367 /* Set the flag which destroy the session. */
Willy Tarreau5321da92022-05-06 11:57:34 +02002368 ctx->die = 1;
2369 appctx_wakeup(ctx->appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002370
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002371 /* Remove all reference between the Lua stack and the coroutine stream. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002372 xref_disconnect(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002373 return 0;
2374}
2375
sada05ed3302018-05-11 11:48:18 -07002376/* The close function calls close_helper.
2377 */
2378__LJMP static int hlua_socket_close(lua_State *L)
2379{
2380 MAY_LJMP(check_args(L, 1, "close"));
2381 return hlua_socket_close_helper(L);
2382}
2383
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002384/* This Lua function assumes that the stack contain three parameters.
2385 * 1 - USERDATA containing a struct socket
2386 * 2 - INTEGER with values of the macro defined below
2387 * If the integer is -1, we must read at most one line.
2388 * If the integer is -2, we ust read all the data until the
2389 * end of the stream.
2390 * If the integer is positive value, we must read a number of
2391 * bytes corresponding to this value.
2392 */
2393#define HLSR_READ_LINE (-1)
2394#define HLSR_READ_ALL (-2)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002395__LJMP static int hlua_socket_receive_yield(struct lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002396{
2397 struct hlua_socket *socket = MAY_LJMP(hlua_checksocket(L, 1));
2398 int wanted = lua_tointeger(L, 2);
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002399 struct hlua *hlua;
Willy Tarreau5321da92022-05-06 11:57:34 +02002400 struct hlua_csk_ctx *csk_ctx;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002401 struct appctx *appctx;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02002402 size_t len;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002403 int nblk;
Willy Tarreau206ba832018-06-14 15:27:31 +02002404 const char *blk1;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02002405 size_t len1;
Willy Tarreau206ba832018-06-14 15:27:31 +02002406 const char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02002407 size_t len2;
Thierry FOURNIER00543922015-03-09 18:35:06 +01002408 int skip_at_end = 0;
Willy Tarreau81389672015-03-10 12:03:52 +01002409 struct channel *oc;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002410 struct stream *s;
2411 struct xref *peer;
Thierry FOURNIER8c126c72018-05-25 16:27:44 +02002412 int missing_bytes;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002413
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002414 /* Get hlua struct, or NULL if we execute from main lua state */
2415 hlua = hlua_gethlua(L);
2416
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002417 /* Check if this lua stack is schedulable. */
2418 if (!hlua || !hlua->task)
2419 WILL_LJMP(luaL_error(L, "The 'receive' function is only allowed in "
2420 "'frontend', 'backend' or 'task'"));
2421
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002422 /* Check if we run on the same thread than the xreator thread.
2423 * We cannot access to the socket if the thread is different.
2424 */
2425 if (socket->tid != tid)
2426 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2427
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002428 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002429 peer = xref_get_peer_and_lock(&socket->xref);
2430 if (!peer)
2431 goto no_peer;
Willy Tarreau5321da92022-05-06 11:57:34 +02002432
2433 csk_ctx = container_of(peer, struct hlua_csk_ctx, xref);
2434 appctx = csk_ctx->appctx;
Willy Tarreau0698c802022-05-11 14:09:57 +02002435 s = appctx_strm(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002436
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002437 oc = &s->res;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002438 if (wanted == HLSR_READ_LINE) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002439 /* Read line. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02002440 nblk = co_getline_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002441 if (nblk < 0) /* Connection close. */
2442 goto connection_closed;
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002443 if (nblk == 0) /* No data available. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002444 goto connection_empty;
Thierry FOURNIER00543922015-03-09 18:35:06 +01002445
2446 /* remove final \r\n. */
2447 if (nblk == 1) {
2448 if (blk1[len1-1] == '\n') {
2449 len1--;
2450 skip_at_end++;
2451 if (blk1[len1-1] == '\r') {
2452 len1--;
2453 skip_at_end++;
2454 }
2455 }
2456 }
2457 else {
2458 if (blk2[len2-1] == '\n') {
2459 len2--;
2460 skip_at_end++;
2461 if (blk2[len2-1] == '\r') {
2462 len2--;
2463 skip_at_end++;
2464 }
2465 }
2466 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002467 }
2468
2469 else if (wanted == HLSR_READ_ALL) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002470 /* Read all the available data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02002471 nblk = co_getblk_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002472 if (nblk < 0) /* Connection close. */
2473 goto connection_closed;
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002474 if (nblk == 0) /* No data available. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002475 goto connection_empty;
2476 }
2477
2478 else {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002479 /* Read a block of data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02002480 nblk = co_getblk_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002481 if (nblk < 0) /* Connection close. */
2482 goto connection_closed;
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002483 if (nblk == 0) /* No data available. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002484 goto connection_empty;
2485
Thierry FOURNIER8c126c72018-05-25 16:27:44 +02002486 missing_bytes = wanted - socket->b.n;
2487 if (len1 > missing_bytes) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002488 nblk = 1;
Thierry FOURNIER8c126c72018-05-25 16:27:44 +02002489 len1 = missing_bytes;
2490 } if (nblk == 2 && len1 + len2 > missing_bytes)
2491 len2 = missing_bytes - len1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002492 }
2493
2494 len = len1;
2495
2496 luaL_addlstring(&socket->b, blk1, len1);
2497 if (nblk == 2) {
2498 len += len2;
2499 luaL_addlstring(&socket->b, blk2, len2);
2500 }
2501
2502 /* Consume data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02002503 co_skip(oc, len + skip_at_end);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002504
2505 /* Don't wait anything. */
Thierry FOURNIER7e4ee472018-05-25 15:03:50 +02002506 appctx_wakeup(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002507
2508 /* If the pattern reclaim to read all the data
2509 * in the connection, got out.
2510 */
2511 if (wanted == HLSR_READ_ALL)
2512 goto connection_empty;
Thierry FOURNIER8c126c72018-05-25 16:27:44 +02002513 else if (wanted >= 0 && socket->b.n < wanted)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002514 goto connection_empty;
2515
2516 /* Return result. */
2517 luaL_pushresult(&socket->b);
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002518 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002519 return 1;
2520
2521connection_closed:
2522
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002523 xref_unlock(&socket->xref, peer);
2524
2525no_peer:
2526
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002527 /* If the buffer containds data. */
2528 if (socket->b.n > 0) {
2529 luaL_pushresult(&socket->b);
2530 return 1;
2531 }
2532 lua_pushnil(L);
2533 lua_pushstring(L, "connection closed.");
2534 return 2;
2535
2536connection_empty:
2537
Willy Tarreau5321da92022-05-06 11:57:34 +02002538 if (!notification_new(&hlua->com, &csk_ctx->wake_on_read, hlua->task)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002539 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002540 WILL_LJMP(luaL_error(L, "out of memory"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002541 }
2542 xref_unlock(&socket->xref, peer);
Willy Tarreau9635e032018-10-16 17:52:55 +02002543 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_receive_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002544 return 0;
2545}
2546
Tim Duesterhusb33754c2018-01-04 19:32:14 +01002547/* This Lua function gets two parameters. The first one can be string
2548 * or a number. If the string is "*l", the user requires one line. If
2549 * the string is "*a", the user requires all the contents of the stream.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002550 * If the value is a number, the user require a number of bytes equal
2551 * to the value. The default value is "*l" (a line).
2552 *
Tim Duesterhusb33754c2018-01-04 19:32:14 +01002553 * This parameter with a variable type is converted in integer. This
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002554 * integer takes this values:
2555 * -1 : read a line
2556 * -2 : read all the stream
Tim Duesterhusb33754c2018-01-04 19:32:14 +01002557 * >0 : amount of bytes.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002558 *
Tim Duesterhusb33754c2018-01-04 19:32:14 +01002559 * The second parameter is optional. It contains a string that must be
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002560 * concatenated with the read data.
2561 */
2562__LJMP static int hlua_socket_receive(struct lua_State *L)
2563{
2564 int wanted = HLSR_READ_LINE;
2565 const char *pattern;
Christopher Fauletc31b2002021-05-03 10:11:13 +02002566 int lastarg, type;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002567 char *error;
2568 size_t len;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002569 struct hlua_socket *socket;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002570
2571 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
2572 WILL_LJMP(luaL_error(L, "The 'receive' function requires between 1 and 3 arguments."));
2573
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002574 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002575
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002576 /* Check if we run on the same thread than the xreator thread.
2577 * We cannot access to the socket if the thread is different.
2578 */
2579 if (socket->tid != tid)
2580 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2581
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002582 /* check for pattern. */
2583 if (lua_gettop(L) >= 2) {
2584 type = lua_type(L, 2);
2585 if (type == LUA_TSTRING) {
2586 pattern = lua_tostring(L, 2);
2587 if (strcmp(pattern, "*a") == 0)
2588 wanted = HLSR_READ_ALL;
2589 else if (strcmp(pattern, "*l") == 0)
2590 wanted = HLSR_READ_LINE;
2591 else {
2592 wanted = strtoll(pattern, &error, 10);
2593 if (*error != '\0')
2594 WILL_LJMP(luaL_error(L, "Unsupported pattern."));
2595 }
2596 }
2597 else if (type == LUA_TNUMBER) {
2598 wanted = lua_tointeger(L, 2);
2599 if (wanted < 0)
2600 WILL_LJMP(luaL_error(L, "Unsupported size."));
2601 }
2602 }
2603
2604 /* Set pattern. */
2605 lua_pushinteger(L, wanted);
Tim Duesterhusc6e377e2018-01-04 19:32:13 +01002606
2607 /* Check if we would replace the top by itself. */
2608 if (lua_gettop(L) != 2)
2609 lua_replace(L, 2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002610
Christopher Fauletc31b2002021-05-03 10:11:13 +02002611 /* Save index of the top of the stack because since buffers are used, it
2612 * may change
2613 */
2614 lastarg = lua_gettop(L);
2615
Tim Duesterhusb33754c2018-01-04 19:32:14 +01002616 /* init buffer, and fill it with prefix. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002617 luaL_buffinit(L, &socket->b);
2618
2619 /* Check prefix. */
Christopher Fauletc31b2002021-05-03 10:11:13 +02002620 if (lastarg >= 3) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002621 if (lua_type(L, 3) != LUA_TSTRING)
2622 WILL_LJMP(luaL_error(L, "Expect a 'string' for the prefix"));
2623 pattern = lua_tolstring(L, 3, &len);
2624 luaL_addlstring(&socket->b, pattern, len);
2625 }
2626
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002627 return __LJMP(hlua_socket_receive_yield(L, 0, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002628}
2629
2630/* Write the Lua input string in the output buffer.
Mark Lakes22154b42018-01-29 14:38:40 -08002631 * This function returns a yield if no space is available.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002632 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002633static int hlua_socket_write_yield(struct lua_State *L,int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002634{
2635 struct hlua_socket *socket;
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002636 struct hlua *hlua;
Willy Tarreau5321da92022-05-06 11:57:34 +02002637 struct hlua_csk_ctx *csk_ctx;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002638 struct appctx *appctx;
2639 size_t buf_len;
2640 const char *buf;
2641 int len;
2642 int send_len;
2643 int sent;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002644 struct xref *peer;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002645 struct stream *s;
Willy Tarreau3e7be362022-05-27 10:35:27 +02002646 struct stconn *sc;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002647
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002648 /* Get hlua struct, or NULL if we execute from main lua state */
2649 hlua = hlua_gethlua(L);
2650
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002651 /* Check if this lua stack is schedulable. */
2652 if (!hlua || !hlua->task)
2653 WILL_LJMP(luaL_error(L, "The 'write' function is only allowed in "
2654 "'frontend', 'backend' or 'task'"));
2655
2656 /* Get object */
2657 socket = MAY_LJMP(hlua_checksocket(L, 1));
2658 buf = MAY_LJMP(luaL_checklstring(L, 2, &buf_len));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002659 sent = MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002660
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002661 /* Check if we run on the same thread than the xreator thread.
2662 * We cannot access to the socket if the thread is different.
2663 */
2664 if (socket->tid != tid)
2665 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2666
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002667 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002668 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002669 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002670 lua_pushinteger(L, -1);
2671 return 1;
2672 }
Willy Tarreau5321da92022-05-06 11:57:34 +02002673
2674 csk_ctx = container_of(peer, struct hlua_csk_ctx, xref);
2675 appctx = csk_ctx->appctx;
Willy Tarreauc12b3212022-05-27 11:08:15 +02002676 sc = appctx_sc(appctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02002677 s = __sc_strm(sc);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002678
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002679 /* Check for connection close. */
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002680 if (channel_output_closed(&s->req)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002681 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002682 lua_pushinteger(L, -1);
2683 return 1;
2684 }
2685
2686 /* Update the input buffer data. */
2687 buf += sent;
2688 send_len = buf_len - sent;
2689
2690 /* All the data are sent. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002691 if (sent >= buf_len) {
2692 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002693 return 1; /* Implicitly return the length sent. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002694 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002695
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002696 /* Check if the buffer is available because HAProxy doesn't allocate
Thierry FOURNIER486d52a2015-03-09 17:51:43 +01002697 * the request buffer if its not required.
2698 */
Willy Tarreauc9fa0482018-07-10 17:43:27 +02002699 if (s->req.buf.size == 0) {
Willy Tarreau3e7be362022-05-27 10:35:27 +02002700 if (!sc_alloc_ibuf(sc, &appctx->buffer_wait))
Christopher Faulet33834b12016-12-19 09:29:06 +01002701 goto hlua_socket_write_yield_return;
Thierry FOURNIER486d52a2015-03-09 17:51:43 +01002702 }
2703
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002704 /* Check for available space. */
Willy Tarreauc9fa0482018-07-10 17:43:27 +02002705 len = b_room(&s->req.buf);
Christopher Faulet33834b12016-12-19 09:29:06 +01002706 if (len <= 0) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002707 goto hlua_socket_write_yield_return;
Christopher Faulet33834b12016-12-19 09:29:06 +01002708 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002709
2710 /* send data */
2711 if (len < send_len)
2712 send_len = len;
Thierry FOURNIER66b89192018-05-27 01:14:47 +02002713 len = ci_putblk(&s->req, buf, send_len);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002714
2715 /* "Not enough space" (-1), "Buffer too little to contain
2716 * the data" (-2) are not expected because the available length
2717 * is tested.
2718 * Other unknown error are also not expected.
2719 */
2720 if (len <= 0) {
Willy Tarreaubc18da12015-03-13 14:00:47 +01002721 if (len == -1)
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002722 s->req.flags |= CF_WAKE_WRITE;
Willy Tarreaubc18da12015-03-13 14:00:47 +01002723
sada05ed3302018-05-11 11:48:18 -07002724 MAY_LJMP(hlua_socket_close_helper(L));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002725 lua_pop(L, 1);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002726 lua_pushinteger(L, -1);
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002727 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002728 return 1;
2729 }
2730
2731 /* update buffers. */
Thierry FOURNIER101b9762018-05-27 01:27:40 +02002732 appctx_wakeup(appctx);
Willy Tarreaude70fa12015-09-26 11:25:05 +02002733
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002734 /* Update length sent. */
2735 lua_pop(L, 1);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002736 lua_pushinteger(L, sent + len);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002737
2738 /* All the data buffer is sent ? */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002739 if (sent + len >= buf_len) {
2740 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002741 return 1;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002742 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002743
2744hlua_socket_write_yield_return:
Willy Tarreau5321da92022-05-06 11:57:34 +02002745 if (!notification_new(&hlua->com, &csk_ctx->wake_on_write, hlua->task)) {
Thierry FOURNIERba42fcd2018-05-27 00:59:48 +02002746 xref_unlock(&socket->xref, peer);
2747 WILL_LJMP(luaL_error(L, "out of memory"));
2748 }
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002749 xref_unlock(&socket->xref, peer);
Willy Tarreau9635e032018-10-16 17:52:55 +02002750 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_write_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002751 return 0;
2752}
2753
2754/* This function initiate the send of data. It just check the input
2755 * parameters and push an integer in the Lua stack that contain the
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002756 * amount of data written to the buffer. This is used by the function
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002757 * "hlua_socket_write_yield" that can yield.
2758 *
2759 * The Lua function gets between 3 and 4 parameters. The first one is
2760 * the associated object. The second is a string buffer. The third is
2761 * a facultative integer that represents where is the buffer position
2762 * of the start of the data that can send. The first byte is the
2763 * position "1". The default value is "1". The fourth argument is a
2764 * facultative integer that represents where is the buffer position
2765 * of the end of the data that can send. The default is the last byte.
2766 */
2767static int hlua_socket_send(struct lua_State *L)
2768{
2769 int i;
2770 int j;
2771 const char *buf;
2772 size_t buf_len;
2773
2774 /* Check number of arguments. */
2775 if (lua_gettop(L) < 2 || lua_gettop(L) > 4)
2776 WILL_LJMP(luaL_error(L, "'send' needs between 2 and 4 arguments"));
2777
2778 /* Get the string. */
2779 buf = MAY_LJMP(luaL_checklstring(L, 2, &buf_len));
2780
2781 /* Get and check j. */
2782 if (lua_gettop(L) == 4) {
2783 j = MAY_LJMP(luaL_checkinteger(L, 4));
2784 if (j < 0)
2785 j = buf_len + j + 1;
2786 if (j > buf_len)
2787 j = buf_len + 1;
2788 lua_pop(L, 1);
2789 }
2790 else
2791 j = buf_len;
2792
2793 /* Get and check i. */
2794 if (lua_gettop(L) == 3) {
2795 i = MAY_LJMP(luaL_checkinteger(L, 3));
2796 if (i < 0)
2797 i = buf_len + i + 1;
2798 if (i > buf_len)
2799 i = buf_len + 1;
2800 lua_pop(L, 1);
2801 } else
2802 i = 1;
2803
2804 /* Check bth i and j. */
2805 if (i > j) {
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002806 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002807 return 1;
2808 }
2809 if (i == 0 && j == 0) {
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002810 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002811 return 1;
2812 }
2813 if (i == 0)
2814 i = 1;
2815 if (j == 0)
2816 j = 1;
2817
2818 /* Pop the string. */
2819 lua_pop(L, 1);
2820
2821 /* Update the buffer length. */
2822 buf += i - 1;
2823 buf_len = j - i + 1;
2824 lua_pushlstring(L, buf, buf_len);
2825
2826 /* This unsigned is used to remember the amount of sent data. */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002827 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002828
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002829 return MAY_LJMP(hlua_socket_write_yield(L, 0, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002830}
2831
Willy Tarreau22b0a682015-06-17 19:43:49 +02002832#define SOCKET_INFO_MAX_LEN sizeof("[0000:0000:0000:0000:0000:0000:0000:0000]:12345")
Christopher Faulete6465b32021-10-22 15:36:08 +02002833__LJMP static inline int hlua_socket_info(struct lua_State *L, const struct sockaddr_storage *addr)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002834{
2835 static char buffer[SOCKET_INFO_MAX_LEN];
2836 int ret;
2837 int len;
2838 char *p;
2839
2840 ret = addr_to_str(addr, buffer+1, SOCKET_INFO_MAX_LEN-1);
2841 if (ret <= 0) {
2842 lua_pushnil(L);
2843 return 1;
2844 }
2845
2846 if (ret == AF_UNIX) {
2847 lua_pushstring(L, buffer+1);
2848 return 1;
2849 }
2850 else if (ret == AF_INET6) {
2851 buffer[0] = '[';
2852 len = strlen(buffer);
2853 buffer[len] = ']';
2854 len++;
2855 buffer[len] = ':';
2856 len++;
2857 p = buffer;
2858 }
2859 else if (ret == AF_INET) {
2860 p = buffer + 1;
2861 len = strlen(p);
2862 p[len] = ':';
2863 len++;
2864 }
2865 else {
2866 lua_pushnil(L);
2867 return 1;
2868 }
2869
2870 if (port_to_str(addr, p + len, SOCKET_INFO_MAX_LEN-1 - len) <= 0) {
2871 lua_pushnil(L);
2872 return 1;
2873 }
2874
2875 lua_pushstring(L, p);
2876 return 1;
2877}
2878
2879/* Returns information about the peer of the connection. */
2880__LJMP static int hlua_socket_getpeername(struct lua_State *L)
2881{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002882 struct hlua_socket *socket;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002883 struct xref *peer;
2884 struct appctx *appctx;
Willy Tarreau3e7be362022-05-27 10:35:27 +02002885 struct stconn *sc;
Christopher Faulet16f16af2021-10-27 09:34:56 +02002886 const struct sockaddr_storage *dst;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002887 int ret;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002888
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002889 MAY_LJMP(check_args(L, 1, "getpeername"));
2890
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002891 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002892
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002893 /* Check if we run on the same thread than the xreator thread.
2894 * We cannot access to the socket if the thread is different.
2895 */
2896 if (socket->tid != tid)
2897 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2898
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002899 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002900 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002901 if (!peer) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002902 lua_pushnil(L);
2903 return 1;
2904 }
Willy Tarreau5321da92022-05-06 11:57:34 +02002905
2906 appctx = container_of(peer, struct hlua_csk_ctx, xref)->appctx;
Willy Tarreauc12b3212022-05-27 11:08:15 +02002907 sc = appctx_sc(appctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02002908 dst = sc_dst(sc_opposite(sc));
Christopher Faulet16f16af2021-10-27 09:34:56 +02002909 if (!dst) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002910 xref_unlock(&socket->xref, peer);
Willy Tarreaua71f6422016-11-16 17:00:14 +01002911 lua_pushnil(L);
2912 return 1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002913 }
2914
Christopher Faulet16f16af2021-10-27 09:34:56 +02002915 ret = MAY_LJMP(hlua_socket_info(L, dst));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002916 xref_unlock(&socket->xref, peer);
2917 return ret;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002918}
2919
2920/* Returns information about my connection side. */
2921static int hlua_socket_getsockname(struct lua_State *L)
2922{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002923 struct hlua_socket *socket;
2924 struct connection *conn;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002925 struct appctx *appctx;
2926 struct xref *peer;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002927 struct stream *s;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002928 int ret;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002929
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002930 MAY_LJMP(check_args(L, 1, "getsockname"));
2931
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002932 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002933
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002934 /* Check if we run on the same thread than the xreator thread.
2935 * We cannot access to the socket if the thread is different.
2936 */
2937 if (socket->tid != tid)
2938 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2939
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002940 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002941 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002942 if (!peer) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002943 lua_pushnil(L);
2944 return 1;
2945 }
Willy Tarreau5321da92022-05-06 11:57:34 +02002946
2947 appctx = container_of(peer, struct hlua_csk_ctx, xref)->appctx;
Willy Tarreau0698c802022-05-11 14:09:57 +02002948 s = appctx_strm(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002949
Willy Tarreaufd9417b2022-05-18 16:23:22 +02002950 conn = sc_conn(s->scb);
Willy Tarreau5a0b25d2019-07-18 18:01:14 +02002951 if (!conn || !conn_get_src(conn)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002952 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002953 lua_pushnil(L);
2954 return 1;
2955 }
2956
Willy Tarreau9da9a6f2019-07-17 14:49:44 +02002957 ret = hlua_socket_info(L, conn->src);
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002958 xref_unlock(&socket->xref, peer);
2959 return ret;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002960}
2961
2962/* This struct define the applet. */
Willy Tarreau30576452015-04-13 13:50:30 +02002963static struct applet update_applet = {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002964 .obj_type = OBJ_TYPE_APPLET,
2965 .name = "<LUA_TCP>",
2966 .fct = hlua_socket_handler,
Christopher Faulet5f35a3e2022-05-12 15:31:05 +02002967 .init = hlua_socket_init,
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002968 .release = hlua_socket_release,
2969};
2970
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002971__LJMP static int hlua_socket_connect_yield(struct lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002972{
2973 struct hlua_socket *socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002974 struct hlua *hlua;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002975 struct xref *peer;
Willy Tarreau5321da92022-05-06 11:57:34 +02002976 struct hlua_csk_ctx *csk_ctx;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002977 struct appctx *appctx;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002978 struct stream *s;
2979
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002980 /* Get hlua struct, or NULL if we execute from main lua state */
2981 hlua = hlua_gethlua(L);
2982 if (!hlua)
2983 return 0;
2984
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002985 /* Check if we run on the same thread than the xreator thread.
2986 * We cannot access to the socket if the thread is different.
2987 */
2988 if (socket->tid != tid)
2989 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2990
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002991 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002992 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002993 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002994 lua_pushnil(L);
2995 lua_pushstring(L, "Can't connect");
2996 return 2;
2997 }
Willy Tarreau5321da92022-05-06 11:57:34 +02002998
2999 csk_ctx = container_of(peer, struct hlua_csk_ctx, xref);
3000 appctx = csk_ctx->appctx;
Willy Tarreau0698c802022-05-11 14:09:57 +02003001 s = appctx_strm(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003002
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02003003 /* Check if we run on the same thread than the xreator thread.
3004 * We cannot access to the socket if the thread is different.
3005 */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02003006 if (socket->tid != tid) {
3007 xref_unlock(&socket->xref, peer);
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02003008 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02003009 }
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02003010
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003011 /* Check for connection close. */
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003012 if (!hlua || channel_output_closed(&s->req)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02003013 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003014 lua_pushnil(L);
3015 lua_pushstring(L, "Can't connect");
3016 return 2;
3017 }
3018
Willy Tarreau8e7c6e62022-05-18 17:58:02 +02003019 appctx = __sc_appctx(s->scf);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003020
3021 /* Check for connection established. */
Willy Tarreau5321da92022-05-06 11:57:34 +02003022 if (csk_ctx->connected) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02003023 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003024 lua_pushinteger(L, 1);
3025 return 1;
3026 }
3027
Willy Tarreau5321da92022-05-06 11:57:34 +02003028 if (!notification_new(&hlua->com, &csk_ctx->wake_on_write, hlua->task)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02003029 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003030 WILL_LJMP(luaL_error(L, "out of memory error"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02003031 }
3032 xref_unlock(&socket->xref, peer);
Willy Tarreau9635e032018-10-16 17:52:55 +02003033 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_connect_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003034 return 0;
3035}
3036
3037/* This function fail or initite the connection. */
3038__LJMP static int hlua_socket_connect(struct lua_State *L)
3039{
3040 struct hlua_socket *socket;
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02003041 int port = -1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003042 const char *ip;
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01003043 struct hlua *hlua;
Willy Tarreau5321da92022-05-06 11:57:34 +02003044 struct hlua_csk_ctx *csk_ctx;
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01003045 struct appctx *appctx;
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02003046 int low, high;
3047 struct sockaddr_storage *addr;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003048 struct xref *peer;
Willy Tarreau3e7be362022-05-27 10:35:27 +02003049 struct stconn *sc;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003050 struct stream *s;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003051
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02003052 if (lua_gettop(L) < 2)
3053 WILL_LJMP(luaL_error(L, "connect: need at least 2 arguments"));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003054
3055 /* Get args. */
3056 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02003057
3058 /* Check if we run on the same thread than the xreator thread.
3059 * We cannot access to the socket if the thread is different.
3060 */
3061 if (socket->tid != tid)
3062 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
3063
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003064 ip = MAY_LJMP(luaL_checkstring(L, 2));
Tim Duesterhus6edab862018-01-06 19:04:45 +01003065 if (lua_gettop(L) >= 3) {
3066 luaL_Buffer b;
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02003067 port = MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003068
Tim Duesterhus6edab862018-01-06 19:04:45 +01003069 /* Force the ip to end with a colon, to support IPv6 addresses
3070 * that are not enclosed within square brackets.
3071 */
3072 if (port > 0) {
3073 luaL_buffinit(L, &b);
3074 luaL_addstring(&b, ip);
3075 luaL_addchar(&b, ':');
3076 luaL_pushresult(&b);
3077 ip = lua_tolstring(L, lua_gettop(L), NULL);
3078 }
3079 }
3080
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003081 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02003082 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003083 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003084 lua_pushnil(L);
3085 return 1;
3086 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003087
3088 /* Parse ip address. */
Willy Tarreau5fc93282020-09-16 18:25:03 +02003089 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 +02003090 if (!addr) {
3091 xref_unlock(&socket->xref, peer);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02003092 WILL_LJMP(luaL_error(L, "connect: cannot parse destination address '%s'", ip));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02003093 }
Willy Tarreau9da9a6f2019-07-17 14:49:44 +02003094
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003095 /* Set port. */
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02003096 if (low == 0) {
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02003097 if (addr->ss_family == AF_INET) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02003098 if (port == -1) {
3099 xref_unlock(&socket->xref, peer);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02003100 WILL_LJMP(luaL_error(L, "connect: port missing"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02003101 }
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02003102 ((struct sockaddr_in *)addr)->sin_port = htons(port);
3103 } else if (addr->ss_family == AF_INET6) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02003104 if (port == -1) {
3105 xref_unlock(&socket->xref, peer);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02003106 WILL_LJMP(luaL_error(L, "connect: port missing"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02003107 }
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02003108 ((struct sockaddr_in6 *)addr)->sin6_port = htons(port);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02003109 }
3110 }
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02003111
Willy Tarreau5321da92022-05-06 11:57:34 +02003112 csk_ctx = container_of(peer, struct hlua_csk_ctx, xref);
3113 appctx = csk_ctx->appctx;
Willy Tarreauc12b3212022-05-27 11:08:15 +02003114 sc = appctx_sc(appctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02003115 s = __sc_strm(sc);
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02003116
Willy Tarreau3e7be362022-05-27 10:35:27 +02003117 if (!sockaddr_alloc(&sc_opposite(sc)->dst, addr, sizeof(*addr))) {
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02003118 xref_unlock(&socket->xref, peer);
3119 WILL_LJMP(luaL_error(L, "connect: internal error"));
3120 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003121
Thierry Fournier4234dbd2020-11-28 13:18:23 +01003122 /* Get hlua struct, or NULL if we execute from main lua state */
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01003123 hlua = hlua_gethlua(L);
Thierry Fournier4234dbd2020-11-28 13:18:23 +01003124 if (!hlua)
3125 return 0;
Willy Tarreaubdc97a82015-08-24 15:42:28 +02003126
3127 /* inform the stream that we want to be notified whenever the
3128 * connection completes.
3129 */
Willy Tarreau90e8b452022-05-25 18:21:43 +02003130 applet_need_more_data(appctx);
Willy Tarreau4164eb92022-05-25 15:42:03 +02003131 applet_have_more_data(appctx);
Thierry FOURNIER8c8fbbe2015-09-26 17:02:35 +02003132 appctx_wakeup(appctx);
Willy Tarreaubdc97a82015-08-24 15:42:28 +02003133
Willy Tarreauf31af932020-01-14 09:59:38 +01003134 hlua->gc_count++;
Thierry FOURNIER7c39ab42015-09-27 22:53:33 +02003135
Willy Tarreau5321da92022-05-06 11:57:34 +02003136 if (!notification_new(&hlua->com, &csk_ctx->wake_on_write, hlua->task)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02003137 xref_unlock(&socket->xref, peer);
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01003138 WILL_LJMP(luaL_error(L, "out of memory"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02003139 }
3140 xref_unlock(&socket->xref, peer);
PiBa-NL706d5ee2018-05-05 23:51:42 +02003141
3142 task_wakeup(s->task, TASK_WOKEN_INIT);
3143 /* Return yield waiting for connection. */
3144
Willy Tarreau9635e032018-10-16 17:52:55 +02003145 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_connect_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003146
3147 return 0;
3148}
3149
Baptiste Assmann84bb4932015-03-02 21:40:06 +01003150#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003151__LJMP static int hlua_socket_connect_ssl(struct lua_State *L)
3152{
3153 struct hlua_socket *socket;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003154 struct xref *peer;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003155 struct stream *s;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003156
3157 MAY_LJMP(check_args(L, 3, "connect_ssl"));
3158 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003159
3160 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02003161 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003162 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003163 lua_pushnil(L);
3164 return 1;
3165 }
Willy Tarreau5321da92022-05-06 11:57:34 +02003166
Willy Tarreau0698c802022-05-11 14:09:57 +02003167 s = appctx_strm(container_of(peer, struct hlua_csk_ctx, xref)->appctx);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003168
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +01003169 s->target = &socket_ssl->obj_type;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02003170 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003171 return MAY_LJMP(hlua_socket_connect(L));
3172}
Baptiste Assmann84bb4932015-03-02 21:40:06 +01003173#endif
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003174
3175__LJMP static int hlua_socket_setoption(struct lua_State *L)
3176{
3177 return 0;
3178}
3179
3180__LJMP static int hlua_socket_settimeout(struct lua_State *L)
3181{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003182 struct hlua_socket *socket;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003183 int tmout;
Mark Lakes56cc1252018-03-27 09:48:06 +02003184 double dtmout;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003185 struct xref *peer;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003186 struct stream *s;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003187
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003188 MAY_LJMP(check_args(L, 2, "settimeout"));
3189
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003190 socket = MAY_LJMP(hlua_checksocket(L, 1));
Mark Lakes56cc1252018-03-27 09:48:06 +02003191
Cyril Bonté7ee465f2018-08-19 22:08:50 +02003192 /* convert the timeout to millis */
3193 dtmout = MAY_LJMP(luaL_checknumber(L, 2)) * 1000;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003194
Thierry Fournier17a921b2018-03-08 09:59:02 +01003195 /* Check for negative values */
Mark Lakes56cc1252018-03-27 09:48:06 +02003196 if (dtmout < 0)
Thierry Fournier17a921b2018-03-08 09:59:02 +01003197 WILL_LJMP(luaL_error(L, "settimeout: cannot set negatives values"));
3198
Mark Lakes56cc1252018-03-27 09:48:06 +02003199 if (dtmout > INT_MAX) /* overflow check */
Cyril Bonté7ee465f2018-08-19 22:08:50 +02003200 WILL_LJMP(luaL_error(L, "settimeout: cannot set values larger than %d ms", INT_MAX));
Mark Lakes56cc1252018-03-27 09:48:06 +02003201
3202 tmout = MS_TO_TICKS((int)dtmout);
Cyril Bonté7ee465f2018-08-19 22:08:50 +02003203 if (tmout == 0)
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05003204 tmout++; /* very small timeouts are adjusted to a minimum of 1ms */
Mark Lakes56cc1252018-03-27 09:48:06 +02003205
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02003206 /* Check if we run on the same thread than the xreator thread.
3207 * We cannot access to the socket if the thread is different.
3208 */
3209 if (socket->tid != tid)
3210 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
3211
Mark Lakes56cc1252018-03-27 09:48:06 +02003212 /* check for connection break. If some data were read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02003213 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003214 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003215 hlua_pusherror(L, "socket: not yet initialised, you can't set timeouts.");
3216 WILL_LJMP(lua_error(L));
3217 return 0;
3218 }
Willy Tarreau5321da92022-05-06 11:57:34 +02003219
Willy Tarreau0698c802022-05-11 14:09:57 +02003220 s = appctx_strm(container_of(peer, struct hlua_csk_ctx, xref)->appctx);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003221
Cyril Bonté7bb63452018-08-17 23:51:02 +02003222 s->sess->fe->timeout.connect = tmout;
Christopher Faulet5aaacfb2023-02-15 08:13:33 +01003223 s->scf->ioto = tmout;
3224 s->scb->ioto = tmout;
Cyril Bonté7bb63452018-08-17 23:51:02 +02003225
3226 s->task->expire = tick_add_ifset(now_ms, tmout);
3227 task_queue(s->task);
3228
Thierry FOURNIER952939d2017-09-01 14:17:32 +02003229 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003230
Thierry Fourniere9636f12018-03-08 09:54:32 +01003231 lua_pushinteger(L, 1);
Tim Duesterhus119a5f12018-01-06 19:16:25 +01003232 return 1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003233}
3234
3235__LJMP static int hlua_socket_new(lua_State *L)
3236{
3237 struct hlua_socket *socket;
Willy Tarreau5321da92022-05-06 11:57:34 +02003238 struct hlua_csk_ctx *ctx;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003239 struct appctx *appctx;
3240
3241 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003242 if (!lua_checkstack(L, 3)) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003243 hlua_pusherror(L, "socket: full stack");
3244 goto out_fail_conf;
3245 }
3246
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003247 /* Create the object: obj[0] = userdata. */
3248 lua_newtable(L);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003249 socket = MAY_LJMP(lua_newuserdata(L, sizeof(*socket)));
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003250 lua_rawseti(L, -2, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003251 memset(socket, 0, sizeof(*socket));
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02003252 socket->tid = tid;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003253
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05003254 /* Check if the various memory pools are initialized. */
Willy Tarreaubafbe012017-11-24 17:34:44 +01003255 if (!pool_head_stream || !pool_head_buffer) {
Thierry FOURNIER4a6170c2015-03-09 17:07:10 +01003256 hlua_pusherror(L, "socket: uninitialized pools.");
3257 goto out_fail_conf;
3258 }
3259
Willy Tarreau87b09662015-04-03 00:22:06 +02003260 /* Pop a class stream metatable and affect it to the userdata. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003261 lua_rawgeti(L, LUA_REGISTRYINDEX, class_socket_ref);
3262 lua_setmetatable(L, -2);
3263
Willy Tarreaud420a972015-04-06 00:39:18 +02003264 /* Create the applet context */
Christopher Faulet6095d572022-05-16 17:09:48 +02003265 appctx = appctx_new_here(&update_applet, NULL);
Willy Tarreau61cf7c82015-04-06 00:48:33 +02003266 if (!appctx) {
3267 hlua_pusherror(L, "socket: out of memory");
Christopher Fauleta9e8b392022-03-23 11:01:09 +01003268 goto out_fail_conf;
Willy Tarreau61cf7c82015-04-06 00:48:33 +02003269 }
Willy Tarreau5321da92022-05-06 11:57:34 +02003270 ctx = applet_reserve_svcctx(appctx, sizeof(*ctx));
3271 ctx->connected = 0;
Willy Tarreau5321da92022-05-06 11:57:34 +02003272 ctx->die = 0;
3273 LIST_INIT(&ctx->wake_on_write);
3274 LIST_INIT(&ctx->wake_on_read);
Willy Tarreaub2bf8332015-04-04 15:58:58 +02003275
Christopher Faulet5f35a3e2022-05-12 15:31:05 +02003276 if (appctx_init(appctx) == -1) {
3277 hlua_pusherror(L, "socket: fail to init applet.");
Christopher Faulet13a35e52021-12-20 15:34:16 +01003278 goto out_fail_appctx;
3279 }
3280
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003281 /* Initialise cross reference between stream and Lua socket object. */
Willy Tarreau5321da92022-05-06 11:57:34 +02003282 xref_create(&socket->xref, &ctx->xref);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003283 return 1;
3284
Christopher Faulet13a35e52021-12-20 15:34:16 +01003285 out_fail_appctx:
Christopher Faulet5f35a3e2022-05-12 15:31:05 +02003286 appctx_free_on_early_error(appctx);
Willy Tarreaud420a972015-04-06 00:39:18 +02003287 out_fail_conf:
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003288 WILL_LJMP(lua_error(L));
3289 return 0;
3290}
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01003291
3292/*
3293 *
3294 *
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003295 * Class Channel
3296 *
3297 *
3298 */
3299
3300/* Returns the struct hlua_channel join to the class channel in the
3301 * stack entry "ud" or throws an argument error.
3302 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01003303__LJMP static struct channel *hlua_checkchannel(lua_State *L, int ud)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003304{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003305 return MAY_LJMP(hlua_checkudata(L, ud, class_channel_ref));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003306}
3307
Willy Tarreau47860ed2015-03-10 14:07:50 +01003308/* Pushes the channel onto the top of the stack. If the stask does not have a
3309 * free slots, the function fails and returns 0;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003310 */
Willy Tarreau2a71af42015-03-10 13:51:50 +01003311static int hlua_channel_new(lua_State *L, struct channel *channel)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003312{
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003313 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003314 if (!lua_checkstack(L, 3))
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003315 return 0;
3316
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003317 lua_newtable(L);
Willy Tarreau47860ed2015-03-10 14:07:50 +01003318 lua_pushlightuserdata(L, channel);
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003319 lua_rawseti(L, -2, 0);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003320
3321 /* Pop a class sesison metatable and affect it to the userdata. */
3322 lua_rawgeti(L, LUA_REGISTRYINDEX, class_channel_ref);
3323 lua_setmetatable(L, -2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003324 return 1;
3325}
3326
Christopher Faulet9f55a502020-02-25 15:21:02 +01003327/* Helper function returning a filter attached to a channel at the position <ud>
3328 * in the stack, filling the current offset and length of the filter. If no
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05003329 * filter is attached, NULL is returned and <offset> and <len> are not
Christopher Faulet9f55a502020-02-25 15:21:02 +01003330 * initialized.
3331 */
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003332static 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 +01003333{
3334 struct filter *filter = NULL;
3335
3336 if (lua_getfield(L, ud, "__filter") == LUA_TLIGHTUSERDATA) {
3337 struct hlua_flt_ctx *flt_ctx;
3338
3339 filter = lua_touserdata (L, -1);
3340 flt_ctx = filter->ctx;
3341 if (hlua_filter_from_payload(filter)) {
3342 *offset = flt_ctx->cur_off[CHN_IDX(chn)];
3343 *len = flt_ctx->cur_len[CHN_IDX(chn)];
3344 }
3345 }
3346
3347 lua_pop(L, 1);
3348 return filter;
3349}
3350
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003351/* Copies <len> bytes of data present in the channel's buffer, starting at the
3352* offset <offset>, and put it in a LUA string variable. It is the caller
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003353* responsibility to ensure <len> and <offset> are valid. It always return the
3354* length of the built string. <len> may be 0, in this case, an empty string is
3355* created and 0 is returned.
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003356*/
3357static inline int _hlua_channel_dup(struct channel *chn, lua_State *L, size_t offset, size_t len)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003358{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003359 size_t block1, block2;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003360 luaL_Buffer b;
3361
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003362 block1 = len;
3363 if (block1 > b_contig_data(&chn->buf, b_peek_ofs(&chn->buf, offset)))
3364 block1 = b_contig_data(&chn->buf, b_peek_ofs(&chn->buf, offset));
3365 block2 = len - block1;
3366
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003367 luaL_buffinit(L, &b);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003368 luaL_addlstring(&b, b_peek(&chn->buf, offset), block1);
3369 if (block2)
3370 luaL_addlstring(&b, b_orig(&chn->buf), block2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003371 luaL_pushresult(&b);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003372 return len;
3373}
3374
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003375/* Inserts the string <str> to the channel's buffer at the offset <offset>. This
3376 * function returns -1 if data cannot be copied. Otherwise, it returns the
3377 * number of bytes copied.
3378 */
3379static int _hlua_channel_insert(struct channel *chn, lua_State *L, struct ist str, size_t offset)
3380{
3381 int ret = 0;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003382
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003383 /* Nothing to do, just return */
3384 if (unlikely(istlen(str) == 0))
3385 goto end;
3386
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003387 if (istlen(str) > c_room(chn)) {
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003388 ret = -1;
3389 goto end;
3390 }
3391 ret = b_insert_blk(&chn->buf, offset, istptr(str), istlen(str));
3392
3393 end:
3394 return ret;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003395}
3396
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003397/* Removes <len> bytes of data at the absolute position <offset>.
3398 */
3399static void _hlua_channel_delete(struct channel *chn, size_t offset, size_t len)
3400{
3401 size_t end = offset + len;
3402
3403 if (b_peek(&chn->buf, end) != b_tail(&chn->buf))
3404 b_move(&chn->buf, b_peek_ofs(&chn->buf, end),
3405 b_data(&chn->buf) - end, -len);
3406 b_sub(&chn->buf, len);
3407}
3408
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003409/* Copies input data in the channel's buffer. It is possible to set a specific
3410 * offset (0 by default) and a length (all remaining input data starting for the
3411 * offset by default). If there is not enough input data and more data can be
3412 * received, this function yields.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003413 *
3414 * From an action, All input data are considered. For a filter, the offset and
3415 * the length of input data to consider are retrieved from the filter context.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003416 */
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003417__LJMP static int hlua_channel_get_data_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003418{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003419 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003420 struct filter *filter;
3421 size_t input, output;
3422 int offset, len;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003423
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003424 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003425
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003426 output = co_data(chn);
3427 input = ci_data(chn);
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003428
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003429 filter = hlua_channel_filter(L, 1, chn, &output, &input);
3430 if (filter && !hlua_filter_from_payload(filter))
3431 WILL_LJMP(lua_error(L));
3432
3433 offset = output;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003434 if (lua_gettop(L) > 1) {
3435 offset = MAY_LJMP(luaL_checkinteger(L, 2));
3436 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02003437 offset = MAX(0, (int)input + offset);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003438 offset += output;
3439 if (offset < output || offset > input + output) {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003440 lua_pushfstring(L, "offset out of range.");
3441 WILL_LJMP(lua_error(L));
3442 }
3443 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003444 len = output + input - offset;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003445 if (lua_gettop(L) == 3) {
3446 len = MAY_LJMP(luaL_checkinteger(L, 3));
3447 if (!len)
3448 goto dup;
3449 if (len == -1)
3450 len = global.tune.bufsize;
3451 if (len < 0) {
3452 lua_pushfstring(L, "length out of range.");
3453 WILL_LJMP(lua_error(L));
3454 }
3455 }
3456
Christopher Faulet0ae2e632023-01-10 15:29:54 +01003457 /* Wait for more data if possible if no length was specified and there
3458 * is no data or not enough data was received.
3459 */
3460 if (!len || offset + len > output + input) {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003461 if (!HLUA_CANT_YIELD(hlua_gethlua(L)) && !channel_input_closed(chn) && channel_may_recv(chn)) {
3462 /* Yield waiting for more data, as requested */
3463 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_get_data_yield, TICK_ETERNITY, 0));
3464 }
Christopher Faulet0ae2e632023-01-10 15:29:54 +01003465
3466 /* Return 'nil' if there is no data and the channel can't receive more data */
3467 if (!len) {
3468 lua_pushnil(L);
3469 return -1;
3470 }
3471
3472 /* Otherwise, return all data */
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003473 len = output + input - offset;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003474 }
3475
3476 dup:
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003477 _hlua_channel_dup(chn, L, offset, len);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003478 return 1;
3479}
3480
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003481/* Copies the first line (including the trailing LF) of input data in the
3482 * channel's buffer. It is possible to set a specific offset (0 by default) and
3483 * a length (all remaining input data starting for the offset by default). If
3484 * there is not enough input data and more data can be received, the function
3485 * yields. If a length is explicitly specified, no more data are
3486 * copied. Otherwise, if no LF is found and more data can be received, this
3487 * function yields.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003488 *
3489 * From an action, All input data are considered. For a filter, the offset and
3490 * the length of input data to consider are retrieved from the filter context.
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003491 */
3492__LJMP static int hlua_channel_get_line_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003493{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003494 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003495 struct filter *filter;
3496 size_t l, input, output;
3497 int offset, len;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003498
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003499 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003500 output = co_data(chn);
3501 input = ci_data(chn);
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003502
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003503 filter = hlua_channel_filter(L, 1, chn, &output, &input);
3504 if (filter && !hlua_filter_from_payload(filter))
3505 WILL_LJMP(lua_error(L));
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003506
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003507 offset = output;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003508 if (lua_gettop(L) > 1) {
3509 offset = MAY_LJMP(luaL_checkinteger(L, 2));
3510 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02003511 offset = MAX(0, (int)input + offset);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003512 offset += output;
3513 if (offset < output || offset > input + output) {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003514 lua_pushfstring(L, "offset out of range.");
3515 WILL_LJMP(lua_error(L));
3516 }
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003517 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003518
3519 len = output + input - offset;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003520 if (lua_gettop(L) == 3) {
3521 len = MAY_LJMP(luaL_checkinteger(L, 3));
3522 if (!len)
3523 goto dup;
3524 if (len == -1)
3525 len = global.tune.bufsize;
3526 if (len < 0) {
3527 lua_pushfstring(L, "length out of range.");
3528 WILL_LJMP(lua_error(L));
3529 }
3530 }
3531
3532 for (l = 0; l < len; l++) {
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003533 if (l + offset >= output + input)
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003534 break;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003535 if (*(b_peek(&chn->buf, offset + l)) == '\n') {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003536 len = l+1;
3537 goto dup;
3538 }
3539 }
3540
Christopher Faulet0ae2e632023-01-10 15:29:54 +01003541 /* Wait for more data if possible if no line is found and no length was
3542 * specified or not enough data was received.
3543 */
3544 if (lua_gettop(L) != 3 || offset + len > output + input) {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003545 if (!HLUA_CANT_YIELD(hlua_gethlua(L)) && !channel_input_closed(chn) && channel_may_recv(chn)) {
3546 /* Yield waiting for more data */
3547 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_get_line_yield, TICK_ETERNITY, 0));
3548 }
Christopher Faulet0ae2e632023-01-10 15:29:54 +01003549
3550 /* Return 'nil' if there is no data and the channel can't receive more data */
3551 if (!len) {
3552 lua_pushnil(L);
3553 return -1;
3554 }
3555
3556 /* Otherwise, return all data */
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003557 len = output + input - offset;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003558 }
3559
3560 dup:
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003561 _hlua_channel_dup(chn, L, offset, len);
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003562 return 1;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003563}
3564
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003565/* [ DEPRECATED ]
3566 *
3567 * Duplicate all input data foud in the channel's buffer. The data are not
3568 * removed from the buffer. This function relies on _hlua_channel_dup().
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003569 *
3570 * From an action, All input data are considered. For a filter, the offset and
3571 * the length of input data to consider are retrieved from the filter context.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003572 */
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003573__LJMP static int hlua_channel_dup(lua_State *L)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003574{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003575 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003576 struct filter *filter;
3577 size_t offset, len;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003578
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003579 MAY_LJMP(check_args(L, 1, "dup"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003580 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003581 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 Faulet9a6ffda2021-08-06 13:49:54 +02003586 offset = co_data(chn);
3587 len = ci_data(chn);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003588
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);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003595 return 1;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003596 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003597
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003598 _hlua_channel_dup(chn, L, offset, len);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003599 return 1;
3600}
3601
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003602/* [ DEPRECATED ]
3603 *
3604 * Get all input data foud in the channel's buffer. The data are removed from
3605 * the buffer after the copy. This function relies on _hlua_channel_dup() and
3606 * _hlua_channel_delete().
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.
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003610 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003611__LJMP static int hlua_channel_get(lua_State *L)
3612{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003613 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003614 struct filter *filter;
3615 size_t offset, len;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003616 int ret;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003617
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003618 MAY_LJMP(check_args(L, 1, "get"));
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003619 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3620 if (IS_HTX_STRM(chn_strm(chn))) {
3621 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3622 WILL_LJMP(lua_error(L));
3623 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003624
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003625 offset = co_data(chn);
3626 len = ci_data(chn);
3627
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003628 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3629 if (filter && !hlua_filter_from_payload(filter))
3630 WILL_LJMP(lua_error(L));
3631
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003632 if (!ci_data(chn) && channel_input_closed(chn)) {
3633 lua_pushnil(L);
3634 return 1;
3635 }
3636
3637 ret = _hlua_channel_dup(chn, L, offset, len);
3638 _hlua_channel_delete(chn, offset, ret);
3639 return 1;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003640}
3641
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003642/* This functions consumes and returns one line. If the channel is closed,
3643 * and the last data does not contains a final '\n', the data are returned
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003644 * without the final '\n'. When no more data are available, it returns nil
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003645 * value.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003646 *
3647 * From an action, All input data are considered. For a filter, the offset and
3648 * the length of input data to consider are retrieved from the filter context.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003649 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003650__LJMP static int hlua_channel_getline_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003651{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003652 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003653 struct filter *filter;
3654 size_t l, offset, len;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003655 int ret;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003656
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003657 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003658
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003659 offset = co_data(chn);
3660 len = ci_data(chn);
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003661
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003662 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3663 if (filter && !hlua_filter_from_payload(filter))
3664 WILL_LJMP(lua_error(L));
3665
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003666 if (!ci_data(chn) && channel_input_closed(chn)) {
3667 lua_pushnil(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003668 return 1;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003669 }
3670
3671 for (l = 0; l < len; l++) {
3672 if (*(b_peek(&chn->buf, offset+l)) == '\n') {
3673 len = l+1;
3674 goto dup;
3675 }
3676 }
3677
3678 if (!HLUA_CANT_YIELD(hlua_gethlua(L)) && !channel_input_closed(chn) && channel_may_recv(chn)) {
3679 /* Yield waiting for more data */
3680 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_getline_yield, TICK_ETERNITY, 0));
3681 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003682
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003683 dup:
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003684 ret = _hlua_channel_dup(chn, L, offset, len);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003685 _hlua_channel_delete(chn, offset, ret);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003686 return 1;
3687}
3688
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003689/* [ DEPRECATED ]
3690 *
3691 * Check arguments for the function "hlua_channel_getline_yield".
3692 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003693__LJMP static int hlua_channel_getline(lua_State *L)
3694{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003695 struct channel *chn;
3696
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003697 MAY_LJMP(check_args(L, 1, "getline"));
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003698 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3699 if (IS_HTX_STRM(chn_strm(chn))) {
3700 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3701 WILL_LJMP(lua_error(L));
3702 }
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003703 return MAY_LJMP(hlua_channel_getline_yield(L, 0, 0));
3704}
3705
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003706/* Retrieves a given amount of input data at the given offset. By default all
3707 * available input data are returned. The offset may be negactive to start from
3708 * the end of input data. The length may be -1 to set it to the maximum buffer
3709 * size.
3710 */
3711__LJMP static int hlua_channel_get_data(lua_State *L)
3712{
3713 struct channel *chn;
3714
3715 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
3716 WILL_LJMP(luaL_error(L, "'data' expects at most 2 arguments"));
3717 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3718 if (IS_HTX_STRM(chn_strm(chn))) {
3719 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3720 WILL_LJMP(lua_error(L));
3721 }
3722 return MAY_LJMP(hlua_channel_get_data_yield(L, 0, 0));
3723}
3724
3725/* Retrieves a given amount of input data at the given offset. By default all
3726 * available input data are returned. The offset may be negactive to start from
3727 * the end of input data. The length may be -1 to set it to the maximum buffer
3728 * size.
3729 */
3730__LJMP static int hlua_channel_get_line(lua_State *L)
3731{
3732 struct channel *chn;
3733
3734 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
3735 WILL_LJMP(luaL_error(L, "'line' expects at most 2 arguments"));
3736 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3737 if (IS_HTX_STRM(chn_strm(chn))) {
3738 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3739 WILL_LJMP(lua_error(L));
3740 }
3741 return MAY_LJMP(hlua_channel_get_line_yield(L, 0, 0));
3742}
3743
3744/* Appends a string into the input side of channel. It returns the length of the
3745 * written string, or -1 if the channel is closed or if the buffer size is too
3746 * little for the data. 0 may be returned if nothing is copied. This function
3747 * does not yield.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003748 *
3749 * For a filter, the context is updated on success.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003750 */
Christopher Faulet23976d92021-08-06 09:59:49 +02003751__LJMP static int hlua_channel_append(lua_State *L)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003752{
Christopher Faulet23976d92021-08-06 09:59:49 +02003753 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003754 struct filter *filter;
Christopher Faulet23976d92021-08-06 09:59:49 +02003755 const char *str;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003756 size_t sz, offset, len;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003757 int ret;
Christopher Faulet23976d92021-08-06 09:59:49 +02003758
3759 MAY_LJMP(check_args(L, 2, "append"));
3760 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003761 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
Christopher Faulet1bb6afa2021-03-08 17:57:53 +01003762 if (IS_HTX_STRM(chn_strm(chn))) {
Thierry Fournier77016da2020-08-15 14:35:51 +02003763 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
Christopher Faulet3f829a42018-12-13 21:56:45 +01003764 WILL_LJMP(lua_error(L));
Thierry Fournier77016da2020-08-15 14:35:51 +02003765 }
Christopher Faulet3f829a42018-12-13 21:56:45 +01003766
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003767 offset = co_data(chn);
3768 len = ci_data(chn);
3769
3770 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3771 if (filter && !hlua_filter_from_payload(filter))
3772 WILL_LJMP(lua_error(L));
3773
3774 ret = _hlua_channel_insert(chn, L, ist2(str, sz), offset);
3775 if (ret > 0 && filter) {
3776 struct hlua_flt_ctx *flt_ctx = filter->ctx;
3777
3778 flt_update_offsets(filter, chn, ret);
3779 flt_ctx->cur_len[CHN_IDX(chn)] += ret;
3780 }
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003781 lua_pushinteger(L, ret);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003782 return 1;
3783}
3784
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003785/* Prepends a string into the input side of channel. It returns the length of the
3786 * written string, or -1 if the channel is closed or if the buffer size is too
3787 * little for the data. 0 may be returned if nothing is copied. This function
3788 * does not yield.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003789 *
3790 * For a filter, the context is updated on success.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003791 */
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003792__LJMP static int hlua_channel_prepend(lua_State *L)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003793{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003794 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003795 struct filter *filter;
Christopher Faulet23976d92021-08-06 09:59:49 +02003796 const char *str;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003797 size_t sz, offset, len;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003798 int ret;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003799
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003800 MAY_LJMP(check_args(L, 2, "prepend"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003801 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003802 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
3803 if (IS_HTX_STRM(chn_strm(chn))) {
3804 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3805 WILL_LJMP(lua_error(L));
3806 }
3807
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003808 offset = co_data(chn);
3809 len = ci_data(chn);
3810
3811 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3812 if (filter && !hlua_filter_from_payload(filter))
3813 WILL_LJMP(lua_error(L));
3814
3815 ret = _hlua_channel_insert(chn, L, ist2(str, sz), offset);
3816 if (ret > 0 && filter) {
3817 struct hlua_flt_ctx *flt_ctx = filter->ctx;
3818
3819 flt_update_offsets(filter, chn, ret);
3820 flt_ctx->cur_len[CHN_IDX(chn)] += ret;
3821 }
3822
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003823 lua_pushinteger(L, ret);
3824 return 1;
3825}
3826
3827/* Inserts a given amount of input data at the given offset by a string
Aurelien DARRAGONafb7daf2022-10-04 12:16:05 +02003828 * content. By default the string is appended in front of input data. It
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003829 * returns the length of the written string, or -1 if the channel is closed or
3830 * if the buffer size is too little for the data.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003831 *
3832 * For a filter, the context is updated on success.
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003833 */
3834__LJMP static int hlua_channel_insert_data(lua_State *L)
3835{
3836 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003837 struct filter *filter;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003838 const char *str;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003839 size_t sz, input, output;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003840 int ret, offset;
3841
3842 if (lua_gettop(L) < 2 || lua_gettop(L) > 3)
3843 WILL_LJMP(luaL_error(L, "'insert' expects at least 1 argument and at most 2 arguments"));
3844 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3845 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003846
3847 output = co_data(chn);
3848 input = ci_data(chn);
3849
3850 filter = hlua_channel_filter(L, 1, chn, &output, &input);
3851 if (filter && !hlua_filter_from_payload(filter))
3852 WILL_LJMP(lua_error(L));
3853
Aurelien DARRAGONafb7daf2022-10-04 12:16:05 +02003854 offset = output;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003855 if (lua_gettop(L) > 2) {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003856 offset = MAY_LJMP(luaL_checkinteger(L, 3));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003857 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02003858 offset = MAX(0, (int)input + offset);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003859 offset += output;
Aurelien DARRAGONafb7daf2022-10-04 12:16:05 +02003860 if (offset > output + input) {
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003861 lua_pushfstring(L, "offset out of range.");
3862 WILL_LJMP(lua_error(L));
3863 }
3864 }
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003865 if (IS_HTX_STRM(chn_strm(chn))) {
3866 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3867 WILL_LJMP(lua_error(L));
3868 }
3869
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003870 ret = _hlua_channel_insert(chn, L, ist2(str, sz), offset);
3871 if (ret > 0 && filter) {
3872 struct hlua_flt_ctx *flt_ctx = filter->ctx;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003873
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003874 flt_update_offsets(filter, chn, ret);
3875 flt_ctx->cur_len[CHN_IDX(chn)] += ret;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003876 }
3877
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003878 lua_pushinteger(L, ret);
3879 return 1;
3880}
3881/* Replaces a given amount of input data at the given offset by a string
3882 * content. By default all remaining data are removed (offset = 0 and len =
3883 * -1). It returns the length of the written string, or -1 if the channel is
3884 * closed or if the buffer size is too little for the data.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003885 *
3886 * For a filter, the context is updated on success.
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003887 */
3888__LJMP static int hlua_channel_set_data(lua_State *L)
3889{
3890 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003891 struct filter *filter;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003892 const char *str;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003893 size_t sz, input, output;
3894 int ret, offset, len;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003895
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003896 if (lua_gettop(L) < 2 || lua_gettop(L) > 4)
3897 WILL_LJMP(luaL_error(L, "'set' expects at least 1 argument and at most 3 arguments"));
3898 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3899 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003900
Christopher Faulet1bb6afa2021-03-08 17:57:53 +01003901 if (IS_HTX_STRM(chn_strm(chn))) {
Thierry Fournier77016da2020-08-15 14:35:51 +02003902 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
Christopher Faulet3f829a42018-12-13 21:56:45 +01003903 WILL_LJMP(lua_error(L));
Thierry Fournier77016da2020-08-15 14:35:51 +02003904 }
Christopher Faulet3f829a42018-12-13 21:56:45 +01003905
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003906 output = co_data(chn);
3907 input = ci_data(chn);
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003908
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003909 filter = hlua_channel_filter(L, 1, chn, &output, &input);
3910 if (filter && !hlua_filter_from_payload(filter))
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003911 WILL_LJMP(lua_error(L));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003912
3913 offset = output;
3914 if (lua_gettop(L) > 2) {
3915 offset = MAY_LJMP(luaL_checkinteger(L, 3));
3916 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02003917 offset = MAX(0, (int)input + offset);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003918 offset += output;
3919 if (offset < output || offset > input + output) {
3920 lua_pushfstring(L, "offset out of range.");
3921 WILL_LJMP(lua_error(L));
3922 }
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003923 }
3924
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003925 len = output + input - offset;
3926 if (lua_gettop(L) == 4) {
3927 len = MAY_LJMP(luaL_checkinteger(L, 4));
3928 if (!len)
3929 goto set;
3930 if (len == -1)
3931 len = output + input - offset;
3932 if (len < 0 || offset + len > output + input) {
3933 lua_pushfstring(L, "length out of range.");
3934 WILL_LJMP(lua_error(L));
3935 }
3936 }
3937
3938 set:
Christopher Faulet23976d92021-08-06 09:59:49 +02003939 /* Be sure we can copied the string once input data will be removed. */
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003940 if (sz > c_room(chn) + len)
Christopher Faulet23976d92021-08-06 09:59:49 +02003941 lua_pushinteger(L, -1);
3942 else {
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003943 _hlua_channel_delete(chn, offset, len);
3944 ret = _hlua_channel_insert(chn, L, ist2(str, sz), offset);
3945 if (filter) {
3946 struct hlua_flt_ctx *flt_ctx = filter->ctx;
3947
3948 len -= (ret > 0 ? ret : 0);
3949 flt_update_offsets(filter, chn, -len);
3950 flt_ctx->cur_len[CHN_IDX(chn)] -= len;
3951 }
3952
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003953 lua_pushinteger(L, ret);
Christopher Faulet23976d92021-08-06 09:59:49 +02003954 }
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003955 return 1;
3956}
3957
3958/* Removes a given amount of input data at the given offset. By default all
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003959 * input data are removed (offset = 0 and len = -1). It returns the amount of
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003960 * the removed data.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003961 *
3962 * For a filter, the context is updated on success.
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003963 */
3964__LJMP static int hlua_channel_del_data(lua_State *L)
3965{
3966 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003967 struct filter *filter;
3968 size_t input, output;
3969 int offset, len;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003970
3971 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
3972 WILL_LJMP(luaL_error(L, "'remove' expects at most 2 arguments"));
3973 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003974
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003975 if (IS_HTX_STRM(chn_strm(chn))) {
3976 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3977 WILL_LJMP(lua_error(L));
3978 }
3979
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003980 output = co_data(chn);
3981 input = ci_data(chn);
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003982
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003983 filter = hlua_channel_filter(L, 1, chn, &output, &input);
3984 if (filter && !hlua_filter_from_payload(filter))
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003985 WILL_LJMP(lua_error(L));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003986
3987 offset = output;
Boyang Lie0c54352022-05-10 17:47:23 +00003988 if (lua_gettop(L) > 1) {
3989 offset = MAY_LJMP(luaL_checkinteger(L, 2));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003990 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02003991 offset = MAX(0, (int)input + offset);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003992 offset += output;
3993 if (offset < output || offset > input + output) {
3994 lua_pushfstring(L, "offset out of range.");
3995 WILL_LJMP(lua_error(L));
3996 }
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003997 }
3998
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003999 len = output + input - offset;
Boyang Lie0c54352022-05-10 17:47:23 +00004000 if (lua_gettop(L) == 3) {
4001 len = MAY_LJMP(luaL_checkinteger(L, 3));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004002 if (!len)
4003 goto end;
4004 if (len == -1)
4005 len = output + input - offset;
4006 if (len < 0 || offset + len > output + input) {
4007 lua_pushfstring(L, "length out of range.");
4008 WILL_LJMP(lua_error(L));
4009 }
4010 }
4011
4012 _hlua_channel_delete(chn, offset, len);
4013 if (filter) {
4014 struct hlua_flt_ctx *flt_ctx = filter->ctx;
4015
4016 flt_update_offsets(filter, chn, -len);
4017 flt_ctx->cur_len[CHN_IDX(chn)] -= len;
4018 }
4019
4020 end:
Christopher Faulet6a79fc12021-08-06 16:02:36 +02004021 lua_pushinteger(L, len);
Christopher Faulet23976d92021-08-06 09:59:49 +02004022 return 1;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004023}
4024
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004025/* Append data in the output side of the buffer. This data is immediately
4026 * sent. The function returns the amount of data written. If the buffer
4027 * cannot contain the data, the function yields. The function returns -1
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004028 * if the channel is closed.
4029 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01004030__LJMP static int hlua_channel_send_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004031{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02004032 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004033 struct filter *filter;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02004034 const char *str;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004035 size_t offset, len, sz;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02004036 int l, ret;
Thierry Fournier4234dbd2020-11-28 13:18:23 +01004037 struct hlua *hlua;
4038
4039 /* Get hlua struct, or NULL if we execute from main lua state */
4040 hlua = hlua_gethlua(L);
4041 if (!hlua) {
4042 lua_pushnil(L);
4043 return 1;
4044 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004045
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02004046 chn = MAY_LJMP(hlua_checkchannel(L, 1));
4047 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
4048 l = MAY_LJMP(luaL_checkinteger(L, 3));
Christopher Faulet3f829a42018-12-13 21:56:45 +01004049
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004050 offset = co_data(chn);
4051 len = ci_data(chn);
4052
4053 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
4054 if (filter && !hlua_filter_from_payload(filter))
4055 WILL_LJMP(lua_error(L));
4056
4057
Willy Tarreau47860ed2015-03-10 14:07:50 +01004058 if (unlikely(channel_output_closed(chn))) {
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004059 lua_pushinteger(L, -1);
4060 return 1;
4061 }
4062
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02004063 len = c_room(chn);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004064 if (len > sz -l) {
4065 if (filter) {
4066 lua_pushinteger(L, -1);
4067 return 1;
4068 }
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02004069 len = sz - l;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004070 }
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01004071
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004072 ret = _hlua_channel_insert(chn, L, ist2(str, len), offset);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02004073 if (ret == -1) {
4074 lua_pop(L, 1);
4075 lua_pushinteger(L, -1);
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01004076 return 1;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02004077 }
4078 if (ret) {
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004079 if (filter) {
4080 struct hlua_flt_ctx *flt_ctx = filter->ctx;
4081
4082
4083 flt_update_offsets(filter, chn, ret);
4084 FLT_OFF(filter, chn) += ret;
4085 flt_ctx->cur_off[CHN_IDX(chn)] += ret;
4086 }
4087 else
4088 c_adv(chn, ret);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004089
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02004090 l += ret;
4091 lua_pop(L, 1);
4092 lua_pushinteger(L, l);
4093 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004094
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02004095 if (l < sz) {
4096 /* Yield only if the channel's output is not empty.
4097 * Otherwise it means we cannot add more data. */
4098 if (co_data(chn) == 0 || HLUA_CANT_YIELD(hlua_gethlua(L)))
Christopher Faulet2e60aa42021-08-05 11:58:37 +02004099 return 1;
4100
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01004101 /* If we are waiting for space in the response buffer, we
4102 * must set the flag WAKERESWR. This flag required the task
4103 * wake up if any activity is detected on the response buffer.
4104 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01004105 if (chn->flags & CF_ISRESP)
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01004106 HLUA_SET_WAKERESWR(hlua);
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01004107 else
4108 HLUA_SET_WAKEREQWR(hlua);
Willy Tarreau9635e032018-10-16 17:52:55 +02004109 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01004110 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004111
4112 return 1;
4113}
4114
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05004115/* Just a wrapper of "_hlua_channel_send". This wrapper permits
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004116 * yield the LUA process, and resume it without checking the
4117 * input arguments.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004118 *
4119 * This function cannot be called from a filter.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004120 */
4121__LJMP static int hlua_channel_send(lua_State *L)
4122{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02004123 struct channel *chn;
4124
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004125 MAY_LJMP(check_args(L, 2, "send"));
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02004126 chn = MAY_LJMP(hlua_checkchannel(L, 1));
4127 if (IS_HTX_STRM(chn_strm(chn))) {
4128 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
4129 WILL_LJMP(lua_error(L));
4130 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004131 lua_pushinteger(L, 0);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01004132 return MAY_LJMP(hlua_channel_send_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004133}
4134
4135/* This function forward and amount of butes. The data pass from
4136 * the input side of the buffer to the output side, and can be
4137 * forwarded. This function never fails.
4138 *
4139 * The Lua function takes an amount of bytes to be forwarded in
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05004140 * input. It returns the number of bytes forwarded.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004141 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01004142__LJMP static int hlua_channel_forward_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004143{
Willy Tarreau47860ed2015-03-10 14:07:50 +01004144 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004145 struct filter *filter;
4146 size_t offset, len, fwd;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02004147 int l, max;
Thierry Fournier4234dbd2020-11-28 13:18:23 +01004148 struct hlua *hlua;
4149
4150 /* Get hlua struct, or NULL if we execute from main lua state */
4151 hlua = hlua_gethlua(L);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02004152 if (!hlua) {
4153 lua_pushnil(L);
Thierry Fournier4234dbd2020-11-28 13:18:23 +01004154 return 1;
Thierry Fournier77016da2020-08-15 14:35:51 +02004155 }
Christopher Faulet3f829a42018-12-13 21:56:45 +01004156
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02004157 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004158 fwd = MAY_LJMP(luaL_checkinteger(L, 2));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004159 l = MAY_LJMP(luaL_checkinteger(L, -1));
4160
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004161 offset = co_data(chn);
4162 len = ci_data(chn);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02004163
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004164 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
4165 if (filter && !hlua_filter_from_payload(filter))
4166 WILL_LJMP(lua_error(L));
4167
4168 max = fwd - l;
4169 if (max > len)
4170 max = len;
4171
4172 if (filter) {
4173 struct hlua_flt_ctx *flt_ctx = filter->ctx;
4174
4175 FLT_OFF(filter, chn) += max;
4176 flt_ctx->cur_off[CHN_IDX(chn)] += max;
4177 flt_ctx->cur_len[CHN_IDX(chn)] -= max;
4178 }
4179 else
4180 channel_forward(chn, max);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004181
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02004182 l += max;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004183 lua_pop(L, 1);
4184 lua_pushinteger(L, l);
4185
4186 /* Check if it miss bytes to forward. */
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004187 if (l < fwd) {
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004188 /* The the input channel or the output channel are closed, we
4189 * must return the amount of data forwarded.
4190 */
Christopher Faulet2e60aa42021-08-05 11:58:37 +02004191 if (channel_input_closed(chn) || channel_output_closed(chn) || HLUA_CANT_YIELD(hlua_gethlua(L)))
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004192 return 1;
4193
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01004194 /* If we are waiting for space data in the response buffer, we
4195 * must set the flag WAKERESWR. This flag required the task
4196 * wake up if any activity is detected on the response buffer.
4197 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01004198 if (chn->flags & CF_ISRESP)
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01004199 HLUA_SET_WAKERESWR(hlua);
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01004200 else
4201 HLUA_SET_WAKEREQWR(hlua);
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01004202
Ilya Shipitsin4a689da2022-10-29 09:34:32 +05004203 /* Otherwise, we can yield waiting for new data in the input side. */
Willy Tarreau9635e032018-10-16 17:52:55 +02004204 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_forward_yield, TICK_ETERNITY, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004205 }
4206
4207 return 1;
4208}
4209
4210/* Just check the input and prepare the stack for the previous
4211 * function "hlua_channel_forward_yield"
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004212 *
4213 * This function cannot be called from a filter.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004214 */
4215__LJMP static int hlua_channel_forward(lua_State *L)
4216{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02004217 struct channel *chn;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004218
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02004219 MAY_LJMP(check_args(L, 2, "forward"));
4220 chn = MAY_LJMP(hlua_checkchannel(L, 1));
4221 if (IS_HTX_STRM(chn_strm(chn))) {
4222 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
4223 WILL_LJMP(lua_error(L));
4224 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004225 lua_pushinteger(L, 0);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01004226 return MAY_LJMP(hlua_channel_forward_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004227}
4228
4229/* Just returns the number of bytes available in the input
4230 * side of the buffer. This function never fails.
4231 */
4232__LJMP static int hlua_channel_get_in_len(lua_State *L)
4233{
Willy Tarreau47860ed2015-03-10 14:07:50 +01004234 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004235 struct filter *filter;
4236 size_t output, input;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004237
Christopher Faulet6a79fc12021-08-06 16:02:36 +02004238 MAY_LJMP(check_args(L, 1, "input"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004239 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004240
4241 output = co_data(chn);
4242 input = ci_data(chn);
4243 filter = hlua_channel_filter(L, 1, chn, &output, &input);
4244 if (filter || !IS_HTX_STRM(chn_strm(chn)))
4245 lua_pushinteger(L, input);
4246 else {
Christopher Fauleta3ceac12018-12-14 13:39:09 +01004247 struct htx *htx = htxbuf(&chn->buf);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004248
Christopher Fauleta3ceac12018-12-14 13:39:09 +01004249 lua_pushinteger(L, htx->data - co_data(chn));
4250 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004251 return 1;
4252}
4253
Thierry FOURNIER / OZON.IO65192f32016-11-07 15:28:40 +01004254/* Returns true if the channel is full. */
4255__LJMP static int hlua_channel_is_full(lua_State *L)
4256{
4257 struct channel *chn;
Thierry FOURNIER / OZON.IO65192f32016-11-07 15:28:40 +01004258
4259 MAY_LJMP(check_args(L, 1, "is_full"));
4260 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Faulet0ec740e2020-02-26 11:59:19 +01004261 /* ignore the reserve, we are not on a producer side (ie in an
4262 * applet).
4263 */
4264 lua_pushboolean(L, channel_full(chn, 0));
Thierry FOURNIER / OZON.IO65192f32016-11-07 15:28:40 +01004265 return 1;
4266}
4267
Christopher Faulet6a79fc12021-08-06 16:02:36 +02004268/* Returns true if the channel may still receive data. */
4269__LJMP static int hlua_channel_may_recv(lua_State *L)
4270{
4271 struct channel *chn;
4272
4273 MAY_LJMP(check_args(L, 1, "may_recv"));
4274 chn = MAY_LJMP(hlua_checkchannel(L, 1));
4275 lua_pushboolean(L, (!channel_input_closed(chn) && channel_may_recv(chn)));
4276 return 1;
4277}
4278
Christopher Faulet2ac9ba22020-02-25 10:15:50 +01004279/* Returns true if the channel is the response channel. */
4280__LJMP static int hlua_channel_is_resp(lua_State *L)
4281{
4282 struct channel *chn;
4283
4284 MAY_LJMP(check_args(L, 1, "is_resp"));
4285 chn = MAY_LJMP(hlua_checkchannel(L, 1));
4286
4287 lua_pushboolean(L, !!(chn->flags & CF_ISRESP));
4288 return 1;
4289}
4290
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004291/* Just returns the number of bytes available in the output
4292 * side of the buffer. This function never fails.
4293 */
4294__LJMP static int hlua_channel_get_out_len(lua_State *L)
4295{
Willy Tarreau47860ed2015-03-10 14:07:50 +01004296 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004297 size_t output, input;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004298
Christopher Faulet6a79fc12021-08-06 16:02:36 +02004299 MAY_LJMP(check_args(L, 1, "output"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004300 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004301
4302 output = co_data(chn);
4303 input = ci_data(chn);
4304 hlua_channel_filter(L, 1, chn, &output, &input);
4305
4306 lua_pushinteger(L, output);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004307 return 1;
4308}
4309
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004310/*
4311 *
4312 *
4313 * Class Fetches
4314 *
4315 *
4316 */
4317
4318/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02004319 * a class stream, otherwise it throws an error.
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004320 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004321__LJMP static struct hlua_smp *hlua_checkfetches(lua_State *L, int ud)
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004322{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004323 return MAY_LJMP(hlua_checkudata(L, ud, class_fetches_ref));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004324}
4325
4326/* This function creates and push in the stack a fetch object according
4327 * with a current TXN.
4328 */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004329static int hlua_fetches_new(lua_State *L, struct hlua_txn *txn, unsigned int flags)
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004330{
Willy Tarreau7073c472015-04-06 11:15:40 +02004331 struct hlua_smp *hsmp;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004332
4333 /* Check stack size. */
4334 if (!lua_checkstack(L, 3))
4335 return 0;
4336
4337 /* Create the object: obj[0] = userdata.
4338 * Note that the base of the Fetches object is the
4339 * transaction object.
4340 */
4341 lua_newtable(L);
Willy Tarreau7073c472015-04-06 11:15:40 +02004342 hsmp = lua_newuserdata(L, sizeof(*hsmp));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004343 lua_rawseti(L, -2, 0);
4344
Willy Tarreau7073c472015-04-06 11:15:40 +02004345 hsmp->s = txn->s;
4346 hsmp->p = txn->p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01004347 hsmp->dir = txn->dir;
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004348 hsmp->flags = flags;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004349
4350 /* Pop a class sesison metatable and affect it to the userdata. */
4351 lua_rawgeti(L, LUA_REGISTRYINDEX, class_fetches_ref);
4352 lua_setmetatable(L, -2);
4353
4354 return 1;
4355}
4356
4357/* This function is an LUA binding. It is called with each sample-fetch.
4358 * It uses closure argument to store the associated sample-fetch. It
4359 * returns only one argument or throws an error. An error is thrown
4360 * only if an error is encountered during the argument parsing. If
4361 * the "sample-fetch" function fails, nil is returned.
4362 */
4363__LJMP static int hlua_run_sample_fetch(lua_State *L)
4364{
Willy Tarreaub2ccb562015-04-06 11:11:15 +02004365 struct hlua_smp *hsmp;
Willy Tarreau2ec22742015-03-10 14:27:20 +01004366 struct sample_fetch *f;
Frédéric Lécaillef874a832018-06-15 13:56:04 +02004367 struct arg args[ARGM_NBARGS + 1] = {{0}};
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004368 int i;
4369 struct sample smp;
4370
4371 /* Get closure arguments. */
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004372 f = lua_touserdata(L, lua_upvalueindex(1));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004373
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004374 /* Get traditional arguments. */
Willy Tarreaub2ccb562015-04-06 11:11:15 +02004375 hsmp = MAY_LJMP(hlua_checkfetches(L, 1));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004376
Thierry FOURNIERca988662015-12-20 18:43:03 +01004377 /* Check execution authorization. */
4378 if (f->use & SMP_USE_HTTP_ANY &&
4379 !(hsmp->flags & HLUA_F_MAY_USE_HTTP)) {
4380 lua_pushfstring(L, "the sample-fetch '%s' needs an HTTP parser which "
4381 "is not available in Lua services", f->kw);
4382 WILL_LJMP(lua_error(L));
4383 }
4384
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004385 /* Get extra arguments. */
4386 for (i = 0; i < lua_gettop(L) - 1; i++) {
4387 if (i >= ARGM_NBARGS)
4388 break;
4389 hlua_lua2arg(L, i + 2, &args[i]);
4390 }
4391 args[i].type = ARGT_STOP;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004392 args[i].data.str.area = NULL;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004393
4394 /* Check arguments. */
Willy Tarreaub2ccb562015-04-06 11:11:15 +02004395 MAY_LJMP(hlua_lua2arg_check(L, 2, args, f->arg_mask, hsmp->p));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004396
4397 /* Run the special args checker. */
Willy Tarreau2ec22742015-03-10 14:27:20 +01004398 if (f->val_args && !f->val_args(args, NULL)) {
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004399 lua_pushfstring(L, "error in arguments");
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004400 goto error;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004401 }
4402
4403 /* Initialise the sample. */
4404 memset(&smp, 0, sizeof(smp));
4405
4406 /* Run the sample fetch process. */
Willy Tarreau1777ea62016-03-10 16:15:46 +01004407 smp_set_owner(&smp, hsmp->p, hsmp->s->sess, hsmp->s, hsmp->dir & SMP_OPT_DIR);
Thierry FOURNIER0786d052015-05-11 15:42:45 +02004408 if (!f->process(args, &smp, f->kw, f->private)) {
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004409 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004410 lua_pushstring(L, "");
4411 else
4412 lua_pushnil(L);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004413 goto end;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004414 }
4415
4416 /* Convert the returned sample in lua value. */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004417 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004418 hlua_smp2lua_str(L, &smp);
4419 else
4420 hlua_smp2lua(L, &smp);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004421
4422 end:
Willy Tarreauee0d7272021-07-16 10:26:56 +02004423 free_args(args);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004424 return 1;
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004425
4426 error:
Willy Tarreauee0d7272021-07-16 10:26:56 +02004427 free_args(args);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004428 WILL_LJMP(lua_error(L));
4429 return 0; /* Never reached */
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004430}
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004431
4432/*
4433 *
4434 *
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004435 * Class Converters
4436 *
4437 *
4438 */
4439
4440/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02004441 * a class stream, otherwise it throws an error.
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004442 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004443__LJMP static struct hlua_smp *hlua_checkconverters(lua_State *L, int ud)
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004444{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004445 return MAY_LJMP(hlua_checkudata(L, ud, class_converters_ref));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004446}
4447
4448/* This function creates and push in the stack a Converters object
4449 * according with a current TXN.
4450 */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004451static int hlua_converters_new(lua_State *L, struct hlua_txn *txn, unsigned int flags)
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004452{
Willy Tarreau7073c472015-04-06 11:15:40 +02004453 struct hlua_smp *hsmp;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004454
4455 /* Check stack size. */
4456 if (!lua_checkstack(L, 3))
4457 return 0;
4458
4459 /* Create the object: obj[0] = userdata.
4460 * Note that the base of the Converters object is the
4461 * same than the TXN object.
4462 */
4463 lua_newtable(L);
Willy Tarreau7073c472015-04-06 11:15:40 +02004464 hsmp = lua_newuserdata(L, sizeof(*hsmp));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004465 lua_rawseti(L, -2, 0);
4466
Willy Tarreau7073c472015-04-06 11:15:40 +02004467 hsmp->s = txn->s;
4468 hsmp->p = txn->p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01004469 hsmp->dir = txn->dir;
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004470 hsmp->flags = flags;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004471
Willy Tarreau87b09662015-04-03 00:22:06 +02004472 /* Pop a class stream metatable and affect it to the table. */
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004473 lua_rawgeti(L, LUA_REGISTRYINDEX, class_converters_ref);
4474 lua_setmetatable(L, -2);
4475
4476 return 1;
4477}
4478
4479/* This function is an LUA binding. It is called with each converter.
4480 * It uses closure argument to store the associated converter. It
4481 * returns only one argument or throws an error. An error is thrown
4482 * only if an error is encountered during the argument parsing. If
4483 * the converter function function fails, nil is returned.
4484 */
4485__LJMP static int hlua_run_sample_conv(lua_State *L)
4486{
Willy Tarreauda5f1082015-04-06 11:17:13 +02004487 struct hlua_smp *hsmp;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004488 struct sample_conv *conv;
Frédéric Lécaillef874a832018-06-15 13:56:04 +02004489 struct arg args[ARGM_NBARGS + 1] = {{0}};
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004490 int i;
4491 struct sample smp;
4492
4493 /* Get closure arguments. */
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004494 conv = lua_touserdata(L, lua_upvalueindex(1));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004495
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004496 /* Get traditional arguments. */
Willy Tarreauda5f1082015-04-06 11:17:13 +02004497 hsmp = MAY_LJMP(hlua_checkconverters(L, 1));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004498
4499 /* Get extra arguments. */
4500 for (i = 0; i < lua_gettop(L) - 2; i++) {
4501 if (i >= ARGM_NBARGS)
4502 break;
4503 hlua_lua2arg(L, i + 3, &args[i]);
4504 }
4505 args[i].type = ARGT_STOP;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004506 args[i].data.str.area = NULL;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004507
4508 /* Check arguments. */
Willy Tarreauda5f1082015-04-06 11:17:13 +02004509 MAY_LJMP(hlua_lua2arg_check(L, 3, args, conv->arg_mask, hsmp->p));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004510
4511 /* Run the special args checker. */
4512 if (conv->val_args && !conv->val_args(args, conv, "", 0, NULL)) {
4513 hlua_pusherror(L, "error in arguments");
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004514 goto error;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004515 }
4516
4517 /* Initialise the sample. */
Amaury Denoyellebc0af6a2020-10-29 17:21:20 +01004518 memset(&smp, 0, sizeof(smp));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004519 if (!hlua_lua2smp(L, 2, &smp)) {
4520 hlua_pusherror(L, "error in the input argument");
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004521 goto error;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004522 }
4523
Willy Tarreau1777ea62016-03-10 16:15:46 +01004524 smp_set_owner(&smp, hsmp->p, hsmp->s->sess, hsmp->s, hsmp->dir & SMP_OPT_DIR);
4525
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004526 /* Apply expected cast. */
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02004527 if (!sample_casts[smp.data.type][conv->in_type]) {
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004528 hlua_pusherror(L, "invalid input argument: cannot cast '%s' to '%s'",
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02004529 smp_to_type[smp.data.type], smp_to_type[conv->in_type]);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004530 goto error;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004531 }
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02004532 if (sample_casts[smp.data.type][conv->in_type] != c_none &&
4533 !sample_casts[smp.data.type][conv->in_type](&smp)) {
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004534 hlua_pusherror(L, "error during the input argument casting");
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004535 goto error;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004536 }
4537
4538 /* Run the sample conversion process. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02004539 if (!conv->process(args, &smp, conv->private)) {
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004540 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004541 lua_pushstring(L, "");
4542 else
Willy Tarreaua678b432015-08-28 10:14:59 +02004543 lua_pushnil(L);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004544 goto end;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004545 }
4546
4547 /* Convert the returned sample in lua value. */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004548 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004549 hlua_smp2lua_str(L, &smp);
4550 else
4551 hlua_smp2lua(L, &smp);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004552 end:
Willy Tarreauee0d7272021-07-16 10:26:56 +02004553 free_args(args);
Willy Tarreaua678b432015-08-28 10:14:59 +02004554 return 1;
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004555
4556 error:
Willy Tarreauee0d7272021-07-16 10:26:56 +02004557 free_args(args);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004558 WILL_LJMP(lua_error(L));
4559 return 0; /* Never reached */
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004560}
4561
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004562/*
4563 *
4564 *
4565 * Class AppletTCP
4566 *
4567 *
4568 */
4569
4570/* Returns a struct hlua_txn if the stack entry "ud" is
4571 * a class stream, otherwise it throws an error.
4572 */
4573__LJMP static struct hlua_appctx *hlua_checkapplet_tcp(lua_State *L, int ud)
4574{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004575 return MAY_LJMP(hlua_checkudata(L, ud, class_applet_tcp_ref));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004576}
4577
4578/* This function creates and push in the stack an Applet object
4579 * according with a current TXN.
4580 */
4581static int hlua_applet_tcp_new(lua_State *L, struct appctx *ctx)
4582{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004583 struct hlua_appctx *luactx;
Willy Tarreau0698c802022-05-11 14:09:57 +02004584 struct stream *s = appctx_strm(ctx);
Christopher Faulet2da02ae2022-02-24 13:45:27 +01004585 struct proxy *p;
4586
4587 ALREADY_CHECKED(s);
4588 p = s->be;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004589
4590 /* Check stack size. */
4591 if (!lua_checkstack(L, 3))
4592 return 0;
4593
4594 /* Create the object: obj[0] = userdata.
4595 * Note that the base of the Converters object is the
4596 * same than the TXN object.
4597 */
4598 lua_newtable(L);
Willy Tarreau7e702d12021-04-28 17:59:21 +02004599 luactx = lua_newuserdata(L, sizeof(*luactx));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004600 lua_rawseti(L, -2, 0);
Willy Tarreau7e702d12021-04-28 17:59:21 +02004601 luactx->appctx = ctx;
4602 luactx->htxn.s = s;
4603 luactx->htxn.p = p;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004604
4605 /* Create the "f" field that contains a list of fetches. */
4606 lua_pushstring(L, "f");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004607 if (!hlua_fetches_new(L, &luactx->htxn, 0))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004608 return 0;
4609 lua_settable(L, -3);
4610
4611 /* Create the "sf" field that contains a list of stringsafe fetches. */
4612 lua_pushstring(L, "sf");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004613 if (!hlua_fetches_new(L, &luactx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004614 return 0;
4615 lua_settable(L, -3);
4616
4617 /* Create the "c" field that contains a list of converters. */
4618 lua_pushstring(L, "c");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004619 if (!hlua_converters_new(L, &luactx->htxn, 0))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004620 return 0;
4621 lua_settable(L, -3);
4622
4623 /* Create the "sc" field that contains a list of stringsafe converters. */
4624 lua_pushstring(L, "sc");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004625 if (!hlua_converters_new(L, &luactx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004626 return 0;
4627 lua_settable(L, -3);
4628
4629 /* Pop a class stream metatable and affect it to the table. */
4630 lua_rawgeti(L, LUA_REGISTRYINDEX, class_applet_tcp_ref);
4631 lua_setmetatable(L, -2);
4632
4633 return 1;
4634}
4635
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004636__LJMP static int hlua_applet_tcp_set_var(lua_State *L)
4637{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004638 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004639 struct stream *s;
4640 const char *name;
4641 size_t len;
4642 struct sample smp;
4643
Tim Duesterhus4e172c92020-05-19 13:49:42 +02004644 if (lua_gettop(L) < 3 || lua_gettop(L) > 4)
4645 WILL_LJMP(luaL_error(L, "'set_var' needs between 3 and 4 arguments"));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004646
4647 /* It is useles to retrieve the stream, but this function
4648 * runs only in a stream context.
4649 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004650 luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004651 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02004652 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004653
4654 /* Converts the third argument in a sample. */
Amaury Denoyellebc0af6a2020-10-29 17:21:20 +01004655 memset(&smp, 0, sizeof(smp));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004656 hlua_lua2smp(L, 3, &smp);
4657
4658 /* Store the sample in a variable. */
4659 smp_set_owner(&smp, s->be, s->sess, s, 0);
Tim Duesterhus4e172c92020-05-19 13:49:42 +02004660
4661 if (lua_gettop(L) == 4 && lua_toboolean(L, 4))
4662 lua_pushboolean(L, vars_set_by_name_ifexist(name, len, &smp) != 0);
4663 else
4664 lua_pushboolean(L, vars_set_by_name(name, len, &smp) != 0);
4665
Tim Duesterhus84ebc132020-05-19 13:49:41 +02004666 return 1;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004667}
4668
4669__LJMP static int hlua_applet_tcp_unset_var(lua_State *L)
4670{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004671 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004672 struct stream *s;
4673 const char *name;
4674 size_t len;
4675 struct sample smp;
4676
4677 MAY_LJMP(check_args(L, 2, "unset_var"));
4678
4679 /* It is useles to retrieve the stream, but this function
4680 * runs only in a stream context.
4681 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004682 luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004683 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02004684 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004685
4686 /* Unset the variable. */
4687 smp_set_owner(&smp, s->be, s->sess, s, 0);
Tim Duesterhus84ebc132020-05-19 13:49:41 +02004688 lua_pushboolean(L, vars_unset_by_name_ifexist(name, len, &smp) != 0);
4689 return 1;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004690}
4691
4692__LJMP static int hlua_applet_tcp_get_var(lua_State *L)
4693{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004694 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004695 struct stream *s;
4696 const char *name;
4697 size_t len;
4698 struct sample smp;
4699
4700 MAY_LJMP(check_args(L, 2, "get_var"));
4701
4702 /* It is useles to retrieve the stream, but this function
4703 * runs only in a stream context.
4704 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004705 luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004706 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02004707 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004708
4709 smp_set_owner(&smp, s->be, s->sess, s, 0);
Willy Tarreaue352b9d2021-09-03 11:52:38 +02004710 if (!vars_get_by_name(name, len, &smp, NULL)) {
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004711 lua_pushnil(L);
4712 return 1;
4713 }
4714
4715 return hlua_smp2lua(L, &smp);
4716}
4717
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004718__LJMP static int hlua_applet_tcp_set_priv(lua_State *L)
4719{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004720 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
4721 struct stream *s = luactx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01004722 struct hlua *hlua;
4723
4724 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01004725 if (!s->hlua)
4726 return 0;
4727 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004728
4729 MAY_LJMP(check_args(L, 2, "set_priv"));
4730
4731 /* Remove previous value. */
Thierry FOURNIERe068b602017-04-26 13:27:05 +02004732 luaL_unref(L, LUA_REGISTRYINDEX, hlua->Mref);
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004733
4734 /* Get and store new value. */
4735 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
4736 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
4737
4738 return 0;
4739}
4740
4741__LJMP static int hlua_applet_tcp_get_priv(lua_State *L)
4742{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004743 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
4744 struct stream *s = luactx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01004745 struct hlua *hlua;
4746
4747 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01004748 if (!s->hlua) {
4749 lua_pushnil(L);
4750 return 1;
4751 }
4752 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004753
4754 /* Push configuration index in the stack. */
4755 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
4756
4757 return 1;
4758}
4759
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004760/* If expected data not yet available, it returns a yield. This function
4761 * consumes the data in the buffer. It returns a string containing the
4762 * data. This string can be empty.
4763 */
4764__LJMP static int hlua_applet_tcp_getline_yield(lua_State *L, int status, lua_KContext ctx)
4765{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004766 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Willy Tarreauc12b3212022-05-27 11:08:15 +02004767 struct stconn *sc = appctx_sc(luactx->appctx);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004768 int ret;
Willy Tarreau206ba832018-06-14 15:27:31 +02004769 const char *blk1;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004770 size_t len1;
Willy Tarreau206ba832018-06-14 15:27:31 +02004771 const char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004772 size_t len2;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004773
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004774 /* Read the maximum amount of data available. */
Willy Tarreau3e7be362022-05-27 10:35:27 +02004775 ret = co_getline_nc(sc_oc(sc), &blk1, &len1, &blk2, &len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004776
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004777 /* Data not yet available. return yield. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004778 if (ret == 0) {
Willy Tarreau90e8b452022-05-25 18:21:43 +02004779 applet_need_more_data(luactx->appctx);
Willy Tarreau9635e032018-10-16 17:52:55 +02004780 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_getline_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004781 }
4782
4783 /* End of data: commit the total strings and return. */
4784 if (ret < 0) {
Willy Tarreau7e702d12021-04-28 17:59:21 +02004785 luaL_pushresult(&luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004786 return 1;
4787 }
4788
4789 /* Ensure that the block 2 length is usable. */
4790 if (ret == 1)
4791 len2 = 0;
4792
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -07004793 /* don't check the max length read and don't check. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004794 luaL_addlstring(&luactx->b, blk1, len1);
4795 luaL_addlstring(&luactx->b, blk2, len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004796
4797 /* Consume input channel output buffer data. */
Willy Tarreau3e7be362022-05-27 10:35:27 +02004798 co_skip(sc_oc(sc), len1 + len2);
Willy Tarreau7e702d12021-04-28 17:59:21 +02004799 luaL_pushresult(&luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004800 return 1;
4801}
4802
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004803/* Check arguments for the function "hlua_channel_get_yield". */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004804__LJMP static int hlua_applet_tcp_getline(lua_State *L)
4805{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004806 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004807
4808 /* Initialise the string catenation. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004809 luaL_buffinit(L, &luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004810
4811 return MAY_LJMP(hlua_applet_tcp_getline_yield(L, 0, 0));
4812}
4813
4814/* If expected data not yet available, it returns a yield. This function
4815 * consumes the data in the buffer. It returns a string containing the
4816 * data. This string can be empty.
4817 */
4818__LJMP static int hlua_applet_tcp_recv_yield(lua_State *L, int status, lua_KContext ctx)
4819{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004820 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Willy Tarreauc12b3212022-05-27 11:08:15 +02004821 struct stconn *sc = appctx_sc(luactx->appctx);
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004822 size_t len = MAY_LJMP(luaL_checkinteger(L, 2));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004823 int ret;
Willy Tarreau206ba832018-06-14 15:27:31 +02004824 const char *blk1;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004825 size_t len1;
Willy Tarreau206ba832018-06-14 15:27:31 +02004826 const char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004827 size_t len2;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004828
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004829 /* Read the maximum amount of data available. */
Willy Tarreau3e7be362022-05-27 10:35:27 +02004830 ret = co_getblk_nc(sc_oc(sc), &blk1, &len1, &blk2, &len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004831
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004832 /* Data not yet available. return yield. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004833 if (ret == 0) {
Willy Tarreau90e8b452022-05-25 18:21:43 +02004834 applet_need_more_data(luactx->appctx);
Willy Tarreau9635e032018-10-16 17:52:55 +02004835 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004836 }
4837
4838 /* End of data: commit the total strings and return. */
4839 if (ret < 0) {
Willy Tarreau7e702d12021-04-28 17:59:21 +02004840 luaL_pushresult(&luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004841 return 1;
4842 }
4843
4844 /* Ensure that the block 2 length is usable. */
4845 if (ret == 1)
4846 len2 = 0;
4847
4848 if (len == -1) {
4849
4850 /* If len == -1, catenate all the data avalaile and
4851 * yield because we want to get all the data until
4852 * the end of data stream.
4853 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004854 luaL_addlstring(&luactx->b, blk1, len1);
4855 luaL_addlstring(&luactx->b, blk2, len2);
Willy Tarreau3e7be362022-05-27 10:35:27 +02004856 co_skip(sc_oc(sc), len1 + len2);
Willy Tarreau90e8b452022-05-25 18:21:43 +02004857 applet_need_more_data(luactx->appctx);
Willy Tarreau9635e032018-10-16 17:52:55 +02004858 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004859
4860 } else {
4861
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05004862 /* Copy the first block caping to the length required. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004863 if (len1 > len)
4864 len1 = len;
Willy Tarreau7e702d12021-04-28 17:59:21 +02004865 luaL_addlstring(&luactx->b, blk1, len1);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004866 len -= len1;
4867
4868 /* Copy the second block. */
4869 if (len2 > len)
4870 len2 = len;
Willy Tarreau7e702d12021-04-28 17:59:21 +02004871 luaL_addlstring(&luactx->b, blk2, len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004872 len -= len2;
4873
4874 /* Consume input channel output buffer data. */
Willy Tarreau3e7be362022-05-27 10:35:27 +02004875 co_skip(sc_oc(sc), len1 + len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004876
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004877 /* If there is no other data available, yield waiting for new data. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004878 if (len > 0) {
4879 lua_pushinteger(L, len);
4880 lua_replace(L, 2);
Willy Tarreau90e8b452022-05-25 18:21:43 +02004881 applet_need_more_data(luactx->appctx);
Willy Tarreau9635e032018-10-16 17:52:55 +02004882 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004883 }
4884
4885 /* return the result. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004886 luaL_pushresult(&luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004887 return 1;
4888 }
4889
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004890 /* we never execute this */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004891 hlua_pusherror(L, "Lua: internal error");
4892 WILL_LJMP(lua_error(L));
4893 return 0;
4894}
4895
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004896/* Check arguments for the function "hlua_channel_get_yield". */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004897__LJMP static int hlua_applet_tcp_recv(lua_State *L)
4898{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004899 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004900 int len = -1;
4901
4902 if (lua_gettop(L) > 2)
4903 WILL_LJMP(luaL_error(L, "The 'recv' function requires between 1 and 2 arguments."));
4904 if (lua_gettop(L) >= 2) {
4905 len = MAY_LJMP(luaL_checkinteger(L, 2));
4906 lua_pop(L, 1);
4907 }
4908
4909 /* Confirm or set the required length */
4910 lua_pushinteger(L, len);
4911
4912 /* Initialise the string catenation. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004913 luaL_buffinit(L, &luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004914
4915 return MAY_LJMP(hlua_applet_tcp_recv_yield(L, 0, 0));
4916}
4917
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004918/* Append data in the output side of the buffer. This data is immediately
4919 * sent. The function returns the amount of data written. If the buffer
4920 * cannot contain the data, the function yields. The function returns -1
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004921 * if the channel is closed.
4922 */
4923__LJMP static int hlua_applet_tcp_send_yield(lua_State *L, int status, lua_KContext ctx)
4924{
4925 size_t len;
Willy Tarreau7e702d12021-04-28 17:59:21 +02004926 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004927 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
4928 int l = MAY_LJMP(luaL_checkinteger(L, 3));
Willy Tarreauc12b3212022-05-27 11:08:15 +02004929 struct stconn *sc = appctx_sc(luactx->appctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02004930 struct channel *chn = sc_ic(sc);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004931 int max;
4932
4933 /* Get the max amount of data which can write as input in the channel. */
4934 max = channel_recv_max(chn);
4935 if (max > (len - l))
4936 max = len - l;
4937
4938 /* Copy data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02004939 ci_putblk(chn, str + l, max);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004940
4941 /* update counters. */
4942 l += max;
4943 lua_pop(L, 1);
4944 lua_pushinteger(L, l);
4945
4946 /* If some data is not send, declares the situation to the
4947 * applet, and returns a yield.
4948 */
4949 if (l < len) {
Christopher Faulet7b3d38a2023-05-05 11:28:45 +02004950 sc_need_room(sc, channel_recv_max(chn) + 1);
Willy Tarreau9635e032018-10-16 17:52:55 +02004951 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004952 }
4953
4954 return 1;
4955}
4956
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05004957/* Just a wrapper of "hlua_applet_tcp_send_yield". This wrapper permits
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004958 * yield the LUA process, and resume it without checking the
4959 * input arguments.
4960 */
4961__LJMP static int hlua_applet_tcp_send(lua_State *L)
4962{
4963 MAY_LJMP(check_args(L, 2, "send"));
4964 lua_pushinteger(L, 0);
4965
4966 return MAY_LJMP(hlua_applet_tcp_send_yield(L, 0, 0));
4967}
4968
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004969/*
4970 *
4971 *
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004972 * Class AppletHTTP
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004973 *
4974 *
4975 */
4976
4977/* Returns a struct hlua_txn if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02004978 * a class stream, otherwise it throws an error.
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004979 */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004980__LJMP static struct hlua_appctx *hlua_checkapplet_http(lua_State *L, int ud)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004981{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004982 return MAY_LJMP(hlua_checkudata(L, ud, class_applet_http_ref));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004983}
4984
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004985/* This function creates and push in the stack an Applet object
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004986 * according with a current TXN.
Willy Tarreauaa229cc2022-05-06 14:26:10 +02004987 * It relies on the caller to have already reserved the room in ctx->svcctx
4988 * for the local storage of hlua_http_ctx.
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004989 */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004990static int hlua_applet_http_new(lua_State *L, struct appctx *ctx)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004991{
Willy Tarreauaa229cc2022-05-06 14:26:10 +02004992 struct hlua_http_ctx *http_ctx = ctx->svcctx;
Willy Tarreau7e702d12021-04-28 17:59:21 +02004993 struct hlua_appctx *luactx;
Thierry FOURNIER841475e2015-12-11 17:10:09 +01004994 struct hlua_txn htxn;
Willy Tarreau0698c802022-05-11 14:09:57 +02004995 struct stream *s = appctx_strm(ctx);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004996 struct proxy *px = s->be;
Christopher Fauleta2097962019-07-15 16:25:33 +02004997 struct htx *htx;
4998 struct htx_blk *blk;
4999 struct htx_sl *sl;
5000 struct ist path;
5001 unsigned long long len = 0;
5002 int32_t pos;
Amaury Denoyellec453f952021-07-06 11:40:12 +02005003 struct http_uri_parser parser;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005004
5005 /* Check stack size. */
5006 if (!lua_checkstack(L, 3))
5007 return 0;
5008
5009 /* Create the object: obj[0] = userdata.
5010 * Note that the base of the Converters object is the
5011 * same than the TXN object.
5012 */
5013 lua_newtable(L);
Willy Tarreau7e702d12021-04-28 17:59:21 +02005014 luactx = lua_newuserdata(L, sizeof(*luactx));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005015 lua_rawseti(L, -2, 0);
Willy Tarreau7e702d12021-04-28 17:59:21 +02005016 luactx->appctx = ctx;
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005017 http_ctx->status = 200; /* Default status code returned. */
5018 http_ctx->reason = NULL; /* Use default reason based on status */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005019 luactx->htxn.s = s;
5020 luactx->htxn.p = px;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005021
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005022 /* Create the "f" field that contains a list of fetches. */
5023 lua_pushstring(L, "f");
Willy Tarreau7e702d12021-04-28 17:59:21 +02005024 if (!hlua_fetches_new(L, &luactx->htxn, 0))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005025 return 0;
5026 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005027
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005028 /* Create the "sf" field that contains a list of stringsafe fetches. */
5029 lua_pushstring(L, "sf");
Willy Tarreau7e702d12021-04-28 17:59:21 +02005030 if (!hlua_fetches_new(L, &luactx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005031 return 0;
5032 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005033
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005034 /* Create the "c" field that contains a list of converters. */
5035 lua_pushstring(L, "c");
Willy Tarreau7e702d12021-04-28 17:59:21 +02005036 if (!hlua_converters_new(L, &luactx->htxn, 0))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005037 return 0;
5038 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005039
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005040 /* Create the "sc" field that contains a list of stringsafe converters. */
5041 lua_pushstring(L, "sc");
Willy Tarreau7e702d12021-04-28 17:59:21 +02005042 if (!hlua_converters_new(L, &luactx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005043 return 0;
5044 lua_settable(L, -3);
Willy Tarreaueee5b512015-04-03 23:46:31 +02005045
Christopher Fauleta2097962019-07-15 16:25:33 +02005046 htx = htxbuf(&s->req.buf);
5047 blk = htx_get_first_blk(htx);
Christopher Fauletea009732019-11-18 15:50:25 +01005048 BUG_ON(!blk || htx_get_blk_type(blk) != HTX_BLK_REQ_SL);
Christopher Fauleta2097962019-07-15 16:25:33 +02005049 sl = htx_get_blk_ptr(htx, blk);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005050
Christopher Fauleta2097962019-07-15 16:25:33 +02005051 /* Stores the request method. */
5052 lua_pushstring(L, "method");
5053 lua_pushlstring(L, HTX_SL_REQ_MPTR(sl), HTX_SL_REQ_MLEN(sl));
5054 lua_settable(L, -3);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005055
Christopher Fauleta2097962019-07-15 16:25:33 +02005056 /* Stores the http version. */
5057 lua_pushstring(L, "version");
5058 lua_pushlstring(L, HTX_SL_REQ_VPTR(sl), HTX_SL_REQ_VLEN(sl));
5059 lua_settable(L, -3);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005060
Christopher Fauleta2097962019-07-15 16:25:33 +02005061 /* creates an array of headers. hlua_http_get_headers() crates and push
5062 * the array on the top of the stack.
5063 */
5064 lua_pushstring(L, "headers");
5065 htxn.s = s;
5066 htxn.p = px;
5067 htxn.dir = SMP_OPT_DIR_REQ;
Christopher Faulet9d1332b2020-02-24 16:46:16 +01005068 if (!hlua_http_get_headers(L, &htxn.s->txn->req))
Christopher Fauleta2097962019-07-15 16:25:33 +02005069 return 0;
5070 lua_settable(L, -3);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005071
Amaury Denoyellec453f952021-07-06 11:40:12 +02005072 parser = http_uri_parser_init(htx_sl_req_uri(sl));
5073 path = http_parse_path(&parser);
Tim Duesterhused526372020-03-05 17:56:33 +01005074 if (isttest(path)) {
Christopher Fauleta2097962019-07-15 16:25:33 +02005075 char *p, *q, *end;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005076
Christopher Fauleta2097962019-07-15 16:25:33 +02005077 p = path.ptr;
Tim Duesterhus4c8f75f2021-11-06 15:14:44 +01005078 end = istend(path);
Christopher Fauleta2097962019-07-15 16:25:33 +02005079 q = p;
5080 while (q < end && *q != '?')
5081 q++;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005082
Thierry FOURNIER7d388632017-02-22 02:06:16 +01005083 /* Stores the request path. */
Christopher Fauleta2097962019-07-15 16:25:33 +02005084 lua_pushstring(L, "path");
5085 lua_pushlstring(L, p, q - p);
Thierry FOURNIER7d388632017-02-22 02:06:16 +01005086 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01005087
Christopher Fauleta2097962019-07-15 16:25:33 +02005088 /* Stores the query string. */
5089 lua_pushstring(L, "qs");
5090 if (*q == '?')
5091 q++;
5092 lua_pushlstring(L, q, end - q);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005093 lua_settable(L, -3);
Christopher Fauleta2097962019-07-15 16:25:33 +02005094 }
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005095
Christopher Fauleta2097962019-07-15 16:25:33 +02005096 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
5097 struct htx_blk *blk = htx_get_blk(htx, pos);
5098 enum htx_blk_type type = htx_get_blk_type(blk);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005099
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01005100 if (type == HTX_BLK_TLR || type == HTX_BLK_EOT)
Christopher Fauleta2097962019-07-15 16:25:33 +02005101 break;
5102 if (type == HTX_BLK_DATA)
5103 len += htx_get_blksz(blk);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005104 }
Christopher Faulet2e47e3a2023-01-13 11:40:24 +01005105 if (htx->extra != HTX_UNKOWN_PAYLOAD_LENGTH)
Christopher Fauleta2097962019-07-15 16:25:33 +02005106 len += htx->extra;
5107
5108 /* Stores the request path. */
5109 lua_pushstring(L, "length");
5110 lua_pushinteger(L, len);
5111 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01005112
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005113 /* Create an empty array of HTTP request headers. */
5114 lua_pushstring(L, "response");
5115 lua_newtable(L);
5116 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01005117
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005118 /* Pop a class stream metatable and affect it to the table. */
5119 lua_rawgeti(L, LUA_REGISTRYINDEX, class_applet_http_ref);
5120 lua_setmetatable(L, -2);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005121
5122 return 1;
5123}
5124
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01005125__LJMP static int hlua_applet_http_set_var(lua_State *L)
5126{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005127 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01005128 struct stream *s;
5129 const char *name;
5130 size_t len;
5131 struct sample smp;
5132
Tim Duesterhus4e172c92020-05-19 13:49:42 +02005133 if (lua_gettop(L) < 3 || lua_gettop(L) > 4)
5134 WILL_LJMP(luaL_error(L, "'set_var' needs between 3 and 4 arguments"));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01005135
5136 /* It is useles to retrieve the stream, but this function
5137 * runs only in a stream context.
5138 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005139 luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01005140 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02005141 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01005142
5143 /* Converts the third argument in a sample. */
Amaury Denoyellebc0af6a2020-10-29 17:21:20 +01005144 memset(&smp, 0, sizeof(smp));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01005145 hlua_lua2smp(L, 3, &smp);
5146
5147 /* Store the sample in a variable. */
5148 smp_set_owner(&smp, s->be, s->sess, s, 0);
Tim Duesterhus4e172c92020-05-19 13:49:42 +02005149
5150 if (lua_gettop(L) == 4 && lua_toboolean(L, 4))
5151 lua_pushboolean(L, vars_set_by_name_ifexist(name, len, &smp) != 0);
5152 else
5153 lua_pushboolean(L, vars_set_by_name(name, len, &smp) != 0);
5154
Tim Duesterhus84ebc132020-05-19 13:49:41 +02005155 return 1;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01005156}
5157
5158__LJMP static int hlua_applet_http_unset_var(lua_State *L)
5159{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005160 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01005161 struct stream *s;
5162 const char *name;
5163 size_t len;
5164 struct sample smp;
5165
5166 MAY_LJMP(check_args(L, 2, "unset_var"));
5167
5168 /* It is useles to retrieve the stream, but this function
5169 * runs only in a stream context.
5170 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005171 luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01005172 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02005173 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01005174
5175 /* Unset the variable. */
5176 smp_set_owner(&smp, s->be, s->sess, s, 0);
Tim Duesterhus84ebc132020-05-19 13:49:41 +02005177 lua_pushboolean(L, vars_unset_by_name_ifexist(name, len, &smp) != 0);
5178 return 1;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01005179}
5180
5181__LJMP static int hlua_applet_http_get_var(lua_State *L)
5182{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005183 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01005184 struct stream *s;
5185 const char *name;
5186 size_t len;
5187 struct sample smp;
5188
5189 MAY_LJMP(check_args(L, 2, "get_var"));
5190
5191 /* It is useles to retrieve the stream, but this function
5192 * runs only in a stream context.
5193 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005194 luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01005195 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02005196 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01005197
5198 smp_set_owner(&smp, s->be, s->sess, s, 0);
Willy Tarreaue352b9d2021-09-03 11:52:38 +02005199 if (!vars_get_by_name(name, len, &smp, NULL)) {
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01005200 lua_pushnil(L);
5201 return 1;
5202 }
5203
5204 return hlua_smp2lua(L, &smp);
5205}
5206
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01005207__LJMP static int hlua_applet_http_set_priv(lua_State *L)
5208{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005209 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
5210 struct stream *s = luactx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01005211 struct hlua *hlua;
5212
5213 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005214 if (!s->hlua)
5215 return 0;
5216 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01005217
5218 MAY_LJMP(check_args(L, 2, "set_priv"));
5219
5220 /* Remove previous value. */
Thierry FOURNIERe068b602017-04-26 13:27:05 +02005221 luaL_unref(L, LUA_REGISTRYINDEX, hlua->Mref);
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01005222
5223 /* Get and store new value. */
5224 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
5225 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
5226
5227 return 0;
5228}
5229
5230__LJMP static int hlua_applet_http_get_priv(lua_State *L)
5231{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005232 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
5233 struct stream *s = luactx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01005234 struct hlua *hlua;
5235
5236 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005237 if (!s->hlua) {
5238 lua_pushnil(L);
5239 return 1;
5240 }
5241 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01005242
5243 /* Push configuration index in the stack. */
5244 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
5245
5246 return 1;
5247}
5248
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005249/* If expected data not yet available, it returns a yield. This function
5250 * consumes the data in the buffer. It returns a string containing the
5251 * data. This string can be empty.
5252 */
Christopher Fauleta2097962019-07-15 16:25:33 +02005253__LJMP static int hlua_applet_http_getline_yield(lua_State *L, int status, lua_KContext ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005254{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005255 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Willy Tarreauc12b3212022-05-27 11:08:15 +02005256 struct stconn *sc = appctx_sc(luactx->appctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02005257 struct channel *req = sc_oc(sc);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005258 struct htx *htx;
5259 struct htx_blk *blk;
5260 size_t count;
5261 int stop = 0;
5262
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005263 htx = htx_from_buf(&req->buf);
5264 count = co_data(req);
Christopher Fauleta3f15502019-05-13 15:27:23 +02005265 blk = htx_get_first_blk(htx);
Christopher Fauletcc26b132018-12-18 21:20:57 +01005266
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005267 while (count && !stop && blk) {
5268 enum htx_blk_type type = htx_get_blk_type(blk);
5269 uint32_t sz = htx_get_blksz(blk);
5270 struct ist v;
5271 uint32_t vlen;
5272 char *nl;
5273
5274 vlen = sz;
5275 if (vlen > count) {
5276 if (type != HTX_BLK_DATA)
5277 break;
5278 vlen = count;
5279 }
5280
5281 switch (type) {
5282 case HTX_BLK_UNUSED:
5283 break;
5284
5285 case HTX_BLK_DATA:
5286 v = htx_get_blk_value(htx, blk);
5287 v.len = vlen;
5288 nl = istchr(v, '\n');
5289 if (nl != NULL) {
5290 stop = 1;
5291 vlen = nl - v.ptr + 1;
5292 }
Willy Tarreau7e702d12021-04-28 17:59:21 +02005293 luaL_addlstring(&luactx->b, v.ptr, vlen);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005294 break;
5295
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005296 case HTX_BLK_TLR:
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01005297 case HTX_BLK_EOT:
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005298 stop = 1;
5299 break;
5300
5301 default:
5302 break;
5303 }
5304
Willy Tarreau84240042022-02-28 16:51:23 +01005305 c_rew(req, vlen);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005306 count -= vlen;
5307 if (sz == vlen)
5308 blk = htx_remove_blk(htx, blk);
5309 else {
5310 htx_cut_data_blk(htx, blk, vlen);
5311 break;
5312 }
5313 }
5314
Christopher Fauleteccb31c2021-04-02 14:24:56 +02005315 /* The message was fully consumed and no more data are expected
5316 * (EOM flag set).
5317 */
Christopher Faulet904763f2023-03-22 14:53:11 +01005318 if (htx_is_empty(htx) && (sc->flags & SC_FL_EOI))
Christopher Fauleteccb31c2021-04-02 14:24:56 +02005319 stop = 1;
5320
Christopher Faulet0ae79d02019-02-27 21:36:59 +01005321 htx_to_buf(htx, &req->buf);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005322 if (!stop) {
Willy Tarreau90e8b452022-05-25 18:21:43 +02005323 applet_need_more_data(luactx->appctx);
Christopher Fauleta2097962019-07-15 16:25:33 +02005324 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_getline_yield, TICK_ETERNITY, 0));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005325 }
5326
5327 /* return the result. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005328 luaL_pushresult(&luactx->b);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005329 return 1;
5330}
5331
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005332
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08005333/* Check arguments for the function "hlua_channel_get_yield". */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005334__LJMP static int hlua_applet_http_getline(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005335{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005336 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005337
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005338 /* Initialise the string catenation. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005339 luaL_buffinit(L, &luactx->b);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005340
Christopher Fauleta2097962019-07-15 16:25:33 +02005341 return MAY_LJMP(hlua_applet_http_getline_yield(L, 0, 0));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005342}
5343
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005344/* If expected data not yet available, it returns a yield. This function
5345 * consumes the data in the buffer. It returns a string containing the
5346 * data. This string can be empty.
5347 */
Christopher Fauleta2097962019-07-15 16:25:33 +02005348__LJMP static int hlua_applet_http_recv_yield(lua_State *L, int status, lua_KContext ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005349{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005350 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Willy Tarreauc12b3212022-05-27 11:08:15 +02005351 struct stconn *sc = appctx_sc(luactx->appctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02005352 struct channel *req = sc_oc(sc);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005353 struct htx *htx;
5354 struct htx_blk *blk;
5355 size_t count;
5356 int len;
5357
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005358 htx = htx_from_buf(&req->buf);
5359 len = MAY_LJMP(luaL_checkinteger(L, 2));
5360 count = co_data(req);
Christopher Faulet29f17582019-05-23 11:03:26 +02005361 blk = htx_get_head_blk(htx);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005362 while (count && len && blk) {
5363 enum htx_blk_type type = htx_get_blk_type(blk);
5364 uint32_t sz = htx_get_blksz(blk);
5365 struct ist v;
5366 uint32_t vlen;
5367
5368 vlen = sz;
5369 if (len > 0 && vlen > len)
5370 vlen = len;
5371 if (vlen > count) {
5372 if (type != HTX_BLK_DATA)
5373 break;
5374 vlen = count;
5375 }
5376
5377 switch (type) {
5378 case HTX_BLK_UNUSED:
5379 break;
5380
5381 case HTX_BLK_DATA:
5382 v = htx_get_blk_value(htx, blk);
Willy Tarreau7e702d12021-04-28 17:59:21 +02005383 luaL_addlstring(&luactx->b, v.ptr, vlen);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005384 break;
5385
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005386 case HTX_BLK_TLR:
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01005387 case HTX_BLK_EOT:
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005388 len = 0;
5389 break;
5390
5391 default:
5392 break;
5393 }
5394
Willy Tarreau84240042022-02-28 16:51:23 +01005395 c_rew(req, vlen);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005396 count -= vlen;
5397 if (len > 0)
5398 len -= vlen;
5399 if (sz == vlen)
5400 blk = htx_remove_blk(htx, blk);
5401 else {
5402 htx_cut_data_blk(htx, blk, vlen);
5403 break;
5404 }
5405 }
5406
Christopher Fauleteccb31c2021-04-02 14:24:56 +02005407 /* The message was fully consumed and no more data are expected
5408 * (EOM flag set).
5409 */
Christopher Faulet904763f2023-03-22 14:53:11 +01005410 if (htx_is_empty(htx) && (sc->flags & SC_FL_EOI))
Christopher Fauleteccb31c2021-04-02 14:24:56 +02005411 len = 0;
5412
Christopher Faulet0ae79d02019-02-27 21:36:59 +01005413 htx_to_buf(htx, &req->buf);
5414
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005415 /* If we are no other data available, yield waiting for new data. */
5416 if (len) {
5417 if (len > 0) {
5418 lua_pushinteger(L, len);
5419 lua_replace(L, 2);
5420 }
Willy Tarreau90e8b452022-05-25 18:21:43 +02005421 applet_need_more_data(luactx->appctx);
Willy Tarreau9635e032018-10-16 17:52:55 +02005422 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005423 }
5424
5425 /* return the result. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005426 luaL_pushresult(&luactx->b);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005427 return 1;
5428}
5429
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08005430/* Check arguments for the function "hlua_channel_get_yield". */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005431__LJMP static int hlua_applet_http_recv(lua_State *L)
5432{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005433 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005434 int len = -1;
5435
5436 /* Check arguments. */
5437 if (lua_gettop(L) > 2)
5438 WILL_LJMP(luaL_error(L, "The 'recv' function requires between 1 and 2 arguments."));
5439 if (lua_gettop(L) >= 2) {
5440 len = MAY_LJMP(luaL_checkinteger(L, 2));
5441 lua_pop(L, 1);
5442 }
5443
Christopher Fauleta2097962019-07-15 16:25:33 +02005444 lua_pushinteger(L, len);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005445
Christopher Fauleta2097962019-07-15 16:25:33 +02005446 /* Initialise the string catenation. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005447 luaL_buffinit(L, &luactx->b);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005448
Christopher Fauleta2097962019-07-15 16:25:33 +02005449 return MAY_LJMP(hlua_applet_http_recv_yield(L, 0, 0));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005450}
5451
5452/* Append data in the output side of the buffer. This data is immediately
5453 * sent. The function returns the amount of data written. If the buffer
5454 * cannot contain the data, the function yields. The function returns -1
5455 * if the channel is closed.
5456 */
Christopher Fauleta2097962019-07-15 16:25:33 +02005457__LJMP static int hlua_applet_http_send_yield(lua_State *L, int status, lua_KContext ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005458{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005459 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Willy Tarreauc12b3212022-05-27 11:08:15 +02005460 struct stconn *sc = appctx_sc(luactx->appctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02005461 struct channel *res = sc_ic(sc);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005462 struct htx *htx = htx_from_buf(&res->buf);
5463 const char *data;
5464 size_t len;
5465 int l = MAY_LJMP(luaL_checkinteger(L, 3));
5466 int max;
5467
Christopher Faulet9060fc02019-07-03 11:39:30 +02005468 max = htx_get_max_blksz(htx, channel_htx_recv_max(res, htx));
Christopher Faulet4b0e9b22019-01-09 12:16:58 +01005469 if (!max)
5470 goto snd_yield;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005471
5472 data = MAY_LJMP(luaL_checklstring(L, 2, &len));
5473
5474 /* Get the max amount of data which can write as input in the channel. */
5475 if (max > (len - l))
5476 max = len - l;
5477
5478 /* Copy data. */
Willy Tarreau0a7ef022019-05-28 10:30:11 +02005479 max = htx_add_data(htx, ist2(data + l, max));
Christopher Fauletf6cce3f2019-02-27 21:20:09 +01005480 channel_add_input(res, max);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005481
5482 /* update counters. */
5483 l += max;
5484 lua_pop(L, 1);
5485 lua_pushinteger(L, l);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005486
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005487 /* If some data is not send, declares the situation to the
5488 * applet, and returns a yield.
5489 */
5490 if (l < len) {
Christopher Faulet4b0e9b22019-01-09 12:16:58 +01005491 snd_yield:
Christopher Faulet0ae79d02019-02-27 21:36:59 +01005492 htx_to_buf(htx, &res->buf);
Christopher Faulet7b3d38a2023-05-05 11:28:45 +02005493 sc_need_room(sc, channel_recv_max(res) + 1);
Willy Tarreau9635e032018-10-16 17:52:55 +02005494 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005495 }
5496
Christopher Fauleta2097962019-07-15 16:25:33 +02005497 htx_to_buf(htx, &res->buf);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005498 return 1;
5499}
5500
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05005501/* Just a wrapper of "hlua_applet_send_yield". This wrapper permits
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005502 * yield the LUA process, and resume it without checking the
5503 * input arguments.
5504 */
5505__LJMP static int hlua_applet_http_send(lua_State *L)
5506{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005507 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005508 struct hlua_http_ctx *http_ctx = luactx->appctx->svcctx;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005509
5510 /* We want to send some data. Headers must be sent. */
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005511 if (!(http_ctx->flags & APPLET_HDR_SENT)) {
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005512 hlua_pusherror(L, "Lua: 'send' you must call start_response() before sending data.");
5513 WILL_LJMP(lua_error(L));
5514 }
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005515
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05005516 /* This integer is used for followinf the amount of data sent. */
Christopher Fauleta2097962019-07-15 16:25:33 +02005517 lua_pushinteger(L, 0);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005518
Christopher Fauleta2097962019-07-15 16:25:33 +02005519 return MAY_LJMP(hlua_applet_http_send_yield(L, 0, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005520}
5521
5522__LJMP static int hlua_applet_http_addheader(lua_State *L)
5523{
5524 const char *name;
5525 int ret;
5526
5527 MAY_LJMP(hlua_checkapplet_http(L, 1));
5528 name = MAY_LJMP(luaL_checkstring(L, 2));
5529 MAY_LJMP(luaL_checkstring(L, 3));
5530
5531 /* Push in the stack the "response" entry. */
5532 ret = lua_getfield(L, 1, "response");
5533 if (ret != LUA_TTABLE) {
5534 hlua_pusherror(L, "Lua: 'add_header' internal error: AppletHTTP['response'] "
5535 "is expected as an array. %s found", lua_typename(L, ret));
5536 WILL_LJMP(lua_error(L));
5537 }
5538
5539 /* check if the header is already registered if it is not
5540 * the case, register it.
5541 */
5542 ret = lua_getfield(L, -1, name);
5543 if (ret == LUA_TNIL) {
5544
5545 /* Entry not found. */
5546 lua_pop(L, 1); /* remove the nil. The "response" table is the top of the stack. */
5547
5548 /* Insert the new header name in the array in the top of the stack.
5549 * It left the new array in the top of the stack.
5550 */
5551 lua_newtable(L);
5552 lua_pushvalue(L, 2);
5553 lua_pushvalue(L, -2);
5554 lua_settable(L, -4);
5555
5556 } else if (ret != LUA_TTABLE) {
5557
5558 /* corruption error. */
5559 hlua_pusherror(L, "Lua: 'add_header' internal error: AppletHTTP['response']['%s'] "
5560 "is expected as an array. %s found", name, lua_typename(L, ret));
5561 WILL_LJMP(lua_error(L));
5562 }
5563
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -07005564 /* Now the top of thestack is an array of values. We push
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005565 * the header value as new entry.
5566 */
5567 lua_pushvalue(L, 3);
5568 ret = lua_rawlen(L, -2);
5569 lua_rawseti(L, -2, ret + 1);
5570 lua_pushboolean(L, 1);
5571 return 1;
5572}
5573
5574__LJMP static int hlua_applet_http_status(lua_State *L)
5575{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005576 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005577 int status = MAY_LJMP(luaL_checkinteger(L, 2));
Robin H. Johnson52f5db22017-01-01 13:10:52 -08005578 const char *reason = MAY_LJMP(luaL_optlstring(L, 3, NULL, NULL));
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005579 struct hlua_http_ctx *http_ctx = luactx->appctx->svcctx;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005580
5581 if (status < 100 || status > 599) {
5582 lua_pushboolean(L, 0);
5583 return 1;
5584 }
5585
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005586 http_ctx->status = status;
5587 http_ctx->reason = reason;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005588 lua_pushboolean(L, 1);
5589 return 1;
5590}
5591
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005592
Christopher Fauleta2097962019-07-15 16:25:33 +02005593__LJMP static int hlua_applet_http_send_response(lua_State *L)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005594{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005595 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005596 struct hlua_http_ctx *http_ctx = luactx->appctx->svcctx;
Willy Tarreauc12b3212022-05-27 11:08:15 +02005597 struct stconn *sc = appctx_sc(luactx->appctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02005598 struct channel *res = sc_ic(sc);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005599 struct htx *htx;
5600 struct htx_sl *sl;
5601 struct h1m h1m;
5602 const char *status, *reason;
5603 const char *name, *value;
5604 size_t nlen, vlen;
5605 unsigned int flags;
5606
5607 /* Send the message at once. */
5608 htx = htx_from_buf(&res->buf);
5609 h1m_init_res(&h1m);
5610
5611 /* Use the same http version than the request. */
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005612 status = ultoa_r(http_ctx->status, trash.area, trash.size);
5613 reason = http_ctx->reason;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005614 if (reason == NULL)
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005615 reason = http_get_reason(http_ctx->status);
5616 if (http_ctx->flags & APPLET_HTTP11) {
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005617 flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11);
5618 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.1"), ist(status), ist(reason));
5619 }
5620 else {
5621 flags = HTX_SL_F_IS_RESP;
5622 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.0"), ist(status), ist(reason));
5623 }
5624 if (!sl) {
5625 hlua_pusherror(L, "Lua applet http '%s': Failed to create response.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005626 luactx->appctx->rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005627 WILL_LJMP(lua_error(L));
5628 }
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005629 sl->info.res.status = http_ctx->status;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005630
5631 /* Get the array associated to the field "response" in the object AppletHTTP. */
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005632 if (lua_getfield(L, 1, "response") != LUA_TTABLE) {
5633 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response'] missing.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005634 luactx->appctx->rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005635 WILL_LJMP(lua_error(L));
5636 }
5637
5638 /* Browse the list of headers. */
5639 lua_pushnil(L);
5640 while(lua_next(L, -2) != 0) {
5641 /* We expect a string as -2. */
5642 if (lua_type(L, -2) != LUA_TSTRING) {
5643 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response'][] element must be a string. got %s.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005644 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005645 lua_typename(L, lua_type(L, -2)));
5646 WILL_LJMP(lua_error(L));
5647 }
5648 name = lua_tolstring(L, -2, &nlen);
5649
5650 /* We expect an array as -1. */
5651 if (lua_type(L, -1) != LUA_TTABLE) {
5652 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 +02005653 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005654 name,
5655 lua_typename(L, lua_type(L, -1)));
5656 WILL_LJMP(lua_error(L));
5657 }
5658
5659 /* Browse the table who is on the top of the stack. */
5660 lua_pushnil(L);
5661 while(lua_next(L, -2) != 0) {
5662 int id;
5663
5664 /* We expect a number as -2. */
5665 if (lua_type(L, -2) != LUA_TNUMBER) {
5666 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 +02005667 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005668 name,
5669 lua_typename(L, lua_type(L, -2)));
5670 WILL_LJMP(lua_error(L));
5671 }
5672 id = lua_tointeger(L, -2);
5673
5674 /* We expect a string as -2. */
5675 if (lua_type(L, -1) != LUA_TSTRING) {
5676 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 +02005677 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005678 name, id,
5679 lua_typename(L, lua_type(L, -1)));
5680 WILL_LJMP(lua_error(L));
5681 }
5682 value = lua_tolstring(L, -1, &vlen);
5683
5684 /* Simple Protocol checks. */
Christopher Faulet545fbba2021-09-28 09:36:25 +02005685 if (isteqi(ist2(name, nlen), ist("transfer-encoding"))) {
5686 int ret;
5687
5688 ret = h1_parse_xfer_enc_header(&h1m, ist2(value, vlen));
5689 if (ret < 0) {
5690 hlua_pusherror(L, "Lua applet http '%s': Invalid '%s' header.\n",
5691 luactx->appctx->rule->arg.hlua_rule->fcn->name,
5692 name);
5693 WILL_LJMP(lua_error(L));
5694 }
5695 else if (ret == 0)
5696 goto next; /* Skip it */
5697 }
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005698 else if (isteqi(ist2(name, nlen), ist("content-length"))) {
5699 struct ist v = ist2(value, vlen);
5700 int ret;
5701
5702 ret = h1_parse_cont_len_header(&h1m, &v);
5703 if (ret < 0) {
5704 hlua_pusherror(L, "Lua applet http '%s': Invalid '%s' header.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005705 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005706 name);
5707 WILL_LJMP(lua_error(L));
5708 }
5709 else if (ret == 0)
5710 goto next; /* Skip it */
5711 }
5712
5713 /* Add a new header */
5714 if (!htx_add_header(htx, ist2(name, nlen), ist2(value, vlen))) {
5715 hlua_pusherror(L, "Lua applet http '%s': Failed to add header '%s' in the response.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005716 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005717 name);
5718 WILL_LJMP(lua_error(L));
5719 }
5720 next:
5721 /* Remove the array from the stack, and get next element with a remaining string. */
5722 lua_pop(L, 1);
5723 }
5724
5725 /* Remove the array from the stack, and get next element with a remaining string. */
5726 lua_pop(L, 1);
5727 }
5728
5729 if (h1m.flags & H1_MF_CHNK)
5730 h1m.flags &= ~H1_MF_CLEN;
5731 if (h1m.flags & (H1_MF_CLEN|H1_MF_CHNK))
5732 h1m.flags |= H1_MF_XFER_LEN;
5733
5734 /* Uset HTX start-line flags */
5735 if (h1m.flags & H1_MF_XFER_ENC)
5736 flags |= HTX_SL_F_XFER_ENC;
5737 if (h1m.flags & H1_MF_XFER_LEN) {
5738 flags |= HTX_SL_F_XFER_LEN;
5739 if (h1m.flags & H1_MF_CHNK)
5740 flags |= HTX_SL_F_CHNK;
5741 else if (h1m.flags & H1_MF_CLEN)
5742 flags |= HTX_SL_F_CLEN;
5743 if (h1m.body_len == 0)
5744 flags |= HTX_SL_F_BODYLESS;
5745 }
5746 sl->flags |= flags;
5747
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -07005748 /* If we don't have a content-length set, and the HTTP version is 1.1
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005749 * and the status code implies the presence of a message body, we must
5750 * announce a transfer encoding chunked. This is required by haproxy
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05005751 * for the keepalive compliance. If the applet announces a transfer-encoding
5752 * chunked itself, don't do anything.
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005753 */
5754 if ((flags & (HTX_SL_F_VER_11|HTX_SL_F_XFER_LEN)) == HTX_SL_F_VER_11 &&
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005755 http_ctx->status >= 200 && http_ctx->status != 204 && http_ctx->status != 304) {
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005756 /* Add a new header */
5757 sl->flags |= (HTX_SL_F_XFER_ENC|H1_MF_CHNK|H1_MF_XFER_LEN);
5758 if (!htx_add_header(htx, ist("transfer-encoding"), ist("chunked"))) {
5759 hlua_pusherror(L, "Lua applet http '%s': Failed to add header 'transfer-encoding' in the response.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005760 luactx->appctx->rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005761 WILL_LJMP(lua_error(L));
5762 }
5763 }
5764
5765 /* Finalize headers. */
5766 if (!htx_add_endof(htx, HTX_BLK_EOH)) {
5767 hlua_pusherror(L, "Lua applet http '%s': Failed create the response.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005768 luactx->appctx->rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005769 WILL_LJMP(lua_error(L));
5770 }
5771
5772 if (htx_used_space(htx) > b_size(&res->buf) - global.tune.maxrewrite) {
5773 b_reset(&res->buf);
5774 hlua_pusherror(L, "Lua: 'start_response': response header block too big");
5775 WILL_LJMP(lua_error(L));
5776 }
5777
5778 htx_to_buf(htx, &res->buf);
Christopher Fauletf6cce3f2019-02-27 21:20:09 +01005779 channel_add_input(res, htx->data);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005780
5781 /* Headers sent, set the flag. */
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005782 http_ctx->flags |= APPLET_HDR_SENT;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005783 return 0;
5784
5785}
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005786/* We will build the status line and the headers of the HTTP response.
5787 * We will try send at once if its not possible, we give back the hand
5788 * waiting for more room.
5789 */
Christopher Fauleta2097962019-07-15 16:25:33 +02005790__LJMP static int hlua_applet_http_start_response_yield(lua_State *L, int status, lua_KContext ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005791{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005792 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Willy Tarreauc12b3212022-05-27 11:08:15 +02005793 struct stconn *sc = appctx_sc(luactx->appctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02005794 struct channel *res = sc_ic(sc);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005795
5796 if (co_data(res)) {
Christopher Faulet7b3d38a2023-05-05 11:28:45 +02005797 sc_need_room(sc, -1);
Christopher Fauleta2097962019-07-15 16:25:33 +02005798 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_start_response_yield, TICK_ETERNITY, 0));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005799 }
Christopher Fauleta2097962019-07-15 16:25:33 +02005800 return MAY_LJMP(hlua_applet_http_send_response(L));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005801}
5802
5803
Christopher Fauleta2097962019-07-15 16:25:33 +02005804__LJMP static int hlua_applet_http_start_response(lua_State *L)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005805{
Christopher Fauleta2097962019-07-15 16:25:33 +02005806 return MAY_LJMP(hlua_applet_http_start_response_yield(L, 0, 0));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005807}
5808
Christopher Fauleta2097962019-07-15 16:25:33 +02005809/*
5810 *
5811 *
5812 * Class HTTP
5813 *
5814 *
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005815 */
Christopher Fauleta2097962019-07-15 16:25:33 +02005816
5817/* Returns a struct hlua_txn if the stack entry "ud" is
5818 * a class stream, otherwise it throws an error.
5819 */
5820__LJMP static struct hlua_txn *hlua_checkhttp(lua_State *L, int ud)
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005821{
Christopher Fauleta2097962019-07-15 16:25:33 +02005822 return MAY_LJMP(hlua_checkudata(L, ud, class_http_ref));
5823}
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005824
Christopher Fauleta2097962019-07-15 16:25:33 +02005825/* This function creates and push in the stack a HTTP object
5826 * according with a current TXN.
5827 */
5828static int hlua_http_new(lua_State *L, struct hlua_txn *txn)
5829{
5830 struct hlua_txn *htxn;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005831
Christopher Fauleta2097962019-07-15 16:25:33 +02005832 /* Check stack size. */
5833 if (!lua_checkstack(L, 3))
5834 return 0;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005835
Christopher Fauleta2097962019-07-15 16:25:33 +02005836 /* Create the object: obj[0] = userdata.
5837 * Note that the base of the Converters object is the
5838 * same than the TXN object.
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005839 */
Christopher Fauleta2097962019-07-15 16:25:33 +02005840 lua_newtable(L);
5841 htxn = lua_newuserdata(L, sizeof(*htxn));
5842 lua_rawseti(L, -2, 0);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005843
5844 htxn->s = txn->s;
5845 htxn->p = txn->p;
Christopher Faulet256b69a2019-05-23 11:14:21 +02005846 htxn->dir = txn->dir;
5847 htxn->flags = txn->flags;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005848
5849 /* Pop a class stream metatable and affect it to the table. */
5850 lua_rawgeti(L, LUA_REGISTRYINDEX, class_http_ref);
5851 lua_setmetatable(L, -2);
5852
5853 return 1;
5854}
5855
Christopher Fauletdf97ac42020-02-26 16:57:19 +01005856/* This function creates and returns an array containing the status-line
5857 * elements. This function does not fails.
5858 */
5859__LJMP static int hlua_http_get_stline(lua_State *L, struct htx_sl *sl)
5860{
5861 /* Create the table. */
5862 lua_newtable(L);
5863
5864 if (sl->flags & HTX_SL_F_IS_RESP) {
5865 lua_pushstring(L, "version");
5866 lua_pushlstring(L, HTX_SL_RES_VPTR(sl), HTX_SL_RES_VLEN(sl));
5867 lua_settable(L, -3);
5868 lua_pushstring(L, "code");
5869 lua_pushlstring(L, HTX_SL_RES_CPTR(sl), HTX_SL_RES_CLEN(sl));
5870 lua_settable(L, -3);
5871 lua_pushstring(L, "reason");
5872 lua_pushlstring(L, HTX_SL_RES_RPTR(sl), HTX_SL_RES_RLEN(sl));
5873 lua_settable(L, -3);
5874 }
5875 else {
5876 lua_pushstring(L, "method");
5877 lua_pushlstring(L, HTX_SL_REQ_MPTR(sl), HTX_SL_REQ_MLEN(sl));
5878 lua_settable(L, -3);
5879 lua_pushstring(L, "uri");
5880 lua_pushlstring(L, HTX_SL_REQ_UPTR(sl), HTX_SL_REQ_ULEN(sl));
5881 lua_settable(L, -3);
5882 lua_pushstring(L, "version");
5883 lua_pushlstring(L, HTX_SL_REQ_VPTR(sl), HTX_SL_REQ_VLEN(sl));
5884 lua_settable(L, -3);
5885 }
5886 return 1;
5887}
5888
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005889/* This function creates ans returns an array of HTTP headers.
5890 * This function does not fails. It is used as wrapper with the
5891 * 2 following functions.
5892 */
Christopher Faulet9d1332b2020-02-24 16:46:16 +01005893__LJMP static int hlua_http_get_headers(lua_State *L, struct http_msg *msg)
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005894{
Christopher Fauleta2097962019-07-15 16:25:33 +02005895 struct htx *htx;
5896 int32_t pos;
5897
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005898 /* Create the table. */
5899 lua_newtable(L);
5900
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005901
Christopher Fauleta2097962019-07-15 16:25:33 +02005902 htx = htxbuf(&msg->chn->buf);
5903 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
5904 struct htx_blk *blk = htx_get_blk(htx, pos);
5905 enum htx_blk_type type = htx_get_blk_type(blk);
5906 struct ist n, v;
5907 int len;
Christopher Faulet724a12c2018-12-13 22:12:15 +01005908
Christopher Fauleta2097962019-07-15 16:25:33 +02005909 if (type == HTX_BLK_HDR) {
5910 n = htx_get_blk_name(htx,blk);
5911 v = htx_get_blk_value(htx, blk);
Christopher Faulet724a12c2018-12-13 22:12:15 +01005912 }
Christopher Fauleta2097962019-07-15 16:25:33 +02005913 else if (type == HTX_BLK_EOH)
5914 break;
5915 else
5916 continue;
Christopher Faulet724a12c2018-12-13 22:12:15 +01005917
Christopher Fauleta2097962019-07-15 16:25:33 +02005918 /* Check for existing entry:
5919 * assume that the table is on the top of the stack, and
5920 * push the key in the stack, the function lua_gettable()
5921 * perform the lookup.
5922 */
5923 lua_pushlstring(L, n.ptr, n.len);
5924 lua_gettable(L, -2);
Christopher Faulet724a12c2018-12-13 22:12:15 +01005925
Christopher Fauleta2097962019-07-15 16:25:33 +02005926 switch (lua_type(L, -1)) {
5927 case LUA_TNIL:
5928 /* Table not found, create it. */
5929 lua_pop(L, 1); /* remove the nil value. */
5930 lua_pushlstring(L, n.ptr, n.len); /* push the header name as key. */
5931 lua_newtable(L); /* create and push empty table. */
5932 lua_pushlstring(L, v.ptr, v.len); /* push header value. */
5933 lua_rawseti(L, -2, 0); /* index header value (pop it). */
5934 lua_rawset(L, -3); /* index new table with header name (pop the values). */
Christopher Faulet724a12c2018-12-13 22:12:15 +01005935 break;
Christopher Faulet724a12c2018-12-13 22:12:15 +01005936
Christopher Fauleta2097962019-07-15 16:25:33 +02005937 case LUA_TTABLE:
5938 /* Entry found: push the value in the table. */
5939 len = lua_rawlen(L, -1);
5940 lua_pushlstring(L, v.ptr, v.len); /* push header value. */
5941 lua_rawseti(L, -2, len+1); /* index header value (pop it). */
5942 lua_pop(L, 1); /* remove the table (it is stored in the main table). */
5943 break;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005944
Christopher Fauleta2097962019-07-15 16:25:33 +02005945 default:
5946 /* Other cases are errors. */
5947 hlua_pusherror(L, "internal error during the parsing of headers.");
5948 WILL_LJMP(lua_error(L));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005949 }
5950 }
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005951 return 1;
5952}
5953
5954__LJMP static int hlua_http_req_get_headers(lua_State *L)
5955{
5956 struct hlua_txn *htxn;
5957
5958 MAY_LJMP(check_args(L, 1, "req_get_headers"));
5959 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5960
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005961 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005962 WILL_LJMP(lua_error(L));
5963
Christopher Faulet9d1332b2020-02-24 16:46:16 +01005964 return hlua_http_get_headers(L, &htxn->s->txn->req);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005965}
5966
5967__LJMP static int hlua_http_res_get_headers(lua_State *L)
5968{
5969 struct hlua_txn *htxn;
5970
5971 MAY_LJMP(check_args(L, 1, "res_get_headers"));
5972 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5973
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005974 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005975 WILL_LJMP(lua_error(L));
5976
Christopher Faulet9d1332b2020-02-24 16:46:16 +01005977 return hlua_http_get_headers(L, &htxn->s->txn->rsp);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005978}
5979
5980/* This function replace full header, or just a value in
5981 * the request or in the response. It is a wrapper fir the
5982 * 4 following functions.
5983 */
Christopher Fauletd1914aa2020-02-24 16:52:46 +01005984__LJMP static inline int hlua_http_rep_hdr(lua_State *L, struct http_msg *msg, int full)
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005985{
5986 size_t name_len;
5987 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
5988 const char *reg = MAY_LJMP(luaL_checkstring(L, 3));
5989 const char *value = MAY_LJMP(luaL_checkstring(L, 4));
Christopher Fauleta2097962019-07-15 16:25:33 +02005990 struct htx *htx;
Dragan Dosen26743032019-04-30 15:54:36 +02005991 struct my_regex *re;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005992
Dragan Dosen26743032019-04-30 15:54:36 +02005993 if (!(re = regex_comp(reg, 1, 1, NULL)))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005994 WILL_LJMP(luaL_argerror(L, 3, "invalid regex"));
5995
Christopher Fauleta2097962019-07-15 16:25:33 +02005996 htx = htxbuf(&msg->chn->buf);
Christopher Fauletd1914aa2020-02-24 16:52:46 +01005997 http_replace_hdrs(chn_strm(msg->chn), htx, ist2(name, name_len), value, re, full);
Dragan Dosen26743032019-04-30 15:54:36 +02005998 regex_free(re);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005999 return 0;
6000}
6001
6002__LJMP static int hlua_http_req_rep_hdr(lua_State *L)
6003{
6004 struct hlua_txn *htxn;
6005
6006 MAY_LJMP(check_args(L, 4, "req_rep_hdr"));
6007 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
6008
Christopher Fauletd8f0e072020-02-25 09:45:51 +01006009 if (htxn->dir != SMP_OPT_DIR_REQ || !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->req, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006013}
6014
6015__LJMP static int hlua_http_res_rep_hdr(lua_State *L)
6016{
6017 struct hlua_txn *htxn;
6018
6019 MAY_LJMP(check_args(L, 4, "res_rep_hdr"));
6020 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
6021
Christopher Fauletd8f0e072020-02-25 09:45:51 +01006022 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006023 WILL_LJMP(lua_error(L));
6024
Christopher Fauletd1914aa2020-02-24 16:52:46 +01006025 return MAY_LJMP(hlua_http_rep_hdr(L, &htxn->s->txn->rsp, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006026}
6027
6028__LJMP static int hlua_http_req_rep_val(lua_State *L)
6029{
6030 struct hlua_txn *htxn;
6031
6032 MAY_LJMP(check_args(L, 4, "req_rep_hdr"));
6033 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
6034
Christopher Fauletd8f0e072020-02-25 09:45:51 +01006035 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006036 WILL_LJMP(lua_error(L));
6037
Christopher Fauletd1914aa2020-02-24 16:52:46 +01006038 return MAY_LJMP(hlua_http_rep_hdr(L, &htxn->s->txn->req, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006039}
6040
6041__LJMP static int hlua_http_res_rep_val(lua_State *L)
6042{
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006043 struct hlua_txn *htxn;
6044
6045 MAY_LJMP(check_args(L, 4, "res_rep_val"));
6046 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
6047
Christopher Fauletd8f0e072020-02-25 09:45:51 +01006048 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006049 WILL_LJMP(lua_error(L));
6050
Christopher Fauletd1914aa2020-02-24 16:52:46 +01006051 return MAY_LJMP(hlua_http_rep_hdr(L, &htxn->s->txn->rsp, 0));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006052}
6053
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08006054/* This function deletes all the occurrences of an header.
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006055 * It is a wrapper for the 2 following functions.
6056 */
Christopher Fauletd31c7b32020-02-25 09:37:57 +01006057__LJMP static inline int hlua_http_del_hdr(lua_State *L, struct http_msg *msg)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006058{
6059 size_t len;
6060 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Christopher Fauleta2097962019-07-15 16:25:33 +02006061 struct htx *htx = htxbuf(&msg->chn->buf);
6062 struct http_hdr_ctx ctx;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006063
Christopher Fauleta2097962019-07-15 16:25:33 +02006064 ctx.blk = NULL;
6065 while (http_find_header(htx, ist2(name, len), &ctx, 1))
6066 http_remove_header(htx, &ctx);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006067 return 0;
6068}
6069
6070__LJMP static int hlua_http_req_del_hdr(lua_State *L)
6071{
6072 struct hlua_txn *htxn;
6073
6074 MAY_LJMP(check_args(L, 2, "req_del_hdr"));
6075 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
6076
Christopher Fauletd8f0e072020-02-25 09:45:51 +01006077 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006078 WILL_LJMP(lua_error(L));
6079
Christopher Fauletd31c7b32020-02-25 09:37:57 +01006080 return hlua_http_del_hdr(L, &htxn->s->txn->req);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006081}
6082
6083__LJMP static int hlua_http_res_del_hdr(lua_State *L)
6084{
6085 struct hlua_txn *htxn;
6086
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006087 MAY_LJMP(check_args(L, 2, "res_del_hdr"));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006088 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
6089
Christopher Fauletd8f0e072020-02-25 09:45:51 +01006090 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006091 WILL_LJMP(lua_error(L));
6092
Christopher Fauletd31c7b32020-02-25 09:37:57 +01006093 return hlua_http_del_hdr(L, &htxn->s->txn->rsp);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006094}
6095
6096/* This function adds an header. It is a wrapper used by
6097 * the 2 following functions.
6098 */
Christopher Fauletd31c7b32020-02-25 09:37:57 +01006099__LJMP static inline int hlua_http_add_hdr(lua_State *L, struct http_msg *msg)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006100{
6101 size_t name_len;
6102 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
6103 size_t value_len;
6104 const char *value = MAY_LJMP(luaL_checklstring(L, 3, &value_len));
Christopher Fauleta2097962019-07-15 16:25:33 +02006105 struct htx *htx = htxbuf(&msg->chn->buf);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006106
Christopher Fauleta2097962019-07-15 16:25:33 +02006107 lua_pushboolean(L, http_add_header(htx, ist2(name, name_len),
6108 ist2(value, value_len)));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006109 return 0;
6110}
6111
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006112__LJMP static int hlua_http_req_add_hdr(lua_State *L)
6113{
6114 struct hlua_txn *htxn;
6115
6116 MAY_LJMP(check_args(L, 3, "req_add_hdr"));
6117 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
6118
6119 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
6120 WILL_LJMP(lua_error(L));
6121
6122 return hlua_http_add_hdr(L, &htxn->s->txn->req);
6123}
6124
6125__LJMP static int hlua_http_res_add_hdr(lua_State *L)
6126{
6127 struct hlua_txn *htxn;
6128
6129 MAY_LJMP(check_args(L, 3, "res_add_hdr"));
6130 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
6131
6132 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
6133 WILL_LJMP(lua_error(L));
6134
6135 return hlua_http_add_hdr(L, &htxn->s->txn->rsp);
6136}
6137
6138static int hlua_http_req_set_hdr(lua_State *L)
6139{
6140 struct hlua_txn *htxn;
6141
6142 MAY_LJMP(check_args(L, 3, "req_set_hdr"));
6143 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
6144
6145 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
6146 WILL_LJMP(lua_error(L));
6147
6148 hlua_http_del_hdr(L, &htxn->s->txn->req);
6149 return hlua_http_add_hdr(L, &htxn->s->txn->req);
6150}
6151
6152static int hlua_http_res_set_hdr(lua_State *L)
6153{
6154 struct hlua_txn *htxn;
6155
6156 MAY_LJMP(check_args(L, 3, "res_set_hdr"));
6157 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
6158
6159 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
6160 WILL_LJMP(lua_error(L));
6161
6162 hlua_http_del_hdr(L, &htxn->s->txn->rsp);
6163 return hlua_http_add_hdr(L, &htxn->s->txn->rsp);
6164}
6165
6166/* This function set the method. */
6167static int hlua_http_req_set_meth(lua_State *L)
6168{
6169 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
6170 size_t name_len;
6171 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
6172
6173 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
6174 WILL_LJMP(lua_error(L));
6175
6176 lua_pushboolean(L, http_req_replace_stline(0, name, name_len, htxn->p, htxn->s) != -1);
6177 return 1;
6178}
6179
6180/* This function set the method. */
6181static int hlua_http_req_set_path(lua_State *L)
6182{
6183 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
6184 size_t name_len;
6185 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
6186
6187 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
6188 WILL_LJMP(lua_error(L));
6189
6190 lua_pushboolean(L, http_req_replace_stline(1, name, name_len, htxn->p, htxn->s) != -1);
6191 return 1;
6192}
6193
6194/* This function set the query-string. */
6195static int hlua_http_req_set_query(lua_State *L)
6196{
6197 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
6198 size_t name_len;
6199 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
6200
6201 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
6202 WILL_LJMP(lua_error(L));
6203
6204 /* Check length. */
6205 if (name_len > trash.size - 1) {
6206 lua_pushboolean(L, 0);
6207 return 1;
6208 }
6209
6210 /* Add the mark question as prefix. */
6211 chunk_reset(&trash);
6212 trash.area[trash.data++] = '?';
6213 memcpy(trash.area + trash.data, name, name_len);
6214 trash.data += name_len;
6215
6216 lua_pushboolean(L,
6217 http_req_replace_stline(2, trash.area, trash.data, htxn->p, htxn->s) != -1);
6218 return 1;
6219}
6220
6221/* This function set the uri. */
6222static int hlua_http_req_set_uri(lua_State *L)
6223{
6224 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
6225 size_t name_len;
6226 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
6227
6228 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
6229 WILL_LJMP(lua_error(L));
6230
6231 lua_pushboolean(L, http_req_replace_stline(3, name, name_len, htxn->p, htxn->s) != -1);
6232 return 1;
6233}
6234
6235/* This function set the response code & optionally reason. */
6236static int hlua_http_res_set_status(lua_State *L)
6237{
6238 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
6239 unsigned int code = MAY_LJMP(luaL_checkinteger(L, 2));
6240 const char *str = MAY_LJMP(luaL_optlstring(L, 3, NULL, NULL));
6241 const struct ist reason = ist2(str, (str ? strlen(str) : 0));
6242
6243 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
6244 WILL_LJMP(lua_error(L));
6245
6246 http_res_set_status(code, reason, htxn->s);
6247 return 0;
6248}
6249
6250/*
6251 *
6252 *
6253 * Class HTTPMessage
6254 *
6255 *
6256 */
6257
6258/* Returns a struct http_msg if the stack entry "ud" is a class HTTPMessage,
6259 * otherwise it throws an error.
6260 */
6261__LJMP static struct http_msg *hlua_checkhttpmsg(lua_State *L, int ud)
6262{
6263 return MAY_LJMP(hlua_checkudata(L, ud, class_http_msg_ref));
6264}
6265
6266/* Creates and pushes on the stack a HTTP object according with a current TXN.
6267 */
Christopher Faulet78c35472020-02-26 17:14:08 +01006268static int hlua_http_msg_new(lua_State *L, struct http_msg *msg)
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006269{
6270 /* Check stack size. */
6271 if (!lua_checkstack(L, 3))
6272 return 0;
6273
6274 lua_newtable(L);
6275 lua_pushlightuserdata(L, msg);
6276 lua_rawseti(L, -2, 0);
6277
6278 /* Create the "channel" field that contains the request channel object. */
6279 lua_pushstring(L, "channel");
6280 if (!hlua_channel_new(L, msg->chn))
6281 return 0;
6282 lua_rawset(L, -3);
6283
6284 /* Pop a class stream metatable and affect it to the table. */
6285 lua_rawgeti(L, LUA_REGISTRYINDEX, class_http_msg_ref);
6286 lua_setmetatable(L, -2);
6287
6288 return 1;
6289}
6290
6291/* Helper function returning a filter attached to the HTTP message at the
6292 * position <ud> in the stack, filling the current offset and length of the
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006293 * filter. If no filter is attached, NULL is returned and <offset> and <len> are
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006294 * filled with output and input length respectively.
6295 */
6296static struct filter *hlua_http_msg_filter(lua_State *L, int ud, struct http_msg *msg, size_t *offset, size_t *len)
6297{
6298 struct channel *chn = msg->chn;
6299 struct htx *htx = htxbuf(&chn->buf);
6300 struct filter *filter = NULL;
6301
6302 *offset = co_data(msg->chn);
6303 *len = htx->data - co_data(msg->chn);
6304
6305 if (lua_getfield(L, ud, "__filter") == LUA_TLIGHTUSERDATA) {
6306 filter = lua_touserdata (L, -1);
6307 if (msg->msg_state >= HTTP_MSG_DATA) {
6308 struct hlua_flt_ctx *flt_ctx = filter->ctx;
6309
6310 *offset = flt_ctx->cur_off[CHN_IDX(chn)];
6311 *len = flt_ctx->cur_len[CHN_IDX(chn)];
6312 }
6313 }
6314
6315 lua_pop(L, 1);
6316 return filter;
6317}
6318
6319/* Returns true if the channel attached to the HTTP message is the response
6320 * channel.
6321 */
6322__LJMP static int hlua_http_msg_is_resp(lua_State *L)
6323{
6324 struct http_msg *msg;
6325
6326 MAY_LJMP(check_args(L, 1, "is_resp"));
6327 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6328
6329 lua_pushboolean(L, !!(msg->chn->flags & CF_ISRESP));
6330 return 1;
6331}
6332
6333/* Returns an array containing the elements status-line of the HTTP message. It relies
6334 * on hlua_http_get_stline().
6335 */
6336__LJMP static int hlua_http_msg_get_stline(lua_State *L)
6337{
6338 struct http_msg *msg;
6339 struct htx *htx;
6340 struct htx_sl *sl;
6341
6342 MAY_LJMP(check_args(L, 1, "get_stline"));
6343 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6344
6345 if (msg->msg_state > HTTP_MSG_BODY)
6346 WILL_LJMP(lua_error(L));
6347
6348 htx = htxbuf(&msg->chn->buf);
6349 sl = http_get_stline(htx);
6350 if (!sl)
6351 return 0;
6352 return hlua_http_get_stline(L, sl);
6353}
6354
6355/* Returns an array containing all headers of the HTTP message. it relies on
6356 * hlua_http_get_headers().
6357 */
6358__LJMP static int hlua_http_msg_get_headers(lua_State *L)
6359{
6360 struct http_msg *msg;
6361
6362 MAY_LJMP(check_args(L, 1, "get_headers"));
6363 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6364
6365 if (msg->msg_state > HTTP_MSG_BODY)
6366 WILL_LJMP(lua_error(L));
6367
6368 return hlua_http_get_headers(L, msg);
6369}
6370
6371/* Deletes all occurrences of an header in the HTTP message matching on its
6372 * name. It relies on hlua_http_del_hdr().
6373 */
6374__LJMP static int hlua_http_msg_del_hdr(lua_State *L)
6375{
6376 struct http_msg *msg;
6377
6378 MAY_LJMP(check_args(L, 2, "del_header"));
6379 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6380
6381 if (msg->msg_state > HTTP_MSG_BODY)
6382 WILL_LJMP(lua_error(L));
6383
6384 return hlua_http_del_hdr(L, msg);
6385}
6386
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006387/* Matches the full value line of all occurrences of an header in the HTTP
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006388 * message given its name against a regex and replaces it if it matches. It
6389 * relies on hlua_http_rep_hdr().
6390 */
6391__LJMP static int hlua_http_msg_rep_hdr(lua_State *L)
6392{
6393 struct http_msg *msg;
6394
6395 MAY_LJMP(check_args(L, 4, "rep_header"));
6396 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6397
6398 if (msg->msg_state > HTTP_MSG_BODY)
6399 WILL_LJMP(lua_error(L));
6400
6401 return hlua_http_rep_hdr(L, msg, 1);
6402}
6403
Ilya Shipitsinbd6b4be2021-10-15 16:18:21 +05006404/* Matches all comma-separated values of all occurrences of an header in the HTTP
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006405 * message given its name against a regex and replaces it if it matches. It
6406 * relies on hlua_http_rep_hdr().
6407 */
6408__LJMP static int hlua_http_msg_rep_val(lua_State *L)
6409{
6410 struct http_msg *msg;
6411
6412 MAY_LJMP(check_args(L, 4, "rep_value"));
6413 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6414
6415 if (msg->msg_state > HTTP_MSG_BODY)
6416 WILL_LJMP(lua_error(L));
6417
6418 return hlua_http_rep_hdr(L, msg, 0);
6419}
6420
6421/* Add an header in the HTTP message. It relies on hlua_http_add_hdr() */
6422__LJMP static int hlua_http_msg_add_hdr(lua_State *L)
6423{
6424 struct http_msg *msg;
6425
6426 MAY_LJMP(check_args(L, 3, "add_header"));
6427 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6428
6429 if (msg->msg_state > HTTP_MSG_BODY)
6430 WILL_LJMP(lua_error(L));
6431
6432 return hlua_http_add_hdr(L, msg);
6433}
6434
6435/* Add an header in the HTTP message removing existing headers with the same
6436 * name. It relies on hlua_http_del_hdr() and hlua_http_add_hdr().
6437 */
6438__LJMP static int hlua_http_msg_set_hdr(lua_State *L)
6439{
6440 struct http_msg *msg;
6441
6442 MAY_LJMP(check_args(L, 3, "set_header"));
6443 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6444
6445 if (msg->msg_state > HTTP_MSG_BODY)
6446 WILL_LJMP(lua_error(L));
6447
6448 hlua_http_del_hdr(L, msg);
6449 return hlua_http_add_hdr(L, msg);
6450}
6451
6452/* Rewrites the request method. It relies on http_req_replace_stline(). */
6453__LJMP static int hlua_http_msg_set_meth(lua_State *L)
6454{
6455 struct stream *s;
6456 struct http_msg *msg;
6457 const char *name;
6458 size_t name_len;
6459
6460 MAY_LJMP(check_args(L, 2, "set_method"));
6461 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6462 name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
6463
6464 if ((msg->chn->flags & CF_ISRESP) || msg->msg_state > HTTP_MSG_BODY)
6465 WILL_LJMP(lua_error(L));
6466
6467 s = chn_strm(msg->chn);
6468 lua_pushboolean(L, http_req_replace_stline(0, name, name_len, s->be, s) != -1);
6469 return 1;
6470}
6471
6472/* Rewrites the request path. It relies on http_req_replace_stline(). */
6473__LJMP static int hlua_http_msg_set_path(lua_State *L)
6474{
6475 struct stream *s;
6476 struct http_msg *msg;
6477 const char *name;
6478 size_t name_len;
6479
6480 MAY_LJMP(check_args(L, 2, "set_path"));
6481 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6482 name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
6483
6484 if ((msg->chn->flags & CF_ISRESP) || msg->msg_state > HTTP_MSG_BODY)
6485 WILL_LJMP(lua_error(L));
6486
6487 s = chn_strm(msg->chn);
6488 lua_pushboolean(L, http_req_replace_stline(1, name, name_len, s->be, s) != -1);
6489 return 1;
6490}
6491
6492/* Rewrites the request query-string. It relies on http_req_replace_stline(). */
6493__LJMP static int hlua_http_msg_set_query(lua_State *L)
6494{
6495 struct stream *s;
6496 struct http_msg *msg;
6497 const char *name;
6498 size_t name_len;
6499
6500 MAY_LJMP(check_args(L, 2, "set_query"));
6501 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6502 name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
6503
6504 if ((msg->chn->flags & CF_ISRESP) || msg->msg_state > HTTP_MSG_BODY)
6505 WILL_LJMP(lua_error(L));
6506
6507 /* Check length. */
6508 if (name_len > trash.size - 1) {
6509 lua_pushboolean(L, 0);
6510 return 1;
6511 }
6512
6513 /* Add the mark question as prefix. */
6514 chunk_reset(&trash);
6515 trash.area[trash.data++] = '?';
6516 memcpy(trash.area + trash.data, name, name_len);
6517 trash.data += name_len;
6518
6519 s = chn_strm(msg->chn);
6520 lua_pushboolean(L, http_req_replace_stline(2, trash.area, trash.data, s->be, s) != -1);
6521 return 1;
6522}
6523
6524/* Rewrites the request URI. It relies on http_req_replace_stline(). */
6525__LJMP static int hlua_http_msg_set_uri(lua_State *L)
6526{
6527 struct stream *s;
6528 struct http_msg *msg;
6529 const char *name;
6530 size_t name_len;
6531
6532 MAY_LJMP(check_args(L, 2, "set_uri"));
6533 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6534 name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
6535
6536 if ((msg->chn->flags & CF_ISRESP) || msg->msg_state > HTTP_MSG_BODY)
6537 WILL_LJMP(lua_error(L));
6538
6539 s = chn_strm(msg->chn);
6540 lua_pushboolean(L, http_req_replace_stline(3, name, name_len, s->be, s) != -1);
6541 return 1;
6542}
6543
6544/* Rewrites the response status code. It relies on http_res_set_status(). */
6545__LJMP static int hlua_http_msg_set_status(lua_State *L)
6546{
6547 struct http_msg *msg;
6548 unsigned int code;
6549 const char *reason;
6550 size_t reason_len;
6551
6552 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6553 code = MAY_LJMP(luaL_checkinteger(L, 2));
6554 reason = MAY_LJMP(luaL_optlstring(L, 3, NULL, &reason_len));
6555
6556 if (!(msg->chn->flags & CF_ISRESP) || msg->msg_state > HTTP_MSG_BODY)
6557 WILL_LJMP(lua_error(L));
6558
6559 lua_pushboolean(L, http_res_set_status(code, ist2(reason, reason_len), chn_strm(msg->chn)) != -1);
6560 return 1;
6561}
6562
6563/* Returns true if the HTTP message is full. */
6564__LJMP static int hlua_http_msg_is_full(lua_State *L)
6565{
6566 struct http_msg *msg;
6567
6568 MAY_LJMP(check_args(L, 1, "is_full"));
6569 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6570 lua_pushboolean(L, channel_full(msg->chn, 0));
6571 return 1;
6572}
6573
6574/* Returns true if the HTTP message may still receive data. */
6575__LJMP static int hlua_http_msg_may_recv(lua_State *L)
6576{
6577 struct http_msg *msg;
6578 struct htx *htx;
6579
6580 MAY_LJMP(check_args(L, 1, "may_recv"));
6581 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6582 htx = htxbuf(&msg->chn->buf);
6583 lua_pushboolean(L, (htx_expect_more(htx) && !channel_input_closed(msg->chn) && channel_may_recv(msg->chn)));
6584 return 1;
6585}
6586
6587/* Returns true if the HTTP message EOM was received */
6588__LJMP static int hlua_http_msg_is_eom(lua_State *L)
6589{
6590 struct http_msg *msg;
6591 struct htx *htx;
6592
6593 MAY_LJMP(check_args(L, 1, "may_recv"));
6594 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6595 htx = htxbuf(&msg->chn->buf);
6596 lua_pushboolean(L, !htx_expect_more(htx));
6597 return 1;
6598}
6599
6600/* Returns the number of bytes available in the input side of the HTTP
6601 * message. This function never fails.
6602 */
6603__LJMP static int hlua_http_msg_get_in_len(lua_State *L)
6604{
6605 struct http_msg *msg;
Christopher Fauleteae8afa2020-02-26 17:15:48 +01006606 size_t output, input;
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006607
6608 MAY_LJMP(check_args(L, 1, "input"));
6609 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
Christopher Fauleteae8afa2020-02-26 17:15:48 +01006610 hlua_http_msg_filter(L, 1, msg, &output, &input);
6611 lua_pushinteger(L, input);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006612 return 1;
6613}
6614
6615/* Returns the number of bytes available in the output side of the HTTP
6616 * message. This function never fails.
6617 */
6618__LJMP static int hlua_http_msg_get_out_len(lua_State *L)
6619{
6620 struct http_msg *msg;
Christopher Fauleteae8afa2020-02-26 17:15:48 +01006621 size_t output, input;
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006622
6623 MAY_LJMP(check_args(L, 1, "output"));
6624 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
Christopher Fauleteae8afa2020-02-26 17:15:48 +01006625 hlua_http_msg_filter(L, 1, msg, &output, &input);
6626 lua_pushinteger(L, output);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006627 return 1;
6628}
6629
6630/* Copies at most <len> bytes of DATA blocks from the HTTP message <msg>
6631 * starting at the offset <offset> and put it in a string LUA variables. It
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006632 * returns the built string length. It stops on the first non-DATA HTX
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006633 * block. This function is called during the payload filtering, so the headers
6634 * are already scheduled for output (from the filter point of view).
6635 */
6636static int _hlua_http_msg_dup(struct http_msg *msg, lua_State *L, size_t offset, size_t len)
6637{
6638 struct htx *htx = htxbuf(&msg->chn->buf);
6639 struct htx_blk *blk;
6640 struct htx_ret htxret;
6641 luaL_Buffer b;
6642 int ret = 0;
6643
6644 luaL_buffinit(L, &b);
6645 htxret = htx_find_offset(htx, offset);
6646 for (blk = htxret.blk, offset = htxret.ret; blk && len; blk = htx_get_next_blk(htx, blk)) {
6647 enum htx_blk_type type = htx_get_blk_type(blk);
6648 struct ist v;
6649
6650 switch (type) {
6651 case HTX_BLK_UNUSED:
6652 break;
6653
6654 case HTX_BLK_DATA:
6655 v = htx_get_blk_value(htx, blk);
Tim Duesterhusb113b5c2021-09-15 13:58:44 +02006656 v = istadv(v, offset);
Tim Duesterhus2471f5c2021-11-08 09:05:01 +01006657 v = isttrim(v, len);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006658
6659 luaL_addlstring(&b, v.ptr, v.len);
6660 ret += v.len;
6661 break;
6662
6663 default:
vishnu0af4bd72021-10-24 06:46:24 +05306664 if (!ret)
6665 goto no_data;
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006666 goto end;
6667 }
6668 offset = 0;
6669 }
6670
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006671end:
vishnu0af4bd72021-10-24 06:46:24 +05306672 if (!ret && (htx->flags & HTX_FL_EOM))
6673 goto no_data;
6674 luaL_pushresult(&b);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006675 return ret;
vishnu0af4bd72021-10-24 06:46:24 +05306676
6677 no_data:
6678 /* Remove the empty string and push nil on the stack */
6679 lua_pop(L, 1);
6680 lua_pushnil(L);
6681 return 0;
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006682}
6683
6684/* Copies the string <str> to the HTTP message <msg> at the offset
6685 * <offset>. This function returns -1 if data cannot be copied. Otherwise, it
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006686 * returns the amount of data written. This function is responsible to update
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006687 * the filter context.
6688 */
6689static int _hlua_http_msg_insert(struct http_msg *msg, struct filter *filter, struct ist str, size_t offset)
6690{
6691 struct htx *htx = htx_from_buf(&msg->chn->buf);
6692 struct htx_ret htxret;
6693 int /*max, */ret = 0;
6694
6695 /* Nothing to do, just return */
6696 if (unlikely(istlen(str) == 0))
6697 goto end;
6698
6699 if (istlen(str) > htx_free_data_space(htx)) {
6700 ret = -1;
6701 goto end;
6702 }
6703
6704 htxret = htx_find_offset(htx, offset);
6705 if (!htxret.blk || htx_get_blk_type(htxret.blk) != HTX_BLK_DATA) {
6706 if (!htx_add_last_data(htx, str))
6707 goto end;
6708 }
6709 else {
6710 struct ist v = htx_get_blk_value(htx, htxret.blk);
6711 v.ptr += htxret.ret;
6712 v.len = 0;
6713 if (!htx_replace_blk_value(htx, htxret.blk, v, str))
6714 goto end;
6715 }
6716 ret = str.len;
6717 if (ret) {
6718 struct hlua_flt_ctx *flt_ctx = filter->ctx;
6719 flt_update_offsets(filter, msg->chn, ret);
6720 flt_ctx->cur_len[CHN_IDX(msg->chn)] += ret;
6721 }
6722
6723 end:
6724 htx_to_buf(htx, &msg->chn->buf);
6725 return ret;
6726}
6727
6728/* Helper function removing at most <len> bytes of DATA blocks at the absolute
6729 * position <offset>. It stops on the first non-DATA HTX block. This function is
6730 * called during the payload filtering, so the headers are already scheduled for
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006731 * output (from the filter point of view). This function is responsible to
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006732 * update the filter context.
6733 */
6734static void _hlua_http_msg_delete(struct http_msg *msg, struct filter *filter, size_t offset, size_t len)
6735{
6736 struct hlua_flt_ctx *flt_ctx = filter->ctx;
6737 struct htx *htx = htx_from_buf(&msg->chn->buf);
6738 struct htx_blk *blk;
6739 struct htx_ret htxret;
6740 size_t ret = 0;
6741
6742 /* Be sure <len> is always the amount of DATA to remove */
6743 if (htx->data == offset+len && htx_get_tail_type(htx) == HTX_BLK_DATA) {
Aurelien DARRAGONbcbcf982022-09-28 19:08:15 +02006744 /* When htx tail type == HTX_BLK_DATA, no need to take care
6745 * of special blocks like HTX_BLK_EOT.
6746 * We simply truncate after offset
6747 * (truncate targeted blk and discard the following ones)
6748 */
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006749 htx_truncate(htx, offset);
6750 ret = len;
6751 goto end;
6752 }
6753
6754 htxret = htx_find_offset(htx, offset);
6755 blk = htxret.blk;
6756 if (htxret.ret) {
Aurelien DARRAGONbcbcf982022-09-28 19:08:15 +02006757 /* dealing with offset: we need to trim targeted blk */
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006758 struct ist v;
6759
6760 if (htx_get_blk_type(blk) != HTX_BLK_DATA)
6761 goto end;
Aurelien DARRAGONbcbcf982022-09-28 19:08:15 +02006762
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006763 v = htx_get_blk_value(htx, blk);
Tim Duesterhusa029d782022-10-08 12:33:18 +02006764 v = istadv(v, htxret.ret);
Aurelien DARRAGONbcbcf982022-09-28 19:08:15 +02006765
Tim Duesterhus2471f5c2021-11-08 09:05:01 +01006766 v = isttrim(v, len);
Aurelien DARRAGONbcbcf982022-09-28 19:08:15 +02006767 /* trimming data in blk: discard everything after the offset
6768 * (replace 'v' with 'IST_NULL')
6769 */
Tim Duesterhusb113b5c2021-09-15 13:58:44 +02006770 blk = htx_replace_blk_value(htx, blk, v, IST_NULL);
Aurelien DARRAGONbcbcf982022-09-28 19:08:15 +02006771 if (blk && v.len < len) {
6772 /* In this case, caller wants to keep removing data,
6773 * but we need to spare current blk
6774 * because it was already trimmed
6775 */
6776 blk = htx_get_next_blk(htx, blk);
6777 }
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006778 len -= v.len;
6779 ret += v.len;
6780 }
6781
6782
6783 while (blk && len) {
Aurelien DARRAGONbcbcf982022-09-28 19:08:15 +02006784 /* there is more data that needs to be discarded */
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006785 enum htx_blk_type type = htx_get_blk_type(blk);
6786 uint32_t sz = htx_get_blksz(blk);
6787
6788 switch (type) {
6789 case HTX_BLK_UNUSED:
6790 break;
6791
6792 case HTX_BLK_DATA:
6793 if (len < sz) {
Aurelien DARRAGONbcbcf982022-09-28 19:08:15 +02006794 /* don't discard whole blk, only part of it
6795 * (from the beginning)
6796 */
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006797 htx_cut_data_blk(htx, blk, len);
6798 ret += len;
6799 goto end;
6800 }
6801 break;
6802
6803 default:
Aurelien DARRAGONbcbcf982022-09-28 19:08:15 +02006804 /* HTX_BLK_EOT blk won't be removed */
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006805 goto end;
6806 }
6807
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006808 /* Remove all the data block */
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006809 len -= sz;
6810 ret += sz;
6811 blk = htx_remove_blk(htx, blk);
6812 }
6813
6814end:
6815 flt_update_offsets(filter, msg->chn, -ret);
6816 flt_ctx->cur_len[CHN_IDX(msg->chn)] -= ret;
6817 /* WARNING: we don't call htx_to_buf() on purpose, because we don't want
6818 * to loose the EOM flag if the message is empty.
6819 */
6820}
6821
6822/* Copies input data found in an HTTP message. Unlike the channel function used
6823 * to duplicate raw data, this one can only be called inside a filter, from
6824 * http_payload callback. So it cannot yield. An exception is returned if it is
6825 * called from another callback. If nothing was copied, a nil value is pushed on
6826 * the stack.
6827 */
6828__LJMP static int hlua_http_msg_get_body(lua_State *L)
6829{
6830 struct http_msg *msg;
6831 struct filter *filter;
6832 size_t output, input;
6833 int offset, len;
6834
6835 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
6836 WILL_LJMP(luaL_error(L, "'data' expects at most 2 arguments"));
6837 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6838
6839 if (msg->msg_state < HTTP_MSG_DATA)
6840 WILL_LJMP(lua_error(L));
6841
6842 filter = hlua_http_msg_filter(L, 1, msg, &output, &input);
6843 if (!filter || !hlua_filter_from_payload(filter))
6844 WILL_LJMP(lua_error(L));
6845
6846 if (!ci_data(msg->chn) && channel_input_closed(msg->chn)) {
6847 lua_pushnil(L);
6848 return 1;
6849 }
6850
6851 offset = output;
6852 if (lua_gettop(L) > 1) {
6853 offset = MAY_LJMP(luaL_checkinteger(L, 2));
6854 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02006855 offset = MAX(0, (int)input + offset);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006856 offset += output;
6857 if (offset < output || offset > input + output) {
6858 lua_pushfstring(L, "offset out of range.");
6859 WILL_LJMP(lua_error(L));
6860 }
6861 }
6862 len = output + input - offset;
6863 if (lua_gettop(L) == 3) {
6864 len = MAY_LJMP(luaL_checkinteger(L, 3));
6865 if (!len)
6866 goto dup;
6867 if (len == -1)
6868 len = global.tune.bufsize;
6869 if (len < 0) {
6870 lua_pushfstring(L, "length out of range.");
6871 WILL_LJMP(lua_error(L));
6872 }
6873 }
6874
6875 dup:
6876 _hlua_http_msg_dup(msg, L, offset, len);
6877 return 1;
6878}
6879
6880/* Appends a string to the HTTP message, after all existing DATA blocks but
6881 * before the trailers, if any. It returns the amount of data written or -1 if
6882 * nothing was copied. Unlike the channel function used to append data, this one
6883 * can only be called inside a filter, from http_payload callback. So it cannot
6884 * yield. An exception is returned if it is called from another callback.
6885 */
6886__LJMP static int hlua_http_msg_append(lua_State *L)
6887{
6888 struct http_msg *msg;
6889 struct filter *filter;
6890 const char *str;
6891 size_t offset, len, sz;
6892 int ret;
6893
6894 MAY_LJMP(check_args(L, 2, "append"));
6895 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6896
6897 if (msg->msg_state < HTTP_MSG_DATA)
6898 WILL_LJMP(lua_error(L));
6899
6900 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
6901 filter = hlua_http_msg_filter(L, 1, msg, &offset, &len);
6902 if (!filter || !hlua_filter_from_payload(filter))
6903 WILL_LJMP(lua_error(L));
6904
6905 ret = _hlua_http_msg_insert(msg, filter, ist2(str, sz), offset+len);
6906 lua_pushinteger(L, ret);
6907 return 1;
6908}
6909
6910/* Prepends a string to the HTTP message, before all existing DATA blocks. It
6911 * returns the amount of data written or -1 if nothing was copied. Unlike the
6912 * channel function used to prepend data, this one can only be called inside a
6913 * filter, from http_payload callback. So it cannot yield. An exception is
6914 * returned if it is called from another callback.
6915 */
6916__LJMP static int hlua_http_msg_prepend(lua_State *L)
6917{
6918 struct http_msg *msg;
6919 struct filter *filter;
6920 const char *str;
6921 size_t offset, len, sz;
6922 int ret;
6923
6924 MAY_LJMP(check_args(L, 2, "prepend"));
6925 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006926
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006927 if (msg->msg_state < HTTP_MSG_DATA)
6928 WILL_LJMP(lua_error(L));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006929
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006930 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
6931 filter = hlua_http_msg_filter(L, 1, msg, &offset, &len);
6932 if (!filter || !hlua_filter_from_payload(filter))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006933 WILL_LJMP(lua_error(L));
6934
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006935 ret = _hlua_http_msg_insert(msg, filter, ist2(str, sz), offset);
6936 lua_pushinteger(L, ret);
6937 return 1;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006938}
6939
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006940/* Inserts a string to the HTTP message at a given offset. By default the string
6941 * is appended at the end of DATA blocks. It returns the amount of data written
6942 * or -1 if nothing was copied. Unlike the channel function used to insert data,
6943 * this one can only be called inside a filter, from http_payload callback. So
6944 * it cannot yield. An exception is returned if it is called from another
6945 * callback.
6946 */
6947__LJMP static int hlua_http_msg_insert_data(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006948{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006949 struct http_msg *msg;
6950 struct filter *filter;
6951 const char *str;
6952 size_t input, output, sz;
6953 int offset;
6954 int ret;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006955
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006956 if (lua_gettop(L) < 2 || lua_gettop(L) > 3)
6957 WILL_LJMP(luaL_error(L, "'insert' expects at least 1 argument and at most 2 arguments"));
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006958 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006959
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006960 if (msg->msg_state < HTTP_MSG_DATA)
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006961 WILL_LJMP(lua_error(L));
6962
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006963 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
Aurelien DARRAGON7fdba0a2022-09-28 16:03:45 +02006964 filter = hlua_http_msg_filter(L, 1, msg, &output, &input);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006965 if (!filter || !hlua_filter_from_payload(filter))
6966 WILL_LJMP(lua_error(L));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006967
Aurelien DARRAGON7fdba0a2022-09-28 16:03:45 +02006968 offset = output;
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006969 if (lua_gettop(L) > 2) {
6970 offset = MAY_LJMP(luaL_checkinteger(L, 3));
6971 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02006972 offset = MAX(0, (int)input + offset);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006973 offset += output;
Aurelien DARRAGON7fdba0a2022-09-28 16:03:45 +02006974 if (offset > output + input) {
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006975 lua_pushfstring(L, "offset out of range.");
6976 WILL_LJMP(lua_error(L));
6977 }
6978 }
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006979
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006980 ret = _hlua_http_msg_insert(msg, filter, ist2(str, sz), offset);
6981 lua_pushinteger(L, ret);
6982 return 1;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006983}
6984
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006985/* Removes a given amount of data from the HTTP message at a given offset. By
6986 * default all DATA blocks are removed. It returns the amount of data
6987 * removed. Unlike the channel function used to remove data, this one can only
6988 * be called inside a filter, from http_payload callback. So it cannot yield. An
6989 * exception is returned if it is called from another callback.
6990 */
6991__LJMP static int hlua_http_msg_del_data(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006992{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006993 struct http_msg *msg;
6994 struct filter *filter;
6995 size_t input, output;
6996 int offset, len;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006997
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006998 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
Boyang Lie0c54352022-05-10 17:47:23 +00006999 WILL_LJMP(luaL_error(L, "'remove' expects at most 2 arguments"));
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007000 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007001
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007002 if (msg->msg_state < HTTP_MSG_DATA)
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02007003 WILL_LJMP(lua_error(L));
7004
Aurelien DARRAGONd7c71b02022-09-28 15:52:18 +02007005 filter = hlua_http_msg_filter(L, 1, msg, &output, &input);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007006 if (!filter || !hlua_filter_from_payload(filter))
7007 WILL_LJMP(lua_error(L));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007008
Aurelien DARRAGONd7c71b02022-09-28 15:52:18 +02007009 offset = output;
Boyang Lie0c54352022-05-10 17:47:23 +00007010 if (lua_gettop(L) > 1) {
7011 offset = MAY_LJMP(luaL_checkinteger(L, 2));
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007012 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02007013 offset = MAX(0, (int)input + offset);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007014 offset += output;
Aurelien DARRAGONd7c71b02022-09-28 15:52:18 +02007015 if (offset > output + input) {
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007016 lua_pushfstring(L, "offset out of range.");
7017 WILL_LJMP(lua_error(L));
7018 }
7019 }
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02007020
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007021 len = output + input - offset;
Boyang Lie0c54352022-05-10 17:47:23 +00007022 if (lua_gettop(L) == 3) {
7023 len = MAY_LJMP(luaL_checkinteger(L, 3));
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007024 if (!len)
7025 goto end;
7026 if (len == -1)
7027 len = output + input - offset;
7028 if (len < 0 || offset + len > output + input) {
7029 lua_pushfstring(L, "length out of range.");
7030 WILL_LJMP(lua_error(L));
7031 }
7032 }
7033
7034 _hlua_http_msg_delete(msg, filter, offset, len);
7035
7036 end:
7037 lua_pushinteger(L, len);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007038 return 1;
7039}
7040
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05007041/* Replaces a given amount of data at the given offset by a string. By default,
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007042 * all remaining data are removed, accordingly to the filter context. It returns
7043 * the amount of data written or -1 if nothing was copied. Unlike the channel
7044 * function used to replace data, this one can only be called inside a filter,
7045 * from http_payload callback. So it cannot yield. An exception is returned if
7046 * it is called from another callback.
7047 */
7048__LJMP static int hlua_http_msg_set_data(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007049{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007050 struct http_msg *msg;
7051 struct filter *filter;
7052 struct htx *htx;
7053 const char *str;
7054 size_t input, output, sz;
7055 int offset, len;
7056 int ret;
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02007057
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007058 if (lua_gettop(L) < 2 || lua_gettop(L) > 4)
7059 WILL_LJMP(luaL_error(L, "'set' expects at least 1 argument and at most 3 arguments"));
7060 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
7061
7062 if (msg->msg_state < HTTP_MSG_DATA)
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02007063 WILL_LJMP(lua_error(L));
7064
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007065 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
7066 filter = hlua_http_msg_filter(L, 1, msg, &output, &input);
7067 if (!filter || !hlua_filter_from_payload(filter))
7068 WILL_LJMP(lua_error(L));
7069
7070 offset = output;
7071 if (lua_gettop(L) > 2) {
7072 offset = MAY_LJMP(luaL_checkinteger(L, 3));
7073 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02007074 offset = MAX(0, (int)input + offset);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007075 offset += output;
7076 if (offset < output || offset > input + output) {
7077 lua_pushfstring(L, "offset out of range.");
7078 WILL_LJMP(lua_error(L));
7079 }
7080 }
7081
7082 len = output + input - offset;
7083 if (lua_gettop(L) == 4) {
7084 len = MAY_LJMP(luaL_checkinteger(L, 4));
7085 if (!len)
7086 goto set;
7087 if (len == -1)
7088 len = output + input - offset;
7089 if (len < 0 || offset + len > output + input) {
7090 lua_pushfstring(L, "length out of range.");
7091 WILL_LJMP(lua_error(L));
7092 }
7093 }
7094
7095 set:
7096 /* Be sure we can copied the string once input data will be removed. */
7097 htx = htx_from_buf(&msg->chn->buf);
7098 if (sz > htx_free_data_space(htx) + len)
7099 lua_pushinteger(L, -1);
7100 else {
7101 _hlua_http_msg_delete(msg, filter, offset, len);
7102 ret = _hlua_http_msg_insert(msg, filter, ist2(str, sz), offset);
7103 lua_pushinteger(L, ret);
7104 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007105 return 1;
7106}
7107
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007108/* Prepends data into an HTTP message and forward it, from the filter point of
7109 * view. It returns the amount of data written or -1 if nothing was sent. Unlike
7110 * the channel function used to send data, this one can only be called inside a
7111 * filter, from http_payload callback. So it cannot yield. An exception is
7112 * returned if it is called from another callback.
7113 */
7114__LJMP static int hlua_http_msg_send(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007115{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007116 struct http_msg *msg;
7117 struct filter *filter;
7118 struct htx *htx;
7119 const char *str;
7120 size_t offset, len, sz;
7121 int ret;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007122
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007123 MAY_LJMP(check_args(L, 2, "send"));
7124 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
7125
7126 if (msg->msg_state < HTTP_MSG_DATA)
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02007127 WILL_LJMP(lua_error(L));
7128
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007129 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
7130 filter = hlua_http_msg_filter(L, 1, msg, &offset, &len);
7131 if (!filter || !hlua_filter_from_payload(filter))
7132 WILL_LJMP(lua_error(L));
7133
7134 /* Return an error if the channel's output is closed */
7135 if (unlikely(channel_output_closed(msg->chn))) {
7136 lua_pushinteger(L, -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007137 return 1;
7138 }
7139
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007140 htx = htx_from_buf(&msg->chn->buf);
7141 if (sz > htx_free_data_space(htx)) {
7142 lua_pushinteger(L, -1);
7143 return 1;
7144 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007145
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007146 ret = _hlua_http_msg_insert(msg, filter, ist2(str, sz), offset);
7147 if (ret > 0) {
7148 struct hlua_flt_ctx *flt_ctx = filter->ctx;
7149
7150 FLT_OFF(filter, msg->chn) += ret;
7151 flt_ctx->cur_len[CHN_IDX(msg->chn)] -= ret;
7152 flt_ctx->cur_off[CHN_IDX(msg->chn)] += ret;
7153 }
7154
7155 lua_pushinteger(L, ret);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007156 return 1;
7157}
7158
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007159/* Forwards a given amount of bytes. It return -1 if the channel's output is
7160 * closed. Otherwise, it returns the number of bytes forwarded. Unlike the
7161 * channel function used to forward data, this one can only be called inside a
7162 * filter, from http_payload callback. So it cannot yield. An exception is
7163 * returned if it is called from another callback. All other functions deal with
7164 * DATA block, this one not.
7165*/
7166__LJMP static int hlua_http_msg_forward(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007167{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007168 struct http_msg *msg;
7169 struct filter *filter;
7170 size_t offset, len;
7171 int fwd, ret = 0;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007172
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007173 MAY_LJMP(check_args(L, 2, "forward"));
7174 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
7175
7176 if (msg->msg_state < HTTP_MSG_DATA)
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02007177 WILL_LJMP(lua_error(L));
7178
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007179 fwd = MAY_LJMP(luaL_checkinteger(L, 2));
7180 filter = hlua_http_msg_filter(L, 1, msg, &offset, &len);
7181 if (!filter || !hlua_filter_from_payload(filter))
7182 WILL_LJMP(lua_error(L));
7183
7184 /* Nothing to do, just return */
7185 if (!fwd)
7186 goto end;
7187
7188 /* Return an error if the channel's output is closed */
7189 if (unlikely(channel_output_closed(msg->chn))) {
7190 ret = -1;
7191 goto end;
7192 }
7193
7194 ret = fwd;
7195 if (ret > len)
7196 ret = len;
7197
7198 if (ret) {
7199 struct hlua_flt_ctx *flt_ctx = filter->ctx;
7200
7201 FLT_OFF(filter, msg->chn) += ret;
7202 flt_ctx->cur_off[CHN_IDX(msg->chn)] += ret;
7203 flt_ctx->cur_len[CHN_IDX(msg->chn)] -= ret;
7204 }
7205
7206 end:
7207 lua_pushinteger(L, ret);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007208 return 1;
7209}
7210
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007211/* Set EOM flag on the HTX message.
7212 *
7213 * NOTE: Not sure it is a good idea to manipulate this flag but for now I don't
7214 * really know how to do without this feature.
7215 */
7216__LJMP static int hlua_http_msg_set_eom(lua_State *L)
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02007217{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007218 struct http_msg *msg;
7219 struct htx *htx;
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02007220
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007221 MAY_LJMP(check_args(L, 1, "set_eom"));
7222 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
7223 htx = htxbuf(&msg->chn->buf);
7224 htx->flags |= HTX_FL_EOM;
7225 return 0;
7226}
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02007227
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007228/* Unset EOM flag on the HTX message.
7229 *
7230 * NOTE: Not sure it is a good idea to manipulate this flag but for now I don't
7231 * really know how to do without this feature.
7232 */
7233__LJMP static int hlua_http_msg_unset_eom(lua_State *L)
7234{
7235 struct http_msg *msg;
7236 struct htx *htx;
7237
7238 MAY_LJMP(check_args(L, 1, "set_eom"));
7239 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
7240 htx = htxbuf(&msg->chn->buf);
7241 htx->flags &= ~HTX_FL_EOM;
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02007242 return 0;
7243}
7244
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007245/*
7246 *
7247 *
William Lallemand3956c4e2021-09-21 16:25:15 +02007248 * Class HTTPClient
7249 *
7250 *
7251 */
7252__LJMP static struct hlua_httpclient *hlua_checkhttpclient(lua_State *L, int ud)
7253{
7254 return MAY_LJMP(hlua_checkudata(L, ud, class_httpclient_ref));
7255}
7256
William Lallemandf77f1de2021-09-28 19:10:38 +02007257
7258/* stops the httpclient and ask it to kill itself */
7259__LJMP static int hlua_httpclient_gc(lua_State *L)
7260{
7261 struct hlua_httpclient *hlua_hc;
7262
7263 MAY_LJMP(check_args(L, 1, "__gc"));
7264
7265 hlua_hc = MAY_LJMP(hlua_checkhttpclient(L, 1));
7266
Aurelien DARRAGON3ffbf382023-02-09 17:02:57 +01007267 if (MT_LIST_DELETE(&hlua_hc->by_hlua)) {
7268 /* we won the race against hlua_httpclient_destroy_all() */
William Lallemandbb581422022-10-20 10:57:28 +02007269 httpclient_stop_and_destroy(hlua_hc->hc);
Aurelien DARRAGON3ffbf382023-02-09 17:02:57 +01007270 hlua_hc->hc = NULL;
7271 }
William Lallemandf77f1de2021-09-28 19:10:38 +02007272
7273 return 0;
7274}
7275
7276
William Lallemand3956c4e2021-09-21 16:25:15 +02007277__LJMP static int hlua_httpclient_new(lua_State *L)
7278{
7279 struct hlua_httpclient *hlua_hc;
7280 struct hlua *hlua;
7281
7282 /* Get hlua struct, or NULL if we execute from main lua state */
7283 hlua = hlua_gethlua(L);
7284 if (!hlua)
7285 return 0;
7286
7287 /* Check stack size. */
7288 if (!lua_checkstack(L, 3)) {
7289 hlua_pusherror(L, "httpclient: full stack");
7290 goto err;
7291 }
7292 /* Create the object: obj[0] = userdata. */
7293 lua_newtable(L);
7294 hlua_hc = MAY_LJMP(lua_newuserdata(L, sizeof(*hlua_hc)));
7295 lua_rawseti(L, -2, 0);
7296 memset(hlua_hc, 0, sizeof(*hlua_hc));
7297
7298 hlua_hc->hc = httpclient_new(hlua, 0, IST_NULL);
7299 if (!hlua_hc->hc)
7300 goto err;
7301
Aurelien DARRAGON3ffbf382023-02-09 17:02:57 +01007302 MT_LIST_APPEND(&hlua->hc_list, &hlua_hc->by_hlua);
William Lallemandbb581422022-10-20 10:57:28 +02007303
William Lallemand3956c4e2021-09-21 16:25:15 +02007304 /* Pop a class stream metatable and affect it to the userdata. */
7305 lua_rawgeti(L, LUA_REGISTRYINDEX, class_httpclient_ref);
7306 lua_setmetatable(L, -2);
7307
7308 return 1;
7309
7310 err:
7311 WILL_LJMP(lua_error(L));
7312 return 0;
7313}
7314
7315
7316/*
7317 * Callback of the httpclient, this callback wakes the lua task up, once the
7318 * httpclient receives some data
7319 *
7320 */
7321
William Lallemandbd5739e2021-10-28 15:41:38 +02007322static void hlua_httpclient_cb(struct httpclient *hc)
William Lallemand3956c4e2021-09-21 16:25:15 +02007323{
7324 struct hlua *hlua = hc->caller;
7325
7326 if (!hlua || !hlua->task)
7327 return;
7328
7329 task_wakeup(hlua->task, TASK_WOKEN_MSG);
7330}
7331
7332/*
William Lallemandd7df73a2021-09-23 17:54:00 +02007333 * Fill the lua stack with headers from the httpclient response
7334 * This works the same way as the hlua_http_get_headers() function
7335 */
7336__LJMP static int hlua_httpclient_get_headers(lua_State *L, struct hlua_httpclient *hlua_hc)
7337{
7338 struct http_hdr *hdr;
7339
7340 lua_newtable(L);
7341
William Lallemandef574b22021-10-05 16:19:31 +02007342 for (hdr = hlua_hc->hc->res.hdrs; hdr && isttest(hdr->n); hdr++) {
William Lallemandd7df73a2021-09-23 17:54:00 +02007343 struct ist n, v;
7344 int len;
7345
7346 n = hdr->n;
7347 v = hdr->v;
7348
7349 /* Check for existing entry:
7350 * assume that the table is on the top of the stack, and
7351 * push the key in the stack, the function lua_gettable()
7352 * perform the lookup.
7353 */
7354
7355 lua_pushlstring(L, n.ptr, n.len);
7356 lua_gettable(L, -2);
7357
7358 switch (lua_type(L, -1)) {
7359 case LUA_TNIL:
7360 /* Table not found, create it. */
7361 lua_pop(L, 1); /* remove the nil value. */
7362 lua_pushlstring(L, n.ptr, n.len); /* push the header name as key. */
7363 lua_newtable(L); /* create and push empty table. */
7364 lua_pushlstring(L, v.ptr, v.len); /* push header value. */
7365 lua_rawseti(L, -2, 0); /* index header value (pop it). */
7366 lua_rawset(L, -3); /* index new table with header name (pop the values). */
7367 break;
7368
7369 case LUA_TTABLE:
7370 /* Entry found: push the value in the table. */
7371 len = lua_rawlen(L, -1);
7372 lua_pushlstring(L, v.ptr, v.len); /* push header value. */
7373 lua_rawseti(L, -2, len+1); /* index header value (pop it). */
7374 lua_pop(L, 1); /* remove the table (it is stored in the main table). */
7375 break;
7376
7377 default:
7378 /* Other cases are errors. */
7379 hlua_pusherror(L, "internal error during the parsing of headers.");
7380 WILL_LJMP(lua_error(L));
7381 }
7382 }
7383 return 1;
7384}
7385
7386/*
William Lallemand746e6f32021-10-06 10:57:44 +02007387 * Allocate and return an array of http_hdr ist extracted from the <headers> lua table
7388 *
7389 * Caller must free the result
7390 */
7391struct http_hdr *hlua_httpclient_table_to_hdrs(lua_State *L)
7392{
7393 struct http_hdr hdrs[global.tune.max_http_hdr];
7394 struct http_hdr *result = NULL;
7395 uint32_t hdr_num = 0;
7396
7397 lua_pushnil(L);
7398 while (lua_next(L, -2) != 0) {
7399 struct ist name, value;
7400 const char *n, *v;
7401 size_t nlen, vlen;
7402
7403 if (!lua_isstring(L, -2) || !lua_istable(L, -1)) {
7404 /* Skip element if the key is not a string or if the value is not a table */
7405 goto next_hdr;
7406 }
7407
7408 n = lua_tolstring(L, -2, &nlen);
7409 name = ist2(n, nlen);
7410
7411 /* Loop on header's values */
7412 lua_pushnil(L);
7413 while (lua_next(L, -2)) {
7414 if (!lua_isstring(L, -1)) {
7415 /* Skip the value if it is not a string */
7416 goto next_value;
7417 }
7418
7419 v = lua_tolstring(L, -1, &vlen);
7420 value = ist2(v, vlen);
7421 name = ist2(n, nlen);
7422
7423 hdrs[hdr_num].n = istdup(name);
7424 hdrs[hdr_num].v = istdup(value);
7425
7426 hdr_num++;
7427
7428 next_value:
7429 lua_pop(L, 1);
7430 }
7431
7432 next_hdr:
7433 lua_pop(L, 1);
7434
7435 }
7436
7437 if (hdr_num) {
7438 /* alloc and copy the headers in the httpclient struct */
Tim Duesterhus16cc16d2021-11-06 15:14:45 +01007439 result = calloc((hdr_num + 1), sizeof(*result));
William Lallemand746e6f32021-10-06 10:57:44 +02007440 if (!result)
7441 goto skip_headers;
7442 memcpy(result, hdrs, sizeof(struct http_hdr) * (hdr_num + 1));
7443
7444 result[hdr_num].n = IST_NULL;
7445 result[hdr_num].v = IST_NULL;
7446 }
7447
7448skip_headers:
William Lallemand746e6f32021-10-06 10:57:44 +02007449
7450 return result;
7451}
7452
7453
William Lallemandbd5739e2021-10-28 15:41:38 +02007454/*
7455 * For each yield, checks if there is some data in the httpclient and push them
7456 * in the lua buffer, once the httpclient finished its job, push the result on
7457 * the stack
7458 */
7459__LJMP static int hlua_httpclient_rcv_yield(lua_State *L, int status, lua_KContext ctx)
7460{
7461 struct buffer *tr;
7462 int res;
7463 struct hlua *hlua = hlua_gethlua(L);
7464 struct hlua_httpclient *hlua_hc = hlua_checkhttpclient(L, 1);
7465
7466
7467 tr = get_trash_chunk();
7468
7469 res = httpclient_res_xfer(hlua_hc->hc, tr);
7470 luaL_addlstring(&hlua_hc->b, b_orig(tr), res);
7471
7472 if (!httpclient_data(hlua_hc->hc) && httpclient_ended(hlua_hc->hc)) {
7473
7474 luaL_pushresult(&hlua_hc->b);
7475 lua_settable(L, -3);
7476
7477 lua_pushstring(L, "status");
7478 lua_pushinteger(L, hlua_hc->hc->res.status);
7479 lua_settable(L, -3);
7480
7481
7482 lua_pushstring(L, "reason");
7483 lua_pushlstring(L, hlua_hc->hc->res.reason.ptr, hlua_hc->hc->res.reason.len);
7484 lua_settable(L, -3);
7485
7486 lua_pushstring(L, "headers");
7487 hlua_httpclient_get_headers(L, hlua_hc);
7488 lua_settable(L, -3);
7489
7490 return 1;
7491 }
7492
7493 if (httpclient_data(hlua_hc->hc))
7494 task_wakeup(hlua->task, TASK_WOKEN_MSG);
7495
7496 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_httpclient_rcv_yield, TICK_ETERNITY, 0));
7497
7498 return 0;
7499}
7500
7501/*
7502 * Call this when trying to stream a body during a request
7503 */
7504__LJMP static int hlua_httpclient_snd_yield(lua_State *L, int status, lua_KContext ctx)
7505{
7506 struct hlua *hlua;
7507 struct hlua_httpclient *hlua_hc = hlua_checkhttpclient(L, 1);
7508 const char *body_str = NULL;
7509 int ret;
7510 int end = 0;
7511 size_t buf_len;
7512 size_t to_send = 0;
7513
7514 hlua = hlua_gethlua(L);
7515
7516 if (!hlua || !hlua->task)
7517 WILL_LJMP(luaL_error(L, "The 'get' function is only allowed in "
7518 "'frontend', 'backend' or 'task'"));
7519
7520 ret = lua_getfield(L, -1, "body");
7521 if (ret != LUA_TSTRING)
7522 goto rcv;
7523
7524 body_str = lua_tolstring(L, -1, &buf_len);
7525 lua_pop(L, 1);
7526
Christopher Fauletfc591292022-01-12 14:46:03 +01007527 to_send = buf_len - hlua_hc->sent;
William Lallemandbd5739e2021-10-28 15:41:38 +02007528
7529 if ((hlua_hc->sent + to_send) >= buf_len)
7530 end = 1;
7531
7532 /* the end flag is always set since we are using the whole remaining size */
7533 hlua_hc->sent += httpclient_req_xfer(hlua_hc->hc, ist2(body_str + hlua_hc->sent, to_send), end);
7534
7535 if (buf_len > hlua_hc->sent) {
7536 /* still need to process the buffer */
7537 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_httpclient_snd_yield, TICK_ETERNITY, 0));
7538 } else {
7539 goto rcv;
7540 /* we sent the whole request buffer we can recv */
7541 }
7542 return 0;
7543
7544rcv:
7545
7546 /* we return a "res" object */
7547 lua_newtable(L);
7548
William Lallemandbd5739e2021-10-28 15:41:38 +02007549 lua_pushstring(L, "body");
William Lallemandd1187eb2021-11-02 10:40:06 +01007550 luaL_buffinit(L, &hlua_hc->b);
William Lallemandbd5739e2021-10-28 15:41:38 +02007551
William Lallemand933fe392021-11-04 09:45:58 +01007552 task_wakeup(hlua->task, TASK_WOKEN_MSG);
William Lallemandbd5739e2021-10-28 15:41:38 +02007553 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_httpclient_rcv_yield, TICK_ETERNITY, 0));
7554
7555 return 1;
7556}
William Lallemand746e6f32021-10-06 10:57:44 +02007557
William Lallemand3956c4e2021-09-21 16:25:15 +02007558/*
William Lallemanddc2cc902021-10-26 11:43:26 +02007559 * Send an HTTP request and wait for a response
William Lallemand3956c4e2021-09-21 16:25:15 +02007560 */
7561
William Lallemanddc2cc902021-10-26 11:43:26 +02007562__LJMP static int hlua_httpclient_send(lua_State *L, enum http_meth_t meth)
William Lallemand3956c4e2021-09-21 16:25:15 +02007563{
7564 struct hlua_httpclient *hlua_hc;
William Lallemand746e6f32021-10-06 10:57:44 +02007565 struct http_hdr *hdrs = NULL;
7566 struct http_hdr *hdrs_i = NULL;
William Lallemand3956c4e2021-09-21 16:25:15 +02007567 struct hlua *hlua;
William Lallemand746e6f32021-10-06 10:57:44 +02007568 const char *url_str = NULL;
William Lallemanddec25c32021-10-25 19:48:37 +02007569 const char *body_str = NULL;
Christopher Faulet380ae9c2022-10-14 14:57:04 +02007570 size_t buf_len = 0;
William Lallemand746e6f32021-10-06 10:57:44 +02007571 int ret;
William Lallemand3956c4e2021-09-21 16:25:15 +02007572
7573 hlua = hlua_gethlua(L);
7574
7575 if (!hlua || !hlua->task)
7576 WILL_LJMP(luaL_error(L, "The 'get' function is only allowed in "
7577 "'frontend', 'backend' or 'task'"));
7578
William Lallemand746e6f32021-10-06 10:57:44 +02007579 if (lua_gettop(L) != 2 || lua_type(L, -1) != LUA_TTABLE)
7580 WILL_LJMP(luaL_error(L, "'get' needs a table as argument"));
7581
William Lallemand4f4f2b72022-02-17 20:00:23 +01007582 hlua_hc = hlua_checkhttpclient(L, 1);
7583
William Lallemand7177a952022-03-03 15:33:12 +01007584 lua_pushnil(L); /* first key */
7585 while (lua_next(L, 2)) {
7586 if (strcmp(lua_tostring(L, -2), "dst") == 0) {
7587 if (httpclient_set_dst(hlua_hc->hc, lua_tostring(L, -1)) < 0)
7588 WILL_LJMP(luaL_error(L, "Can't use the 'dst' argument"));
William Lallemand4f4f2b72022-02-17 20:00:23 +01007589
William Lallemand7177a952022-03-03 15:33:12 +01007590 } else if (strcmp(lua_tostring(L, -2), "url") == 0) {
7591 if (lua_type(L, -1) != LUA_TSTRING)
7592 WILL_LJMP(luaL_error(L, "invalid parameter in 'url', must be a string"));
7593 url_str = lua_tostring(L, -1);
William Lallemand3956c4e2021-09-21 16:25:15 +02007594
William Lallemand7177a952022-03-03 15:33:12 +01007595 } else if (strcmp(lua_tostring(L, -2), "timeout") == 0) {
7596 if (lua_type(L, -1) != LUA_TNUMBER)
7597 WILL_LJMP(luaL_error(L, "invalid parameter in 'timeout', must be a number"));
7598 httpclient_set_timeout(hlua_hc->hc, lua_tointeger(L, -1));
William Lallemandb4a4ef62022-02-23 14:18:16 +01007599
William Lallemand7177a952022-03-03 15:33:12 +01007600 } else if (strcmp(lua_tostring(L, -2), "headers") == 0) {
7601 if (lua_type(L, -1) != LUA_TTABLE)
7602 WILL_LJMP(luaL_error(L, "invalid parameter in 'headers', must be a table"));
7603 hdrs = hlua_httpclient_table_to_hdrs(L);
William Lallemand79416cb2021-09-24 14:51:44 +02007604
William Lallemand7177a952022-03-03 15:33:12 +01007605 } else if (strcmp(lua_tostring(L, -2), "body") == 0) {
7606 if (lua_type(L, -1) != LUA_TSTRING)
7607 WILL_LJMP(luaL_error(L, "invalid parameter in 'body', must be a string"));
7608 body_str = lua_tolstring(L, -1, &buf_len);
William Lallemandbd5739e2021-10-28 15:41:38 +02007609
William Lallemand7177a952022-03-03 15:33:12 +01007610 } else {
7611 WILL_LJMP(luaL_error(L, "'%s' invalid parameter name", lua_tostring(L, -2)));
7612 }
7613 /* removes 'value'; keeps 'key' for next iteration */
7614 lua_pop(L, 1);
7615 }
William Lallemanddec25c32021-10-25 19:48:37 +02007616
William Lallemand746e6f32021-10-06 10:57:44 +02007617 if (!url_str) {
7618 WILL_LJMP(luaL_error(L, "'get' need a 'url' argument"));
7619 return 0;
7620 }
William Lallemand3956c4e2021-09-21 16:25:15 +02007621
William Lallemand10a37362022-03-02 16:18:26 +01007622 hlua_hc->sent = 0;
William Lallemand3956c4e2021-09-21 16:25:15 +02007623
Aurelien DARRAGON03564072023-02-09 15:26:25 +01007624 istfree(&hlua_hc->hc->req.url);
William Lallemand3956c4e2021-09-21 16:25:15 +02007625 hlua_hc->hc->req.url = istdup(ist(url_str));
William Lallemanddc2cc902021-10-26 11:43:26 +02007626 hlua_hc->hc->req.meth = meth;
William Lallemand3956c4e2021-09-21 16:25:15 +02007627
7628 /* update the httpclient callbacks */
William Lallemandbd5739e2021-10-28 15:41:38 +02007629 hlua_hc->hc->ops.res_stline = hlua_httpclient_cb;
7630 hlua_hc->hc->ops.res_headers = hlua_httpclient_cb;
7631 hlua_hc->hc->ops.res_payload = hlua_httpclient_cb;
William Lallemand8f170c72022-03-15 10:52:07 +01007632 hlua_hc->hc->ops.res_end = hlua_httpclient_cb;
William Lallemand3956c4e2021-09-21 16:25:15 +02007633
William Lallemandbd5739e2021-10-28 15:41:38 +02007634 /* a body is available, it will use the request callback */
Christopher Faulet380ae9c2022-10-14 14:57:04 +02007635 if (body_str && buf_len) {
William Lallemandbd5739e2021-10-28 15:41:38 +02007636 hlua_hc->hc->ops.req_payload = hlua_httpclient_cb;
7637 }
William Lallemand3956c4e2021-09-21 16:25:15 +02007638
William Lallemandbd5739e2021-10-28 15:41:38 +02007639 ret = httpclient_req_gen(hlua_hc->hc, hlua_hc->hc->req.url, meth, hdrs, IST_NULL);
William Lallemand3956c4e2021-09-21 16:25:15 +02007640
William Lallemand746e6f32021-10-06 10:57:44 +02007641 /* free the temporary headers array */
7642 hdrs_i = hdrs;
7643 while (hdrs_i && isttest(hdrs_i->n)) {
7644 istfree(&hdrs_i->n);
7645 istfree(&hdrs_i->v);
7646 hdrs_i++;
7647 }
7648 ha_free(&hdrs);
7649
7650
William Lallemand6137a9e2021-10-26 15:01:53 +02007651 if (ret != ERR_NONE) {
7652 WILL_LJMP(luaL_error(L, "Can't generate the HTTP request"));
7653 return 0;
7654 }
7655
William Lallemandc2d3db42022-04-26 11:46:13 +02007656 if (!httpclient_start(hlua_hc->hc))
7657 WILL_LJMP(luaL_error(L, "couldn't start the httpclient"));
William Lallemand6137a9e2021-10-26 15:01:53 +02007658
William Lallemandbd5739e2021-10-28 15:41:38 +02007659 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_httpclient_snd_yield, TICK_ETERNITY, 0));
William Lallemand3956c4e2021-09-21 16:25:15 +02007660
William Lallemand3956c4e2021-09-21 16:25:15 +02007661 return 0;
7662}
7663
7664/*
William Lallemanddc2cc902021-10-26 11:43:26 +02007665 * Sends an HTTP HEAD request and wait for a response
7666 *
7667 * httpclient:head(url, headers, payload)
7668 */
7669__LJMP static int hlua_httpclient_head(lua_State *L)
7670{
7671 return hlua_httpclient_send(L, HTTP_METH_HEAD);
7672}
7673
7674/*
7675 * Send an HTTP GET request and wait for a response
7676 *
7677 * httpclient:get(url, headers, payload)
7678 */
7679__LJMP static int hlua_httpclient_get(lua_State *L)
7680{
7681 return hlua_httpclient_send(L, HTTP_METH_GET);
7682
7683}
7684
7685/*
7686 * Sends an HTTP PUT request and wait for a response
7687 *
7688 * httpclient:put(url, headers, payload)
7689 */
7690__LJMP static int hlua_httpclient_put(lua_State *L)
7691{
7692 return hlua_httpclient_send(L, HTTP_METH_PUT);
7693}
7694
7695/*
7696 * Send an HTTP POST request and wait for a response
7697 *
7698 * httpclient:post(url, headers, payload)
7699 */
7700__LJMP static int hlua_httpclient_post(lua_State *L)
7701{
7702 return hlua_httpclient_send(L, HTTP_METH_POST);
7703}
7704
7705
7706/*
7707 * Sends an HTTP DELETE request and wait for a response
7708 *
7709 * httpclient:delete(url, headers, payload)
7710 */
7711__LJMP static int hlua_httpclient_delete(lua_State *L)
7712{
7713 return hlua_httpclient_send(L, HTTP_METH_DELETE);
7714}
7715
7716/*
William Lallemand3956c4e2021-09-21 16:25:15 +02007717 *
7718 *
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007719 * Class TXN
7720 *
7721 *
7722 */
7723
7724/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02007725 * a class stream, otherwise it throws an error.
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007726 */
7727__LJMP static struct hlua_txn *hlua_checktxn(lua_State *L, int ud)
7728{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02007729 return MAY_LJMP(hlua_checkudata(L, ud, class_txn_ref));
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007730}
7731
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007732__LJMP static int hlua_set_var(lua_State *L)
7733{
7734 struct hlua_txn *htxn;
7735 const char *name;
7736 size_t len;
7737 struct sample smp;
7738
Tim Duesterhus4e172c92020-05-19 13:49:42 +02007739 if (lua_gettop(L) < 3 || lua_gettop(L) > 4)
7740 WILL_LJMP(luaL_error(L, "'set_var' needs between 3 and 4 arguments"));
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007741
7742 /* It is useles to retrieve the stream, but this function
7743 * runs only in a stream context.
7744 */
7745 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7746 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
7747
7748 /* Converts the third argument in a sample. */
Amaury Denoyellebc0af6a2020-10-29 17:21:20 +01007749 memset(&smp, 0, sizeof(smp));
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007750 hlua_lua2smp(L, 3, &smp);
7751
7752 /* Store the sample in a variable. */
Willy Tarreau7560dd42016-03-10 16:28:58 +01007753 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
Tim Duesterhus4e172c92020-05-19 13:49:42 +02007754
7755 if (lua_gettop(L) == 4 && lua_toboolean(L, 4))
7756 lua_pushboolean(L, vars_set_by_name_ifexist(name, len, &smp) != 0);
7757 else
7758 lua_pushboolean(L, vars_set_by_name(name, len, &smp) != 0);
7759
Tim Duesterhus84ebc132020-05-19 13:49:41 +02007760 return 1;
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007761}
7762
Christopher Faulet85d79c92016-11-09 16:54:56 +01007763__LJMP static int hlua_unset_var(lua_State *L)
7764{
7765 struct hlua_txn *htxn;
7766 const char *name;
7767 size_t len;
7768 struct sample smp;
7769
7770 MAY_LJMP(check_args(L, 2, "unset_var"));
7771
7772 /* It is useles to retrieve the stream, but this function
7773 * runs only in a stream context.
7774 */
7775 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7776 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
7777
7778 /* Unset the variable. */
7779 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
Tim Duesterhus84ebc132020-05-19 13:49:41 +02007780 lua_pushboolean(L, vars_unset_by_name_ifexist(name, len, &smp) != 0);
7781 return 1;
Christopher Faulet85d79c92016-11-09 16:54:56 +01007782}
7783
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007784__LJMP static int hlua_get_var(lua_State *L)
7785{
7786 struct hlua_txn *htxn;
7787 const char *name;
7788 size_t len;
7789 struct sample smp;
7790
7791 MAY_LJMP(check_args(L, 2, "get_var"));
7792
7793 /* It is useles to retrieve the stream, but this function
7794 * runs only in a stream context.
7795 */
7796 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7797 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
7798
Willy Tarreau7560dd42016-03-10 16:28:58 +01007799 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
Willy Tarreaue352b9d2021-09-03 11:52:38 +02007800 if (!vars_get_by_name(name, len, &smp, NULL)) {
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007801 lua_pushnil(L);
7802 return 1;
7803 }
7804
7805 return hlua_smp2lua(L, &smp);
7806}
7807
Willy Tarreau59551662015-03-10 14:23:13 +01007808__LJMP static int hlua_set_priv(lua_State *L)
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007809{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007810 struct hlua *hlua;
7811
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007812 MAY_LJMP(check_args(L, 2, "set_priv"));
7813
Willy Tarreau87b09662015-04-03 00:22:06 +02007814 /* It is useles to retrieve the stream, but this function
7815 * runs only in a stream context.
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007816 */
7817 MAY_LJMP(hlua_checktxn(L, 1));
Thierry Fournier4234dbd2020-11-28 13:18:23 +01007818
7819 /* Get hlua struct, or NULL if we execute from main lua state */
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007820 hlua = hlua_gethlua(L);
Thierry Fournier4234dbd2020-11-28 13:18:23 +01007821 if (!hlua)
7822 return 0;
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007823
7824 /* Remove previous value. */
Thierry FOURNIERe068b602017-04-26 13:27:05 +02007825 luaL_unref(L, LUA_REGISTRYINDEX, hlua->Mref);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007826
7827 /* Get and store new value. */
7828 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
7829 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
7830
7831 return 0;
7832}
7833
Willy Tarreau59551662015-03-10 14:23:13 +01007834__LJMP static int hlua_get_priv(lua_State *L)
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007835{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007836 struct hlua *hlua;
7837
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007838 MAY_LJMP(check_args(L, 1, "get_priv"));
7839
Willy Tarreau87b09662015-04-03 00:22:06 +02007840 /* It is useles to retrieve the stream, but this function
7841 * runs only in a stream context.
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007842 */
7843 MAY_LJMP(hlua_checktxn(L, 1));
Thierry Fournier4234dbd2020-11-28 13:18:23 +01007844
7845 /* Get hlua struct, or NULL if we execute from main lua state */
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007846 hlua = hlua_gethlua(L);
Thierry Fournier4234dbd2020-11-28 13:18:23 +01007847 if (!hlua) {
7848 lua_pushnil(L);
7849 return 1;
7850 }
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007851
7852 /* Push configuration index in the stack. */
7853 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
7854
7855 return 1;
7856}
7857
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007858/* Create stack entry containing a class TXN. This function
7859 * return 0 if the stack does not contains free slots,
7860 * otherwise it returns 1.
7861 */
Thierry FOURNIERab00df62016-07-14 11:42:37 +02007862static int hlua_txn_new(lua_State *L, struct stream *s, struct proxy *p, int dir, int flags)
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007863{
Willy Tarreaude491382015-04-06 11:04:28 +02007864 struct hlua_txn *htxn;
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007865
7866 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01007867 if (!lua_checkstack(L, 3))
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007868 return 0;
7869
7870 /* NOTE: The allocation never fails. The failure
7871 * throw an error, and the function never returns.
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08007872 * if the throw is not available, the process is aborted.
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007873 */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01007874 /* Create the object: obj[0] = userdata. */
7875 lua_newtable(L);
Willy Tarreaude491382015-04-06 11:04:28 +02007876 htxn = lua_newuserdata(L, sizeof(*htxn));
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01007877 lua_rawseti(L, -2, 0);
7878
Willy Tarreaude491382015-04-06 11:04:28 +02007879 htxn->s = s;
7880 htxn->p = p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01007881 htxn->dir = dir;
Thierry FOURNIERab00df62016-07-14 11:42:37 +02007882 htxn->flags = flags;
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007883
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01007884 /* Create the "f" field that contains a list of fetches. */
7885 lua_pushstring(L, "f");
Thierry FOURNIERca988662015-12-20 18:43:03 +01007886 if (!hlua_fetches_new(L, htxn, HLUA_F_MAY_USE_HTTP))
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01007887 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007888 lua_rawset(L, -3);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01007889
7890 /* Create the "sf" field that contains a list of stringsafe fetches. */
7891 lua_pushstring(L, "sf");
Thierry FOURNIERca988662015-12-20 18:43:03 +01007892 if (!hlua_fetches_new(L, htxn, HLUA_F_MAY_USE_HTTP | HLUA_F_AS_STRING))
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01007893 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007894 lua_rawset(L, -3);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01007895
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007896 /* Create the "c" field that contains a list of converters. */
7897 lua_pushstring(L, "c");
Willy Tarreaude491382015-04-06 11:04:28 +02007898 if (!hlua_converters_new(L, htxn, 0))
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01007899 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007900 lua_rawset(L, -3);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01007901
7902 /* Create the "sc" field that contains a list of stringsafe converters. */
7903 lua_pushstring(L, "sc");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01007904 if (!hlua_converters_new(L, htxn, HLUA_F_AS_STRING))
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007905 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007906 lua_rawset(L, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007907
Thierry FOURNIER397826a2015-03-11 19:39:09 +01007908 /* Create the "req" field that contains the request channel object. */
7909 lua_pushstring(L, "req");
Willy Tarreau2a71af42015-03-10 13:51:50 +01007910 if (!hlua_channel_new(L, &s->req))
Thierry FOURNIER397826a2015-03-11 19:39:09 +01007911 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007912 lua_rawset(L, -3);
Thierry FOURNIER397826a2015-03-11 19:39:09 +01007913
7914 /* Create the "res" field that contains the response channel object. */
7915 lua_pushstring(L, "res");
Willy Tarreau2a71af42015-03-10 13:51:50 +01007916 if (!hlua_channel_new(L, &s->res))
Thierry FOURNIER397826a2015-03-11 19:39:09 +01007917 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007918 lua_rawset(L, -3);
Thierry FOURNIER397826a2015-03-11 19:39:09 +01007919
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007920 /* Creates the HTTP object is the current proxy allows http. */
7921 lua_pushstring(L, "http");
Christopher Faulet1bb6afa2021-03-08 17:57:53 +01007922 if (IS_HTX_STRM(s)) {
Willy Tarreaude491382015-04-06 11:04:28 +02007923 if (!hlua_http_new(L, htxn))
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007924 return 0;
7925 }
7926 else
7927 lua_pushnil(L);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007928 lua_rawset(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007929
Christopher Faulet78c35472020-02-26 17:14:08 +01007930 if ((htxn->flags & HLUA_TXN_CTX_MASK) == HLUA_TXN_FLT_CTX) {
7931 /* HTTPMessage object are created when a lua TXN is created from
7932 * a filter context only
7933 */
7934
7935 /* Creates the HTTP-Request object is the current proxy allows http. */
7936 lua_pushstring(L, "http_req");
7937 if (p->mode == PR_MODE_HTTP) {
7938 if (!hlua_http_msg_new(L, &s->txn->req))
7939 return 0;
7940 }
7941 else
7942 lua_pushnil(L);
7943 lua_rawset(L, -3);
7944
7945 /* Creates the HTTP-Response object is the current proxy allows http. */
7946 lua_pushstring(L, "http_res");
7947 if (p->mode == PR_MODE_HTTP) {
7948 if (!hlua_http_msg_new(L, &s->txn->rsp))
7949 return 0;
7950 }
7951 else
7952 lua_pushnil(L);
7953 lua_rawset(L, -3);
7954 }
7955
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007956 /* Pop a class sesison metatable and affect it to the userdata. */
7957 lua_rawgeti(L, LUA_REGISTRYINDEX, class_txn_ref);
7958 lua_setmetatable(L, -2);
7959
7960 return 1;
7961}
7962
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01007963__LJMP static int hlua_txn_deflog(lua_State *L)
7964{
7965 const char *msg;
7966 struct hlua_txn *htxn;
7967
7968 MAY_LJMP(check_args(L, 2, "deflog"));
7969 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7970 msg = MAY_LJMP(luaL_checkstring(L, 2));
7971
7972 hlua_sendlog(htxn->s->be, htxn->s->logs.level, msg);
7973 return 0;
7974}
7975
7976__LJMP static int hlua_txn_log(lua_State *L)
7977{
7978 int level;
7979 const char *msg;
7980 struct hlua_txn *htxn;
7981
7982 MAY_LJMP(check_args(L, 3, "log"));
7983 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7984 level = MAY_LJMP(luaL_checkinteger(L, 2));
7985 msg = MAY_LJMP(luaL_checkstring(L, 3));
7986
7987 if (level < 0 || level >= NB_LOG_LEVELS)
7988 WILL_LJMP(luaL_argerror(L, 1, "Invalid loglevel."));
7989
7990 hlua_sendlog(htxn->s->be, level, msg);
7991 return 0;
7992}
7993
7994__LJMP static int hlua_txn_log_debug(lua_State *L)
7995{
7996 const char *msg;
7997 struct hlua_txn *htxn;
7998
7999 MAY_LJMP(check_args(L, 2, "Debug"));
8000 htxn = MAY_LJMP(hlua_checktxn(L, 1));
8001 msg = MAY_LJMP(luaL_checkstring(L, 2));
8002 hlua_sendlog(htxn->s->be, LOG_DEBUG, msg);
8003 return 0;
8004}
8005
8006__LJMP static int hlua_txn_log_info(lua_State *L)
8007{
8008 const char *msg;
8009 struct hlua_txn *htxn;
8010
8011 MAY_LJMP(check_args(L, 2, "Info"));
8012 htxn = MAY_LJMP(hlua_checktxn(L, 1));
8013 msg = MAY_LJMP(luaL_checkstring(L, 2));
8014 hlua_sendlog(htxn->s->be, LOG_INFO, msg);
8015 return 0;
8016}
8017
8018__LJMP static int hlua_txn_log_warning(lua_State *L)
8019{
8020 const char *msg;
8021 struct hlua_txn *htxn;
8022
8023 MAY_LJMP(check_args(L, 2, "Warning"));
8024 htxn = MAY_LJMP(hlua_checktxn(L, 1));
8025 msg = MAY_LJMP(luaL_checkstring(L, 2));
8026 hlua_sendlog(htxn->s->be, LOG_WARNING, msg);
8027 return 0;
8028}
8029
8030__LJMP static int hlua_txn_log_alert(lua_State *L)
8031{
8032 const char *msg;
8033 struct hlua_txn *htxn;
8034
8035 MAY_LJMP(check_args(L, 2, "Alert"));
8036 htxn = MAY_LJMP(hlua_checktxn(L, 1));
8037 msg = MAY_LJMP(luaL_checkstring(L, 2));
8038 hlua_sendlog(htxn->s->be, LOG_ALERT, msg);
8039 return 0;
8040}
8041
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01008042__LJMP static int hlua_txn_set_loglevel(lua_State *L)
8043{
8044 struct hlua_txn *htxn;
8045 int ll;
8046
8047 MAY_LJMP(check_args(L, 2, "set_loglevel"));
8048 htxn = MAY_LJMP(hlua_checktxn(L, 1));
8049 ll = MAY_LJMP(luaL_checkinteger(L, 2));
8050
8051 if (ll < 0 || ll > 7)
8052 WILL_LJMP(luaL_argerror(L, 2, "Bad log level. It must be between 0 and 7"));
8053
8054 htxn->s->logs.level = ll;
8055 return 0;
8056}
8057
8058__LJMP static int hlua_txn_set_tos(lua_State *L)
8059{
8060 struct hlua_txn *htxn;
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01008061 int tos;
8062
8063 MAY_LJMP(check_args(L, 2, "set_tos"));
8064 htxn = MAY_LJMP(hlua_checktxn(L, 1));
8065 tos = MAY_LJMP(luaL_checkinteger(L, 2));
8066
Willy Tarreau1a18b542018-12-11 16:37:42 +01008067 conn_set_tos(objt_conn(htxn->s->sess->origin), tos);
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01008068 return 0;
8069}
8070
8071__LJMP static int hlua_txn_set_mark(lua_State *L)
8072{
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01008073 struct hlua_txn *htxn;
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01008074 int mark;
8075
8076 MAY_LJMP(check_args(L, 2, "set_mark"));
8077 htxn = MAY_LJMP(hlua_checktxn(L, 1));
8078 mark = MAY_LJMP(luaL_checkinteger(L, 2));
8079
Lukas Tribus579e3e32019-08-11 18:03:45 +02008080 conn_set_mark(objt_conn(htxn->s->sess->origin), mark);
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01008081 return 0;
8082}
8083
Patrick Hemmer268a7072018-05-11 12:52:31 -04008084__LJMP static int hlua_txn_set_priority_class(lua_State *L)
8085{
8086 struct hlua_txn *htxn;
8087
8088 MAY_LJMP(check_args(L, 2, "set_priority_class"));
8089 htxn = MAY_LJMP(hlua_checktxn(L, 1));
8090 htxn->s->priority_class = queue_limit_class(MAY_LJMP(luaL_checkinteger(L, 2)));
8091 return 0;
8092}
8093
8094__LJMP static int hlua_txn_set_priority_offset(lua_State *L)
8095{
8096 struct hlua_txn *htxn;
8097
8098 MAY_LJMP(check_args(L, 2, "set_priority_offset"));
8099 htxn = MAY_LJMP(hlua_checktxn(L, 1));
8100 htxn->s->priority_offset = queue_limit_offset(MAY_LJMP(luaL_checkinteger(L, 2)));
8101 return 0;
8102}
8103
Christopher Faulet700d9e82020-01-31 12:21:52 +01008104/* Forward the Reply object to the client. This function converts the reply in
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05008105 * HTX an push it to into the response channel. It is response to forward the
Christopher Faulet700d9e82020-01-31 12:21:52 +01008106 * message and terminate the transaction. It returns 1 on success and 0 on
8107 * error. The Reply must be on top of the stack.
8108 */
8109__LJMP static int hlua_txn_forward_reply(lua_State *L, struct stream *s)
8110{
8111 struct htx *htx;
8112 struct htx_sl *sl;
8113 struct h1m h1m;
8114 const char *status, *reason, *body;
8115 size_t status_len, reason_len, body_len;
8116 int ret, code, flags;
8117
8118 code = 200;
8119 status = "200";
8120 status_len = 3;
8121 ret = lua_getfield(L, -1, "status");
8122 if (ret == LUA_TNUMBER) {
8123 code = lua_tointeger(L, -1);
8124 status = lua_tolstring(L, -1, &status_len);
8125 }
8126 lua_pop(L, 1);
8127
8128 reason = http_get_reason(code);
8129 reason_len = strlen(reason);
8130 ret = lua_getfield(L, -1, "reason");
8131 if (ret == LUA_TSTRING)
8132 reason = lua_tolstring(L, -1, &reason_len);
8133 lua_pop(L, 1);
8134
8135 body = NULL;
8136 body_len = 0;
8137 ret = lua_getfield(L, -1, "body");
8138 if (ret == LUA_TSTRING)
8139 body = lua_tolstring(L, -1, &body_len);
8140 lua_pop(L, 1);
8141
8142 /* Prepare the response before inserting the headers */
8143 h1m_init_res(&h1m);
8144 htx = htx_from_buf(&s->res.buf);
8145 channel_htx_truncate(&s->res, htx);
8146 if (s->txn->req.flags & HTTP_MSGF_VER_11) {
8147 flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11);
8148 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.1"),
8149 ist2(status, status_len), ist2(reason, reason_len));
8150 }
8151 else {
8152 flags = HTX_SL_F_IS_RESP;
8153 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.0"),
8154 ist2(status, status_len), ist2(reason, reason_len));
8155 }
8156 if (!sl)
8157 goto fail;
8158 sl->info.res.status = code;
8159
8160 /* Push in the stack the "headers" entry. */
8161 ret = lua_getfield(L, -1, "headers");
8162 if (ret != LUA_TTABLE)
8163 goto skip_headers;
8164
8165 lua_pushnil(L);
8166 while (lua_next(L, -2) != 0) {
8167 struct ist name, value;
8168 const char *n, *v;
8169 size_t nlen, vlen;
8170
8171 if (!lua_isstring(L, -2) || !lua_istable(L, -1)) {
8172 /* Skip element if the key is not a string or if the value is not a table */
8173 goto next_hdr;
8174 }
8175
8176 n = lua_tolstring(L, -2, &nlen);
8177 name = ist2(n, nlen);
8178 if (isteqi(name, ist("content-length"))) {
8179 /* Always skip content-length header. It will be added
8180 * later with the correct len
8181 */
8182 goto next_hdr;
8183 }
8184
8185 /* Loop on header's values */
8186 lua_pushnil(L);
8187 while (lua_next(L, -2)) {
8188 if (!lua_isstring(L, -1)) {
8189 /* Skip the value if it is not a string */
8190 goto next_value;
8191 }
8192
8193 v = lua_tolstring(L, -1, &vlen);
8194 value = ist2(v, vlen);
8195
8196 if (isteqi(name, ist("transfer-encoding")))
8197 h1_parse_xfer_enc_header(&h1m, value);
8198 if (!htx_add_header(htx, ist2(n, nlen), ist2(v, vlen)))
8199 goto fail;
8200
8201 next_value:
8202 lua_pop(L, 1);
8203 }
8204
8205 next_hdr:
8206 lua_pop(L, 1);
8207 }
8208 skip_headers:
8209 lua_pop(L, 1);
8210
8211 /* Update h1m flags: CLEN is set if CHNK is not present */
8212 if (!(h1m.flags & H1_MF_CHNK)) {
8213 const char *clen = ultoa(body_len);
8214
8215 h1m.flags |= H1_MF_CLEN;
8216 if (!htx_add_header(htx, ist("content-length"), ist(clen)))
8217 goto fail;
8218 }
8219 if (h1m.flags & (H1_MF_CLEN|H1_MF_CHNK))
8220 h1m.flags |= H1_MF_XFER_LEN;
8221
8222 /* Update HTX start-line flags */
8223 if (h1m.flags & H1_MF_XFER_ENC)
8224 flags |= HTX_SL_F_XFER_ENC;
8225 if (h1m.flags & H1_MF_XFER_LEN) {
8226 flags |= HTX_SL_F_XFER_LEN;
8227 if (h1m.flags & H1_MF_CHNK)
8228 flags |= HTX_SL_F_CHNK;
8229 else if (h1m.flags & H1_MF_CLEN)
8230 flags |= HTX_SL_F_CLEN;
8231 if (h1m.body_len == 0)
8232 flags |= HTX_SL_F_BODYLESS;
8233 }
8234 sl->flags |= flags;
8235
8236
8237 if (!htx_add_endof(htx, HTX_BLK_EOH) ||
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01008238 (body_len && !htx_add_data_atonce(htx, ist2(body, body_len))))
Christopher Faulet700d9e82020-01-31 12:21:52 +01008239 goto fail;
8240
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01008241 htx->flags |= HTX_FL_EOM;
8242
Christopher Faulet700d9e82020-01-31 12:21:52 +01008243 /* Now, forward the response and terminate the transaction */
8244 s->txn->status = code;
8245 htx_to_buf(htx, &s->res.buf);
8246 if (!http_forward_proxy_resp(s, 1))
8247 goto fail;
8248
8249 return 1;
8250
8251 fail:
8252 channel_htx_truncate(&s->res, htx);
8253 return 0;
8254}
8255
8256/* Terminate a transaction if called from a lua action. For TCP streams,
8257 * processing is just aborted. Nothing is returned to the client and all
8258 * arguments are ignored. For HTTP streams, if a reply is passed as argument, it
8259 * is forwarded to the client before terminating the transaction. On success,
8260 * the function exits with ACT_RET_DONE code. If an error occurred, it exits
8261 * with ACT_RET_ERR code. If this function is not called from a lua action, it
8262 * just exits without any processing.
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01008263 */
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02008264__LJMP static int hlua_txn_done(lua_State *L)
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01008265{
Willy Tarreaub2ccb562015-04-06 11:11:15 +02008266 struct hlua_txn *htxn;
Christopher Faulet700d9e82020-01-31 12:21:52 +01008267 struct stream *s;
8268 int finst;
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01008269
Willy Tarreaub2ccb562015-04-06 11:11:15 +02008270 htxn = MAY_LJMP(hlua_checktxn(L, 1));
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01008271
Christopher Faulet700d9e82020-01-31 12:21:52 +01008272 /* If the flags NOTERM is set, we cannot terminate the session, so we
8273 * just end the execution of the current lua code. */
8274 if (htxn->flags & HLUA_TXN_NOTERM)
Thierry FOURNIERab00df62016-07-14 11:42:37 +02008275 WILL_LJMP(hlua_done(L));
Thierry FOURNIERab00df62016-07-14 11:42:37 +02008276
Christopher Faulet700d9e82020-01-31 12:21:52 +01008277 s = htxn->s;
Christopher Fauletd8f0e072020-02-25 09:45:51 +01008278 if (!IS_HTX_STRM(htxn->s)) {
Christopher Faulet700d9e82020-01-31 12:21:52 +01008279 struct channel *req = &s->req;
8280 struct channel *res = &s->res;
Willy Tarreau81389672015-03-10 12:03:52 +01008281
Christopher Faulet700d9e82020-01-31 12:21:52 +01008282 channel_auto_read(req);
8283 channel_abort(req);
Christopher Faulet700d9e82020-01-31 12:21:52 +01008284 channel_erase(req);
8285
Christopher Faulet700d9e82020-01-31 12:21:52 +01008286 channel_auto_read(res);
8287 channel_auto_close(res);
Christopher Faulet12762f02023-04-13 15:40:10 +02008288 sc_schedule_abort(s->scb);
Christopher Faulet700d9e82020-01-31 12:21:52 +01008289
8290 finst = ((htxn->dir == SMP_OPT_DIR_REQ) ? SF_FINST_R : SF_FINST_D);
8291 goto done;
Christopher Fauletfe6a71b2019-07-26 16:40:24 +02008292 }
Thierry FOURNIER10ec2142015-08-24 17:23:45 +02008293
Christopher Faulet700d9e82020-01-31 12:21:52 +01008294 if (lua_gettop(L) == 1 || !lua_istable(L, 2)) {
8295 /* No reply or invalid reply */
8296 s->txn->status = 0;
8297 http_reply_and_close(s, 0, NULL);
8298 }
8299 else {
8300 /* Remove extra args to have the reply on top of the stack */
8301 if (lua_gettop(L) > 2)
8302 lua_pop(L, lua_gettop(L) - 2);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01008303
Christopher Faulet700d9e82020-01-31 12:21:52 +01008304 if (!hlua_txn_forward_reply(L, s)) {
8305 if (!(s->flags & SF_ERR_MASK))
8306 s->flags |= SF_ERR_PRXCOND;
8307 lua_pushinteger(L, ACT_RET_ERR);
8308 WILL_LJMP(hlua_done(L));
8309 return 0; /* Never reached */
8310 }
Christopher Faulet4d0e2632019-07-16 10:52:40 +02008311 }
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02008312
Christopher Faulet700d9e82020-01-31 12:21:52 +01008313 finst = ((htxn->dir == SMP_OPT_DIR_REQ) ? SF_FINST_R : SF_FINST_H);
8314 if (htxn->dir == SMP_OPT_DIR_REQ) {
8315 /* let's log the request time */
Willy Tarreau69530f52023-04-28 09:16:15 +02008316 s->logs.request_ts = now_ns;
Christopher Faulet700d9e82020-01-31 12:21:52 +01008317 if (s->sess->fe == s->be) /* report it if the request was intercepted by the frontend */
Willy Tarreau4781b152021-04-06 13:53:36 +02008318 _HA_ATOMIC_INC(&s->sess->fe->fe_counters.intercepted_req);
Christopher Faulet700d9e82020-01-31 12:21:52 +01008319 }
Christopher Fauletfe6a71b2019-07-26 16:40:24 +02008320
Christopher Faulet700d9e82020-01-31 12:21:52 +01008321 done:
8322 if (!(s->flags & SF_ERR_MASK))
8323 s->flags |= SF_ERR_LOCAL;
8324 if (!(s->flags & SF_FINST_MASK))
8325 s->flags |= finst;
Christopher Fauletfe6a71b2019-07-26 16:40:24 +02008326
Christopher Faulete48d1dc2021-08-13 14:11:17 +02008327 if ((htxn->flags & HLUA_TXN_CTX_MASK) == HLUA_TXN_FLT_CTX)
8328 lua_pushinteger(L, -1);
8329 else
8330 lua_pushinteger(L, ACT_RET_ABRT);
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02008331 WILL_LJMP(hlua_done(L));
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01008332 return 0;
8333}
8334
Christopher Faulet700d9e82020-01-31 12:21:52 +01008335/*
8336 *
8337 *
8338 * Class REPLY
8339 *
8340 *
8341 */
8342
8343/* Pushes the TXN reply onto the top of the stack. If the stask does not have a
8344 * free slots, the function fails and returns 0;
8345 */
8346static int hlua_txn_reply_new(lua_State *L)
8347{
8348 struct hlua_txn *htxn;
8349 const char *reason, *body = NULL;
8350 int ret, status;
8351
8352 htxn = MAY_LJMP(hlua_checktxn(L, 1));
Christopher Fauletd8f0e072020-02-25 09:45:51 +01008353 if (!IS_HTX_STRM(htxn->s)) {
Christopher Faulet700d9e82020-01-31 12:21:52 +01008354 hlua_pusherror(L, "txn object is not an HTTP transaction.");
8355 WILL_LJMP(lua_error(L));
8356 }
8357
8358 /* Default value */
8359 status = 200;
8360 reason = http_get_reason(status);
8361
8362 if (lua_istable(L, 2)) {
8363 /* load status and reason from the table argument at index 2 */
8364 ret = lua_getfield(L, 2, "status");
8365 if (ret == LUA_TNIL)
8366 goto reason;
8367 else if (ret != LUA_TNUMBER) {
8368 /* invalid status: ignore the reason */
8369 goto body;
8370 }
8371 status = lua_tointeger(L, -1);
8372
8373 reason:
8374 lua_pop(L, 1); /* restore the stack: remove status */
8375 ret = lua_getfield(L, 2, "reason");
8376 if (ret == LUA_TSTRING)
8377 reason = lua_tostring(L, -1);
8378
8379 body:
8380 lua_pop(L, 1); /* restore the stack: remove invalid status or reason */
8381 ret = lua_getfield(L, 2, "body");
8382 if (ret == LUA_TSTRING)
8383 body = lua_tostring(L, -1);
8384 lua_pop(L, 1); /* restore the stack: remove body */
8385 }
8386
8387 /* Create the Reply table */
8388 lua_newtable(L);
8389
8390 /* Add status element */
8391 lua_pushstring(L, "status");
8392 lua_pushinteger(L, status);
8393 lua_settable(L, -3);
8394
8395 /* Add reason element */
8396 reason = http_get_reason(status);
8397 lua_pushstring(L, "reason");
8398 lua_pushstring(L, reason);
8399 lua_settable(L, -3);
8400
8401 /* Add body element, nil if undefined */
8402 lua_pushstring(L, "body");
8403 if (body)
8404 lua_pushstring(L, body);
8405 else
8406 lua_pushnil(L);
8407 lua_settable(L, -3);
8408
8409 /* Add headers element */
8410 lua_pushstring(L, "headers");
8411 lua_newtable(L);
8412
8413 /* stack: [ txn, <Arg:table>, <Reply:table>, "headers", <headers:table> ] */
8414 if (lua_istable(L, 2)) {
8415 /* load headers from the table argument at index 2. If it is a table, copy it. */
8416 ret = lua_getfield(L, 2, "headers");
8417 if (ret == LUA_TTABLE) {
8418 /* stack: [ ... <headers:table>, <table> ] */
8419 lua_pushnil(L);
8420 while (lua_next(L, -2) != 0) {
8421 /* stack: [ ... <headers:table>, <table>, k, v] */
8422 if (!lua_isstring(L, -1) && !lua_istable(L, -1)) {
8423 /* invalid value type, skip it */
8424 lua_pop(L, 1);
8425 continue;
8426 }
8427
8428
8429 /* Duplicate the key and swap it with the value. */
8430 lua_pushvalue(L, -2);
8431 lua_insert(L, -2);
8432 /* stack: [ ... <headers:table>, <table>, k, k, v ] */
8433
8434 lua_newtable(L);
8435 lua_insert(L, -2);
8436 /* stack: [ ... <headers:table>, <table>, k, k, <inner:table>, v ] */
8437
8438 if (lua_isstring(L, -1)) {
8439 /* push the value in the inner table */
8440 lua_rawseti(L, -2, 1);
8441 }
8442 else { /* table */
8443 lua_pushnil(L);
8444 while (lua_next(L, -2) != 0) {
8445 /* stack: [ ... <headers:table>, <table>, k, k, <inner:table>, <v:table>, k2, v2 ] */
8446 if (!lua_isstring(L, -1)) {
8447 /* invalid value type, skip it*/
8448 lua_pop(L, 1);
8449 continue;
8450 }
8451 /* push the value in the inner table */
8452 lua_rawseti(L, -4, lua_rawlen(L, -4) + 1);
8453 /* stack: [ ... <headers:table>, <table>, k, k, <inner:table>, <v:table>, k2 ] */
8454 }
8455 lua_pop(L, 1);
8456 /* stack: [ ... <headers:table>, <table>, k, k, <inner:table> ] */
8457 }
8458
8459 /* push (k,v) on the stack in the headers table:
8460 * stack: [ ... <headers:table>, <table>, k, k, v ]
8461 */
8462 lua_settable(L, -5);
8463 /* stack: [ ... <headers:table>, <table>, k ] */
8464 }
8465 }
8466 lua_pop(L, 1);
8467 }
8468 /* stack: [ txn, <Arg:table>, <Reply:table>, "headers", <headers:table> ] */
8469 lua_settable(L, -3);
8470 /* stack: [ txn, <Arg:table>, <Reply:table> ] */
8471
8472 /* Pop a class sesison metatable and affect it to the userdata. */
8473 lua_rawgeti(L, LUA_REGISTRYINDEX, class_txn_reply_ref);
8474 lua_setmetatable(L, -2);
8475 return 1;
8476}
8477
8478/* Set the reply status code, and optionally the reason. If no reason is
8479 * provided, the default one corresponding to the status code is used.
8480 */
8481__LJMP static int hlua_txn_reply_set_status(lua_State *L)
8482{
8483 int status = MAY_LJMP(luaL_checkinteger(L, 2));
8484 const char *reason = MAY_LJMP(luaL_optlstring(L, 3, NULL, NULL));
8485
8486 /* First argument (self) must be a table */
Aurelien DARRAGONd83d0452022-10-05 11:46:45 +02008487 MAY_LJMP(luaL_checktype(L, 1, LUA_TTABLE));
Christopher Faulet700d9e82020-01-31 12:21:52 +01008488
8489 if (status < 100 || status > 599) {
8490 lua_pushboolean(L, 0);
8491 return 1;
8492 }
8493 if (!reason)
8494 reason = http_get_reason(status);
8495
8496 lua_pushinteger(L, status);
8497 lua_setfield(L, 1, "status");
8498
8499 lua_pushstring(L, reason);
8500 lua_setfield(L, 1, "reason");
8501
8502 lua_pushboolean(L, 1);
8503 return 1;
8504}
8505
8506/* Add a header into the reply object. Each header name is associated to an
8507 * array of values in the "headers" table. If the header name is not found, a
8508 * new entry is created.
8509 */
8510__LJMP static int hlua_txn_reply_add_header(lua_State *L)
8511{
8512 const char *name = MAY_LJMP(luaL_checkstring(L, 2));
8513 const char *value = MAY_LJMP(luaL_checkstring(L, 3));
8514 int ret;
8515
8516 /* First argument (self) must be a table */
Aurelien DARRAGONd83d0452022-10-05 11:46:45 +02008517 MAY_LJMP(luaL_checktype(L, 1, LUA_TTABLE));
Christopher Faulet700d9e82020-01-31 12:21:52 +01008518
8519 /* Push in the stack the "headers" entry. */
8520 ret = lua_getfield(L, 1, "headers");
8521 if (ret != LUA_TTABLE) {
8522 hlua_pusherror(L, "Reply['headers'] is expected to a an array. %s found", lua_typename(L, ret));
8523 WILL_LJMP(lua_error(L));
8524 }
8525
8526 /* check if the header is already registered. If not, register it. */
8527 ret = lua_getfield(L, -1, name);
8528 if (ret == LUA_TNIL) {
8529 /* Entry not found. */
8530 lua_pop(L, 1); /* remove the nil. The "headers" table is the top of the stack. */
8531
8532 /* Insert the new header name in the array in the top of the stack.
8533 * It left the new array in the top of the stack.
8534 */
8535 lua_newtable(L);
8536 lua_pushstring(L, name);
8537 lua_pushvalue(L, -2);
8538 lua_settable(L, -4);
8539 }
8540 else if (ret != LUA_TTABLE) {
8541 hlua_pusherror(L, "Reply['headers']['%s'] is expected to be an array. %s found", name, lua_typename(L, ret));
8542 WILL_LJMP(lua_error(L));
8543 }
8544
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -07008545 /* Now the top of thestack is an array of values. We push
Christopher Faulet700d9e82020-01-31 12:21:52 +01008546 * the header value as new entry.
8547 */
8548 lua_pushstring(L, value);
8549 ret = lua_rawlen(L, -2);
8550 lua_rawseti(L, -2, ret + 1);
8551
8552 lua_pushboolean(L, 1);
8553 return 1;
8554}
8555
8556/* Remove all occurrences of a given header name. */
8557__LJMP static int hlua_txn_reply_del_header(lua_State *L)
8558{
8559 const char *name = MAY_LJMP(luaL_checkstring(L, 2));
8560 int ret;
8561
8562 /* First argument (self) must be a table */
Aurelien DARRAGONd83d0452022-10-05 11:46:45 +02008563 MAY_LJMP(luaL_checktype(L, 1, LUA_TTABLE));
Christopher Faulet700d9e82020-01-31 12:21:52 +01008564
8565 /* Push in the stack the "headers" entry. */
8566 ret = lua_getfield(L, 1, "headers");
8567 if (ret != LUA_TTABLE) {
8568 hlua_pusherror(L, "Reply['headers'] is expected to be an array. %s found", lua_typename(L, ret));
8569 WILL_LJMP(lua_error(L));
8570 }
8571
8572 lua_pushstring(L, name);
8573 lua_pushnil(L);
8574 lua_settable(L, -3);
8575
8576 lua_pushboolean(L, 1);
8577 return 1;
8578}
8579
8580/* Set the reply's body. Overwrite any existing entry. */
8581__LJMP static int hlua_txn_reply_set_body(lua_State *L)
8582{
8583 const char *payload = MAY_LJMP(luaL_checkstring(L, 2));
8584
8585 /* First argument (self) must be a table */
Aurelien DARRAGONd83d0452022-10-05 11:46:45 +02008586 MAY_LJMP(luaL_checktype(L, 1, LUA_TTABLE));
Christopher Faulet700d9e82020-01-31 12:21:52 +01008587
8588 lua_pushstring(L, payload);
8589 lua_setfield(L, 1, "body");
8590
8591 lua_pushboolean(L, 1);
8592 return 1;
8593}
8594
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01008595__LJMP static int hlua_log(lua_State *L)
8596{
8597 int level;
8598 const char *msg;
8599
8600 MAY_LJMP(check_args(L, 2, "log"));
8601 level = MAY_LJMP(luaL_checkinteger(L, 1));
8602 msg = MAY_LJMP(luaL_checkstring(L, 2));
8603
8604 if (level < 0 || level >= NB_LOG_LEVELS)
8605 WILL_LJMP(luaL_argerror(L, 1, "Invalid loglevel."));
8606
8607 hlua_sendlog(NULL, level, msg);
8608 return 0;
8609}
8610
8611__LJMP static int hlua_log_debug(lua_State *L)
8612{
8613 const char *msg;
8614
8615 MAY_LJMP(check_args(L, 1, "debug"));
8616 msg = MAY_LJMP(luaL_checkstring(L, 1));
8617 hlua_sendlog(NULL, LOG_DEBUG, msg);
8618 return 0;
8619}
8620
8621__LJMP static int hlua_log_info(lua_State *L)
8622{
8623 const char *msg;
8624
8625 MAY_LJMP(check_args(L, 1, "info"));
8626 msg = MAY_LJMP(luaL_checkstring(L, 1));
8627 hlua_sendlog(NULL, LOG_INFO, msg);
8628 return 0;
8629}
8630
8631__LJMP static int hlua_log_warning(lua_State *L)
8632{
8633 const char *msg;
8634
8635 MAY_LJMP(check_args(L, 1, "warning"));
8636 msg = MAY_LJMP(luaL_checkstring(L, 1));
8637 hlua_sendlog(NULL, LOG_WARNING, msg);
8638 return 0;
8639}
8640
8641__LJMP static int hlua_log_alert(lua_State *L)
8642{
8643 const char *msg;
8644
8645 MAY_LJMP(check_args(L, 1, "alert"));
8646 msg = MAY_LJMP(luaL_checkstring(L, 1));
8647 hlua_sendlog(NULL, LOG_ALERT, msg);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01008648 return 0;
8649}
8650
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01008651__LJMP static int hlua_sleep_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008652{
8653 int wakeup_ms = lua_tointeger(L, -1);
Willy Tarreau12c02702021-09-30 16:12:31 +02008654 if (!tick_is_expired(wakeup_ms, now_ms))
Willy Tarreau9635e032018-10-16 17:52:55 +02008655 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008656 return 0;
8657}
8658
8659__LJMP static int hlua_sleep(lua_State *L)
8660{
8661 unsigned int delay;
Aurelien DARRAGON2a9764b2023-04-04 18:41:04 +02008662 int wakeup_ms; // tick value
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008663
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008664 MAY_LJMP(check_args(L, 1, "sleep"));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008665
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01008666 delay = MAY_LJMP(luaL_checkinteger(L, 1)) * 1000;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008667 wakeup_ms = tick_add(now_ms, delay);
8668 lua_pushinteger(L, wakeup_ms);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008669
Willy Tarreau9635e032018-10-16 17:52:55 +02008670 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008671 return 0;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008672}
8673
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008674__LJMP static int hlua_msleep(lua_State *L)
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008675{
8676 unsigned int delay;
Aurelien DARRAGON2a9764b2023-04-04 18:41:04 +02008677 int wakeup_ms; // tick value
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008678
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008679 MAY_LJMP(check_args(L, 1, "msleep"));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008680
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01008681 delay = MAY_LJMP(luaL_checkinteger(L, 1));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008682 wakeup_ms = tick_add(now_ms, delay);
8683 lua_pushinteger(L, wakeup_ms);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008684
Willy Tarreau9635e032018-10-16 17:52:55 +02008685 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008686 return 0;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008687}
8688
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01008689/* This functionis an LUA binding. it permits to give back
8690 * the hand at the HAProxy scheduler. It is used when the
8691 * LUA processing consumes a lot of time.
8692 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01008693__LJMP static int hlua_yield_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008694{
8695 return 0;
8696}
8697
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01008698__LJMP static int hlua_yield(lua_State *L)
8699{
Willy Tarreau9635e032018-10-16 17:52:55 +02008700 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_yield_yield, TICK_ETERNITY, HLUA_CTRLYIELD));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008701 return 0;
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01008702}
8703
Thierry FOURNIER37196f42015-02-16 19:34:56 +01008704/* This function change the nice of the currently executed
8705 * task. It is used set low or high priority at the current
8706 * task.
8707 */
Willy Tarreau59551662015-03-10 14:23:13 +01008708__LJMP static int hlua_set_nice(lua_State *L)
Thierry FOURNIER37196f42015-02-16 19:34:56 +01008709{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01008710 struct hlua *hlua;
8711 int nice;
Thierry FOURNIER37196f42015-02-16 19:34:56 +01008712
Willy Tarreau80f5fae2015-02-27 16:38:20 +01008713 MAY_LJMP(check_args(L, 1, "set_nice"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01008714 nice = MAY_LJMP(luaL_checkinteger(L, 1));
Thierry FOURNIER37196f42015-02-16 19:34:56 +01008715
Thierry Fournier4234dbd2020-11-28 13:18:23 +01008716 /* Get hlua struct, or NULL if we execute from main lua state */
8717 hlua = hlua_gethlua(L);
8718
8719 /* If the task is not set, I'm in a start mode. */
Thierry FOURNIER37196f42015-02-16 19:34:56 +01008720 if (!hlua || !hlua->task)
8721 return 0;
8722
8723 if (nice < -1024)
8724 nice = -1024;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01008725 else if (nice > 1024)
Thierry FOURNIER37196f42015-02-16 19:34:56 +01008726 nice = 1024;
8727
8728 hlua->task->nice = nice;
8729 return 0;
8730}
8731
Aurelien DARRAGON8cd620b2023-04-07 17:37:46 +02008732/* safe lua coroutine.create() function:
8733 *
8734 * This is a simple wrapper for coroutine.create() that
8735 * ensures the current hlua state ctx is available from
8736 * the new subroutine state
8737 */
8738__LJMP static int hlua_coroutine_create(lua_State *L)
8739{
8740 lua_State *new; /* new coroutine state */
8741 struct hlua **hlua_store;
8742 struct hlua *hlua = hlua_gethlua(L);
8743
8744 new = lua_newthread(L);
8745 if (!new)
8746 return 0;
8747
8748 hlua_store = lua_getextraspace(new);
8749 /* Expose current hlua ctx on new lua thread
8750 * (hlua_gethlua() will properly return the last "known"
8751 * hlua ctx instead of NULL when it is called from such coroutines)
8752 */
8753 *hlua_store = hlua;
8754
8755 /* new lua thread is on the top of the stack, we
8756 * need to duplicate first stack argument (<f> from coroutine.create(<f>))
8757 * on the top of the stack to be able to use xmove() to move it on the new
8758 * stack
8759 */
8760 lua_pushvalue(L, 1);
8761 /* move <f> function to the new stack */
8762 lua_xmove(L, new, 1);
8763 /* new lua thread is back at the top of the stack */
8764 return 1;
8765}
8766
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08008767/* This function is used as a callback of a task. It is called by the
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008768 * HAProxy task subsystem when the task is awaked. The LUA runtime can
8769 * return an E_AGAIN signal, the emmiter of this signal must set a
8770 * signal to wake the task.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008771 *
8772 * Task wrapper are longjmp safe because the only one Lua code
8773 * executed is the safe hlua_ctx_resume();
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008774 */
Willy Tarreau144f84a2021-03-02 16:09:26 +01008775struct task *hlua_process_task(struct task *task, void *context, unsigned int state)
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008776{
Olivier Houchard9f6af332018-05-25 14:04:04 +02008777 struct hlua *hlua = context;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008778 enum hlua_exec status;
8779
Willy Tarreau6ef52f42022-06-15 14:19:48 +02008780 if (task->tid < 0)
8781 task->tid = tid;
8782
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008783 /* If it is the first call to the task, we must initialize the
8784 * execution timeouts.
8785 */
8786 if (!HLUA_IS_RUNNING(hlua))
Aurelien DARRAGONda9503c2022-11-25 09:10:07 +01008787 hlua_timer_init(&hlua->timer, hlua_timeout_task);
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008788
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008789 /* Execute the Lua code. */
8790 status = hlua_ctx_resume(hlua, 1);
8791
8792 switch (status) {
8793 /* finished or yield */
8794 case HLUA_E_OK:
8795 hlua_ctx_destroy(hlua);
Olivier Houchard3f795f72019-04-17 22:51:06 +02008796 task_destroy(task);
Tim Duesterhuscd235c62018-04-24 13:56:01 +02008797 task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008798 break;
8799
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01008800 case HLUA_E_AGAIN: /* co process or timeout wake me later. */
Thierry FOURNIERcb146882017-12-10 17:10:57 +01008801 notification_gc(&hlua->com);
PiBa-NLfe971b32018-05-02 22:27:14 +02008802 task->expire = hlua->wake_time;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008803 break;
8804
8805 /* finished with error. */
Aurelien DARRAGON79544102022-11-24 14:27:15 +01008806 case HLUA_E_ETMOUT:
8807 SEND_ERR(NULL, "Lua task: execution timeout.\n");
8808 goto err_task_abort;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008809 case HLUA_E_ERRMSG:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008810 SEND_ERR(NULL, "Lua task: %s.\n", lua_tostring(hlua->T, -1));
Aurelien DARRAGON79544102022-11-24 14:27:15 +01008811 goto err_task_abort;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008812 case HLUA_E_ERR:
8813 default:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008814 SEND_ERR(NULL, "Lua task: unknown error.\n");
Aurelien DARRAGON79544102022-11-24 14:27:15 +01008815 err_task_abort:
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008816 hlua_ctx_destroy(hlua);
Olivier Houchard3f795f72019-04-17 22:51:06 +02008817 task_destroy(task);
Emeric Brun253e53e2017-10-17 18:58:40 +02008818 task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008819 break;
8820 }
Emeric Brun253e53e2017-10-17 18:58:40 +02008821 return task;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008822}
8823
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008824/* This function is an LUA binding that register LUA function to be
8825 * executed after the HAProxy configuration parsing and before the
8826 * HAProxy scheduler starts. This function expect only one LUA
8827 * argument that is a function. This function returns nothing, but
8828 * throws if an error is encountered.
8829 */
8830__LJMP static int hlua_register_init(lua_State *L)
8831{
8832 struct hlua_init_function *init;
8833 int ref;
8834
8835 MAY_LJMP(check_args(L, 1, "register_init"));
8836
Aurelien DARRAGON87f52972023-02-24 09:43:54 +01008837 if (hlua_gethlua(L)) {
8838 /* runtime processing */
8839 WILL_LJMP(luaL_error(L, "register_init: not available outside of body context"));
8840 }
8841
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008842 ref = MAY_LJMP(hlua_checkfunction(L, 1));
8843
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02008844 init = calloc(1, sizeof(*init));
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +01008845 if (!init) {
8846 hlua_unref(L, ref);
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01008847 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +01008848 }
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008849
8850 init->function_ref = ref;
Willy Tarreau2b718102021-04-21 07:32:39 +02008851 LIST_APPEND(&hlua_init_functions[hlua_state_id], &init->l);
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008852 return 0;
8853}
8854
Ilya Shipitsin6f86eaa2022-11-30 16:22:42 +05008855/* This function is an LUA binding. It permits to register a task
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008856 * executed in parallel of the main HAroxy activity. The task is
8857 * created and it is set in the HAProxy scheduler. It can be called
8858 * from the "init" section, "post init" or during the runtime.
8859 *
8860 * Lua prototype:
8861 *
Aurelien DARRAGONb8038992023-03-09 16:48:30 +01008862 * <none> core.register_task(<function>[, <arg1>[, <arg2>[, ...[, <arg4>]]]])
8863 *
8864 * <arg1..4> are optional arguments that will be provided to <function>
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008865 */
Aurelien DARRAGONe0b16352023-04-21 17:38:37 +02008866__LJMP static int hlua_register_task(lua_State *L)
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008867{
Christopher Faulet5294ec02021-04-12 12:24:47 +02008868 struct hlua *hlua = NULL;
8869 struct task *task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008870 int ref;
Aurelien DARRAGONb8038992023-03-09 16:48:30 +01008871 int nb_arg;
8872 int it;
8873 int arg_ref[4]; /* optional arguments */
Thierry Fournier021d9862020-11-28 23:42:03 +01008874 int state_id;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008875
Aurelien DARRAGONb8038992023-03-09 16:48:30 +01008876 nb_arg = lua_gettop(L);
8877 if (nb_arg < 1)
8878 WILL_LJMP(luaL_error(L, "register_task: <func> argument is required"));
8879 else if (nb_arg > 5)
8880 WILL_LJMP(luaL_error(L, "register_task: no more that 4 optional arguments may be provided"));
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008881
Aurelien DARRAGONb8038992023-03-09 16:48:30 +01008882 /* first arg: function ref */
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008883 ref = MAY_LJMP(hlua_checkfunction(L, 1));
8884
Aurelien DARRAGONb8038992023-03-09 16:48:30 +01008885 /* extract optional args (if any) */
8886 it = 0;
8887 while (--nb_arg) {
8888 lua_pushvalue(L, 2 + it);
8889 arg_ref[it] = hlua_ref(L); /* get arg reference */
8890 it += 1;
8891 }
8892 nb_arg = it;
8893
Thierry Fournier75fc0292020-11-28 13:18:56 +01008894 /* Get the reference state. If the reference is NULL, L is the master
8895 * state, otherwise hlua->T is.
8896 */
8897 hlua = hlua_gethlua(L);
8898 if (hlua)
Thierry Fournier021d9862020-11-28 23:42:03 +01008899 /* we are in runtime processing */
8900 state_id = hlua->state_id;
Thierry Fournier75fc0292020-11-28 13:18:56 +01008901 else
Thierry Fournier021d9862020-11-28 23:42:03 +01008902 /* we are in initialization mode */
Thierry Fournierc7492592020-11-28 23:57:24 +01008903 state_id = hlua_state_id;
Thierry Fournier75fc0292020-11-28 13:18:56 +01008904
Willy Tarreaubafbe012017-11-24 17:34:44 +01008905 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008906 if (!hlua)
Christopher Faulet5294ec02021-04-12 12:24:47 +02008907 goto alloc_error;
Christopher Faulet1e8433f2021-03-24 15:03:01 +01008908 HLUA_INIT(hlua);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008909
Thierry Fournier59f11be2020-11-29 00:37:41 +01008910 /* We are in the common lua state, execute the task anywhere,
8911 * otherwise, inherit the current thread identifier
8912 */
8913 if (state_id == 0)
Willy Tarreaubeeabf52021-10-01 18:23:30 +02008914 task = task_new_anywhere();
Thierry Fournier59f11be2020-11-29 00:37:41 +01008915 else
Willy Tarreaubeeabf52021-10-01 18:23:30 +02008916 task = task_new_here();
Willy Tarreaue09101e2018-10-16 17:37:12 +02008917 if (!task)
Christopher Faulet5294ec02021-04-12 12:24:47 +02008918 goto alloc_error;
Willy Tarreaue09101e2018-10-16 17:37:12 +02008919
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008920 task->context = hlua;
8921 task->process = hlua_process_task;
8922
Aurelien DARRAGON6b0b9bd2023-03-21 14:02:16 +01008923 if (!hlua_ctx_init(hlua, state_id, task))
Christopher Faulet5294ec02021-04-12 12:24:47 +02008924 goto alloc_error;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008925
Aurelien DARRAGONb8038992023-03-09 16:48:30 +01008926 /* Ensure there is enough space on the stack for the function
8927 * plus optional arguments
8928 */
8929 if (!lua_checkstack(hlua->T, (1 + nb_arg)))
8930 goto alloc_error;
8931
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008932 /* Restore the function in the stack. */
Aurelien DARRAGON4fdf8b52023-03-20 17:22:37 +01008933 hlua_pushref(hlua->T, ref);
Aurelien DARRAGONbe58d662023-03-13 14:09:21 +01008934 /* function ref not needed anymore since it was pushed to the substack */
8935 hlua_unref(L, ref);
8936
Aurelien DARRAGONb8038992023-03-09 16:48:30 +01008937 hlua->nargs = nb_arg;
8938
8939 /* push optional arguments to the function */
8940 for (it = 0; it < nb_arg; it++) {
8941 /* push arg to the stack */
8942 hlua_pushref(hlua->T, arg_ref[it]);
8943 /* arg ref not needed anymore since it was pushed to the substack */
8944 hlua_unref(L, arg_ref[it]);
8945 }
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008946
8947 /* Schedule task. */
Willy Tarreaue3957f82021-09-30 16:17:37 +02008948 task_wakeup(task, TASK_WOKEN_INIT);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008949
8950 return 0;
Christopher Faulet5294ec02021-04-12 12:24:47 +02008951
8952 alloc_error:
8953 task_destroy(task);
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +01008954 hlua_unref(L, ref);
Aurelien DARRAGONb8038992023-03-09 16:48:30 +01008955 for (it = 0; it < nb_arg; it++) {
8956 hlua_unref(L, arg_ref[it]);
8957 }
Christopher Faulet5294ec02021-04-12 12:24:47 +02008958 hlua_ctx_destroy(hlua);
8959 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
8960 return 0; /* Never reached */
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008961}
8962
Aurelien DARRAGONc84899c2023-02-20 18:18:59 +01008963/* called from unsafe location */
8964static void hlua_event_subscription_destroy(struct hlua_event_sub *hlua_sub)
8965{
8966 /* hlua cleanup */
8967
8968 hlua_lock(hlua_sub->hlua);
8969 /* registry is shared between coroutines */
8970 hlua_unref(hlua_sub->hlua->T, hlua_sub->fcn_ref);
8971 hlua_unlock(hlua_sub->hlua);
8972
8973 hlua_ctx_destroy(hlua_sub->hlua);
8974
8975 /* free */
8976 pool_free(pool_head_hlua_event_sub, hlua_sub);
8977}
8978
8979/* single event handler: hlua ctx is shared between multiple events handlers
8980 * issued from the same subscription. Thus, it is not destroyed when the event
8981 * is processed: it is destroyed when no more events are expected for the
8982 * subscription (ie: when the subscription ends).
8983 *
8984 * Moreover, events are processed sequentially within the subscription:
8985 * one event must be fully processed before another one may be processed.
8986 * This ensures proper consistency for lua event handling from an ordering
8987 * point of view. This is especially useful with server events for example
8988 * where ADD/DEL/UP/DOWN events ordering really matters to trigger specific
8989 * actions from lua (e.g.: sending emails or making API calls).
8990 *
8991 * Due to this design, each lua event handler is pleased to process the event
8992 * as fast as possible to prevent the event queue from growing up.
8993 * Strictly speaking, there is no runtime limit for the callback function
8994 * (timeout set to default task timeout), but if the event queue goes past
8995 * the limit of unconsumed events an error will be reported and the
8996 * susbscription will pause itself for as long as it takes for the handler to
8997 * catch up (events will be lost as a result).
8998 * If the event handler does not need the sequential ordering and wants to
8999 * process multiple events at a time, it may spawn a new side-task using
9000 * 'core.register_task' to delegate the event handling and make parallel event
9001 * processing within the same subscription set.
9002 */
9003static void hlua_event_handler(struct hlua *hlua)
9004{
9005 enum hlua_exec status;
9006
9007 /* If it is the first call to the task, we must initialize the
9008 * execution timeouts.
9009 */
Aurelien DARRAGONda9503c2022-11-25 09:10:07 +01009010 if (!HLUA_IS_RUNNING(hlua))
9011 hlua_timer_init(&hlua->timer, hlua_timeout_task);
Aurelien DARRAGONc84899c2023-02-20 18:18:59 +01009012
9013 /* make sure to reset the task expiry before each hlua_ctx_resume()
9014 * since the task is re-used for multiple cb function calls
9015 * We couldn't risk to have t->expire pointing to a past date because
9016 * it was set during last function invocation but was never reset since
9017 * (ie: E_AGAIN)
9018 */
9019 hlua->task->expire = TICK_ETERNITY;
9020
9021 /* Execute the Lua code. */
9022 status = hlua_ctx_resume(hlua, 1);
9023
9024 switch (status) {
9025 /* finished or yield */
9026 case HLUA_E_OK:
9027 break;
9028
9029 case HLUA_E_AGAIN: /* co process or timeout wake me later. */
9030 notification_gc(&hlua->com);
9031 hlua->task->expire = hlua->wake_time;
9032 break;
9033
9034 /* finished with error. */
9035 case HLUA_E_ETMOUT:
9036 SEND_ERR(NULL, "Lua event_hdl: execution timeout.\n");
9037 break;
9038
9039 case HLUA_E_ERRMSG:
9040 SEND_ERR(NULL, "Lua event_hdl: %s.\n", lua_tostring(hlua->T, -1));
9041 break;
9042
9043 case HLUA_E_ERR:
9044 default:
9045 SEND_ERR(NULL, "Lua event_hdl: unknown error.\n");
9046 break;
9047 }
9048}
9049
Aurelien DARRAGONc99f3ad2023-04-12 15:47:16 +02009050__LJMP static void hlua_event_hdl_cb_push_event_checkres(lua_State *L,
9051 struct event_hdl_cb_data_server_checkres *check)
9052{
9053 lua_pushstring(L, "agent");
9054 lua_pushboolean(L, check->agent);
9055 lua_settable(L, -3);
9056 lua_pushstring(L, "result");
9057 switch (check->result) {
9058 case CHK_RES_FAILED:
9059 lua_pushstring(L, "FAILED");
9060 break;
9061 case CHK_RES_PASSED:
9062 lua_pushstring(L, "PASSED");
9063 break;
9064 case CHK_RES_CONDPASS:
9065 lua_pushstring(L, "CONDPASS");
9066 break;
9067 default:
9068 lua_pushnil(L);
9069 break;
9070 }
9071 lua_settable(L, -3);
9072
9073 lua_pushstring(L, "duration");
9074 lua_pushinteger(L, check->duration);
9075 lua_settable(L, -3);
9076
9077 lua_pushstring(L, "reason");
9078 lua_newtable(L);
9079
9080 lua_pushstring(L, "short");
9081 lua_pushstring(L, get_check_status_info(check->reason.status));
9082 lua_settable(L, -3);
9083 lua_pushstring(L, "desc");
9084 lua_pushstring(L, get_check_status_description(check->reason.status));
9085 lua_settable(L, -3);
9086 if (check->reason.status >= HCHK_STATUS_L57DATA) {
9087 /* code only available when the check reached data analysis stage */
9088 lua_pushstring(L, "code");
9089 lua_pushinteger(L, check->reason.code);
9090 lua_settable(L, -3);
9091 }
9092
9093 lua_settable(L, -3); /* reason table */
9094
9095 lua_pushstring(L, "health");
9096 lua_newtable(L);
9097
9098 lua_pushstring(L, "cur");
9099 lua_pushinteger(L, check->health.cur);
9100 lua_settable(L, -3);
9101 lua_pushstring(L, "rise");
9102 lua_pushinteger(L, check->health.rise);
9103 lua_settable(L, -3);
9104 lua_pushstring(L, "fall");
9105 lua_pushinteger(L, check->health.fall);
9106 lua_settable(L, -3);
9107
9108 lua_settable(L, -3); /* health table */
9109}
9110
Aurelien DARRAGON2f6a07d2023-03-27 18:16:21 +02009111/* This function pushes various arguments such as event type and event data to
9112 * the lua function that will be called to consume the event.
9113 */
9114__LJMP static void hlua_event_hdl_cb_push_args(struct hlua_event_sub *hlua_sub,
9115 struct event_hdl_async_event *e)
Aurelien DARRAGONc84899c2023-02-20 18:18:59 +01009116{
9117 struct hlua *hlua = hlua_sub->hlua;
Aurelien DARRAGON2f6a07d2023-03-27 18:16:21 +02009118 struct event_hdl_sub_type event = e->type;
9119 void *data = e->data;
Aurelien DARRAGONc84899c2023-02-20 18:18:59 +01009120
Aurelien DARRAGON2f6a07d2023-03-27 18:16:21 +02009121 /* push event type */
Aurelien DARRAGONc84899c2023-02-20 18:18:59 +01009122 hlua->nargs = 1;
9123 lua_pushstring(hlua->T, event_hdl_sub_type_to_string(event));
Aurelien DARRAGON2f6a07d2023-03-27 18:16:21 +02009124
9125 /* push event data (according to event type) */
Aurelien DARRAGONc84899c2023-02-20 18:18:59 +01009126 if (event_hdl_sub_family_equal(EVENT_HDL_SUB_SERVER, event)) {
9127 struct event_hdl_cb_data_server *e_server = data;
9128 struct proxy *px;
9129 struct server *server;
9130
9131 hlua->nargs += 1;
9132 lua_newtable(hlua->T);
9133 /* Add server name */
9134 lua_pushstring(hlua->T, "name");
9135 lua_pushstring(hlua->T, e_server->safe.name);
9136 lua_settable(hlua->T, -3);
9137 /* Add server puid */
9138 lua_pushstring(hlua->T, "puid");
9139 lua_pushinteger(hlua->T, e_server->safe.puid);
9140 lua_settable(hlua->T, -3);
9141 /* Add server rid */
9142 lua_pushstring(hlua->T, "rid");
9143 lua_pushinteger(hlua->T, e_server->safe.rid);
9144 lua_settable(hlua->T, -3);
9145 /* Add server proxy name */
9146 lua_pushstring(hlua->T, "proxy_name");
9147 lua_pushstring(hlua->T, e_server->safe.proxy_name);
9148 lua_settable(hlua->T, -3);
Aurelien DARRAGON55f84c72023-03-22 17:49:04 +01009149 /* Add server proxy uuid */
9150 lua_pushstring(hlua->T, "proxy_uuid");
9151 lua_pushinteger(hlua->T, e_server->safe.proxy_uuid);
9152 lua_settable(hlua->T, -3);
Aurelien DARRAGONc84899c2023-02-20 18:18:59 +01009153
Aurelien DARRAGONc99f3ad2023-04-12 15:47:16 +02009154 /* special events, fetch additional info with explicit type casting */
9155 if (event_hdl_sub_type_equal(EVENT_HDL_SUB_SERVER_STATE, event)) {
9156 struct event_hdl_cb_data_server_state *state = data;
9157 int it;
9158
9159 if (!lua_checkstack(hlua->T, 20))
9160 WILL_LJMP(luaL_error(hlua->T, "Lua out of memory error."));
9161
9162 /* state subclass */
9163 lua_pushstring(hlua->T, "state");
9164 lua_newtable(hlua->T);
9165
9166 lua_pushstring(hlua->T, "admin");
9167 lua_pushboolean(hlua->T, state->safe.type);
9168 lua_settable(hlua->T, -3);
9169
9170 /* is it because of a check ? */
9171 if (!state->safe.type &&
9172 (state->safe.op_st_chg.cause == SRV_OP_STCHGC_HEALTH ||
9173 state->safe.op_st_chg.cause == SRV_OP_STCHGC_AGENT)) {
9174 /* yes, provide check result */
9175 lua_pushstring(hlua->T, "check");
9176 lua_newtable(hlua->T);
9177 hlua_event_hdl_cb_push_event_checkres(hlua->T, &state->safe.op_st_chg.check);
9178 lua_settable(hlua->T, -3); /* check table */
9179 }
9180
9181 lua_pushstring(hlua->T, "cause");
9182 if (state->safe.type)
9183 lua_pushstring(hlua->T, srv_adm_st_chg_cause(state->safe.adm_st_chg.cause));
9184 else
9185 lua_pushstring(hlua->T, srv_op_st_chg_cause(state->safe.op_st_chg.cause));
9186 lua_settable(hlua->T, -3);
9187
9188 /* old_state, new_state */
9189 for (it = 0; it < 2; it++) {
9190 enum srv_state srv_state = (!it) ? state->safe.old_state : state->safe.new_state;
9191
9192 lua_pushstring(hlua->T, (!it) ? "old_state" : "new_state");
9193 switch (srv_state) {
9194 case SRV_ST_STOPPED:
9195 lua_pushstring(hlua->T, "STOPPED");
9196 break;
9197 case SRV_ST_STOPPING:
9198 lua_pushstring(hlua->T, "STOPPING");
9199 break;
9200 case SRV_ST_STARTING:
9201 lua_pushstring(hlua->T, "STARTING");
9202 break;
9203 case SRV_ST_RUNNING:
9204 lua_pushstring(hlua->T, "RUNNING");
9205 break;
9206 default:
9207 lua_pushnil(hlua->T);
9208 break;
9209 }
9210 lua_settable(hlua->T, -3);
9211 }
9212
9213 /* requeued */
9214 lua_pushstring(hlua->T, "requeued");
9215 lua_pushinteger(hlua->T, state->safe.requeued);
9216 lua_settable(hlua->T, -3);
9217
9218 lua_settable(hlua->T, -3); /* state table */
9219 }
Aurelien DARRAGON948dd3d2023-04-26 11:27:09 +02009220 else if (event_hdl_sub_type_equal(EVENT_HDL_SUB_SERVER_ADMIN, event)) {
9221 struct event_hdl_cb_data_server_admin *admin = data;
9222 int it;
9223
9224 if (!lua_checkstack(hlua->T, 20))
9225 WILL_LJMP(luaL_error(hlua->T, "Lua out of memory error."));
9226
9227 /* admin subclass */
9228 lua_pushstring(hlua->T, "admin");
9229 lua_newtable(hlua->T);
9230
9231 lua_pushstring(hlua->T, "cause");
9232 lua_pushstring(hlua->T, srv_adm_st_chg_cause(admin->safe.cause));
9233 lua_settable(hlua->T, -3);
9234
9235 /* old_admin, new_admin */
9236 for (it = 0; it < 2; it++) {
9237 enum srv_admin srv_admin = (!it) ? admin->safe.old_admin : admin->safe.new_admin;
9238
9239 lua_pushstring(hlua->T, (!it) ? "old_admin" : "new_admin");
9240
9241 /* admin state matrix */
9242 lua_newtable(hlua->T);
9243
9244 lua_pushstring(hlua->T, "MAINT");
9245 lua_pushboolean(hlua->T, srv_admin & SRV_ADMF_MAINT);
9246 lua_settable(hlua->T, -3);
9247 lua_pushstring(hlua->T, "FMAINT");
9248 lua_pushboolean(hlua->T, srv_admin & SRV_ADMF_FMAINT);
9249 lua_settable(hlua->T, -3);
9250 lua_pushstring(hlua->T, "IMAINT");
9251 lua_pushboolean(hlua->T, srv_admin & SRV_ADMF_IMAINT);
9252 lua_settable(hlua->T, -3);
9253 lua_pushstring(hlua->T, "RMAINT");
9254 lua_pushboolean(hlua->T, srv_admin & SRV_ADMF_RMAINT);
9255 lua_settable(hlua->T, -3);
9256 lua_pushstring(hlua->T, "CMAINT");
9257 lua_pushboolean(hlua->T, srv_admin & SRV_ADMF_CMAINT);
9258 lua_settable(hlua->T, -3);
9259
9260 lua_pushstring(hlua->T, "DRAIN");
9261 lua_pushboolean(hlua->T, srv_admin & SRV_ADMF_DRAIN);
9262 lua_settable(hlua->T, -3);
9263 lua_pushstring(hlua->T, "FDRAIN");
9264 lua_pushboolean(hlua->T, srv_admin & SRV_ADMF_FDRAIN);
9265 lua_settable(hlua->T, -3);
9266 lua_pushstring(hlua->T, "IDRAIN");
9267 lua_pushboolean(hlua->T, srv_admin & SRV_ADMF_IDRAIN);
9268 lua_settable(hlua->T, -3);
9269
9270 lua_settable(hlua->T, -3); /* matrix table */
9271 }
9272 /* requeued */
9273 lua_pushstring(hlua->T, "requeued");
9274 lua_pushinteger(hlua->T, admin->safe.requeued);
9275 lua_settable(hlua->T, -3);
9276
9277 lua_settable(hlua->T, -3); /* admin table */
9278 }
Aurelien DARRAGON0bd53b22023-03-30 15:53:33 +02009279 else if (event_hdl_sub_type_equal(EVENT_HDL_SUB_SERVER_CHECK, event)) {
9280 struct event_hdl_cb_data_server_check *check = data;
9281
9282 if (!lua_checkstack(hlua->T, 20))
9283 WILL_LJMP(luaL_error(hlua->T, "Lua out of memory error."));
9284
9285 /* check subclass */
9286 lua_pushstring(hlua->T, "check");
9287 lua_newtable(hlua->T);
9288
9289 /* check result snapshot */
9290 hlua_event_hdl_cb_push_event_checkres(hlua->T, &check->safe.res);
9291
9292 lua_settable(hlua->T, -3); /* check table */
9293 }
Aurelien DARRAGONc99f3ad2023-04-12 15:47:16 +02009294
Aurelien DARRAGONc84899c2023-02-20 18:18:59 +01009295 /* attempt to provide reference server object
9296 * (if it wasn't removed yet, SERVER_DEL will never succeed here)
9297 */
Aurelien DARRAGON3d9bf4e2023-03-22 17:46:12 +01009298 px = proxy_find_by_id(e_server->safe.proxy_uuid, PR_CAP_BE, 0);
Aurelien DARRAGONc84899c2023-02-20 18:18:59 +01009299 BUG_ON(!px);
9300 server = findserver_unique_id(px, e_server->safe.puid, e_server->safe.rid);
9301 if (server) {
9302 lua_pushstring(hlua->T, "reference");
9303 hlua_fcn_new_server(hlua->T, server);
9304 lua_settable(hlua->T, -3);
9305 }
9306 }
9307 /* sub mgmt */
9308 hlua->nargs += 1;
9309 hlua_fcn_new_event_sub(hlua->T, hlua_sub->sub);
Aurelien DARRAGON096b3832023-04-20 11:32:46 +02009310
9311 /* when? */
9312 hlua->nargs += 1;
9313 lua_pushinteger(hlua->T, e->when.tv_sec);
Aurelien DARRAGONc84899c2023-02-20 18:18:59 +01009314}
9315
9316/* events runner: if there's an ongoing hlua event handling process, finish it
9317 * then, check if there are new events waiting to be processed
9318 * (events are processed sequentially)
9319 *
9320 * We have a safety measure to warn/guard if the event queue is growing up
9321 * too much due to many events being generated and lua handler is unable to
9322 * keep up the pace (e.g.: when the event queue grows past 100 unconsumed events).
9323 * TODO: make it tunable
9324 */
9325static struct task *hlua_event_runner(struct task *task, void *context, unsigned int state)
9326{
9327 struct hlua_event_sub *hlua_sub = context;
9328 struct event_hdl_async_event *event;
9329 const char *error = NULL;
9330
9331 if (!hlua_sub->paused && event_hdl_async_equeue_size(&hlua_sub->equeue) > 100) {
9332 const char *trace;
9333
9334 /* We reached the limit of pending events in the queue: we should
9335 * warn the user, and temporarily pause the subscription to give a chance
Ilya Shipitsinccf80122023-04-22 20:20:39 +02009336 * to the handler to catch up? (it also prevents resource shortage since
Aurelien DARRAGONc84899c2023-02-20 18:18:59 +01009337 * the queue could grow indefinitely otherwise)
9338 * TODO: find a way to inform the handler that it missed some events
9339 * (example: stats within the subscription in event_hdl api exposed via lua api?)
9340 *
9341 * Nonetheless, reaching this limit means that the handler is not fast enough
9342 * and/or that it subscribed to events that happen too frequently and did not
9343 * expect it. This could come from an inadequate design in the user's script.
9344 */
9345 event_hdl_pause(hlua_sub->sub);
9346 hlua_sub->paused = 1;
9347
9348 /* The following Lua calls can fail. */
9349 if (!SET_SAFE_LJMP(hlua_sub->hlua))
9350 trace = NULL;
9351 trace = hlua_traceback(hlua_sub->hlua->T, ", ");
9352 /* At this point the execution is safe. */
9353 RESET_SAFE_LJMP(hlua_sub->hlua);
9354
9355 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 : ""));
9356 }
9357
9358 if (HLUA_IS_RUNNING(hlua_sub->hlua)) {
9359 /* ongoing hlua event handler, resume it */
9360 hlua_event_handler(hlua_sub->hlua);
9361 } else if ((event = event_hdl_async_equeue_pop(&hlua_sub->equeue))) { /* check for new events */
9362 if (event_hdl_sub_type_equal(event->type, EVENT_HDL_SUB_END)) {
9363 /* ending event: no more events to come */
9364 event_hdl_async_free_event(event);
9365 task_destroy(task);
9366 hlua_event_subscription_destroy(hlua_sub);
9367 return NULL;
9368 }
9369 /* new event: start processing it */
9370
9371 /* The following Lua calls can fail. */
9372 if (!SET_SAFE_LJMP(hlua_sub->hlua)) {
9373 if (lua_type(hlua_sub->hlua->T, -1) == LUA_TSTRING)
9374 error = lua_tostring(hlua_sub->hlua->T, -1);
9375 else
9376 error = "critical error";
9377 ha_alert("Lua event_hdl: %s.\n", error);
9378 goto skip_event;
9379 }
9380
9381 /* Check stack available size. */
9382 if (!lua_checkstack(hlua_sub->hlua->T, 5)) {
9383 ha_alert("Lua event_hdl: full stack.\n");
9384 RESET_SAFE_LJMP(hlua_sub->hlua);
9385 goto skip_event;
9386 }
9387
9388 /* Restore the function in the stack. */
9389 hlua_pushref(hlua_sub->hlua->T, hlua_sub->fcn_ref);
9390
9391 /* push args */
9392 hlua_sub->hlua->nargs = 0;
Aurelien DARRAGON2f6a07d2023-03-27 18:16:21 +02009393 MAY_LJMP(hlua_event_hdl_cb_push_args(hlua_sub, event));
Aurelien DARRAGONc84899c2023-02-20 18:18:59 +01009394
9395 /* At this point the execution is safe. */
9396 RESET_SAFE_LJMP(hlua_sub->hlua);
9397
9398 /* At this point the event was successfully translated into hlua ctx,
Ilya Shipitsinccf80122023-04-22 20:20:39 +02009399 * or hlua error occurred, so we can safely discard it
Aurelien DARRAGONc84899c2023-02-20 18:18:59 +01009400 */
9401 event_hdl_async_free_event(event);
9402 event = NULL;
9403
9404 hlua_event_handler(hlua_sub->hlua);
9405 skip_event:
9406 if (event)
9407 event_hdl_async_free_event(event);
9408
9409 }
9410
9411 if (!HLUA_IS_RUNNING(hlua_sub->hlua)) {
9412 /* we just finished the processing of one event..
9413 * check for new events before becoming idle
9414 */
9415 if (!event_hdl_async_equeue_isempty(&hlua_sub->equeue)) {
9416 /* more events to process, make sure the task
9417 * will be resumed ASAP to process pending events
9418 */
9419 task_wakeup(task, TASK_WOKEN_OTHER);
9420 }
9421 else if (hlua_sub->paused) {
Ilya Shipitsinccf80122023-04-22 20:20:39 +02009422 /* empty queue, the handler caught up: resume the subscription */
Aurelien DARRAGONc84899c2023-02-20 18:18:59 +01009423 event_hdl_resume(hlua_sub->sub);
9424 hlua_sub->paused = 0;
9425 }
9426 }
9427
9428 return task;
9429}
9430
9431/* Must be called directly under lua protected/safe environment
9432 * (not from external callback)
9433 * <fcn_ref> should NOT be dropped after the function successfully returns:
9434 * it will be done automatically in hlua_event_subscription_destroy() when the
9435 * subscription ends.
9436 *
9437 * Returns the new subscription on success and NULL on failure (memory error)
9438 */
9439static struct event_hdl_sub *hlua_event_subscribe(event_hdl_sub_list *list, struct event_hdl_sub_type e_type,
9440 int state_id, int fcn_ref)
9441{
9442 struct hlua_event_sub *hlua_sub;
9443 struct task *task = NULL;
9444
9445 hlua_sub = pool_alloc(pool_head_hlua_event_sub);
9446 if (!hlua_sub)
9447 goto mem_error;
9448 hlua_sub->task = NULL;
9449 hlua_sub->hlua = NULL;
9450 hlua_sub->paused = 0;
9451 if ((task = task_new_here()) == NULL) {
9452 ha_alert("out of memory while allocating hlua event task");
9453 goto mem_error;
9454 }
9455 task->process = hlua_event_runner;
9456 task->context = hlua_sub;
9457 event_hdl_async_equeue_init(&hlua_sub->equeue);
9458 hlua_sub->task = task;
9459 hlua_sub->fcn_ref = fcn_ref;
9460 hlua_sub->state_id = state_id;
9461 hlua_sub->hlua = pool_alloc(pool_head_hlua);
9462 if (!hlua_sub->hlua)
9463 goto mem_error;
9464 HLUA_INIT(hlua_sub->hlua);
9465 if (!hlua_ctx_init(hlua_sub->hlua, hlua_sub->state_id, task))
9466 goto mem_error;
9467
9468 hlua_sub->sub = event_hdl_subscribe_ptr(list, e_type,
9469 EVENT_HDL_ASYNC_TASK(&hlua_sub->equeue,
9470 task,
9471 hlua_sub,
9472 NULL));
9473 if (!hlua_sub->sub)
9474 goto mem_error;
9475
9476 return hlua_sub->sub; /* returns pointer to event_hdl_sub struct */
9477
9478 mem_error:
9479 if (hlua_sub) {
Tim Duesterhusfe83f582023-04-22 17:47:34 +02009480 task_destroy(hlua_sub->task);
Aurelien DARRAGONc84899c2023-02-20 18:18:59 +01009481 if (hlua_sub->hlua)
9482 hlua_ctx_destroy(hlua_sub->hlua);
9483 pool_free(pool_head_hlua_event_sub, hlua_sub);
9484 }
9485
9486 return NULL;
9487}
9488
9489/* looks for an array of strings referring to a composition of event_hdl subscription
9490 * types at <index> in <L> stack
9491 */
9492__LJMP static struct event_hdl_sub_type hlua_check_event_sub_types(lua_State *L, int index)
9493{
9494 struct event_hdl_sub_type subscriptions;
9495 const char *msg;
9496
9497 if (lua_type(L, index) != LUA_TTABLE) {
9498 msg = lua_pushfstring(L, "table of strings expected, got %s", luaL_typename(L, index));
9499 luaL_argerror(L, index, msg);
9500 }
9501
9502 subscriptions = EVENT_HDL_SUB_NONE;
9503
9504 /* browse the argument as an array. */
9505 lua_pushnil(L);
9506 while (lua_next(L, index) != 0) {
9507 if (lua_type(L, -1) != LUA_TSTRING) {
9508 msg = lua_pushfstring(L, "table of strings expected, got %s", luaL_typename(L, index));
9509 luaL_argerror(L, index, msg);
9510 }
9511
9512 if (event_hdl_sub_type_equal(EVENT_HDL_SUB_NONE, event_hdl_string_to_sub_type(lua_tostring(L, -1)))) {
9513 msg = lua_pushfstring(L, "'%s' event type is unknown", lua_tostring(L, -1));
9514 luaL_argerror(L, index, msg);
9515 }
9516
9517 /* perform subscriptions |= current sub */
9518 subscriptions = event_hdl_sub_type_add(subscriptions, event_hdl_string_to_sub_type(lua_tostring(L, -1)));
9519
9520 /* pop the current value. */
9521 lua_pop(L, 1);
9522 }
9523
9524 return subscriptions;
9525}
9526
9527/* Wrapper for hlua_fcn_new_event_sub(): catch errors raised by
9528 * the function to prevent LJMP
9529 *
Ilya Shipitsinccf80122023-04-22 20:20:39 +02009530 * If no error occurred, the function returns 1, else it returns 0 and
Aurelien DARRAGONc84899c2023-02-20 18:18:59 +01009531 * the error message is pushed at the top of the stack
9532 */
9533__LJMP static int _hlua_new_event_sub_safe(lua_State *L)
9534{
9535 struct event_hdl_sub *sub = lua_touserdata(L, 1);
9536
9537 /* this function may raise errors */
9538 return MAY_LJMP(hlua_fcn_new_event_sub(L, sub));
9539}
9540static int hlua_new_event_sub_safe(lua_State *L, struct event_hdl_sub *sub)
9541{
9542 if (!lua_checkstack(L, 2))
9543 return 0;
9544 lua_pushcfunction(L, _hlua_new_event_sub_safe);
9545 lua_pushlightuserdata(L, sub);
9546 switch (lua_pcall(L, 1, 1, 0)) {
9547 case LUA_OK:
9548 return 1;
9549 default:
Ilya Shipitsinccf80122023-04-22 20:20:39 +02009550 /* error was caught */
Aurelien DARRAGONc84899c2023-02-20 18:18:59 +01009551 return 0;
9552 }
9553}
9554
9555/* This function is a LUA helper used for registering lua event callbacks.
9556 * It expects an event subscription array and the function to be executed
9557 * when subscribed events occur (stack arguments).
9558 * It can be called from the "init" section, "post init" or during the runtime.
9559 *
9560 * <sub_list> is the subscription list where the subscription will be attempted
9561 *
9562 * Pushes the newly allocated subscription on the stack on success
9563 */
9564__LJMP int hlua_event_sub(lua_State *L, event_hdl_sub_list *sub_list)
9565{
9566 struct hlua *hlua;
9567 struct event_hdl_sub *sub;
9568 struct event_hdl_sub_type subscriptions;
9569 int fcn_ref;
9570 int state_id;
9571
9572 MAY_LJMP(check_args(L, 2, "event_sub"));
9573
9574 /* Get the reference state */
9575 hlua = hlua_gethlua(L);
9576 if (hlua)
9577 /* we are in runtime processing, any thread may subscribe to events:
9578 * subscription events will be handled by the thread who performed
9579 * the registration.
9580 */
9581 state_id = hlua->state_id;
9582 else {
9583 /* we are in initialization mode, only thread 0 (actual calling thread)
9584 * may subscribe to events to prevent the same handler (from different lua
9585 * stacks) from being registered multiple times
9586 *
9587 * hlua_state_id == 0: monostack (lua-load)
9588 * hlua_state_id > 0: hlua_state_id=tid+1, multi-stack (lua-load-per-thread)
9589 * (thus if hlua_state_id > 1, it means we are not in primary thread ctx)
9590 */
9591 if (hlua_state_id > 1)
9592 return 0; /* skip registration */
9593 state_id = hlua_state_id;
9594 }
9595
9596 /* First argument : event subscriptions. */
9597 subscriptions = MAY_LJMP(hlua_check_event_sub_types(L, 1));
9598
9599 if (event_hdl_sub_type_equal(subscriptions, EVENT_HDL_SUB_NONE)) {
9600 WILL_LJMP(luaL_error(L, "event_sub: no valid event types were provided"));
9601 return 0; /* Never reached */
9602 }
9603
9604 /* Second argument : lua function. */
9605 fcn_ref = MAY_LJMP(hlua_checkfunction(L, 2));
9606
9607 /* try to subscribe */
9608 sub = hlua_event_subscribe(sub_list, subscriptions, state_id, fcn_ref);
9609 if (!sub) {
9610 hlua_unref(L, fcn_ref);
9611 WILL_LJMP(luaL_error(L, "event_sub: lua out of memory error"));
9612 return 0; /* Never reached */
9613 }
9614
9615 /* push the subscription to the stack
9616 *
9617 * Here we use the safe function so that lua errors will be
9618 * handled explicitly to prevent 'sub' from being lost
9619 */
9620 if (!hlua_new_event_sub_safe(L, sub)) {
9621 /* Some events could already be pending in the handler's queue.
9622 * However it is wiser to cancel the subscription since we are unable to
9623 * provide a valid reference to it.
9624 * Pending events will be delivered (unless lua keeps raising errors).
9625 */
9626 event_hdl_unsubscribe(sub); /* cancel the subscription */
9627 WILL_LJMP(luaL_error(L, "event_sub: cannot push the subscription (%s)", lua_tostring(L, -1)));
9628 return 0; /* Never reached */
9629 }
9630 event_hdl_drop(sub); /* sub has been duplicated, discard old ref */
9631
9632 return 1;
9633}
9634
9635/* This function is a LUA wrapper used for registering global lua event callbacks
9636 * The new subscription is pushed onto the stack on success
9637 * Returns the number of arguments pushed to the stack (1 for success)
9638 */
9639__LJMP static int hlua_event_global_sub(lua_State *L)
9640{
9641 /* NULL <sub_list> = global subscription list */
9642 return MAY_LJMP(hlua_event_sub(L, NULL));
9643}
9644
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009645/* Wrapper called by HAProxy to execute an LUA converter. This wrapper
9646 * doesn't allow "yield" functions because the HAProxy engine cannot
9647 * resume converters.
9648 */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02009649static int hlua_sample_conv_wrapper(const struct arg *arg_p, struct sample *smp, void *private)
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009650{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02009651 struct hlua_function *fcn = private;
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02009652 struct stream *stream = smp->strm;
Thierry Fournierfd107a22016-02-19 19:57:23 +01009653 const char *error;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009654
Willy Tarreaube508f12016-03-10 11:47:01 +01009655 if (!stream)
9656 return 0;
9657
Willy Tarreau87b09662015-04-03 00:22:06 +02009658 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01009659 * Lua context can be not initialized. This behavior
9660 * permits to save performances because a systematic
9661 * Lua initialization cause 5% performances loss.
9662 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009663 if (!stream->hlua) {
Christopher Faulet1e8433f2021-03-24 15:03:01 +01009664 struct hlua *hlua;
9665
9666 hlua = pool_alloc(pool_head_hlua);
9667 if (!hlua) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009668 SEND_ERR(stream->be, "Lua converter '%s': can't initialize Lua context.\n", fcn->name);
9669 return 0;
9670 }
Christopher Faulet1e8433f2021-03-24 15:03:01 +01009671 HLUA_INIT(hlua);
9672 stream->hlua = hlua;
Aurelien DARRAGON6b0b9bd2023-03-21 14:02:16 +01009673 if (!hlua_ctx_init(stream->hlua, fcn_ref_to_stack_id(fcn), stream->task)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009674 SEND_ERR(stream->be, "Lua converter '%s': can't initialize Lua context.\n", fcn->name);
9675 return 0;
9676 }
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01009677 }
9678
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009679 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009680 if (!HLUA_IS_RUNNING(stream->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02009681
9682 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009683 if (!SET_SAFE_LJMP(stream->hlua)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009684 if (lua_type(stream->hlua->T, -1) == LUA_TSTRING)
9685 error = lua_tostring(stream->hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +01009686 else
9687 error = "critical error";
9688 SEND_ERR(stream->be, "Lua converter '%s': %s.\n", fcn->name, error);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02009689 return 0;
9690 }
9691
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009692 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009693 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009694 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009695 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009696 return 0;
9697 }
9698
9699 /* Restore the function in the stack. */
Aurelien DARRAGON4fdf8b52023-03-20 17:22:37 +01009700 hlua_pushref(stream->hlua->T, fcn->function_ref[stream->hlua->state_id]);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009701
9702 /* convert input sample and pust-it in the stack. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009703 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009704 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009705 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009706 return 0;
9707 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009708 hlua_smp2lua(stream->hlua->T, smp);
9709 stream->hlua->nargs = 1;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009710
9711 /* push keywords in the stack. */
9712 if (arg_p) {
9713 for (; arg_p->type != ARGT_STOP; arg_p++) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009714 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009715 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009716 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009717 return 0;
9718 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009719 hlua_arg2lua(stream->hlua->T, arg_p);
9720 stream->hlua->nargs++;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009721 }
9722 }
9723
Thierry FOURNIERbd413492015-03-03 16:52:26 +01009724 /* We must initialize the execution timeouts. */
Aurelien DARRAGONda9503c2022-11-25 09:10:07 +01009725 hlua_timer_init(&stream->hlua->timer, hlua_timeout_session);
Thierry FOURNIERbd413492015-03-03 16:52:26 +01009726
Thierry FOURNIERbabae282015-09-17 11:36:37 +02009727 /* At this point the execution is safe. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009728 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009729 }
9730
9731 /* Execute the function. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009732 switch (hlua_ctx_resume(stream->hlua, 0)) {
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009733 /* finished. */
9734 case HLUA_E_OK:
Thierry FOURNIERfd80df12017-05-12 16:32:20 +02009735 /* If the stack is empty, the function fails. */
9736 if (lua_gettop(stream->hlua->T) <= 0)
9737 return 0;
9738
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009739 /* Convert the returned value in sample. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009740 hlua_lua2smp(stream->hlua->T, -1, smp);
9741 lua_pop(stream->hlua->T, 1);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009742 return 1;
9743
9744 /* yield. */
9745 case HLUA_E_AGAIN:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009746 SEND_ERR(stream->be, "Lua converter '%s': cannot use yielded functions.\n", fcn->name);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009747 return 0;
9748
9749 /* finished with error. */
9750 case HLUA_E_ERRMSG:
9751 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009752 SEND_ERR(stream->be, "Lua converter '%s': %s.\n",
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009753 fcn->name, lua_tostring(stream->hlua->T, -1));
9754 lua_pop(stream->hlua->T, 1);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009755 return 0;
9756
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009757 case HLUA_E_ETMOUT:
9758 SEND_ERR(stream->be, "Lua converter '%s': execution timeout.\n", fcn->name);
9759 return 0;
9760
9761 case HLUA_E_NOMEM:
9762 SEND_ERR(stream->be, "Lua converter '%s': out of memory error.\n", fcn->name);
9763 return 0;
9764
9765 case HLUA_E_YIELD:
9766 SEND_ERR(stream->be, "Lua converter '%s': yield functions like core.tcp() or core.sleep() are not allowed.\n", fcn->name);
9767 return 0;
9768
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009769 case HLUA_E_ERR:
9770 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009771 SEND_ERR(stream->be, "Lua converter '%s' returns an unknown error.\n", fcn->name);
Willy Tarreau14de3952022-11-14 07:08:28 +01009772 __fallthrough;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009773
9774 default:
9775 return 0;
9776 }
9777}
9778
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009779/* Wrapper called by HAProxy to execute a sample-fetch. this wrapper
9780 * doesn't allow "yield" functions because the HAProxy engine cannot
Willy Tarreaube508f12016-03-10 11:47:01 +01009781 * resume sample-fetches. This function will be called by the sample
9782 * fetch engine to call lua-based fetch operations.
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009783 */
Thierry FOURNIER0786d052015-05-11 15:42:45 +02009784static int hlua_sample_fetch_wrapper(const struct arg *arg_p, struct sample *smp,
9785 const char *kw, void *private)
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009786{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02009787 struct hlua_function *fcn = private;
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02009788 struct stream *stream = smp->strm;
Thierry Fournierfd107a22016-02-19 19:57:23 +01009789 const char *error;
Christopher Faulet8c9e6bb2021-08-06 16:29:41 +02009790 unsigned int hflags = HLUA_TXN_NOTERM | HLUA_TXN_SMP_CTX;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009791
Willy Tarreaube508f12016-03-10 11:47:01 +01009792 if (!stream)
9793 return 0;
Christopher Fauletafd8f102018-11-08 11:34:21 +01009794
Willy Tarreau87b09662015-04-03 00:22:06 +02009795 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01009796 * Lua context can be not initialized. This behavior
9797 * permits to save performances because a systematic
9798 * Lua initialization cause 5% performances loss.
9799 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009800 if (!stream->hlua) {
Christopher Faulet1e8433f2021-03-24 15:03:01 +01009801 struct hlua *hlua;
9802
9803 hlua = pool_alloc(pool_head_hlua);
9804 if (!hlua) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009805 SEND_ERR(stream->be, "Lua sample-fetch '%s': can't initialize Lua context.\n", fcn->name);
9806 return 0;
9807 }
Christopher Faulet1e8433f2021-03-24 15:03:01 +01009808 hlua->T = NULL;
9809 stream->hlua = hlua;
Aurelien DARRAGON6b0b9bd2023-03-21 14:02:16 +01009810 if (!hlua_ctx_init(stream->hlua, fcn_ref_to_stack_id(fcn), stream->task)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009811 SEND_ERR(stream->be, "Lua sample-fetch '%s': can't initialize Lua context.\n", fcn->name);
9812 return 0;
9813 }
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01009814 }
9815
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009816 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009817 if (!HLUA_IS_RUNNING(stream->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02009818
9819 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009820 if (!SET_SAFE_LJMP(stream->hlua)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009821 if (lua_type(stream->hlua->T, -1) == LUA_TSTRING)
9822 error = lua_tostring(stream->hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +01009823 else
9824 error = "critical error";
9825 SEND_ERR(smp->px, "Lua sample-fetch '%s': %s.\n", fcn->name, error);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02009826 return 0;
9827 }
9828
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009829 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009830 if (!lua_checkstack(stream->hlua->T, 2)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009831 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009832 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009833 return 0;
9834 }
9835
9836 /* Restore the function in the stack. */
Aurelien DARRAGON4fdf8b52023-03-20 17:22:37 +01009837 hlua_pushref(stream->hlua->T, fcn->function_ref[stream->hlua->state_id]);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009838
9839 /* push arguments in the stack. */
Christopher Fauletbfab2dd2019-07-26 15:09:53 +02009840 if (!hlua_txn_new(stream->hlua->T, stream, smp->px, smp->opt & SMP_OPT_DIR, hflags)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009841 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009842 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009843 return 0;
9844 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009845 stream->hlua->nargs = 1;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009846
9847 /* push keywords in the stack. */
9848 for (; arg_p && arg_p->type != ARGT_STOP; arg_p++) {
9849 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009850 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009851 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009852 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009853 return 0;
9854 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009855 hlua_arg2lua(stream->hlua->T, arg_p);
9856 stream->hlua->nargs++;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009857 }
9858
Thierry FOURNIERbd413492015-03-03 16:52:26 +01009859 /* We must initialize the execution timeouts. */
Aurelien DARRAGONda9503c2022-11-25 09:10:07 +01009860 hlua_timer_init(&stream->hlua->timer, hlua_timeout_session);
Thierry FOURNIERbd413492015-03-03 16:52:26 +01009861
Thierry FOURNIERbabae282015-09-17 11:36:37 +02009862 /* At this point the execution is safe. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009863 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009864 }
9865
9866 /* Execute the function. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009867 switch (hlua_ctx_resume(stream->hlua, 0)) {
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009868 /* finished. */
9869 case HLUA_E_OK:
Thierry FOURNIERfd80df12017-05-12 16:32:20 +02009870 /* If the stack is empty, the function fails. */
9871 if (lua_gettop(stream->hlua->T) <= 0)
9872 return 0;
9873
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009874 /* Convert the returned value in sample. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009875 hlua_lua2smp(stream->hlua->T, -1, smp);
9876 lua_pop(stream->hlua->T, 1);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009877
9878 /* Set the end of execution flag. */
9879 smp->flags &= ~SMP_F_MAY_CHANGE;
9880 return 1;
9881
9882 /* yield. */
9883 case HLUA_E_AGAIN:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009884 SEND_ERR(smp->px, "Lua sample-fetch '%s': cannot use yielded functions.\n", fcn->name);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009885 return 0;
9886
9887 /* finished with error. */
9888 case HLUA_E_ERRMSG:
9889 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009890 SEND_ERR(smp->px, "Lua sample-fetch '%s': %s.\n",
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009891 fcn->name, lua_tostring(stream->hlua->T, -1));
9892 lua_pop(stream->hlua->T, 1);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009893 return 0;
9894
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009895 case HLUA_E_ETMOUT:
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009896 SEND_ERR(smp->px, "Lua sample-fetch '%s': execution timeout.\n", fcn->name);
9897 return 0;
9898
9899 case HLUA_E_NOMEM:
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009900 SEND_ERR(smp->px, "Lua sample-fetch '%s': out of memory error.\n", fcn->name);
9901 return 0;
9902
9903 case HLUA_E_YIELD:
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009904 SEND_ERR(smp->px, "Lua sample-fetch '%s': yield not allowed.\n", fcn->name);
9905 return 0;
9906
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009907 case HLUA_E_ERR:
9908 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009909 SEND_ERR(smp->px, "Lua sample-fetch '%s' returns an unknown error.\n", fcn->name);
Willy Tarreau14de3952022-11-14 07:08:28 +01009910 __fallthrough;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009911
9912 default:
9913 return 0;
9914 }
9915}
9916
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009917/* This function is an LUA binding used for registering
9918 * "sample-conv" functions. It expects a converter name used
9919 * in the haproxy configuration file, and an LUA function.
9920 */
9921__LJMP static int hlua_register_converters(lua_State *L)
9922{
9923 struct sample_conv_kw_list *sck;
9924 const char *name;
9925 int ref;
9926 int len;
Christopher Fauletaa224302021-04-12 14:08:21 +02009927 struct hlua_function *fcn = NULL;
Thierry Fournierf67442e2020-11-28 20:41:07 +01009928 struct sample_conv *sc;
9929 struct buffer *trash;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009930
9931 MAY_LJMP(check_args(L, 2, "register_converters"));
9932
Aurelien DARRAGON87f52972023-02-24 09:43:54 +01009933 if (hlua_gethlua(L)) {
9934 /* runtime processing */
9935 WILL_LJMP(luaL_error(L, "register_converters: not available outside of body context"));
9936 }
9937
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009938 /* First argument : converter name. */
9939 name = MAY_LJMP(luaL_checkstring(L, 1));
9940
9941 /* Second argument : lua function. */
9942 ref = MAY_LJMP(hlua_checkfunction(L, 2));
9943
Thierry Fournierf67442e2020-11-28 20:41:07 +01009944 /* Check if the converter is already registered */
9945 trash = get_trash_chunk();
9946 chunk_printf(trash, "lua.%s", name);
9947 sc = find_sample_conv(trash->area, trash->data);
9948 if (sc != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +01009949 fcn = sc->private;
9950 if (fcn->function_ref[hlua_state_id] != -1) {
9951 ha_warning("Trying to register converter 'lua.%s' more than once. "
9952 "This will become a hard error in version 2.5.\n", name);
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +01009953 hlua_unref(L, fcn->function_ref[hlua_state_id]);
Thierry Fournier59f11be2020-11-29 00:37:41 +01009954 }
9955 fcn->function_ref[hlua_state_id] = ref;
9956 return 0;
Thierry Fournierf67442e2020-11-28 20:41:07 +01009957 }
9958
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009959 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02009960 sck = calloc(1, sizeof(*sck) + sizeof(struct sample_conv) * 2);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009961 if (!sck)
Christopher Fauletaa224302021-04-12 14:08:21 +02009962 goto alloc_error;
Thierry Fournier62a22aa2020-11-28 21:06:35 +01009963 fcn = new_hlua_function();
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009964 if (!fcn)
Christopher Fauletaa224302021-04-12 14:08:21 +02009965 goto alloc_error;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009966
9967 /* Fill fcn. */
9968 fcn->name = strdup(name);
9969 if (!fcn->name)
Christopher Fauletaa224302021-04-12 14:08:21 +02009970 goto alloc_error;
Thierry Fournierc7492592020-11-28 23:57:24 +01009971 fcn->function_ref[hlua_state_id] = ref;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009972
9973 /* List head */
9974 sck->list.n = sck->list.p = NULL;
9975
9976 /* converter keyword. */
9977 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02009978 sck->kw[0].kw = calloc(1, len);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009979 if (!sck->kw[0].kw)
Christopher Fauletaa224302021-04-12 14:08:21 +02009980 goto alloc_error;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009981
9982 snprintf((char *)sck->kw[0].kw, len, "lua.%s", name);
9983 sck->kw[0].process = hlua_sample_conv_wrapper;
David Carlier0c437f42016-04-27 16:21:56 +01009984 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 +01009985 sck->kw[0].val_args = NULL;
9986 sck->kw[0].in_type = SMP_T_STR;
9987 sck->kw[0].out_type = SMP_T_STR;
9988 sck->kw[0].private = fcn;
9989
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009990 /* Register this new converter */
9991 sample_register_convs(sck);
9992
9993 return 0;
Christopher Fauletaa224302021-04-12 14:08:21 +02009994
9995 alloc_error:
9996 release_hlua_function(fcn);
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +01009997 hlua_unref(L, ref);
Christopher Fauletaa224302021-04-12 14:08:21 +02009998 ha_free(&sck);
9999 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
10000 return 0; /* Never reached */
Thierry FOURNIER9be813f2015-02-16 20:21:12 +010010001}
10002
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -080010003/* This function is an LUA binding used for registering
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +010010004 * "sample-fetch" functions. It expects a converter name used
10005 * in the haproxy configuration file, and an LUA function.
10006 */
10007__LJMP static int hlua_register_fetches(lua_State *L)
10008{
10009 const char *name;
10010 int ref;
10011 int len;
10012 struct sample_fetch_kw_list *sfk;
Christopher Faulet2567f182021-04-12 14:11:50 +020010013 struct hlua_function *fcn = NULL;
Thierry Fournierf67442e2020-11-28 20:41:07 +010010014 struct sample_fetch *sf;
10015 struct buffer *trash;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +010010016
10017 MAY_LJMP(check_args(L, 2, "register_fetches"));
10018
Aurelien DARRAGON87f52972023-02-24 09:43:54 +010010019 if (hlua_gethlua(L)) {
10020 /* runtime processing */
10021 WILL_LJMP(luaL_error(L, "register_fetches: not available outside of body context"));
10022 }
10023
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +010010024 /* First argument : sample-fetch name. */
10025 name = MAY_LJMP(luaL_checkstring(L, 1));
10026
10027 /* Second argument : lua function. */
10028 ref = MAY_LJMP(hlua_checkfunction(L, 2));
10029
Thierry Fournierf67442e2020-11-28 20:41:07 +010010030 /* Check if the sample-fetch is already registered */
10031 trash = get_trash_chunk();
10032 chunk_printf(trash, "lua.%s", name);
10033 sf = find_sample_fetch(trash->area, trash->data);
10034 if (sf != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +010010035 fcn = sf->private;
10036 if (fcn->function_ref[hlua_state_id] != -1) {
10037 ha_warning("Trying to register sample-fetch 'lua.%s' more than once. "
10038 "This will become a hard error in version 2.5.\n", name);
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +010010039 hlua_unref(L, fcn->function_ref[hlua_state_id]);
Thierry Fournier59f11be2020-11-29 00:37:41 +010010040 }
10041 fcn->function_ref[hlua_state_id] = ref;
10042 return 0;
Thierry Fournierf67442e2020-11-28 20:41:07 +010010043 }
10044
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +010010045 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +020010046 sfk = calloc(1, sizeof(*sfk) + sizeof(struct sample_fetch) * 2);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +010010047 if (!sfk)
Christopher Faulet2567f182021-04-12 14:11:50 +020010048 goto alloc_error;
Thierry Fournier62a22aa2020-11-28 21:06:35 +010010049 fcn = new_hlua_function();
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +010010050 if (!fcn)
Christopher Faulet2567f182021-04-12 14:11:50 +020010051 goto alloc_error;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +010010052
10053 /* Fill fcn. */
10054 fcn->name = strdup(name);
10055 if (!fcn->name)
Christopher Faulet2567f182021-04-12 14:11:50 +020010056 goto alloc_error;
Thierry Fournierc7492592020-11-28 23:57:24 +010010057 fcn->function_ref[hlua_state_id] = ref;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +010010058
10059 /* List head */
10060 sfk->list.n = sfk->list.p = NULL;
10061
10062 /* sample-fetch keyword. */
10063 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +020010064 sfk->kw[0].kw = calloc(1, len);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +010010065 if (!sfk->kw[0].kw)
Christopher Faulet2567f182021-04-12 14:11:50 +020010066 goto alloc_error;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +010010067
10068 snprintf((char *)sfk->kw[0].kw, len, "lua.%s", name);
10069 sfk->kw[0].process = hlua_sample_fetch_wrapper;
David Carlier0c437f42016-04-27 16:21:56 +010010070 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 +010010071 sfk->kw[0].val_args = NULL;
10072 sfk->kw[0].out_type = SMP_T_STR;
10073 sfk->kw[0].use = SMP_USE_HTTP_ANY;
10074 sfk->kw[0].val = 0;
10075 sfk->kw[0].private = fcn;
10076
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +010010077 /* Register this new fetch. */
10078 sample_register_fetches(sfk);
10079
10080 return 0;
Christopher Faulet2567f182021-04-12 14:11:50 +020010081
10082 alloc_error:
10083 release_hlua_function(fcn);
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +010010084 hlua_unref(L, ref);
Christopher Faulet2567f182021-04-12 14:11:50 +020010085 ha_free(&sfk);
10086 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
10087 return 0; /* Never reached */
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +010010088}
10089
Christopher Faulet501465d2020-02-26 14:54:16 +010010090/* This function is a lua binding to set the wake_time.
Christopher Faulet2c2c2e32020-01-31 19:07:52 +010010091 */
Christopher Faulet501465d2020-02-26 14:54:16 +010010092__LJMP static int hlua_set_wake_time(lua_State *L)
Christopher Faulet2c2c2e32020-01-31 19:07:52 +010010093{
Thierry Fournier4234dbd2020-11-28 13:18:23 +010010094 struct hlua *hlua;
Christopher Faulet2c2c2e32020-01-31 19:07:52 +010010095 unsigned int delay;
Aurelien DARRAGON2a9764b2023-04-04 18:41:04 +020010096 int wakeup_ms; // tick value
Christopher Faulet2c2c2e32020-01-31 19:07:52 +010010097
Thierry Fournier4234dbd2020-11-28 13:18:23 +010010098 /* Get hlua struct, or NULL if we execute from main lua state */
10099 hlua = hlua_gethlua(L);
10100 if (!hlua) {
10101 return 0;
10102 }
10103
Christopher Faulet2c2c2e32020-01-31 19:07:52 +010010104 MAY_LJMP(check_args(L, 1, "wake_time"));
10105
10106 delay = MAY_LJMP(luaL_checkinteger(L, 1));
10107 wakeup_ms = tick_add(now_ms, delay);
10108 hlua->wake_time = wakeup_ms;
10109 return 0;
10110}
10111
Christopher Faulet7716cdf2020-01-29 11:53:30 +010010112/* This function is a wrapper to execute each LUA function declared as an action
10113 * wrapper during the initialisation period. This function may return any
10114 * ACT_RET_* value. On error ACT_RET_CONT is returned and the action is
10115 * ignored. If the lua action yields, ACT_RET_YIELD is returned. On success, the
10116 * return value is the first element on the stack.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +010010117 */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +020010118static enum act_return hlua_action(struct act_rule *rule, struct proxy *px,
Willy Tarreau658b85b2015-09-27 10:00:49 +020010119 struct session *sess, struct stream *s, int flags)
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +010010120{
10121 char **arg;
Christopher Faulet8c9e6bb2021-08-06 16:29:41 +020010122 unsigned int hflags = HLUA_TXN_ACT_CTX;
Christopher Faulet7716cdf2020-01-29 11:53:30 +010010123 int dir, act_ret = ACT_RET_CONT;
Thierry Fournierfd107a22016-02-19 19:57:23 +010010124 const char *error;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +020010125
10126 switch (rule->from) {
Christopher Fauletd8f0e072020-02-25 09:45:51 +010010127 case ACT_F_TCP_REQ_CNT: dir = SMP_OPT_DIR_REQ; break;
10128 case ACT_F_TCP_RES_CNT: dir = SMP_OPT_DIR_RES; break;
10129 case ACT_F_HTTP_REQ: dir = SMP_OPT_DIR_REQ; break;
10130 case ACT_F_HTTP_RES: dir = SMP_OPT_DIR_RES; break;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +020010131 default:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +020010132 SEND_ERR(px, "Lua: internal error while execute action.\n");
Christopher Faulet7716cdf2020-01-29 11:53:30 +010010133 goto end;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +020010134 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +010010135
Willy Tarreau87b09662015-04-03 00:22:06 +020010136 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +010010137 * Lua context can be not initialized. This behavior
10138 * permits to save performances because a systematic
10139 * Lua initialization cause 5% performances loss.
10140 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +010010141 if (!s->hlua) {
Christopher Faulet1e8433f2021-03-24 15:03:01 +010010142 struct hlua *hlua;
10143
10144 hlua = pool_alloc(pool_head_hlua);
10145 if (!hlua) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +010010146 SEND_ERR(px, "Lua action '%s': can't initialize Lua context.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010147 rule->arg.hlua_rule->fcn->name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +010010148 goto end;
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +010010149 }
Christopher Faulet1e8433f2021-03-24 15:03:01 +010010150 HLUA_INIT(hlua);
10151 s->hlua = hlua;
Aurelien DARRAGON6b0b9bd2023-03-21 14:02:16 +010010152 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 +010010153 SEND_ERR(px, "Lua action '%s': can't initialize Lua context.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010154 rule->arg.hlua_rule->fcn->name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +010010155 goto end;
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +010010156 }
Thierry FOURNIER05ac4242015-02-27 18:37:27 +010010157 }
10158
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +010010159 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +010010160 if (!HLUA_IS_RUNNING(s->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +020010161
10162 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010163 if (!SET_SAFE_LJMP(s->hlua)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +010010164 if (lua_type(s->hlua->T, -1) == LUA_TSTRING)
10165 error = lua_tostring(s->hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +010010166 else
10167 error = "critical error";
10168 SEND_ERR(px, "Lua function '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010169 rule->arg.hlua_rule->fcn->name, error);
Christopher Faulet7716cdf2020-01-29 11:53:30 +010010170 goto end;
Thierry FOURNIERbabae282015-09-17 11:36:37 +020010171 }
10172
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +010010173 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +010010174 if (!lua_checkstack(s->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +020010175 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010176 rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010177 RESET_SAFE_LJMP(s->hlua);
Christopher Faulet7716cdf2020-01-29 11:53:30 +010010178 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +010010179 }
10180
10181 /* Restore the function in the stack. */
Aurelien DARRAGON4fdf8b52023-03-20 17:22:37 +010010182 hlua_pushref(s->hlua->T, rule->arg.hlua_rule->fcn->function_ref[s->hlua->state_id]);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +010010183
Willy Tarreau87b09662015-04-03 00:22:06 +020010184 /* Create and and push object stream in the stack. */
Christopher Fauletbfab2dd2019-07-26 15:09:53 +020010185 if (!hlua_txn_new(s->hlua->T, s, px, dir, hflags)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +020010186 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010187 rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010188 RESET_SAFE_LJMP(s->hlua);
Christopher Faulet7716cdf2020-01-29 11:53:30 +010010189 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +010010190 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +010010191 s->hlua->nargs = 1;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +010010192
10193 /* push keywords in the stack. */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +020010194 for (arg = rule->arg.hlua_rule->args; arg && *arg; arg++) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +010010195 if (!lua_checkstack(s->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +020010196 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010197 rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010198 RESET_SAFE_LJMP(s->hlua);
Christopher Faulet7716cdf2020-01-29 11:53:30 +010010199 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +010010200 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +010010201 lua_pushstring(s->hlua->T, *arg);
10202 s->hlua->nargs++;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +010010203 }
10204
Thierry FOURNIERbabae282015-09-17 11:36:37 +020010205 /* Now the execution is safe. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010206 RESET_SAFE_LJMP(s->hlua);
Thierry FOURNIERbabae282015-09-17 11:36:37 +020010207
Thierry FOURNIERbd413492015-03-03 16:52:26 +010010208 /* We must initialize the execution timeouts. */
Aurelien DARRAGONda9503c2022-11-25 09:10:07 +010010209 hlua_timer_init(&s->hlua->timer, hlua_timeout_session);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +010010210 }
10211
10212 /* Execute the function. */
Christopher Faulet105ba6c2019-12-18 14:41:51 +010010213 switch (hlua_ctx_resume(s->hlua, !(flags & ACT_OPT_FINAL))) {
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +010010214 /* finished. */
10215 case HLUA_E_OK:
Christopher Faulet7716cdf2020-01-29 11:53:30 +010010216 /* Catch the return value */
10217 if (lua_gettop(s->hlua->T) > 0)
10218 act_ret = lua_tointeger(s->hlua->T, -1);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +010010219
Christopher Faulet2c2c2e32020-01-31 19:07:52 +010010220 /* Set timeout in the required channel. */
Christopher Faulet498c4832020-07-28 11:59:58 +020010221 if (act_ret == ACT_RET_YIELD) {
10222 if (flags & ACT_OPT_FINAL)
10223 goto err_yield;
10224
Christopher Faulet8f587ea2020-07-28 12:01:55 +020010225 if (dir == SMP_OPT_DIR_REQ)
10226 s->req.analyse_exp = tick_first((tick_is_expired(s->req.analyse_exp, now_ms) ? 0 : s->req.analyse_exp),
10227 s->hlua->wake_time);
10228 else
10229 s->res.analyse_exp = tick_first((tick_is_expired(s->res.analyse_exp, now_ms) ? 0 : s->res.analyse_exp),
10230 s->hlua->wake_time);
Christopher Faulet2c2c2e32020-01-31 19:07:52 +010010231 }
10232 goto end;
10233
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +010010234 /* yield. */
10235 case HLUA_E_AGAIN:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +010010236 /* Set timeout in the required channel. */
Christopher Faulet8f587ea2020-07-28 12:01:55 +020010237 if (dir == SMP_OPT_DIR_REQ)
10238 s->req.analyse_exp = tick_first((tick_is_expired(s->req.analyse_exp, now_ms) ? 0 : s->req.analyse_exp),
10239 s->hlua->wake_time);
10240 else
10241 s->res.analyse_exp = tick_first((tick_is_expired(s->res.analyse_exp, now_ms) ? 0 : s->res.analyse_exp),
10242 s->hlua->wake_time);
10243
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +010010244 /* Some actions can be wake up when a "write" event
10245 * is detected on a response channel. This is useful
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -080010246 * only for actions targeted on the requests.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +010010247 */
Christopher Faulet51fa3582019-07-26 14:54:52 +020010248 if (HLUA_IS_WAKERESWR(s->hlua))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +010010249 s->res.flags |= CF_WAKE_WRITE;
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +010010250 if (HLUA_IS_WAKEREQWR(s->hlua))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +010010251 s->req.flags |= CF_WAKE_WRITE;
Christopher Faulet7716cdf2020-01-29 11:53:30 +010010252 act_ret = ACT_RET_YIELD;
10253 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +010010254
10255 /* finished with error. */
10256 case HLUA_E_ERRMSG:
10257 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +020010258 SEND_ERR(px, "Lua function '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010259 rule->arg.hlua_rule->fcn->name, lua_tostring(s->hlua->T, -1));
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +010010260 lua_pop(s->hlua->T, 1);
Christopher Faulet7716cdf2020-01-29 11:53:30 +010010261 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +010010262
Thierry Fournierd5b073c2018-05-21 19:42:47 +020010263 case HLUA_E_ETMOUT:
Thierry Fournierad5345f2020-11-29 02:05:57 +010010264 SEND_ERR(px, "Lua function '%s': execution timeout.\n", rule->arg.hlua_rule->fcn->name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +010010265 goto end;
Thierry Fournierd5b073c2018-05-21 19:42:47 +020010266
10267 case HLUA_E_NOMEM:
Thierry Fournierad5345f2020-11-29 02:05:57 +010010268 SEND_ERR(px, "Lua function '%s': out of memory error.\n", rule->arg.hlua_rule->fcn->name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +010010269 goto end;
Thierry Fournierd5b073c2018-05-21 19:42:47 +020010270
10271 case HLUA_E_YIELD:
Christopher Faulet498c4832020-07-28 11:59:58 +020010272 err_yield:
10273 act_ret = ACT_RET_CONT;
Thierry Fournierd5b073c2018-05-21 19:42:47 +020010274 SEND_ERR(px, "Lua function '%s': aborting Lua processing on expired timeout.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010275 rule->arg.hlua_rule->fcn->name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +010010276 goto end;
Thierry Fournierd5b073c2018-05-21 19:42:47 +020010277
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +010010278 case HLUA_E_ERR:
10279 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +020010280 SEND_ERR(px, "Lua function '%s' return an unknown error.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010281 rule->arg.hlua_rule->fcn->name);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +010010282
10283 default:
Christopher Faulet7716cdf2020-01-29 11:53:30 +010010284 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +010010285 }
Christopher Faulet7716cdf2020-01-29 11:53:30 +010010286
10287 end:
Christopher Faulet2361fd92020-07-30 10:40:58 +020010288 if (act_ret != ACT_RET_YIELD && s->hlua)
Christopher Faulet8f587ea2020-07-28 12:01:55 +020010289 s->hlua->wake_time = TICK_ETERNITY;
Christopher Faulet7716cdf2020-01-29 11:53:30 +010010290 return act_ret;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +010010291}
10292
Willy Tarreau144f84a2021-03-02 16:09:26 +010010293struct task *hlua_applet_wakeup(struct task *t, void *context, unsigned int state)
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010294{
Olivier Houchard9f6af332018-05-25 14:04:04 +020010295 struct appctx *ctx = context;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010296
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010297 appctx_wakeup(ctx);
Willy Tarreaud9587412017-08-23 16:07:33 +020010298 t->expire = TICK_ETERNITY;
Willy Tarreaud1aa41f2017-07-21 16:41:56 +020010299 return t;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010300}
10301
Christopher Faulet4aa1d282022-01-13 16:01:35 +010010302static int hlua_applet_tcp_init(struct appctx *ctx)
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010303{
Willy Tarreaue23f33b2022-05-06 14:07:13 +020010304 struct hlua_tcp_ctx *tcp_ctx = applet_reserve_svcctx(ctx, sizeof(*tcp_ctx));
Willy Tarreauc12b3212022-05-27 11:08:15 +020010305 struct stconn *sc = appctx_sc(ctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +020010306 struct stream *strm = __sc_strm(sc);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +010010307 struct hlua *hlua;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010308 struct task *task;
10309 char **arg;
Thierry Fournierfd107a22016-02-19 19:57:23 +010010310 const char *error;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010311
Willy Tarreaubafbe012017-11-24 17:34:44 +010010312 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +010010313 if (!hlua) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +010010314 SEND_ERR(strm->be, "Lua applet tcp '%s': out of memory.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010315 ctx->rule->arg.hlua_rule->fcn->name);
Christopher Fauletc9929382022-05-12 11:52:27 +020010316 return -1;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +010010317 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010318 HLUA_INIT(hlua);
Willy Tarreaue23f33b2022-05-06 14:07:13 +020010319 tcp_ctx->hlua = hlua;
10320 tcp_ctx->flags = 0;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010321
10322 /* Create task used by signal to wakeup applets. */
Willy Tarreaubeeabf52021-10-01 18:23:30 +020010323 task = task_new_here();
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010324 if (!task) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +010010325 SEND_ERR(strm->be, "Lua applet tcp '%s': out of memory.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010326 ctx->rule->arg.hlua_rule->fcn->name);
Christopher Fauletc9929382022-05-12 11:52:27 +020010327 return -1;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010328 }
10329 task->nice = 0;
10330 task->context = ctx;
10331 task->process = hlua_applet_wakeup;
Willy Tarreaue23f33b2022-05-06 14:07:13 +020010332 tcp_ctx->task = task;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010333
10334 /* In the execution wrappers linked with a stream, the
10335 * Lua context can be not initialized. This behavior
10336 * permits to save performances because a systematic
10337 * Lua initialization cause 5% performances loss.
10338 */
Aurelien DARRAGON6b0b9bd2023-03-21 14:02:16 +010010339 if (!hlua_ctx_init(hlua, fcn_ref_to_stack_id(ctx->rule->arg.hlua_rule->fcn), task)) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +010010340 SEND_ERR(strm->be, "Lua applet tcp '%s': can't initialize Lua context.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010341 ctx->rule->arg.hlua_rule->fcn->name);
Christopher Fauletc9929382022-05-12 11:52:27 +020010342 return -1;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010343 }
10344
10345 /* Set timeout according with the applet configuration. */
Aurelien DARRAGONda9503c2022-11-25 09:10:07 +010010346 hlua_timer_init(&hlua->timer, ctx->applet->timeout);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010347
10348 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010349 if (!SET_SAFE_LJMP(hlua)) {
Thierry Fournierfd107a22016-02-19 19:57:23 +010010350 if (lua_type(hlua->T, -1) == LUA_TSTRING)
10351 error = lua_tostring(hlua->T, -1);
10352 else
10353 error = "critical error";
Christopher Faulet4aa1d282022-01-13 16:01:35 +010010354 SEND_ERR(strm->be, "Lua applet tcp '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010355 ctx->rule->arg.hlua_rule->fcn->name, error);
Christopher Fauletc9929382022-05-12 11:52:27 +020010356 return -1;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010357 }
10358
10359 /* Check stack available size. */
10360 if (!lua_checkstack(hlua->T, 1)) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +010010361 SEND_ERR(strm->be, "Lua applet tcp '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010362 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010363 RESET_SAFE_LJMP(hlua);
Christopher Fauletc9929382022-05-12 11:52:27 +020010364 return -1;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010365 }
10366
10367 /* Restore the function in the stack. */
Aurelien DARRAGON4fdf8b52023-03-20 17:22:37 +010010368 hlua_pushref(hlua->T, ctx->rule->arg.hlua_rule->fcn->function_ref[hlua->state_id]);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010369
10370 /* Create and and push object stream in the stack. */
10371 if (!hlua_applet_tcp_new(hlua->T, ctx)) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +010010372 SEND_ERR(strm->be, "Lua applet tcp '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010373 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010374 RESET_SAFE_LJMP(hlua);
Christopher Fauletc9929382022-05-12 11:52:27 +020010375 return -1;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010376 }
10377 hlua->nargs = 1;
10378
10379 /* push keywords in the stack. */
10380 for (arg = ctx->rule->arg.hlua_rule->args; arg && *arg; arg++) {
10381 if (!lua_checkstack(hlua->T, 1)) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +010010382 SEND_ERR(strm->be, "Lua applet tcp '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010383 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010384 RESET_SAFE_LJMP(hlua);
Christopher Fauletc9929382022-05-12 11:52:27 +020010385 return -1;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010386 }
10387 lua_pushstring(hlua->T, *arg);
10388 hlua->nargs++;
10389 }
10390
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010391 RESET_SAFE_LJMP(hlua);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010392
10393 /* Wakeup the applet ASAP. */
Willy Tarreau90e8b452022-05-25 18:21:43 +020010394 applet_need_more_data(ctx);
Willy Tarreau4164eb92022-05-25 15:42:03 +020010395 applet_have_more_data(ctx);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010396
Christopher Fauletc9929382022-05-12 11:52:27 +020010397 return 0;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010398}
10399
Willy Tarreau60409db2019-08-21 14:14:50 +020010400void hlua_applet_tcp_fct(struct appctx *ctx)
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010401{
Willy Tarreaue23f33b2022-05-06 14:07:13 +020010402 struct hlua_tcp_ctx *tcp_ctx = ctx->svcctx;
Willy Tarreauc12b3212022-05-27 11:08:15 +020010403 struct stconn *sc = appctx_sc(ctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +020010404 struct stream *strm = __sc_strm(sc);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010405 struct act_rule *rule = ctx->rule;
10406 struct proxy *px = strm->be;
Willy Tarreaue23f33b2022-05-06 14:07:13 +020010407 struct hlua *hlua = tcp_ctx->hlua;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010408
Christopher Faulet31572222023-03-31 11:13:48 +020010409 if (unlikely(se_fl_test(ctx->sedesc, (SE_FL_EOS|SE_FL_ERROR|SE_FL_SHR|SE_FL_SHW))))
10410 goto out;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010411
Christopher Faulet31572222023-03-31 11:13:48 +020010412 /* The applet execution is already done. */
10413 if (tcp_ctx->flags & APPLET_DONE)
10414 goto out;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010415
10416 /* Execute the function. */
10417 switch (hlua_ctx_resume(hlua, 1)) {
10418 /* finished. */
10419 case HLUA_E_OK:
Willy Tarreaue23f33b2022-05-06 14:07:13 +020010420 tcp_ctx->flags |= APPLET_DONE;
Christopher Faulet31572222023-03-31 11:13:48 +020010421 se_fl_set(ctx->sedesc, SE_FL_EOI|SE_FL_EOS);
10422 break;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010423
10424 /* yield. */
10425 case HLUA_E_AGAIN:
Thierry Fournier0164f202016-02-20 17:47:43 +010010426 if (hlua->wake_time != TICK_ETERNITY)
Willy Tarreaue23f33b2022-05-06 14:07:13 +020010427 task_schedule(tcp_ctx->task, hlua->wake_time);
Christopher Faulet31572222023-03-31 11:13:48 +020010428 break;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010429
10430 /* finished with error. */
10431 case HLUA_E_ERRMSG:
10432 /* Display log. */
10433 SEND_ERR(px, "Lua applet tcp '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010434 rule->arg.hlua_rule->fcn->name, lua_tostring(hlua->T, -1));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010435 lua_pop(hlua->T, 1);
10436 goto error;
10437
Thierry Fournierd5b073c2018-05-21 19:42:47 +020010438 case HLUA_E_ETMOUT:
10439 SEND_ERR(px, "Lua applet tcp '%s': execution timeout.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010440 rule->arg.hlua_rule->fcn->name);
Thierry Fournierd5b073c2018-05-21 19:42:47 +020010441 goto error;
10442
10443 case HLUA_E_NOMEM:
10444 SEND_ERR(px, "Lua applet tcp '%s': out of memory error.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010445 rule->arg.hlua_rule->fcn->name);
Thierry Fournierd5b073c2018-05-21 19:42:47 +020010446 goto error;
10447
10448 case HLUA_E_YIELD: /* unexpected */
10449 SEND_ERR(px, "Lua applet tcp '%s': yield not allowed.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010450 rule->arg.hlua_rule->fcn->name);
Thierry Fournierd5b073c2018-05-21 19:42:47 +020010451 goto error;
10452
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010453 case HLUA_E_ERR:
10454 /* Display log. */
10455 SEND_ERR(px, "Lua applet tcp '%s' return an unknown error.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010456 rule->arg.hlua_rule->fcn->name);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010457 goto error;
10458
10459 default:
10460 goto error;
10461 }
10462
Christopher Faulet31572222023-03-31 11:13:48 +020010463out:
10464 /* eat the whole request */
10465 co_skip(sc_oc(sc), co_data(sc_oc(sc)));
10466 return;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010467
Christopher Faulet31572222023-03-31 11:13:48 +020010468error:
10469 se_fl_set(ctx->sedesc, SE_FL_ERROR);
Willy Tarreaue23f33b2022-05-06 14:07:13 +020010470 tcp_ctx->flags |= APPLET_DONE;
Christopher Faulet31572222023-03-31 11:13:48 +020010471 goto out;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010472}
10473
10474static void hlua_applet_tcp_release(struct appctx *ctx)
10475{
Willy Tarreaue23f33b2022-05-06 14:07:13 +020010476 struct hlua_tcp_ctx *tcp_ctx = ctx->svcctx;
10477
10478 task_destroy(tcp_ctx->task);
10479 tcp_ctx->task = NULL;
10480 hlua_ctx_destroy(tcp_ctx->hlua);
10481 tcp_ctx->hlua = NULL;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010482}
10483
Christopher Fauletc9929382022-05-12 11:52:27 +020010484/* The function returns 0 if the initialisation is complete or -1 if
10485 * an errors occurs. It also reserves the appctx for an hlua_http_ctx.
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010486 */
Christopher Faulet4aa1d282022-01-13 16:01:35 +010010487static int hlua_applet_http_init(struct appctx *ctx)
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010488{
Willy Tarreauaa229cc2022-05-06 14:26:10 +020010489 struct hlua_http_ctx *http_ctx = applet_reserve_svcctx(ctx, sizeof(*http_ctx));
Willy Tarreauc12b3212022-05-27 11:08:15 +020010490 struct stconn *sc = appctx_sc(ctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +020010491 struct stream *strm = __sc_strm(sc);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010492 struct http_txn *txn;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +010010493 struct hlua *hlua;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010494 char **arg;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010495 struct task *task;
Thierry Fournierfd107a22016-02-19 19:57:23 +010010496 const char *error;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010497
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010498 txn = strm->txn;
Willy Tarreaubafbe012017-11-24 17:34:44 +010010499 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +010010500 if (!hlua) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +010010501 SEND_ERR(strm->be, "Lua applet http '%s': out of memory.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010502 ctx->rule->arg.hlua_rule->fcn->name);
Christopher Fauletc9929382022-05-12 11:52:27 +020010503 return -1;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +010010504 }
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010505 HLUA_INIT(hlua);
Willy Tarreauaa229cc2022-05-06 14:26:10 +020010506 http_ctx->hlua = hlua;
10507 http_ctx->left_bytes = -1;
10508 http_ctx->flags = 0;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010509
Thierry FOURNIERd93ea2b2015-12-20 19:14:52 +010010510 if (txn->req.flags & HTTP_MSGF_VER_11)
Willy Tarreauaa229cc2022-05-06 14:26:10 +020010511 http_ctx->flags |= APPLET_HTTP11;
Thierry FOURNIERd93ea2b2015-12-20 19:14:52 +010010512
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010513 /* Create task used by signal to wakeup applets. */
Willy Tarreaubeeabf52021-10-01 18:23:30 +020010514 task = task_new_here();
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010515 if (!task) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +010010516 SEND_ERR(strm->be, "Lua applet http '%s': out of memory.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010517 ctx->rule->arg.hlua_rule->fcn->name);
Christopher Fauletc9929382022-05-12 11:52:27 +020010518 return -1;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010519 }
10520 task->nice = 0;
10521 task->context = ctx;
10522 task->process = hlua_applet_wakeup;
Willy Tarreauaa229cc2022-05-06 14:26:10 +020010523 http_ctx->task = task;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010524
10525 /* In the execution wrappers linked with a stream, the
10526 * Lua context can be not initialized. This behavior
10527 * permits to save performances because a systematic
10528 * Lua initialization cause 5% performances loss.
10529 */
Aurelien DARRAGON6b0b9bd2023-03-21 14:02:16 +010010530 if (!hlua_ctx_init(hlua, fcn_ref_to_stack_id(ctx->rule->arg.hlua_rule->fcn), task)) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +010010531 SEND_ERR(strm->be, "Lua applet http '%s': can't initialize Lua context.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010532 ctx->rule->arg.hlua_rule->fcn->name);
Christopher Fauletc9929382022-05-12 11:52:27 +020010533 return -1;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010534 }
10535
10536 /* Set timeout according with the applet configuration. */
Aurelien DARRAGONda9503c2022-11-25 09:10:07 +010010537 hlua_timer_init(&hlua->timer, ctx->applet->timeout);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010538
10539 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010540 if (!SET_SAFE_LJMP(hlua)) {
Thierry Fournierfd107a22016-02-19 19:57:23 +010010541 if (lua_type(hlua->T, -1) == LUA_TSTRING)
10542 error = lua_tostring(hlua->T, -1);
10543 else
10544 error = "critical error";
Christopher Faulet4aa1d282022-01-13 16:01:35 +010010545 SEND_ERR(strm->be, "Lua applet http '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010546 ctx->rule->arg.hlua_rule->fcn->name, error);
Christopher Fauletc9929382022-05-12 11:52:27 +020010547 return -1;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010548 }
10549
10550 /* Check stack available size. */
10551 if (!lua_checkstack(hlua->T, 1)) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +010010552 SEND_ERR(strm->be, "Lua applet http '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010553 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010554 RESET_SAFE_LJMP(hlua);
Christopher Fauletc9929382022-05-12 11:52:27 +020010555 return -1;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010556 }
10557
10558 /* Restore the function in the stack. */
Aurelien DARRAGON4fdf8b52023-03-20 17:22:37 +010010559 hlua_pushref(hlua->T, ctx->rule->arg.hlua_rule->fcn->function_ref[hlua->state_id]);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010560
10561 /* Create and and push object stream in the stack. */
10562 if (!hlua_applet_http_new(hlua->T, ctx)) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +010010563 SEND_ERR(strm->be, "Lua applet http '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010564 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010565 RESET_SAFE_LJMP(hlua);
Christopher Fauletc9929382022-05-12 11:52:27 +020010566 return -1;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010567 }
10568 hlua->nargs = 1;
10569
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010570 /* push keywords in the stack. */
10571 for (arg = ctx->rule->arg.hlua_rule->args; arg && *arg; arg++) {
10572 if (!lua_checkstack(hlua->T, 1)) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +010010573 SEND_ERR(strm->be, "Lua applet http '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010574 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010575 RESET_SAFE_LJMP(hlua);
Christopher Fauletc9929382022-05-12 11:52:27 +020010576 return -1;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010577 }
10578 lua_pushstring(hlua->T, *arg);
10579 hlua->nargs++;
10580 }
10581
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010582 RESET_SAFE_LJMP(hlua);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010583
10584 /* Wakeup the applet when data is ready for read. */
Willy Tarreau90e8b452022-05-25 18:21:43 +020010585 applet_need_more_data(ctx);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010586
Christopher Fauletc9929382022-05-12 11:52:27 +020010587 return 0;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010588}
10589
Willy Tarreau60409db2019-08-21 14:14:50 +020010590void hlua_applet_http_fct(struct appctx *ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010591{
Willy Tarreauaa229cc2022-05-06 14:26:10 +020010592 struct hlua_http_ctx *http_ctx = ctx->svcctx;
Willy Tarreauc12b3212022-05-27 11:08:15 +020010593 struct stconn *sc = appctx_sc(ctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +020010594 struct stream *strm = __sc_strm(sc);
10595 struct channel *req = sc_oc(sc);
10596 struct channel *res = sc_ic(sc);
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010597 struct act_rule *rule = ctx->rule;
10598 struct proxy *px = strm->be;
Willy Tarreauaa229cc2022-05-06 14:26:10 +020010599 struct hlua *hlua = http_ctx->hlua;
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010600 struct htx *req_htx, *res_htx;
10601
10602 res_htx = htx_from_buf(&res->buf);
10603
Christopher Faulet31572222023-03-31 11:13:48 +020010604 if (unlikely(se_fl_test(ctx->sedesc, (SE_FL_EOS|SE_FL_ERROR|SE_FL_SHR|SE_FL_SHW))))
10605 goto out;
10606
10607 /* The applet execution is already done. */
10608 if (http_ctx->flags & APPLET_DONE)
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010609 goto out;
10610
Ilya Shipitsin856aabc2020-04-16 23:51:34 +050010611 /* Check if the input buffer is available. */
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010612 if (!b_size(&res->buf)) {
Christopher Faulet7b3d38a2023-05-05 11:28:45 +020010613 sc_need_room(sc, 0);
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010614 goto out;
10615 }
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010616
10617 /* Set the currently running flag. */
10618 if (!HLUA_IS_RUNNING(hlua) &&
Willy Tarreauaa229cc2022-05-06 14:26:10 +020010619 !(http_ctx->flags & APPLET_DONE)) {
Christopher Fauletbd878d22021-04-28 10:50:21 +020010620 if (!co_data(req)) {
Willy Tarreau90e8b452022-05-25 18:21:43 +020010621 applet_need_more_data(ctx);
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010622 goto out;
10623 }
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010624 }
10625
Christopher Faulet31572222023-03-31 11:13:48 +020010626 /* Execute the function. */
10627 switch (hlua_ctx_resume(hlua, 1)) {
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010628 /* finished. */
10629 case HLUA_E_OK:
Willy Tarreauaa229cc2022-05-06 14:26:10 +020010630 http_ctx->flags |= APPLET_DONE;
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010631 break;
10632
10633 /* yield. */
10634 case HLUA_E_AGAIN:
10635 if (hlua->wake_time != TICK_ETERNITY)
Willy Tarreauaa229cc2022-05-06 14:26:10 +020010636 task_schedule(http_ctx->task, hlua->wake_time);
Christopher Faulet56a3d6e2019-02-27 22:06:23 +010010637 goto out;
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010638
10639 /* finished with error. */
10640 case HLUA_E_ERRMSG:
10641 /* Display log. */
10642 SEND_ERR(px, "Lua applet http '%s': %s.\n",
Christopher Faulet31572222023-03-31 11:13:48 +020010643 rule->arg.hlua_rule->fcn->name, lua_tostring(hlua->T, -1));
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010644 lua_pop(hlua->T, 1);
10645 goto error;
10646
10647 case HLUA_E_ETMOUT:
10648 SEND_ERR(px, "Lua applet http '%s': execution timeout.\n",
Christopher Faulet31572222023-03-31 11:13:48 +020010649 rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010650 goto error;
10651
10652 case HLUA_E_NOMEM:
10653 SEND_ERR(px, "Lua applet http '%s': out of memory error.\n",
Christopher Faulet31572222023-03-31 11:13:48 +020010654 rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010655 goto error;
10656
10657 case HLUA_E_YIELD: /* unexpected */
10658 SEND_ERR(px, "Lua applet http '%s': yield not allowed.\n",
Christopher Faulet31572222023-03-31 11:13:48 +020010659 rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010660 goto error;
10661
10662 case HLUA_E_ERR:
10663 /* Display log. */
10664 SEND_ERR(px, "Lua applet http '%s' return an unknown error.\n",
Christopher Faulet31572222023-03-31 11:13:48 +020010665 rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010666 goto error;
10667
10668 default:
10669 goto error;
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010670 }
10671
Willy Tarreauaa229cc2022-05-06 14:26:10 +020010672 if (http_ctx->flags & APPLET_DONE) {
10673 if (http_ctx->flags & APPLET_RSP_SENT)
Christopher Faulet31572222023-03-31 11:13:48 +020010674 goto out;
Christopher Faulet56a3d6e2019-02-27 22:06:23 +010010675
Willy Tarreauaa229cc2022-05-06 14:26:10 +020010676 if (!(http_ctx->flags & APPLET_HDR_SENT))
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010677 goto error;
10678
Christopher Fauletf89af9c2022-04-07 10:07:18 +020010679 /* no more data are expected. If the response buffer is empty
10680 * for a chunked message, be sure to add something (EOT block in
10681 * this case) to have something to send. It is important to be
10682 * sure the EOM flags will be handled by the endpoint.
10683 */
10684 if (htx_is_empty(res_htx) && (strm->txn->rsp.flags & (HTTP_MSGF_XFER_LEN|HTTP_MSGF_CNT_LEN)) == HTTP_MSGF_XFER_LEN) {
10685 if (!htx_add_endof(res_htx, HTX_BLK_EOT)) {
Christopher Faulet7b3d38a2023-05-05 11:28:45 +020010686 sc_need_room(sc, sizeof(struct htx_blk)+1);
Christopher Fauletf89af9c2022-04-07 10:07:18 +020010687 goto out;
10688 }
10689 channel_add_input(res, 1);
10690 }
10691
Christopher Fauletd1ac2b92020-12-02 19:12:22 +010010692 res_htx->flags |= HTX_FL_EOM;
Christopher Faulet31572222023-03-31 11:13:48 +020010693 se_fl_set(ctx->sedesc, SE_FL_EOI|SE_FL_EOS);
Willy Tarreauaa229cc2022-05-06 14:26:10 +020010694 strm->txn->status = http_ctx->status;
10695 http_ctx->flags |= APPLET_RSP_SENT;
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010696 }
10697
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010698 out:
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010699 htx_to_buf(res_htx, &res->buf);
Christopher Faulet31572222023-03-31 11:13:48 +020010700 /* eat the whole request */
10701 if (co_data(req)) {
10702 req_htx = htx_from_buf(&req->buf);
10703 co_htx_skip(req, req_htx, co_data(req));
10704 htx_to_buf(req_htx, &req->buf);
10705 }
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010706 return;
10707
10708 error:
10709
10710 /* If we are in HTTP mode, and we are not send any
10711 * data, return a 500 server error in best effort:
10712 * if there is no room available in the buffer,
10713 * just close the connection.
10714 */
Willy Tarreauaa229cc2022-05-06 14:26:10 +020010715 if (!(http_ctx->flags & APPLET_HDR_SENT)) {
Christopher Fauletf7346382019-07-17 22:02:08 +020010716 struct buffer *err = &http_err_chunks[HTTP_ERR_500];
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010717
10718 channel_erase(res);
10719 res->buf.data = b_data(err);
10720 memcpy(res->buf.area, b_head(err), b_data(err));
10721 res_htx = htx_from_buf(&res->buf);
Christopher Fauletf6cce3f2019-02-27 21:20:09 +010010722 channel_add_input(res, res_htx->data);
Christopher Faulet31572222023-03-31 11:13:48 +020010723 se_fl_set(ctx->sedesc, SE_FL_EOI|SE_FL_EOS);
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010724 }
Christopher Faulet31572222023-03-31 11:13:48 +020010725 else
10726 se_fl_set(ctx->sedesc, SE_FL_ERROR);
10727
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010728 if (!(strm->flags & SF_ERR_MASK))
10729 strm->flags |= SF_ERR_RESOURCE;
Willy Tarreauaa229cc2022-05-06 14:26:10 +020010730 http_ctx->flags |= APPLET_DONE;
Christopher Faulet31572222023-03-31 11:13:48 +020010731 goto out;
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010732}
10733
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010734static void hlua_applet_http_release(struct appctx *ctx)
10735{
Willy Tarreauaa229cc2022-05-06 14:26:10 +020010736 struct hlua_http_ctx *http_ctx = ctx->svcctx;
10737
10738 task_destroy(http_ctx->task);
10739 http_ctx->task = NULL;
10740 hlua_ctx_destroy(http_ctx->hlua);
10741 http_ctx->hlua = NULL;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010742}
10743
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +020010744/* global {tcp|http}-request parser. Return ACT_RET_PRS_OK in
Ilya Shipitsin856aabc2020-04-16 23:51:34 +050010745 * success case, else return ACT_RET_PRS_ERR.
Thierry FOURNIERbabae282015-09-17 11:36:37 +020010746 *
10747 * This function can fail with an abort() due to an Lua critical error.
10748 * We are in the configuration parsing process of HAProxy, this abort() is
10749 * tolerated.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +010010750 */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +020010751static enum act_parse_ret action_register_lua(const char **args, int *cur_arg, struct proxy *px,
10752 struct act_rule *rule, char **err)
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +010010753{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +020010754 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +010010755 int i;
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010756
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +020010757 /* Memory for the rule. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +020010758 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +020010759 if (!rule->arg.hlua_rule) {
10760 memprintf(err, "out of memory error");
Christopher Faulet528526f2021-04-12 14:37:32 +020010761 goto error;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +020010762 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +010010763
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +010010764 /* Memory for arguments. */
Tim Duesterhuse52b6e52020-09-12 20:26:43 +020010765 rule->arg.hlua_rule->args = calloc(fcn->nargs + 1,
10766 sizeof(*rule->arg.hlua_rule->args));
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +010010767 if (!rule->arg.hlua_rule->args) {
10768 memprintf(err, "out of memory error");
Christopher Faulet528526f2021-04-12 14:37:32 +020010769 goto error;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +010010770 }
10771
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +020010772 /* Reference the Lua function and store the reference. */
Thierry Fournierad5345f2020-11-29 02:05:57 +010010773 rule->arg.hlua_rule->fcn = fcn;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +020010774
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +010010775 /* Expect some arguments */
10776 for (i = 0; i < fcn->nargs; i++) {
Thierry FOURNIER1725c2e2019-01-06 19:38:49 +010010777 if (*args[*cur_arg] == '\0') {
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +010010778 memprintf(err, "expect %d arguments", fcn->nargs);
Christopher Faulet528526f2021-04-12 14:37:32 +020010779 goto error;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +010010780 }
Thierry FOURNIER1725c2e2019-01-06 19:38:49 +010010781 rule->arg.hlua_rule->args[i] = strdup(args[*cur_arg]);
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +010010782 if (!rule->arg.hlua_rule->args[i]) {
10783 memprintf(err, "out of memory error");
Christopher Faulet528526f2021-04-12 14:37:32 +020010784 goto error;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +010010785 }
10786 (*cur_arg)++;
10787 }
10788 rule->arg.hlua_rule->args[i] = NULL;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +020010789
Thierry FOURNIER42148732015-09-02 17:17:33 +020010790 rule->action = ACT_CUSTOM;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +020010791 rule->action_ptr = hlua_action;
Thierry FOURNIERafa80492015-08-19 09:04:15 +020010792 return ACT_RET_PRS_OK;
Christopher Faulet528526f2021-04-12 14:37:32 +020010793
10794 error:
10795 if (rule->arg.hlua_rule) {
10796 if (rule->arg.hlua_rule->args) {
10797 for (i = 0; i < fcn->nargs; i++)
10798 ha_free(&rule->arg.hlua_rule->args[i]);
10799 ha_free(&rule->arg.hlua_rule->args);
10800 }
10801 ha_free(&rule->arg.hlua_rule);
10802 }
10803 return ACT_RET_PRS_ERR;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +010010804}
10805
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010806static enum act_parse_ret action_register_service_http(const char **args, int *cur_arg, struct proxy *px,
10807 struct act_rule *rule, char **err)
10808{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +020010809 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010810
Thierry FOURNIER718e2a72015-12-20 20:13:14 +010010811 /* HTTP applets are forbidden in tcp-request rules.
Ilya Shipitsin856aabc2020-04-16 23:51:34 +050010812 * HTTP applet request requires everything initialized by
Thierry FOURNIER718e2a72015-12-20 20:13:14 +010010813 * "http_process_request" (analyzer flag AN_REQ_HTTP_INNER).
Ilya Shipitsin856aabc2020-04-16 23:51:34 +050010814 * The applet will be immediately initialized, but its before
Thierry FOURNIER718e2a72015-12-20 20:13:14 +010010815 * the call of this analyzer.
10816 */
10817 if (rule->from != ACT_F_HTTP_REQ) {
10818 memprintf(err, "HTTP applets are forbidden from 'tcp-request' rulesets");
10819 return ACT_RET_PRS_ERR;
10820 }
10821
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010822 /* Memory for the rule. */
10823 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
10824 if (!rule->arg.hlua_rule) {
10825 memprintf(err, "out of memory error");
10826 return ACT_RET_PRS_ERR;
10827 }
10828
10829 /* Reference the Lua function and store the reference. */
Thierry Fournierad5345f2020-11-29 02:05:57 +010010830 rule->arg.hlua_rule->fcn = fcn;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010831
10832 /* TODO: later accept arguments. */
10833 rule->arg.hlua_rule->args = NULL;
10834
10835 /* Add applet pointer in the rule. */
10836 rule->applet.obj_type = OBJ_TYPE_APPLET;
10837 rule->applet.name = fcn->name;
10838 rule->applet.init = hlua_applet_http_init;
10839 rule->applet.fct = hlua_applet_http_fct;
10840 rule->applet.release = hlua_applet_http_release;
10841 rule->applet.timeout = hlua_timeout_applet;
10842
10843 return ACT_RET_PRS_OK;
10844}
10845
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010846/* This function is an LUA binding used for registering
10847 * "sample-conv" functions. It expects a converter name used
10848 * in the haproxy configuration file, and an LUA function.
10849 */
10850__LJMP static int hlua_register_action(lua_State *L)
10851{
Christopher Faulet4fc9da02021-04-12 15:08:12 +020010852 struct action_kw_list *akl = NULL;
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010853 const char *name;
10854 int ref;
10855 int len;
Christopher Faulet4fc9da02021-04-12 15:08:12 +020010856 struct hlua_function *fcn = NULL;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +010010857 int nargs;
Thierry Fournierf67442e2020-11-28 20:41:07 +010010858 struct buffer *trash;
10859 struct action_kw *akw;
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010860
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +010010861 /* Initialise the number of expected arguments at 0. */
10862 nargs = 0;
10863
10864 if (lua_gettop(L) < 3 || lua_gettop(L) > 4)
10865 WILL_LJMP(luaL_error(L, "'register_action' needs between 3 and 4 arguments"));
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010866
Aurelien DARRAGON87f52972023-02-24 09:43:54 +010010867 if (hlua_gethlua(L)) {
10868 /* runtime processing */
10869 WILL_LJMP(luaL_error(L, "register_action: not available outside of body context"));
10870 }
10871
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010872 /* First argument : converter name. */
10873 name = MAY_LJMP(luaL_checkstring(L, 1));
10874
10875 /* Second argument : environment. */
10876 if (lua_type(L, 2) != LUA_TTABLE)
10877 WILL_LJMP(luaL_error(L, "register_action: second argument must be a table of strings"));
10878
10879 /* Third argument : lua function. */
10880 ref = MAY_LJMP(hlua_checkfunction(L, 3));
10881
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -080010882 /* Fourth argument : number of mandatory arguments expected on the configuration line. */
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +010010883 if (lua_gettop(L) >= 4)
10884 nargs = MAY_LJMP(luaL_checkinteger(L, 4));
10885
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -080010886 /* browse the second argument as an array. */
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010887 lua_pushnil(L);
10888 while (lua_next(L, 2) != 0) {
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +010010889 if (lua_type(L, -1) != LUA_TSTRING) {
10890 hlua_unref(L, ref);
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010891 WILL_LJMP(luaL_error(L, "register_action: second argument must be a table of strings"));
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +010010892 }
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010893
Thierry Fournierf67442e2020-11-28 20:41:07 +010010894 /* Check if action exists */
10895 trash = get_trash_chunk();
10896 chunk_printf(trash, "lua.%s", name);
10897 if (strcmp(lua_tostring(L, -1), "tcp-req") == 0) {
10898 akw = tcp_req_cont_action(trash->area);
10899 } else if (strcmp(lua_tostring(L, -1), "tcp-res") == 0) {
10900 akw = tcp_res_cont_action(trash->area);
10901 } else if (strcmp(lua_tostring(L, -1), "http-req") == 0) {
10902 akw = action_http_req_custom(trash->area);
10903 } else if (strcmp(lua_tostring(L, -1), "http-res") == 0) {
10904 akw = action_http_res_custom(trash->area);
10905 } else {
10906 akw = NULL;
10907 }
10908 if (akw != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +010010909 fcn = akw->private;
10910 if (fcn->function_ref[hlua_state_id] != -1) {
10911 ha_warning("Trying to register action 'lua.%s' more than once. "
10912 "This will become a hard error in version 2.5.\n", name);
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +010010913 hlua_unref(L, fcn->function_ref[hlua_state_id]);
Thierry Fournier59f11be2020-11-29 00:37:41 +010010914 }
10915 fcn->function_ref[hlua_state_id] = ref;
10916
10917 /* pop the environment string. */
10918 lua_pop(L, 1);
10919 continue;
Thierry Fournierf67442e2020-11-28 20:41:07 +010010920 }
10921
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010922 /* Check required environment. Only accepted "http" or "tcp". */
10923 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +020010924 akl = calloc(1, sizeof(*akl) + sizeof(struct action_kw) * 2);
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010925 if (!akl)
Christopher Faulet4fc9da02021-04-12 15:08:12 +020010926 goto alloc_error;;
Thierry Fournier62a22aa2020-11-28 21:06:35 +010010927 fcn = new_hlua_function();
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010928 if (!fcn)
Christopher Faulet4fc9da02021-04-12 15:08:12 +020010929 goto alloc_error;
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010930
10931 /* Fill fcn. */
10932 fcn->name = strdup(name);
10933 if (!fcn->name)
Christopher Faulet4fc9da02021-04-12 15:08:12 +020010934 goto alloc_error;
Thierry Fournierc7492592020-11-28 23:57:24 +010010935 fcn->function_ref[hlua_state_id] = ref;
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010936
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -070010937 /* Set the expected number of arguments. */
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +010010938 fcn->nargs = nargs;
10939
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010940 /* List head */
10941 akl->list.n = akl->list.p = NULL;
10942
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010943 /* action keyword. */
10944 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +020010945 akl->kw[0].kw = calloc(1, len);
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010946 if (!akl->kw[0].kw)
Christopher Faulet4fc9da02021-04-12 15:08:12 +020010947 goto alloc_error;
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010948
10949 snprintf((char *)akl->kw[0].kw, len, "lua.%s", name);
10950
Amaury Denoyellee4a617c2021-05-06 15:33:09 +020010951 akl->kw[0].flags = 0;
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010952 akl->kw[0].private = fcn;
10953 akl->kw[0].parse = action_register_lua;
10954
10955 /* select the action registering point. */
10956 if (strcmp(lua_tostring(L, -1), "tcp-req") == 0)
10957 tcp_req_cont_keywords_register(akl);
10958 else if (strcmp(lua_tostring(L, -1), "tcp-res") == 0)
10959 tcp_res_cont_keywords_register(akl);
10960 else if (strcmp(lua_tostring(L, -1), "http-req") == 0)
10961 http_req_keywords_register(akl);
10962 else if (strcmp(lua_tostring(L, -1), "http-res") == 0)
10963 http_res_keywords_register(akl);
Christopher Faulet4fc9da02021-04-12 15:08:12 +020010964 else {
10965 release_hlua_function(fcn);
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +010010966 hlua_unref(L, ref);
Christopher Faulet4fc9da02021-04-12 15:08:12 +020010967 if (akl)
10968 ha_free((char **)&(akl->kw[0].kw));
10969 ha_free(&akl);
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +010010970 WILL_LJMP(luaL_error(L, "Lua action environment '%s' is unknown. "
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010971 "'tcp-req', 'tcp-res', 'http-req' or 'http-res' "
10972 "are expected.", lua_tostring(L, -1)));
Christopher Faulet4fc9da02021-04-12 15:08:12 +020010973 }
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010974
10975 /* pop the environment string. */
10976 lua_pop(L, 1);
Christopher Faulet4fc9da02021-04-12 15:08:12 +020010977
10978 /* reset for next loop */
10979 akl = NULL;
10980 fcn = NULL;
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010981 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010982 return ACT_RET_PRS_OK;
Christopher Faulet4fc9da02021-04-12 15:08:12 +020010983
10984 alloc_error:
10985 release_hlua_function(fcn);
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +010010986 hlua_unref(L, ref);
Christopher Faulet4fc9da02021-04-12 15:08:12 +020010987 ha_free(&akl);
10988 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
10989 return 0; /* Never reached */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010990}
10991
10992static enum act_parse_ret action_register_service_tcp(const char **args, int *cur_arg, struct proxy *px,
10993 struct act_rule *rule, char **err)
10994{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +020010995 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010996
Christopher Faulet280f85b2019-07-15 15:02:04 +020010997 if (px->mode == PR_MODE_HTTP) {
10998 memprintf(err, "Lua TCP services cannot be used on HTTP proxies");
Christopher Fauletafd8f102018-11-08 11:34:21 +010010999 return ACT_RET_PRS_ERR;
11000 }
11001
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020011002 /* Memory for the rule. */
11003 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
11004 if (!rule->arg.hlua_rule) {
11005 memprintf(err, "out of memory error");
11006 return ACT_RET_PRS_ERR;
11007 }
Thierry FOURNIER8255a752015-09-23 21:03:35 +020011008
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020011009 /* Reference the Lua function and store the reference. */
Thierry Fournierad5345f2020-11-29 02:05:57 +010011010 rule->arg.hlua_rule->fcn = fcn;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020011011
11012 /* TODO: later accept arguments. */
11013 rule->arg.hlua_rule->args = NULL;
11014
11015 /* Add applet pointer in the rule. */
11016 rule->applet.obj_type = OBJ_TYPE_APPLET;
11017 rule->applet.name = fcn->name;
11018 rule->applet.init = hlua_applet_tcp_init;
11019 rule->applet.fct = hlua_applet_tcp_fct;
11020 rule->applet.release = hlua_applet_tcp_release;
11021 rule->applet.timeout = hlua_timeout_applet;
11022
11023 return 0;
11024}
11025
11026/* This function is an LUA binding used for registering
11027 * "sample-conv" functions. It expects a converter name used
11028 * in the haproxy configuration file, and an LUA function.
11029 */
11030__LJMP static int hlua_register_service(lua_State *L)
11031{
11032 struct action_kw_list *akl;
11033 const char *name;
11034 const char *env;
11035 int ref;
11036 int len;
Christopher Faulet5c028d72021-04-12 15:11:44 +020011037 struct hlua_function *fcn = NULL;
Thierry Fournierf67442e2020-11-28 20:41:07 +010011038 struct buffer *trash;
11039 struct action_kw *akw;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020011040
11041 MAY_LJMP(check_args(L, 3, "register_service"));
11042
Aurelien DARRAGON87f52972023-02-24 09:43:54 +010011043 if (hlua_gethlua(L)) {
11044 /* runtime processing */
11045 WILL_LJMP(luaL_error(L, "register_service: not available outside of body context"));
11046 }
11047
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020011048 /* First argument : converter name. */
11049 name = MAY_LJMP(luaL_checkstring(L, 1));
11050
11051 /* Second argument : environment. */
11052 env = MAY_LJMP(luaL_checkstring(L, 2));
11053
11054 /* Third argument : lua function. */
11055 ref = MAY_LJMP(hlua_checkfunction(L, 3));
11056
Thierry Fournierf67442e2020-11-28 20:41:07 +010011057 /* Check for service already registered */
11058 trash = get_trash_chunk();
11059 chunk_printf(trash, "lua.%s", name);
11060 akw = service_find(trash->area);
11061 if (akw != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +010011062 fcn = akw->private;
11063 if (fcn->function_ref[hlua_state_id] != -1) {
11064 ha_warning("Trying to register service 'lua.%s' more than once. "
11065 "This will become a hard error in version 2.5.\n", name);
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +010011066 hlua_unref(L, fcn->function_ref[hlua_state_id]);
Thierry Fournier59f11be2020-11-29 00:37:41 +010011067 }
11068 fcn->function_ref[hlua_state_id] = ref;
11069 return 0;
Thierry Fournierf67442e2020-11-28 20:41:07 +010011070 }
11071
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020011072 /* Allocate and fill the sample fetch keyword struct. */
11073 akl = calloc(1, sizeof(*akl) + sizeof(struct action_kw) * 2);
11074 if (!akl)
Christopher Faulet5c028d72021-04-12 15:11:44 +020011075 goto alloc_error;
Thierry Fournier62a22aa2020-11-28 21:06:35 +010011076 fcn = new_hlua_function();
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020011077 if (!fcn)
Christopher Faulet5c028d72021-04-12 15:11:44 +020011078 goto alloc_error;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020011079
11080 /* Fill fcn. */
11081 len = strlen("<lua.>") + strlen(name) + 1;
11082 fcn->name = calloc(1, len);
11083 if (!fcn->name)
Christopher Faulet5c028d72021-04-12 15:11:44 +020011084 goto alloc_error;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020011085 snprintf((char *)fcn->name, len, "<lua.%s>", name);
Thierry Fournierc7492592020-11-28 23:57:24 +010011086 fcn->function_ref[hlua_state_id] = ref;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020011087
11088 /* List head */
11089 akl->list.n = akl->list.p = NULL;
11090
11091 /* converter keyword. */
11092 len = strlen("lua.") + strlen(name) + 1;
11093 akl->kw[0].kw = calloc(1, len);
11094 if (!akl->kw[0].kw)
Christopher Faulet5c028d72021-04-12 15:11:44 +020011095 goto alloc_error;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020011096
11097 snprintf((char *)akl->kw[0].kw, len, "lua.%s", name);
11098
Thierry FOURNIER / OZON.IO02564fd2016-11-12 11:07:05 +010011099 /* Check required environment. Only accepted "http" or "tcp". */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020011100 if (strcmp(env, "tcp") == 0)
11101 akl->kw[0].parse = action_register_service_tcp;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020011102 else if (strcmp(env, "http") == 0)
11103 akl->kw[0].parse = action_register_service_http;
Christopher Faulet5c028d72021-04-12 15:11:44 +020011104 else {
11105 release_hlua_function(fcn);
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +010011106 hlua_unref(L, ref);
Christopher Faulet5c028d72021-04-12 15:11:44 +020011107 if (akl)
11108 ha_free((char **)&(akl->kw[0].kw));
11109 ha_free(&akl);
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +010011110 WILL_LJMP(luaL_error(L, "Lua service environment '%s' is unknown. "
Eric Salamafe7456f2017-12-21 14:30:07 +010011111 "'tcp' or 'http' are expected.", env));
Christopher Faulet5c028d72021-04-12 15:11:44 +020011112 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020011113
Amaury Denoyellee4a617c2021-05-06 15:33:09 +020011114 akl->kw[0].flags = 0;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020011115 akl->kw[0].private = fcn;
11116
11117 /* End of array. */
11118 memset(&akl->kw[1], 0, sizeof(*akl->kw));
11119
11120 /* Register this new converter */
11121 service_keywords_register(akl);
11122
Thierry FOURNIER8255a752015-09-23 21:03:35 +020011123 return 0;
Christopher Faulet5c028d72021-04-12 15:11:44 +020011124
11125 alloc_error:
11126 release_hlua_function(fcn);
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +010011127 hlua_unref(L, ref);
Christopher Faulet5c028d72021-04-12 15:11:44 +020011128 ha_free(&akl);
11129 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
11130 return 0; /* Never reached */
Thierry FOURNIER8255a752015-09-23 21:03:35 +020011131}
11132
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011133/* This function initialises Lua cli handler. It copies the
11134 * arguments in the Lua stack and create channel IO objects.
11135 */
Aurélien Nephtaliabbf6072018-04-18 13:26:46 +020011136static int hlua_cli_parse_fct(char **args, char *payload, struct appctx *appctx, void *private)
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011137{
Willy Tarreaubcda5f62022-05-03 18:13:39 +020011138 struct hlua_cli_ctx *ctx = applet_reserve_svcctx(appctx, sizeof(*ctx));
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011139 struct hlua *hlua;
11140 struct hlua_function *fcn;
11141 int i;
11142 const char *error;
11143
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011144 fcn = private;
Willy Tarreaubcda5f62022-05-03 18:13:39 +020011145 ctx->fcn = private;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +010011146
Willy Tarreaubafbe012017-11-24 17:34:44 +010011147 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +010011148 if (!hlua) {
11149 SEND_ERR(NULL, "Lua cli '%s': out of memory.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +010011150 return 1;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +010011151 }
11152 HLUA_INIT(hlua);
Willy Tarreaubcda5f62022-05-03 18:13:39 +020011153 ctx->hlua = hlua;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011154
11155 /* Create task used by signal to wakeup applets.
Ilya Shipitsind4259502020-04-08 01:07:56 +050011156 * We use the same wakeup function than the Lua applet_tcp and
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011157 * applet_http. It is absolutely compatible.
11158 */
Willy Tarreaubcda5f62022-05-03 18:13:39 +020011159 ctx->task = task_new_here();
11160 if (!ctx->task) {
Thierry FOURNIERffbf5692016-12-16 11:14:06 +010011161 SEND_ERR(NULL, "Lua cli '%s': out of memory.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +010011162 goto error;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011163 }
Willy Tarreaubcda5f62022-05-03 18:13:39 +020011164 ctx->task->nice = 0;
11165 ctx->task->context = appctx;
11166 ctx->task->process = hlua_applet_wakeup;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011167
11168 /* Initialises the Lua context */
Aurelien DARRAGON6b0b9bd2023-03-21 14:02:16 +010011169 if (!hlua_ctx_init(hlua, fcn_ref_to_stack_id(fcn), ctx->task)) {
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011170 SEND_ERR(NULL, "Lua cli '%s': can't initialize Lua context.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +010011171 goto error;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011172 }
11173
11174 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +010011175 if (!SET_SAFE_LJMP(hlua)) {
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011176 if (lua_type(hlua->T, -1) == LUA_TSTRING)
11177 error = lua_tostring(hlua->T, -1);
11178 else
11179 error = "critical error";
11180 SEND_ERR(NULL, "Lua cli '%s': %s.\n", fcn->name, error);
11181 goto error;
11182 }
11183
11184 /* Check stack available size. */
11185 if (!lua_checkstack(hlua->T, 2)) {
11186 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
11187 goto error;
11188 }
11189
11190 /* Restore the function in the stack. */
Aurelien DARRAGON4fdf8b52023-03-20 17:22:37 +010011191 hlua_pushref(hlua->T, fcn->function_ref[hlua->state_id]);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011192
11193 /* Once the arguments parsed, the CLI is like an AppletTCP,
11194 * so push AppletTCP in the stack.
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011195 */
11196 if (!hlua_applet_tcp_new(hlua->T, appctx)) {
11197 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
11198 goto error;
11199 }
11200 hlua->nargs = 1;
11201
11202 /* push keywords in the stack. */
11203 for (i = 0; *args[i]; i++) {
11204 /* Check stack available size. */
11205 if (!lua_checkstack(hlua->T, 1)) {
11206 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
11207 goto error;
11208 }
11209 lua_pushstring(hlua->T, args[i]);
11210 hlua->nargs++;
11211 }
11212
11213 /* We must initialize the execution timeouts. */
Aurelien DARRAGONda9503c2022-11-25 09:10:07 +010011214 hlua_timer_init(&hlua->timer, hlua_timeout_session);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011215
11216 /* At this point the execution is safe. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +010011217 RESET_SAFE_LJMP(hlua);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011218
11219 /* It's ok */
11220 return 0;
11221
11222 /* It's not ok. */
11223error:
Thierry Fournier7cbe5042020-11-28 17:02:21 +010011224 RESET_SAFE_LJMP(hlua);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011225 hlua_ctx_destroy(hlua);
Willy Tarreaubcda5f62022-05-03 18:13:39 +020011226 ctx->hlua = NULL;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011227 return 1;
11228}
11229
11230static int hlua_cli_io_handler_fct(struct appctx *appctx)
11231{
Willy Tarreaubcda5f62022-05-03 18:13:39 +020011232 struct hlua_cli_ctx *ctx = appctx->svcctx;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011233 struct hlua *hlua;
Willy Tarreau475e4632022-05-27 10:26:46 +020011234 struct stconn *sc;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011235 struct hlua_function *fcn;
11236
Willy Tarreaubcda5f62022-05-03 18:13:39 +020011237 hlua = ctx->hlua;
Willy Tarreauc12b3212022-05-27 11:08:15 +020011238 sc = appctx_sc(appctx);
Willy Tarreaubcda5f62022-05-03 18:13:39 +020011239 fcn = ctx->fcn;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011240
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011241 /* Execute the function. */
11242 switch (hlua_ctx_resume(hlua, 1)) {
11243
11244 /* finished. */
11245 case HLUA_E_OK:
11246 return 1;
11247
11248 /* yield. */
11249 case HLUA_E_AGAIN:
11250 /* We want write. */
11251 if (HLUA_IS_WAKERESWR(hlua))
Christopher Faulet7b3d38a2023-05-05 11:28:45 +020011252 sc_need_room(sc, -1);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011253 /* Set the timeout. */
11254 if (hlua->wake_time != TICK_ETERNITY)
11255 task_schedule(hlua->task, hlua->wake_time);
11256 return 0;
11257
11258 /* finished with error. */
11259 case HLUA_E_ERRMSG:
11260 /* Display log. */
11261 SEND_ERR(NULL, "Lua cli '%s': %s.\n",
11262 fcn->name, lua_tostring(hlua->T, -1));
11263 lua_pop(hlua->T, 1);
11264 return 1;
11265
Thierry Fournierd5b073c2018-05-21 19:42:47 +020011266 case HLUA_E_ETMOUT:
11267 SEND_ERR(NULL, "Lua converter '%s': execution timeout.\n",
11268 fcn->name);
11269 return 1;
11270
11271 case HLUA_E_NOMEM:
11272 SEND_ERR(NULL, "Lua converter '%s': out of memory error.\n",
11273 fcn->name);
11274 return 1;
11275
11276 case HLUA_E_YIELD: /* unexpected */
11277 SEND_ERR(NULL, "Lua converter '%s': yield not allowed.\n",
11278 fcn->name);
11279 return 1;
11280
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011281 case HLUA_E_ERR:
11282 /* Display log. */
11283 SEND_ERR(NULL, "Lua cli '%s' return an unknown error.\n",
11284 fcn->name);
11285 return 1;
11286
11287 default:
11288 return 1;
11289 }
11290
11291 return 1;
11292}
11293
11294static void hlua_cli_io_release_fct(struct appctx *appctx)
11295{
Willy Tarreaubcda5f62022-05-03 18:13:39 +020011296 struct hlua_cli_ctx *ctx = appctx->svcctx;
11297
11298 hlua_ctx_destroy(ctx->hlua);
11299 ctx->hlua = NULL;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011300}
11301
11302/* This function is an LUA binding used for registering
11303 * new keywords in the cli. It expects a list of keywords
11304 * which are the "path". It is limited to 5 keywords. A
11305 * description of the command, a function to be executed
11306 * for the parsing and a function for io handlers.
11307 */
11308__LJMP static int hlua_register_cli(lua_State *L)
11309{
11310 struct cli_kw_list *cli_kws;
11311 const char *message;
11312 int ref_io;
11313 int len;
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020011314 struct hlua_function *fcn = NULL;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011315 int index;
11316 int i;
Thierry Fournierf67442e2020-11-28 20:41:07 +010011317 struct buffer *trash;
11318 const char *kw[5];
11319 struct cli_kw *cli_kw;
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020011320 const char *errmsg;
Willy Tarreau22450af2023-04-07 15:27:55 +020011321 char *end;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011322
11323 MAY_LJMP(check_args(L, 3, "register_cli"));
11324
Aurelien DARRAGON87f52972023-02-24 09:43:54 +010011325 if (hlua_gethlua(L)) {
11326 /* runtime processing */
11327 WILL_LJMP(luaL_error(L, "register_cli: not available outside of body context"));
11328 }
11329
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011330 /* First argument : an array of maximum 5 keywords. */
11331 if (!lua_istable(L, 1))
11332 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table"));
11333
11334 /* Second argument : string with contextual message. */
11335 message = MAY_LJMP(luaL_checkstring(L, 2));
11336
11337 /* Third and fourth argument : lua function. */
11338 ref_io = MAY_LJMP(hlua_checkfunction(L, 3));
11339
Thierry Fournierf67442e2020-11-28 20:41:07 +010011340 /* Check for CLI service already registered */
11341 trash = get_trash_chunk();
11342 index = 0;
11343 lua_pushnil(L);
11344 memset(kw, 0, sizeof(kw));
11345 while (lua_next(L, 1) != 0) {
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +010011346 if (index >= CLI_PREFIX_KW_NB) {
11347 hlua_unref(L, ref_io);
Thierry Fournierf67442e2020-11-28 20:41:07 +010011348 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 +010011349 }
11350 if (lua_type(L, -1) != LUA_TSTRING) {
11351 hlua_unref(L, ref_io);
Thierry Fournierf67442e2020-11-28 20:41:07 +010011352 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table filled with strings"));
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +010011353 }
Thierry Fournierf67442e2020-11-28 20:41:07 +010011354 kw[index] = lua_tostring(L, -1);
11355 if (index == 0)
11356 chunk_printf(trash, "%s", kw[index]);
11357 else
11358 chunk_appendf(trash, " %s", kw[index]);
11359 index++;
11360 lua_pop(L, 1);
11361 }
11362 cli_kw = cli_find_kw_exact((char **)kw);
11363 if (cli_kw != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +010011364 fcn = cli_kw->private;
11365 if (fcn->function_ref[hlua_state_id] != -1) {
11366 ha_warning("Trying to register CLI keyword 'lua.%s' more than once. "
11367 "This will become a hard error in version 2.5.\n", trash->area);
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +010011368 hlua_unref(L, fcn->function_ref[hlua_state_id]);
Thierry Fournier59f11be2020-11-29 00:37:41 +010011369 }
11370 fcn->function_ref[hlua_state_id] = ref_io;
11371 return 0;
Thierry Fournierf67442e2020-11-28 20:41:07 +010011372 }
11373
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011374 /* Allocate and fill the sample fetch keyword struct. */
11375 cli_kws = calloc(1, sizeof(*cli_kws) + sizeof(struct cli_kw) * 2);
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020011376 if (!cli_kws) {
11377 errmsg = "Lua out of memory error.";
11378 goto error;
11379 }
Thierry Fournier62a22aa2020-11-28 21:06:35 +010011380 fcn = new_hlua_function();
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020011381 if (!fcn) {
11382 errmsg = "Lua out of memory error.";
11383 goto error;
11384 }
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011385
11386 /* Fill path. */
11387 index = 0;
11388 lua_pushnil(L);
11389 while(lua_next(L, 1) != 0) {
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020011390 if (index >= 5) {
11391 errmsg = "1st argument must be a table with a maximum of 5 entries";
11392 goto error;
11393 }
11394 if (lua_type(L, -1) != LUA_TSTRING) {
11395 errmsg = "1st argument must be a table filled with strings";
11396 goto error;
11397 }
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011398 cli_kws->kw[0].str_kw[index] = strdup(lua_tostring(L, -1));
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020011399 if (!cli_kws->kw[0].str_kw[index]) {
11400 errmsg = "Lua out of memory error.";
11401 goto error;
11402 }
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011403 index++;
11404 lua_pop(L, 1);
11405 }
11406
11407 /* Copy help message. */
11408 cli_kws->kw[0].usage = strdup(message);
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020011409 if (!cli_kws->kw[0].usage) {
11410 errmsg = "Lua out of memory error.";
11411 goto error;
11412 }
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011413
11414 /* Fill fcn io handler. */
11415 len = strlen("<lua.cli>") + 1;
11416 for (i = 0; i < index; i++)
11417 len += strlen(cli_kws->kw[0].str_kw[i]) + 1;
11418 fcn->name = calloc(1, len);
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020011419 if (!fcn->name) {
11420 errmsg = "Lua out of memory error.";
11421 goto error;
11422 }
Willy Tarreau22450af2023-04-07 15:27:55 +020011423
11424 end = fcn->name;
11425 len = 8;
11426 memcpy(end, "<lua.cli", len);
11427 end += len;
11428
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011429 for (i = 0; i < index; i++) {
Willy Tarreau22450af2023-04-07 15:27:55 +020011430 *(end++) = '.';
11431 len = strlen(cli_kws->kw[0].str_kw[i]);
11432 memcpy(end, cli_kws->kw[0].str_kw[i], len);
11433 end += len;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011434 }
Willy Tarreau22450af2023-04-07 15:27:55 +020011435 *(end++) = '>';
11436 *(end++) = 0;
11437
Thierry Fournierc7492592020-11-28 23:57:24 +010011438 fcn->function_ref[hlua_state_id] = ref_io;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011439
11440 /* Fill last entries. */
11441 cli_kws->kw[0].private = fcn;
11442 cli_kws->kw[0].parse = hlua_cli_parse_fct;
11443 cli_kws->kw[0].io_handler = hlua_cli_io_handler_fct;
11444 cli_kws->kw[0].io_release = hlua_cli_io_release_fct;
11445
11446 /* Register this new converter */
11447 cli_register_kw(cli_kws);
11448
11449 return 0;
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020011450
11451 error:
11452 release_hlua_function(fcn);
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +010011453 hlua_unref(L, ref_io);
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020011454 if (cli_kws) {
11455 for (i = 0; i < index; i++)
11456 ha_free((char **)&(cli_kws->kw[0].str_kw[i]));
11457 ha_free((char **)&(cli_kws->kw[0].usage));
11458 }
11459 ha_free(&cli_kws);
11460 WILL_LJMP(luaL_error(L, errmsg));
11461 return 0; /* Never reached */
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011462}
11463
Christopher Faulet69c581a2021-05-31 08:54:04 +020011464static int hlua_filter_init_per_thread(struct proxy *px, struct flt_conf *fconf)
11465{
11466 struct hlua_flt_config *conf = fconf->conf;
11467 lua_State *L;
11468 int error, pos, state_id, flt_ref;
11469
11470 state_id = reg_flt_to_stack_id(conf->reg);
11471 L = hlua_states[state_id];
11472 pos = lua_gettop(L);
11473
11474 /* The filter parsing function */
Aurelien DARRAGON4fdf8b52023-03-20 17:22:37 +010011475 hlua_pushref(L, conf->reg->fun_ref[state_id]);
Christopher Faulet69c581a2021-05-31 08:54:04 +020011476
11477 /* Push the filter class on the stack and resolve all callbacks */
Aurelien DARRAGON4fdf8b52023-03-20 17:22:37 +010011478 hlua_pushref(L, conf->reg->flt_ref[state_id]);
Christopher Faulet69c581a2021-05-31 08:54:04 +020011479
11480 /* Duplicate the filter class so each filter will have its own copy */
11481 lua_newtable(L);
11482 lua_pushnil(L);
11483
11484 while (lua_next(L, pos+2)) {
11485 lua_pushvalue(L, -2);
11486 lua_insert(L, -2);
11487 lua_settable(L, -4);
11488 }
Aurelien DARRAGON73d1a982023-03-20 17:42:08 +010011489 flt_ref = hlua_ref(L);
Christopher Faulet69c581a2021-05-31 08:54:04 +020011490
11491 /* Remove the original lua filter class from the stack */
11492 lua_pop(L, 1);
11493
11494 /* Push the copy on the stack */
Aurelien DARRAGON4fdf8b52023-03-20 17:22:37 +010011495 hlua_pushref(L, flt_ref);
Christopher Faulet69c581a2021-05-31 08:54:04 +020011496
11497 /* extra args are pushed in a table */
11498 lua_newtable(L);
11499 for (pos = 0; conf->args[pos]; pos++) {
11500 /* Check stack available size. */
11501 if (!lua_checkstack(L, 1)) {
11502 ha_alert("Lua filter '%s' : Lua error : full stack.", conf->reg->name);
11503 goto error;
11504 }
11505 lua_pushstring(L, conf->args[pos]);
11506 lua_rawseti(L, -2, lua_rawlen(L, -2) + 1);
11507 }
11508
11509 error = lua_pcall(L, 2, LUA_MULTRET, 0);
11510 switch (error) {
11511 case LUA_OK:
11512 /* replace the filter ref */
11513 conf->ref[state_id] = flt_ref;
11514 break;
11515 case LUA_ERRRUN:
11516 ha_alert("Lua filter '%s' : runtime error : %s", conf->reg->name, lua_tostring(L, -1));
11517 goto error;
11518 case LUA_ERRMEM:
11519 ha_alert("Lua filter '%s' : out of memory error", conf->reg->name);
11520 goto error;
11521 case LUA_ERRERR:
11522 ha_alert("Lua filter '%s' : message handler error : %s", conf->reg->name, lua_tostring(L, -1));
11523 goto error;
11524#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM <= 503
11525 case LUA_ERRGCMM:
11526 ha_alert("Lua filter '%s' : garbage collector error : %s", conf->reg->name, lua_tostring(L, -1));
11527 goto error;
11528#endif
11529 default:
Ilya Shipitsinff0f2782021-08-22 22:18:07 +050011530 ha_alert("Lua filter '%s' : unknown error : %s", conf->reg->name, lua_tostring(L, -1));
Christopher Faulet69c581a2021-05-31 08:54:04 +020011531 goto error;
11532 }
11533
11534 lua_settop(L, 0);
11535 return 0;
11536
11537 error:
11538 lua_settop(L, 0);
11539 return -1;
11540}
11541
11542static void hlua_filter_deinit_per_thread(struct proxy *px, struct flt_conf *fconf)
11543{
11544 struct hlua_flt_config *conf = fconf->conf;
11545 lua_State *L;
11546 int state_id;
11547
11548 if (!conf)
11549 return;
11550
11551 state_id = reg_flt_to_stack_id(conf->reg);
11552 L = hlua_states[state_id];
Aurelien DARRAGONfde199d2023-03-20 15:09:33 +010011553 hlua_unref(L, conf->ref[state_id]);
Christopher Faulet69c581a2021-05-31 08:54:04 +020011554}
11555
11556static int hlua_filter_init(struct proxy *px, struct flt_conf *fconf)
11557{
11558 struct hlua_flt_config *conf = fconf->conf;
11559 int state_id = reg_flt_to_stack_id(conf->reg);
11560
11561 /* Rely on per-thread init for global scripts */
11562 if (!state_id)
11563 return hlua_filter_init_per_thread(px, fconf);
11564 return 0;
11565}
11566
11567static void hlua_filter_deinit(struct proxy *px, struct flt_conf *fconf)
11568{
11569
11570 if (fconf->conf) {
11571 struct hlua_flt_config *conf = fconf->conf;
11572 int state_id = reg_flt_to_stack_id(conf->reg);
11573 int pos;
11574
11575 /* Rely on per-thread deinit for global scripts */
11576 if (!state_id)
11577 hlua_filter_deinit_per_thread(px, fconf);
11578
11579 for (pos = 0; conf->args[pos]; pos++)
11580 free(conf->args[pos]);
11581 free(conf->args);
11582 }
11583 ha_free(&fconf->conf);
11584 ha_free((char **)&fconf->id);
11585 ha_free(&fconf->ops);
11586}
11587
11588static int hlua_filter_new(struct stream *s, struct filter *filter)
11589{
11590 struct hlua_flt_config *conf = FLT_CONF(filter);
11591 struct hlua_flt_ctx *flt_ctx = NULL;
11592 int ret = 1;
11593
11594 /* In the execution wrappers linked with a stream, the
11595 * Lua context can be not initialized. This behavior
11596 * permits to save performances because a systematic
11597 * Lua initialization cause 5% performances loss.
11598 */
11599 if (!s->hlua) {
11600 struct hlua *hlua;
11601
11602 hlua = pool_alloc(pool_head_hlua);
11603 if (!hlua) {
11604 SEND_ERR(s->be, "Lua filter '%s': can't initialize Lua context.\n",
11605 conf->reg->name);
11606 ret = 0;
11607 goto end;
11608 }
11609 HLUA_INIT(hlua);
11610 s->hlua = hlua;
Aurelien DARRAGON6b0b9bd2023-03-21 14:02:16 +010011611 if (!hlua_ctx_init(s->hlua, reg_flt_to_stack_id(conf->reg), s->task)) {
Christopher Faulet69c581a2021-05-31 08:54:04 +020011612 SEND_ERR(s->be, "Lua filter '%s': can't initialize Lua context.\n",
11613 conf->reg->name);
11614 ret = 0;
11615 goto end;
11616 }
11617 }
11618
11619 flt_ctx = pool_zalloc(pool_head_hlua_flt_ctx);
11620 if (!flt_ctx) {
11621 SEND_ERR(s->be, "Lua filter '%s': can't initialize filter Lua context.\n",
11622 conf->reg->name);
11623 ret = 0;
11624 goto end;
11625 }
11626 flt_ctx->hlua[0] = pool_alloc(pool_head_hlua);
11627 flt_ctx->hlua[1] = pool_alloc(pool_head_hlua);
11628 if (!flt_ctx->hlua[0] || !flt_ctx->hlua[1]) {
11629 SEND_ERR(s->be, "Lua filter '%s': can't initialize filter Lua context.\n",
11630 conf->reg->name);
11631 ret = 0;
11632 goto end;
11633 }
11634 HLUA_INIT(flt_ctx->hlua[0]);
11635 HLUA_INIT(flt_ctx->hlua[1]);
Aurelien DARRAGON6b0b9bd2023-03-21 14:02:16 +010011636 if (!hlua_ctx_init(flt_ctx->hlua[0], reg_flt_to_stack_id(conf->reg), s->task) ||
11637 !hlua_ctx_init(flt_ctx->hlua[1], reg_flt_to_stack_id(conf->reg), s->task)) {
Christopher Faulet69c581a2021-05-31 08:54:04 +020011638 SEND_ERR(s->be, "Lua filter '%s': can't initialize filter Lua context.\n",
11639 conf->reg->name);
11640 ret = 0;
11641 goto end;
11642 }
11643
11644 if (!HLUA_IS_RUNNING(s->hlua)) {
11645 /* The following Lua calls can fail. */
11646 if (!SET_SAFE_LJMP(s->hlua)) {
11647 const char *error;
11648
11649 if (lua_type(s->hlua->T, -1) == LUA_TSTRING)
11650 error = lua_tostring(s->hlua->T, -1);
11651 else
11652 error = "critical error";
11653 SEND_ERR(s->be, "Lua filter '%s': %s.\n", conf->reg->name, error);
11654 ret = 0;
11655 goto end;
11656 }
11657
11658 /* Check stack size. */
11659 if (!lua_checkstack(s->hlua->T, 1)) {
11660 SEND_ERR(s->be, "Lua filter '%s': full stack.\n", conf->reg->name);
Tim Duesterhus22817382021-09-11 23:17:25 +020011661 RESET_SAFE_LJMP(s->hlua);
Christopher Faulet69c581a2021-05-31 08:54:04 +020011662 ret = 0;
11663 goto end;
11664 }
11665
Aurelien DARRAGON4fdf8b52023-03-20 17:22:37 +010011666 hlua_pushref(s->hlua->T, conf->ref[s->hlua->state_id]);
Christopher Faulet69c581a2021-05-31 08:54:04 +020011667 if (lua_getfield(s->hlua->T, -1, "new") != LUA_TFUNCTION) {
11668 SEND_ERR(s->be, "Lua filter '%s': 'new' field is not a function.\n",
11669 conf->reg->name);
11670 RESET_SAFE_LJMP(s->hlua);
11671 ret = 0;
11672 goto end;
11673 }
11674 lua_insert(s->hlua->T, -2);
11675
11676 /* Push the copy on the stack */
11677 s->hlua->nargs = 1;
11678
11679 /* We must initialize the execution timeouts. */
Aurelien DARRAGONda9503c2022-11-25 09:10:07 +010011680 hlua_timer_init(&s->hlua->timer, hlua_timeout_session);
Christopher Faulet69c581a2021-05-31 08:54:04 +020011681
11682 /* At this point the execution is safe. */
11683 RESET_SAFE_LJMP(s->hlua);
11684 }
11685
11686 switch (hlua_ctx_resume(s->hlua, 0)) {
11687 case HLUA_E_OK:
11688 /* Nothing returned or not a table, ignore the filter for current stream */
11689 if (!lua_gettop(s->hlua->T) || !lua_istable(s->hlua->T, 1)) {
11690 ret = 0;
11691 goto end;
11692 }
11693
11694 /* Attached the filter pointer to the ctx */
11695 lua_pushstring(s->hlua->T, "__filter");
11696 lua_pushlightuserdata(s->hlua->T, filter);
11697 lua_settable(s->hlua->T, -3);
11698
11699 /* Save a ref on the filter ctx */
11700 lua_pushvalue(s->hlua->T, 1);
Aurelien DARRAGON73d1a982023-03-20 17:42:08 +010011701 flt_ctx->ref = hlua_ref(s->hlua->T);
Christopher Faulet69c581a2021-05-31 08:54:04 +020011702 filter->ctx = flt_ctx;
11703 break;
11704 case HLUA_E_ERRMSG:
11705 SEND_ERR(s->be, "Lua filter '%s' : %s.\n", conf->reg->name, lua_tostring(s->hlua->T, -1));
11706 ret = -1;
11707 goto end;
11708 case HLUA_E_ETMOUT:
11709 SEND_ERR(s->be, "Lua filter '%s' : 'new' execution timeout.\n", conf->reg->name);
11710 ret = 0;
11711 goto end;
11712 case HLUA_E_NOMEM:
11713 SEND_ERR(s->be, "Lua filter '%s' : out of memory error.\n", conf->reg->name);
11714 ret = 0;
11715 goto end;
11716 case HLUA_E_AGAIN:
11717 case HLUA_E_YIELD:
11718 SEND_ERR(s->be, "Lua filter '%s': yield functions like core.tcp() or core.sleep()"
11719 " are not allowed from 'new' function.\n", conf->reg->name);
11720 ret = 0;
11721 goto end;
11722 case HLUA_E_ERR:
11723 SEND_ERR(s->be, "Lua filter '%s': 'new' returns an unknown error.\n", conf->reg->name);
11724 ret = 0;
11725 goto end;
11726 default:
11727 ret = 0;
11728 goto end;
11729 }
11730
11731 end:
11732 if (s->hlua)
11733 lua_settop(s->hlua->T, 0);
11734 if (ret <= 0) {
11735 if (flt_ctx) {
11736 hlua_ctx_destroy(flt_ctx->hlua[0]);
11737 hlua_ctx_destroy(flt_ctx->hlua[1]);
11738 pool_free(pool_head_hlua_flt_ctx, flt_ctx);
11739 }
11740 }
11741 return ret;
11742}
11743
11744static void hlua_filter_delete(struct stream *s, struct filter *filter)
11745{
11746 struct hlua_flt_ctx *flt_ctx = filter->ctx;
11747
Aurelien DARRAGONfde199d2023-03-20 15:09:33 +010011748 hlua_unref(s->hlua->T, flt_ctx->ref);
Christopher Faulet69c581a2021-05-31 08:54:04 +020011749 hlua_ctx_destroy(flt_ctx->hlua[0]);
11750 hlua_ctx_destroy(flt_ctx->hlua[1]);
11751 pool_free(pool_head_hlua_flt_ctx, flt_ctx);
11752 filter->ctx = NULL;
11753}
11754
Christopher Faulet9f55a502020-02-25 15:21:02 +010011755static int hlua_filter_from_payload(struct filter *filter)
11756{
11757 struct hlua_flt_ctx *flt_ctx = filter->ctx;
11758
11759 return (flt_ctx && !!(flt_ctx->flags & HLUA_FLT_CTX_FL_PAYLOAD));
11760}
11761
Christopher Fauletc404f112020-02-26 15:03:09 +010011762static int hlua_filter_callback(struct stream *s, struct filter *filter, const char *fun,
11763 int dir, unsigned int flags)
11764{
11765 struct hlua *flt_hlua;
11766 struct hlua_flt_config *conf = FLT_CONF(filter);
11767 struct hlua_flt_ctx *flt_ctx = filter->ctx;
11768 unsigned int hflags = HLUA_TXN_FLT_CTX;
11769 int ret = 1;
11770
11771 flt_hlua = flt_ctx->hlua[(dir == SMP_OPT_DIR_REQ ? 0 : 1)];
11772 if (!flt_hlua)
11773 goto end;
11774
11775 if (!HLUA_IS_RUNNING(flt_hlua)) {
11776 int extra_idx = lua_gettop(flt_hlua->T);
11777
11778 /* The following Lua calls can fail. */
11779 if (!SET_SAFE_LJMP(flt_hlua)) {
11780 const char *error;
11781
11782 if (lua_type(flt_hlua->T, -1) == LUA_TSTRING)
11783 error = lua_tostring(flt_hlua->T, -1);
11784 else
11785 error = "critical error";
11786 SEND_ERR(s->be, "Lua filter '%s': %s.\n", conf->reg->name, error);
11787 goto end;
11788 }
11789
11790 /* Check stack size. */
11791 if (!lua_checkstack(flt_hlua->T, 3)) {
11792 SEND_ERR(s->be, "Lua filter '%s': full stack.\n", conf->reg->name);
11793 RESET_SAFE_LJMP(flt_hlua);
11794 goto end;
11795 }
11796
Aurelien DARRAGON4fdf8b52023-03-20 17:22:37 +010011797 hlua_pushref(flt_hlua->T, flt_ctx->ref);
Christopher Fauletc404f112020-02-26 15:03:09 +010011798 if (lua_getfield(flt_hlua->T, -1, fun) != LUA_TFUNCTION) {
11799 RESET_SAFE_LJMP(flt_hlua);
11800 goto end;
11801 }
11802 lua_insert(flt_hlua->T, -2);
11803
11804 if (!hlua_txn_new(flt_hlua->T, s, s->be, dir, hflags)) {
11805 SEND_ERR(s->be, "Lua filter '%s': full stack.\n", conf->reg->name);
11806 RESET_SAFE_LJMP(flt_hlua);
11807 goto end;
11808 }
11809 flt_hlua->nargs = 2;
11810
11811 if (flags & HLUA_FLT_CB_ARG_CHN) {
11812 if (dir == SMP_OPT_DIR_REQ)
11813 lua_getfield(flt_hlua->T, -1, "req");
11814 else
11815 lua_getfield(flt_hlua->T, -1, "res");
11816 if (lua_type(flt_hlua->T, -1) == LUA_TTABLE) {
11817 lua_pushstring(flt_hlua->T, "__filter");
11818 lua_pushlightuserdata(flt_hlua->T, filter);
11819 lua_settable(flt_hlua->T, -3);
11820 }
11821 flt_hlua->nargs++;
11822 }
11823 else if (flags & HLUA_FLT_CB_ARG_HTTP_MSG) {
Christopher Fauleteae8afa2020-02-26 17:15:48 +010011824 if (dir == SMP_OPT_DIR_REQ)
11825 lua_getfield(flt_hlua->T, -1, "http_req");
11826 else
11827 lua_getfield(flt_hlua->T, -1, "http_res");
11828 if (lua_type(flt_hlua->T, -1) == LUA_TTABLE) {
11829 lua_pushstring(flt_hlua->T, "__filter");
11830 lua_pushlightuserdata(flt_hlua->T, filter);
11831 lua_settable(flt_hlua->T, -3);
11832 }
11833 flt_hlua->nargs++;
Christopher Fauletc404f112020-02-26 15:03:09 +010011834 }
11835
11836 /* Check stack size. */
11837 if (!lua_checkstack(flt_hlua->T, 1)) {
11838 SEND_ERR(s->be, "Lua filter '%s': full stack.\n", conf->reg->name);
11839 RESET_SAFE_LJMP(flt_hlua);
11840 goto end;
11841 }
11842
11843 while (extra_idx--) {
11844 lua_pushvalue(flt_hlua->T, 1);
11845 lua_remove(flt_hlua->T, 1);
11846 flt_hlua->nargs++;
11847 }
11848
11849 /* We must initialize the execution timeouts. */
Aurelien DARRAGONda9503c2022-11-25 09:10:07 +010011850 hlua_timer_init(&flt_hlua->timer, hlua_timeout_session);
Christopher Fauletc404f112020-02-26 15:03:09 +010011851
11852 /* At this point the execution is safe. */
11853 RESET_SAFE_LJMP(flt_hlua);
11854 }
11855
11856 switch (hlua_ctx_resume(flt_hlua, !(flags & HLUA_FLT_CB_FINAL))) {
11857 case HLUA_E_OK:
11858 /* Catch the return value if it required */
11859 if ((flags & HLUA_FLT_CB_RETVAL) && lua_gettop(flt_hlua->T) > 0) {
11860 ret = lua_tointeger(flt_hlua->T, -1);
11861 lua_settop(flt_hlua->T, 0); /* Empty the stack. */
11862 }
11863
11864 /* Set timeout in the required channel. */
11865 if (flt_hlua->wake_time != TICK_ETERNITY) {
11866 if (dir == SMP_OPT_DIR_REQ)
11867 s->req.analyse_exp = flt_hlua->wake_time;
11868 else
11869 s->res.analyse_exp = flt_hlua->wake_time;
11870 }
11871 break;
11872 case HLUA_E_AGAIN:
11873 /* Set timeout in the required channel. */
11874 if (flt_hlua->wake_time != TICK_ETERNITY) {
11875 if (dir == SMP_OPT_DIR_REQ)
11876 s->req.analyse_exp = flt_hlua->wake_time;
11877 else
11878 s->res.analyse_exp = flt_hlua->wake_time;
11879 }
11880 /* Some actions can be wake up when a "write" event
11881 * is detected on a response channel. This is useful
11882 * only for actions targeted on the requests.
11883 */
11884 if (HLUA_IS_WAKERESWR(flt_hlua))
11885 s->res.flags |= CF_WAKE_WRITE;
11886 if (HLUA_IS_WAKEREQWR(flt_hlua))
11887 s->req.flags |= CF_WAKE_WRITE;
11888 ret = 0;
11889 goto end;
11890 case HLUA_E_ERRMSG:
11891 SEND_ERR(s->be, "Lua filter '%s' : %s.\n", conf->reg->name, lua_tostring(flt_hlua->T, -1));
11892 ret = -1;
11893 goto end;
11894 case HLUA_E_ETMOUT:
11895 SEND_ERR(s->be, "Lua filter '%s' : '%s' callback execution timeout.\n", conf->reg->name, fun);
11896 goto end;
11897 case HLUA_E_NOMEM:
11898 SEND_ERR(s->be, "Lua filter '%s' : out of memory error.\n", conf->reg->name);
11899 goto end;
11900 case HLUA_E_YIELD:
11901 SEND_ERR(s->be, "Lua filter '%s': yield functions like core.tcp() or core.sleep()"
11902 " are not allowed from '%s' callback.\n", conf->reg->name, fun);
11903 goto end;
11904 case HLUA_E_ERR:
11905 SEND_ERR(s->be, "Lua filter '%s': '%s' returns an unknown error.\n", conf->reg->name, fun);
11906 goto end;
11907 default:
11908 goto end;
11909 }
11910
11911
11912 end:
11913 return ret;
11914}
11915
11916static int hlua_filter_start_analyze(struct stream *s, struct filter *filter, struct channel *chn)
11917{
11918 struct hlua_flt_ctx *flt_ctx = filter->ctx;
11919
11920 flt_ctx->flags = 0;
11921 return hlua_filter_callback(s, filter, "start_analyze",
11922 (!(chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES),
11923 (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_RETVAL | HLUA_FLT_CB_ARG_CHN));
11924}
11925
11926static int hlua_filter_end_analyze(struct stream *s, struct filter *filter, struct channel *chn)
11927{
11928 struct hlua_flt_ctx *flt_ctx = filter->ctx;
11929
11930 flt_ctx->flags &= ~HLUA_FLT_CTX_FL_PAYLOAD;
11931 return hlua_filter_callback(s, filter, "end_analyze",
11932 (!(chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES),
11933 (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_RETVAL | HLUA_FLT_CB_ARG_CHN));
11934}
11935
Christopher Fauleteae8afa2020-02-26 17:15:48 +010011936static int hlua_filter_http_headers(struct stream *s, struct filter *filter, struct http_msg *msg)
11937{
11938 struct hlua_flt_ctx *flt_ctx = filter->ctx;
11939
11940 flt_ctx->flags &= ~HLUA_FLT_CTX_FL_PAYLOAD;
11941 return hlua_filter_callback(s, filter, "http_headers",
11942 (!(msg->chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES),
11943 (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_RETVAL | HLUA_FLT_CB_ARG_HTTP_MSG));
11944}
11945
11946static int hlua_filter_http_payload(struct stream *s, struct filter *filter, struct http_msg *msg,
11947 unsigned int offset, unsigned int len)
11948{
11949 struct hlua_flt_ctx *flt_ctx = filter->ctx;
11950 struct hlua *flt_hlua;
11951 int dir = (!(msg->chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES);
11952 int idx = (dir == SMP_OPT_DIR_REQ ? 0 : 1);
11953 int ret;
11954
11955 flt_hlua = flt_ctx->hlua[idx];
11956 flt_ctx->cur_off[idx] = offset;
11957 flt_ctx->cur_len[idx] = len;
11958 flt_ctx->flags |= HLUA_FLT_CTX_FL_PAYLOAD;
11959 ret = hlua_filter_callback(s, filter, "http_payload", dir, (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_ARG_HTTP_MSG));
11960 if (ret != -1) {
11961 ret = flt_ctx->cur_len[idx];
11962 if (lua_gettop(flt_hlua->T) > 0) {
11963 ret = lua_tointeger(flt_hlua->T, -1);
11964 if (ret > flt_ctx->cur_len[idx])
11965 ret = flt_ctx->cur_len[idx];
11966 lua_settop(flt_hlua->T, 0); /* Empty the stack. */
11967 }
11968 }
11969 return ret;
11970}
11971
11972static int hlua_filter_http_end(struct stream *s, struct filter *filter, struct http_msg *msg)
11973{
11974 struct hlua_flt_ctx *flt_ctx = filter->ctx;
11975
11976 flt_ctx->flags &= ~HLUA_FLT_CTX_FL_PAYLOAD;
11977 return hlua_filter_callback(s, filter, "http_end",
11978 (!(msg->chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES),
11979 (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_RETVAL | HLUA_FLT_CB_ARG_HTTP_MSG));
11980}
11981
Christopher Fauletc404f112020-02-26 15:03:09 +010011982static int hlua_filter_tcp_payload(struct stream *s, struct filter *filter, struct channel *chn,
11983 unsigned int offset, unsigned int len)
11984{
11985 struct hlua_flt_ctx *flt_ctx = filter->ctx;
11986 struct hlua *flt_hlua;
11987 int dir = (!(chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES);
11988 int idx = (dir == SMP_OPT_DIR_REQ ? 0 : 1);
11989 int ret;
11990
11991 flt_hlua = flt_ctx->hlua[idx];
11992 flt_ctx->cur_off[idx] = offset;
11993 flt_ctx->cur_len[idx] = len;
11994 flt_ctx->flags |= HLUA_FLT_CTX_FL_PAYLOAD;
11995 ret = hlua_filter_callback(s, filter, "tcp_payload", dir, (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_ARG_CHN));
11996 if (ret != -1) {
11997 ret = flt_ctx->cur_len[idx];
11998 if (lua_gettop(flt_hlua->T) > 0) {
11999 ret = lua_tointeger(flt_hlua->T, -1);
12000 if (ret > flt_ctx->cur_len[idx])
12001 ret = flt_ctx->cur_len[idx];
12002 lua_settop(flt_hlua->T, 0); /* Empty the stack. */
12003 }
12004 }
12005 return ret;
12006}
12007
Christopher Faulet69c581a2021-05-31 08:54:04 +020012008static int hlua_filter_parse_fct(char **args, int *cur_arg, struct proxy *px,
12009 struct flt_conf *fconf, char **err, void *private)
12010{
12011 struct hlua_reg_filter *reg_flt = private;
12012 lua_State *L;
12013 struct hlua_flt_config *conf = NULL;
12014 const char *flt_id = NULL;
12015 int state_id, pos, flt_flags = 0;
12016 struct flt_ops *hlua_flt_ops = NULL;
12017
12018 state_id = reg_flt_to_stack_id(reg_flt);
12019 L = hlua_states[state_id];
12020
12021 /* Initialize the filter ops with default callbacks */
12022 hlua_flt_ops = calloc(1, sizeof(*hlua_flt_ops));
Christopher Fauletc86bb872021-08-13 08:33:57 +020012023 if (!hlua_flt_ops)
12024 goto error;
Christopher Faulet69c581a2021-05-31 08:54:04 +020012025 hlua_flt_ops->init = hlua_filter_init;
12026 hlua_flt_ops->deinit = hlua_filter_deinit;
12027 if (state_id) {
12028 /* Set per-thread callback if script is loaded per-thread */
12029 hlua_flt_ops->init_per_thread = hlua_filter_init_per_thread;
12030 hlua_flt_ops->deinit_per_thread = hlua_filter_deinit_per_thread;
12031 }
12032 hlua_flt_ops->attach = hlua_filter_new;
12033 hlua_flt_ops->detach = hlua_filter_delete;
12034
12035 /* Push the filter class on the stack and resolve all callbacks */
Aurelien DARRAGON4fdf8b52023-03-20 17:22:37 +010012036 hlua_pushref(L, reg_flt->flt_ref[state_id]);
Christopher Faulet69c581a2021-05-31 08:54:04 +020012037
Christopher Fauletc404f112020-02-26 15:03:09 +010012038 if (lua_getfield(L, -1, "start_analyze") == LUA_TFUNCTION)
12039 hlua_flt_ops->channel_start_analyze = hlua_filter_start_analyze;
12040 lua_pop(L, 1);
12041 if (lua_getfield(L, -1, "end_analyze") == LUA_TFUNCTION)
12042 hlua_flt_ops->channel_end_analyze = hlua_filter_end_analyze;
12043 lua_pop(L, 1);
Christopher Fauleteae8afa2020-02-26 17:15:48 +010012044 if (lua_getfield(L, -1, "http_headers") == LUA_TFUNCTION)
12045 hlua_flt_ops->http_headers = hlua_filter_http_headers;
12046 lua_pop(L, 1);
12047 if (lua_getfield(L, -1, "http_payload") == LUA_TFUNCTION)
12048 hlua_flt_ops->http_payload = hlua_filter_http_payload;
12049 lua_pop(L, 1);
12050 if (lua_getfield(L, -1, "http_end") == LUA_TFUNCTION)
12051 hlua_flt_ops->http_end = hlua_filter_http_end;
12052 lua_pop(L, 1);
Christopher Fauletc404f112020-02-26 15:03:09 +010012053 if (lua_getfield(L, -1, "tcp_payload") == LUA_TFUNCTION)
12054 hlua_flt_ops->tcp_payload = hlua_filter_tcp_payload;
12055 lua_pop(L, 1);
Christopher Faulet69c581a2021-05-31 08:54:04 +020012056
12057 /* Get id and flags of the filter class */
12058 if (lua_getfield(L, -1, "id") == LUA_TSTRING)
12059 flt_id = lua_tostring(L, -1);
12060 lua_pop(L, 1);
12061 if (lua_getfield(L, -1, "flags") == LUA_TNUMBER)
12062 flt_flags = lua_tointeger(L, -1);
12063 lua_pop(L, 1);
12064
12065 /* Create the filter config */
12066 conf = calloc(1, sizeof(*conf));
Christopher Fauletc86bb872021-08-13 08:33:57 +020012067 if (!conf)
Christopher Faulet69c581a2021-05-31 08:54:04 +020012068 goto error;
Christopher Faulet69c581a2021-05-31 08:54:04 +020012069 conf->reg = reg_flt;
12070
12071 /* duplicate args */
12072 for (pos = 0; *args[*cur_arg + 1 + pos]; pos++);
12073 conf->args = calloc(pos + 1, sizeof(*conf->args));
Christopher Fauletc86bb872021-08-13 08:33:57 +020012074 if (!conf->args)
12075 goto error;
12076 for (pos = 0; *args[*cur_arg + 1 + pos]; pos++) {
Christopher Faulet69c581a2021-05-31 08:54:04 +020012077 conf->args[pos] = strdup(args[*cur_arg + 1 + pos]);
Christopher Fauletc86bb872021-08-13 08:33:57 +020012078 if (!conf->args[pos])
12079 goto error;
12080 }
Christopher Faulet69c581a2021-05-31 08:54:04 +020012081 conf->args[pos] = NULL;
12082 *cur_arg += pos + 1;
12083
Christopher Fauletc86bb872021-08-13 08:33:57 +020012084 if (flt_id) {
12085 fconf->id = strdup(flt_id);
12086 if (!fconf->id)
12087 goto error;
12088 }
Christopher Faulet69c581a2021-05-31 08:54:04 +020012089 fconf->flags = flt_flags;
12090 fconf->conf = conf;
12091 fconf->ops = hlua_flt_ops;
12092
12093 lua_settop(L, 0);
12094 return 0;
12095
12096 error:
Christopher Fauletc86bb872021-08-13 08:33:57 +020012097 memprintf(err, "Lua filter '%s' : Lua out of memory error", reg_flt->name);
Christopher Faulet69c581a2021-05-31 08:54:04 +020012098 free(hlua_flt_ops);
Christopher Fauletc86bb872021-08-13 08:33:57 +020012099 if (conf && conf->args) {
12100 for (pos = 0; conf->args[pos]; pos++)
12101 free(conf->args[pos]);
12102 free(conf->args);
12103 }
Christopher Faulet69c581a2021-05-31 08:54:04 +020012104 free(conf);
Christopher Fauletc86bb872021-08-13 08:33:57 +020012105 free((char *)fconf->id);
Christopher Faulet69c581a2021-05-31 08:54:04 +020012106 lua_settop(L, 0);
12107 return -1;
12108}
12109
Christopher Fauletc404f112020-02-26 15:03:09 +010012110__LJMP static int hlua_register_data_filter(lua_State *L)
12111{
12112 struct filter *filter;
12113 struct channel *chn;
12114
12115 MAY_LJMP(check_args(L, 2, "register_data_filter"));
12116 MAY_LJMP(luaL_checktype(L, 1, LUA_TTABLE));
12117 chn = MAY_LJMP(hlua_checkchannel(L, 2));
12118
12119 lua_getfield(L, 1, "__filter");
12120 MAY_LJMP(luaL_checktype(L, -1, LUA_TLIGHTUSERDATA));
12121 filter = lua_touserdata (L, -1);
12122 lua_pop(L, 1);
12123
12124 register_data_filter(chn_strm(chn), chn, filter);
12125 return 1;
12126}
12127
12128__LJMP static int hlua_unregister_data_filter(lua_State *L)
12129{
12130 struct filter *filter;
12131 struct channel *chn;
12132
12133 MAY_LJMP(check_args(L, 2, "unregister_data_filter"));
12134 MAY_LJMP(luaL_checktype(L, 1, LUA_TTABLE));
12135 chn = MAY_LJMP(hlua_checkchannel(L, 2));
12136
12137 lua_getfield(L, 1, "__filter");
12138 MAY_LJMP(luaL_checktype(L, -1, LUA_TLIGHTUSERDATA));
12139 filter = lua_touserdata (L, -1);
12140 lua_pop(L, 1);
12141
12142 unregister_data_filter(chn_strm(chn), chn, filter);
12143 return 1;
12144}
12145
Christopher Faulet69c581a2021-05-31 08:54:04 +020012146/* This function is an LUA binding used for registering a filter. It expects a
Ilya Shipitsinff0f2782021-08-22 22:18:07 +050012147 * filter name used in the haproxy configuration file and a LUA function to
Christopher Faulet69c581a2021-05-31 08:54:04 +020012148 * parse configuration arguments.
12149 */
12150__LJMP static int hlua_register_filter(lua_State *L)
12151{
12152 struct buffer *trash;
12153 struct flt_kw_list *fkl;
12154 struct flt_kw *fkw;
12155 const char *name;
12156 struct hlua_reg_filter *reg_flt= NULL;
12157 int flt_ref, fun_ref;
12158 int len;
12159
12160 MAY_LJMP(check_args(L, 3, "register_filter"));
12161
Aurelien DARRAGON87f52972023-02-24 09:43:54 +010012162 if (hlua_gethlua(L)) {
12163 /* runtime processing */
12164 WILL_LJMP(luaL_error(L, "register_filter: not available outside of body context"));
12165 }
12166
Christopher Faulet69c581a2021-05-31 08:54:04 +020012167 /* First argument : filter name. */
12168 name = MAY_LJMP(luaL_checkstring(L, 1));
12169
12170 /* Second argument : The filter class */
12171 flt_ref = MAY_LJMP(hlua_checktable(L, 2));
12172
12173 /* Third argument : lua function. */
12174 fun_ref = MAY_LJMP(hlua_checkfunction(L, 3));
12175
12176 trash = get_trash_chunk();
12177 chunk_printf(trash, "lua.%s", name);
12178 fkw = flt_find_kw(trash->area);
12179 if (fkw != NULL) {
12180 reg_flt = fkw->private;
12181 if (reg_flt->flt_ref[hlua_state_id] != -1 || reg_flt->fun_ref[hlua_state_id] != -1) {
12182 ha_warning("Trying to register filter 'lua.%s' more than once. "
12183 "This will become a hard error in version 2.5.\n", name);
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +010012184 if (reg_flt->flt_ref[hlua_state_id] != -1)
12185 hlua_unref(L, reg_flt->flt_ref[hlua_state_id]);
12186 if (reg_flt->fun_ref[hlua_state_id] != -1)
12187 hlua_unref(L, reg_flt->fun_ref[hlua_state_id]);
Christopher Faulet69c581a2021-05-31 08:54:04 +020012188 }
12189 reg_flt->flt_ref[hlua_state_id] = flt_ref;
12190 reg_flt->fun_ref[hlua_state_id] = fun_ref;
12191 return 0;
12192 }
12193
12194 fkl = calloc(1, sizeof(*fkl) + sizeof(struct flt_kw) * 2);
12195 if (!fkl)
12196 goto alloc_error;
12197 fkl->scope = "HLUA";
12198
12199 reg_flt = new_hlua_reg_filter(name);
12200 if (!reg_flt)
12201 goto alloc_error;
12202
12203 reg_flt->flt_ref[hlua_state_id] = flt_ref;
12204 reg_flt->fun_ref[hlua_state_id] = fun_ref;
12205
12206 /* The filter keyword */
12207 len = strlen("lua.") + strlen(name) + 1;
12208 fkl->kw[0].kw = calloc(1, len);
12209 if (!fkl->kw[0].kw)
12210 goto alloc_error;
12211
12212 snprintf((char *)fkl->kw[0].kw, len, "lua.%s", name);
12213
12214 fkl->kw[0].parse = hlua_filter_parse_fct;
12215 fkl->kw[0].private = reg_flt;
12216 memset(&fkl->kw[1], 0, sizeof(*fkl->kw));
12217
12218 /* Register this new filter */
12219 flt_register_keywords(fkl);
12220
12221 return 0;
12222
12223 alloc_error:
12224 release_hlua_reg_filter(reg_flt);
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +010012225 hlua_unref(L, flt_ref);
12226 hlua_unref(L, fun_ref);
Christopher Faulet69c581a2021-05-31 08:54:04 +020012227 ha_free(&fkl);
12228 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
12229 return 0; /* Never reached */
12230}
12231
Thierry FOURNIERbd413492015-03-03 16:52:26 +010012232static int hlua_read_timeout(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010012233 const struct proxy *defpx, const char *file, int line,
Thierry FOURNIERbd413492015-03-03 16:52:26 +010012234 char **err, unsigned int *timeout)
12235{
12236 const char *error;
12237
12238 error = parse_time_err(args[1], timeout, TIME_UNIT_MS);
Willy Tarreau9faebe32019-06-07 19:00:37 +020012239 if (error == PARSE_TIME_OVER) {
12240 memprintf(err, "timer overflow in argument <%s> to <%s> (maximum value is 2147483647 ms or ~24.8 days)",
12241 args[1], args[0]);
12242 return -1;
12243 }
12244 else if (error == PARSE_TIME_UNDER) {
12245 memprintf(err, "timer underflow in argument <%s> to <%s> (minimum non-null value is 1 ms)",
12246 args[1], args[0]);
12247 return -1;
12248 }
12249 else if (error) {
Thierry FOURNIERbd413492015-03-03 16:52:26 +010012250 memprintf(err, "%s: invalid timeout", args[0]);
12251 return -1;
12252 }
12253 return 0;
12254}
12255
Aurelien DARRAGON58e36e52023-04-06 22:51:56 +020012256static int hlua_burst_timeout(char **args, int section_type, struct proxy *curpx,
12257 const struct proxy *defpx, const char *file, int line,
12258 char **err)
12259{
12260 return hlua_read_timeout(args, section_type, curpx, defpx,
12261 file, line, err, &hlua_timeout_burst);
12262}
12263
Thierry FOURNIERbd413492015-03-03 16:52:26 +010012264static int hlua_session_timeout(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010012265 const struct proxy *defpx, const char *file, int line,
Thierry FOURNIERbd413492015-03-03 16:52:26 +010012266 char **err)
12267{
12268 return hlua_read_timeout(args, section_type, curpx, defpx,
12269 file, line, err, &hlua_timeout_session);
12270}
12271
12272static int hlua_task_timeout(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010012273 const struct proxy *defpx, const char *file, int line,
Thierry FOURNIERbd413492015-03-03 16:52:26 +010012274 char **err)
12275{
12276 return hlua_read_timeout(args, section_type, curpx, defpx,
12277 file, line, err, &hlua_timeout_task);
12278}
12279
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020012280static int hlua_applet_timeout(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010012281 const struct proxy *defpx, const char *file, int line,
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020012282 char **err)
12283{
12284 return hlua_read_timeout(args, section_type, curpx, defpx,
12285 file, line, err, &hlua_timeout_applet);
12286}
12287
Thierry FOURNIERee9f8022015-03-03 17:37:37 +010012288static int hlua_forced_yield(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010012289 const struct proxy *defpx, const char *file, int line,
Thierry FOURNIERee9f8022015-03-03 17:37:37 +010012290 char **err)
12291{
12292 char *error;
12293
12294 hlua_nb_instruction = strtoll(args[1], &error, 10);
12295 if (*error != '\0') {
12296 memprintf(err, "%s: invalid number", args[0]);
12297 return -1;
12298 }
12299 return 0;
12300}
12301
Willy Tarreau32f61e22015-03-18 17:54:59 +010012302static int hlua_parse_maxmem(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010012303 const struct proxy *defpx, const char *file, int line,
Willy Tarreau32f61e22015-03-18 17:54:59 +010012304 char **err)
12305{
12306 char *error;
12307
12308 if (*(args[1]) == 0) {
Thierry Fournier70e38e92022-09-19 09:01:53 +020012309 memprintf(err, "'%s' expects an integer argument (Lua memory size in MB).", args[0]);
Willy Tarreau32f61e22015-03-18 17:54:59 +010012310 return -1;
12311 }
12312 hlua_global_allocator.limit = strtoll(args[1], &error, 10) * 1024L * 1024L;
12313 if (*error != '\0') {
12314 memprintf(err, "%s: invalid number %s (error at '%c')", args[0], args[1], *error);
12315 return -1;
12316 }
12317 return 0;
12318}
12319
12320
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010012321/* This function is called by the main configuration key "lua-load". It loads and
12322 * execute an lua file during the parsing of the HAProxy configuration file. It is
12323 * the main lua entry point.
12324 *
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -080012325 * This function runs with the HAProxy keywords API. It returns -1 if an error
12326 * occurs, otherwise it returns 0.
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010012327 *
12328 * In some error case, LUA set an error message in top of the stack. This function
12329 * returns this error message in the HAProxy logs and pop it from the stack.
Thierry FOURNIERbabae282015-09-17 11:36:37 +020012330 *
12331 * This function can fail with an abort() due to an Lua critical error.
12332 * We are in the configuration parsing process of HAProxy, this abort() is
12333 * tolerated.
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010012334 */
Thierry Fournierae6b5682022-09-19 09:04:16 +020012335static int hlua_load_state(char **args, lua_State *L, char **err)
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010012336{
12337 int error;
Thierry Fournierae6b5682022-09-19 09:04:16 +020012338 int nargs;
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010012339
12340 /* Just load and compile the file. */
Thierry Fournierae6b5682022-09-19 09:04:16 +020012341 error = luaL_loadfile(L, args[0]);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010012342 if (error) {
Thierry Fournierae6b5682022-09-19 09:04:16 +020012343 memprintf(err, "error in Lua file '%s': %s", args[0], lua_tostring(L, -1));
Thierry Fournierc93c15c2020-11-28 15:02:13 +010012344 lua_pop(L, 1);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010012345 return -1;
12346 }
Thierry Fournierae6b5682022-09-19 09:04:16 +020012347
12348 /* Push args in the Lua stack, except the first one which is the filename */
12349 for (nargs = 1; *(args[nargs]) != 0; nargs++) {
Aurelien DARRAGON4d7aefe2022-09-23 10:22:14 +020012350 /* Check stack size. */
12351 if (!lua_checkstack(L, 1)) {
12352 memprintf(err, "Lua runtime error while loading arguments: stack is full.");
12353 return -1;
12354 }
Thierry Fournierae6b5682022-09-19 09:04:16 +020012355 lua_pushstring(L, args[nargs]);
12356 }
12357 nargs--;
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010012358
12359 /* If no syntax error where detected, execute the code. */
Thierry Fournierae6b5682022-09-19 09:04:16 +020012360 error = lua_pcall(L, nargs, LUA_MULTRET, 0);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010012361 switch (error) {
12362 case LUA_OK:
12363 break;
12364 case LUA_ERRRUN:
Thierry Fournier70e38e92022-09-19 09:01:53 +020012365 memprintf(err, "Lua runtime error: %s", lua_tostring(L, -1));
Thierry Fournierc93c15c2020-11-28 15:02:13 +010012366 lua_pop(L, 1);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010012367 return -1;
12368 case LUA_ERRMEM:
Thierry Fournier70e38e92022-09-19 09:01:53 +020012369 memprintf(err, "Lua out of memory error");
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010012370 return -1;
12371 case LUA_ERRERR:
Thierry Fournier70e38e92022-09-19 09:01:53 +020012372 memprintf(err, "Lua message handler error: %s", lua_tostring(L, -1));
Thierry Fournierc93c15c2020-11-28 15:02:13 +010012373 lua_pop(L, 1);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010012374 return -1;
Christopher Faulet08ed98f2020-07-28 10:33:25 +020012375#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM <= 503
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010012376 case LUA_ERRGCMM:
Thierry Fournier70e38e92022-09-19 09:01:53 +020012377 memprintf(err, "Lua garbage collector error: %s", lua_tostring(L, -1));
Thierry Fournierc93c15c2020-11-28 15:02:13 +010012378 lua_pop(L, 1);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010012379 return -1;
Christopher Faulet08ed98f2020-07-28 10:33:25 +020012380#endif
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010012381 default:
Thierry Fournier70e38e92022-09-19 09:01:53 +020012382 memprintf(err, "Lua unknown error: %s", lua_tostring(L, -1));
Thierry Fournierc93c15c2020-11-28 15:02:13 +010012383 lua_pop(L, 1);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010012384 return -1;
12385 }
12386
12387 return 0;
12388}
12389
Thierry Fournierc93c15c2020-11-28 15:02:13 +010012390static int hlua_load(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010012391 const struct proxy *defpx, const char *file, int line,
Thierry Fournierc93c15c2020-11-28 15:02:13 +010012392 char **err)
12393{
12394 if (*(args[1]) == 0) {
Thierry Fournier70e38e92022-09-19 09:01:53 +020012395 memprintf(err, "'%s' expects a file name as parameter.", args[0]);
Thierry Fournierc93c15c2020-11-28 15:02:13 +010012396 return -1;
12397 }
12398
Thierry Fournier59f11be2020-11-29 00:37:41 +010012399 /* loading for global state */
Thierry Fournierc7492592020-11-28 23:57:24 +010012400 hlua_state_id = 0;
Willy Tarreau43ab05b2021-09-28 09:43:11 +020012401 ha_set_thread(NULL);
Thierry Fournierae6b5682022-09-19 09:04:16 +020012402 return hlua_load_state(&args[1], hlua_states[0], err);
Thierry Fournierc93c15c2020-11-28 15:02:13 +010012403}
12404
Thierry Fournier59f11be2020-11-29 00:37:41 +010012405static int hlua_load_per_thread(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010012406 const struct proxy *defpx, const char *file, int line,
Thierry Fournier59f11be2020-11-29 00:37:41 +010012407 char **err)
12408{
12409 int len;
Thierry Fournierae6b5682022-09-19 09:04:16 +020012410 int i;
Thierry Fournier59f11be2020-11-29 00:37:41 +010012411
12412 if (*(args[1]) == 0) {
Thierry Fournier70e38e92022-09-19 09:01:53 +020012413 memprintf(err, "'%s' expects a file as parameter.", args[0]);
Thierry Fournier59f11be2020-11-29 00:37:41 +010012414 return -1;
12415 }
12416
12417 if (per_thread_load == NULL) {
12418 /* allocate the first entry large enough to store the final NULL */
12419 per_thread_load = calloc(1, sizeof(*per_thread_load));
12420 if (per_thread_load == NULL) {
12421 memprintf(err, "out of memory error");
12422 return -1;
12423 }
12424 }
12425
12426 /* count used entries */
12427 for (len = 0; per_thread_load[len] != NULL; len++)
12428 ;
12429
12430 per_thread_load = realloc(per_thread_load, (len + 2) * sizeof(*per_thread_load));
12431 if (per_thread_load == NULL) {
12432 memprintf(err, "out of memory error");
12433 return -1;
12434 }
Thierry Fournier59f11be2020-11-29 00:37:41 +010012435 per_thread_load[len + 1] = NULL;
12436
Thierry Fournierae6b5682022-09-19 09:04:16 +020012437 /* count args excepting the first, allocate array and copy args */
12438 for (i = 0; *(args[i + 1]) != 0; i++);
Aurelien DARRAGONb12d1692022-09-23 08:48:34 +020012439 per_thread_load[len] = calloc(i + 1, sizeof(*per_thread_load[len]));
Thierry Fournier59f11be2020-11-29 00:37:41 +010012440 if (per_thread_load[len] == NULL) {
12441 memprintf(err, "out of memory error");
12442 return -1;
12443 }
Thierry Fournierae6b5682022-09-19 09:04:16 +020012444 for (i = 1; *(args[i]) != 0; i++) {
12445 per_thread_load[len][i - 1] = strdup(args[i]);
12446 if (per_thread_load[len][i - 1] == NULL) {
12447 memprintf(err, "out of memory error");
12448 return -1;
12449 }
12450 }
12451 per_thread_load[len][i - 1] = strdup("");
12452 if (per_thread_load[len][i - 1] == NULL) {
12453 memprintf(err, "out of memory error");
12454 return -1;
12455 }
Thierry Fournier59f11be2020-11-29 00:37:41 +010012456
12457 /* loading for thread 1 only */
12458 hlua_state_id = 1;
Willy Tarreau43ab05b2021-09-28 09:43:11 +020012459 ha_set_thread(NULL);
Thierry Fournierae6b5682022-09-19 09:04:16 +020012460 return hlua_load_state(per_thread_load[len], hlua_states[1], err);
Thierry Fournier59f11be2020-11-29 00:37:41 +010012461}
12462
Tim Duesterhusc9fc9f22020-01-12 13:55:39 +010012463/* Prepend the given <path> followed by a semicolon to the `package.<type>` variable
12464 * in the given <ctx>.
12465 */
Thierry Fournier3fb9e512020-11-28 10:13:12 +010012466static int hlua_prepend_path(lua_State *L, char *type, char *path)
Tim Duesterhusc9fc9f22020-01-12 13:55:39 +010012467{
Thierry Fournier3fb9e512020-11-28 10:13:12 +010012468 lua_getglobal(L, "package"); /* push package variable */
12469 lua_pushstring(L, path); /* push given path */
12470 lua_pushstring(L, ";"); /* push semicolon */
12471 lua_getfield(L, -3, type); /* push old path */
12472 lua_concat(L, 3); /* concatenate to new path */
12473 lua_setfield(L, -2, type); /* store new path */
12474 lua_pop(L, 1); /* pop package variable */
Tim Duesterhusc9fc9f22020-01-12 13:55:39 +010012475
12476 return 0;
12477}
12478
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010012479static int hlua_config_prepend_path(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010012480 const struct proxy *defpx, const char *file, int line,
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010012481 char **err)
12482{
12483 char *path;
12484 char *type = "path";
Tim Duesterhus621e74a2021-01-03 20:04:36 +010012485 struct prepend_path *p = NULL;
Bertrand Jacquin7fbc7702021-11-24 21:16:06 +000012486 size_t i;
Thierry Fournier59f11be2020-11-29 00:37:41 +010012487
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010012488 if (too_many_args(2, args, err, NULL)) {
Tim Duesterhus621e74a2021-01-03 20:04:36 +010012489 goto err;
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010012490 }
12491
12492 if (!(*args[1])) {
12493 memprintf(err, "'%s' expects to receive a <path> as argument", args[0]);
Tim Duesterhus621e74a2021-01-03 20:04:36 +010012494 goto err;
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010012495 }
12496 path = args[1];
12497
12498 if (*args[2]) {
12499 if (strcmp(args[2], "path") != 0 && strcmp(args[2], "cpath") != 0) {
12500 memprintf(err, "'%s' expects <type> to either be 'path' or 'cpath'", args[0]);
Tim Duesterhus621e74a2021-01-03 20:04:36 +010012501 goto err;
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010012502 }
12503 type = args[2];
12504 }
12505
Thierry Fournier59f11be2020-11-29 00:37:41 +010012506 p = calloc(1, sizeof(*p));
12507 if (p == NULL) {
Tim Duesterhusf89d43a2021-01-03 20:04:37 +010012508 memprintf(err, "memory allocation failed");
Tim Duesterhus621e74a2021-01-03 20:04:36 +010012509 goto err;
Thierry Fournier59f11be2020-11-29 00:37:41 +010012510 }
12511 p->path = strdup(path);
12512 if (p->path == NULL) {
Tim Duesterhusf89d43a2021-01-03 20:04:37 +010012513 memprintf(err, "memory allocation failed");
Tim Duesterhus621e74a2021-01-03 20:04:36 +010012514 goto err2;
Thierry Fournier59f11be2020-11-29 00:37:41 +010012515 }
12516 p->type = strdup(type);
12517 if (p->type == NULL) {
Tim Duesterhusf89d43a2021-01-03 20:04:37 +010012518 memprintf(err, "memory allocation failed");
Tim Duesterhus621e74a2021-01-03 20:04:36 +010012519 goto err2;
Thierry Fournier59f11be2020-11-29 00:37:41 +010012520 }
Willy Tarreau2b718102021-04-21 07:32:39 +020012521 LIST_APPEND(&prepend_path_list, &p->l);
Thierry Fournier59f11be2020-11-29 00:37:41 +010012522
Tim Duesterhus9e5e5862021-10-11 18:51:08 +020012523 /* Handle the global state and the per-thread state for the first
12524 * thread. The remaining threads will be initialized based on
12525 * prepend_path_list.
12526 */
Bertrand Jacquin7fbc7702021-11-24 21:16:06 +000012527 for (i = 0; i < 2; i++) {
Tim Duesterhus9e5e5862021-10-11 18:51:08 +020012528 lua_State *L = hlua_states[i];
12529 const char *error;
12530
12531 if (setjmp(safe_ljmp_env) != 0) {
12532 lua_atpanic(L, hlua_panic_safe);
12533 if (lua_type(L, -1) == LUA_TSTRING)
12534 error = lua_tostring(L, -1);
12535 else
12536 error = "critical error";
12537 fprintf(stderr, "lua-prepend-path: %s.\n", error);
12538 exit(1);
12539 } else {
12540 lua_atpanic(L, hlua_panic_ljmp);
12541 }
12542
12543 hlua_prepend_path(L, type, path);
12544
12545 lua_atpanic(L, hlua_panic_safe);
12546 }
12547
Thierry Fournier59f11be2020-11-29 00:37:41 +010012548 return 0;
Tim Duesterhus621e74a2021-01-03 20:04:36 +010012549
12550err2:
12551 free(p->type);
12552 free(p->path);
12553err:
12554 free(p);
12555 return -1;
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010012556}
12557
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010012558/* configuration keywords declaration */
12559static struct cfg_kw_list cfg_kws = {{ },{
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010012560 { CFG_GLOBAL, "lua-prepend-path", hlua_config_prepend_path },
Thierry FOURNIERbd413492015-03-03 16:52:26 +010012561 { CFG_GLOBAL, "lua-load", hlua_load },
Thierry Fournier59f11be2020-11-29 00:37:41 +010012562 { CFG_GLOBAL, "lua-load-per-thread", hlua_load_per_thread },
Thierry FOURNIERbd413492015-03-03 16:52:26 +010012563 { CFG_GLOBAL, "tune.lua.session-timeout", hlua_session_timeout },
12564 { CFG_GLOBAL, "tune.lua.task-timeout", hlua_task_timeout },
Thierry FOURNIER56da1012015-10-01 08:42:31 +020012565 { CFG_GLOBAL, "tune.lua.service-timeout", hlua_applet_timeout },
Aurelien DARRAGON58e36e52023-04-06 22:51:56 +020012566 { CFG_GLOBAL, "tune.lua.burst-timeout", hlua_burst_timeout },
Thierry FOURNIERee9f8022015-03-03 17:37:37 +010012567 { CFG_GLOBAL, "tune.lua.forced-yield", hlua_forced_yield },
Willy Tarreau32f61e22015-03-18 17:54:59 +010012568 { CFG_GLOBAL, "tune.lua.maxmem", hlua_parse_maxmem },
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010012569 { 0, NULL, NULL },
12570}};
12571
Willy Tarreau0108d902018-11-25 19:14:37 +010012572INITCALL1(STG_REGISTER, cfg_register_keywords, &cfg_kws);
12573
William Lallemand52139182022-03-30 15:05:42 +020012574#ifdef USE_OPENSSL
Christopher Fauletafd8f102018-11-08 11:34:21 +010012575
William Lallemand30fcca12022-03-30 12:03:12 +020012576/*
12577 * This function replace a ckch_store by another one, and rebuild the ckch_inst and all its dependencies.
12578 * It does the sam as "cli_io_handler_commit_cert" but for lua, the major
12579 * difference is that the yield in lua and for the CLI is not handled the same
12580 * way.
12581 */
12582__LJMP static int hlua_ckch_commit_yield(lua_State *L, int status, lua_KContext ctx)
12583{
12584 struct ckch_inst **lua_ckchi = lua_touserdata(L, -1);
12585 struct ckch_store **lua_ckchs = lua_touserdata(L, -2);
12586 struct ckch_inst *ckchi = *lua_ckchi;
12587 struct ckch_store *old_ckchs = lua_ckchs[0];
12588 struct ckch_store *new_ckchs = lua_ckchs[1];
12589 struct hlua *hlua;
12590 char *err = NULL;
12591 int y = 1;
12592
12593 hlua = hlua_gethlua(L);
12594
12595 /* get the first ckchi to copy */
12596 if (ckchi == NULL)
12597 ckchi = LIST_ELEM(old_ckchs->ckch_inst.n, typeof(ckchi), by_ckchs);
12598
12599 /* walk through the old ckch_inst and creates new ckch_inst using the updated ckchs */
12600 list_for_each_entry_from(ckchi, &old_ckchs->ckch_inst, by_ckchs) {
12601 struct ckch_inst *new_inst;
12602
12603 /* it takes a lot of CPU to creates SSL_CTXs, so we yield every 10 CKCH instances */
12604 if (y % 10 == 0) {
12605
12606 *lua_ckchi = ckchi;
12607
12608 task_wakeup(hlua->task, TASK_WOKEN_MSG);
12609 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_ckch_commit_yield, TICK_ETERNITY, 0));
12610 }
12611
12612 if (ckch_inst_rebuild(new_ckchs, ckchi, &new_inst, &err))
12613 goto error;
12614
12615 /* link the new ckch_inst to the duplicate */
12616 LIST_APPEND(&new_ckchs->ckch_inst, &new_inst->by_ckchs);
12617 y++;
12618 }
12619
12620 /* The generation is finished, we can insert everything */
12621 ckch_store_replace(old_ckchs, new_ckchs);
12622
12623 lua_pop(L, 2); /* pop the lua_ckchs and ckchi */
12624
12625 HA_SPIN_UNLOCK(CKCH_LOCK, &ckch_lock);
12626
12627 return 0;
12628
12629error:
12630 ckch_store_free(new_ckchs);
12631 HA_SPIN_UNLOCK(CKCH_LOCK, &ckch_lock);
12632 WILL_LJMP(luaL_error(L, "%s", err));
12633 free(err);
12634
12635 return 0;
12636}
12637
12638/*
12639 * Replace a ckch_store <filename> in the ckchs_tree with a ckch_store created
12640 * from the table in parameter.
12641 *
12642 * This is equivalent to "set ssl cert" + "commit ssl cert" over the CLI, which
12643 * means it does not need to have a transaction since everything is done in the
12644 * same function.
12645 *
12646 * CertCache.set{filename="", crt="", key="", sctl="", ocsp="", issuer=""}
12647 *
12648 */
12649__LJMP static int hlua_ckch_set(lua_State *L)
12650{
12651 struct hlua *hlua;
12652 struct ckch_inst **lua_ckchi;
12653 struct ckch_store **lua_ckchs;
12654 struct ckch_store *old_ckchs = NULL;
12655 struct ckch_store *new_ckchs = NULL;
12656 int errcode = 0;
12657 char *err = NULL;
12658 struct cert_exts *cert_ext = NULL;
12659 char *filename;
William Lallemand52ddd992022-11-22 11:51:53 +010012660 struct ckch_data *data;
William Lallemand30fcca12022-03-30 12:03:12 +020012661 int ret;
12662
12663 if (lua_type(L, -1) != LUA_TTABLE)
12664 WILL_LJMP(luaL_error(L, "'CertCache.set' needs a table as argument"));
12665
12666 hlua = hlua_gethlua(L);
12667
12668 /* FIXME: this should not return an error but should come back later */
12669 if (HA_SPIN_TRYLOCK(CKCH_LOCK, &ckch_lock))
12670 WILL_LJMP(luaL_error(L, "CertCache already under lock"));
12671
12672 ret = lua_getfield(L, -1, "filename");
12673 if (ret != LUA_TSTRING) {
Thierry Fournier70e38e92022-09-19 09:01:53 +020012674 memprintf(&err, "%sNo filename specified!", err ? err : "");
William Lallemand30fcca12022-03-30 12:03:12 +020012675 errcode |= ERR_ALERT | ERR_FATAL;
12676 goto end;
12677 }
12678 filename = (char *)lua_tostring(L, -1);
12679
12680
12681 /* look for the filename in the tree */
12682 old_ckchs = ckchs_lookup(filename);
12683 if (!old_ckchs) {
Thierry Fournier70e38e92022-09-19 09:01:53 +020012684 memprintf(&err, "%sCan't replace a certificate which is not referenced by the configuration!", err ? err : "");
William Lallemand30fcca12022-03-30 12:03:12 +020012685 errcode |= ERR_ALERT | ERR_FATAL;
12686 goto end;
12687 }
12688 /* TODO: handle extra_files_noext */
12689
12690 new_ckchs = ckchs_dup(old_ckchs);
12691 if (!new_ckchs) {
Thierry Fournier70e38e92022-09-19 09:01:53 +020012692 memprintf(&err, "%sCannot allocate memory!", err ? err : "");
William Lallemand30fcca12022-03-30 12:03:12 +020012693 errcode |= ERR_ALERT | ERR_FATAL;
12694 goto end;
12695 }
12696
William Lallemand52ddd992022-11-22 11:51:53 +010012697 data = new_ckchs->data;
William Lallemand30fcca12022-03-30 12:03:12 +020012698
12699 /* loop on the field in the table, which have the same name as the
12700 * possible extensions of files */
12701 lua_pushnil(L);
12702 while (lua_next(L, 1)) {
12703 int i;
12704 const char *field = lua_tostring(L, -2);
12705 char *payload = (char *)lua_tostring(L, -1);
12706
12707 if (!field || strcmp(field, "filename") == 0) {
12708 lua_pop(L, 1);
12709 continue;
12710 }
12711
12712 for (i = 0; field && cert_exts[i].ext != NULL; i++) {
12713 if (strcmp(field, cert_exts[i].ext) == 0) {
12714 cert_ext = &cert_exts[i];
12715 break;
12716 }
12717 }
12718
12719 /* this is the default type, the field is not supported */
12720 if (cert_ext == NULL) {
Thierry Fournier70e38e92022-09-19 09:01:53 +020012721 memprintf(&err, "%sUnsupported field '%s'", err ? err : "", field);
William Lallemand30fcca12022-03-30 12:03:12 +020012722 errcode |= ERR_ALERT | ERR_FATAL;
12723 goto end;
12724 }
12725
12726 /* appply the change on the duplicate */
William Lallemand52ddd992022-11-22 11:51:53 +010012727 if (cert_ext->load(filename, payload, data, &err) != 0) {
Thierry Fournier70e38e92022-09-19 09:01:53 +020012728 memprintf(&err, "%sCan't load the payload for '%s'", err ? err : "", cert_ext->ext);
William Lallemand30fcca12022-03-30 12:03:12 +020012729 errcode |= ERR_ALERT | ERR_FATAL;
12730 goto end;
12731 }
12732 lua_pop(L, 1);
12733 }
12734
12735 /* store the pointers on the lua stack */
12736 lua_ckchs = lua_newuserdata(L, sizeof(struct ckch_store *) * 2);
12737 lua_ckchs[0] = old_ckchs;
12738 lua_ckchs[1] = new_ckchs;
12739 lua_ckchi = lua_newuserdata(L, sizeof(struct ckch_inst *));
12740 *lua_ckchi = NULL;
12741
12742 task_wakeup(hlua->task, TASK_WOKEN_MSG);
12743 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_ckch_commit_yield, TICK_ETERNITY, 0));
12744
12745end:
12746 HA_SPIN_UNLOCK(CKCH_LOCK, &ckch_lock);
12747
12748 if (errcode & ERR_CODE) {
12749 ckch_store_free(new_ckchs);
12750 WILL_LJMP(luaL_error(L, "%s", err));
12751 }
12752 free(err);
12753
12754 return 0;
12755}
12756
William Lallemand52139182022-03-30 15:05:42 +020012757#else
12758
12759__LJMP static int hlua_ckch_set(lua_State *L)
12760{
12761 WILL_LJMP(luaL_error(L, "'CertCache.set' needs an HAProxy built with OpenSSL"));
12762
12763 return 0;
12764}
12765#endif /* ! USE_OPENSSL */
12766
12767
12768
Thierry FOURNIERbabae282015-09-17 11:36:37 +020012769/* This function can fail with an abort() due to an Lua critical error.
12770 * We are in the initialisation process of HAProxy, this abort() is
12771 * tolerated.
12772 */
Thierry Fournierb8cef172020-11-28 15:37:17 +010012773int hlua_post_init_state(lua_State *L)
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010012774{
12775 struct hlua_init_function *init;
12776 const char *msg;
12777 enum hlua_exec ret;
Thierry Fournierfd107a22016-02-19 19:57:23 +010012778 const char *error;
Thierry Fournier670db242020-11-28 10:49:59 +010012779 const char *kind;
12780 const char *trace;
12781 int return_status = 1;
12782#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM >= 504
12783 int nres;
12784#endif
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010012785
Willy Tarreaucdb53462020-12-02 12:12:00 +010012786 /* disable memory limit checks if limit is not set */
12787 if (!hlua_global_allocator.limit)
12788 hlua_global_allocator.limit = ~hlua_global_allocator.limit;
12789
Ilya Shipitsin856aabc2020-04-16 23:51:34 +050012790 /* Call post initialisation function in safe environment. */
Thierry Fournier3c539322020-11-28 16:05:05 +010012791 if (setjmp(safe_ljmp_env) != 0) {
12792 lua_atpanic(L, hlua_panic_safe);
Thierry Fournierb8cef172020-11-28 15:37:17 +010012793 if (lua_type(L, -1) == LUA_TSTRING)
12794 error = lua_tostring(L, -1);
Thierry Fournier3d4a6752016-02-19 20:53:30 +010012795 else
12796 error = "critical error";
12797 fprintf(stderr, "Lua post-init: %s.\n", error);
12798 exit(1);
Thierry Fournier3c539322020-11-28 16:05:05 +010012799 } else {
12800 lua_atpanic(L, hlua_panic_ljmp);
Thierry Fournier3d4a6752016-02-19 20:53:30 +010012801 }
Frédéric Lécaille54f2bcf2018-08-29 13:46:24 +020012802
Thierry Fournierc7492592020-11-28 23:57:24 +010012803 list_for_each_entry(init, &hlua_init_functions[hlua_state_id], l) {
Aurelien DARRAGON4fdf8b52023-03-20 17:22:37 +010012804 hlua_pushref(L, init->function_ref);
Aurelien DARRAGON16d047b2023-03-20 16:29:55 +010012805 /* function ref should be released right away since it was pushed
12806 * on the stack and will not be used anymore
12807 */
12808 hlua_unref(L, init->function_ref);
Thierry Fournier670db242020-11-28 10:49:59 +010012809
12810#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM >= 504
Thierry Fournierb8cef172020-11-28 15:37:17 +010012811 ret = lua_resume(L, L, 0, &nres);
Thierry Fournier670db242020-11-28 10:49:59 +010012812#else
Thierry Fournierb8cef172020-11-28 15:37:17 +010012813 ret = lua_resume(L, L, 0);
Thierry Fournier670db242020-11-28 10:49:59 +010012814#endif
12815 kind = NULL;
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010012816 switch (ret) {
Thierry Fournier670db242020-11-28 10:49:59 +010012817
12818 case LUA_OK:
Thierry Fournierb8cef172020-11-28 15:37:17 +010012819 lua_pop(L, -1);
Thierry Fournier13d08b72020-11-28 11:02:58 +010012820 break;
Thierry Fournier670db242020-11-28 10:49:59 +010012821
12822 case LUA_ERRERR:
12823 kind = "message handler error";
Willy Tarreau14de3952022-11-14 07:08:28 +010012824 __fallthrough;
Thierry Fournier670db242020-11-28 10:49:59 +010012825 case LUA_ERRRUN:
12826 if (!kind)
12827 kind = "runtime error";
Thierry Fournierb8cef172020-11-28 15:37:17 +010012828 msg = lua_tostring(L, -1);
12829 lua_settop(L, 0); /* Empty the stack. */
12830 lua_pop(L, 1);
Christopher Fauletd09cc512021-03-24 14:48:45 +010012831 trace = hlua_traceback(L, ", ");
Thierry Fournier670db242020-11-28 10:49:59 +010012832 if (msg)
12833 ha_alert("Lua init: %s: '%s' from %s\n", kind, msg, trace);
12834 else
12835 ha_alert("Lua init: unknown %s from %s\n", kind, trace);
12836 return_status = 0;
12837 break;
12838
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010012839 default:
Thierry Fournier670db242020-11-28 10:49:59 +010012840 /* Unknown error */
12841 kind = "Unknown error";
Willy Tarreau14de3952022-11-14 07:08:28 +010012842 __fallthrough;
Thierry Fournier670db242020-11-28 10:49:59 +010012843 case LUA_YIELD:
12844 /* yield is not configured at this step, this state doesn't happen */
12845 if (!kind)
12846 kind = "yield not allowed";
Willy Tarreau14de3952022-11-14 07:08:28 +010012847 __fallthrough;
Thierry Fournier670db242020-11-28 10:49:59 +010012848 case LUA_ERRMEM:
12849 if (!kind)
12850 kind = "out of memory error";
Thierry Fournierb8cef172020-11-28 15:37:17 +010012851 lua_settop(L, 0);
12852 lua_pop(L, 1);
Christopher Fauletd09cc512021-03-24 14:48:45 +010012853 trace = hlua_traceback(L, ", ");
Thierry Fournier670db242020-11-28 10:49:59 +010012854 ha_alert("Lua init: %s: %s\n", kind, trace);
12855 return_status = 0;
12856 break;
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010012857 }
Thierry Fournier670db242020-11-28 10:49:59 +010012858 if (!return_status)
12859 break;
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010012860 }
Thierry Fournier3c539322020-11-28 16:05:05 +010012861
12862 lua_atpanic(L, hlua_panic_safe);
Thierry Fournier670db242020-11-28 10:49:59 +010012863 return return_status;
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010012864}
12865
Thierry Fournierb8cef172020-11-28 15:37:17 +010012866int hlua_post_init()
12867{
Thierry Fournier59f11be2020-11-29 00:37:41 +010012868 int ret;
12869 int i;
12870 int errors;
12871 char *err = NULL;
12872 struct hlua_function *fcn;
Christopher Faulet69c581a2021-05-31 08:54:04 +020012873 struct hlua_reg_filter *reg_flt;
Thierry Fournier59f11be2020-11-29 00:37:41 +010012874
Willy Tarreaub1310492021-08-30 09:35:18 +020012875#if defined(USE_OPENSSL)
Thierry Fournierb8cef172020-11-28 15:37:17 +010012876 /* Initialize SSL server. */
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010012877 if (socket_ssl->xprt->prepare_srv) {
Thierry Fournierb8cef172020-11-28 15:37:17 +010012878 int saved_used_backed = global.ssl_used_backend;
12879 // don't affect maxconn automatic computation
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010012880 socket_ssl->xprt->prepare_srv(socket_ssl);
Thierry Fournierb8cef172020-11-28 15:37:17 +010012881 global.ssl_used_backend = saved_used_backed;
12882 }
12883#endif
12884
Thierry Fournierc7492592020-11-28 23:57:24 +010012885 /* Perform post init of common thread */
12886 hlua_state_id = 0;
Willy Tarreau43ab05b2021-09-28 09:43:11 +020012887 ha_set_thread(&ha_thread_info[0]);
Thierry Fournier59f11be2020-11-29 00:37:41 +010012888 ret = hlua_post_init_state(hlua_states[hlua_state_id]);
12889 if (ret == 0)
12890 return 0;
12891
12892 /* init remaining lua states and load files */
12893 for (hlua_state_id = 2; hlua_state_id < global.nbthread + 1; hlua_state_id++) {
12894
12895 /* set thread context */
Willy Tarreau43ab05b2021-09-28 09:43:11 +020012896 ha_set_thread(&ha_thread_info[hlua_state_id - 1]);
Thierry Fournier59f11be2020-11-29 00:37:41 +010012897
12898 /* Init lua state */
12899 hlua_states[hlua_state_id] = hlua_init_state(hlua_state_id);
12900
12901 /* Load lua files */
12902 for (i = 0; per_thread_load && per_thread_load[i]; i++) {
12903 ret = hlua_load_state(per_thread_load[i], hlua_states[hlua_state_id], &err);
12904 if (ret != 0) {
12905 ha_alert("Lua init: %s\n", err);
12906 return 0;
12907 }
12908 }
12909 }
12910
12911 /* Reset thread context */
Willy Tarreau43ab05b2021-09-28 09:43:11 +020012912 ha_set_thread(NULL);
Thierry Fournier59f11be2020-11-29 00:37:41 +010012913
12914 /* Execute post init for all states */
12915 for (hlua_state_id = 1; hlua_state_id < global.nbthread + 1; hlua_state_id++) {
12916
12917 /* set thread context */
Willy Tarreau43ab05b2021-09-28 09:43:11 +020012918 ha_set_thread(&ha_thread_info[hlua_state_id - 1]);
Thierry Fournier59f11be2020-11-29 00:37:41 +010012919
12920 /* run post init */
12921 ret = hlua_post_init_state(hlua_states[hlua_state_id]);
12922 if (ret == 0)
12923 return 0;
12924 }
12925
12926 /* Reset thread context */
Willy Tarreau43ab05b2021-09-28 09:43:11 +020012927 ha_set_thread(NULL);
Thierry Fournier59f11be2020-11-29 00:37:41 +010012928
12929 /* control functions registering. Each function must have:
12930 * - only the function_ref[0] set positive and all other to -1
12931 * - only the function_ref[0] set to -1 and all other positive
12932 * This ensure a same reference is not used both in shared
12933 * lua state and thread dedicated lua state. Note: is the case
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +050012934 * reach, the shared state is priority, but the bug will be
Thierry Fournier59f11be2020-11-29 00:37:41 +010012935 * complicated to found for the end user.
12936 */
12937 errors = 0;
12938 list_for_each_entry(fcn, &referenced_functions, l) {
12939 ret = 0;
12940 for (i = 1; i < global.nbthread + 1; i++) {
12941 if (fcn->function_ref[i] == -1)
12942 ret--;
12943 else
12944 ret++;
12945 }
12946 if (abs(ret) != global.nbthread) {
12947 ha_alert("Lua function '%s' is not referenced in all thread. "
12948 "Expect function in all thread or in none thread.\n", fcn->name);
12949 errors++;
12950 continue;
12951 }
12952
12953 if ((fcn->function_ref[0] == -1) == (ret < 0)) {
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +050012954 ha_alert("Lua function '%s' is referenced both ins shared Lua context (through lua-load) "
12955 "and per-thread Lua context (through lua-load-per-thread). these two context "
Thierry Fournier59f11be2020-11-29 00:37:41 +010012956 "exclusive.\n", fcn->name);
12957 errors++;
12958 }
12959 }
12960
Christopher Faulet69c581a2021-05-31 08:54:04 +020012961 /* Do the same with registered filters */
12962 list_for_each_entry(reg_flt, &referenced_filters, l) {
12963 ret = 0;
12964 for (i = 1; i < global.nbthread + 1; i++) {
12965 if (reg_flt->flt_ref[i] == -1)
12966 ret--;
12967 else
12968 ret++;
12969 }
12970 if (abs(ret) != global.nbthread) {
12971 ha_alert("Lua filter '%s' is not referenced in all thread. "
12972 "Expect function in all thread or in none thread.\n", reg_flt->name);
12973 errors++;
12974 continue;
12975 }
12976
12977 if ((reg_flt->flt_ref[0] == -1) == (ret < 0)) {
12978 ha_alert("Lua filter '%s' is referenced both ins shared Lua context (through lua-load) "
12979 "and per-thread Lua context (through lua-load-per-thread). these two context "
12980 "exclusive.\n", fcn->name);
12981 errors++;
12982 }
12983 }
12984
12985
Thierry Fournier59f11be2020-11-29 00:37:41 +010012986 if (errors > 0)
12987 return 0;
12988
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +050012989 /* after this point, this global will no longer be used, so set to
Thierry Fournier59f11be2020-11-29 00:37:41 +010012990 * -1 in order to have probably a segfault if someone use it
12991 */
12992 hlua_state_id = -1;
12993
12994 return 1;
Thierry Fournierb8cef172020-11-28 15:37:17 +010012995}
12996
Willy Tarreau32f61e22015-03-18 17:54:59 +010012997/* The memory allocator used by the Lua stack. <ud> is a pointer to the
12998 * allocator's context. <ptr> is the pointer to alloc/free/realloc. <osize>
12999 * is the previously allocated size or the kind of object in case of a new
Willy Tarreaud36c7fa2020-12-02 12:26:29 +010013000 * allocation. <nsize> is the requested new size. A new allocation is
13001 * indicated by <ptr> being NULL. A free is indicated by <nsize> being
Willy Tarreaucdb53462020-12-02 12:12:00 +010013002 * zero. This one verifies that the limits are respected but is optimized
13003 * for the fast case where limits are not used, hence stats are not updated.
Willy Tarreaua5efdff2021-10-22 16:00:02 +020013004 *
13005 * Warning: while this API ressembles glibc's realloc() a lot, glibc surpasses
13006 * POSIX by making realloc(ptr,0) an effective free(), but others do not do
13007 * that and will simply allocate zero as if it were the result of malloc(0),
13008 * so mapping this onto realloc() will lead to memory leaks on non-glibc
13009 * systems.
Willy Tarreau32f61e22015-03-18 17:54:59 +010013010 */
13011static void *hlua_alloc(void *ud, void *ptr, size_t osize, size_t nsize)
13012{
13013 struct hlua_mem_allocator *zone = ud;
Willy Tarreaucdb53462020-12-02 12:12:00 +010013014 size_t limit, old, new;
13015
13016 /* a limit of ~0 means unlimited and boot complete, so there's no need
13017 * for accounting anymore.
13018 */
Willy Tarreaua5efdff2021-10-22 16:00:02 +020013019 if (likely(~zone->limit == 0)) {
13020 if (!nsize)
13021 ha_free(&ptr);
13022 else
13023 ptr = realloc(ptr, nsize);
13024 return ptr;
13025 }
Willy Tarreau32f61e22015-03-18 17:54:59 +010013026
Willy Tarreaud36c7fa2020-12-02 12:26:29 +010013027 if (!ptr)
13028 osize = 0;
Willy Tarreau32f61e22015-03-18 17:54:59 +010013029
Willy Tarreaucdb53462020-12-02 12:12:00 +010013030 /* enforce strict limits across all threads */
13031 limit = zone->limit;
13032 old = _HA_ATOMIC_LOAD(&zone->allocated);
13033 do {
13034 new = old + nsize - osize;
13035 if (unlikely(nsize && limit && new > limit))
13036 return NULL;
13037 } while (!_HA_ATOMIC_CAS(&zone->allocated, &old, new));
Willy Tarreau32f61e22015-03-18 17:54:59 +010013038
Willy Tarreaua5efdff2021-10-22 16:00:02 +020013039 if (!nsize)
13040 ha_free(&ptr);
13041 else
13042 ptr = realloc(ptr, nsize);
Willy Tarreaucdb53462020-12-02 12:12:00 +010013043
13044 if (unlikely(!ptr && nsize)) // failed
13045 _HA_ATOMIC_SUB(&zone->allocated, nsize - osize);
13046
13047 __ha_barrier_atomic_store();
Willy Tarreau32f61e22015-03-18 17:54:59 +010013048 return ptr;
13049}
13050
Thierry Fournierecb83c22020-11-28 15:49:44 +010013051/* This function can fail with an abort() due to a Lua critical error.
Thierry FOURNIERbabae282015-09-17 11:36:37 +020013052 * We are in the initialisation process of HAProxy, this abort() is
13053 * tolerated.
13054 */
Thierry Fournierecb83c22020-11-28 15:49:44 +010013055lua_State *hlua_init_state(int thread_num)
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +010013056{
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010013057 int i;
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010013058 int idx;
13059 struct sample_fetch *sf;
Thierry FOURNIER594afe72015-03-10 23:58:30 +010013060 struct sample_conv *sc;
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010013061 char *p;
Thierry Fournierfd107a22016-02-19 19:57:23 +010013062 const char *error_msg;
Thierry Fournier4234dbd2020-11-28 13:18:23 +010013063 void **context;
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013064 lua_State *L;
Thierry Fournier59f11be2020-11-29 00:37:41 +010013065 struct prepend_path *pp;
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010013066
Thierry FOURNIER380d0932015-01-23 14:27:52 +010013067 /* Init main lua stack. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013068 L = lua_newstate(hlua_alloc, &hlua_global_allocator);
Thierry FOURNIER380d0932015-01-23 14:27:52 +010013069
Thierry Fournier4234dbd2020-11-28 13:18:23 +010013070 /* Initialise Lua context to NULL */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013071 context = lua_getextraspace(L);
Thierry Fournier4234dbd2020-11-28 13:18:23 +010013072 *context = NULL;
13073
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -080013074 /* From this point, until the end of the initialisation function,
Thierry FOURNIERbabae282015-09-17 11:36:37 +020013075 * the Lua function can fail with an abort. We are in the initialisation
13076 * process of HAProxy, this abort() is tolerated.
13077 */
13078
Thierry Fournier3c539322020-11-28 16:05:05 +010013079 /* Call post initialisation function in safe environment. */
13080 if (setjmp(safe_ljmp_env) != 0) {
13081 lua_atpanic(L, hlua_panic_safe);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013082 if (lua_type(L, -1) == LUA_TSTRING)
13083 error_msg = lua_tostring(L, -1);
Thierry Fournier2f05cc62020-11-28 16:08:02 +010013084 else
13085 error_msg = "critical error";
13086 fprintf(stderr, "Lua init: %s.\n", error_msg);
13087 exit(1);
Thierry Fournier3c539322020-11-28 16:05:05 +010013088 } else {
13089 lua_atpanic(L, hlua_panic_ljmp);
Thierry Fournier2f05cc62020-11-28 16:08:02 +010013090 }
13091
Thierry FOURNIER380d0932015-01-23 14:27:52 +010013092 /* Initialise lua. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013093 luaL_openlibs(L);
Tim Duesterhus541fe1e2020-01-12 13:55:41 +010013094#define HLUA_PREPEND_PATH_TOSTRING1(x) #x
13095#define HLUA_PREPEND_PATH_TOSTRING(x) HLUA_PREPEND_PATH_TOSTRING1(x)
13096#ifdef HLUA_PREPEND_PATH
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013097 hlua_prepend_path(L, "path", HLUA_PREPEND_PATH_TOSTRING(HLUA_PREPEND_PATH));
Tim Duesterhus541fe1e2020-01-12 13:55:41 +010013098#endif
13099#ifdef HLUA_PREPEND_CPATH
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013100 hlua_prepend_path(L, "cpath", HLUA_PREPEND_PATH_TOSTRING(HLUA_PREPEND_CPATH));
Tim Duesterhus541fe1e2020-01-12 13:55:41 +010013101#endif
13102#undef HLUA_PREPEND_PATH_TOSTRING
13103#undef HLUA_PREPEND_PATH_TOSTRING1
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010013104
Thierry Fournier59f11be2020-11-29 00:37:41 +010013105 /* Apply configured prepend path */
13106 list_for_each_entry(pp, &prepend_path_list, l)
13107 hlua_prepend_path(L, pp->type, pp->path);
13108
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010013109 /*
Aurelien DARRAGON8cd620b2023-04-07 17:37:46 +020013110 * Override some lua functions.
13111 *
13112 */
13113
13114 /* push our "safe" coroutine.create() function */
13115 lua_getglobal(L, "coroutine");
13116 lua_pushcclosure(L, hlua_coroutine_create, 0);
13117 lua_setfield(L, -2, "create");
13118
13119 /*
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010013120 *
13121 * Create "core" object.
13122 *
13123 */
13124
Thierry FOURNIERa2d8c652015-03-11 17:29:39 +010013125 /* This table entry is the object "core" base. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013126 lua_newtable(L);
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010013127
Thierry Fournierecb83c22020-11-28 15:49:44 +010013128 /* set the thread id */
13129 hlua_class_const_int(L, "thread", thread_num);
13130
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010013131 /* Push the loglevel constants. */
Willy Tarreau80f5fae2015-02-27 16:38:20 +010013132 for (i = 0; i < NB_LOG_LEVELS; i++)
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013133 hlua_class_const_int(L, log_levels[i], i);
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010013134
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010013135 /* Register special functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013136 hlua_class_function(L, "register_init", hlua_register_init);
13137 hlua_class_function(L, "register_task", hlua_register_task);
13138 hlua_class_function(L, "register_fetches", hlua_register_fetches);
13139 hlua_class_function(L, "register_converters", hlua_register_converters);
13140 hlua_class_function(L, "register_action", hlua_register_action);
13141 hlua_class_function(L, "register_service", hlua_register_service);
13142 hlua_class_function(L, "register_cli", hlua_register_cli);
Christopher Faulet69c581a2021-05-31 08:54:04 +020013143 hlua_class_function(L, "register_filter", hlua_register_filter);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013144 hlua_class_function(L, "yield", hlua_yield);
13145 hlua_class_function(L, "set_nice", hlua_set_nice);
13146 hlua_class_function(L, "sleep", hlua_sleep);
13147 hlua_class_function(L, "msleep", hlua_msleep);
13148 hlua_class_function(L, "add_acl", hlua_add_acl);
13149 hlua_class_function(L, "del_acl", hlua_del_acl);
13150 hlua_class_function(L, "set_map", hlua_set_map);
13151 hlua_class_function(L, "del_map", hlua_del_map);
13152 hlua_class_function(L, "tcp", hlua_socket_new);
William Lallemand3956c4e2021-09-21 16:25:15 +020013153 hlua_class_function(L, "httpclient", hlua_httpclient_new);
Aurelien DARRAGONc84899c2023-02-20 18:18:59 +010013154 hlua_class_function(L, "event_sub", hlua_event_global_sub);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013155 hlua_class_function(L, "log", hlua_log);
13156 hlua_class_function(L, "Debug", hlua_log_debug);
13157 hlua_class_function(L, "Info", hlua_log_info);
13158 hlua_class_function(L, "Warning", hlua_log_warning);
13159 hlua_class_function(L, "Alert", hlua_log_alert);
13160 hlua_class_function(L, "done", hlua_done);
Aurelien DARRAGON5bed48f2023-04-21 17:32:46 +020013161 hlua_class_function(L, "disable_legacy_mailers", hlua_disable_legacy_mailers);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013162 hlua_fcn_reg_core_fcn(L);
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010013163
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013164 lua_setglobal(L, "core");
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010013165
13166 /*
13167 *
Christopher Faulet0f3c8902020-01-31 18:57:12 +010013168 * Create "act" object.
13169 *
13170 */
13171
13172 /* This table entry is the object "act" base. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013173 lua_newtable(L);
Christopher Faulet0f3c8902020-01-31 18:57:12 +010013174
13175 /* push action return constants */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013176 hlua_class_const_int(L, "CONTINUE", ACT_RET_CONT);
13177 hlua_class_const_int(L, "STOP", ACT_RET_STOP);
13178 hlua_class_const_int(L, "YIELD", ACT_RET_YIELD);
13179 hlua_class_const_int(L, "ERROR", ACT_RET_ERR);
13180 hlua_class_const_int(L, "DONE", ACT_RET_DONE);
13181 hlua_class_const_int(L, "DENY", ACT_RET_DENY);
13182 hlua_class_const_int(L, "ABORT", ACT_RET_ABRT);
13183 hlua_class_const_int(L, "INVALID", ACT_RET_INV);
Christopher Faulet0f3c8902020-01-31 18:57:12 +010013184
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013185 hlua_class_function(L, "wake_time", hlua_set_wake_time);
Christopher Faulet2c2c2e32020-01-31 19:07:52 +010013186
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013187 lua_setglobal(L, "act");
Christopher Faulet0f3c8902020-01-31 18:57:12 +010013188
13189 /*
13190 *
Christopher Faulet69c581a2021-05-31 08:54:04 +020013191 * Create "Filter" object.
13192 *
13193 */
13194
13195 /* This table entry is the object "filter" base. */
13196 lua_newtable(L);
13197
13198 /* push flags and constants */
13199 hlua_class_const_int(L, "CONTINUE", 1);
13200 hlua_class_const_int(L, "WAIT", 0);
13201 hlua_class_const_int(L, "ERROR", -1);
13202
13203 hlua_class_const_int(L, "FLT_CFG_FL_HTX", FLT_CFG_FL_HTX);
13204
Christopher Fauletc404f112020-02-26 15:03:09 +010013205 hlua_class_function(L, "wake_time", hlua_set_wake_time);
13206 hlua_class_function(L, "register_data_filter", hlua_register_data_filter);
13207 hlua_class_function(L, "unregister_data_filter", hlua_unregister_data_filter);
13208
Christopher Faulet69c581a2021-05-31 08:54:04 +020013209 lua_setglobal(L, "filter");
13210
13211 /*
13212 *
Thierry FOURNIER3def3932015-04-07 11:27:54 +020013213 * Register class Map
13214 *
13215 */
13216
13217 /* This table entry is the object "Map" base. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013218 lua_newtable(L);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020013219
13220 /* register pattern types. */
13221 for (i=0; i<PAT_MATCH_NUM; i++)
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013222 hlua_class_const_int(L, pat_match_names[i], i);
Thierry FOURNIER4dc71972017-01-28 08:33:08 +010013223 for (i=0; i<PAT_MATCH_NUM; i++) {
Willy Tarreau843b7cb2018-07-13 10:54:26 +020013224 snprintf(trash.area, trash.size, "_%s", pat_match_names[i]);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013225 hlua_class_const_int(L, trash.area, i);
Thierry FOURNIER4dc71972017-01-28 08:33:08 +010013226 }
Thierry FOURNIER3def3932015-04-07 11:27:54 +020013227
13228 /* register constructor. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013229 hlua_class_function(L, "new", hlua_map_new);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020013230
13231 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013232 lua_newtable(L);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020013233
Ilya Shipitsind4259502020-04-08 01:07:56 +050013234 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013235 lua_pushstring(L, "__index");
13236 lua_newtable(L);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020013237
13238 /* Register . */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013239 hlua_class_function(L, "lookup", hlua_map_lookup);
13240 hlua_class_function(L, "slookup", hlua_map_slookup);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020013241
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013242 lua_rawset(L, -3);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020013243
Thierry Fournier45e78d72016-02-19 18:34:46 +010013244 /* Register previous table in the registry with reference and named entry.
13245 * The function hlua_register_metatable() pops the stack, so we
13246 * previously create a copy of the table.
13247 */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013248 lua_pushvalue(L, -1); /* Copy the -1 entry and push it on the stack. */
13249 class_map_ref = hlua_register_metatable(L, CLASS_MAP);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020013250
13251 /* Assign the metatable to the mai Map object. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013252 lua_setmetatable(L, -2);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020013253
13254 /* Set a name to the table. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013255 lua_setglobal(L, "Map");
Thierry FOURNIER3def3932015-04-07 11:27:54 +020013256
13257 /*
13258 *
William Lallemand30fcca12022-03-30 12:03:12 +020013259 * Register "CertCache" class
13260 *
13261 */
13262
13263 /* Create and fill the metatable. */
13264 lua_newtable(L);
13265 /* Register */
13266 hlua_class_function(L, "set", hlua_ckch_set);
13267 lua_setglobal(L, CLASS_CERTCACHE); /* Create global object called Regex */
13268
13269 /*
13270 *
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010013271 * Register class Channel
13272 *
13273 */
13274
13275 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013276 lua_newtable(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010013277
Ilya Shipitsind4259502020-04-08 01:07:56 +050013278 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013279 lua_pushstring(L, "__index");
13280 lua_newtable(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010013281
13282 /* Register . */
Christopher Faulet6a79fc12021-08-06 16:02:36 +020013283 hlua_class_function(L, "data", hlua_channel_get_data);
13284 hlua_class_function(L, "line", hlua_channel_get_line);
13285 hlua_class_function(L, "set", hlua_channel_set_data);
13286 hlua_class_function(L, "remove", hlua_channel_del_data);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013287 hlua_class_function(L, "append", hlua_channel_append);
Christopher Faulet6a79fc12021-08-06 16:02:36 +020013288 hlua_class_function(L, "prepend", hlua_channel_prepend);
13289 hlua_class_function(L, "insert", hlua_channel_insert_data);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013290 hlua_class_function(L, "send", hlua_channel_send);
13291 hlua_class_function(L, "forward", hlua_channel_forward);
Christopher Faulet6a79fc12021-08-06 16:02:36 +020013292 hlua_class_function(L, "input", hlua_channel_get_in_len);
13293 hlua_class_function(L, "output", hlua_channel_get_out_len);
13294 hlua_class_function(L, "may_recv", hlua_channel_may_recv);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013295 hlua_class_function(L, "is_full", hlua_channel_is_full);
13296 hlua_class_function(L, "is_resp", hlua_channel_is_resp);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010013297
Christopher Faulet6a79fc12021-08-06 16:02:36 +020013298 /* Deprecated API */
13299 hlua_class_function(L, "get", hlua_channel_get);
13300 hlua_class_function(L, "dup", hlua_channel_dup);
13301 hlua_class_function(L, "getline", hlua_channel_getline);
13302 hlua_class_function(L, "get_in_len", hlua_channel_get_in_len);
13303 hlua_class_function(L, "get_out_len", hlua_channel_get_out_len);
13304
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013305 lua_rawset(L, -3);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010013306
13307 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013308 class_channel_ref = hlua_register_metatable(L, CLASS_CHANNEL);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010013309
13310 /*
13311 *
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010013312 * Register class Fetches
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010013313 *
13314 */
13315
13316 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013317 lua_newtable(L);
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010013318
Ilya Shipitsind4259502020-04-08 01:07:56 +050013319 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013320 lua_pushstring(L, "__index");
13321 lua_newtable(L);
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010013322
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010013323 /* Browse existing fetches and create the associated
13324 * object method.
13325 */
13326 sf = NULL;
13327 while ((sf = sample_fetch_getnext(sf, &idx)) != NULL) {
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010013328 /* gL.Tua doesn't support '.' and '-' in the function names, replace it
13329 * by an underscore.
13330 */
Willy Tarreau5ef96562021-08-26 16:48:53 +020013331 strlcpy2(trash.area, sf->kw, trash.size);
Willy Tarreau843b7cb2018-07-13 10:54:26 +020013332 for (p = trash.area; *p; p++)
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010013333 if (*p == '.' || *p == '-' || *p == '+')
13334 *p = '_';
13335
13336 /* Register the function. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013337 lua_pushstring(L, trash.area);
13338 lua_pushlightuserdata(L, sf);
13339 lua_pushcclosure(L, hlua_run_sample_fetch, 1);
13340 lua_rawset(L, -3);
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010013341 }
13342
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013343 lua_rawset(L, -3);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010013344
13345 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013346 class_fetches_ref = hlua_register_metatable(L, CLASS_FETCHES);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010013347
13348 /*
13349 *
Thierry FOURNIER594afe72015-03-10 23:58:30 +010013350 * Register class Converters
13351 *
13352 */
13353
13354 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013355 lua_newtable(L);
Thierry FOURNIER594afe72015-03-10 23:58:30 +010013356
13357 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013358 lua_pushstring(L, "__index");
13359 lua_newtable(L);
Thierry FOURNIER594afe72015-03-10 23:58:30 +010013360
13361 /* Browse existing converters and create the associated
13362 * object method.
13363 */
13364 sc = NULL;
13365 while ((sc = sample_conv_getnext(sc, &idx)) != NULL) {
Thierry FOURNIER594afe72015-03-10 23:58:30 +010013366 /* gL.Tua doesn't support '.' and '-' in the function names, replace it
13367 * by an underscore.
13368 */
Willy Tarreau5ef96562021-08-26 16:48:53 +020013369 strlcpy2(trash.area, sc->kw, trash.size);
Willy Tarreau843b7cb2018-07-13 10:54:26 +020013370 for (p = trash.area; *p; p++)
Thierry FOURNIER594afe72015-03-10 23:58:30 +010013371 if (*p == '.' || *p == '-' || *p == '+')
13372 *p = '_';
13373
13374 /* Register the function. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013375 lua_pushstring(L, trash.area);
13376 lua_pushlightuserdata(L, sc);
13377 lua_pushcclosure(L, hlua_run_sample_conv, 1);
13378 lua_rawset(L, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +010013379 }
13380
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013381 lua_rawset(L, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +010013382
13383 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013384 class_converters_ref = hlua_register_metatable(L, CLASS_CONVERTERS);
Thierry FOURNIER594afe72015-03-10 23:58:30 +010013385
13386 /*
13387 *
Thierry FOURNIER08504f42015-03-16 14:17:08 +010013388 * Register class HTTP
13389 *
13390 */
13391
13392 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013393 lua_newtable(L);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010013394
Ilya Shipitsind4259502020-04-08 01:07:56 +050013395 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013396 lua_pushstring(L, "__index");
13397 lua_newtable(L);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010013398
13399 /* Register Lua functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013400 hlua_class_function(L, "req_get_headers",hlua_http_req_get_headers);
13401 hlua_class_function(L, "req_del_header", hlua_http_req_del_hdr);
13402 hlua_class_function(L, "req_rep_header", hlua_http_req_rep_hdr);
13403 hlua_class_function(L, "req_rep_value", hlua_http_req_rep_val);
13404 hlua_class_function(L, "req_add_header", hlua_http_req_add_hdr);
13405 hlua_class_function(L, "req_set_header", hlua_http_req_set_hdr);
13406 hlua_class_function(L, "req_set_method", hlua_http_req_set_meth);
13407 hlua_class_function(L, "req_set_path", hlua_http_req_set_path);
13408 hlua_class_function(L, "req_set_query", hlua_http_req_set_query);
13409 hlua_class_function(L, "req_set_uri", hlua_http_req_set_uri);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010013410
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013411 hlua_class_function(L, "res_get_headers",hlua_http_res_get_headers);
13412 hlua_class_function(L, "res_del_header", hlua_http_res_del_hdr);
13413 hlua_class_function(L, "res_rep_header", hlua_http_res_rep_hdr);
13414 hlua_class_function(L, "res_rep_value", hlua_http_res_rep_val);
13415 hlua_class_function(L, "res_add_header", hlua_http_res_add_hdr);
13416 hlua_class_function(L, "res_set_header", hlua_http_res_set_hdr);
13417 hlua_class_function(L, "res_set_status", hlua_http_res_set_status);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010013418
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013419 lua_rawset(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010013420
13421 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013422 class_http_ref = hlua_register_metatable(L, CLASS_HTTP);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010013423
Christopher Fauletdf97ac42020-02-26 16:57:19 +010013424 /*
13425 *
13426 * Register class HTTPMessage
13427 *
13428 */
13429
13430 /* Create and fill the metatable. */
13431 lua_newtable(L);
13432
Ilya Shipitsinff0f2782021-08-22 22:18:07 +050013433 /* Create and fill the __index entry. */
Christopher Fauletdf97ac42020-02-26 16:57:19 +010013434 lua_pushstring(L, "__index");
13435 lua_newtable(L);
13436
13437 /* Register Lua functions. */
13438 hlua_class_function(L, "is_resp", hlua_http_msg_is_resp);
13439 hlua_class_function(L, "get_stline", hlua_http_msg_get_stline);
13440 hlua_class_function(L, "get_headers", hlua_http_msg_get_headers);
13441 hlua_class_function(L, "del_header", hlua_http_msg_del_hdr);
13442 hlua_class_function(L, "rep_header", hlua_http_msg_rep_hdr);
13443 hlua_class_function(L, "rep_value", hlua_http_msg_rep_val);
13444 hlua_class_function(L, "add_header", hlua_http_msg_add_hdr);
13445 hlua_class_function(L, "set_header", hlua_http_msg_set_hdr);
13446 hlua_class_function(L, "set_method", hlua_http_msg_set_meth);
13447 hlua_class_function(L, "set_path", hlua_http_msg_set_path);
13448 hlua_class_function(L, "set_query", hlua_http_msg_set_query);
13449 hlua_class_function(L, "set_uri", hlua_http_msg_set_uri);
13450 hlua_class_function(L, "set_status", hlua_http_msg_set_status);
13451 hlua_class_function(L, "is_full", hlua_http_msg_is_full);
13452 hlua_class_function(L, "may_recv", hlua_http_msg_may_recv);
13453 hlua_class_function(L, "eom", hlua_http_msg_is_eom);
13454 hlua_class_function(L, "input", hlua_http_msg_get_in_len);
13455 hlua_class_function(L, "output", hlua_http_msg_get_out_len);
13456
13457 hlua_class_function(L, "body", hlua_http_msg_get_body);
13458 hlua_class_function(L, "set", hlua_http_msg_set_data);
13459 hlua_class_function(L, "remove", hlua_http_msg_del_data);
13460 hlua_class_function(L, "append", hlua_http_msg_append);
13461 hlua_class_function(L, "prepend", hlua_http_msg_prepend);
13462 hlua_class_function(L, "insert", hlua_http_msg_insert_data);
13463 hlua_class_function(L, "set_eom", hlua_http_msg_set_eom);
13464 hlua_class_function(L, "unset_eom", hlua_http_msg_unset_eom);
13465
13466 hlua_class_function(L, "send", hlua_http_msg_send);
13467 hlua_class_function(L, "forward", hlua_http_msg_forward);
13468
13469 lua_rawset(L, -3);
13470
13471 /* Register previous table in the registry with reference and named entry. */
13472 class_http_msg_ref = hlua_register_metatable(L, CLASS_HTTP_MSG);
William Lallemand3956c4e2021-09-21 16:25:15 +020013473
13474 /*
13475 *
13476 * Register class HTTPClient
13477 *
13478 */
13479
13480 /* Create and fill the metatable. */
13481 lua_newtable(L);
13482 lua_pushstring(L, "__index");
13483 lua_newtable(L);
13484 hlua_class_function(L, "get", hlua_httpclient_get);
William Lallemanddc2cc902021-10-26 11:43:26 +020013485 hlua_class_function(L, "head", hlua_httpclient_head);
13486 hlua_class_function(L, "put", hlua_httpclient_put);
13487 hlua_class_function(L, "post", hlua_httpclient_post);
13488 hlua_class_function(L, "delete", hlua_httpclient_delete);
William Lallemand3956c4e2021-09-21 16:25:15 +020013489 lua_settable(L, -3); /* Sets the __index entry. */
William Lallemandf77f1de2021-09-28 19:10:38 +020013490 /* Register the garbage collector entry. */
13491 lua_pushstring(L, "__gc");
13492 lua_pushcclosure(L, hlua_httpclient_gc, 0);
13493 lua_settable(L, -3); /* Push the last 2 entries in the table at index -3 */
13494
William Lallemand3956c4e2021-09-21 16:25:15 +020013495
13496
13497 class_httpclient_ref = hlua_register_metatable(L, CLASS_HTTPCLIENT);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010013498 /*
13499 *
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020013500 * Register class AppletTCP
13501 *
13502 */
13503
13504 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013505 lua_newtable(L);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020013506
Ilya Shipitsind4259502020-04-08 01:07:56 +050013507 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013508 lua_pushstring(L, "__index");
13509 lua_newtable(L);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020013510
13511 /* Register Lua functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013512 hlua_class_function(L, "getline", hlua_applet_tcp_getline);
13513 hlua_class_function(L, "receive", hlua_applet_tcp_recv);
13514 hlua_class_function(L, "send", hlua_applet_tcp_send);
13515 hlua_class_function(L, "set_priv", hlua_applet_tcp_set_priv);
13516 hlua_class_function(L, "get_priv", hlua_applet_tcp_get_priv);
13517 hlua_class_function(L, "set_var", hlua_applet_tcp_set_var);
13518 hlua_class_function(L, "unset_var", hlua_applet_tcp_unset_var);
13519 hlua_class_function(L, "get_var", hlua_applet_tcp_get_var);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020013520
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013521 lua_settable(L, -3);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020013522
13523 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013524 class_applet_tcp_ref = hlua_register_metatable(L, CLASS_APPLET_TCP);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020013525
13526 /*
13527 *
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020013528 * Register class AppletHTTP
13529 *
13530 */
13531
13532 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013533 lua_newtable(L);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020013534
Ilya Shipitsind4259502020-04-08 01:07:56 +050013535 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013536 lua_pushstring(L, "__index");
13537 lua_newtable(L);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020013538
13539 /* Register Lua functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013540 hlua_class_function(L, "set_priv", hlua_applet_http_set_priv);
13541 hlua_class_function(L, "get_priv", hlua_applet_http_get_priv);
13542 hlua_class_function(L, "set_var", hlua_applet_http_set_var);
13543 hlua_class_function(L, "unset_var", hlua_applet_http_unset_var);
13544 hlua_class_function(L, "get_var", hlua_applet_http_get_var);
13545 hlua_class_function(L, "getline", hlua_applet_http_getline);
13546 hlua_class_function(L, "receive", hlua_applet_http_recv);
13547 hlua_class_function(L, "send", hlua_applet_http_send);
13548 hlua_class_function(L, "add_header", hlua_applet_http_addheader);
13549 hlua_class_function(L, "set_status", hlua_applet_http_status);
13550 hlua_class_function(L, "start_response", hlua_applet_http_start_response);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020013551
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013552 lua_settable(L, -3);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020013553
13554 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013555 class_applet_http_ref = hlua_register_metatable(L, CLASS_APPLET_HTTP);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020013556
13557 /*
13558 *
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010013559 * Register class TXN
13560 *
13561 */
13562
13563 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013564 lua_newtable(L);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010013565
Ilya Shipitsind4259502020-04-08 01:07:56 +050013566 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013567 lua_pushstring(L, "__index");
13568 lua_newtable(L);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010013569
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +010013570 /* Register Lua functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013571 hlua_class_function(L, "set_priv", hlua_set_priv);
13572 hlua_class_function(L, "get_priv", hlua_get_priv);
13573 hlua_class_function(L, "set_var", hlua_set_var);
13574 hlua_class_function(L, "unset_var", hlua_unset_var);
13575 hlua_class_function(L, "get_var", hlua_get_var);
13576 hlua_class_function(L, "done", hlua_txn_done);
13577 hlua_class_function(L, "reply", hlua_txn_reply_new);
13578 hlua_class_function(L, "set_loglevel", hlua_txn_set_loglevel);
13579 hlua_class_function(L, "set_tos", hlua_txn_set_tos);
13580 hlua_class_function(L, "set_mark", hlua_txn_set_mark);
13581 hlua_class_function(L, "set_priority_class", hlua_txn_set_priority_class);
13582 hlua_class_function(L, "set_priority_offset", hlua_txn_set_priority_offset);
13583 hlua_class_function(L, "deflog", hlua_txn_deflog);
13584 hlua_class_function(L, "log", hlua_txn_log);
13585 hlua_class_function(L, "Debug", hlua_txn_log_debug);
13586 hlua_class_function(L, "Info", hlua_txn_log_info);
13587 hlua_class_function(L, "Warning", hlua_txn_log_warning);
13588 hlua_class_function(L, "Alert", hlua_txn_log_alert);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +010013589
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013590 lua_rawset(L, -3);
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010013591
13592 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013593 class_txn_ref = hlua_register_metatable(L, CLASS_TXN);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010013594
13595 /*
13596 *
Christopher Faulet700d9e82020-01-31 12:21:52 +010013597 * Register class reply
13598 *
13599 */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013600 lua_newtable(L);
13601 lua_pushstring(L, "__index");
13602 lua_newtable(L);
13603 hlua_class_function(L, "set_status", hlua_txn_reply_set_status);
13604 hlua_class_function(L, "add_header", hlua_txn_reply_add_header);
13605 hlua_class_function(L, "del_header", hlua_txn_reply_del_header);
13606 hlua_class_function(L, "set_body", hlua_txn_reply_set_body);
13607 lua_settable(L, -3); /* Sets the __index entry. */
13608 class_txn_reply_ref = luaL_ref(L, LUA_REGISTRYINDEX);
Christopher Faulet700d9e82020-01-31 12:21:52 +010013609
13610
13611 /*
13612 *
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010013613 * Register class Socket
13614 *
13615 */
13616
13617 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013618 lua_newtable(L);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010013619
Ilya Shipitsind4259502020-04-08 01:07:56 +050013620 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013621 lua_pushstring(L, "__index");
13622 lua_newtable(L);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010013623
Baptiste Assmann84bb4932015-03-02 21:40:06 +010013624#ifdef USE_OPENSSL
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013625 hlua_class_function(L, "connect_ssl", hlua_socket_connect_ssl);
Baptiste Assmann84bb4932015-03-02 21:40:06 +010013626#endif
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013627 hlua_class_function(L, "connect", hlua_socket_connect);
13628 hlua_class_function(L, "send", hlua_socket_send);
13629 hlua_class_function(L, "receive", hlua_socket_receive);
13630 hlua_class_function(L, "close", hlua_socket_close);
13631 hlua_class_function(L, "getpeername", hlua_socket_getpeername);
13632 hlua_class_function(L, "getsockname", hlua_socket_getsockname);
13633 hlua_class_function(L, "setoption", hlua_socket_setoption);
13634 hlua_class_function(L, "settimeout", hlua_socket_settimeout);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010013635
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013636 lua_rawset(L, -3); /* Push the last 2 entries in the table at index -3 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010013637
13638 /* Register the garbage collector entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013639 lua_pushstring(L, "__gc");
13640 lua_pushcclosure(L, hlua_socket_gc, 0);
13641 lua_rawset(L, -3); /* Push the last 2 entries in the table at index -3 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010013642
13643 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013644 class_socket_ref = hlua_register_metatable(L, CLASS_SOCKET);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010013645
Thierry Fournieraafc7772020-12-04 11:47:47 +010013646 lua_atpanic(L, hlua_panic_safe);
13647
13648 return L;
13649}
13650
13651void hlua_init(void) {
13652 int i;
Amaury Denoyelle239fdbf2021-03-24 10:22:03 +010013653 char *errmsg;
Thierry Fournieraafc7772020-12-04 11:47:47 +010013654#ifdef USE_OPENSSL
13655 struct srv_kw *kw;
13656 int tmp_error;
13657 char *error;
13658 char *args[] = { /* SSL client configuration. */
13659 "ssl",
13660 "verify",
13661 "none",
13662 NULL
13663 };
13664#endif
13665
13666 /* Init post init function list head */
13667 for (i = 0; i < MAX_THREADS + 1; i++)
13668 LIST_INIT(&hlua_init_functions[i]);
13669
13670 /* Init state for common/shared lua parts */
13671 hlua_state_id = 0;
Willy Tarreau43ab05b2021-09-28 09:43:11 +020013672 ha_set_thread(NULL);
Thierry Fournieraafc7772020-12-04 11:47:47 +010013673 hlua_states[0] = hlua_init_state(0);
13674
13675 /* Init state 1 for thread 0. We have at least one thread. */
13676 hlua_state_id = 1;
Willy Tarreau43ab05b2021-09-28 09:43:11 +020013677 ha_set_thread(NULL);
Thierry Fournieraafc7772020-12-04 11:47:47 +010013678 hlua_states[1] = hlua_init_state(1);
13679
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010013680 /* Proxy and server configuration initialisation. */
William Lallemand6bb77b92021-07-28 15:48:16 +020013681 socket_proxy = alloc_new_proxy("LUA-SOCKET", PR_CAP_FE|PR_CAP_BE|PR_CAP_INT, &errmsg);
Amaury Denoyelle239fdbf2021-03-24 10:22:03 +010013682 if (!socket_proxy) {
13683 fprintf(stderr, "Lua init: %s\n", errmsg);
13684 exit(1);
13685 }
13686 proxy_preset_defaults(socket_proxy);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010013687
13688 /* Init TCP server: unchanged parameters */
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010013689 socket_tcp = new_server(socket_proxy);
13690 if (!socket_tcp) {
13691 fprintf(stderr, "Lua init: failed to allocate tcp server socket\n");
13692 exit(1);
13693 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010013694
13695#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010013696 /* Init TCP server: unchanged parameters */
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010013697 socket_ssl = new_server(socket_proxy);
13698 if (!socket_ssl) {
13699 fprintf(stderr, "Lua init: failed to allocate ssl server socket\n");
13700 exit(1);
13701 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010013702
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010013703 socket_ssl->use_ssl = 1;
13704 socket_ssl->xprt = xprt_get(XPRT_SSL);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010013705
Bertrand Jacquin80839ff2021-01-21 19:14:46 +000013706 for (i = 0; args[i] != NULL; i++) {
13707 if ((kw = srv_find_kw(args[i])) != NULL) { /* Maybe it's registered server keyword */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010013708 /*
13709 *
13710 * If the keyword is not known, we can search in the registered
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -080013711 * server keywords. This is useful to configure special SSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010013712 * features like client certificates and ssl_verify.
13713 *
13714 */
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010013715 tmp_error = kw->parse(args, &i, socket_proxy, socket_ssl, &error);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010013716 if (tmp_error != 0) {
13717 fprintf(stderr, "INTERNAL ERROR: %s\n", error);
13718 abort(); /* This must be never arrives because the command line
13719 not editable by the user. */
13720 }
Bertrand Jacquin80839ff2021-01-21 19:14:46 +000013721 i += kw->skip;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010013722 }
13723 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010013724#endif
Thierry Fournier75933d42016-01-21 09:30:18 +010013725
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +010013726}
Willy Tarreaubb57d942016-12-21 19:04:56 +010013727
Tim Duesterhusd0c0ca22020-07-04 11:53:26 +020013728static void hlua_deinit()
13729{
Willy Tarreau186f3762020-12-04 11:48:12 +010013730 int thr;
Christopher Faulet69c581a2021-05-31 08:54:04 +020013731 struct hlua_reg_filter *reg_flt, *reg_flt_bck;
13732
13733 list_for_each_entry_safe(reg_flt, reg_flt_bck, &referenced_filters, l)
13734 release_hlua_reg_filter(reg_flt);
Willy Tarreau186f3762020-12-04 11:48:12 +010013735
13736 for (thr = 0; thr < MAX_THREADS+1; thr++) {
13737 if (hlua_states[thr])
13738 lua_close(hlua_states[thr]);
13739 }
Willy Tarreau430bf4a2021-03-04 09:45:32 +010013740
Amaury Denoyellebc2ebfa2021-08-25 15:34:53 +020013741 srv_drop(socket_tcp);
Willy Tarreau430bf4a2021-03-04 09:45:32 +010013742
Willy Tarreau0f143af2021-03-05 10:41:48 +010013743#ifdef USE_OPENSSL
Amaury Denoyellebc2ebfa2021-08-25 15:34:53 +020013744 srv_drop(socket_ssl);
Willy Tarreau0f143af2021-03-05 10:41:48 +010013745#endif
Amaury Denoyelle239fdbf2021-03-24 10:22:03 +010013746
13747 free_proxy(socket_proxy);
Tim Duesterhusd0c0ca22020-07-04 11:53:26 +020013748}
13749
13750REGISTER_POST_DEINIT(hlua_deinit);
13751
Willy Tarreau80713382018-11-26 10:19:54 +010013752static void hlua_register_build_options(void)
13753{
Willy Tarreaubb57d942016-12-21 19:04:56 +010013754 char *ptr = NULL;
Willy Tarreau80713382018-11-26 10:19:54 +010013755
Willy Tarreaubb57d942016-12-21 19:04:56 +010013756 memprintf(&ptr, "Built with Lua version : %s", LUA_RELEASE);
13757 hap_register_build_opts(ptr, 1);
13758}
Willy Tarreau80713382018-11-26 10:19:54 +010013759
13760INITCALL0(STG_REGISTER, hlua_register_build_options);