blob: d05e9cd6068b8af5955d4c969b51fa2d02215a4b [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 */
1297static inline struct hlua *hlua_gethlua(lua_State *L)
1298{
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)))) {
2212 notification_wake(&ctx->wake_on_read);
2213 notification_wake(&ctx->wake_on_write);
2214 return;
2215 }
2216
Willy Tarreau5321da92022-05-06 11:57:34 +02002217 if (ctx->die) {
Christopher Faulet31572222023-03-31 11:13:48 +02002218 se_fl_set(appctx->sedesc, SE_FL_EOI|SE_FL_EOS);
Willy Tarreau5321da92022-05-06 11:57:34 +02002219 notification_wake(&ctx->wake_on_read);
2220 notification_wake(&ctx->wake_on_write);
Christopher Faulet31572222023-03-31 11:13:48 +02002221 return;
Thierry FOURNIERb13b20a2017-07-16 20:48:54 +02002222 }
2223
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +05002224 /* If we can't write, wakeup the pending write signals. */
Willy Tarreau3e7be362022-05-27 10:35:27 +02002225 if (channel_output_closed(sc_ic(sc)))
Willy Tarreau5321da92022-05-06 11:57:34 +02002226 notification_wake(&ctx->wake_on_write);
Thierry FOURNIER6d695e62015-09-27 19:29:38 +02002227
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +05002228 /* If we can't read, wakeup the pending read signals. */
Willy Tarreau3e7be362022-05-27 10:35:27 +02002229 if (channel_input_closed(sc_oc(sc)))
Willy Tarreau5321da92022-05-06 11:57:34 +02002230 notification_wake(&ctx->wake_on_read);
Thierry FOURNIER6d695e62015-09-27 19:29:38 +02002231
Willy Tarreau5a0b25d2019-07-18 18:01:14 +02002232 /* if the connection is not established, inform the stream that we want
Thierry FOURNIER316e3192015-09-04 18:25:53 +02002233 * to be notified whenever the connection completes.
2234 */
Willy Tarreau3e7be362022-05-27 10:35:27 +02002235 if (sc_opposite(sc)->state < SC_ST_EST) {
Willy Tarreau90e8b452022-05-25 18:21:43 +02002236 applet_need_more_data(appctx);
Willy Tarreaub23edc82022-05-24 16:49:03 +02002237 se_need_remote_conn(appctx->sedesc);
Willy Tarreau4164eb92022-05-25 15:42:03 +02002238 applet_have_more_data(appctx);
Willy Tarreaud4da1962015-04-20 01:31:23 +02002239 return;
Thierry FOURNIER316e3192015-09-04 18:25:53 +02002240 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002241
2242 /* This function is called after the connect. */
Willy Tarreau5321da92022-05-06 11:57:34 +02002243 ctx->connected = 1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002244
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002245 /* Wake the tasks which wants to write if the buffer have available space. */
Willy Tarreau3e7be362022-05-27 10:35:27 +02002246 if (channel_may_recv(sc_ic(sc)))
Willy Tarreau5321da92022-05-06 11:57:34 +02002247 notification_wake(&ctx->wake_on_write);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002248
2249 /* Wake the tasks which wants to read if the buffer contains data. */
Willy Tarreau3e7be362022-05-27 10:35:27 +02002250 if (!channel_is_empty(sc_oc(sc)))
Willy Tarreau5321da92022-05-06 11:57:34 +02002251 notification_wake(&ctx->wake_on_read);
Thierry FOURNIER101b9762018-05-27 01:27:40 +02002252
Thierry FOURNIER101b9762018-05-27 01:27:40 +02002253 /* If write notifications are registered, we considers we want
Willy Tarreau3367d412018-11-15 10:57:41 +01002254 * to write, so we clear the blocking flag.
Thierry FOURNIER101b9762018-05-27 01:27:40 +02002255 */
Willy Tarreau5321da92022-05-06 11:57:34 +02002256 if (notification_registered(&ctx->wake_on_write))
Willy Tarreau4164eb92022-05-25 15:42:03 +02002257 applet_have_more_data(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002258}
2259
Christopher Faulet5f35a3e2022-05-12 15:31:05 +02002260static int hlua_socket_init(struct appctx *appctx)
2261{
2262 struct hlua_csk_ctx *ctx = appctx->svcctx;
2263 struct stream *s;
2264
2265 if (appctx_finalize_startup(appctx, socket_proxy, &BUF_NULL) == -1)
2266 goto error;
2267
2268 s = appctx_strm(appctx);
2269
Willy Tarreau4596fe22022-05-17 19:07:51 +02002270 /* Configure "right" stream connector. This stconn is used to connect
Christopher Faulet5f35a3e2022-05-12 15:31:05 +02002271 * and retrieve data from the server. The connection is initialized
2272 * with the "struct server".
2273 */
Willy Tarreau74568cf2022-05-27 09:03:30 +02002274 sc_set_state(s->scb, SC_ST_ASS);
Christopher Faulet5f35a3e2022-05-12 15:31:05 +02002275
2276 /* Force destination server. */
2277 s->flags |= SF_DIRECT | SF_ASSIGNED | SF_BE_ASSIGNED;
2278 s->target = &socket_tcp->obj_type;
2279
2280 ctx->appctx = appctx;
2281 return 0;
2282
2283 error:
2284 return -1;
2285}
2286
Willy Tarreau87b09662015-04-03 00:22:06 +02002287/* This function is called when the "struct stream" is destroyed.
2288 * Remove the link from the object to this stream.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002289 * Wake all the pending signals.
2290 */
Willy Tarreau00a37f02015-04-13 12:05:19 +02002291static void hlua_socket_release(struct appctx *appctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002292{
Willy Tarreau5321da92022-05-06 11:57:34 +02002293 struct hlua_csk_ctx *ctx = appctx->svcctx;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002294 struct xref *peer;
2295
Christopher Faulet5f35a3e2022-05-12 15:31:05 +02002296 /* Remove my link in the original objects. */
Willy Tarreau5321da92022-05-06 11:57:34 +02002297 peer = xref_get_peer_and_lock(&ctx->xref);
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002298 if (peer)
Willy Tarreau5321da92022-05-06 11:57:34 +02002299 xref_disconnect(&ctx->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002300
2301 /* Wake all the task waiting for me. */
Willy Tarreau5321da92022-05-06 11:57:34 +02002302 notification_wake(&ctx->wake_on_read);
2303 notification_wake(&ctx->wake_on_write);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002304}
2305
2306/* If the garbage collectio of the object is launch, nobody
Willy Tarreau87b09662015-04-03 00:22:06 +02002307 * uses this object. If the stream does not exists, just quit.
2308 * Send the shutdown signal to the stream. In some cases,
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002309 * pending signal can rest in the read and write lists. destroy
2310 * it.
2311 */
2312__LJMP static int hlua_socket_gc(lua_State *L)
2313{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002314 struct hlua_socket *socket;
Willy Tarreau5321da92022-05-06 11:57:34 +02002315 struct hlua_csk_ctx *ctx;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002316 struct xref *peer;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002317
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002318 MAY_LJMP(check_args(L, 1, "__gc"));
2319
2320 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002321 peer = xref_get_peer_and_lock(&socket->xref);
2322 if (!peer)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002323 return 0;
Willy Tarreau5321da92022-05-06 11:57:34 +02002324
2325 ctx = container_of(peer, struct hlua_csk_ctx, xref);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002326
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002327 /* Set the flag which destroy the session. */
Willy Tarreau5321da92022-05-06 11:57:34 +02002328 ctx->die = 1;
2329 appctx_wakeup(ctx->appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002330
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002331 /* Remove all reference between the Lua stack and the coroutine stream. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002332 xref_disconnect(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002333 return 0;
2334}
2335
2336/* The close function send shutdown signal and break the
Willy Tarreau87b09662015-04-03 00:22:06 +02002337 * links between the stream and the object.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002338 */
sada05ed3302018-05-11 11:48:18 -07002339__LJMP static int hlua_socket_close_helper(lua_State *L)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002340{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002341 struct hlua_socket *socket;
Willy Tarreau5321da92022-05-06 11:57:34 +02002342 struct hlua_csk_ctx *ctx;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002343 struct xref *peer;
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002344 struct hlua *hlua;
2345
2346 /* Get hlua struct, or NULL if we execute from main lua state */
2347 hlua = hlua_gethlua(L);
2348 if (!hlua)
2349 return 0;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002350
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002351 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002352
2353 /* Check if we run on the same thread than the xreator thread.
2354 * We cannot access to the socket if the thread is different.
2355 */
2356 if (socket->tid != tid)
2357 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2358
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002359 peer = xref_get_peer_and_lock(&socket->xref);
2360 if (!peer)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002361 return 0;
Willy Tarreauf31af932020-01-14 09:59:38 +01002362
2363 hlua->gc_count--;
Willy Tarreau5321da92022-05-06 11:57:34 +02002364 ctx = container_of(peer, struct hlua_csk_ctx, xref);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002365
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002366 /* Set the flag which destroy the session. */
Willy Tarreau5321da92022-05-06 11:57:34 +02002367 ctx->die = 1;
2368 appctx_wakeup(ctx->appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002369
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002370 /* Remove all reference between the Lua stack and the coroutine stream. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002371 xref_disconnect(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002372 return 0;
2373}
2374
sada05ed3302018-05-11 11:48:18 -07002375/* The close function calls close_helper.
2376 */
2377__LJMP static int hlua_socket_close(lua_State *L)
2378{
2379 MAY_LJMP(check_args(L, 1, "close"));
2380 return hlua_socket_close_helper(L);
2381}
2382
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002383/* This Lua function assumes that the stack contain three parameters.
2384 * 1 - USERDATA containing a struct socket
2385 * 2 - INTEGER with values of the macro defined below
2386 * If the integer is -1, we must read at most one line.
2387 * If the integer is -2, we ust read all the data until the
2388 * end of the stream.
2389 * If the integer is positive value, we must read a number of
2390 * bytes corresponding to this value.
2391 */
2392#define HLSR_READ_LINE (-1)
2393#define HLSR_READ_ALL (-2)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002394__LJMP static int hlua_socket_receive_yield(struct lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002395{
2396 struct hlua_socket *socket = MAY_LJMP(hlua_checksocket(L, 1));
2397 int wanted = lua_tointeger(L, 2);
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002398 struct hlua *hlua;
Willy Tarreau5321da92022-05-06 11:57:34 +02002399 struct hlua_csk_ctx *csk_ctx;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002400 struct appctx *appctx;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02002401 size_t len;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002402 int nblk;
Willy Tarreau206ba832018-06-14 15:27:31 +02002403 const char *blk1;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02002404 size_t len1;
Willy Tarreau206ba832018-06-14 15:27:31 +02002405 const char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02002406 size_t len2;
Thierry FOURNIER00543922015-03-09 18:35:06 +01002407 int skip_at_end = 0;
Willy Tarreau81389672015-03-10 12:03:52 +01002408 struct channel *oc;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002409 struct stream *s;
2410 struct xref *peer;
Thierry FOURNIER8c126c72018-05-25 16:27:44 +02002411 int missing_bytes;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002412
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002413 /* Get hlua struct, or NULL if we execute from main lua state */
2414 hlua = hlua_gethlua(L);
2415
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002416 /* Check if this lua stack is schedulable. */
2417 if (!hlua || !hlua->task)
2418 WILL_LJMP(luaL_error(L, "The 'receive' function is only allowed in "
2419 "'frontend', 'backend' or 'task'"));
2420
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002421 /* Check if we run on the same thread than the xreator thread.
2422 * We cannot access to the socket if the thread is different.
2423 */
2424 if (socket->tid != tid)
2425 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2426
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002427 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002428 peer = xref_get_peer_and_lock(&socket->xref);
2429 if (!peer)
2430 goto no_peer;
Willy Tarreau5321da92022-05-06 11:57:34 +02002431
2432 csk_ctx = container_of(peer, struct hlua_csk_ctx, xref);
2433 appctx = csk_ctx->appctx;
Willy Tarreau0698c802022-05-11 14:09:57 +02002434 s = appctx_strm(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002435
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002436 oc = &s->res;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002437 if (wanted == HLSR_READ_LINE) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002438 /* Read line. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02002439 nblk = co_getline_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002440 if (nblk < 0) /* Connection close. */
2441 goto connection_closed;
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002442 if (nblk == 0) /* No data available. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002443 goto connection_empty;
Thierry FOURNIER00543922015-03-09 18:35:06 +01002444
2445 /* remove final \r\n. */
2446 if (nblk == 1) {
2447 if (blk1[len1-1] == '\n') {
2448 len1--;
2449 skip_at_end++;
2450 if (blk1[len1-1] == '\r') {
2451 len1--;
2452 skip_at_end++;
2453 }
2454 }
2455 }
2456 else {
2457 if (blk2[len2-1] == '\n') {
2458 len2--;
2459 skip_at_end++;
2460 if (blk2[len2-1] == '\r') {
2461 len2--;
2462 skip_at_end++;
2463 }
2464 }
2465 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002466 }
2467
2468 else if (wanted == HLSR_READ_ALL) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002469 /* Read all the available data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02002470 nblk = co_getblk_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002471 if (nblk < 0) /* Connection close. */
2472 goto connection_closed;
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002473 if (nblk == 0) /* No data available. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002474 goto connection_empty;
2475 }
2476
2477 else {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002478 /* Read a block of data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02002479 nblk = co_getblk_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002480 if (nblk < 0) /* Connection close. */
2481 goto connection_closed;
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002482 if (nblk == 0) /* No data available. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002483 goto connection_empty;
2484
Thierry FOURNIER8c126c72018-05-25 16:27:44 +02002485 missing_bytes = wanted - socket->b.n;
2486 if (len1 > missing_bytes) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002487 nblk = 1;
Thierry FOURNIER8c126c72018-05-25 16:27:44 +02002488 len1 = missing_bytes;
2489 } if (nblk == 2 && len1 + len2 > missing_bytes)
2490 len2 = missing_bytes - len1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002491 }
2492
2493 len = len1;
2494
2495 luaL_addlstring(&socket->b, blk1, len1);
2496 if (nblk == 2) {
2497 len += len2;
2498 luaL_addlstring(&socket->b, blk2, len2);
2499 }
2500
2501 /* Consume data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02002502 co_skip(oc, len + skip_at_end);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002503
2504 /* Don't wait anything. */
Thierry FOURNIER7e4ee472018-05-25 15:03:50 +02002505 appctx_wakeup(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002506
2507 /* If the pattern reclaim to read all the data
2508 * in the connection, got out.
2509 */
2510 if (wanted == HLSR_READ_ALL)
2511 goto connection_empty;
Thierry FOURNIER8c126c72018-05-25 16:27:44 +02002512 else if (wanted >= 0 && socket->b.n < wanted)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002513 goto connection_empty;
2514
2515 /* Return result. */
2516 luaL_pushresult(&socket->b);
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002517 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002518 return 1;
2519
2520connection_closed:
2521
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002522 xref_unlock(&socket->xref, peer);
2523
2524no_peer:
2525
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002526 /* If the buffer containds data. */
2527 if (socket->b.n > 0) {
2528 luaL_pushresult(&socket->b);
2529 return 1;
2530 }
2531 lua_pushnil(L);
2532 lua_pushstring(L, "connection closed.");
2533 return 2;
2534
2535connection_empty:
2536
Willy Tarreau5321da92022-05-06 11:57:34 +02002537 if (!notification_new(&hlua->com, &csk_ctx->wake_on_read, hlua->task)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002538 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002539 WILL_LJMP(luaL_error(L, "out of memory"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002540 }
2541 xref_unlock(&socket->xref, peer);
Willy Tarreau9635e032018-10-16 17:52:55 +02002542 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_receive_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002543 return 0;
2544}
2545
Tim Duesterhusb33754c2018-01-04 19:32:14 +01002546/* This Lua function gets two parameters. The first one can be string
2547 * or a number. If the string is "*l", the user requires one line. If
2548 * the string is "*a", the user requires all the contents of the stream.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002549 * If the value is a number, the user require a number of bytes equal
2550 * to the value. The default value is "*l" (a line).
2551 *
Tim Duesterhusb33754c2018-01-04 19:32:14 +01002552 * This parameter with a variable type is converted in integer. This
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002553 * integer takes this values:
2554 * -1 : read a line
2555 * -2 : read all the stream
Tim Duesterhusb33754c2018-01-04 19:32:14 +01002556 * >0 : amount of bytes.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002557 *
Tim Duesterhusb33754c2018-01-04 19:32:14 +01002558 * The second parameter is optional. It contains a string that must be
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002559 * concatenated with the read data.
2560 */
2561__LJMP static int hlua_socket_receive(struct lua_State *L)
2562{
2563 int wanted = HLSR_READ_LINE;
2564 const char *pattern;
Christopher Fauletc31b2002021-05-03 10:11:13 +02002565 int lastarg, type;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002566 char *error;
2567 size_t len;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002568 struct hlua_socket *socket;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002569
2570 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
2571 WILL_LJMP(luaL_error(L, "The 'receive' function requires between 1 and 3 arguments."));
2572
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002573 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002574
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002575 /* Check if we run on the same thread than the xreator thread.
2576 * We cannot access to the socket if the thread is different.
2577 */
2578 if (socket->tid != tid)
2579 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2580
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002581 /* check for pattern. */
2582 if (lua_gettop(L) >= 2) {
2583 type = lua_type(L, 2);
2584 if (type == LUA_TSTRING) {
2585 pattern = lua_tostring(L, 2);
2586 if (strcmp(pattern, "*a") == 0)
2587 wanted = HLSR_READ_ALL;
2588 else if (strcmp(pattern, "*l") == 0)
2589 wanted = HLSR_READ_LINE;
2590 else {
2591 wanted = strtoll(pattern, &error, 10);
2592 if (*error != '\0')
2593 WILL_LJMP(luaL_error(L, "Unsupported pattern."));
2594 }
2595 }
2596 else if (type == LUA_TNUMBER) {
2597 wanted = lua_tointeger(L, 2);
2598 if (wanted < 0)
2599 WILL_LJMP(luaL_error(L, "Unsupported size."));
2600 }
2601 }
2602
2603 /* Set pattern. */
2604 lua_pushinteger(L, wanted);
Tim Duesterhusc6e377e2018-01-04 19:32:13 +01002605
2606 /* Check if we would replace the top by itself. */
2607 if (lua_gettop(L) != 2)
2608 lua_replace(L, 2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002609
Christopher Fauletc31b2002021-05-03 10:11:13 +02002610 /* Save index of the top of the stack because since buffers are used, it
2611 * may change
2612 */
2613 lastarg = lua_gettop(L);
2614
Tim Duesterhusb33754c2018-01-04 19:32:14 +01002615 /* init buffer, and fill it with prefix. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002616 luaL_buffinit(L, &socket->b);
2617
2618 /* Check prefix. */
Christopher Fauletc31b2002021-05-03 10:11:13 +02002619 if (lastarg >= 3) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002620 if (lua_type(L, 3) != LUA_TSTRING)
2621 WILL_LJMP(luaL_error(L, "Expect a 'string' for the prefix"));
2622 pattern = lua_tolstring(L, 3, &len);
2623 luaL_addlstring(&socket->b, pattern, len);
2624 }
2625
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002626 return __LJMP(hlua_socket_receive_yield(L, 0, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002627}
2628
2629/* Write the Lua input string in the output buffer.
Mark Lakes22154b42018-01-29 14:38:40 -08002630 * This function returns a yield if no space is available.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002631 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002632static int hlua_socket_write_yield(struct lua_State *L,int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002633{
2634 struct hlua_socket *socket;
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002635 struct hlua *hlua;
Willy Tarreau5321da92022-05-06 11:57:34 +02002636 struct hlua_csk_ctx *csk_ctx;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002637 struct appctx *appctx;
2638 size_t buf_len;
2639 const char *buf;
2640 int len;
2641 int send_len;
2642 int sent;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002643 struct xref *peer;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002644 struct stream *s;
Willy Tarreau3e7be362022-05-27 10:35:27 +02002645 struct stconn *sc;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002646
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002647 /* Get hlua struct, or NULL if we execute from main lua state */
2648 hlua = hlua_gethlua(L);
2649
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002650 /* Check if this lua stack is schedulable. */
2651 if (!hlua || !hlua->task)
2652 WILL_LJMP(luaL_error(L, "The 'write' function is only allowed in "
2653 "'frontend', 'backend' or 'task'"));
2654
2655 /* Get object */
2656 socket = MAY_LJMP(hlua_checksocket(L, 1));
2657 buf = MAY_LJMP(luaL_checklstring(L, 2, &buf_len));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002658 sent = MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002659
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002660 /* Check if we run on the same thread than the xreator thread.
2661 * We cannot access to the socket if the thread is different.
2662 */
2663 if (socket->tid != tid)
2664 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2665
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002666 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002667 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002668 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002669 lua_pushinteger(L, -1);
2670 return 1;
2671 }
Willy Tarreau5321da92022-05-06 11:57:34 +02002672
2673 csk_ctx = container_of(peer, struct hlua_csk_ctx, xref);
2674 appctx = csk_ctx->appctx;
Willy Tarreauc12b3212022-05-27 11:08:15 +02002675 sc = appctx_sc(appctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02002676 s = __sc_strm(sc);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002677
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002678 /* Check for connection close. */
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002679 if (channel_output_closed(&s->req)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002680 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002681 lua_pushinteger(L, -1);
2682 return 1;
2683 }
2684
2685 /* Update the input buffer data. */
2686 buf += sent;
2687 send_len = buf_len - sent;
2688
2689 /* All the data are sent. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002690 if (sent >= buf_len) {
2691 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002692 return 1; /* Implicitly return the length sent. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002693 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002694
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002695 /* Check if the buffer is available because HAProxy doesn't allocate
Thierry FOURNIER486d52a2015-03-09 17:51:43 +01002696 * the request buffer if its not required.
2697 */
Willy Tarreauc9fa0482018-07-10 17:43:27 +02002698 if (s->req.buf.size == 0) {
Willy Tarreau3e7be362022-05-27 10:35:27 +02002699 if (!sc_alloc_ibuf(sc, &appctx->buffer_wait))
Christopher Faulet33834b12016-12-19 09:29:06 +01002700 goto hlua_socket_write_yield_return;
Thierry FOURNIER486d52a2015-03-09 17:51:43 +01002701 }
2702
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002703 /* Check for available space. */
Willy Tarreauc9fa0482018-07-10 17:43:27 +02002704 len = b_room(&s->req.buf);
Christopher Faulet33834b12016-12-19 09:29:06 +01002705 if (len <= 0) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002706 goto hlua_socket_write_yield_return;
Christopher Faulet33834b12016-12-19 09:29:06 +01002707 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002708
2709 /* send data */
2710 if (len < send_len)
2711 send_len = len;
Thierry FOURNIER66b89192018-05-27 01:14:47 +02002712 len = ci_putblk(&s->req, buf, send_len);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002713
2714 /* "Not enough space" (-1), "Buffer too little to contain
2715 * the data" (-2) are not expected because the available length
2716 * is tested.
2717 * Other unknown error are also not expected.
2718 */
2719 if (len <= 0) {
Willy Tarreaubc18da12015-03-13 14:00:47 +01002720 if (len == -1)
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002721 s->req.flags |= CF_WAKE_WRITE;
Willy Tarreaubc18da12015-03-13 14:00:47 +01002722
sada05ed3302018-05-11 11:48:18 -07002723 MAY_LJMP(hlua_socket_close_helper(L));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002724 lua_pop(L, 1);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002725 lua_pushinteger(L, -1);
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002726 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002727 return 1;
2728 }
2729
2730 /* update buffers. */
Thierry FOURNIER101b9762018-05-27 01:27:40 +02002731 appctx_wakeup(appctx);
Willy Tarreaude70fa12015-09-26 11:25:05 +02002732
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002733 /* Update length sent. */
2734 lua_pop(L, 1);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002735 lua_pushinteger(L, sent + len);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002736
2737 /* All the data buffer is sent ? */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002738 if (sent + len >= buf_len) {
2739 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002740 return 1;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002741 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002742
2743hlua_socket_write_yield_return:
Willy Tarreau5321da92022-05-06 11:57:34 +02002744 if (!notification_new(&hlua->com, &csk_ctx->wake_on_write, hlua->task)) {
Thierry FOURNIERba42fcd2018-05-27 00:59:48 +02002745 xref_unlock(&socket->xref, peer);
2746 WILL_LJMP(luaL_error(L, "out of memory"));
2747 }
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002748 xref_unlock(&socket->xref, peer);
Willy Tarreau9635e032018-10-16 17:52:55 +02002749 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_write_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002750 return 0;
2751}
2752
2753/* This function initiate the send of data. It just check the input
2754 * parameters and push an integer in the Lua stack that contain the
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002755 * amount of data written to the buffer. This is used by the function
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002756 * "hlua_socket_write_yield" that can yield.
2757 *
2758 * The Lua function gets between 3 and 4 parameters. The first one is
2759 * the associated object. The second is a string buffer. The third is
2760 * a facultative integer that represents where is the buffer position
2761 * of the start of the data that can send. The first byte is the
2762 * position "1". The default value is "1". The fourth argument is a
2763 * facultative integer that represents where is the buffer position
2764 * of the end of the data that can send. The default is the last byte.
2765 */
2766static int hlua_socket_send(struct lua_State *L)
2767{
2768 int i;
2769 int j;
2770 const char *buf;
2771 size_t buf_len;
2772
2773 /* Check number of arguments. */
2774 if (lua_gettop(L) < 2 || lua_gettop(L) > 4)
2775 WILL_LJMP(luaL_error(L, "'send' needs between 2 and 4 arguments"));
2776
2777 /* Get the string. */
2778 buf = MAY_LJMP(luaL_checklstring(L, 2, &buf_len));
2779
2780 /* Get and check j. */
2781 if (lua_gettop(L) == 4) {
2782 j = MAY_LJMP(luaL_checkinteger(L, 4));
2783 if (j < 0)
2784 j = buf_len + j + 1;
2785 if (j > buf_len)
2786 j = buf_len + 1;
2787 lua_pop(L, 1);
2788 }
2789 else
2790 j = buf_len;
2791
2792 /* Get and check i. */
2793 if (lua_gettop(L) == 3) {
2794 i = MAY_LJMP(luaL_checkinteger(L, 3));
2795 if (i < 0)
2796 i = buf_len + i + 1;
2797 if (i > buf_len)
2798 i = buf_len + 1;
2799 lua_pop(L, 1);
2800 } else
2801 i = 1;
2802
2803 /* Check bth i and j. */
2804 if (i > j) {
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002805 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002806 return 1;
2807 }
2808 if (i == 0 && j == 0) {
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002809 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002810 return 1;
2811 }
2812 if (i == 0)
2813 i = 1;
2814 if (j == 0)
2815 j = 1;
2816
2817 /* Pop the string. */
2818 lua_pop(L, 1);
2819
2820 /* Update the buffer length. */
2821 buf += i - 1;
2822 buf_len = j - i + 1;
2823 lua_pushlstring(L, buf, buf_len);
2824
2825 /* This unsigned is used to remember the amount of sent data. */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002826 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002827
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002828 return MAY_LJMP(hlua_socket_write_yield(L, 0, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002829}
2830
Willy Tarreau22b0a682015-06-17 19:43:49 +02002831#define SOCKET_INFO_MAX_LEN sizeof("[0000:0000:0000:0000:0000:0000:0000:0000]:12345")
Christopher Faulete6465b32021-10-22 15:36:08 +02002832__LJMP static inline int hlua_socket_info(struct lua_State *L, const struct sockaddr_storage *addr)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002833{
2834 static char buffer[SOCKET_INFO_MAX_LEN];
2835 int ret;
2836 int len;
2837 char *p;
2838
2839 ret = addr_to_str(addr, buffer+1, SOCKET_INFO_MAX_LEN-1);
2840 if (ret <= 0) {
2841 lua_pushnil(L);
2842 return 1;
2843 }
2844
2845 if (ret == AF_UNIX) {
2846 lua_pushstring(L, buffer+1);
2847 return 1;
2848 }
2849 else if (ret == AF_INET6) {
2850 buffer[0] = '[';
2851 len = strlen(buffer);
2852 buffer[len] = ']';
2853 len++;
2854 buffer[len] = ':';
2855 len++;
2856 p = buffer;
2857 }
2858 else if (ret == AF_INET) {
2859 p = buffer + 1;
2860 len = strlen(p);
2861 p[len] = ':';
2862 len++;
2863 }
2864 else {
2865 lua_pushnil(L);
2866 return 1;
2867 }
2868
2869 if (port_to_str(addr, p + len, SOCKET_INFO_MAX_LEN-1 - len) <= 0) {
2870 lua_pushnil(L);
2871 return 1;
2872 }
2873
2874 lua_pushstring(L, p);
2875 return 1;
2876}
2877
2878/* Returns information about the peer of the connection. */
2879__LJMP static int hlua_socket_getpeername(struct lua_State *L)
2880{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002881 struct hlua_socket *socket;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002882 struct xref *peer;
2883 struct appctx *appctx;
Willy Tarreau3e7be362022-05-27 10:35:27 +02002884 struct stconn *sc;
Christopher Faulet16f16af2021-10-27 09:34:56 +02002885 const struct sockaddr_storage *dst;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002886 int ret;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002887
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002888 MAY_LJMP(check_args(L, 1, "getpeername"));
2889
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002890 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002891
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002892 /* Check if we run on the same thread than the xreator thread.
2893 * We cannot access to the socket if the thread is different.
2894 */
2895 if (socket->tid != tid)
2896 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2897
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002898 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002899 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002900 if (!peer) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002901 lua_pushnil(L);
2902 return 1;
2903 }
Willy Tarreau5321da92022-05-06 11:57:34 +02002904
2905 appctx = container_of(peer, struct hlua_csk_ctx, xref)->appctx;
Willy Tarreauc12b3212022-05-27 11:08:15 +02002906 sc = appctx_sc(appctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02002907 dst = sc_dst(sc_opposite(sc));
Christopher Faulet16f16af2021-10-27 09:34:56 +02002908 if (!dst) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002909 xref_unlock(&socket->xref, peer);
Willy Tarreaua71f6422016-11-16 17:00:14 +01002910 lua_pushnil(L);
2911 return 1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002912 }
2913
Christopher Faulet16f16af2021-10-27 09:34:56 +02002914 ret = MAY_LJMP(hlua_socket_info(L, dst));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002915 xref_unlock(&socket->xref, peer);
2916 return ret;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002917}
2918
2919/* Returns information about my connection side. */
2920static int hlua_socket_getsockname(struct lua_State *L)
2921{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002922 struct hlua_socket *socket;
2923 struct connection *conn;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002924 struct appctx *appctx;
2925 struct xref *peer;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002926 struct stream *s;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002927 int ret;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002928
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002929 MAY_LJMP(check_args(L, 1, "getsockname"));
2930
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002931 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002932
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002933 /* Check if we run on the same thread than the xreator thread.
2934 * We cannot access to the socket if the thread is different.
2935 */
2936 if (socket->tid != tid)
2937 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2938
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002939 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002940 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002941 if (!peer) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002942 lua_pushnil(L);
2943 return 1;
2944 }
Willy Tarreau5321da92022-05-06 11:57:34 +02002945
2946 appctx = container_of(peer, struct hlua_csk_ctx, xref)->appctx;
Willy Tarreau0698c802022-05-11 14:09:57 +02002947 s = appctx_strm(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002948
Willy Tarreaufd9417b2022-05-18 16:23:22 +02002949 conn = sc_conn(s->scb);
Willy Tarreau5a0b25d2019-07-18 18:01:14 +02002950 if (!conn || !conn_get_src(conn)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002951 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002952 lua_pushnil(L);
2953 return 1;
2954 }
2955
Willy Tarreau9da9a6f2019-07-17 14:49:44 +02002956 ret = hlua_socket_info(L, conn->src);
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002957 xref_unlock(&socket->xref, peer);
2958 return ret;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002959}
2960
2961/* This struct define the applet. */
Willy Tarreau30576452015-04-13 13:50:30 +02002962static struct applet update_applet = {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002963 .obj_type = OBJ_TYPE_APPLET,
2964 .name = "<LUA_TCP>",
2965 .fct = hlua_socket_handler,
Christopher Faulet5f35a3e2022-05-12 15:31:05 +02002966 .init = hlua_socket_init,
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002967 .release = hlua_socket_release,
2968};
2969
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002970__LJMP static int hlua_socket_connect_yield(struct lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002971{
2972 struct hlua_socket *socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002973 struct hlua *hlua;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002974 struct xref *peer;
Willy Tarreau5321da92022-05-06 11:57:34 +02002975 struct hlua_csk_ctx *csk_ctx;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002976 struct appctx *appctx;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002977 struct stream *s;
2978
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002979 /* Get hlua struct, or NULL if we execute from main lua state */
2980 hlua = hlua_gethlua(L);
2981 if (!hlua)
2982 return 0;
2983
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002984 /* Check if we run on the same thread than the xreator thread.
2985 * We cannot access to the socket if the thread is different.
2986 */
2987 if (socket->tid != tid)
2988 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2989
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002990 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002991 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002992 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002993 lua_pushnil(L);
2994 lua_pushstring(L, "Can't connect");
2995 return 2;
2996 }
Willy Tarreau5321da92022-05-06 11:57:34 +02002997
2998 csk_ctx = container_of(peer, struct hlua_csk_ctx, xref);
2999 appctx = csk_ctx->appctx;
Willy Tarreau0698c802022-05-11 14:09:57 +02003000 s = appctx_strm(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003001
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02003002 /* Check if we run on the same thread than the xreator thread.
3003 * We cannot access to the socket if the thread is different.
3004 */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02003005 if (socket->tid != tid) {
3006 xref_unlock(&socket->xref, peer);
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02003007 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02003008 }
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02003009
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003010 /* Check for connection close. */
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003011 if (!hlua || channel_output_closed(&s->req)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02003012 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003013 lua_pushnil(L);
3014 lua_pushstring(L, "Can't connect");
3015 return 2;
3016 }
3017
Willy Tarreau8e7c6e62022-05-18 17:58:02 +02003018 appctx = __sc_appctx(s->scf);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003019
3020 /* Check for connection established. */
Willy Tarreau5321da92022-05-06 11:57:34 +02003021 if (csk_ctx->connected) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02003022 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003023 lua_pushinteger(L, 1);
3024 return 1;
3025 }
3026
Willy Tarreau5321da92022-05-06 11:57:34 +02003027 if (!notification_new(&hlua->com, &csk_ctx->wake_on_write, hlua->task)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02003028 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003029 WILL_LJMP(luaL_error(L, "out of memory error"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02003030 }
3031 xref_unlock(&socket->xref, peer);
Willy Tarreau9635e032018-10-16 17:52:55 +02003032 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_connect_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003033 return 0;
3034}
3035
3036/* This function fail or initite the connection. */
3037__LJMP static int hlua_socket_connect(struct lua_State *L)
3038{
3039 struct hlua_socket *socket;
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02003040 int port = -1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003041 const char *ip;
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01003042 struct hlua *hlua;
Willy Tarreau5321da92022-05-06 11:57:34 +02003043 struct hlua_csk_ctx *csk_ctx;
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01003044 struct appctx *appctx;
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02003045 int low, high;
3046 struct sockaddr_storage *addr;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003047 struct xref *peer;
Willy Tarreau3e7be362022-05-27 10:35:27 +02003048 struct stconn *sc;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003049 struct stream *s;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003050
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02003051 if (lua_gettop(L) < 2)
3052 WILL_LJMP(luaL_error(L, "connect: need at least 2 arguments"));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003053
3054 /* Get args. */
3055 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02003056
3057 /* Check if we run on the same thread than the xreator thread.
3058 * We cannot access to the socket if the thread is different.
3059 */
3060 if (socket->tid != tid)
3061 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
3062
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003063 ip = MAY_LJMP(luaL_checkstring(L, 2));
Tim Duesterhus6edab862018-01-06 19:04:45 +01003064 if (lua_gettop(L) >= 3) {
3065 luaL_Buffer b;
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02003066 port = MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003067
Tim Duesterhus6edab862018-01-06 19:04:45 +01003068 /* Force the ip to end with a colon, to support IPv6 addresses
3069 * that are not enclosed within square brackets.
3070 */
3071 if (port > 0) {
3072 luaL_buffinit(L, &b);
3073 luaL_addstring(&b, ip);
3074 luaL_addchar(&b, ':');
3075 luaL_pushresult(&b);
3076 ip = lua_tolstring(L, lua_gettop(L), NULL);
3077 }
3078 }
3079
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003080 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02003081 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003082 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003083 lua_pushnil(L);
3084 return 1;
3085 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003086
3087 /* Parse ip address. */
Willy Tarreau5fc93282020-09-16 18:25:03 +02003088 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 +02003089 if (!addr) {
3090 xref_unlock(&socket->xref, peer);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02003091 WILL_LJMP(luaL_error(L, "connect: cannot parse destination address '%s'", ip));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02003092 }
Willy Tarreau9da9a6f2019-07-17 14:49:44 +02003093
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003094 /* Set port. */
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02003095 if (low == 0) {
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02003096 if (addr->ss_family == AF_INET) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02003097 if (port == -1) {
3098 xref_unlock(&socket->xref, peer);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02003099 WILL_LJMP(luaL_error(L, "connect: port missing"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02003100 }
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02003101 ((struct sockaddr_in *)addr)->sin_port = htons(port);
3102 } else if (addr->ss_family == AF_INET6) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02003103 if (port == -1) {
3104 xref_unlock(&socket->xref, peer);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02003105 WILL_LJMP(luaL_error(L, "connect: port missing"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02003106 }
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02003107 ((struct sockaddr_in6 *)addr)->sin6_port = htons(port);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02003108 }
3109 }
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02003110
Willy Tarreau5321da92022-05-06 11:57:34 +02003111 csk_ctx = container_of(peer, struct hlua_csk_ctx, xref);
3112 appctx = csk_ctx->appctx;
Willy Tarreauc12b3212022-05-27 11:08:15 +02003113 sc = appctx_sc(appctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02003114 s = __sc_strm(sc);
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02003115
Willy Tarreau3e7be362022-05-27 10:35:27 +02003116 if (!sockaddr_alloc(&sc_opposite(sc)->dst, addr, sizeof(*addr))) {
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02003117 xref_unlock(&socket->xref, peer);
3118 WILL_LJMP(luaL_error(L, "connect: internal error"));
3119 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003120
Thierry Fournier4234dbd2020-11-28 13:18:23 +01003121 /* Get hlua struct, or NULL if we execute from main lua state */
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01003122 hlua = hlua_gethlua(L);
Thierry Fournier4234dbd2020-11-28 13:18:23 +01003123 if (!hlua)
3124 return 0;
Willy Tarreaubdc97a82015-08-24 15:42:28 +02003125
3126 /* inform the stream that we want to be notified whenever the
3127 * connection completes.
3128 */
Willy Tarreau90e8b452022-05-25 18:21:43 +02003129 applet_need_more_data(appctx);
Willy Tarreau4164eb92022-05-25 15:42:03 +02003130 applet_have_more_data(appctx);
Thierry FOURNIER8c8fbbe2015-09-26 17:02:35 +02003131 appctx_wakeup(appctx);
Willy Tarreaubdc97a82015-08-24 15:42:28 +02003132
Willy Tarreauf31af932020-01-14 09:59:38 +01003133 hlua->gc_count++;
Thierry FOURNIER7c39ab42015-09-27 22:53:33 +02003134
Willy Tarreau5321da92022-05-06 11:57:34 +02003135 if (!notification_new(&hlua->com, &csk_ctx->wake_on_write, hlua->task)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02003136 xref_unlock(&socket->xref, peer);
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01003137 WILL_LJMP(luaL_error(L, "out of memory"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02003138 }
3139 xref_unlock(&socket->xref, peer);
PiBa-NL706d5ee2018-05-05 23:51:42 +02003140
3141 task_wakeup(s->task, TASK_WOKEN_INIT);
3142 /* Return yield waiting for connection. */
3143
Willy Tarreau9635e032018-10-16 17:52:55 +02003144 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_connect_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003145
3146 return 0;
3147}
3148
Baptiste Assmann84bb4932015-03-02 21:40:06 +01003149#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003150__LJMP static int hlua_socket_connect_ssl(struct lua_State *L)
3151{
3152 struct hlua_socket *socket;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003153 struct xref *peer;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003154 struct stream *s;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003155
3156 MAY_LJMP(check_args(L, 3, "connect_ssl"));
3157 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003158
3159 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02003160 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003161 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003162 lua_pushnil(L);
3163 return 1;
3164 }
Willy Tarreau5321da92022-05-06 11:57:34 +02003165
Willy Tarreau0698c802022-05-11 14:09:57 +02003166 s = appctx_strm(container_of(peer, struct hlua_csk_ctx, xref)->appctx);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003167
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +01003168 s->target = &socket_ssl->obj_type;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02003169 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003170 return MAY_LJMP(hlua_socket_connect(L));
3171}
Baptiste Assmann84bb4932015-03-02 21:40:06 +01003172#endif
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003173
3174__LJMP static int hlua_socket_setoption(struct lua_State *L)
3175{
3176 return 0;
3177}
3178
3179__LJMP static int hlua_socket_settimeout(struct lua_State *L)
3180{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003181 struct hlua_socket *socket;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003182 int tmout;
Mark Lakes56cc1252018-03-27 09:48:06 +02003183 double dtmout;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003184 struct xref *peer;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003185 struct stream *s;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003186
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003187 MAY_LJMP(check_args(L, 2, "settimeout"));
3188
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003189 socket = MAY_LJMP(hlua_checksocket(L, 1));
Mark Lakes56cc1252018-03-27 09:48:06 +02003190
Cyril Bonté7ee465f2018-08-19 22:08:50 +02003191 /* convert the timeout to millis */
3192 dtmout = MAY_LJMP(luaL_checknumber(L, 2)) * 1000;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003193
Thierry Fournier17a921b2018-03-08 09:59:02 +01003194 /* Check for negative values */
Mark Lakes56cc1252018-03-27 09:48:06 +02003195 if (dtmout < 0)
Thierry Fournier17a921b2018-03-08 09:59:02 +01003196 WILL_LJMP(luaL_error(L, "settimeout: cannot set negatives values"));
3197
Mark Lakes56cc1252018-03-27 09:48:06 +02003198 if (dtmout > INT_MAX) /* overflow check */
Cyril Bonté7ee465f2018-08-19 22:08:50 +02003199 WILL_LJMP(luaL_error(L, "settimeout: cannot set values larger than %d ms", INT_MAX));
Mark Lakes56cc1252018-03-27 09:48:06 +02003200
3201 tmout = MS_TO_TICKS((int)dtmout);
Cyril Bonté7ee465f2018-08-19 22:08:50 +02003202 if (tmout == 0)
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05003203 tmout++; /* very small timeouts are adjusted to a minimum of 1ms */
Mark Lakes56cc1252018-03-27 09:48:06 +02003204
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02003205 /* Check if we run on the same thread than the xreator thread.
3206 * We cannot access to the socket if the thread is different.
3207 */
3208 if (socket->tid != tid)
3209 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
3210
Mark Lakes56cc1252018-03-27 09:48:06 +02003211 /* check for connection break. If some data were read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02003212 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003213 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003214 hlua_pusherror(L, "socket: not yet initialised, you can't set timeouts.");
3215 WILL_LJMP(lua_error(L));
3216 return 0;
3217 }
Willy Tarreau5321da92022-05-06 11:57:34 +02003218
Willy Tarreau0698c802022-05-11 14:09:57 +02003219 s = appctx_strm(container_of(peer, struct hlua_csk_ctx, xref)->appctx);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003220
Cyril Bonté7bb63452018-08-17 23:51:02 +02003221 s->sess->fe->timeout.connect = tmout;
Christopher Faulet5aaacfb2023-02-15 08:13:33 +01003222 s->scf->ioto = tmout;
3223 s->scb->ioto = tmout;
Cyril Bonté7bb63452018-08-17 23:51:02 +02003224
3225 s->task->expire = tick_add_ifset(now_ms, tmout);
3226 task_queue(s->task);
3227
Thierry FOURNIER952939d2017-09-01 14:17:32 +02003228 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003229
Thierry Fourniere9636f12018-03-08 09:54:32 +01003230 lua_pushinteger(L, 1);
Tim Duesterhus119a5f12018-01-06 19:16:25 +01003231 return 1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003232}
3233
3234__LJMP static int hlua_socket_new(lua_State *L)
3235{
3236 struct hlua_socket *socket;
Willy Tarreau5321da92022-05-06 11:57:34 +02003237 struct hlua_csk_ctx *ctx;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003238 struct appctx *appctx;
3239
3240 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003241 if (!lua_checkstack(L, 3)) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003242 hlua_pusherror(L, "socket: full stack");
3243 goto out_fail_conf;
3244 }
3245
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003246 /* Create the object: obj[0] = userdata. */
3247 lua_newtable(L);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003248 socket = MAY_LJMP(lua_newuserdata(L, sizeof(*socket)));
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003249 lua_rawseti(L, -2, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003250 memset(socket, 0, sizeof(*socket));
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02003251 socket->tid = tid;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003252
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05003253 /* Check if the various memory pools are initialized. */
Willy Tarreaubafbe012017-11-24 17:34:44 +01003254 if (!pool_head_stream || !pool_head_buffer) {
Thierry FOURNIER4a6170c2015-03-09 17:07:10 +01003255 hlua_pusherror(L, "socket: uninitialized pools.");
3256 goto out_fail_conf;
3257 }
3258
Willy Tarreau87b09662015-04-03 00:22:06 +02003259 /* Pop a class stream metatable and affect it to the userdata. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003260 lua_rawgeti(L, LUA_REGISTRYINDEX, class_socket_ref);
3261 lua_setmetatable(L, -2);
3262
Willy Tarreaud420a972015-04-06 00:39:18 +02003263 /* Create the applet context */
Christopher Faulet6095d572022-05-16 17:09:48 +02003264 appctx = appctx_new_here(&update_applet, NULL);
Willy Tarreau61cf7c82015-04-06 00:48:33 +02003265 if (!appctx) {
3266 hlua_pusherror(L, "socket: out of memory");
Christopher Fauleta9e8b392022-03-23 11:01:09 +01003267 goto out_fail_conf;
Willy Tarreau61cf7c82015-04-06 00:48:33 +02003268 }
Willy Tarreau5321da92022-05-06 11:57:34 +02003269 ctx = applet_reserve_svcctx(appctx, sizeof(*ctx));
3270 ctx->connected = 0;
Willy Tarreau5321da92022-05-06 11:57:34 +02003271 ctx->die = 0;
3272 LIST_INIT(&ctx->wake_on_write);
3273 LIST_INIT(&ctx->wake_on_read);
Willy Tarreaub2bf8332015-04-04 15:58:58 +02003274
Christopher Faulet5f35a3e2022-05-12 15:31:05 +02003275 if (appctx_init(appctx) == -1) {
3276 hlua_pusherror(L, "socket: fail to init applet.");
Christopher Faulet13a35e52021-12-20 15:34:16 +01003277 goto out_fail_appctx;
3278 }
3279
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003280 /* Initialise cross reference between stream and Lua socket object. */
Willy Tarreau5321da92022-05-06 11:57:34 +02003281 xref_create(&socket->xref, &ctx->xref);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003282 return 1;
3283
Christopher Faulet13a35e52021-12-20 15:34:16 +01003284 out_fail_appctx:
Christopher Faulet5f35a3e2022-05-12 15:31:05 +02003285 appctx_free_on_early_error(appctx);
Willy Tarreaud420a972015-04-06 00:39:18 +02003286 out_fail_conf:
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003287 WILL_LJMP(lua_error(L));
3288 return 0;
3289}
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01003290
3291/*
3292 *
3293 *
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003294 * Class Channel
3295 *
3296 *
3297 */
3298
3299/* Returns the struct hlua_channel join to the class channel in the
3300 * stack entry "ud" or throws an argument error.
3301 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01003302__LJMP static struct channel *hlua_checkchannel(lua_State *L, int ud)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003303{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003304 return MAY_LJMP(hlua_checkudata(L, ud, class_channel_ref));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003305}
3306
Willy Tarreau47860ed2015-03-10 14:07:50 +01003307/* Pushes the channel onto the top of the stack. If the stask does not have a
3308 * free slots, the function fails and returns 0;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003309 */
Willy Tarreau2a71af42015-03-10 13:51:50 +01003310static int hlua_channel_new(lua_State *L, struct channel *channel)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003311{
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003312 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003313 if (!lua_checkstack(L, 3))
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003314 return 0;
3315
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003316 lua_newtable(L);
Willy Tarreau47860ed2015-03-10 14:07:50 +01003317 lua_pushlightuserdata(L, channel);
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003318 lua_rawseti(L, -2, 0);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003319
3320 /* Pop a class sesison metatable and affect it to the userdata. */
3321 lua_rawgeti(L, LUA_REGISTRYINDEX, class_channel_ref);
3322 lua_setmetatable(L, -2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003323 return 1;
3324}
3325
Christopher Faulet9f55a502020-02-25 15:21:02 +01003326/* Helper function returning a filter attached to a channel at the position <ud>
3327 * in the stack, filling the current offset and length of the filter. If no
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05003328 * filter is attached, NULL is returned and <offset> and <len> are not
Christopher Faulet9f55a502020-02-25 15:21:02 +01003329 * initialized.
3330 */
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003331static 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 +01003332{
3333 struct filter *filter = NULL;
3334
3335 if (lua_getfield(L, ud, "__filter") == LUA_TLIGHTUSERDATA) {
3336 struct hlua_flt_ctx *flt_ctx;
3337
3338 filter = lua_touserdata (L, -1);
3339 flt_ctx = filter->ctx;
3340 if (hlua_filter_from_payload(filter)) {
3341 *offset = flt_ctx->cur_off[CHN_IDX(chn)];
3342 *len = flt_ctx->cur_len[CHN_IDX(chn)];
3343 }
3344 }
3345
3346 lua_pop(L, 1);
3347 return filter;
3348}
3349
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003350/* Copies <len> bytes of data present in the channel's buffer, starting at the
3351* offset <offset>, and put it in a LUA string variable. It is the caller
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003352* responsibility to ensure <len> and <offset> are valid. It always return the
3353* length of the built string. <len> may be 0, in this case, an empty string is
3354* created and 0 is returned.
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003355*/
3356static inline int _hlua_channel_dup(struct channel *chn, lua_State *L, size_t offset, size_t len)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003357{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003358 size_t block1, block2;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003359 luaL_Buffer b;
3360
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003361 block1 = len;
3362 if (block1 > b_contig_data(&chn->buf, b_peek_ofs(&chn->buf, offset)))
3363 block1 = b_contig_data(&chn->buf, b_peek_ofs(&chn->buf, offset));
3364 block2 = len - block1;
3365
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003366 luaL_buffinit(L, &b);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003367 luaL_addlstring(&b, b_peek(&chn->buf, offset), block1);
3368 if (block2)
3369 luaL_addlstring(&b, b_orig(&chn->buf), block2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003370 luaL_pushresult(&b);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003371 return len;
3372}
3373
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003374/* Inserts the string <str> to the channel's buffer at the offset <offset>. This
3375 * function returns -1 if data cannot be copied. Otherwise, it returns the
3376 * number of bytes copied.
3377 */
3378static int _hlua_channel_insert(struct channel *chn, lua_State *L, struct ist str, size_t offset)
3379{
3380 int ret = 0;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003381
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003382 /* Nothing to do, just return */
3383 if (unlikely(istlen(str) == 0))
3384 goto end;
3385
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003386 if (istlen(str) > c_room(chn)) {
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003387 ret = -1;
3388 goto end;
3389 }
3390 ret = b_insert_blk(&chn->buf, offset, istptr(str), istlen(str));
3391
3392 end:
3393 return ret;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003394}
3395
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003396/* Removes <len> bytes of data at the absolute position <offset>.
3397 */
3398static void _hlua_channel_delete(struct channel *chn, size_t offset, size_t len)
3399{
3400 size_t end = offset + len;
3401
3402 if (b_peek(&chn->buf, end) != b_tail(&chn->buf))
3403 b_move(&chn->buf, b_peek_ofs(&chn->buf, end),
3404 b_data(&chn->buf) - end, -len);
3405 b_sub(&chn->buf, len);
3406}
3407
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003408/* Copies input data in the channel's buffer. It is possible to set a specific
3409 * offset (0 by default) and a length (all remaining input data starting for the
3410 * offset by default). If there is not enough input data and more data can be
3411 * received, this function yields.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003412 *
3413 * From an action, All input data are considered. For a filter, the offset and
3414 * the length of input data to consider are retrieved from the filter context.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003415 */
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003416__LJMP static int hlua_channel_get_data_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003417{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003418 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003419 struct filter *filter;
3420 size_t input, output;
3421 int offset, len;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003422
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003423 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003424
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003425 output = co_data(chn);
3426 input = ci_data(chn);
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003427
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003428 filter = hlua_channel_filter(L, 1, chn, &output, &input);
3429 if (filter && !hlua_filter_from_payload(filter))
3430 WILL_LJMP(lua_error(L));
3431
3432 offset = output;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003433 if (lua_gettop(L) > 1) {
3434 offset = MAY_LJMP(luaL_checkinteger(L, 2));
3435 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02003436 offset = MAX(0, (int)input + offset);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003437 offset += output;
3438 if (offset < output || offset > input + output) {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003439 lua_pushfstring(L, "offset out of range.");
3440 WILL_LJMP(lua_error(L));
3441 }
3442 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003443 len = output + input - offset;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003444 if (lua_gettop(L) == 3) {
3445 len = MAY_LJMP(luaL_checkinteger(L, 3));
3446 if (!len)
3447 goto dup;
3448 if (len == -1)
3449 len = global.tune.bufsize;
3450 if (len < 0) {
3451 lua_pushfstring(L, "length out of range.");
3452 WILL_LJMP(lua_error(L));
3453 }
3454 }
3455
Christopher Faulet0ae2e632023-01-10 15:29:54 +01003456 /* Wait for more data if possible if no length was specified and there
3457 * is no data or not enough data was received.
3458 */
3459 if (!len || offset + len > output + input) {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003460 if (!HLUA_CANT_YIELD(hlua_gethlua(L)) && !channel_input_closed(chn) && channel_may_recv(chn)) {
3461 /* Yield waiting for more data, as requested */
3462 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_get_data_yield, TICK_ETERNITY, 0));
3463 }
Christopher Faulet0ae2e632023-01-10 15:29:54 +01003464
3465 /* Return 'nil' if there is no data and the channel can't receive more data */
3466 if (!len) {
3467 lua_pushnil(L);
3468 return -1;
3469 }
3470
3471 /* Otherwise, return all data */
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003472 len = output + input - offset;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003473 }
3474
3475 dup:
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003476 _hlua_channel_dup(chn, L, offset, len);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003477 return 1;
3478}
3479
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003480/* Copies the first line (including the trailing LF) of input data in the
3481 * channel's buffer. It is possible to set a specific offset (0 by default) and
3482 * a length (all remaining input data starting for the offset by default). If
3483 * there is not enough input data and more data can be received, the function
3484 * yields. If a length is explicitly specified, no more data are
3485 * copied. Otherwise, if no LF is found and more data can be received, this
3486 * function yields.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003487 *
3488 * From an action, All input data are considered. For a filter, the offset and
3489 * the length of input data to consider are retrieved from the filter context.
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003490 */
3491__LJMP static int hlua_channel_get_line_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003492{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003493 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003494 struct filter *filter;
3495 size_t l, input, output;
3496 int offset, len;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003497
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003498 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003499 output = co_data(chn);
3500 input = ci_data(chn);
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003501
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003502 filter = hlua_channel_filter(L, 1, chn, &output, &input);
3503 if (filter && !hlua_filter_from_payload(filter))
3504 WILL_LJMP(lua_error(L));
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003505
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003506 offset = output;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003507 if (lua_gettop(L) > 1) {
3508 offset = MAY_LJMP(luaL_checkinteger(L, 2));
3509 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02003510 offset = MAX(0, (int)input + offset);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003511 offset += output;
3512 if (offset < output || offset > input + output) {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003513 lua_pushfstring(L, "offset out of range.");
3514 WILL_LJMP(lua_error(L));
3515 }
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003516 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003517
3518 len = output + input - offset;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003519 if (lua_gettop(L) == 3) {
3520 len = MAY_LJMP(luaL_checkinteger(L, 3));
3521 if (!len)
3522 goto dup;
3523 if (len == -1)
3524 len = global.tune.bufsize;
3525 if (len < 0) {
3526 lua_pushfstring(L, "length out of range.");
3527 WILL_LJMP(lua_error(L));
3528 }
3529 }
3530
3531 for (l = 0; l < len; l++) {
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003532 if (l + offset >= output + input)
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003533 break;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003534 if (*(b_peek(&chn->buf, offset + l)) == '\n') {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003535 len = l+1;
3536 goto dup;
3537 }
3538 }
3539
Christopher Faulet0ae2e632023-01-10 15:29:54 +01003540 /* Wait for more data if possible if no line is found and no length was
3541 * specified or not enough data was received.
3542 */
3543 if (lua_gettop(L) != 3 || offset + len > output + input) {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003544 if (!HLUA_CANT_YIELD(hlua_gethlua(L)) && !channel_input_closed(chn) && channel_may_recv(chn)) {
3545 /* Yield waiting for more data */
3546 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_get_line_yield, TICK_ETERNITY, 0));
3547 }
Christopher Faulet0ae2e632023-01-10 15:29:54 +01003548
3549 /* Return 'nil' if there is no data and the channel can't receive more data */
3550 if (!len) {
3551 lua_pushnil(L);
3552 return -1;
3553 }
3554
3555 /* Otherwise, return all data */
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003556 len = output + input - offset;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003557 }
3558
3559 dup:
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003560 _hlua_channel_dup(chn, L, offset, len);
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003561 return 1;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003562}
3563
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003564/* [ DEPRECATED ]
3565 *
3566 * Duplicate all input data foud in the channel's buffer. The data are not
3567 * removed from the buffer. This function relies on _hlua_channel_dup().
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003568 *
3569 * From an action, All input data are considered. For a filter, the offset and
3570 * the length of input data to consider are retrieved from the filter context.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003571 */
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003572__LJMP static int hlua_channel_dup(lua_State *L)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003573{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003574 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003575 struct filter *filter;
3576 size_t offset, len;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003577
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003578 MAY_LJMP(check_args(L, 1, "dup"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003579 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003580 if (IS_HTX_STRM(chn_strm(chn))) {
3581 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3582 WILL_LJMP(lua_error(L));
3583 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003584
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003585 offset = co_data(chn);
3586 len = ci_data(chn);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003587
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003588 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3589 if (filter && !hlua_filter_from_payload(filter))
3590 WILL_LJMP(lua_error(L));
3591
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003592 if (!ci_data(chn) && channel_input_closed(chn)) {
3593 lua_pushnil(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003594 return 1;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003595 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003596
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003597 _hlua_channel_dup(chn, L, offset, len);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003598 return 1;
3599}
3600
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003601/* [ DEPRECATED ]
3602 *
3603 * Get all input data foud in the channel's buffer. The data are removed from
3604 * the buffer after the copy. This function relies on _hlua_channel_dup() and
3605 * _hlua_channel_delete().
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003606 *
3607 * From an action, All input data are considered. For a filter, the offset and
3608 * the length of input data to consider are retrieved from the filter context.
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003609 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003610__LJMP static int hlua_channel_get(lua_State *L)
3611{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003612 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003613 struct filter *filter;
3614 size_t offset, len;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003615 int ret;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003616
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003617 MAY_LJMP(check_args(L, 1, "get"));
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003618 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3619 if (IS_HTX_STRM(chn_strm(chn))) {
3620 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3621 WILL_LJMP(lua_error(L));
3622 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003623
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003624 offset = co_data(chn);
3625 len = ci_data(chn);
3626
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003627 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3628 if (filter && !hlua_filter_from_payload(filter))
3629 WILL_LJMP(lua_error(L));
3630
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003631 if (!ci_data(chn) && channel_input_closed(chn)) {
3632 lua_pushnil(L);
3633 return 1;
3634 }
3635
3636 ret = _hlua_channel_dup(chn, L, offset, len);
3637 _hlua_channel_delete(chn, offset, ret);
3638 return 1;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003639}
3640
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003641/* This functions consumes and returns one line. If the channel is closed,
3642 * and the last data does not contains a final '\n', the data are returned
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003643 * without the final '\n'. When no more data are available, it returns nil
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003644 * value.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003645 *
3646 * From an action, All input data are considered. For a filter, the offset and
3647 * the length of input data to consider are retrieved from the filter context.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003648 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003649__LJMP static int hlua_channel_getline_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003650{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003651 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003652 struct filter *filter;
3653 size_t l, offset, len;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003654 int ret;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003655
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003656 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003657
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003658 offset = co_data(chn);
3659 len = ci_data(chn);
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003660
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003661 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3662 if (filter && !hlua_filter_from_payload(filter))
3663 WILL_LJMP(lua_error(L));
3664
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003665 if (!ci_data(chn) && channel_input_closed(chn)) {
3666 lua_pushnil(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003667 return 1;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003668 }
3669
3670 for (l = 0; l < len; l++) {
3671 if (*(b_peek(&chn->buf, offset+l)) == '\n') {
3672 len = l+1;
3673 goto dup;
3674 }
3675 }
3676
3677 if (!HLUA_CANT_YIELD(hlua_gethlua(L)) && !channel_input_closed(chn) && channel_may_recv(chn)) {
3678 /* Yield waiting for more data */
3679 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_getline_yield, TICK_ETERNITY, 0));
3680 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003681
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003682 dup:
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003683 ret = _hlua_channel_dup(chn, L, offset, len);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003684 _hlua_channel_delete(chn, offset, ret);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003685 return 1;
3686}
3687
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003688/* [ DEPRECATED ]
3689 *
3690 * Check arguments for the function "hlua_channel_getline_yield".
3691 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003692__LJMP static int hlua_channel_getline(lua_State *L)
3693{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003694 struct channel *chn;
3695
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003696 MAY_LJMP(check_args(L, 1, "getline"));
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003697 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3698 if (IS_HTX_STRM(chn_strm(chn))) {
3699 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3700 WILL_LJMP(lua_error(L));
3701 }
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003702 return MAY_LJMP(hlua_channel_getline_yield(L, 0, 0));
3703}
3704
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003705/* Retrieves a given amount of input data at the given offset. By default all
3706 * available input data are returned. The offset may be negactive to start from
3707 * the end of input data. The length may be -1 to set it to the maximum buffer
3708 * size.
3709 */
3710__LJMP static int hlua_channel_get_data(lua_State *L)
3711{
3712 struct channel *chn;
3713
3714 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
3715 WILL_LJMP(luaL_error(L, "'data' expects at most 2 arguments"));
3716 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3717 if (IS_HTX_STRM(chn_strm(chn))) {
3718 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3719 WILL_LJMP(lua_error(L));
3720 }
3721 return MAY_LJMP(hlua_channel_get_data_yield(L, 0, 0));
3722}
3723
3724/* Retrieves a given amount of input data at the given offset. By default all
3725 * available input data are returned. The offset may be negactive to start from
3726 * the end of input data. The length may be -1 to set it to the maximum buffer
3727 * size.
3728 */
3729__LJMP static int hlua_channel_get_line(lua_State *L)
3730{
3731 struct channel *chn;
3732
3733 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
3734 WILL_LJMP(luaL_error(L, "'line' expects at most 2 arguments"));
3735 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3736 if (IS_HTX_STRM(chn_strm(chn))) {
3737 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3738 WILL_LJMP(lua_error(L));
3739 }
3740 return MAY_LJMP(hlua_channel_get_line_yield(L, 0, 0));
3741}
3742
3743/* Appends a string into the input side of channel. It returns the length of the
3744 * written string, or -1 if the channel is closed or if the buffer size is too
3745 * little for the data. 0 may be returned if nothing is copied. This function
3746 * does not yield.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003747 *
3748 * For a filter, the context is updated on success.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003749 */
Christopher Faulet23976d92021-08-06 09:59:49 +02003750__LJMP static int hlua_channel_append(lua_State *L)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003751{
Christopher Faulet23976d92021-08-06 09:59:49 +02003752 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003753 struct filter *filter;
Christopher Faulet23976d92021-08-06 09:59:49 +02003754 const char *str;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003755 size_t sz, offset, len;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003756 int ret;
Christopher Faulet23976d92021-08-06 09:59:49 +02003757
3758 MAY_LJMP(check_args(L, 2, "append"));
3759 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003760 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
Christopher Faulet1bb6afa2021-03-08 17:57:53 +01003761 if (IS_HTX_STRM(chn_strm(chn))) {
Thierry Fournier77016da2020-08-15 14:35:51 +02003762 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
Christopher Faulet3f829a42018-12-13 21:56:45 +01003763 WILL_LJMP(lua_error(L));
Thierry Fournier77016da2020-08-15 14:35:51 +02003764 }
Christopher Faulet3f829a42018-12-13 21:56:45 +01003765
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003766 offset = co_data(chn);
3767 len = ci_data(chn);
3768
3769 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3770 if (filter && !hlua_filter_from_payload(filter))
3771 WILL_LJMP(lua_error(L));
3772
3773 ret = _hlua_channel_insert(chn, L, ist2(str, sz), offset);
3774 if (ret > 0 && filter) {
3775 struct hlua_flt_ctx *flt_ctx = filter->ctx;
3776
3777 flt_update_offsets(filter, chn, ret);
3778 flt_ctx->cur_len[CHN_IDX(chn)] += ret;
3779 }
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003780 lua_pushinteger(L, ret);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003781 return 1;
3782}
3783
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003784/* Prepends a string into the input side of channel. It returns the length of the
3785 * written string, or -1 if the channel is closed or if the buffer size is too
3786 * little for the data. 0 may be returned if nothing is copied. This function
3787 * does not yield.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003788 *
3789 * For a filter, the context is updated on success.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003790 */
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003791__LJMP static int hlua_channel_prepend(lua_State *L)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003792{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003793 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003794 struct filter *filter;
Christopher Faulet23976d92021-08-06 09:59:49 +02003795 const char *str;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003796 size_t sz, offset, len;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003797 int ret;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003798
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003799 MAY_LJMP(check_args(L, 2, "prepend"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003800 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003801 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
3802 if (IS_HTX_STRM(chn_strm(chn))) {
3803 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3804 WILL_LJMP(lua_error(L));
3805 }
3806
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003807 offset = co_data(chn);
3808 len = ci_data(chn);
3809
3810 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3811 if (filter && !hlua_filter_from_payload(filter))
3812 WILL_LJMP(lua_error(L));
3813
3814 ret = _hlua_channel_insert(chn, L, ist2(str, sz), offset);
3815 if (ret > 0 && filter) {
3816 struct hlua_flt_ctx *flt_ctx = filter->ctx;
3817
3818 flt_update_offsets(filter, chn, ret);
3819 flt_ctx->cur_len[CHN_IDX(chn)] += ret;
3820 }
3821
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003822 lua_pushinteger(L, ret);
3823 return 1;
3824}
3825
3826/* Inserts a given amount of input data at the given offset by a string
Aurelien DARRAGONafb7daf2022-10-04 12:16:05 +02003827 * content. By default the string is appended in front of input data. It
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003828 * returns the length of the written string, or -1 if the channel is closed or
3829 * if the buffer size is too little for the data.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003830 *
3831 * For a filter, the context is updated on success.
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003832 */
3833__LJMP static int hlua_channel_insert_data(lua_State *L)
3834{
3835 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003836 struct filter *filter;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003837 const char *str;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003838 size_t sz, input, output;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003839 int ret, offset;
3840
3841 if (lua_gettop(L) < 2 || lua_gettop(L) > 3)
3842 WILL_LJMP(luaL_error(L, "'insert' expects at least 1 argument and at most 2 arguments"));
3843 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3844 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003845
3846 output = co_data(chn);
3847 input = ci_data(chn);
3848
3849 filter = hlua_channel_filter(L, 1, chn, &output, &input);
3850 if (filter && !hlua_filter_from_payload(filter))
3851 WILL_LJMP(lua_error(L));
3852
Aurelien DARRAGONafb7daf2022-10-04 12:16:05 +02003853 offset = output;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003854 if (lua_gettop(L) > 2) {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003855 offset = MAY_LJMP(luaL_checkinteger(L, 3));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003856 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02003857 offset = MAX(0, (int)input + offset);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003858 offset += output;
Aurelien DARRAGONafb7daf2022-10-04 12:16:05 +02003859 if (offset > output + input) {
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003860 lua_pushfstring(L, "offset out of range.");
3861 WILL_LJMP(lua_error(L));
3862 }
3863 }
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003864 if (IS_HTX_STRM(chn_strm(chn))) {
3865 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3866 WILL_LJMP(lua_error(L));
3867 }
3868
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003869 ret = _hlua_channel_insert(chn, L, ist2(str, sz), offset);
3870 if (ret > 0 && filter) {
3871 struct hlua_flt_ctx *flt_ctx = filter->ctx;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003872
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003873 flt_update_offsets(filter, chn, ret);
3874 flt_ctx->cur_len[CHN_IDX(chn)] += ret;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003875 }
3876
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003877 lua_pushinteger(L, ret);
3878 return 1;
3879}
3880/* Replaces a given amount of input data at the given offset by a string
3881 * content. By default all remaining data are removed (offset = 0 and len =
3882 * -1). It returns the length of the written string, or -1 if the channel is
3883 * closed or if the buffer size is too little for the data.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003884 *
3885 * For a filter, the context is updated on success.
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003886 */
3887__LJMP static int hlua_channel_set_data(lua_State *L)
3888{
3889 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003890 struct filter *filter;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003891 const char *str;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003892 size_t sz, input, output;
3893 int ret, offset, len;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003894
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003895 if (lua_gettop(L) < 2 || lua_gettop(L) > 4)
3896 WILL_LJMP(luaL_error(L, "'set' expects at least 1 argument and at most 3 arguments"));
3897 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3898 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003899
Christopher Faulet1bb6afa2021-03-08 17:57:53 +01003900 if (IS_HTX_STRM(chn_strm(chn))) {
Thierry Fournier77016da2020-08-15 14:35:51 +02003901 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
Christopher Faulet3f829a42018-12-13 21:56:45 +01003902 WILL_LJMP(lua_error(L));
Thierry Fournier77016da2020-08-15 14:35:51 +02003903 }
Christopher Faulet3f829a42018-12-13 21:56:45 +01003904
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003905 output = co_data(chn);
3906 input = ci_data(chn);
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003907
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003908 filter = hlua_channel_filter(L, 1, chn, &output, &input);
3909 if (filter && !hlua_filter_from_payload(filter))
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003910 WILL_LJMP(lua_error(L));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003911
3912 offset = output;
3913 if (lua_gettop(L) > 2) {
3914 offset = MAY_LJMP(luaL_checkinteger(L, 3));
3915 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02003916 offset = MAX(0, (int)input + offset);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003917 offset += output;
3918 if (offset < output || offset > input + output) {
3919 lua_pushfstring(L, "offset out of range.");
3920 WILL_LJMP(lua_error(L));
3921 }
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003922 }
3923
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003924 len = output + input - offset;
3925 if (lua_gettop(L) == 4) {
3926 len = MAY_LJMP(luaL_checkinteger(L, 4));
3927 if (!len)
3928 goto set;
3929 if (len == -1)
3930 len = output + input - offset;
3931 if (len < 0 || offset + len > output + input) {
3932 lua_pushfstring(L, "length out of range.");
3933 WILL_LJMP(lua_error(L));
3934 }
3935 }
3936
3937 set:
Christopher Faulet23976d92021-08-06 09:59:49 +02003938 /* Be sure we can copied the string once input data will be removed. */
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003939 if (sz > c_room(chn) + len)
Christopher Faulet23976d92021-08-06 09:59:49 +02003940 lua_pushinteger(L, -1);
3941 else {
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003942 _hlua_channel_delete(chn, offset, len);
3943 ret = _hlua_channel_insert(chn, L, ist2(str, sz), offset);
3944 if (filter) {
3945 struct hlua_flt_ctx *flt_ctx = filter->ctx;
3946
3947 len -= (ret > 0 ? ret : 0);
3948 flt_update_offsets(filter, chn, -len);
3949 flt_ctx->cur_len[CHN_IDX(chn)] -= len;
3950 }
3951
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003952 lua_pushinteger(L, ret);
Christopher Faulet23976d92021-08-06 09:59:49 +02003953 }
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003954 return 1;
3955}
3956
3957/* Removes a given amount of input data at the given offset. By default all
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003958 * input data are removed (offset = 0 and len = -1). It returns the amount of
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003959 * the removed data.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003960 *
3961 * For a filter, the context is updated on success.
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003962 */
3963__LJMP static int hlua_channel_del_data(lua_State *L)
3964{
3965 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003966 struct filter *filter;
3967 size_t input, output;
3968 int offset, len;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003969
3970 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
3971 WILL_LJMP(luaL_error(L, "'remove' expects at most 2 arguments"));
3972 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003973
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003974 if (IS_HTX_STRM(chn_strm(chn))) {
3975 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3976 WILL_LJMP(lua_error(L));
3977 }
3978
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003979 output = co_data(chn);
3980 input = ci_data(chn);
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003981
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003982 filter = hlua_channel_filter(L, 1, chn, &output, &input);
3983 if (filter && !hlua_filter_from_payload(filter))
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003984 WILL_LJMP(lua_error(L));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003985
3986 offset = output;
Boyang Lie0c54352022-05-10 17:47:23 +00003987 if (lua_gettop(L) > 1) {
3988 offset = MAY_LJMP(luaL_checkinteger(L, 2));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003989 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02003990 offset = MAX(0, (int)input + offset);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003991 offset += output;
3992 if (offset < output || offset > input + output) {
3993 lua_pushfstring(L, "offset out of range.");
3994 WILL_LJMP(lua_error(L));
3995 }
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003996 }
3997
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003998 len = output + input - offset;
Boyang Lie0c54352022-05-10 17:47:23 +00003999 if (lua_gettop(L) == 3) {
4000 len = MAY_LJMP(luaL_checkinteger(L, 3));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004001 if (!len)
4002 goto end;
4003 if (len == -1)
4004 len = output + input - offset;
4005 if (len < 0 || offset + len > output + input) {
4006 lua_pushfstring(L, "length out of range.");
4007 WILL_LJMP(lua_error(L));
4008 }
4009 }
4010
4011 _hlua_channel_delete(chn, offset, len);
4012 if (filter) {
4013 struct hlua_flt_ctx *flt_ctx = filter->ctx;
4014
4015 flt_update_offsets(filter, chn, -len);
4016 flt_ctx->cur_len[CHN_IDX(chn)] -= len;
4017 }
4018
4019 end:
Christopher Faulet6a79fc12021-08-06 16:02:36 +02004020 lua_pushinteger(L, len);
Christopher Faulet23976d92021-08-06 09:59:49 +02004021 return 1;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004022}
4023
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004024/* Append data in the output side of the buffer. This data is immediately
4025 * sent. The function returns the amount of data written. If the buffer
4026 * cannot contain the data, the function yields. The function returns -1
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004027 * if the channel is closed.
4028 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01004029__LJMP static int hlua_channel_send_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004030{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02004031 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004032 struct filter *filter;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02004033 const char *str;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004034 size_t offset, len, sz;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02004035 int l, ret;
Thierry Fournier4234dbd2020-11-28 13:18:23 +01004036 struct hlua *hlua;
4037
4038 /* Get hlua struct, or NULL if we execute from main lua state */
4039 hlua = hlua_gethlua(L);
4040 if (!hlua) {
4041 lua_pushnil(L);
4042 return 1;
4043 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004044
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02004045 chn = MAY_LJMP(hlua_checkchannel(L, 1));
4046 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
4047 l = MAY_LJMP(luaL_checkinteger(L, 3));
Christopher Faulet3f829a42018-12-13 21:56:45 +01004048
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004049 offset = co_data(chn);
4050 len = ci_data(chn);
4051
4052 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
4053 if (filter && !hlua_filter_from_payload(filter))
4054 WILL_LJMP(lua_error(L));
4055
4056
Willy Tarreau47860ed2015-03-10 14:07:50 +01004057 if (unlikely(channel_output_closed(chn))) {
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004058 lua_pushinteger(L, -1);
4059 return 1;
4060 }
4061
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02004062 len = c_room(chn);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004063 if (len > sz -l) {
4064 if (filter) {
4065 lua_pushinteger(L, -1);
4066 return 1;
4067 }
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02004068 len = sz - l;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004069 }
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01004070
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004071 ret = _hlua_channel_insert(chn, L, ist2(str, len), offset);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02004072 if (ret == -1) {
4073 lua_pop(L, 1);
4074 lua_pushinteger(L, -1);
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01004075 return 1;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02004076 }
4077 if (ret) {
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004078 if (filter) {
4079 struct hlua_flt_ctx *flt_ctx = filter->ctx;
4080
4081
4082 flt_update_offsets(filter, chn, ret);
4083 FLT_OFF(filter, chn) += ret;
4084 flt_ctx->cur_off[CHN_IDX(chn)] += ret;
4085 }
4086 else
4087 c_adv(chn, ret);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004088
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02004089 l += ret;
4090 lua_pop(L, 1);
4091 lua_pushinteger(L, l);
4092 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004093
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02004094 if (l < sz) {
4095 /* Yield only if the channel's output is not empty.
4096 * Otherwise it means we cannot add more data. */
4097 if (co_data(chn) == 0 || HLUA_CANT_YIELD(hlua_gethlua(L)))
Christopher Faulet2e60aa42021-08-05 11:58:37 +02004098 return 1;
4099
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01004100 /* If we are waiting for space in the response buffer, we
4101 * must set the flag WAKERESWR. This flag required the task
4102 * wake up if any activity is detected on the response buffer.
4103 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01004104 if (chn->flags & CF_ISRESP)
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01004105 HLUA_SET_WAKERESWR(hlua);
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01004106 else
4107 HLUA_SET_WAKEREQWR(hlua);
Willy Tarreau9635e032018-10-16 17:52:55 +02004108 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01004109 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004110
4111 return 1;
4112}
4113
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05004114/* Just a wrapper of "_hlua_channel_send". This wrapper permits
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004115 * yield the LUA process, and resume it without checking the
4116 * input arguments.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004117 *
4118 * This function cannot be called from a filter.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004119 */
4120__LJMP static int hlua_channel_send(lua_State *L)
4121{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02004122 struct channel *chn;
4123
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004124 MAY_LJMP(check_args(L, 2, "send"));
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02004125 chn = MAY_LJMP(hlua_checkchannel(L, 1));
4126 if (IS_HTX_STRM(chn_strm(chn))) {
4127 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
4128 WILL_LJMP(lua_error(L));
4129 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004130 lua_pushinteger(L, 0);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01004131 return MAY_LJMP(hlua_channel_send_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004132}
4133
4134/* This function forward and amount of butes. The data pass from
4135 * the input side of the buffer to the output side, and can be
4136 * forwarded. This function never fails.
4137 *
4138 * The Lua function takes an amount of bytes to be forwarded in
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05004139 * input. It returns the number of bytes forwarded.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004140 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01004141__LJMP static int hlua_channel_forward_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004142{
Willy Tarreau47860ed2015-03-10 14:07:50 +01004143 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004144 struct filter *filter;
4145 size_t offset, len, fwd;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02004146 int l, max;
Thierry Fournier4234dbd2020-11-28 13:18:23 +01004147 struct hlua *hlua;
4148
4149 /* Get hlua struct, or NULL if we execute from main lua state */
4150 hlua = hlua_gethlua(L);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02004151 if (!hlua) {
4152 lua_pushnil(L);
Thierry Fournier4234dbd2020-11-28 13:18:23 +01004153 return 1;
Thierry Fournier77016da2020-08-15 14:35:51 +02004154 }
Christopher Faulet3f829a42018-12-13 21:56:45 +01004155
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02004156 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004157 fwd = MAY_LJMP(luaL_checkinteger(L, 2));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004158 l = MAY_LJMP(luaL_checkinteger(L, -1));
4159
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004160 offset = co_data(chn);
4161 len = ci_data(chn);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02004162
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004163 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
4164 if (filter && !hlua_filter_from_payload(filter))
4165 WILL_LJMP(lua_error(L));
4166
4167 max = fwd - l;
4168 if (max > len)
4169 max = len;
4170
4171 if (filter) {
4172 struct hlua_flt_ctx *flt_ctx = filter->ctx;
4173
4174 FLT_OFF(filter, chn) += max;
4175 flt_ctx->cur_off[CHN_IDX(chn)] += max;
4176 flt_ctx->cur_len[CHN_IDX(chn)] -= max;
4177 }
4178 else
4179 channel_forward(chn, max);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004180
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02004181 l += max;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004182 lua_pop(L, 1);
4183 lua_pushinteger(L, l);
4184
4185 /* Check if it miss bytes to forward. */
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004186 if (l < fwd) {
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004187 /* The the input channel or the output channel are closed, we
4188 * must return the amount of data forwarded.
4189 */
Christopher Faulet2e60aa42021-08-05 11:58:37 +02004190 if (channel_input_closed(chn) || channel_output_closed(chn) || HLUA_CANT_YIELD(hlua_gethlua(L)))
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004191 return 1;
4192
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01004193 /* If we are waiting for space data in the response buffer, we
4194 * must set the flag WAKERESWR. This flag required the task
4195 * wake up if any activity is detected on the response buffer.
4196 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01004197 if (chn->flags & CF_ISRESP)
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01004198 HLUA_SET_WAKERESWR(hlua);
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01004199 else
4200 HLUA_SET_WAKEREQWR(hlua);
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01004201
Ilya Shipitsin4a689da2022-10-29 09:34:32 +05004202 /* Otherwise, we can yield waiting for new data in the input side. */
Willy Tarreau9635e032018-10-16 17:52:55 +02004203 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_forward_yield, TICK_ETERNITY, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004204 }
4205
4206 return 1;
4207}
4208
4209/* Just check the input and prepare the stack for the previous
4210 * function "hlua_channel_forward_yield"
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004211 *
4212 * This function cannot be called from a filter.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004213 */
4214__LJMP static int hlua_channel_forward(lua_State *L)
4215{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02004216 struct channel *chn;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004217
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02004218 MAY_LJMP(check_args(L, 2, "forward"));
4219 chn = MAY_LJMP(hlua_checkchannel(L, 1));
4220 if (IS_HTX_STRM(chn_strm(chn))) {
4221 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
4222 WILL_LJMP(lua_error(L));
4223 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004224 lua_pushinteger(L, 0);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01004225 return MAY_LJMP(hlua_channel_forward_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004226}
4227
4228/* Just returns the number of bytes available in the input
4229 * side of the buffer. This function never fails.
4230 */
4231__LJMP static int hlua_channel_get_in_len(lua_State *L)
4232{
Willy Tarreau47860ed2015-03-10 14:07:50 +01004233 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004234 struct filter *filter;
4235 size_t output, input;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004236
Christopher Faulet6a79fc12021-08-06 16:02:36 +02004237 MAY_LJMP(check_args(L, 1, "input"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004238 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004239
4240 output = co_data(chn);
4241 input = ci_data(chn);
4242 filter = hlua_channel_filter(L, 1, chn, &output, &input);
4243 if (filter || !IS_HTX_STRM(chn_strm(chn)))
4244 lua_pushinteger(L, input);
4245 else {
Christopher Fauleta3ceac12018-12-14 13:39:09 +01004246 struct htx *htx = htxbuf(&chn->buf);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004247
Christopher Fauleta3ceac12018-12-14 13:39:09 +01004248 lua_pushinteger(L, htx->data - co_data(chn));
4249 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004250 return 1;
4251}
4252
Thierry FOURNIER / OZON.IO65192f32016-11-07 15:28:40 +01004253/* Returns true if the channel is full. */
4254__LJMP static int hlua_channel_is_full(lua_State *L)
4255{
4256 struct channel *chn;
Thierry FOURNIER / OZON.IO65192f32016-11-07 15:28:40 +01004257
4258 MAY_LJMP(check_args(L, 1, "is_full"));
4259 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Faulet0ec740e2020-02-26 11:59:19 +01004260 /* ignore the reserve, we are not on a producer side (ie in an
4261 * applet).
4262 */
4263 lua_pushboolean(L, channel_full(chn, 0));
Thierry FOURNIER / OZON.IO65192f32016-11-07 15:28:40 +01004264 return 1;
4265}
4266
Christopher Faulet6a79fc12021-08-06 16:02:36 +02004267/* Returns true if the channel may still receive data. */
4268__LJMP static int hlua_channel_may_recv(lua_State *L)
4269{
4270 struct channel *chn;
4271
4272 MAY_LJMP(check_args(L, 1, "may_recv"));
4273 chn = MAY_LJMP(hlua_checkchannel(L, 1));
4274 lua_pushboolean(L, (!channel_input_closed(chn) && channel_may_recv(chn)));
4275 return 1;
4276}
4277
Christopher Faulet2ac9ba22020-02-25 10:15:50 +01004278/* Returns true if the channel is the response channel. */
4279__LJMP static int hlua_channel_is_resp(lua_State *L)
4280{
4281 struct channel *chn;
4282
4283 MAY_LJMP(check_args(L, 1, "is_resp"));
4284 chn = MAY_LJMP(hlua_checkchannel(L, 1));
4285
4286 lua_pushboolean(L, !!(chn->flags & CF_ISRESP));
4287 return 1;
4288}
4289
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004290/* Just returns the number of bytes available in the output
4291 * side of the buffer. This function never fails.
4292 */
4293__LJMP static int hlua_channel_get_out_len(lua_State *L)
4294{
Willy Tarreau47860ed2015-03-10 14:07:50 +01004295 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004296 size_t output, input;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004297
Christopher Faulet6a79fc12021-08-06 16:02:36 +02004298 MAY_LJMP(check_args(L, 1, "output"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004299 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004300
4301 output = co_data(chn);
4302 input = ci_data(chn);
4303 hlua_channel_filter(L, 1, chn, &output, &input);
4304
4305 lua_pushinteger(L, output);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004306 return 1;
4307}
4308
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004309/*
4310 *
4311 *
4312 * Class Fetches
4313 *
4314 *
4315 */
4316
4317/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02004318 * a class stream, otherwise it throws an error.
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004319 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004320__LJMP static struct hlua_smp *hlua_checkfetches(lua_State *L, int ud)
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004321{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004322 return MAY_LJMP(hlua_checkudata(L, ud, class_fetches_ref));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004323}
4324
4325/* This function creates and push in the stack a fetch object according
4326 * with a current TXN.
4327 */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004328static int hlua_fetches_new(lua_State *L, struct hlua_txn *txn, unsigned int flags)
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004329{
Willy Tarreau7073c472015-04-06 11:15:40 +02004330 struct hlua_smp *hsmp;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004331
4332 /* Check stack size. */
4333 if (!lua_checkstack(L, 3))
4334 return 0;
4335
4336 /* Create the object: obj[0] = userdata.
4337 * Note that the base of the Fetches object is the
4338 * transaction object.
4339 */
4340 lua_newtable(L);
Willy Tarreau7073c472015-04-06 11:15:40 +02004341 hsmp = lua_newuserdata(L, sizeof(*hsmp));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004342 lua_rawseti(L, -2, 0);
4343
Willy Tarreau7073c472015-04-06 11:15:40 +02004344 hsmp->s = txn->s;
4345 hsmp->p = txn->p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01004346 hsmp->dir = txn->dir;
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004347 hsmp->flags = flags;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004348
4349 /* Pop a class sesison metatable and affect it to the userdata. */
4350 lua_rawgeti(L, LUA_REGISTRYINDEX, class_fetches_ref);
4351 lua_setmetatable(L, -2);
4352
4353 return 1;
4354}
4355
4356/* This function is an LUA binding. It is called with each sample-fetch.
4357 * It uses closure argument to store the associated sample-fetch. It
4358 * returns only one argument or throws an error. An error is thrown
4359 * only if an error is encountered during the argument parsing. If
4360 * the "sample-fetch" function fails, nil is returned.
4361 */
4362__LJMP static int hlua_run_sample_fetch(lua_State *L)
4363{
Willy Tarreaub2ccb562015-04-06 11:11:15 +02004364 struct hlua_smp *hsmp;
Willy Tarreau2ec22742015-03-10 14:27:20 +01004365 struct sample_fetch *f;
Frédéric Lécaillef874a832018-06-15 13:56:04 +02004366 struct arg args[ARGM_NBARGS + 1] = {{0}};
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004367 int i;
4368 struct sample smp;
4369
4370 /* Get closure arguments. */
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004371 f = lua_touserdata(L, lua_upvalueindex(1));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004372
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004373 /* Get traditional arguments. */
Willy Tarreaub2ccb562015-04-06 11:11:15 +02004374 hsmp = MAY_LJMP(hlua_checkfetches(L, 1));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004375
Thierry FOURNIERca988662015-12-20 18:43:03 +01004376 /* Check execution authorization. */
4377 if (f->use & SMP_USE_HTTP_ANY &&
4378 !(hsmp->flags & HLUA_F_MAY_USE_HTTP)) {
4379 lua_pushfstring(L, "the sample-fetch '%s' needs an HTTP parser which "
4380 "is not available in Lua services", f->kw);
4381 WILL_LJMP(lua_error(L));
4382 }
4383
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004384 /* Get extra arguments. */
4385 for (i = 0; i < lua_gettop(L) - 1; i++) {
4386 if (i >= ARGM_NBARGS)
4387 break;
4388 hlua_lua2arg(L, i + 2, &args[i]);
4389 }
4390 args[i].type = ARGT_STOP;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004391 args[i].data.str.area = NULL;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004392
4393 /* Check arguments. */
Willy Tarreaub2ccb562015-04-06 11:11:15 +02004394 MAY_LJMP(hlua_lua2arg_check(L, 2, args, f->arg_mask, hsmp->p));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004395
4396 /* Run the special args checker. */
Willy Tarreau2ec22742015-03-10 14:27:20 +01004397 if (f->val_args && !f->val_args(args, NULL)) {
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004398 lua_pushfstring(L, "error in arguments");
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004399 goto error;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004400 }
4401
4402 /* Initialise the sample. */
4403 memset(&smp, 0, sizeof(smp));
4404
4405 /* Run the sample fetch process. */
Willy Tarreau1777ea62016-03-10 16:15:46 +01004406 smp_set_owner(&smp, hsmp->p, hsmp->s->sess, hsmp->s, hsmp->dir & SMP_OPT_DIR);
Thierry FOURNIER0786d052015-05-11 15:42:45 +02004407 if (!f->process(args, &smp, f->kw, f->private)) {
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004408 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004409 lua_pushstring(L, "");
4410 else
4411 lua_pushnil(L);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004412 goto end;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004413 }
4414
4415 /* Convert the returned sample in lua value. */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004416 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004417 hlua_smp2lua_str(L, &smp);
4418 else
4419 hlua_smp2lua(L, &smp);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004420
4421 end:
Willy Tarreauee0d7272021-07-16 10:26:56 +02004422 free_args(args);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004423 return 1;
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004424
4425 error:
Willy Tarreauee0d7272021-07-16 10:26:56 +02004426 free_args(args);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004427 WILL_LJMP(lua_error(L));
4428 return 0; /* Never reached */
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004429}
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004430
4431/*
4432 *
4433 *
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004434 * Class Converters
4435 *
4436 *
4437 */
4438
4439/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02004440 * a class stream, otherwise it throws an error.
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004441 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004442__LJMP static struct hlua_smp *hlua_checkconverters(lua_State *L, int ud)
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004443{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004444 return MAY_LJMP(hlua_checkudata(L, ud, class_converters_ref));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004445}
4446
4447/* This function creates and push in the stack a Converters object
4448 * according with a current TXN.
4449 */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004450static int hlua_converters_new(lua_State *L, struct hlua_txn *txn, unsigned int flags)
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004451{
Willy Tarreau7073c472015-04-06 11:15:40 +02004452 struct hlua_smp *hsmp;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004453
4454 /* Check stack size. */
4455 if (!lua_checkstack(L, 3))
4456 return 0;
4457
4458 /* Create the object: obj[0] = userdata.
4459 * Note that the base of the Converters object is the
4460 * same than the TXN object.
4461 */
4462 lua_newtable(L);
Willy Tarreau7073c472015-04-06 11:15:40 +02004463 hsmp = lua_newuserdata(L, sizeof(*hsmp));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004464 lua_rawseti(L, -2, 0);
4465
Willy Tarreau7073c472015-04-06 11:15:40 +02004466 hsmp->s = txn->s;
4467 hsmp->p = txn->p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01004468 hsmp->dir = txn->dir;
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004469 hsmp->flags = flags;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004470
Willy Tarreau87b09662015-04-03 00:22:06 +02004471 /* Pop a class stream metatable and affect it to the table. */
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004472 lua_rawgeti(L, LUA_REGISTRYINDEX, class_converters_ref);
4473 lua_setmetatable(L, -2);
4474
4475 return 1;
4476}
4477
4478/* This function is an LUA binding. It is called with each converter.
4479 * It uses closure argument to store the associated converter. It
4480 * returns only one argument or throws an error. An error is thrown
4481 * only if an error is encountered during the argument parsing. If
4482 * the converter function function fails, nil is returned.
4483 */
4484__LJMP static int hlua_run_sample_conv(lua_State *L)
4485{
Willy Tarreauda5f1082015-04-06 11:17:13 +02004486 struct hlua_smp *hsmp;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004487 struct sample_conv *conv;
Frédéric Lécaillef874a832018-06-15 13:56:04 +02004488 struct arg args[ARGM_NBARGS + 1] = {{0}};
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004489 int i;
4490 struct sample smp;
4491
4492 /* Get closure arguments. */
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004493 conv = lua_touserdata(L, lua_upvalueindex(1));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004494
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004495 /* Get traditional arguments. */
Willy Tarreauda5f1082015-04-06 11:17:13 +02004496 hsmp = MAY_LJMP(hlua_checkconverters(L, 1));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004497
4498 /* Get extra arguments. */
4499 for (i = 0; i < lua_gettop(L) - 2; i++) {
4500 if (i >= ARGM_NBARGS)
4501 break;
4502 hlua_lua2arg(L, i + 3, &args[i]);
4503 }
4504 args[i].type = ARGT_STOP;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004505 args[i].data.str.area = NULL;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004506
4507 /* Check arguments. */
Willy Tarreauda5f1082015-04-06 11:17:13 +02004508 MAY_LJMP(hlua_lua2arg_check(L, 3, args, conv->arg_mask, hsmp->p));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004509
4510 /* Run the special args checker. */
4511 if (conv->val_args && !conv->val_args(args, conv, "", 0, NULL)) {
4512 hlua_pusherror(L, "error in arguments");
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004513 goto error;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004514 }
4515
4516 /* Initialise the sample. */
Amaury Denoyellebc0af6a2020-10-29 17:21:20 +01004517 memset(&smp, 0, sizeof(smp));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004518 if (!hlua_lua2smp(L, 2, &smp)) {
4519 hlua_pusherror(L, "error in the input argument");
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004520 goto error;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004521 }
4522
Willy Tarreau1777ea62016-03-10 16:15:46 +01004523 smp_set_owner(&smp, hsmp->p, hsmp->s->sess, hsmp->s, hsmp->dir & SMP_OPT_DIR);
4524
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004525 /* Apply expected cast. */
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02004526 if (!sample_casts[smp.data.type][conv->in_type]) {
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004527 hlua_pusherror(L, "invalid input argument: cannot cast '%s' to '%s'",
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02004528 smp_to_type[smp.data.type], smp_to_type[conv->in_type]);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004529 goto error;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004530 }
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02004531 if (sample_casts[smp.data.type][conv->in_type] != c_none &&
4532 !sample_casts[smp.data.type][conv->in_type](&smp)) {
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004533 hlua_pusherror(L, "error during the input argument casting");
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004534 goto error;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004535 }
4536
4537 /* Run the sample conversion process. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02004538 if (!conv->process(args, &smp, conv->private)) {
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004539 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004540 lua_pushstring(L, "");
4541 else
Willy Tarreaua678b432015-08-28 10:14:59 +02004542 lua_pushnil(L);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004543 goto end;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004544 }
4545
4546 /* Convert the returned sample in lua value. */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004547 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004548 hlua_smp2lua_str(L, &smp);
4549 else
4550 hlua_smp2lua(L, &smp);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004551 end:
Willy Tarreauee0d7272021-07-16 10:26:56 +02004552 free_args(args);
Willy Tarreaua678b432015-08-28 10:14:59 +02004553 return 1;
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004554
4555 error:
Willy Tarreauee0d7272021-07-16 10:26:56 +02004556 free_args(args);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004557 WILL_LJMP(lua_error(L));
4558 return 0; /* Never reached */
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004559}
4560
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004561/*
4562 *
4563 *
4564 * Class AppletTCP
4565 *
4566 *
4567 */
4568
4569/* Returns a struct hlua_txn if the stack entry "ud" is
4570 * a class stream, otherwise it throws an error.
4571 */
4572__LJMP static struct hlua_appctx *hlua_checkapplet_tcp(lua_State *L, int ud)
4573{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004574 return MAY_LJMP(hlua_checkudata(L, ud, class_applet_tcp_ref));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004575}
4576
4577/* This function creates and push in the stack an Applet object
4578 * according with a current TXN.
4579 */
4580static int hlua_applet_tcp_new(lua_State *L, struct appctx *ctx)
4581{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004582 struct hlua_appctx *luactx;
Willy Tarreau0698c802022-05-11 14:09:57 +02004583 struct stream *s = appctx_strm(ctx);
Christopher Faulet2da02ae2022-02-24 13:45:27 +01004584 struct proxy *p;
4585
4586 ALREADY_CHECKED(s);
4587 p = s->be;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004588
4589 /* Check stack size. */
4590 if (!lua_checkstack(L, 3))
4591 return 0;
4592
4593 /* Create the object: obj[0] = userdata.
4594 * Note that the base of the Converters object is the
4595 * same than the TXN object.
4596 */
4597 lua_newtable(L);
Willy Tarreau7e702d12021-04-28 17:59:21 +02004598 luactx = lua_newuserdata(L, sizeof(*luactx));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004599 lua_rawseti(L, -2, 0);
Willy Tarreau7e702d12021-04-28 17:59:21 +02004600 luactx->appctx = ctx;
4601 luactx->htxn.s = s;
4602 luactx->htxn.p = p;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004603
4604 /* Create the "f" field that contains a list of fetches. */
4605 lua_pushstring(L, "f");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004606 if (!hlua_fetches_new(L, &luactx->htxn, 0))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004607 return 0;
4608 lua_settable(L, -3);
4609
4610 /* Create the "sf" field that contains a list of stringsafe fetches. */
4611 lua_pushstring(L, "sf");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004612 if (!hlua_fetches_new(L, &luactx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004613 return 0;
4614 lua_settable(L, -3);
4615
4616 /* Create the "c" field that contains a list of converters. */
4617 lua_pushstring(L, "c");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004618 if (!hlua_converters_new(L, &luactx->htxn, 0))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004619 return 0;
4620 lua_settable(L, -3);
4621
4622 /* Create the "sc" field that contains a list of stringsafe converters. */
4623 lua_pushstring(L, "sc");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004624 if (!hlua_converters_new(L, &luactx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004625 return 0;
4626 lua_settable(L, -3);
4627
4628 /* Pop a class stream metatable and affect it to the table. */
4629 lua_rawgeti(L, LUA_REGISTRYINDEX, class_applet_tcp_ref);
4630 lua_setmetatable(L, -2);
4631
4632 return 1;
4633}
4634
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004635__LJMP static int hlua_applet_tcp_set_var(lua_State *L)
4636{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004637 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004638 struct stream *s;
4639 const char *name;
4640 size_t len;
4641 struct sample smp;
4642
Tim Duesterhus4e172c92020-05-19 13:49:42 +02004643 if (lua_gettop(L) < 3 || lua_gettop(L) > 4)
4644 WILL_LJMP(luaL_error(L, "'set_var' needs between 3 and 4 arguments"));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004645
4646 /* It is useles to retrieve the stream, but this function
4647 * runs only in a stream context.
4648 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004649 luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004650 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02004651 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004652
4653 /* Converts the third argument in a sample. */
Amaury Denoyellebc0af6a2020-10-29 17:21:20 +01004654 memset(&smp, 0, sizeof(smp));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004655 hlua_lua2smp(L, 3, &smp);
4656
4657 /* Store the sample in a variable. */
4658 smp_set_owner(&smp, s->be, s->sess, s, 0);
Tim Duesterhus4e172c92020-05-19 13:49:42 +02004659
4660 if (lua_gettop(L) == 4 && lua_toboolean(L, 4))
4661 lua_pushboolean(L, vars_set_by_name_ifexist(name, len, &smp) != 0);
4662 else
4663 lua_pushboolean(L, vars_set_by_name(name, len, &smp) != 0);
4664
Tim Duesterhus84ebc132020-05-19 13:49:41 +02004665 return 1;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004666}
4667
4668__LJMP static int hlua_applet_tcp_unset_var(lua_State *L)
4669{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004670 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004671 struct stream *s;
4672 const char *name;
4673 size_t len;
4674 struct sample smp;
4675
4676 MAY_LJMP(check_args(L, 2, "unset_var"));
4677
4678 /* It is useles to retrieve the stream, but this function
4679 * runs only in a stream context.
4680 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004681 luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004682 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02004683 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004684
4685 /* Unset the variable. */
4686 smp_set_owner(&smp, s->be, s->sess, s, 0);
Tim Duesterhus84ebc132020-05-19 13:49:41 +02004687 lua_pushboolean(L, vars_unset_by_name_ifexist(name, len, &smp) != 0);
4688 return 1;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004689}
4690
4691__LJMP static int hlua_applet_tcp_get_var(lua_State *L)
4692{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004693 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004694 struct stream *s;
4695 const char *name;
4696 size_t len;
4697 struct sample smp;
4698
4699 MAY_LJMP(check_args(L, 2, "get_var"));
4700
4701 /* It is useles to retrieve the stream, but this function
4702 * runs only in a stream context.
4703 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004704 luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004705 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02004706 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004707
4708 smp_set_owner(&smp, s->be, s->sess, s, 0);
Willy Tarreaue352b9d2021-09-03 11:52:38 +02004709 if (!vars_get_by_name(name, len, &smp, NULL)) {
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004710 lua_pushnil(L);
4711 return 1;
4712 }
4713
4714 return hlua_smp2lua(L, &smp);
4715}
4716
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004717__LJMP static int hlua_applet_tcp_set_priv(lua_State *L)
4718{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004719 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
4720 struct stream *s = luactx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01004721 struct hlua *hlua;
4722
4723 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01004724 if (!s->hlua)
4725 return 0;
4726 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004727
4728 MAY_LJMP(check_args(L, 2, "set_priv"));
4729
4730 /* Remove previous value. */
Thierry FOURNIERe068b602017-04-26 13:27:05 +02004731 luaL_unref(L, LUA_REGISTRYINDEX, hlua->Mref);
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004732
4733 /* Get and store new value. */
4734 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
4735 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
4736
4737 return 0;
4738}
4739
4740__LJMP static int hlua_applet_tcp_get_priv(lua_State *L)
4741{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004742 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
4743 struct stream *s = luactx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01004744 struct hlua *hlua;
4745
4746 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01004747 if (!s->hlua) {
4748 lua_pushnil(L);
4749 return 1;
4750 }
4751 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004752
4753 /* Push configuration index in the stack. */
4754 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
4755
4756 return 1;
4757}
4758
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004759/* If expected data not yet available, it returns a yield. This function
4760 * consumes the data in the buffer. It returns a string containing the
4761 * data. This string can be empty.
4762 */
4763__LJMP static int hlua_applet_tcp_getline_yield(lua_State *L, int status, lua_KContext ctx)
4764{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004765 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Willy Tarreauc12b3212022-05-27 11:08:15 +02004766 struct stconn *sc = appctx_sc(luactx->appctx);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004767 int ret;
Willy Tarreau206ba832018-06-14 15:27:31 +02004768 const char *blk1;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004769 size_t len1;
Willy Tarreau206ba832018-06-14 15:27:31 +02004770 const char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004771 size_t len2;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004772
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004773 /* Read the maximum amount of data available. */
Willy Tarreau3e7be362022-05-27 10:35:27 +02004774 ret = co_getline_nc(sc_oc(sc), &blk1, &len1, &blk2, &len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004775
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004776 /* Data not yet available. return yield. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004777 if (ret == 0) {
Willy Tarreau90e8b452022-05-25 18:21:43 +02004778 applet_need_more_data(luactx->appctx);
Willy Tarreau9635e032018-10-16 17:52:55 +02004779 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_getline_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004780 }
4781
4782 /* End of data: commit the total strings and return. */
4783 if (ret < 0) {
Willy Tarreau7e702d12021-04-28 17:59:21 +02004784 luaL_pushresult(&luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004785 return 1;
4786 }
4787
4788 /* Ensure that the block 2 length is usable. */
4789 if (ret == 1)
4790 len2 = 0;
4791
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -07004792 /* don't check the max length read and don't check. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004793 luaL_addlstring(&luactx->b, blk1, len1);
4794 luaL_addlstring(&luactx->b, blk2, len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004795
4796 /* Consume input channel output buffer data. */
Willy Tarreau3e7be362022-05-27 10:35:27 +02004797 co_skip(sc_oc(sc), len1 + len2);
Willy Tarreau7e702d12021-04-28 17:59:21 +02004798 luaL_pushresult(&luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004799 return 1;
4800}
4801
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004802/* Check arguments for the function "hlua_channel_get_yield". */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004803__LJMP static int hlua_applet_tcp_getline(lua_State *L)
4804{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004805 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004806
4807 /* Initialise the string catenation. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004808 luaL_buffinit(L, &luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004809
4810 return MAY_LJMP(hlua_applet_tcp_getline_yield(L, 0, 0));
4811}
4812
4813/* If expected data not yet available, it returns a yield. This function
4814 * consumes the data in the buffer. It returns a string containing the
4815 * data. This string can be empty.
4816 */
4817__LJMP static int hlua_applet_tcp_recv_yield(lua_State *L, int status, lua_KContext ctx)
4818{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004819 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Willy Tarreauc12b3212022-05-27 11:08:15 +02004820 struct stconn *sc = appctx_sc(luactx->appctx);
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004821 size_t len = MAY_LJMP(luaL_checkinteger(L, 2));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004822 int ret;
Willy Tarreau206ba832018-06-14 15:27:31 +02004823 const char *blk1;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004824 size_t len1;
Willy Tarreau206ba832018-06-14 15:27:31 +02004825 const char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004826 size_t len2;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004827
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004828 /* Read the maximum amount of data available. */
Willy Tarreau3e7be362022-05-27 10:35:27 +02004829 ret = co_getblk_nc(sc_oc(sc), &blk1, &len1, &blk2, &len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004830
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004831 /* Data not yet available. return yield. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004832 if (ret == 0) {
Willy Tarreau90e8b452022-05-25 18:21:43 +02004833 applet_need_more_data(luactx->appctx);
Willy Tarreau9635e032018-10-16 17:52:55 +02004834 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004835 }
4836
4837 /* End of data: commit the total strings and return. */
4838 if (ret < 0) {
Willy Tarreau7e702d12021-04-28 17:59:21 +02004839 luaL_pushresult(&luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004840 return 1;
4841 }
4842
4843 /* Ensure that the block 2 length is usable. */
4844 if (ret == 1)
4845 len2 = 0;
4846
4847 if (len == -1) {
4848
4849 /* If len == -1, catenate all the data avalaile and
4850 * yield because we want to get all the data until
4851 * the end of data stream.
4852 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004853 luaL_addlstring(&luactx->b, blk1, len1);
4854 luaL_addlstring(&luactx->b, blk2, len2);
Willy Tarreau3e7be362022-05-27 10:35:27 +02004855 co_skip(sc_oc(sc), len1 + len2);
Willy Tarreau90e8b452022-05-25 18:21:43 +02004856 applet_need_more_data(luactx->appctx);
Willy Tarreau9635e032018-10-16 17:52:55 +02004857 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004858
4859 } else {
4860
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05004861 /* Copy the first block caping to the length required. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004862 if (len1 > len)
4863 len1 = len;
Willy Tarreau7e702d12021-04-28 17:59:21 +02004864 luaL_addlstring(&luactx->b, blk1, len1);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004865 len -= len1;
4866
4867 /* Copy the second block. */
4868 if (len2 > len)
4869 len2 = len;
Willy Tarreau7e702d12021-04-28 17:59:21 +02004870 luaL_addlstring(&luactx->b, blk2, len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004871 len -= len2;
4872
4873 /* Consume input channel output buffer data. */
Willy Tarreau3e7be362022-05-27 10:35:27 +02004874 co_skip(sc_oc(sc), len1 + len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004875
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004876 /* If there is no other data available, yield waiting for new data. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004877 if (len > 0) {
4878 lua_pushinteger(L, len);
4879 lua_replace(L, 2);
Willy Tarreau90e8b452022-05-25 18:21:43 +02004880 applet_need_more_data(luactx->appctx);
Willy Tarreau9635e032018-10-16 17:52:55 +02004881 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004882 }
4883
4884 /* return the result. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004885 luaL_pushresult(&luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004886 return 1;
4887 }
4888
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004889 /* we never execute this */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004890 hlua_pusherror(L, "Lua: internal error");
4891 WILL_LJMP(lua_error(L));
4892 return 0;
4893}
4894
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004895/* Check arguments for the function "hlua_channel_get_yield". */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004896__LJMP static int hlua_applet_tcp_recv(lua_State *L)
4897{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004898 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004899 int len = -1;
4900
4901 if (lua_gettop(L) > 2)
4902 WILL_LJMP(luaL_error(L, "The 'recv' function requires between 1 and 2 arguments."));
4903 if (lua_gettop(L) >= 2) {
4904 len = MAY_LJMP(luaL_checkinteger(L, 2));
4905 lua_pop(L, 1);
4906 }
4907
4908 /* Confirm or set the required length */
4909 lua_pushinteger(L, len);
4910
4911 /* Initialise the string catenation. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004912 luaL_buffinit(L, &luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004913
4914 return MAY_LJMP(hlua_applet_tcp_recv_yield(L, 0, 0));
4915}
4916
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004917/* Append data in the output side of the buffer. This data is immediately
4918 * sent. The function returns the amount of data written. If the buffer
4919 * cannot contain the data, the function yields. The function returns -1
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004920 * if the channel is closed.
4921 */
4922__LJMP static int hlua_applet_tcp_send_yield(lua_State *L, int status, lua_KContext ctx)
4923{
4924 size_t len;
Willy Tarreau7e702d12021-04-28 17:59:21 +02004925 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004926 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
4927 int l = MAY_LJMP(luaL_checkinteger(L, 3));
Willy Tarreauc12b3212022-05-27 11:08:15 +02004928 struct stconn *sc = appctx_sc(luactx->appctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02004929 struct channel *chn = sc_ic(sc);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004930 int max;
4931
4932 /* Get the max amount of data which can write as input in the channel. */
4933 max = channel_recv_max(chn);
4934 if (max > (len - l))
4935 max = len - l;
4936
4937 /* Copy data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02004938 ci_putblk(chn, str + l, max);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004939
4940 /* update counters. */
4941 l += max;
4942 lua_pop(L, 1);
4943 lua_pushinteger(L, l);
4944
4945 /* If some data is not send, declares the situation to the
4946 * applet, and returns a yield.
4947 */
4948 if (l < len) {
Christopher Faulet7b3d38a2023-05-05 11:28:45 +02004949 sc_need_room(sc, channel_recv_max(chn) + 1);
Willy Tarreau9635e032018-10-16 17:52:55 +02004950 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004951 }
4952
4953 return 1;
4954}
4955
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05004956/* Just a wrapper of "hlua_applet_tcp_send_yield". This wrapper permits
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004957 * yield the LUA process, and resume it without checking the
4958 * input arguments.
4959 */
4960__LJMP static int hlua_applet_tcp_send(lua_State *L)
4961{
4962 MAY_LJMP(check_args(L, 2, "send"));
4963 lua_pushinteger(L, 0);
4964
4965 return MAY_LJMP(hlua_applet_tcp_send_yield(L, 0, 0));
4966}
4967
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004968/*
4969 *
4970 *
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004971 * Class AppletHTTP
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004972 *
4973 *
4974 */
4975
4976/* Returns a struct hlua_txn if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02004977 * a class stream, otherwise it throws an error.
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004978 */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004979__LJMP static struct hlua_appctx *hlua_checkapplet_http(lua_State *L, int ud)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004980{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004981 return MAY_LJMP(hlua_checkudata(L, ud, class_applet_http_ref));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004982}
4983
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004984/* This function creates and push in the stack an Applet object
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004985 * according with a current TXN.
Willy Tarreauaa229cc2022-05-06 14:26:10 +02004986 * It relies on the caller to have already reserved the room in ctx->svcctx
4987 * for the local storage of hlua_http_ctx.
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004988 */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004989static int hlua_applet_http_new(lua_State *L, struct appctx *ctx)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004990{
Willy Tarreauaa229cc2022-05-06 14:26:10 +02004991 struct hlua_http_ctx *http_ctx = ctx->svcctx;
Willy Tarreau7e702d12021-04-28 17:59:21 +02004992 struct hlua_appctx *luactx;
Thierry FOURNIER841475e2015-12-11 17:10:09 +01004993 struct hlua_txn htxn;
Willy Tarreau0698c802022-05-11 14:09:57 +02004994 struct stream *s = appctx_strm(ctx);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004995 struct proxy *px = s->be;
Christopher Fauleta2097962019-07-15 16:25:33 +02004996 struct htx *htx;
4997 struct htx_blk *blk;
4998 struct htx_sl *sl;
4999 struct ist path;
5000 unsigned long long len = 0;
5001 int32_t pos;
Amaury Denoyellec453f952021-07-06 11:40:12 +02005002 struct http_uri_parser parser;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005003
5004 /* Check stack size. */
5005 if (!lua_checkstack(L, 3))
5006 return 0;
5007
5008 /* Create the object: obj[0] = userdata.
5009 * Note that the base of the Converters object is the
5010 * same than the TXN object.
5011 */
5012 lua_newtable(L);
Willy Tarreau7e702d12021-04-28 17:59:21 +02005013 luactx = lua_newuserdata(L, sizeof(*luactx));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005014 lua_rawseti(L, -2, 0);
Willy Tarreau7e702d12021-04-28 17:59:21 +02005015 luactx->appctx = ctx;
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005016 http_ctx->status = 200; /* Default status code returned. */
5017 http_ctx->reason = NULL; /* Use default reason based on status */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005018 luactx->htxn.s = s;
5019 luactx->htxn.p = px;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005020
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005021 /* Create the "f" field that contains a list of fetches. */
5022 lua_pushstring(L, "f");
Willy Tarreau7e702d12021-04-28 17:59:21 +02005023 if (!hlua_fetches_new(L, &luactx->htxn, 0))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005024 return 0;
5025 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005026
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005027 /* Create the "sf" field that contains a list of stringsafe fetches. */
5028 lua_pushstring(L, "sf");
Willy Tarreau7e702d12021-04-28 17:59:21 +02005029 if (!hlua_fetches_new(L, &luactx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005030 return 0;
5031 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005032
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005033 /* Create the "c" field that contains a list of converters. */
5034 lua_pushstring(L, "c");
Willy Tarreau7e702d12021-04-28 17:59:21 +02005035 if (!hlua_converters_new(L, &luactx->htxn, 0))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005036 return 0;
5037 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005038
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005039 /* Create the "sc" field that contains a list of stringsafe converters. */
5040 lua_pushstring(L, "sc");
Willy Tarreau7e702d12021-04-28 17:59:21 +02005041 if (!hlua_converters_new(L, &luactx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005042 return 0;
5043 lua_settable(L, -3);
Willy Tarreaueee5b512015-04-03 23:46:31 +02005044
Christopher Fauleta2097962019-07-15 16:25:33 +02005045 htx = htxbuf(&s->req.buf);
5046 blk = htx_get_first_blk(htx);
Christopher Fauletea009732019-11-18 15:50:25 +01005047 BUG_ON(!blk || htx_get_blk_type(blk) != HTX_BLK_REQ_SL);
Christopher Fauleta2097962019-07-15 16:25:33 +02005048 sl = htx_get_blk_ptr(htx, blk);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005049
Christopher Fauleta2097962019-07-15 16:25:33 +02005050 /* Stores the request method. */
5051 lua_pushstring(L, "method");
5052 lua_pushlstring(L, HTX_SL_REQ_MPTR(sl), HTX_SL_REQ_MLEN(sl));
5053 lua_settable(L, -3);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005054
Christopher Fauleta2097962019-07-15 16:25:33 +02005055 /* Stores the http version. */
5056 lua_pushstring(L, "version");
5057 lua_pushlstring(L, HTX_SL_REQ_VPTR(sl), HTX_SL_REQ_VLEN(sl));
5058 lua_settable(L, -3);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005059
Christopher Fauleta2097962019-07-15 16:25:33 +02005060 /* creates an array of headers. hlua_http_get_headers() crates and push
5061 * the array on the top of the stack.
5062 */
5063 lua_pushstring(L, "headers");
5064 htxn.s = s;
5065 htxn.p = px;
5066 htxn.dir = SMP_OPT_DIR_REQ;
Christopher Faulet9d1332b2020-02-24 16:46:16 +01005067 if (!hlua_http_get_headers(L, &htxn.s->txn->req))
Christopher Fauleta2097962019-07-15 16:25:33 +02005068 return 0;
5069 lua_settable(L, -3);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005070
Amaury Denoyellec453f952021-07-06 11:40:12 +02005071 parser = http_uri_parser_init(htx_sl_req_uri(sl));
5072 path = http_parse_path(&parser);
Tim Duesterhused526372020-03-05 17:56:33 +01005073 if (isttest(path)) {
Christopher Fauleta2097962019-07-15 16:25:33 +02005074 char *p, *q, *end;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005075
Christopher Fauleta2097962019-07-15 16:25:33 +02005076 p = path.ptr;
Tim Duesterhus4c8f75f2021-11-06 15:14:44 +01005077 end = istend(path);
Christopher Fauleta2097962019-07-15 16:25:33 +02005078 q = p;
5079 while (q < end && *q != '?')
5080 q++;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005081
Thierry FOURNIER7d388632017-02-22 02:06:16 +01005082 /* Stores the request path. */
Christopher Fauleta2097962019-07-15 16:25:33 +02005083 lua_pushstring(L, "path");
5084 lua_pushlstring(L, p, q - p);
Thierry FOURNIER7d388632017-02-22 02:06:16 +01005085 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01005086
Christopher Fauleta2097962019-07-15 16:25:33 +02005087 /* Stores the query string. */
5088 lua_pushstring(L, "qs");
5089 if (*q == '?')
5090 q++;
5091 lua_pushlstring(L, q, end - q);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005092 lua_settable(L, -3);
Christopher Fauleta2097962019-07-15 16:25:33 +02005093 }
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005094
Christopher Fauleta2097962019-07-15 16:25:33 +02005095 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
5096 struct htx_blk *blk = htx_get_blk(htx, pos);
5097 enum htx_blk_type type = htx_get_blk_type(blk);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005098
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01005099 if (type == HTX_BLK_TLR || type == HTX_BLK_EOT)
Christopher Fauleta2097962019-07-15 16:25:33 +02005100 break;
5101 if (type == HTX_BLK_DATA)
5102 len += htx_get_blksz(blk);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005103 }
Christopher Faulet2e47e3a2023-01-13 11:40:24 +01005104 if (htx->extra != HTX_UNKOWN_PAYLOAD_LENGTH)
Christopher Fauleta2097962019-07-15 16:25:33 +02005105 len += htx->extra;
5106
5107 /* Stores the request path. */
5108 lua_pushstring(L, "length");
5109 lua_pushinteger(L, len);
5110 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01005111
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005112 /* Create an empty array of HTTP request headers. */
5113 lua_pushstring(L, "response");
5114 lua_newtable(L);
5115 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01005116
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005117 /* Pop a class stream metatable and affect it to the table. */
5118 lua_rawgeti(L, LUA_REGISTRYINDEX, class_applet_http_ref);
5119 lua_setmetatable(L, -2);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005120
5121 return 1;
5122}
5123
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01005124__LJMP static int hlua_applet_http_set_var(lua_State *L)
5125{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005126 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01005127 struct stream *s;
5128 const char *name;
5129 size_t len;
5130 struct sample smp;
5131
Tim Duesterhus4e172c92020-05-19 13:49:42 +02005132 if (lua_gettop(L) < 3 || lua_gettop(L) > 4)
5133 WILL_LJMP(luaL_error(L, "'set_var' needs between 3 and 4 arguments"));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01005134
5135 /* It is useles to retrieve the stream, but this function
5136 * runs only in a stream context.
5137 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005138 luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01005139 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02005140 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01005141
5142 /* Converts the third argument in a sample. */
Amaury Denoyellebc0af6a2020-10-29 17:21:20 +01005143 memset(&smp, 0, sizeof(smp));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01005144 hlua_lua2smp(L, 3, &smp);
5145
5146 /* Store the sample in a variable. */
5147 smp_set_owner(&smp, s->be, s->sess, s, 0);
Tim Duesterhus4e172c92020-05-19 13:49:42 +02005148
5149 if (lua_gettop(L) == 4 && lua_toboolean(L, 4))
5150 lua_pushboolean(L, vars_set_by_name_ifexist(name, len, &smp) != 0);
5151 else
5152 lua_pushboolean(L, vars_set_by_name(name, len, &smp) != 0);
5153
Tim Duesterhus84ebc132020-05-19 13:49:41 +02005154 return 1;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01005155}
5156
5157__LJMP static int hlua_applet_http_unset_var(lua_State *L)
5158{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005159 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01005160 struct stream *s;
5161 const char *name;
5162 size_t len;
5163 struct sample smp;
5164
5165 MAY_LJMP(check_args(L, 2, "unset_var"));
5166
5167 /* It is useles to retrieve the stream, but this function
5168 * runs only in a stream context.
5169 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005170 luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01005171 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02005172 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01005173
5174 /* Unset the variable. */
5175 smp_set_owner(&smp, s->be, s->sess, s, 0);
Tim Duesterhus84ebc132020-05-19 13:49:41 +02005176 lua_pushboolean(L, vars_unset_by_name_ifexist(name, len, &smp) != 0);
5177 return 1;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01005178}
5179
5180__LJMP static int hlua_applet_http_get_var(lua_State *L)
5181{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005182 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01005183 struct stream *s;
5184 const char *name;
5185 size_t len;
5186 struct sample smp;
5187
5188 MAY_LJMP(check_args(L, 2, "get_var"));
5189
5190 /* It is useles to retrieve the stream, but this function
5191 * runs only in a stream context.
5192 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005193 luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01005194 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02005195 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01005196
5197 smp_set_owner(&smp, s->be, s->sess, s, 0);
Willy Tarreaue352b9d2021-09-03 11:52:38 +02005198 if (!vars_get_by_name(name, len, &smp, NULL)) {
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01005199 lua_pushnil(L);
5200 return 1;
5201 }
5202
5203 return hlua_smp2lua(L, &smp);
5204}
5205
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01005206__LJMP static int hlua_applet_http_set_priv(lua_State *L)
5207{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005208 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
5209 struct stream *s = luactx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01005210 struct hlua *hlua;
5211
5212 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005213 if (!s->hlua)
5214 return 0;
5215 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01005216
5217 MAY_LJMP(check_args(L, 2, "set_priv"));
5218
5219 /* Remove previous value. */
Thierry FOURNIERe068b602017-04-26 13:27:05 +02005220 luaL_unref(L, LUA_REGISTRYINDEX, hlua->Mref);
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01005221
5222 /* Get and store new value. */
5223 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
5224 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
5225
5226 return 0;
5227}
5228
5229__LJMP static int hlua_applet_http_get_priv(lua_State *L)
5230{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005231 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
5232 struct stream *s = luactx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01005233 struct hlua *hlua;
5234
5235 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005236 if (!s->hlua) {
5237 lua_pushnil(L);
5238 return 1;
5239 }
5240 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01005241
5242 /* Push configuration index in the stack. */
5243 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
5244
5245 return 1;
5246}
5247
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005248/* If expected data not yet available, it returns a yield. This function
5249 * consumes the data in the buffer. It returns a string containing the
5250 * data. This string can be empty.
5251 */
Christopher Fauleta2097962019-07-15 16:25:33 +02005252__LJMP static int hlua_applet_http_getline_yield(lua_State *L, int status, lua_KContext ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005253{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005254 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Willy Tarreauc12b3212022-05-27 11:08:15 +02005255 struct stconn *sc = appctx_sc(luactx->appctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02005256 struct channel *req = sc_oc(sc);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005257 struct htx *htx;
5258 struct htx_blk *blk;
5259 size_t count;
5260 int stop = 0;
5261
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005262 htx = htx_from_buf(&req->buf);
5263 count = co_data(req);
Christopher Fauleta3f15502019-05-13 15:27:23 +02005264 blk = htx_get_first_blk(htx);
Christopher Fauletcc26b132018-12-18 21:20:57 +01005265
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005266 while (count && !stop && blk) {
5267 enum htx_blk_type type = htx_get_blk_type(blk);
5268 uint32_t sz = htx_get_blksz(blk);
5269 struct ist v;
5270 uint32_t vlen;
5271 char *nl;
5272
5273 vlen = sz;
5274 if (vlen > count) {
5275 if (type != HTX_BLK_DATA)
5276 break;
5277 vlen = count;
5278 }
5279
5280 switch (type) {
5281 case HTX_BLK_UNUSED:
5282 break;
5283
5284 case HTX_BLK_DATA:
5285 v = htx_get_blk_value(htx, blk);
5286 v.len = vlen;
5287 nl = istchr(v, '\n');
5288 if (nl != NULL) {
5289 stop = 1;
5290 vlen = nl - v.ptr + 1;
5291 }
Willy Tarreau7e702d12021-04-28 17:59:21 +02005292 luaL_addlstring(&luactx->b, v.ptr, vlen);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005293 break;
5294
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005295 case HTX_BLK_TLR:
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01005296 case HTX_BLK_EOT:
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005297 stop = 1;
5298 break;
5299
5300 default:
5301 break;
5302 }
5303
Willy Tarreau84240042022-02-28 16:51:23 +01005304 c_rew(req, vlen);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005305 count -= vlen;
5306 if (sz == vlen)
5307 blk = htx_remove_blk(htx, blk);
5308 else {
5309 htx_cut_data_blk(htx, blk, vlen);
5310 break;
5311 }
5312 }
5313
Christopher Fauleteccb31c2021-04-02 14:24:56 +02005314 /* The message was fully consumed and no more data are expected
5315 * (EOM flag set).
5316 */
Christopher Faulet904763f2023-03-22 14:53:11 +01005317 if (htx_is_empty(htx) && (sc->flags & SC_FL_EOI))
Christopher Fauleteccb31c2021-04-02 14:24:56 +02005318 stop = 1;
5319
Christopher Faulet0ae79d02019-02-27 21:36:59 +01005320 htx_to_buf(htx, &req->buf);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005321 if (!stop) {
Willy Tarreau90e8b452022-05-25 18:21:43 +02005322 applet_need_more_data(luactx->appctx);
Christopher Fauleta2097962019-07-15 16:25:33 +02005323 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_getline_yield, TICK_ETERNITY, 0));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005324 }
5325
5326 /* return the result. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005327 luaL_pushresult(&luactx->b);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005328 return 1;
5329}
5330
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005331
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08005332/* Check arguments for the function "hlua_channel_get_yield". */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005333__LJMP static int hlua_applet_http_getline(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005334{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005335 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005336
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005337 /* Initialise the string catenation. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005338 luaL_buffinit(L, &luactx->b);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005339
Christopher Fauleta2097962019-07-15 16:25:33 +02005340 return MAY_LJMP(hlua_applet_http_getline_yield(L, 0, 0));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005341}
5342
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005343/* If expected data not yet available, it returns a yield. This function
5344 * consumes the data in the buffer. It returns a string containing the
5345 * data. This string can be empty.
5346 */
Christopher Fauleta2097962019-07-15 16:25:33 +02005347__LJMP static int hlua_applet_http_recv_yield(lua_State *L, int status, lua_KContext ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005348{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005349 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Willy Tarreauc12b3212022-05-27 11:08:15 +02005350 struct stconn *sc = appctx_sc(luactx->appctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02005351 struct channel *req = sc_oc(sc);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005352 struct htx *htx;
5353 struct htx_blk *blk;
5354 size_t count;
5355 int len;
5356
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005357 htx = htx_from_buf(&req->buf);
5358 len = MAY_LJMP(luaL_checkinteger(L, 2));
5359 count = co_data(req);
Christopher Faulet29f17582019-05-23 11:03:26 +02005360 blk = htx_get_head_blk(htx);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005361 while (count && len && blk) {
5362 enum htx_blk_type type = htx_get_blk_type(blk);
5363 uint32_t sz = htx_get_blksz(blk);
5364 struct ist v;
5365 uint32_t vlen;
5366
5367 vlen = sz;
5368 if (len > 0 && vlen > len)
5369 vlen = len;
5370 if (vlen > count) {
5371 if (type != HTX_BLK_DATA)
5372 break;
5373 vlen = count;
5374 }
5375
5376 switch (type) {
5377 case HTX_BLK_UNUSED:
5378 break;
5379
5380 case HTX_BLK_DATA:
5381 v = htx_get_blk_value(htx, blk);
Willy Tarreau7e702d12021-04-28 17:59:21 +02005382 luaL_addlstring(&luactx->b, v.ptr, vlen);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005383 break;
5384
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005385 case HTX_BLK_TLR:
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01005386 case HTX_BLK_EOT:
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005387 len = 0;
5388 break;
5389
5390 default:
5391 break;
5392 }
5393
Willy Tarreau84240042022-02-28 16:51:23 +01005394 c_rew(req, vlen);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005395 count -= vlen;
5396 if (len > 0)
5397 len -= vlen;
5398 if (sz == vlen)
5399 blk = htx_remove_blk(htx, blk);
5400 else {
5401 htx_cut_data_blk(htx, blk, vlen);
5402 break;
5403 }
5404 }
5405
Christopher Fauleteccb31c2021-04-02 14:24:56 +02005406 /* The message was fully consumed and no more data are expected
5407 * (EOM flag set).
5408 */
Christopher Faulet904763f2023-03-22 14:53:11 +01005409 if (htx_is_empty(htx) && (sc->flags & SC_FL_EOI))
Christopher Fauleteccb31c2021-04-02 14:24:56 +02005410 len = 0;
5411
Christopher Faulet0ae79d02019-02-27 21:36:59 +01005412 htx_to_buf(htx, &req->buf);
5413
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005414 /* If we are no other data available, yield waiting for new data. */
5415 if (len) {
5416 if (len > 0) {
5417 lua_pushinteger(L, len);
5418 lua_replace(L, 2);
5419 }
Willy Tarreau90e8b452022-05-25 18:21:43 +02005420 applet_need_more_data(luactx->appctx);
Willy Tarreau9635e032018-10-16 17:52:55 +02005421 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005422 }
5423
5424 /* return the result. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005425 luaL_pushresult(&luactx->b);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005426 return 1;
5427}
5428
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08005429/* Check arguments for the function "hlua_channel_get_yield". */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005430__LJMP static int hlua_applet_http_recv(lua_State *L)
5431{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005432 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005433 int len = -1;
5434
5435 /* Check arguments. */
5436 if (lua_gettop(L) > 2)
5437 WILL_LJMP(luaL_error(L, "The 'recv' function requires between 1 and 2 arguments."));
5438 if (lua_gettop(L) >= 2) {
5439 len = MAY_LJMP(luaL_checkinteger(L, 2));
5440 lua_pop(L, 1);
5441 }
5442
Christopher Fauleta2097962019-07-15 16:25:33 +02005443 lua_pushinteger(L, len);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005444
Christopher Fauleta2097962019-07-15 16:25:33 +02005445 /* Initialise the string catenation. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005446 luaL_buffinit(L, &luactx->b);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005447
Christopher Fauleta2097962019-07-15 16:25:33 +02005448 return MAY_LJMP(hlua_applet_http_recv_yield(L, 0, 0));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005449}
5450
5451/* Append data in the output side of the buffer. This data is immediately
5452 * sent. The function returns the amount of data written. If the buffer
5453 * cannot contain the data, the function yields. The function returns -1
5454 * if the channel is closed.
5455 */
Christopher Fauleta2097962019-07-15 16:25:33 +02005456__LJMP static int hlua_applet_http_send_yield(lua_State *L, int status, lua_KContext ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005457{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005458 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Willy Tarreauc12b3212022-05-27 11:08:15 +02005459 struct stconn *sc = appctx_sc(luactx->appctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02005460 struct channel *res = sc_ic(sc);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005461 struct htx *htx = htx_from_buf(&res->buf);
5462 const char *data;
5463 size_t len;
5464 int l = MAY_LJMP(luaL_checkinteger(L, 3));
5465 int max;
5466
Christopher Faulet9060fc02019-07-03 11:39:30 +02005467 max = htx_get_max_blksz(htx, channel_htx_recv_max(res, htx));
Christopher Faulet4b0e9b22019-01-09 12:16:58 +01005468 if (!max)
5469 goto snd_yield;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005470
5471 data = MAY_LJMP(luaL_checklstring(L, 2, &len));
5472
5473 /* Get the max amount of data which can write as input in the channel. */
5474 if (max > (len - l))
5475 max = len - l;
5476
5477 /* Copy data. */
Willy Tarreau0a7ef022019-05-28 10:30:11 +02005478 max = htx_add_data(htx, ist2(data + l, max));
Christopher Fauletf6cce3f2019-02-27 21:20:09 +01005479 channel_add_input(res, max);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005480
5481 /* update counters. */
5482 l += max;
5483 lua_pop(L, 1);
5484 lua_pushinteger(L, l);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005485
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005486 /* If some data is not send, declares the situation to the
5487 * applet, and returns a yield.
5488 */
5489 if (l < len) {
Christopher Faulet4b0e9b22019-01-09 12:16:58 +01005490 snd_yield:
Christopher Faulet0ae79d02019-02-27 21:36:59 +01005491 htx_to_buf(htx, &res->buf);
Christopher Faulet7b3d38a2023-05-05 11:28:45 +02005492 sc_need_room(sc, channel_recv_max(res) + 1);
Willy Tarreau9635e032018-10-16 17:52:55 +02005493 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005494 }
5495
Christopher Fauleta2097962019-07-15 16:25:33 +02005496 htx_to_buf(htx, &res->buf);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005497 return 1;
5498}
5499
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05005500/* Just a wrapper of "hlua_applet_send_yield". This wrapper permits
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005501 * yield the LUA process, and resume it without checking the
5502 * input arguments.
5503 */
5504__LJMP static int hlua_applet_http_send(lua_State *L)
5505{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005506 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005507 struct hlua_http_ctx *http_ctx = luactx->appctx->svcctx;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005508
5509 /* We want to send some data. Headers must be sent. */
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005510 if (!(http_ctx->flags & APPLET_HDR_SENT)) {
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005511 hlua_pusherror(L, "Lua: 'send' you must call start_response() before sending data.");
5512 WILL_LJMP(lua_error(L));
5513 }
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005514
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05005515 /* This integer is used for followinf the amount of data sent. */
Christopher Fauleta2097962019-07-15 16:25:33 +02005516 lua_pushinteger(L, 0);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005517
Christopher Fauleta2097962019-07-15 16:25:33 +02005518 return MAY_LJMP(hlua_applet_http_send_yield(L, 0, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005519}
5520
5521__LJMP static int hlua_applet_http_addheader(lua_State *L)
5522{
5523 const char *name;
5524 int ret;
5525
5526 MAY_LJMP(hlua_checkapplet_http(L, 1));
5527 name = MAY_LJMP(luaL_checkstring(L, 2));
5528 MAY_LJMP(luaL_checkstring(L, 3));
5529
5530 /* Push in the stack the "response" entry. */
5531 ret = lua_getfield(L, 1, "response");
5532 if (ret != LUA_TTABLE) {
5533 hlua_pusherror(L, "Lua: 'add_header' internal error: AppletHTTP['response'] "
5534 "is expected as an array. %s found", lua_typename(L, ret));
5535 WILL_LJMP(lua_error(L));
5536 }
5537
5538 /* check if the header is already registered if it is not
5539 * the case, register it.
5540 */
5541 ret = lua_getfield(L, -1, name);
5542 if (ret == LUA_TNIL) {
5543
5544 /* Entry not found. */
5545 lua_pop(L, 1); /* remove the nil. The "response" table is the top of the stack. */
5546
5547 /* Insert the new header name in the array in the top of the stack.
5548 * It left the new array in the top of the stack.
5549 */
5550 lua_newtable(L);
5551 lua_pushvalue(L, 2);
5552 lua_pushvalue(L, -2);
5553 lua_settable(L, -4);
5554
5555 } else if (ret != LUA_TTABLE) {
5556
5557 /* corruption error. */
5558 hlua_pusherror(L, "Lua: 'add_header' internal error: AppletHTTP['response']['%s'] "
5559 "is expected as an array. %s found", name, lua_typename(L, ret));
5560 WILL_LJMP(lua_error(L));
5561 }
5562
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -07005563 /* Now the top of thestack is an array of values. We push
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005564 * the header value as new entry.
5565 */
5566 lua_pushvalue(L, 3);
5567 ret = lua_rawlen(L, -2);
5568 lua_rawseti(L, -2, ret + 1);
5569 lua_pushboolean(L, 1);
5570 return 1;
5571}
5572
5573__LJMP static int hlua_applet_http_status(lua_State *L)
5574{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005575 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005576 int status = MAY_LJMP(luaL_checkinteger(L, 2));
Robin H. Johnson52f5db22017-01-01 13:10:52 -08005577 const char *reason = MAY_LJMP(luaL_optlstring(L, 3, NULL, NULL));
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005578 struct hlua_http_ctx *http_ctx = luactx->appctx->svcctx;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005579
5580 if (status < 100 || status > 599) {
5581 lua_pushboolean(L, 0);
5582 return 1;
5583 }
5584
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005585 http_ctx->status = status;
5586 http_ctx->reason = reason;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005587 lua_pushboolean(L, 1);
5588 return 1;
5589}
5590
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005591
Christopher Fauleta2097962019-07-15 16:25:33 +02005592__LJMP static int hlua_applet_http_send_response(lua_State *L)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005593{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005594 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005595 struct hlua_http_ctx *http_ctx = luactx->appctx->svcctx;
Willy Tarreauc12b3212022-05-27 11:08:15 +02005596 struct stconn *sc = appctx_sc(luactx->appctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02005597 struct channel *res = sc_ic(sc);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005598 struct htx *htx;
5599 struct htx_sl *sl;
5600 struct h1m h1m;
5601 const char *status, *reason;
5602 const char *name, *value;
5603 size_t nlen, vlen;
5604 unsigned int flags;
5605
5606 /* Send the message at once. */
5607 htx = htx_from_buf(&res->buf);
5608 h1m_init_res(&h1m);
5609
5610 /* Use the same http version than the request. */
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005611 status = ultoa_r(http_ctx->status, trash.area, trash.size);
5612 reason = http_ctx->reason;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005613 if (reason == NULL)
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005614 reason = http_get_reason(http_ctx->status);
5615 if (http_ctx->flags & APPLET_HTTP11) {
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005616 flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11);
5617 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.1"), ist(status), ist(reason));
5618 }
5619 else {
5620 flags = HTX_SL_F_IS_RESP;
5621 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.0"), ist(status), ist(reason));
5622 }
5623 if (!sl) {
5624 hlua_pusherror(L, "Lua applet http '%s': Failed to create response.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005625 luactx->appctx->rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005626 WILL_LJMP(lua_error(L));
5627 }
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005628 sl->info.res.status = http_ctx->status;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005629
5630 /* Get the array associated to the field "response" in the object AppletHTTP. */
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005631 if (lua_getfield(L, 1, "response") != LUA_TTABLE) {
5632 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response'] missing.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005633 luactx->appctx->rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005634 WILL_LJMP(lua_error(L));
5635 }
5636
5637 /* Browse the list of headers. */
5638 lua_pushnil(L);
5639 while(lua_next(L, -2) != 0) {
5640 /* We expect a string as -2. */
5641 if (lua_type(L, -2) != LUA_TSTRING) {
5642 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response'][] element must be a string. got %s.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005643 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005644 lua_typename(L, lua_type(L, -2)));
5645 WILL_LJMP(lua_error(L));
5646 }
5647 name = lua_tolstring(L, -2, &nlen);
5648
5649 /* We expect an array as -1. */
5650 if (lua_type(L, -1) != LUA_TTABLE) {
5651 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 +02005652 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005653 name,
5654 lua_typename(L, lua_type(L, -1)));
5655 WILL_LJMP(lua_error(L));
5656 }
5657
5658 /* Browse the table who is on the top of the stack. */
5659 lua_pushnil(L);
5660 while(lua_next(L, -2) != 0) {
5661 int id;
5662
5663 /* We expect a number as -2. */
5664 if (lua_type(L, -2) != LUA_TNUMBER) {
5665 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 +02005666 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005667 name,
5668 lua_typename(L, lua_type(L, -2)));
5669 WILL_LJMP(lua_error(L));
5670 }
5671 id = lua_tointeger(L, -2);
5672
5673 /* We expect a string as -2. */
5674 if (lua_type(L, -1) != LUA_TSTRING) {
5675 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 +02005676 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005677 name, id,
5678 lua_typename(L, lua_type(L, -1)));
5679 WILL_LJMP(lua_error(L));
5680 }
5681 value = lua_tolstring(L, -1, &vlen);
5682
5683 /* Simple Protocol checks. */
Christopher Faulet545fbba2021-09-28 09:36:25 +02005684 if (isteqi(ist2(name, nlen), ist("transfer-encoding"))) {
5685 int ret;
5686
5687 ret = h1_parse_xfer_enc_header(&h1m, ist2(value, vlen));
5688 if (ret < 0) {
5689 hlua_pusherror(L, "Lua applet http '%s': Invalid '%s' header.\n",
5690 luactx->appctx->rule->arg.hlua_rule->fcn->name,
5691 name);
5692 WILL_LJMP(lua_error(L));
5693 }
5694 else if (ret == 0)
5695 goto next; /* Skip it */
5696 }
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005697 else if (isteqi(ist2(name, nlen), ist("content-length"))) {
5698 struct ist v = ist2(value, vlen);
5699 int ret;
5700
5701 ret = h1_parse_cont_len_header(&h1m, &v);
5702 if (ret < 0) {
5703 hlua_pusherror(L, "Lua applet http '%s': Invalid '%s' header.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005704 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005705 name);
5706 WILL_LJMP(lua_error(L));
5707 }
5708 else if (ret == 0)
5709 goto next; /* Skip it */
5710 }
5711
5712 /* Add a new header */
5713 if (!htx_add_header(htx, ist2(name, nlen), ist2(value, vlen))) {
5714 hlua_pusherror(L, "Lua applet http '%s': Failed to add header '%s' in the response.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005715 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005716 name);
5717 WILL_LJMP(lua_error(L));
5718 }
5719 next:
5720 /* Remove the array from the stack, and get next element with a remaining string. */
5721 lua_pop(L, 1);
5722 }
5723
5724 /* Remove the array from the stack, and get next element with a remaining string. */
5725 lua_pop(L, 1);
5726 }
5727
5728 if (h1m.flags & H1_MF_CHNK)
5729 h1m.flags &= ~H1_MF_CLEN;
5730 if (h1m.flags & (H1_MF_CLEN|H1_MF_CHNK))
5731 h1m.flags |= H1_MF_XFER_LEN;
5732
5733 /* Uset HTX start-line flags */
5734 if (h1m.flags & H1_MF_XFER_ENC)
5735 flags |= HTX_SL_F_XFER_ENC;
5736 if (h1m.flags & H1_MF_XFER_LEN) {
5737 flags |= HTX_SL_F_XFER_LEN;
5738 if (h1m.flags & H1_MF_CHNK)
5739 flags |= HTX_SL_F_CHNK;
5740 else if (h1m.flags & H1_MF_CLEN)
5741 flags |= HTX_SL_F_CLEN;
5742 if (h1m.body_len == 0)
5743 flags |= HTX_SL_F_BODYLESS;
5744 }
5745 sl->flags |= flags;
5746
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -07005747 /* If we don't have a content-length set, and the HTTP version is 1.1
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005748 * and the status code implies the presence of a message body, we must
5749 * announce a transfer encoding chunked. This is required by haproxy
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05005750 * for the keepalive compliance. If the applet announces a transfer-encoding
5751 * chunked itself, don't do anything.
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005752 */
5753 if ((flags & (HTX_SL_F_VER_11|HTX_SL_F_XFER_LEN)) == HTX_SL_F_VER_11 &&
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005754 http_ctx->status >= 200 && http_ctx->status != 204 && http_ctx->status != 304) {
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005755 /* Add a new header */
5756 sl->flags |= (HTX_SL_F_XFER_ENC|H1_MF_CHNK|H1_MF_XFER_LEN);
5757 if (!htx_add_header(htx, ist("transfer-encoding"), ist("chunked"))) {
5758 hlua_pusherror(L, "Lua applet http '%s': Failed to add header 'transfer-encoding' in the response.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005759 luactx->appctx->rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005760 WILL_LJMP(lua_error(L));
5761 }
5762 }
5763
5764 /* Finalize headers. */
5765 if (!htx_add_endof(htx, HTX_BLK_EOH)) {
5766 hlua_pusherror(L, "Lua applet http '%s': Failed create the response.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005767 luactx->appctx->rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005768 WILL_LJMP(lua_error(L));
5769 }
5770
5771 if (htx_used_space(htx) > b_size(&res->buf) - global.tune.maxrewrite) {
5772 b_reset(&res->buf);
5773 hlua_pusherror(L, "Lua: 'start_response': response header block too big");
5774 WILL_LJMP(lua_error(L));
5775 }
5776
5777 htx_to_buf(htx, &res->buf);
Christopher Fauletf6cce3f2019-02-27 21:20:09 +01005778 channel_add_input(res, htx->data);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005779
5780 /* Headers sent, set the flag. */
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005781 http_ctx->flags |= APPLET_HDR_SENT;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005782 return 0;
5783
5784}
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005785/* We will build the status line and the headers of the HTTP response.
5786 * We will try send at once if its not possible, we give back the hand
5787 * waiting for more room.
5788 */
Christopher Fauleta2097962019-07-15 16:25:33 +02005789__LJMP static int hlua_applet_http_start_response_yield(lua_State *L, int status, lua_KContext ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005790{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005791 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Willy Tarreauc12b3212022-05-27 11:08:15 +02005792 struct stconn *sc = appctx_sc(luactx->appctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02005793 struct channel *res = sc_ic(sc);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005794
5795 if (co_data(res)) {
Christopher Faulet7b3d38a2023-05-05 11:28:45 +02005796 sc_need_room(sc, -1);
Christopher Fauleta2097962019-07-15 16:25:33 +02005797 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_start_response_yield, TICK_ETERNITY, 0));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005798 }
Christopher Fauleta2097962019-07-15 16:25:33 +02005799 return MAY_LJMP(hlua_applet_http_send_response(L));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005800}
5801
5802
Christopher Fauleta2097962019-07-15 16:25:33 +02005803__LJMP static int hlua_applet_http_start_response(lua_State *L)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005804{
Christopher Fauleta2097962019-07-15 16:25:33 +02005805 return MAY_LJMP(hlua_applet_http_start_response_yield(L, 0, 0));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005806}
5807
Christopher Fauleta2097962019-07-15 16:25:33 +02005808/*
5809 *
5810 *
5811 * Class HTTP
5812 *
5813 *
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005814 */
Christopher Fauleta2097962019-07-15 16:25:33 +02005815
5816/* Returns a struct hlua_txn if the stack entry "ud" is
5817 * a class stream, otherwise it throws an error.
5818 */
5819__LJMP static struct hlua_txn *hlua_checkhttp(lua_State *L, int ud)
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005820{
Christopher Fauleta2097962019-07-15 16:25:33 +02005821 return MAY_LJMP(hlua_checkudata(L, ud, class_http_ref));
5822}
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005823
Christopher Fauleta2097962019-07-15 16:25:33 +02005824/* This function creates and push in the stack a HTTP object
5825 * according with a current TXN.
5826 */
5827static int hlua_http_new(lua_State *L, struct hlua_txn *txn)
5828{
5829 struct hlua_txn *htxn;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005830
Christopher Fauleta2097962019-07-15 16:25:33 +02005831 /* Check stack size. */
5832 if (!lua_checkstack(L, 3))
5833 return 0;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005834
Christopher Fauleta2097962019-07-15 16:25:33 +02005835 /* Create the object: obj[0] = userdata.
5836 * Note that the base of the Converters object is the
5837 * same than the TXN object.
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005838 */
Christopher Fauleta2097962019-07-15 16:25:33 +02005839 lua_newtable(L);
5840 htxn = lua_newuserdata(L, sizeof(*htxn));
5841 lua_rawseti(L, -2, 0);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005842
5843 htxn->s = txn->s;
5844 htxn->p = txn->p;
Christopher Faulet256b69a2019-05-23 11:14:21 +02005845 htxn->dir = txn->dir;
5846 htxn->flags = txn->flags;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005847
5848 /* Pop a class stream metatable and affect it to the table. */
5849 lua_rawgeti(L, LUA_REGISTRYINDEX, class_http_ref);
5850 lua_setmetatable(L, -2);
5851
5852 return 1;
5853}
5854
Christopher Fauletdf97ac42020-02-26 16:57:19 +01005855/* This function creates and returns an array containing the status-line
5856 * elements. This function does not fails.
5857 */
5858__LJMP static int hlua_http_get_stline(lua_State *L, struct htx_sl *sl)
5859{
5860 /* Create the table. */
5861 lua_newtable(L);
5862
5863 if (sl->flags & HTX_SL_F_IS_RESP) {
5864 lua_pushstring(L, "version");
5865 lua_pushlstring(L, HTX_SL_RES_VPTR(sl), HTX_SL_RES_VLEN(sl));
5866 lua_settable(L, -3);
5867 lua_pushstring(L, "code");
5868 lua_pushlstring(L, HTX_SL_RES_CPTR(sl), HTX_SL_RES_CLEN(sl));
5869 lua_settable(L, -3);
5870 lua_pushstring(L, "reason");
5871 lua_pushlstring(L, HTX_SL_RES_RPTR(sl), HTX_SL_RES_RLEN(sl));
5872 lua_settable(L, -3);
5873 }
5874 else {
5875 lua_pushstring(L, "method");
5876 lua_pushlstring(L, HTX_SL_REQ_MPTR(sl), HTX_SL_REQ_MLEN(sl));
5877 lua_settable(L, -3);
5878 lua_pushstring(L, "uri");
5879 lua_pushlstring(L, HTX_SL_REQ_UPTR(sl), HTX_SL_REQ_ULEN(sl));
5880 lua_settable(L, -3);
5881 lua_pushstring(L, "version");
5882 lua_pushlstring(L, HTX_SL_REQ_VPTR(sl), HTX_SL_REQ_VLEN(sl));
5883 lua_settable(L, -3);
5884 }
5885 return 1;
5886}
5887
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005888/* This function creates ans returns an array of HTTP headers.
5889 * This function does not fails. It is used as wrapper with the
5890 * 2 following functions.
5891 */
Christopher Faulet9d1332b2020-02-24 16:46:16 +01005892__LJMP static int hlua_http_get_headers(lua_State *L, struct http_msg *msg)
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005893{
Christopher Fauleta2097962019-07-15 16:25:33 +02005894 struct htx *htx;
5895 int32_t pos;
5896
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005897 /* Create the table. */
5898 lua_newtable(L);
5899
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005900
Christopher Fauleta2097962019-07-15 16:25:33 +02005901 htx = htxbuf(&msg->chn->buf);
5902 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
5903 struct htx_blk *blk = htx_get_blk(htx, pos);
5904 enum htx_blk_type type = htx_get_blk_type(blk);
5905 struct ist n, v;
5906 int len;
Christopher Faulet724a12c2018-12-13 22:12:15 +01005907
Christopher Fauleta2097962019-07-15 16:25:33 +02005908 if (type == HTX_BLK_HDR) {
5909 n = htx_get_blk_name(htx,blk);
5910 v = htx_get_blk_value(htx, blk);
Christopher Faulet724a12c2018-12-13 22:12:15 +01005911 }
Christopher Fauleta2097962019-07-15 16:25:33 +02005912 else if (type == HTX_BLK_EOH)
5913 break;
5914 else
5915 continue;
Christopher Faulet724a12c2018-12-13 22:12:15 +01005916
Christopher Fauleta2097962019-07-15 16:25:33 +02005917 /* Check for existing entry:
5918 * assume that the table is on the top of the stack, and
5919 * push the key in the stack, the function lua_gettable()
5920 * perform the lookup.
5921 */
5922 lua_pushlstring(L, n.ptr, n.len);
5923 lua_gettable(L, -2);
Christopher Faulet724a12c2018-12-13 22:12:15 +01005924
Christopher Fauleta2097962019-07-15 16:25:33 +02005925 switch (lua_type(L, -1)) {
5926 case LUA_TNIL:
5927 /* Table not found, create it. */
5928 lua_pop(L, 1); /* remove the nil value. */
5929 lua_pushlstring(L, n.ptr, n.len); /* push the header name as key. */
5930 lua_newtable(L); /* create and push empty table. */
5931 lua_pushlstring(L, v.ptr, v.len); /* push header value. */
5932 lua_rawseti(L, -2, 0); /* index header value (pop it). */
5933 lua_rawset(L, -3); /* index new table with header name (pop the values). */
Christopher Faulet724a12c2018-12-13 22:12:15 +01005934 break;
Christopher Faulet724a12c2018-12-13 22:12:15 +01005935
Christopher Fauleta2097962019-07-15 16:25:33 +02005936 case LUA_TTABLE:
5937 /* Entry found: push the value in the table. */
5938 len = lua_rawlen(L, -1);
5939 lua_pushlstring(L, v.ptr, v.len); /* push header value. */
5940 lua_rawseti(L, -2, len+1); /* index header value (pop it). */
5941 lua_pop(L, 1); /* remove the table (it is stored in the main table). */
5942 break;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005943
Christopher Fauleta2097962019-07-15 16:25:33 +02005944 default:
5945 /* Other cases are errors. */
5946 hlua_pusherror(L, "internal error during the parsing of headers.");
5947 WILL_LJMP(lua_error(L));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005948 }
5949 }
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005950 return 1;
5951}
5952
5953__LJMP static int hlua_http_req_get_headers(lua_State *L)
5954{
5955 struct hlua_txn *htxn;
5956
5957 MAY_LJMP(check_args(L, 1, "req_get_headers"));
5958 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5959
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005960 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005961 WILL_LJMP(lua_error(L));
5962
Christopher Faulet9d1332b2020-02-24 16:46:16 +01005963 return hlua_http_get_headers(L, &htxn->s->txn->req);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005964}
5965
5966__LJMP static int hlua_http_res_get_headers(lua_State *L)
5967{
5968 struct hlua_txn *htxn;
5969
5970 MAY_LJMP(check_args(L, 1, "res_get_headers"));
5971 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5972
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005973 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005974 WILL_LJMP(lua_error(L));
5975
Christopher Faulet9d1332b2020-02-24 16:46:16 +01005976 return hlua_http_get_headers(L, &htxn->s->txn->rsp);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005977}
5978
5979/* This function replace full header, or just a value in
5980 * the request or in the response. It is a wrapper fir the
5981 * 4 following functions.
5982 */
Christopher Fauletd1914aa2020-02-24 16:52:46 +01005983__LJMP static inline int hlua_http_rep_hdr(lua_State *L, struct http_msg *msg, int full)
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005984{
5985 size_t name_len;
5986 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
5987 const char *reg = MAY_LJMP(luaL_checkstring(L, 3));
5988 const char *value = MAY_LJMP(luaL_checkstring(L, 4));
Christopher Fauleta2097962019-07-15 16:25:33 +02005989 struct htx *htx;
Dragan Dosen26743032019-04-30 15:54:36 +02005990 struct my_regex *re;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005991
Dragan Dosen26743032019-04-30 15:54:36 +02005992 if (!(re = regex_comp(reg, 1, 1, NULL)))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005993 WILL_LJMP(luaL_argerror(L, 3, "invalid regex"));
5994
Christopher Fauleta2097962019-07-15 16:25:33 +02005995 htx = htxbuf(&msg->chn->buf);
Christopher Fauletd1914aa2020-02-24 16:52:46 +01005996 http_replace_hdrs(chn_strm(msg->chn), htx, ist2(name, name_len), value, re, full);
Dragan Dosen26743032019-04-30 15:54:36 +02005997 regex_free(re);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005998 return 0;
5999}
6000
6001__LJMP static int hlua_http_req_rep_hdr(lua_State *L)
6002{
6003 struct hlua_txn *htxn;
6004
6005 MAY_LJMP(check_args(L, 4, "req_rep_hdr"));
6006 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
6007
Christopher Fauletd8f0e072020-02-25 09:45:51 +01006008 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006009 WILL_LJMP(lua_error(L));
6010
Christopher Fauletd1914aa2020-02-24 16:52:46 +01006011 return MAY_LJMP(hlua_http_rep_hdr(L, &htxn->s->txn->req, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006012}
6013
6014__LJMP static int hlua_http_res_rep_hdr(lua_State *L)
6015{
6016 struct hlua_txn *htxn;
6017
6018 MAY_LJMP(check_args(L, 4, "res_rep_hdr"));
6019 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
6020
Christopher Fauletd8f0e072020-02-25 09:45:51 +01006021 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006022 WILL_LJMP(lua_error(L));
6023
Christopher Fauletd1914aa2020-02-24 16:52:46 +01006024 return MAY_LJMP(hlua_http_rep_hdr(L, &htxn->s->txn->rsp, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006025}
6026
6027__LJMP static int hlua_http_req_rep_val(lua_State *L)
6028{
6029 struct hlua_txn *htxn;
6030
6031 MAY_LJMP(check_args(L, 4, "req_rep_hdr"));
6032 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
6033
Christopher Fauletd8f0e072020-02-25 09:45:51 +01006034 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006035 WILL_LJMP(lua_error(L));
6036
Christopher Fauletd1914aa2020-02-24 16:52:46 +01006037 return MAY_LJMP(hlua_http_rep_hdr(L, &htxn->s->txn->req, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006038}
6039
6040__LJMP static int hlua_http_res_rep_val(lua_State *L)
6041{
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006042 struct hlua_txn *htxn;
6043
6044 MAY_LJMP(check_args(L, 4, "res_rep_val"));
6045 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
6046
Christopher Fauletd8f0e072020-02-25 09:45:51 +01006047 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006048 WILL_LJMP(lua_error(L));
6049
Christopher Fauletd1914aa2020-02-24 16:52:46 +01006050 return MAY_LJMP(hlua_http_rep_hdr(L, &htxn->s->txn->rsp, 0));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006051}
6052
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08006053/* This function deletes all the occurrences of an header.
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006054 * It is a wrapper for the 2 following functions.
6055 */
Christopher Fauletd31c7b32020-02-25 09:37:57 +01006056__LJMP static inline int hlua_http_del_hdr(lua_State *L, struct http_msg *msg)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006057{
6058 size_t len;
6059 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Christopher Fauleta2097962019-07-15 16:25:33 +02006060 struct htx *htx = htxbuf(&msg->chn->buf);
6061 struct http_hdr_ctx ctx;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006062
Christopher Fauleta2097962019-07-15 16:25:33 +02006063 ctx.blk = NULL;
6064 while (http_find_header(htx, ist2(name, len), &ctx, 1))
6065 http_remove_header(htx, &ctx);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006066 return 0;
6067}
6068
6069__LJMP static int hlua_http_req_del_hdr(lua_State *L)
6070{
6071 struct hlua_txn *htxn;
6072
6073 MAY_LJMP(check_args(L, 2, "req_del_hdr"));
6074 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
6075
Christopher Fauletd8f0e072020-02-25 09:45:51 +01006076 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006077 WILL_LJMP(lua_error(L));
6078
Christopher Fauletd31c7b32020-02-25 09:37:57 +01006079 return hlua_http_del_hdr(L, &htxn->s->txn->req);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006080}
6081
6082__LJMP static int hlua_http_res_del_hdr(lua_State *L)
6083{
6084 struct hlua_txn *htxn;
6085
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006086 MAY_LJMP(check_args(L, 2, "res_del_hdr"));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006087 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
6088
Christopher Fauletd8f0e072020-02-25 09:45:51 +01006089 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006090 WILL_LJMP(lua_error(L));
6091
Christopher Fauletd31c7b32020-02-25 09:37:57 +01006092 return hlua_http_del_hdr(L, &htxn->s->txn->rsp);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006093}
6094
6095/* This function adds an header. It is a wrapper used by
6096 * the 2 following functions.
6097 */
Christopher Fauletd31c7b32020-02-25 09:37:57 +01006098__LJMP static inline int hlua_http_add_hdr(lua_State *L, struct http_msg *msg)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006099{
6100 size_t name_len;
6101 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
6102 size_t value_len;
6103 const char *value = MAY_LJMP(luaL_checklstring(L, 3, &value_len));
Christopher Fauleta2097962019-07-15 16:25:33 +02006104 struct htx *htx = htxbuf(&msg->chn->buf);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006105
Christopher Fauleta2097962019-07-15 16:25:33 +02006106 lua_pushboolean(L, http_add_header(htx, ist2(name, name_len),
6107 ist2(value, value_len)));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006108 return 0;
6109}
6110
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006111__LJMP static int hlua_http_req_add_hdr(lua_State *L)
6112{
6113 struct hlua_txn *htxn;
6114
6115 MAY_LJMP(check_args(L, 3, "req_add_hdr"));
6116 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
6117
6118 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
6119 WILL_LJMP(lua_error(L));
6120
6121 return hlua_http_add_hdr(L, &htxn->s->txn->req);
6122}
6123
6124__LJMP static int hlua_http_res_add_hdr(lua_State *L)
6125{
6126 struct hlua_txn *htxn;
6127
6128 MAY_LJMP(check_args(L, 3, "res_add_hdr"));
6129 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
6130
6131 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
6132 WILL_LJMP(lua_error(L));
6133
6134 return hlua_http_add_hdr(L, &htxn->s->txn->rsp);
6135}
6136
6137static int hlua_http_req_set_hdr(lua_State *L)
6138{
6139 struct hlua_txn *htxn;
6140
6141 MAY_LJMP(check_args(L, 3, "req_set_hdr"));
6142 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
6143
6144 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
6145 WILL_LJMP(lua_error(L));
6146
6147 hlua_http_del_hdr(L, &htxn->s->txn->req);
6148 return hlua_http_add_hdr(L, &htxn->s->txn->req);
6149}
6150
6151static int hlua_http_res_set_hdr(lua_State *L)
6152{
6153 struct hlua_txn *htxn;
6154
6155 MAY_LJMP(check_args(L, 3, "res_set_hdr"));
6156 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
6157
6158 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
6159 WILL_LJMP(lua_error(L));
6160
6161 hlua_http_del_hdr(L, &htxn->s->txn->rsp);
6162 return hlua_http_add_hdr(L, &htxn->s->txn->rsp);
6163}
6164
6165/* This function set the method. */
6166static int hlua_http_req_set_meth(lua_State *L)
6167{
6168 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
6169 size_t name_len;
6170 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
6171
6172 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
6173 WILL_LJMP(lua_error(L));
6174
6175 lua_pushboolean(L, http_req_replace_stline(0, name, name_len, htxn->p, htxn->s) != -1);
6176 return 1;
6177}
6178
6179/* This function set the method. */
6180static int hlua_http_req_set_path(lua_State *L)
6181{
6182 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
6183 size_t name_len;
6184 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
6185
6186 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
6187 WILL_LJMP(lua_error(L));
6188
6189 lua_pushboolean(L, http_req_replace_stline(1, name, name_len, htxn->p, htxn->s) != -1);
6190 return 1;
6191}
6192
6193/* This function set the query-string. */
6194static int hlua_http_req_set_query(lua_State *L)
6195{
6196 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
6197 size_t name_len;
6198 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
6199
6200 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
6201 WILL_LJMP(lua_error(L));
6202
6203 /* Check length. */
6204 if (name_len > trash.size - 1) {
6205 lua_pushboolean(L, 0);
6206 return 1;
6207 }
6208
6209 /* Add the mark question as prefix. */
6210 chunk_reset(&trash);
6211 trash.area[trash.data++] = '?';
6212 memcpy(trash.area + trash.data, name, name_len);
6213 trash.data += name_len;
6214
6215 lua_pushboolean(L,
6216 http_req_replace_stline(2, trash.area, trash.data, htxn->p, htxn->s) != -1);
6217 return 1;
6218}
6219
6220/* This function set the uri. */
6221static int hlua_http_req_set_uri(lua_State *L)
6222{
6223 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
6224 size_t name_len;
6225 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
6226
6227 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
6228 WILL_LJMP(lua_error(L));
6229
6230 lua_pushboolean(L, http_req_replace_stline(3, name, name_len, htxn->p, htxn->s) != -1);
6231 return 1;
6232}
6233
6234/* This function set the response code & optionally reason. */
6235static int hlua_http_res_set_status(lua_State *L)
6236{
6237 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
6238 unsigned int code = MAY_LJMP(luaL_checkinteger(L, 2));
6239 const char *str = MAY_LJMP(luaL_optlstring(L, 3, NULL, NULL));
6240 const struct ist reason = ist2(str, (str ? strlen(str) : 0));
6241
6242 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
6243 WILL_LJMP(lua_error(L));
6244
6245 http_res_set_status(code, reason, htxn->s);
6246 return 0;
6247}
6248
6249/*
6250 *
6251 *
6252 * Class HTTPMessage
6253 *
6254 *
6255 */
6256
6257/* Returns a struct http_msg if the stack entry "ud" is a class HTTPMessage,
6258 * otherwise it throws an error.
6259 */
6260__LJMP static struct http_msg *hlua_checkhttpmsg(lua_State *L, int ud)
6261{
6262 return MAY_LJMP(hlua_checkudata(L, ud, class_http_msg_ref));
6263}
6264
6265/* Creates and pushes on the stack a HTTP object according with a current TXN.
6266 */
Christopher Faulet78c35472020-02-26 17:14:08 +01006267static int hlua_http_msg_new(lua_State *L, struct http_msg *msg)
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006268{
6269 /* Check stack size. */
6270 if (!lua_checkstack(L, 3))
6271 return 0;
6272
6273 lua_newtable(L);
6274 lua_pushlightuserdata(L, msg);
6275 lua_rawseti(L, -2, 0);
6276
6277 /* Create the "channel" field that contains the request channel object. */
6278 lua_pushstring(L, "channel");
6279 if (!hlua_channel_new(L, msg->chn))
6280 return 0;
6281 lua_rawset(L, -3);
6282
6283 /* Pop a class stream metatable and affect it to the table. */
6284 lua_rawgeti(L, LUA_REGISTRYINDEX, class_http_msg_ref);
6285 lua_setmetatable(L, -2);
6286
6287 return 1;
6288}
6289
6290/* Helper function returning a filter attached to the HTTP message at the
6291 * position <ud> in the stack, filling the current offset and length of the
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006292 * filter. If no filter is attached, NULL is returned and <offset> and <len> are
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006293 * filled with output and input length respectively.
6294 */
6295static struct filter *hlua_http_msg_filter(lua_State *L, int ud, struct http_msg *msg, size_t *offset, size_t *len)
6296{
6297 struct channel *chn = msg->chn;
6298 struct htx *htx = htxbuf(&chn->buf);
6299 struct filter *filter = NULL;
6300
6301 *offset = co_data(msg->chn);
6302 *len = htx->data - co_data(msg->chn);
6303
6304 if (lua_getfield(L, ud, "__filter") == LUA_TLIGHTUSERDATA) {
6305 filter = lua_touserdata (L, -1);
6306 if (msg->msg_state >= HTTP_MSG_DATA) {
6307 struct hlua_flt_ctx *flt_ctx = filter->ctx;
6308
6309 *offset = flt_ctx->cur_off[CHN_IDX(chn)];
6310 *len = flt_ctx->cur_len[CHN_IDX(chn)];
6311 }
6312 }
6313
6314 lua_pop(L, 1);
6315 return filter;
6316}
6317
6318/* Returns true if the channel attached to the HTTP message is the response
6319 * channel.
6320 */
6321__LJMP static int hlua_http_msg_is_resp(lua_State *L)
6322{
6323 struct http_msg *msg;
6324
6325 MAY_LJMP(check_args(L, 1, "is_resp"));
6326 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6327
6328 lua_pushboolean(L, !!(msg->chn->flags & CF_ISRESP));
6329 return 1;
6330}
6331
6332/* Returns an array containing the elements status-line of the HTTP message. It relies
6333 * on hlua_http_get_stline().
6334 */
6335__LJMP static int hlua_http_msg_get_stline(lua_State *L)
6336{
6337 struct http_msg *msg;
6338 struct htx *htx;
6339 struct htx_sl *sl;
6340
6341 MAY_LJMP(check_args(L, 1, "get_stline"));
6342 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6343
6344 if (msg->msg_state > HTTP_MSG_BODY)
6345 WILL_LJMP(lua_error(L));
6346
6347 htx = htxbuf(&msg->chn->buf);
6348 sl = http_get_stline(htx);
6349 if (!sl)
6350 return 0;
6351 return hlua_http_get_stline(L, sl);
6352}
6353
6354/* Returns an array containing all headers of the HTTP message. it relies on
6355 * hlua_http_get_headers().
6356 */
6357__LJMP static int hlua_http_msg_get_headers(lua_State *L)
6358{
6359 struct http_msg *msg;
6360
6361 MAY_LJMP(check_args(L, 1, "get_headers"));
6362 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6363
6364 if (msg->msg_state > HTTP_MSG_BODY)
6365 WILL_LJMP(lua_error(L));
6366
6367 return hlua_http_get_headers(L, msg);
6368}
6369
6370/* Deletes all occurrences of an header in the HTTP message matching on its
6371 * name. It relies on hlua_http_del_hdr().
6372 */
6373__LJMP static int hlua_http_msg_del_hdr(lua_State *L)
6374{
6375 struct http_msg *msg;
6376
6377 MAY_LJMP(check_args(L, 2, "del_header"));
6378 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6379
6380 if (msg->msg_state > HTTP_MSG_BODY)
6381 WILL_LJMP(lua_error(L));
6382
6383 return hlua_http_del_hdr(L, msg);
6384}
6385
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006386/* Matches the full value line of all occurrences of an header in the HTTP
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006387 * message given its name against a regex and replaces it if it matches. It
6388 * relies on hlua_http_rep_hdr().
6389 */
6390__LJMP static int hlua_http_msg_rep_hdr(lua_State *L)
6391{
6392 struct http_msg *msg;
6393
6394 MAY_LJMP(check_args(L, 4, "rep_header"));
6395 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6396
6397 if (msg->msg_state > HTTP_MSG_BODY)
6398 WILL_LJMP(lua_error(L));
6399
6400 return hlua_http_rep_hdr(L, msg, 1);
6401}
6402
Ilya Shipitsinbd6b4be2021-10-15 16:18:21 +05006403/* Matches all comma-separated values of all occurrences of an header in the HTTP
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006404 * message given its name against a regex and replaces it if it matches. It
6405 * relies on hlua_http_rep_hdr().
6406 */
6407__LJMP static int hlua_http_msg_rep_val(lua_State *L)
6408{
6409 struct http_msg *msg;
6410
6411 MAY_LJMP(check_args(L, 4, "rep_value"));
6412 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6413
6414 if (msg->msg_state > HTTP_MSG_BODY)
6415 WILL_LJMP(lua_error(L));
6416
6417 return hlua_http_rep_hdr(L, msg, 0);
6418}
6419
6420/* Add an header in the HTTP message. It relies on hlua_http_add_hdr() */
6421__LJMP static int hlua_http_msg_add_hdr(lua_State *L)
6422{
6423 struct http_msg *msg;
6424
6425 MAY_LJMP(check_args(L, 3, "add_header"));
6426 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6427
6428 if (msg->msg_state > HTTP_MSG_BODY)
6429 WILL_LJMP(lua_error(L));
6430
6431 return hlua_http_add_hdr(L, msg);
6432}
6433
6434/* Add an header in the HTTP message removing existing headers with the same
6435 * name. It relies on hlua_http_del_hdr() and hlua_http_add_hdr().
6436 */
6437__LJMP static int hlua_http_msg_set_hdr(lua_State *L)
6438{
6439 struct http_msg *msg;
6440
6441 MAY_LJMP(check_args(L, 3, "set_header"));
6442 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6443
6444 if (msg->msg_state > HTTP_MSG_BODY)
6445 WILL_LJMP(lua_error(L));
6446
6447 hlua_http_del_hdr(L, msg);
6448 return hlua_http_add_hdr(L, msg);
6449}
6450
6451/* Rewrites the request method. It relies on http_req_replace_stline(). */
6452__LJMP static int hlua_http_msg_set_meth(lua_State *L)
6453{
6454 struct stream *s;
6455 struct http_msg *msg;
6456 const char *name;
6457 size_t name_len;
6458
6459 MAY_LJMP(check_args(L, 2, "set_method"));
6460 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6461 name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
6462
6463 if ((msg->chn->flags & CF_ISRESP) || msg->msg_state > HTTP_MSG_BODY)
6464 WILL_LJMP(lua_error(L));
6465
6466 s = chn_strm(msg->chn);
6467 lua_pushboolean(L, http_req_replace_stline(0, name, name_len, s->be, s) != -1);
6468 return 1;
6469}
6470
6471/* Rewrites the request path. It relies on http_req_replace_stline(). */
6472__LJMP static int hlua_http_msg_set_path(lua_State *L)
6473{
6474 struct stream *s;
6475 struct http_msg *msg;
6476 const char *name;
6477 size_t name_len;
6478
6479 MAY_LJMP(check_args(L, 2, "set_path"));
6480 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6481 name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
6482
6483 if ((msg->chn->flags & CF_ISRESP) || msg->msg_state > HTTP_MSG_BODY)
6484 WILL_LJMP(lua_error(L));
6485
6486 s = chn_strm(msg->chn);
6487 lua_pushboolean(L, http_req_replace_stline(1, name, name_len, s->be, s) != -1);
6488 return 1;
6489}
6490
6491/* Rewrites the request query-string. It relies on http_req_replace_stline(). */
6492__LJMP static int hlua_http_msg_set_query(lua_State *L)
6493{
6494 struct stream *s;
6495 struct http_msg *msg;
6496 const char *name;
6497 size_t name_len;
6498
6499 MAY_LJMP(check_args(L, 2, "set_query"));
6500 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6501 name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
6502
6503 if ((msg->chn->flags & CF_ISRESP) || msg->msg_state > HTTP_MSG_BODY)
6504 WILL_LJMP(lua_error(L));
6505
6506 /* Check length. */
6507 if (name_len > trash.size - 1) {
6508 lua_pushboolean(L, 0);
6509 return 1;
6510 }
6511
6512 /* Add the mark question as prefix. */
6513 chunk_reset(&trash);
6514 trash.area[trash.data++] = '?';
6515 memcpy(trash.area + trash.data, name, name_len);
6516 trash.data += name_len;
6517
6518 s = chn_strm(msg->chn);
6519 lua_pushboolean(L, http_req_replace_stline(2, trash.area, trash.data, s->be, s) != -1);
6520 return 1;
6521}
6522
6523/* Rewrites the request URI. It relies on http_req_replace_stline(). */
6524__LJMP static int hlua_http_msg_set_uri(lua_State *L)
6525{
6526 struct stream *s;
6527 struct http_msg *msg;
6528 const char *name;
6529 size_t name_len;
6530
6531 MAY_LJMP(check_args(L, 2, "set_uri"));
6532 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6533 name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
6534
6535 if ((msg->chn->flags & CF_ISRESP) || msg->msg_state > HTTP_MSG_BODY)
6536 WILL_LJMP(lua_error(L));
6537
6538 s = chn_strm(msg->chn);
6539 lua_pushboolean(L, http_req_replace_stline(3, name, name_len, s->be, s) != -1);
6540 return 1;
6541}
6542
6543/* Rewrites the response status code. It relies on http_res_set_status(). */
6544__LJMP static int hlua_http_msg_set_status(lua_State *L)
6545{
6546 struct http_msg *msg;
6547 unsigned int code;
6548 const char *reason;
6549 size_t reason_len;
6550
6551 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6552 code = MAY_LJMP(luaL_checkinteger(L, 2));
6553 reason = MAY_LJMP(luaL_optlstring(L, 3, NULL, &reason_len));
6554
6555 if (!(msg->chn->flags & CF_ISRESP) || msg->msg_state > HTTP_MSG_BODY)
6556 WILL_LJMP(lua_error(L));
6557
6558 lua_pushboolean(L, http_res_set_status(code, ist2(reason, reason_len), chn_strm(msg->chn)) != -1);
6559 return 1;
6560}
6561
6562/* Returns true if the HTTP message is full. */
6563__LJMP static int hlua_http_msg_is_full(lua_State *L)
6564{
6565 struct http_msg *msg;
6566
6567 MAY_LJMP(check_args(L, 1, "is_full"));
6568 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6569 lua_pushboolean(L, channel_full(msg->chn, 0));
6570 return 1;
6571}
6572
6573/* Returns true if the HTTP message may still receive data. */
6574__LJMP static int hlua_http_msg_may_recv(lua_State *L)
6575{
6576 struct http_msg *msg;
6577 struct htx *htx;
6578
6579 MAY_LJMP(check_args(L, 1, "may_recv"));
6580 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6581 htx = htxbuf(&msg->chn->buf);
6582 lua_pushboolean(L, (htx_expect_more(htx) && !channel_input_closed(msg->chn) && channel_may_recv(msg->chn)));
6583 return 1;
6584}
6585
6586/* Returns true if the HTTP message EOM was received */
6587__LJMP static int hlua_http_msg_is_eom(lua_State *L)
6588{
6589 struct http_msg *msg;
6590 struct htx *htx;
6591
6592 MAY_LJMP(check_args(L, 1, "may_recv"));
6593 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6594 htx = htxbuf(&msg->chn->buf);
6595 lua_pushboolean(L, !htx_expect_more(htx));
6596 return 1;
6597}
6598
6599/* Returns the number of bytes available in the input side of the HTTP
6600 * message. This function never fails.
6601 */
6602__LJMP static int hlua_http_msg_get_in_len(lua_State *L)
6603{
6604 struct http_msg *msg;
Christopher Fauleteae8afa2020-02-26 17:15:48 +01006605 size_t output, input;
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006606
6607 MAY_LJMP(check_args(L, 1, "input"));
6608 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
Christopher Fauleteae8afa2020-02-26 17:15:48 +01006609 hlua_http_msg_filter(L, 1, msg, &output, &input);
6610 lua_pushinteger(L, input);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006611 return 1;
6612}
6613
6614/* Returns the number of bytes available in the output side of the HTTP
6615 * message. This function never fails.
6616 */
6617__LJMP static int hlua_http_msg_get_out_len(lua_State *L)
6618{
6619 struct http_msg *msg;
Christopher Fauleteae8afa2020-02-26 17:15:48 +01006620 size_t output, input;
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006621
6622 MAY_LJMP(check_args(L, 1, "output"));
6623 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
Christopher Fauleteae8afa2020-02-26 17:15:48 +01006624 hlua_http_msg_filter(L, 1, msg, &output, &input);
6625 lua_pushinteger(L, output);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006626 return 1;
6627}
6628
6629/* Copies at most <len> bytes of DATA blocks from the HTTP message <msg>
6630 * starting at the offset <offset> and put it in a string LUA variables. It
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006631 * returns the built string length. It stops on the first non-DATA HTX
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006632 * block. This function is called during the payload filtering, so the headers
6633 * are already scheduled for output (from the filter point of view).
6634 */
6635static int _hlua_http_msg_dup(struct http_msg *msg, lua_State *L, size_t offset, size_t len)
6636{
6637 struct htx *htx = htxbuf(&msg->chn->buf);
6638 struct htx_blk *blk;
6639 struct htx_ret htxret;
6640 luaL_Buffer b;
6641 int ret = 0;
6642
6643 luaL_buffinit(L, &b);
6644 htxret = htx_find_offset(htx, offset);
6645 for (blk = htxret.blk, offset = htxret.ret; blk && len; blk = htx_get_next_blk(htx, blk)) {
6646 enum htx_blk_type type = htx_get_blk_type(blk);
6647 struct ist v;
6648
6649 switch (type) {
6650 case HTX_BLK_UNUSED:
6651 break;
6652
6653 case HTX_BLK_DATA:
6654 v = htx_get_blk_value(htx, blk);
Tim Duesterhusb113b5c2021-09-15 13:58:44 +02006655 v = istadv(v, offset);
Tim Duesterhus2471f5c2021-11-08 09:05:01 +01006656 v = isttrim(v, len);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006657
6658 luaL_addlstring(&b, v.ptr, v.len);
6659 ret += v.len;
6660 break;
6661
6662 default:
vishnu0af4bd72021-10-24 06:46:24 +05306663 if (!ret)
6664 goto no_data;
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006665 goto end;
6666 }
6667 offset = 0;
6668 }
6669
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006670end:
vishnu0af4bd72021-10-24 06:46:24 +05306671 if (!ret && (htx->flags & HTX_FL_EOM))
6672 goto no_data;
6673 luaL_pushresult(&b);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006674 return ret;
vishnu0af4bd72021-10-24 06:46:24 +05306675
6676 no_data:
6677 /* Remove the empty string and push nil on the stack */
6678 lua_pop(L, 1);
6679 lua_pushnil(L);
6680 return 0;
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006681}
6682
6683/* Copies the string <str> to the HTTP message <msg> at the offset
6684 * <offset>. This function returns -1 if data cannot be copied. Otherwise, it
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006685 * returns the amount of data written. This function is responsible to update
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006686 * the filter context.
6687 */
6688static int _hlua_http_msg_insert(struct http_msg *msg, struct filter *filter, struct ist str, size_t offset)
6689{
6690 struct htx *htx = htx_from_buf(&msg->chn->buf);
6691 struct htx_ret htxret;
6692 int /*max, */ret = 0;
6693
6694 /* Nothing to do, just return */
6695 if (unlikely(istlen(str) == 0))
6696 goto end;
6697
6698 if (istlen(str) > htx_free_data_space(htx)) {
6699 ret = -1;
6700 goto end;
6701 }
6702
6703 htxret = htx_find_offset(htx, offset);
6704 if (!htxret.blk || htx_get_blk_type(htxret.blk) != HTX_BLK_DATA) {
6705 if (!htx_add_last_data(htx, str))
6706 goto end;
6707 }
6708 else {
6709 struct ist v = htx_get_blk_value(htx, htxret.blk);
6710 v.ptr += htxret.ret;
6711 v.len = 0;
6712 if (!htx_replace_blk_value(htx, htxret.blk, v, str))
6713 goto end;
6714 }
6715 ret = str.len;
6716 if (ret) {
6717 struct hlua_flt_ctx *flt_ctx = filter->ctx;
6718 flt_update_offsets(filter, msg->chn, ret);
6719 flt_ctx->cur_len[CHN_IDX(msg->chn)] += ret;
6720 }
6721
6722 end:
6723 htx_to_buf(htx, &msg->chn->buf);
6724 return ret;
6725}
6726
6727/* Helper function removing at most <len> bytes of DATA blocks at the absolute
6728 * position <offset>. It stops on the first non-DATA HTX block. This function is
6729 * called during the payload filtering, so the headers are already scheduled for
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006730 * output (from the filter point of view). This function is responsible to
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006731 * update the filter context.
6732 */
6733static void _hlua_http_msg_delete(struct http_msg *msg, struct filter *filter, size_t offset, size_t len)
6734{
6735 struct hlua_flt_ctx *flt_ctx = filter->ctx;
6736 struct htx *htx = htx_from_buf(&msg->chn->buf);
6737 struct htx_blk *blk;
6738 struct htx_ret htxret;
6739 size_t ret = 0;
6740
6741 /* Be sure <len> is always the amount of DATA to remove */
6742 if (htx->data == offset+len && htx_get_tail_type(htx) == HTX_BLK_DATA) {
Aurelien DARRAGONbcbcf982022-09-28 19:08:15 +02006743 /* When htx tail type == HTX_BLK_DATA, no need to take care
6744 * of special blocks like HTX_BLK_EOT.
6745 * We simply truncate after offset
6746 * (truncate targeted blk and discard the following ones)
6747 */
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006748 htx_truncate(htx, offset);
6749 ret = len;
6750 goto end;
6751 }
6752
6753 htxret = htx_find_offset(htx, offset);
6754 blk = htxret.blk;
6755 if (htxret.ret) {
Aurelien DARRAGONbcbcf982022-09-28 19:08:15 +02006756 /* dealing with offset: we need to trim targeted blk */
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006757 struct ist v;
6758
6759 if (htx_get_blk_type(blk) != HTX_BLK_DATA)
6760 goto end;
Aurelien DARRAGONbcbcf982022-09-28 19:08:15 +02006761
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006762 v = htx_get_blk_value(htx, blk);
Tim Duesterhusa029d782022-10-08 12:33:18 +02006763 v = istadv(v, htxret.ret);
Aurelien DARRAGONbcbcf982022-09-28 19:08:15 +02006764
Tim Duesterhus2471f5c2021-11-08 09:05:01 +01006765 v = isttrim(v, len);
Aurelien DARRAGONbcbcf982022-09-28 19:08:15 +02006766 /* trimming data in blk: discard everything after the offset
6767 * (replace 'v' with 'IST_NULL')
6768 */
Tim Duesterhusb113b5c2021-09-15 13:58:44 +02006769 blk = htx_replace_blk_value(htx, blk, v, IST_NULL);
Aurelien DARRAGONbcbcf982022-09-28 19:08:15 +02006770 if (blk && v.len < len) {
6771 /* In this case, caller wants to keep removing data,
6772 * but we need to spare current blk
6773 * because it was already trimmed
6774 */
6775 blk = htx_get_next_blk(htx, blk);
6776 }
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006777 len -= v.len;
6778 ret += v.len;
6779 }
6780
6781
6782 while (blk && len) {
Aurelien DARRAGONbcbcf982022-09-28 19:08:15 +02006783 /* there is more data that needs to be discarded */
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006784 enum htx_blk_type type = htx_get_blk_type(blk);
6785 uint32_t sz = htx_get_blksz(blk);
6786
6787 switch (type) {
6788 case HTX_BLK_UNUSED:
6789 break;
6790
6791 case HTX_BLK_DATA:
6792 if (len < sz) {
Aurelien DARRAGONbcbcf982022-09-28 19:08:15 +02006793 /* don't discard whole blk, only part of it
6794 * (from the beginning)
6795 */
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006796 htx_cut_data_blk(htx, blk, len);
6797 ret += len;
6798 goto end;
6799 }
6800 break;
6801
6802 default:
Aurelien DARRAGONbcbcf982022-09-28 19:08:15 +02006803 /* HTX_BLK_EOT blk won't be removed */
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006804 goto end;
6805 }
6806
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006807 /* Remove all the data block */
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006808 len -= sz;
6809 ret += sz;
6810 blk = htx_remove_blk(htx, blk);
6811 }
6812
6813end:
6814 flt_update_offsets(filter, msg->chn, -ret);
6815 flt_ctx->cur_len[CHN_IDX(msg->chn)] -= ret;
6816 /* WARNING: we don't call htx_to_buf() on purpose, because we don't want
6817 * to loose the EOM flag if the message is empty.
6818 */
6819}
6820
6821/* Copies input data found in an HTTP message. Unlike the channel function used
6822 * to duplicate raw data, this one can only be called inside a filter, from
6823 * http_payload callback. So it cannot yield. An exception is returned if it is
6824 * called from another callback. If nothing was copied, a nil value is pushed on
6825 * the stack.
6826 */
6827__LJMP static int hlua_http_msg_get_body(lua_State *L)
6828{
6829 struct http_msg *msg;
6830 struct filter *filter;
6831 size_t output, input;
6832 int offset, len;
6833
6834 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
6835 WILL_LJMP(luaL_error(L, "'data' expects at most 2 arguments"));
6836 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6837
6838 if (msg->msg_state < HTTP_MSG_DATA)
6839 WILL_LJMP(lua_error(L));
6840
6841 filter = hlua_http_msg_filter(L, 1, msg, &output, &input);
6842 if (!filter || !hlua_filter_from_payload(filter))
6843 WILL_LJMP(lua_error(L));
6844
6845 if (!ci_data(msg->chn) && channel_input_closed(msg->chn)) {
6846 lua_pushnil(L);
6847 return 1;
6848 }
6849
6850 offset = output;
6851 if (lua_gettop(L) > 1) {
6852 offset = MAY_LJMP(luaL_checkinteger(L, 2));
6853 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02006854 offset = MAX(0, (int)input + offset);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006855 offset += output;
6856 if (offset < output || offset > input + output) {
6857 lua_pushfstring(L, "offset out of range.");
6858 WILL_LJMP(lua_error(L));
6859 }
6860 }
6861 len = output + input - offset;
6862 if (lua_gettop(L) == 3) {
6863 len = MAY_LJMP(luaL_checkinteger(L, 3));
6864 if (!len)
6865 goto dup;
6866 if (len == -1)
6867 len = global.tune.bufsize;
6868 if (len < 0) {
6869 lua_pushfstring(L, "length out of range.");
6870 WILL_LJMP(lua_error(L));
6871 }
6872 }
6873
6874 dup:
6875 _hlua_http_msg_dup(msg, L, offset, len);
6876 return 1;
6877}
6878
6879/* Appends a string to the HTTP message, after all existing DATA blocks but
6880 * before the trailers, if any. It returns the amount of data written or -1 if
6881 * nothing was copied. Unlike the channel function used to append data, this one
6882 * can only be called inside a filter, from http_payload callback. So it cannot
6883 * yield. An exception is returned if it is called from another callback.
6884 */
6885__LJMP static int hlua_http_msg_append(lua_State *L)
6886{
6887 struct http_msg *msg;
6888 struct filter *filter;
6889 const char *str;
6890 size_t offset, len, sz;
6891 int ret;
6892
6893 MAY_LJMP(check_args(L, 2, "append"));
6894 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6895
6896 if (msg->msg_state < HTTP_MSG_DATA)
6897 WILL_LJMP(lua_error(L));
6898
6899 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
6900 filter = hlua_http_msg_filter(L, 1, msg, &offset, &len);
6901 if (!filter || !hlua_filter_from_payload(filter))
6902 WILL_LJMP(lua_error(L));
6903
6904 ret = _hlua_http_msg_insert(msg, filter, ist2(str, sz), offset+len);
6905 lua_pushinteger(L, ret);
6906 return 1;
6907}
6908
6909/* Prepends a string to the HTTP message, before all existing DATA blocks. It
6910 * returns the amount of data written or -1 if nothing was copied. Unlike the
6911 * channel function used to prepend data, this one can only be called inside a
6912 * filter, from http_payload callback. So it cannot yield. An exception is
6913 * returned if it is called from another callback.
6914 */
6915__LJMP static int hlua_http_msg_prepend(lua_State *L)
6916{
6917 struct http_msg *msg;
6918 struct filter *filter;
6919 const char *str;
6920 size_t offset, len, sz;
6921 int ret;
6922
6923 MAY_LJMP(check_args(L, 2, "prepend"));
6924 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006925
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006926 if (msg->msg_state < HTTP_MSG_DATA)
6927 WILL_LJMP(lua_error(L));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006928
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006929 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
6930 filter = hlua_http_msg_filter(L, 1, msg, &offset, &len);
6931 if (!filter || !hlua_filter_from_payload(filter))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006932 WILL_LJMP(lua_error(L));
6933
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006934 ret = _hlua_http_msg_insert(msg, filter, ist2(str, sz), offset);
6935 lua_pushinteger(L, ret);
6936 return 1;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006937}
6938
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006939/* Inserts a string to the HTTP message at a given offset. By default the string
6940 * is appended at the end of DATA blocks. It returns the amount of data written
6941 * or -1 if nothing was copied. Unlike the channel function used to insert data,
6942 * this one can only be called inside a filter, from http_payload callback. So
6943 * it cannot yield. An exception is returned if it is called from another
6944 * callback.
6945 */
6946__LJMP static int hlua_http_msg_insert_data(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006947{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006948 struct http_msg *msg;
6949 struct filter *filter;
6950 const char *str;
6951 size_t input, output, sz;
6952 int offset;
6953 int ret;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006954
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006955 if (lua_gettop(L) < 2 || lua_gettop(L) > 3)
6956 WILL_LJMP(luaL_error(L, "'insert' expects at least 1 argument and at most 2 arguments"));
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006957 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006958
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006959 if (msg->msg_state < HTTP_MSG_DATA)
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006960 WILL_LJMP(lua_error(L));
6961
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006962 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
Aurelien DARRAGON7fdba0a2022-09-28 16:03:45 +02006963 filter = hlua_http_msg_filter(L, 1, msg, &output, &input);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006964 if (!filter || !hlua_filter_from_payload(filter))
6965 WILL_LJMP(lua_error(L));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006966
Aurelien DARRAGON7fdba0a2022-09-28 16:03:45 +02006967 offset = output;
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006968 if (lua_gettop(L) > 2) {
6969 offset = MAY_LJMP(luaL_checkinteger(L, 3));
6970 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02006971 offset = MAX(0, (int)input + offset);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006972 offset += output;
Aurelien DARRAGON7fdba0a2022-09-28 16:03:45 +02006973 if (offset > output + input) {
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006974 lua_pushfstring(L, "offset out of range.");
6975 WILL_LJMP(lua_error(L));
6976 }
6977 }
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006978
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006979 ret = _hlua_http_msg_insert(msg, filter, ist2(str, sz), offset);
6980 lua_pushinteger(L, ret);
6981 return 1;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006982}
6983
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006984/* Removes a given amount of data from the HTTP message at a given offset. By
6985 * default all DATA blocks are removed. It returns the amount of data
6986 * removed. Unlike the channel function used to remove data, this one can only
6987 * be called inside a filter, from http_payload callback. So it cannot yield. An
6988 * exception is returned if it is called from another callback.
6989 */
6990__LJMP static int hlua_http_msg_del_data(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006991{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006992 struct http_msg *msg;
6993 struct filter *filter;
6994 size_t input, output;
6995 int offset, len;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006996
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006997 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
Boyang Lie0c54352022-05-10 17:47:23 +00006998 WILL_LJMP(luaL_error(L, "'remove' expects at most 2 arguments"));
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006999 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007000
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007001 if (msg->msg_state < HTTP_MSG_DATA)
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02007002 WILL_LJMP(lua_error(L));
7003
Aurelien DARRAGONd7c71b02022-09-28 15:52:18 +02007004 filter = hlua_http_msg_filter(L, 1, msg, &output, &input);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007005 if (!filter || !hlua_filter_from_payload(filter))
7006 WILL_LJMP(lua_error(L));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007007
Aurelien DARRAGONd7c71b02022-09-28 15:52:18 +02007008 offset = output;
Boyang Lie0c54352022-05-10 17:47:23 +00007009 if (lua_gettop(L) > 1) {
7010 offset = MAY_LJMP(luaL_checkinteger(L, 2));
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007011 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02007012 offset = MAX(0, (int)input + offset);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007013 offset += output;
Aurelien DARRAGONd7c71b02022-09-28 15:52:18 +02007014 if (offset > output + input) {
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007015 lua_pushfstring(L, "offset out of range.");
7016 WILL_LJMP(lua_error(L));
7017 }
7018 }
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02007019
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007020 len = output + input - offset;
Boyang Lie0c54352022-05-10 17:47:23 +00007021 if (lua_gettop(L) == 3) {
7022 len = MAY_LJMP(luaL_checkinteger(L, 3));
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007023 if (!len)
7024 goto end;
7025 if (len == -1)
7026 len = output + input - offset;
7027 if (len < 0 || offset + len > output + input) {
7028 lua_pushfstring(L, "length out of range.");
7029 WILL_LJMP(lua_error(L));
7030 }
7031 }
7032
7033 _hlua_http_msg_delete(msg, filter, offset, len);
7034
7035 end:
7036 lua_pushinteger(L, len);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007037 return 1;
7038}
7039
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05007040/* Replaces a given amount of data at the given offset by a string. By default,
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007041 * all remaining data are removed, accordingly to the filter context. It returns
7042 * the amount of data written or -1 if nothing was copied. Unlike the channel
7043 * function used to replace data, this one can only be called inside a filter,
7044 * from http_payload callback. So it cannot yield. An exception is returned if
7045 * it is called from another callback.
7046 */
7047__LJMP static int hlua_http_msg_set_data(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007048{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007049 struct http_msg *msg;
7050 struct filter *filter;
7051 struct htx *htx;
7052 const char *str;
7053 size_t input, output, sz;
7054 int offset, len;
7055 int ret;
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02007056
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007057 if (lua_gettop(L) < 2 || lua_gettop(L) > 4)
7058 WILL_LJMP(luaL_error(L, "'set' expects at least 1 argument and at most 3 arguments"));
7059 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
7060
7061 if (msg->msg_state < HTTP_MSG_DATA)
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02007062 WILL_LJMP(lua_error(L));
7063
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007064 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
7065 filter = hlua_http_msg_filter(L, 1, msg, &output, &input);
7066 if (!filter || !hlua_filter_from_payload(filter))
7067 WILL_LJMP(lua_error(L));
7068
7069 offset = output;
7070 if (lua_gettop(L) > 2) {
7071 offset = MAY_LJMP(luaL_checkinteger(L, 3));
7072 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02007073 offset = MAX(0, (int)input + offset);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007074 offset += output;
7075 if (offset < output || offset > input + output) {
7076 lua_pushfstring(L, "offset out of range.");
7077 WILL_LJMP(lua_error(L));
7078 }
7079 }
7080
7081 len = output + input - offset;
7082 if (lua_gettop(L) == 4) {
7083 len = MAY_LJMP(luaL_checkinteger(L, 4));
7084 if (!len)
7085 goto set;
7086 if (len == -1)
7087 len = output + input - offset;
7088 if (len < 0 || offset + len > output + input) {
7089 lua_pushfstring(L, "length out of range.");
7090 WILL_LJMP(lua_error(L));
7091 }
7092 }
7093
7094 set:
7095 /* Be sure we can copied the string once input data will be removed. */
7096 htx = htx_from_buf(&msg->chn->buf);
7097 if (sz > htx_free_data_space(htx) + len)
7098 lua_pushinteger(L, -1);
7099 else {
7100 _hlua_http_msg_delete(msg, filter, offset, len);
7101 ret = _hlua_http_msg_insert(msg, filter, ist2(str, sz), offset);
7102 lua_pushinteger(L, ret);
7103 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007104 return 1;
7105}
7106
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007107/* Prepends data into an HTTP message and forward it, from the filter point of
7108 * view. It returns the amount of data written or -1 if nothing was sent. Unlike
7109 * the channel function used to send data, this one can only be called inside a
7110 * filter, from http_payload callback. So it cannot yield. An exception is
7111 * returned if it is called from another callback.
7112 */
7113__LJMP static int hlua_http_msg_send(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007114{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007115 struct http_msg *msg;
7116 struct filter *filter;
7117 struct htx *htx;
7118 const char *str;
7119 size_t offset, len, sz;
7120 int ret;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007121
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007122 MAY_LJMP(check_args(L, 2, "send"));
7123 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
7124
7125 if (msg->msg_state < HTTP_MSG_DATA)
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02007126 WILL_LJMP(lua_error(L));
7127
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007128 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
7129 filter = hlua_http_msg_filter(L, 1, msg, &offset, &len);
7130 if (!filter || !hlua_filter_from_payload(filter))
7131 WILL_LJMP(lua_error(L));
7132
7133 /* Return an error if the channel's output is closed */
7134 if (unlikely(channel_output_closed(msg->chn))) {
7135 lua_pushinteger(L, -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007136 return 1;
7137 }
7138
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007139 htx = htx_from_buf(&msg->chn->buf);
7140 if (sz > htx_free_data_space(htx)) {
7141 lua_pushinteger(L, -1);
7142 return 1;
7143 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007144
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007145 ret = _hlua_http_msg_insert(msg, filter, ist2(str, sz), offset);
7146 if (ret > 0) {
7147 struct hlua_flt_ctx *flt_ctx = filter->ctx;
7148
7149 FLT_OFF(filter, msg->chn) += ret;
7150 flt_ctx->cur_len[CHN_IDX(msg->chn)] -= ret;
7151 flt_ctx->cur_off[CHN_IDX(msg->chn)] += ret;
7152 }
7153
7154 lua_pushinteger(L, ret);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007155 return 1;
7156}
7157
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007158/* Forwards a given amount of bytes. It return -1 if the channel's output is
7159 * closed. Otherwise, it returns the number of bytes forwarded. Unlike the
7160 * channel function used to forward data, this one can only be called inside a
7161 * filter, from http_payload callback. So it cannot yield. An exception is
7162 * returned if it is called from another callback. All other functions deal with
7163 * DATA block, this one not.
7164*/
7165__LJMP static int hlua_http_msg_forward(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007166{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007167 struct http_msg *msg;
7168 struct filter *filter;
7169 size_t offset, len;
7170 int fwd, ret = 0;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007171
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007172 MAY_LJMP(check_args(L, 2, "forward"));
7173 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
7174
7175 if (msg->msg_state < HTTP_MSG_DATA)
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02007176 WILL_LJMP(lua_error(L));
7177
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007178 fwd = MAY_LJMP(luaL_checkinteger(L, 2));
7179 filter = hlua_http_msg_filter(L, 1, msg, &offset, &len);
7180 if (!filter || !hlua_filter_from_payload(filter))
7181 WILL_LJMP(lua_error(L));
7182
7183 /* Nothing to do, just return */
7184 if (!fwd)
7185 goto end;
7186
7187 /* Return an error if the channel's output is closed */
7188 if (unlikely(channel_output_closed(msg->chn))) {
7189 ret = -1;
7190 goto end;
7191 }
7192
7193 ret = fwd;
7194 if (ret > len)
7195 ret = len;
7196
7197 if (ret) {
7198 struct hlua_flt_ctx *flt_ctx = filter->ctx;
7199
7200 FLT_OFF(filter, msg->chn) += ret;
7201 flt_ctx->cur_off[CHN_IDX(msg->chn)] += ret;
7202 flt_ctx->cur_len[CHN_IDX(msg->chn)] -= ret;
7203 }
7204
7205 end:
7206 lua_pushinteger(L, ret);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007207 return 1;
7208}
7209
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007210/* Set EOM flag on the HTX message.
7211 *
7212 * NOTE: Not sure it is a good idea to manipulate this flag but for now I don't
7213 * really know how to do without this feature.
7214 */
7215__LJMP static int hlua_http_msg_set_eom(lua_State *L)
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02007216{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007217 struct http_msg *msg;
7218 struct htx *htx;
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02007219
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007220 MAY_LJMP(check_args(L, 1, "set_eom"));
7221 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
7222 htx = htxbuf(&msg->chn->buf);
7223 htx->flags |= HTX_FL_EOM;
7224 return 0;
7225}
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02007226
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007227/* Unset EOM flag on the HTX message.
7228 *
7229 * NOTE: Not sure it is a good idea to manipulate this flag but for now I don't
7230 * really know how to do without this feature.
7231 */
7232__LJMP static int hlua_http_msg_unset_eom(lua_State *L)
7233{
7234 struct http_msg *msg;
7235 struct htx *htx;
7236
7237 MAY_LJMP(check_args(L, 1, "set_eom"));
7238 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
7239 htx = htxbuf(&msg->chn->buf);
7240 htx->flags &= ~HTX_FL_EOM;
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02007241 return 0;
7242}
7243
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007244/*
7245 *
7246 *
William Lallemand3956c4e2021-09-21 16:25:15 +02007247 * Class HTTPClient
7248 *
7249 *
7250 */
7251__LJMP static struct hlua_httpclient *hlua_checkhttpclient(lua_State *L, int ud)
7252{
7253 return MAY_LJMP(hlua_checkudata(L, ud, class_httpclient_ref));
7254}
7255
William Lallemandf77f1de2021-09-28 19:10:38 +02007256
7257/* stops the httpclient and ask it to kill itself */
7258__LJMP static int hlua_httpclient_gc(lua_State *L)
7259{
7260 struct hlua_httpclient *hlua_hc;
7261
7262 MAY_LJMP(check_args(L, 1, "__gc"));
7263
7264 hlua_hc = MAY_LJMP(hlua_checkhttpclient(L, 1));
7265
Aurelien DARRAGON3ffbf382023-02-09 17:02:57 +01007266 if (MT_LIST_DELETE(&hlua_hc->by_hlua)) {
7267 /* we won the race against hlua_httpclient_destroy_all() */
William Lallemandbb581422022-10-20 10:57:28 +02007268 httpclient_stop_and_destroy(hlua_hc->hc);
Aurelien DARRAGON3ffbf382023-02-09 17:02:57 +01007269 hlua_hc->hc = NULL;
7270 }
William Lallemandf77f1de2021-09-28 19:10:38 +02007271
7272 return 0;
7273}
7274
7275
William Lallemand3956c4e2021-09-21 16:25:15 +02007276__LJMP static int hlua_httpclient_new(lua_State *L)
7277{
7278 struct hlua_httpclient *hlua_hc;
7279 struct hlua *hlua;
7280
7281 /* Get hlua struct, or NULL if we execute from main lua state */
7282 hlua = hlua_gethlua(L);
7283 if (!hlua)
7284 return 0;
7285
7286 /* Check stack size. */
7287 if (!lua_checkstack(L, 3)) {
7288 hlua_pusherror(L, "httpclient: full stack");
7289 goto err;
7290 }
7291 /* Create the object: obj[0] = userdata. */
7292 lua_newtable(L);
7293 hlua_hc = MAY_LJMP(lua_newuserdata(L, sizeof(*hlua_hc)));
7294 lua_rawseti(L, -2, 0);
7295 memset(hlua_hc, 0, sizeof(*hlua_hc));
7296
7297 hlua_hc->hc = httpclient_new(hlua, 0, IST_NULL);
7298 if (!hlua_hc->hc)
7299 goto err;
7300
Aurelien DARRAGON3ffbf382023-02-09 17:02:57 +01007301 MT_LIST_APPEND(&hlua->hc_list, &hlua_hc->by_hlua);
William Lallemandbb581422022-10-20 10:57:28 +02007302
William Lallemand3956c4e2021-09-21 16:25:15 +02007303 /* Pop a class stream metatable and affect it to the userdata. */
7304 lua_rawgeti(L, LUA_REGISTRYINDEX, class_httpclient_ref);
7305 lua_setmetatable(L, -2);
7306
7307 return 1;
7308
7309 err:
7310 WILL_LJMP(lua_error(L));
7311 return 0;
7312}
7313
7314
7315/*
7316 * Callback of the httpclient, this callback wakes the lua task up, once the
7317 * httpclient receives some data
7318 *
7319 */
7320
William Lallemandbd5739e2021-10-28 15:41:38 +02007321static void hlua_httpclient_cb(struct httpclient *hc)
William Lallemand3956c4e2021-09-21 16:25:15 +02007322{
7323 struct hlua *hlua = hc->caller;
7324
7325 if (!hlua || !hlua->task)
7326 return;
7327
7328 task_wakeup(hlua->task, TASK_WOKEN_MSG);
7329}
7330
7331/*
William Lallemandd7df73a2021-09-23 17:54:00 +02007332 * Fill the lua stack with headers from the httpclient response
7333 * This works the same way as the hlua_http_get_headers() function
7334 */
7335__LJMP static int hlua_httpclient_get_headers(lua_State *L, struct hlua_httpclient *hlua_hc)
7336{
7337 struct http_hdr *hdr;
7338
7339 lua_newtable(L);
7340
William Lallemandef574b22021-10-05 16:19:31 +02007341 for (hdr = hlua_hc->hc->res.hdrs; hdr && isttest(hdr->n); hdr++) {
William Lallemandd7df73a2021-09-23 17:54:00 +02007342 struct ist n, v;
7343 int len;
7344
7345 n = hdr->n;
7346 v = hdr->v;
7347
7348 /* Check for existing entry:
7349 * assume that the table is on the top of the stack, and
7350 * push the key in the stack, the function lua_gettable()
7351 * perform the lookup.
7352 */
7353
7354 lua_pushlstring(L, n.ptr, n.len);
7355 lua_gettable(L, -2);
7356
7357 switch (lua_type(L, -1)) {
7358 case LUA_TNIL:
7359 /* Table not found, create it. */
7360 lua_pop(L, 1); /* remove the nil value. */
7361 lua_pushlstring(L, n.ptr, n.len); /* push the header name as key. */
7362 lua_newtable(L); /* create and push empty table. */
7363 lua_pushlstring(L, v.ptr, v.len); /* push header value. */
7364 lua_rawseti(L, -2, 0); /* index header value (pop it). */
7365 lua_rawset(L, -3); /* index new table with header name (pop the values). */
7366 break;
7367
7368 case LUA_TTABLE:
7369 /* Entry found: push the value in the table. */
7370 len = lua_rawlen(L, -1);
7371 lua_pushlstring(L, v.ptr, v.len); /* push header value. */
7372 lua_rawseti(L, -2, len+1); /* index header value (pop it). */
7373 lua_pop(L, 1); /* remove the table (it is stored in the main table). */
7374 break;
7375
7376 default:
7377 /* Other cases are errors. */
7378 hlua_pusherror(L, "internal error during the parsing of headers.");
7379 WILL_LJMP(lua_error(L));
7380 }
7381 }
7382 return 1;
7383}
7384
7385/*
William Lallemand746e6f32021-10-06 10:57:44 +02007386 * Allocate and return an array of http_hdr ist extracted from the <headers> lua table
7387 *
7388 * Caller must free the result
7389 */
7390struct http_hdr *hlua_httpclient_table_to_hdrs(lua_State *L)
7391{
7392 struct http_hdr hdrs[global.tune.max_http_hdr];
7393 struct http_hdr *result = NULL;
7394 uint32_t hdr_num = 0;
7395
7396 lua_pushnil(L);
7397 while (lua_next(L, -2) != 0) {
7398 struct ist name, value;
7399 const char *n, *v;
7400 size_t nlen, vlen;
7401
7402 if (!lua_isstring(L, -2) || !lua_istable(L, -1)) {
7403 /* Skip element if the key is not a string or if the value is not a table */
7404 goto next_hdr;
7405 }
7406
7407 n = lua_tolstring(L, -2, &nlen);
7408 name = ist2(n, nlen);
7409
7410 /* Loop on header's values */
7411 lua_pushnil(L);
7412 while (lua_next(L, -2)) {
7413 if (!lua_isstring(L, -1)) {
7414 /* Skip the value if it is not a string */
7415 goto next_value;
7416 }
7417
7418 v = lua_tolstring(L, -1, &vlen);
7419 value = ist2(v, vlen);
7420 name = ist2(n, nlen);
7421
7422 hdrs[hdr_num].n = istdup(name);
7423 hdrs[hdr_num].v = istdup(value);
7424
7425 hdr_num++;
7426
7427 next_value:
7428 lua_pop(L, 1);
7429 }
7430
7431 next_hdr:
7432 lua_pop(L, 1);
7433
7434 }
7435
7436 if (hdr_num) {
7437 /* alloc and copy the headers in the httpclient struct */
Tim Duesterhus16cc16d2021-11-06 15:14:45 +01007438 result = calloc((hdr_num + 1), sizeof(*result));
William Lallemand746e6f32021-10-06 10:57:44 +02007439 if (!result)
7440 goto skip_headers;
7441 memcpy(result, hdrs, sizeof(struct http_hdr) * (hdr_num + 1));
7442
7443 result[hdr_num].n = IST_NULL;
7444 result[hdr_num].v = IST_NULL;
7445 }
7446
7447skip_headers:
William Lallemand746e6f32021-10-06 10:57:44 +02007448
7449 return result;
7450}
7451
7452
William Lallemandbd5739e2021-10-28 15:41:38 +02007453/*
7454 * For each yield, checks if there is some data in the httpclient and push them
7455 * in the lua buffer, once the httpclient finished its job, push the result on
7456 * the stack
7457 */
7458__LJMP static int hlua_httpclient_rcv_yield(lua_State *L, int status, lua_KContext ctx)
7459{
7460 struct buffer *tr;
7461 int res;
7462 struct hlua *hlua = hlua_gethlua(L);
7463 struct hlua_httpclient *hlua_hc = hlua_checkhttpclient(L, 1);
7464
7465
7466 tr = get_trash_chunk();
7467
7468 res = httpclient_res_xfer(hlua_hc->hc, tr);
7469 luaL_addlstring(&hlua_hc->b, b_orig(tr), res);
7470
7471 if (!httpclient_data(hlua_hc->hc) && httpclient_ended(hlua_hc->hc)) {
7472
7473 luaL_pushresult(&hlua_hc->b);
7474 lua_settable(L, -3);
7475
7476 lua_pushstring(L, "status");
7477 lua_pushinteger(L, hlua_hc->hc->res.status);
7478 lua_settable(L, -3);
7479
7480
7481 lua_pushstring(L, "reason");
7482 lua_pushlstring(L, hlua_hc->hc->res.reason.ptr, hlua_hc->hc->res.reason.len);
7483 lua_settable(L, -3);
7484
7485 lua_pushstring(L, "headers");
7486 hlua_httpclient_get_headers(L, hlua_hc);
7487 lua_settable(L, -3);
7488
7489 return 1;
7490 }
7491
7492 if (httpclient_data(hlua_hc->hc))
7493 task_wakeup(hlua->task, TASK_WOKEN_MSG);
7494
7495 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_httpclient_rcv_yield, TICK_ETERNITY, 0));
7496
7497 return 0;
7498}
7499
7500/*
7501 * Call this when trying to stream a body during a request
7502 */
7503__LJMP static int hlua_httpclient_snd_yield(lua_State *L, int status, lua_KContext ctx)
7504{
7505 struct hlua *hlua;
7506 struct hlua_httpclient *hlua_hc = hlua_checkhttpclient(L, 1);
7507 const char *body_str = NULL;
7508 int ret;
7509 int end = 0;
7510 size_t buf_len;
7511 size_t to_send = 0;
7512
7513 hlua = hlua_gethlua(L);
7514
7515 if (!hlua || !hlua->task)
7516 WILL_LJMP(luaL_error(L, "The 'get' function is only allowed in "
7517 "'frontend', 'backend' or 'task'"));
7518
7519 ret = lua_getfield(L, -1, "body");
7520 if (ret != LUA_TSTRING)
7521 goto rcv;
7522
7523 body_str = lua_tolstring(L, -1, &buf_len);
7524 lua_pop(L, 1);
7525
Christopher Fauletfc591292022-01-12 14:46:03 +01007526 to_send = buf_len - hlua_hc->sent;
William Lallemandbd5739e2021-10-28 15:41:38 +02007527
7528 if ((hlua_hc->sent + to_send) >= buf_len)
7529 end = 1;
7530
7531 /* the end flag is always set since we are using the whole remaining size */
7532 hlua_hc->sent += httpclient_req_xfer(hlua_hc->hc, ist2(body_str + hlua_hc->sent, to_send), end);
7533
7534 if (buf_len > hlua_hc->sent) {
7535 /* still need to process the buffer */
7536 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_httpclient_snd_yield, TICK_ETERNITY, 0));
7537 } else {
7538 goto rcv;
7539 /* we sent the whole request buffer we can recv */
7540 }
7541 return 0;
7542
7543rcv:
7544
7545 /* we return a "res" object */
7546 lua_newtable(L);
7547
William Lallemandbd5739e2021-10-28 15:41:38 +02007548 lua_pushstring(L, "body");
William Lallemandd1187eb2021-11-02 10:40:06 +01007549 luaL_buffinit(L, &hlua_hc->b);
William Lallemandbd5739e2021-10-28 15:41:38 +02007550
William Lallemand933fe392021-11-04 09:45:58 +01007551 task_wakeup(hlua->task, TASK_WOKEN_MSG);
William Lallemandbd5739e2021-10-28 15:41:38 +02007552 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_httpclient_rcv_yield, TICK_ETERNITY, 0));
7553
7554 return 1;
7555}
William Lallemand746e6f32021-10-06 10:57:44 +02007556
William Lallemand3956c4e2021-09-21 16:25:15 +02007557/*
William Lallemanddc2cc902021-10-26 11:43:26 +02007558 * Send an HTTP request and wait for a response
William Lallemand3956c4e2021-09-21 16:25:15 +02007559 */
7560
William Lallemanddc2cc902021-10-26 11:43:26 +02007561__LJMP static int hlua_httpclient_send(lua_State *L, enum http_meth_t meth)
William Lallemand3956c4e2021-09-21 16:25:15 +02007562{
7563 struct hlua_httpclient *hlua_hc;
William Lallemand746e6f32021-10-06 10:57:44 +02007564 struct http_hdr *hdrs = NULL;
7565 struct http_hdr *hdrs_i = NULL;
William Lallemand3956c4e2021-09-21 16:25:15 +02007566 struct hlua *hlua;
William Lallemand746e6f32021-10-06 10:57:44 +02007567 const char *url_str = NULL;
William Lallemanddec25c32021-10-25 19:48:37 +02007568 const char *body_str = NULL;
Christopher Faulet380ae9c2022-10-14 14:57:04 +02007569 size_t buf_len = 0;
William Lallemand746e6f32021-10-06 10:57:44 +02007570 int ret;
William Lallemand3956c4e2021-09-21 16:25:15 +02007571
7572 hlua = hlua_gethlua(L);
7573
7574 if (!hlua || !hlua->task)
7575 WILL_LJMP(luaL_error(L, "The 'get' function is only allowed in "
7576 "'frontend', 'backend' or 'task'"));
7577
William Lallemand746e6f32021-10-06 10:57:44 +02007578 if (lua_gettop(L) != 2 || lua_type(L, -1) != LUA_TTABLE)
7579 WILL_LJMP(luaL_error(L, "'get' needs a table as argument"));
7580
William Lallemand4f4f2b72022-02-17 20:00:23 +01007581 hlua_hc = hlua_checkhttpclient(L, 1);
7582
William Lallemand7177a952022-03-03 15:33:12 +01007583 lua_pushnil(L); /* first key */
7584 while (lua_next(L, 2)) {
7585 if (strcmp(lua_tostring(L, -2), "dst") == 0) {
7586 if (httpclient_set_dst(hlua_hc->hc, lua_tostring(L, -1)) < 0)
7587 WILL_LJMP(luaL_error(L, "Can't use the 'dst' argument"));
William Lallemand4f4f2b72022-02-17 20:00:23 +01007588
William Lallemand7177a952022-03-03 15:33:12 +01007589 } else if (strcmp(lua_tostring(L, -2), "url") == 0) {
7590 if (lua_type(L, -1) != LUA_TSTRING)
7591 WILL_LJMP(luaL_error(L, "invalid parameter in 'url', must be a string"));
7592 url_str = lua_tostring(L, -1);
William Lallemand3956c4e2021-09-21 16:25:15 +02007593
William Lallemand7177a952022-03-03 15:33:12 +01007594 } else if (strcmp(lua_tostring(L, -2), "timeout") == 0) {
7595 if (lua_type(L, -1) != LUA_TNUMBER)
7596 WILL_LJMP(luaL_error(L, "invalid parameter in 'timeout', must be a number"));
7597 httpclient_set_timeout(hlua_hc->hc, lua_tointeger(L, -1));
William Lallemandb4a4ef62022-02-23 14:18:16 +01007598
William Lallemand7177a952022-03-03 15:33:12 +01007599 } else if (strcmp(lua_tostring(L, -2), "headers") == 0) {
7600 if (lua_type(L, -1) != LUA_TTABLE)
7601 WILL_LJMP(luaL_error(L, "invalid parameter in 'headers', must be a table"));
7602 hdrs = hlua_httpclient_table_to_hdrs(L);
William Lallemand79416cb2021-09-24 14:51:44 +02007603
William Lallemand7177a952022-03-03 15:33:12 +01007604 } else if (strcmp(lua_tostring(L, -2), "body") == 0) {
7605 if (lua_type(L, -1) != LUA_TSTRING)
7606 WILL_LJMP(luaL_error(L, "invalid parameter in 'body', must be a string"));
7607 body_str = lua_tolstring(L, -1, &buf_len);
William Lallemandbd5739e2021-10-28 15:41:38 +02007608
William Lallemand7177a952022-03-03 15:33:12 +01007609 } else {
7610 WILL_LJMP(luaL_error(L, "'%s' invalid parameter name", lua_tostring(L, -2)));
7611 }
7612 /* removes 'value'; keeps 'key' for next iteration */
7613 lua_pop(L, 1);
7614 }
William Lallemanddec25c32021-10-25 19:48:37 +02007615
William Lallemand746e6f32021-10-06 10:57:44 +02007616 if (!url_str) {
7617 WILL_LJMP(luaL_error(L, "'get' need a 'url' argument"));
7618 return 0;
7619 }
William Lallemand3956c4e2021-09-21 16:25:15 +02007620
William Lallemand10a37362022-03-02 16:18:26 +01007621 hlua_hc->sent = 0;
William Lallemand3956c4e2021-09-21 16:25:15 +02007622
Aurelien DARRAGON03564072023-02-09 15:26:25 +01007623 istfree(&hlua_hc->hc->req.url);
William Lallemand3956c4e2021-09-21 16:25:15 +02007624 hlua_hc->hc->req.url = istdup(ist(url_str));
William Lallemanddc2cc902021-10-26 11:43:26 +02007625 hlua_hc->hc->req.meth = meth;
William Lallemand3956c4e2021-09-21 16:25:15 +02007626
7627 /* update the httpclient callbacks */
William Lallemandbd5739e2021-10-28 15:41:38 +02007628 hlua_hc->hc->ops.res_stline = hlua_httpclient_cb;
7629 hlua_hc->hc->ops.res_headers = hlua_httpclient_cb;
7630 hlua_hc->hc->ops.res_payload = hlua_httpclient_cb;
William Lallemand8f170c72022-03-15 10:52:07 +01007631 hlua_hc->hc->ops.res_end = hlua_httpclient_cb;
William Lallemand3956c4e2021-09-21 16:25:15 +02007632
William Lallemandbd5739e2021-10-28 15:41:38 +02007633 /* a body is available, it will use the request callback */
Christopher Faulet380ae9c2022-10-14 14:57:04 +02007634 if (body_str && buf_len) {
William Lallemandbd5739e2021-10-28 15:41:38 +02007635 hlua_hc->hc->ops.req_payload = hlua_httpclient_cb;
7636 }
William Lallemand3956c4e2021-09-21 16:25:15 +02007637
William Lallemandbd5739e2021-10-28 15:41:38 +02007638 ret = httpclient_req_gen(hlua_hc->hc, hlua_hc->hc->req.url, meth, hdrs, IST_NULL);
William Lallemand3956c4e2021-09-21 16:25:15 +02007639
William Lallemand746e6f32021-10-06 10:57:44 +02007640 /* free the temporary headers array */
7641 hdrs_i = hdrs;
7642 while (hdrs_i && isttest(hdrs_i->n)) {
7643 istfree(&hdrs_i->n);
7644 istfree(&hdrs_i->v);
7645 hdrs_i++;
7646 }
7647 ha_free(&hdrs);
7648
7649
William Lallemand6137a9e2021-10-26 15:01:53 +02007650 if (ret != ERR_NONE) {
7651 WILL_LJMP(luaL_error(L, "Can't generate the HTTP request"));
7652 return 0;
7653 }
7654
William Lallemandc2d3db42022-04-26 11:46:13 +02007655 if (!httpclient_start(hlua_hc->hc))
7656 WILL_LJMP(luaL_error(L, "couldn't start the httpclient"));
William Lallemand6137a9e2021-10-26 15:01:53 +02007657
William Lallemandbd5739e2021-10-28 15:41:38 +02007658 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_httpclient_snd_yield, TICK_ETERNITY, 0));
William Lallemand3956c4e2021-09-21 16:25:15 +02007659
William Lallemand3956c4e2021-09-21 16:25:15 +02007660 return 0;
7661}
7662
7663/*
William Lallemanddc2cc902021-10-26 11:43:26 +02007664 * Sends an HTTP HEAD request and wait for a response
7665 *
7666 * httpclient:head(url, headers, payload)
7667 */
7668__LJMP static int hlua_httpclient_head(lua_State *L)
7669{
7670 return hlua_httpclient_send(L, HTTP_METH_HEAD);
7671}
7672
7673/*
7674 * Send an HTTP GET request and wait for a response
7675 *
7676 * httpclient:get(url, headers, payload)
7677 */
7678__LJMP static int hlua_httpclient_get(lua_State *L)
7679{
7680 return hlua_httpclient_send(L, HTTP_METH_GET);
7681
7682}
7683
7684/*
7685 * Sends an HTTP PUT request and wait for a response
7686 *
7687 * httpclient:put(url, headers, payload)
7688 */
7689__LJMP static int hlua_httpclient_put(lua_State *L)
7690{
7691 return hlua_httpclient_send(L, HTTP_METH_PUT);
7692}
7693
7694/*
7695 * Send an HTTP POST request and wait for a response
7696 *
7697 * httpclient:post(url, headers, payload)
7698 */
7699__LJMP static int hlua_httpclient_post(lua_State *L)
7700{
7701 return hlua_httpclient_send(L, HTTP_METH_POST);
7702}
7703
7704
7705/*
7706 * Sends an HTTP DELETE request and wait for a response
7707 *
7708 * httpclient:delete(url, headers, payload)
7709 */
7710__LJMP static int hlua_httpclient_delete(lua_State *L)
7711{
7712 return hlua_httpclient_send(L, HTTP_METH_DELETE);
7713}
7714
7715/*
William Lallemand3956c4e2021-09-21 16:25:15 +02007716 *
7717 *
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007718 * Class TXN
7719 *
7720 *
7721 */
7722
7723/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02007724 * a class stream, otherwise it throws an error.
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007725 */
7726__LJMP static struct hlua_txn *hlua_checktxn(lua_State *L, int ud)
7727{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02007728 return MAY_LJMP(hlua_checkudata(L, ud, class_txn_ref));
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007729}
7730
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007731__LJMP static int hlua_set_var(lua_State *L)
7732{
7733 struct hlua_txn *htxn;
7734 const char *name;
7735 size_t len;
7736 struct sample smp;
7737
Tim Duesterhus4e172c92020-05-19 13:49:42 +02007738 if (lua_gettop(L) < 3 || lua_gettop(L) > 4)
7739 WILL_LJMP(luaL_error(L, "'set_var' needs between 3 and 4 arguments"));
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007740
7741 /* It is useles to retrieve the stream, but this function
7742 * runs only in a stream context.
7743 */
7744 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7745 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
7746
7747 /* Converts the third argument in a sample. */
Amaury Denoyellebc0af6a2020-10-29 17:21:20 +01007748 memset(&smp, 0, sizeof(smp));
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007749 hlua_lua2smp(L, 3, &smp);
7750
7751 /* Store the sample in a variable. */
Willy Tarreau7560dd42016-03-10 16:28:58 +01007752 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
Tim Duesterhus4e172c92020-05-19 13:49:42 +02007753
7754 if (lua_gettop(L) == 4 && lua_toboolean(L, 4))
7755 lua_pushboolean(L, vars_set_by_name_ifexist(name, len, &smp) != 0);
7756 else
7757 lua_pushboolean(L, vars_set_by_name(name, len, &smp) != 0);
7758
Tim Duesterhus84ebc132020-05-19 13:49:41 +02007759 return 1;
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007760}
7761
Christopher Faulet85d79c92016-11-09 16:54:56 +01007762__LJMP static int hlua_unset_var(lua_State *L)
7763{
7764 struct hlua_txn *htxn;
7765 const char *name;
7766 size_t len;
7767 struct sample smp;
7768
7769 MAY_LJMP(check_args(L, 2, "unset_var"));
7770
7771 /* It is useles to retrieve the stream, but this function
7772 * runs only in a stream context.
7773 */
7774 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7775 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
7776
7777 /* Unset the variable. */
7778 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
Tim Duesterhus84ebc132020-05-19 13:49:41 +02007779 lua_pushboolean(L, vars_unset_by_name_ifexist(name, len, &smp) != 0);
7780 return 1;
Christopher Faulet85d79c92016-11-09 16:54:56 +01007781}
7782
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007783__LJMP static int hlua_get_var(lua_State *L)
7784{
7785 struct hlua_txn *htxn;
7786 const char *name;
7787 size_t len;
7788 struct sample smp;
7789
7790 MAY_LJMP(check_args(L, 2, "get_var"));
7791
7792 /* It is useles to retrieve the stream, but this function
7793 * runs only in a stream context.
7794 */
7795 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7796 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
7797
Willy Tarreau7560dd42016-03-10 16:28:58 +01007798 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
Willy Tarreaue352b9d2021-09-03 11:52:38 +02007799 if (!vars_get_by_name(name, len, &smp, NULL)) {
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007800 lua_pushnil(L);
7801 return 1;
7802 }
7803
7804 return hlua_smp2lua(L, &smp);
7805}
7806
Willy Tarreau59551662015-03-10 14:23:13 +01007807__LJMP static int hlua_set_priv(lua_State *L)
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007808{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007809 struct hlua *hlua;
7810
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007811 MAY_LJMP(check_args(L, 2, "set_priv"));
7812
Willy Tarreau87b09662015-04-03 00:22:06 +02007813 /* It is useles to retrieve the stream, but this function
7814 * runs only in a stream context.
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007815 */
7816 MAY_LJMP(hlua_checktxn(L, 1));
Thierry Fournier4234dbd2020-11-28 13:18:23 +01007817
7818 /* Get hlua struct, or NULL if we execute from main lua state */
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007819 hlua = hlua_gethlua(L);
Thierry Fournier4234dbd2020-11-28 13:18:23 +01007820 if (!hlua)
7821 return 0;
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007822
7823 /* Remove previous value. */
Thierry FOURNIERe068b602017-04-26 13:27:05 +02007824 luaL_unref(L, LUA_REGISTRYINDEX, hlua->Mref);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007825
7826 /* Get and store new value. */
7827 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
7828 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
7829
7830 return 0;
7831}
7832
Willy Tarreau59551662015-03-10 14:23:13 +01007833__LJMP static int hlua_get_priv(lua_State *L)
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007834{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007835 struct hlua *hlua;
7836
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007837 MAY_LJMP(check_args(L, 1, "get_priv"));
7838
Willy Tarreau87b09662015-04-03 00:22:06 +02007839 /* It is useles to retrieve the stream, but this function
7840 * runs only in a stream context.
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007841 */
7842 MAY_LJMP(hlua_checktxn(L, 1));
Thierry Fournier4234dbd2020-11-28 13:18:23 +01007843
7844 /* Get hlua struct, or NULL if we execute from main lua state */
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007845 hlua = hlua_gethlua(L);
Thierry Fournier4234dbd2020-11-28 13:18:23 +01007846 if (!hlua) {
7847 lua_pushnil(L);
7848 return 1;
7849 }
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007850
7851 /* Push configuration index in the stack. */
7852 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
7853
7854 return 1;
7855}
7856
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007857/* Create stack entry containing a class TXN. This function
7858 * return 0 if the stack does not contains free slots,
7859 * otherwise it returns 1.
7860 */
Thierry FOURNIERab00df62016-07-14 11:42:37 +02007861static int hlua_txn_new(lua_State *L, struct stream *s, struct proxy *p, int dir, int flags)
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007862{
Willy Tarreaude491382015-04-06 11:04:28 +02007863 struct hlua_txn *htxn;
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007864
7865 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01007866 if (!lua_checkstack(L, 3))
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007867 return 0;
7868
7869 /* NOTE: The allocation never fails. The failure
7870 * throw an error, and the function never returns.
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08007871 * if the throw is not available, the process is aborted.
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007872 */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01007873 /* Create the object: obj[0] = userdata. */
7874 lua_newtable(L);
Willy Tarreaude491382015-04-06 11:04:28 +02007875 htxn = lua_newuserdata(L, sizeof(*htxn));
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01007876 lua_rawseti(L, -2, 0);
7877
Willy Tarreaude491382015-04-06 11:04:28 +02007878 htxn->s = s;
7879 htxn->p = p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01007880 htxn->dir = dir;
Thierry FOURNIERab00df62016-07-14 11:42:37 +02007881 htxn->flags = flags;
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007882
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01007883 /* Create the "f" field that contains a list of fetches. */
7884 lua_pushstring(L, "f");
Thierry FOURNIERca988662015-12-20 18:43:03 +01007885 if (!hlua_fetches_new(L, htxn, HLUA_F_MAY_USE_HTTP))
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01007886 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007887 lua_rawset(L, -3);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01007888
7889 /* Create the "sf" field that contains a list of stringsafe fetches. */
7890 lua_pushstring(L, "sf");
Thierry FOURNIERca988662015-12-20 18:43:03 +01007891 if (!hlua_fetches_new(L, htxn, HLUA_F_MAY_USE_HTTP | HLUA_F_AS_STRING))
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01007892 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007893 lua_rawset(L, -3);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01007894
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007895 /* Create the "c" field that contains a list of converters. */
7896 lua_pushstring(L, "c");
Willy Tarreaude491382015-04-06 11:04:28 +02007897 if (!hlua_converters_new(L, htxn, 0))
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01007898 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007899 lua_rawset(L, -3);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01007900
7901 /* Create the "sc" field that contains a list of stringsafe converters. */
7902 lua_pushstring(L, "sc");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01007903 if (!hlua_converters_new(L, htxn, HLUA_F_AS_STRING))
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007904 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007905 lua_rawset(L, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007906
Thierry FOURNIER397826a2015-03-11 19:39:09 +01007907 /* Create the "req" field that contains the request channel object. */
7908 lua_pushstring(L, "req");
Willy Tarreau2a71af42015-03-10 13:51:50 +01007909 if (!hlua_channel_new(L, &s->req))
Thierry FOURNIER397826a2015-03-11 19:39:09 +01007910 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007911 lua_rawset(L, -3);
Thierry FOURNIER397826a2015-03-11 19:39:09 +01007912
7913 /* Create the "res" field that contains the response channel object. */
7914 lua_pushstring(L, "res");
Willy Tarreau2a71af42015-03-10 13:51:50 +01007915 if (!hlua_channel_new(L, &s->res))
Thierry FOURNIER397826a2015-03-11 19:39:09 +01007916 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007917 lua_rawset(L, -3);
Thierry FOURNIER397826a2015-03-11 19:39:09 +01007918
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007919 /* Creates the HTTP object is the current proxy allows http. */
7920 lua_pushstring(L, "http");
Christopher Faulet1bb6afa2021-03-08 17:57:53 +01007921 if (IS_HTX_STRM(s)) {
Willy Tarreaude491382015-04-06 11:04:28 +02007922 if (!hlua_http_new(L, htxn))
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007923 return 0;
7924 }
7925 else
7926 lua_pushnil(L);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007927 lua_rawset(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007928
Christopher Faulet78c35472020-02-26 17:14:08 +01007929 if ((htxn->flags & HLUA_TXN_CTX_MASK) == HLUA_TXN_FLT_CTX) {
7930 /* HTTPMessage object are created when a lua TXN is created from
7931 * a filter context only
7932 */
7933
7934 /* Creates the HTTP-Request object is the current proxy allows http. */
7935 lua_pushstring(L, "http_req");
7936 if (p->mode == PR_MODE_HTTP) {
7937 if (!hlua_http_msg_new(L, &s->txn->req))
7938 return 0;
7939 }
7940 else
7941 lua_pushnil(L);
7942 lua_rawset(L, -3);
7943
7944 /* Creates the HTTP-Response object is the current proxy allows http. */
7945 lua_pushstring(L, "http_res");
7946 if (p->mode == PR_MODE_HTTP) {
7947 if (!hlua_http_msg_new(L, &s->txn->rsp))
7948 return 0;
7949 }
7950 else
7951 lua_pushnil(L);
7952 lua_rawset(L, -3);
7953 }
7954
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007955 /* Pop a class sesison metatable and affect it to the userdata. */
7956 lua_rawgeti(L, LUA_REGISTRYINDEX, class_txn_ref);
7957 lua_setmetatable(L, -2);
7958
7959 return 1;
7960}
7961
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01007962__LJMP static int hlua_txn_deflog(lua_State *L)
7963{
7964 const char *msg;
7965 struct hlua_txn *htxn;
7966
7967 MAY_LJMP(check_args(L, 2, "deflog"));
7968 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7969 msg = MAY_LJMP(luaL_checkstring(L, 2));
7970
7971 hlua_sendlog(htxn->s->be, htxn->s->logs.level, msg);
7972 return 0;
7973}
7974
7975__LJMP static int hlua_txn_log(lua_State *L)
7976{
7977 int level;
7978 const char *msg;
7979 struct hlua_txn *htxn;
7980
7981 MAY_LJMP(check_args(L, 3, "log"));
7982 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7983 level = MAY_LJMP(luaL_checkinteger(L, 2));
7984 msg = MAY_LJMP(luaL_checkstring(L, 3));
7985
7986 if (level < 0 || level >= NB_LOG_LEVELS)
7987 WILL_LJMP(luaL_argerror(L, 1, "Invalid loglevel."));
7988
7989 hlua_sendlog(htxn->s->be, level, msg);
7990 return 0;
7991}
7992
7993__LJMP static int hlua_txn_log_debug(lua_State *L)
7994{
7995 const char *msg;
7996 struct hlua_txn *htxn;
7997
7998 MAY_LJMP(check_args(L, 2, "Debug"));
7999 htxn = MAY_LJMP(hlua_checktxn(L, 1));
8000 msg = MAY_LJMP(luaL_checkstring(L, 2));
8001 hlua_sendlog(htxn->s->be, LOG_DEBUG, msg);
8002 return 0;
8003}
8004
8005__LJMP static int hlua_txn_log_info(lua_State *L)
8006{
8007 const char *msg;
8008 struct hlua_txn *htxn;
8009
8010 MAY_LJMP(check_args(L, 2, "Info"));
8011 htxn = MAY_LJMP(hlua_checktxn(L, 1));
8012 msg = MAY_LJMP(luaL_checkstring(L, 2));
8013 hlua_sendlog(htxn->s->be, LOG_INFO, msg);
8014 return 0;
8015}
8016
8017__LJMP static int hlua_txn_log_warning(lua_State *L)
8018{
8019 const char *msg;
8020 struct hlua_txn *htxn;
8021
8022 MAY_LJMP(check_args(L, 2, "Warning"));
8023 htxn = MAY_LJMP(hlua_checktxn(L, 1));
8024 msg = MAY_LJMP(luaL_checkstring(L, 2));
8025 hlua_sendlog(htxn->s->be, LOG_WARNING, msg);
8026 return 0;
8027}
8028
8029__LJMP static int hlua_txn_log_alert(lua_State *L)
8030{
8031 const char *msg;
8032 struct hlua_txn *htxn;
8033
8034 MAY_LJMP(check_args(L, 2, "Alert"));
8035 htxn = MAY_LJMP(hlua_checktxn(L, 1));
8036 msg = MAY_LJMP(luaL_checkstring(L, 2));
8037 hlua_sendlog(htxn->s->be, LOG_ALERT, msg);
8038 return 0;
8039}
8040
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01008041__LJMP static int hlua_txn_set_loglevel(lua_State *L)
8042{
8043 struct hlua_txn *htxn;
8044 int ll;
8045
8046 MAY_LJMP(check_args(L, 2, "set_loglevel"));
8047 htxn = MAY_LJMP(hlua_checktxn(L, 1));
8048 ll = MAY_LJMP(luaL_checkinteger(L, 2));
8049
8050 if (ll < 0 || ll > 7)
8051 WILL_LJMP(luaL_argerror(L, 2, "Bad log level. It must be between 0 and 7"));
8052
8053 htxn->s->logs.level = ll;
8054 return 0;
8055}
8056
8057__LJMP static int hlua_txn_set_tos(lua_State *L)
8058{
8059 struct hlua_txn *htxn;
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01008060 int tos;
8061
8062 MAY_LJMP(check_args(L, 2, "set_tos"));
8063 htxn = MAY_LJMP(hlua_checktxn(L, 1));
8064 tos = MAY_LJMP(luaL_checkinteger(L, 2));
8065
Willy Tarreau1a18b542018-12-11 16:37:42 +01008066 conn_set_tos(objt_conn(htxn->s->sess->origin), tos);
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01008067 return 0;
8068}
8069
8070__LJMP static int hlua_txn_set_mark(lua_State *L)
8071{
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01008072 struct hlua_txn *htxn;
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01008073 int mark;
8074
8075 MAY_LJMP(check_args(L, 2, "set_mark"));
8076 htxn = MAY_LJMP(hlua_checktxn(L, 1));
8077 mark = MAY_LJMP(luaL_checkinteger(L, 2));
8078
Lukas Tribus579e3e32019-08-11 18:03:45 +02008079 conn_set_mark(objt_conn(htxn->s->sess->origin), mark);
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01008080 return 0;
8081}
8082
Patrick Hemmer268a7072018-05-11 12:52:31 -04008083__LJMP static int hlua_txn_set_priority_class(lua_State *L)
8084{
8085 struct hlua_txn *htxn;
8086
8087 MAY_LJMP(check_args(L, 2, "set_priority_class"));
8088 htxn = MAY_LJMP(hlua_checktxn(L, 1));
8089 htxn->s->priority_class = queue_limit_class(MAY_LJMP(luaL_checkinteger(L, 2)));
8090 return 0;
8091}
8092
8093__LJMP static int hlua_txn_set_priority_offset(lua_State *L)
8094{
8095 struct hlua_txn *htxn;
8096
8097 MAY_LJMP(check_args(L, 2, "set_priority_offset"));
8098 htxn = MAY_LJMP(hlua_checktxn(L, 1));
8099 htxn->s->priority_offset = queue_limit_offset(MAY_LJMP(luaL_checkinteger(L, 2)));
8100 return 0;
8101}
8102
Christopher Faulet700d9e82020-01-31 12:21:52 +01008103/* Forward the Reply object to the client. This function converts the reply in
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05008104 * HTX an push it to into the response channel. It is response to forward the
Christopher Faulet700d9e82020-01-31 12:21:52 +01008105 * message and terminate the transaction. It returns 1 on success and 0 on
8106 * error. The Reply must be on top of the stack.
8107 */
8108__LJMP static int hlua_txn_forward_reply(lua_State *L, struct stream *s)
8109{
8110 struct htx *htx;
8111 struct htx_sl *sl;
8112 struct h1m h1m;
8113 const char *status, *reason, *body;
8114 size_t status_len, reason_len, body_len;
8115 int ret, code, flags;
8116
8117 code = 200;
8118 status = "200";
8119 status_len = 3;
8120 ret = lua_getfield(L, -1, "status");
8121 if (ret == LUA_TNUMBER) {
8122 code = lua_tointeger(L, -1);
8123 status = lua_tolstring(L, -1, &status_len);
8124 }
8125 lua_pop(L, 1);
8126
8127 reason = http_get_reason(code);
8128 reason_len = strlen(reason);
8129 ret = lua_getfield(L, -1, "reason");
8130 if (ret == LUA_TSTRING)
8131 reason = lua_tolstring(L, -1, &reason_len);
8132 lua_pop(L, 1);
8133
8134 body = NULL;
8135 body_len = 0;
8136 ret = lua_getfield(L, -1, "body");
8137 if (ret == LUA_TSTRING)
8138 body = lua_tolstring(L, -1, &body_len);
8139 lua_pop(L, 1);
8140
8141 /* Prepare the response before inserting the headers */
8142 h1m_init_res(&h1m);
8143 htx = htx_from_buf(&s->res.buf);
8144 channel_htx_truncate(&s->res, htx);
8145 if (s->txn->req.flags & HTTP_MSGF_VER_11) {
8146 flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11);
8147 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.1"),
8148 ist2(status, status_len), ist2(reason, reason_len));
8149 }
8150 else {
8151 flags = HTX_SL_F_IS_RESP;
8152 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.0"),
8153 ist2(status, status_len), ist2(reason, reason_len));
8154 }
8155 if (!sl)
8156 goto fail;
8157 sl->info.res.status = code;
8158
8159 /* Push in the stack the "headers" entry. */
8160 ret = lua_getfield(L, -1, "headers");
8161 if (ret != LUA_TTABLE)
8162 goto skip_headers;
8163
8164 lua_pushnil(L);
8165 while (lua_next(L, -2) != 0) {
8166 struct ist name, value;
8167 const char *n, *v;
8168 size_t nlen, vlen;
8169
8170 if (!lua_isstring(L, -2) || !lua_istable(L, -1)) {
8171 /* Skip element if the key is not a string or if the value is not a table */
8172 goto next_hdr;
8173 }
8174
8175 n = lua_tolstring(L, -2, &nlen);
8176 name = ist2(n, nlen);
8177 if (isteqi(name, ist("content-length"))) {
8178 /* Always skip content-length header. It will be added
8179 * later with the correct len
8180 */
8181 goto next_hdr;
8182 }
8183
8184 /* Loop on header's values */
8185 lua_pushnil(L);
8186 while (lua_next(L, -2)) {
8187 if (!lua_isstring(L, -1)) {
8188 /* Skip the value if it is not a string */
8189 goto next_value;
8190 }
8191
8192 v = lua_tolstring(L, -1, &vlen);
8193 value = ist2(v, vlen);
8194
8195 if (isteqi(name, ist("transfer-encoding")))
8196 h1_parse_xfer_enc_header(&h1m, value);
8197 if (!htx_add_header(htx, ist2(n, nlen), ist2(v, vlen)))
8198 goto fail;
8199
8200 next_value:
8201 lua_pop(L, 1);
8202 }
8203
8204 next_hdr:
8205 lua_pop(L, 1);
8206 }
8207 skip_headers:
8208 lua_pop(L, 1);
8209
8210 /* Update h1m flags: CLEN is set if CHNK is not present */
8211 if (!(h1m.flags & H1_MF_CHNK)) {
8212 const char *clen = ultoa(body_len);
8213
8214 h1m.flags |= H1_MF_CLEN;
8215 if (!htx_add_header(htx, ist("content-length"), ist(clen)))
8216 goto fail;
8217 }
8218 if (h1m.flags & (H1_MF_CLEN|H1_MF_CHNK))
8219 h1m.flags |= H1_MF_XFER_LEN;
8220
8221 /* Update HTX start-line flags */
8222 if (h1m.flags & H1_MF_XFER_ENC)
8223 flags |= HTX_SL_F_XFER_ENC;
8224 if (h1m.flags & H1_MF_XFER_LEN) {
8225 flags |= HTX_SL_F_XFER_LEN;
8226 if (h1m.flags & H1_MF_CHNK)
8227 flags |= HTX_SL_F_CHNK;
8228 else if (h1m.flags & H1_MF_CLEN)
8229 flags |= HTX_SL_F_CLEN;
8230 if (h1m.body_len == 0)
8231 flags |= HTX_SL_F_BODYLESS;
8232 }
8233 sl->flags |= flags;
8234
8235
8236 if (!htx_add_endof(htx, HTX_BLK_EOH) ||
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01008237 (body_len && !htx_add_data_atonce(htx, ist2(body, body_len))))
Christopher Faulet700d9e82020-01-31 12:21:52 +01008238 goto fail;
8239
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01008240 htx->flags |= HTX_FL_EOM;
8241
Christopher Faulet700d9e82020-01-31 12:21:52 +01008242 /* Now, forward the response and terminate the transaction */
8243 s->txn->status = code;
8244 htx_to_buf(htx, &s->res.buf);
8245 if (!http_forward_proxy_resp(s, 1))
8246 goto fail;
8247
8248 return 1;
8249
8250 fail:
8251 channel_htx_truncate(&s->res, htx);
8252 return 0;
8253}
8254
8255/* Terminate a transaction if called from a lua action. For TCP streams,
8256 * processing is just aborted. Nothing is returned to the client and all
8257 * arguments are ignored. For HTTP streams, if a reply is passed as argument, it
8258 * is forwarded to the client before terminating the transaction. On success,
8259 * the function exits with ACT_RET_DONE code. If an error occurred, it exits
8260 * with ACT_RET_ERR code. If this function is not called from a lua action, it
8261 * just exits without any processing.
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01008262 */
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02008263__LJMP static int hlua_txn_done(lua_State *L)
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01008264{
Willy Tarreaub2ccb562015-04-06 11:11:15 +02008265 struct hlua_txn *htxn;
Christopher Faulet700d9e82020-01-31 12:21:52 +01008266 struct stream *s;
8267 int finst;
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01008268
Willy Tarreaub2ccb562015-04-06 11:11:15 +02008269 htxn = MAY_LJMP(hlua_checktxn(L, 1));
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01008270
Christopher Faulet700d9e82020-01-31 12:21:52 +01008271 /* If the flags NOTERM is set, we cannot terminate the session, so we
8272 * just end the execution of the current lua code. */
8273 if (htxn->flags & HLUA_TXN_NOTERM)
Thierry FOURNIERab00df62016-07-14 11:42:37 +02008274 WILL_LJMP(hlua_done(L));
Thierry FOURNIERab00df62016-07-14 11:42:37 +02008275
Christopher Faulet700d9e82020-01-31 12:21:52 +01008276 s = htxn->s;
Christopher Fauletd8f0e072020-02-25 09:45:51 +01008277 if (!IS_HTX_STRM(htxn->s)) {
Christopher Faulet700d9e82020-01-31 12:21:52 +01008278 struct channel *req = &s->req;
8279 struct channel *res = &s->res;
Willy Tarreau81389672015-03-10 12:03:52 +01008280
Christopher Faulet700d9e82020-01-31 12:21:52 +01008281 channel_auto_read(req);
8282 channel_abort(req);
Christopher Faulet700d9e82020-01-31 12:21:52 +01008283 channel_erase(req);
8284
Christopher Faulet700d9e82020-01-31 12:21:52 +01008285 channel_auto_read(res);
8286 channel_auto_close(res);
Christopher Faulet12762f02023-04-13 15:40:10 +02008287 sc_schedule_abort(s->scb);
Christopher Faulet700d9e82020-01-31 12:21:52 +01008288
8289 finst = ((htxn->dir == SMP_OPT_DIR_REQ) ? SF_FINST_R : SF_FINST_D);
8290 goto done;
Christopher Fauletfe6a71b2019-07-26 16:40:24 +02008291 }
Thierry FOURNIER10ec2142015-08-24 17:23:45 +02008292
Christopher Faulet700d9e82020-01-31 12:21:52 +01008293 if (lua_gettop(L) == 1 || !lua_istable(L, 2)) {
8294 /* No reply or invalid reply */
8295 s->txn->status = 0;
8296 http_reply_and_close(s, 0, NULL);
8297 }
8298 else {
8299 /* Remove extra args to have the reply on top of the stack */
8300 if (lua_gettop(L) > 2)
8301 lua_pop(L, lua_gettop(L) - 2);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01008302
Christopher Faulet700d9e82020-01-31 12:21:52 +01008303 if (!hlua_txn_forward_reply(L, s)) {
8304 if (!(s->flags & SF_ERR_MASK))
8305 s->flags |= SF_ERR_PRXCOND;
8306 lua_pushinteger(L, ACT_RET_ERR);
8307 WILL_LJMP(hlua_done(L));
8308 return 0; /* Never reached */
8309 }
Christopher Faulet4d0e2632019-07-16 10:52:40 +02008310 }
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02008311
Christopher Faulet700d9e82020-01-31 12:21:52 +01008312 finst = ((htxn->dir == SMP_OPT_DIR_REQ) ? SF_FINST_R : SF_FINST_H);
8313 if (htxn->dir == SMP_OPT_DIR_REQ) {
8314 /* let's log the request time */
Willy Tarreau69530f52023-04-28 09:16:15 +02008315 s->logs.request_ts = now_ns;
Christopher Faulet700d9e82020-01-31 12:21:52 +01008316 if (s->sess->fe == s->be) /* report it if the request was intercepted by the frontend */
Willy Tarreau4781b152021-04-06 13:53:36 +02008317 _HA_ATOMIC_INC(&s->sess->fe->fe_counters.intercepted_req);
Christopher Faulet700d9e82020-01-31 12:21:52 +01008318 }
Christopher Fauletfe6a71b2019-07-26 16:40:24 +02008319
Christopher Faulet700d9e82020-01-31 12:21:52 +01008320 done:
8321 if (!(s->flags & SF_ERR_MASK))
8322 s->flags |= SF_ERR_LOCAL;
8323 if (!(s->flags & SF_FINST_MASK))
8324 s->flags |= finst;
Christopher Fauletfe6a71b2019-07-26 16:40:24 +02008325
Christopher Faulete48d1dc2021-08-13 14:11:17 +02008326 if ((htxn->flags & HLUA_TXN_CTX_MASK) == HLUA_TXN_FLT_CTX)
8327 lua_pushinteger(L, -1);
8328 else
8329 lua_pushinteger(L, ACT_RET_ABRT);
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02008330 WILL_LJMP(hlua_done(L));
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01008331 return 0;
8332}
8333
Christopher Faulet700d9e82020-01-31 12:21:52 +01008334/*
8335 *
8336 *
8337 * Class REPLY
8338 *
8339 *
8340 */
8341
8342/* Pushes the TXN reply onto the top of the stack. If the stask does not have a
8343 * free slots, the function fails and returns 0;
8344 */
8345static int hlua_txn_reply_new(lua_State *L)
8346{
8347 struct hlua_txn *htxn;
8348 const char *reason, *body = NULL;
8349 int ret, status;
8350
8351 htxn = MAY_LJMP(hlua_checktxn(L, 1));
Christopher Fauletd8f0e072020-02-25 09:45:51 +01008352 if (!IS_HTX_STRM(htxn->s)) {
Christopher Faulet700d9e82020-01-31 12:21:52 +01008353 hlua_pusherror(L, "txn object is not an HTTP transaction.");
8354 WILL_LJMP(lua_error(L));
8355 }
8356
8357 /* Default value */
8358 status = 200;
8359 reason = http_get_reason(status);
8360
8361 if (lua_istable(L, 2)) {
8362 /* load status and reason from the table argument at index 2 */
8363 ret = lua_getfield(L, 2, "status");
8364 if (ret == LUA_TNIL)
8365 goto reason;
8366 else if (ret != LUA_TNUMBER) {
8367 /* invalid status: ignore the reason */
8368 goto body;
8369 }
8370 status = lua_tointeger(L, -1);
8371
8372 reason:
8373 lua_pop(L, 1); /* restore the stack: remove status */
8374 ret = lua_getfield(L, 2, "reason");
8375 if (ret == LUA_TSTRING)
8376 reason = lua_tostring(L, -1);
8377
8378 body:
8379 lua_pop(L, 1); /* restore the stack: remove invalid status or reason */
8380 ret = lua_getfield(L, 2, "body");
8381 if (ret == LUA_TSTRING)
8382 body = lua_tostring(L, -1);
8383 lua_pop(L, 1); /* restore the stack: remove body */
8384 }
8385
8386 /* Create the Reply table */
8387 lua_newtable(L);
8388
8389 /* Add status element */
8390 lua_pushstring(L, "status");
8391 lua_pushinteger(L, status);
8392 lua_settable(L, -3);
8393
8394 /* Add reason element */
8395 reason = http_get_reason(status);
8396 lua_pushstring(L, "reason");
8397 lua_pushstring(L, reason);
8398 lua_settable(L, -3);
8399
8400 /* Add body element, nil if undefined */
8401 lua_pushstring(L, "body");
8402 if (body)
8403 lua_pushstring(L, body);
8404 else
8405 lua_pushnil(L);
8406 lua_settable(L, -3);
8407
8408 /* Add headers element */
8409 lua_pushstring(L, "headers");
8410 lua_newtable(L);
8411
8412 /* stack: [ txn, <Arg:table>, <Reply:table>, "headers", <headers:table> ] */
8413 if (lua_istable(L, 2)) {
8414 /* load headers from the table argument at index 2. If it is a table, copy it. */
8415 ret = lua_getfield(L, 2, "headers");
8416 if (ret == LUA_TTABLE) {
8417 /* stack: [ ... <headers:table>, <table> ] */
8418 lua_pushnil(L);
8419 while (lua_next(L, -2) != 0) {
8420 /* stack: [ ... <headers:table>, <table>, k, v] */
8421 if (!lua_isstring(L, -1) && !lua_istable(L, -1)) {
8422 /* invalid value type, skip it */
8423 lua_pop(L, 1);
8424 continue;
8425 }
8426
8427
8428 /* Duplicate the key and swap it with the value. */
8429 lua_pushvalue(L, -2);
8430 lua_insert(L, -2);
8431 /* stack: [ ... <headers:table>, <table>, k, k, v ] */
8432
8433 lua_newtable(L);
8434 lua_insert(L, -2);
8435 /* stack: [ ... <headers:table>, <table>, k, k, <inner:table>, v ] */
8436
8437 if (lua_isstring(L, -1)) {
8438 /* push the value in the inner table */
8439 lua_rawseti(L, -2, 1);
8440 }
8441 else { /* table */
8442 lua_pushnil(L);
8443 while (lua_next(L, -2) != 0) {
8444 /* stack: [ ... <headers:table>, <table>, k, k, <inner:table>, <v:table>, k2, v2 ] */
8445 if (!lua_isstring(L, -1)) {
8446 /* invalid value type, skip it*/
8447 lua_pop(L, 1);
8448 continue;
8449 }
8450 /* push the value in the inner table */
8451 lua_rawseti(L, -4, lua_rawlen(L, -4) + 1);
8452 /* stack: [ ... <headers:table>, <table>, k, k, <inner:table>, <v:table>, k2 ] */
8453 }
8454 lua_pop(L, 1);
8455 /* stack: [ ... <headers:table>, <table>, k, k, <inner:table> ] */
8456 }
8457
8458 /* push (k,v) on the stack in the headers table:
8459 * stack: [ ... <headers:table>, <table>, k, k, v ]
8460 */
8461 lua_settable(L, -5);
8462 /* stack: [ ... <headers:table>, <table>, k ] */
8463 }
8464 }
8465 lua_pop(L, 1);
8466 }
8467 /* stack: [ txn, <Arg:table>, <Reply:table>, "headers", <headers:table> ] */
8468 lua_settable(L, -3);
8469 /* stack: [ txn, <Arg:table>, <Reply:table> ] */
8470
8471 /* Pop a class sesison metatable and affect it to the userdata. */
8472 lua_rawgeti(L, LUA_REGISTRYINDEX, class_txn_reply_ref);
8473 lua_setmetatable(L, -2);
8474 return 1;
8475}
8476
8477/* Set the reply status code, and optionally the reason. If no reason is
8478 * provided, the default one corresponding to the status code is used.
8479 */
8480__LJMP static int hlua_txn_reply_set_status(lua_State *L)
8481{
8482 int status = MAY_LJMP(luaL_checkinteger(L, 2));
8483 const char *reason = MAY_LJMP(luaL_optlstring(L, 3, NULL, NULL));
8484
8485 /* First argument (self) must be a table */
Aurelien DARRAGONd83d0452022-10-05 11:46:45 +02008486 MAY_LJMP(luaL_checktype(L, 1, LUA_TTABLE));
Christopher Faulet700d9e82020-01-31 12:21:52 +01008487
8488 if (status < 100 || status > 599) {
8489 lua_pushboolean(L, 0);
8490 return 1;
8491 }
8492 if (!reason)
8493 reason = http_get_reason(status);
8494
8495 lua_pushinteger(L, status);
8496 lua_setfield(L, 1, "status");
8497
8498 lua_pushstring(L, reason);
8499 lua_setfield(L, 1, "reason");
8500
8501 lua_pushboolean(L, 1);
8502 return 1;
8503}
8504
8505/* Add a header into the reply object. Each header name is associated to an
8506 * array of values in the "headers" table. If the header name is not found, a
8507 * new entry is created.
8508 */
8509__LJMP static int hlua_txn_reply_add_header(lua_State *L)
8510{
8511 const char *name = MAY_LJMP(luaL_checkstring(L, 2));
8512 const char *value = MAY_LJMP(luaL_checkstring(L, 3));
8513 int ret;
8514
8515 /* First argument (self) must be a table */
Aurelien DARRAGONd83d0452022-10-05 11:46:45 +02008516 MAY_LJMP(luaL_checktype(L, 1, LUA_TTABLE));
Christopher Faulet700d9e82020-01-31 12:21:52 +01008517
8518 /* Push in the stack the "headers" entry. */
8519 ret = lua_getfield(L, 1, "headers");
8520 if (ret != LUA_TTABLE) {
8521 hlua_pusherror(L, "Reply['headers'] is expected to a an array. %s found", lua_typename(L, ret));
8522 WILL_LJMP(lua_error(L));
8523 }
8524
8525 /* check if the header is already registered. If not, register it. */
8526 ret = lua_getfield(L, -1, name);
8527 if (ret == LUA_TNIL) {
8528 /* Entry not found. */
8529 lua_pop(L, 1); /* remove the nil. The "headers" table is the top of the stack. */
8530
8531 /* Insert the new header name in the array in the top of the stack.
8532 * It left the new array in the top of the stack.
8533 */
8534 lua_newtable(L);
8535 lua_pushstring(L, name);
8536 lua_pushvalue(L, -2);
8537 lua_settable(L, -4);
8538 }
8539 else if (ret != LUA_TTABLE) {
8540 hlua_pusherror(L, "Reply['headers']['%s'] is expected to be an array. %s found", name, lua_typename(L, ret));
8541 WILL_LJMP(lua_error(L));
8542 }
8543
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -07008544 /* Now the top of thestack is an array of values. We push
Christopher Faulet700d9e82020-01-31 12:21:52 +01008545 * the header value as new entry.
8546 */
8547 lua_pushstring(L, value);
8548 ret = lua_rawlen(L, -2);
8549 lua_rawseti(L, -2, ret + 1);
8550
8551 lua_pushboolean(L, 1);
8552 return 1;
8553}
8554
8555/* Remove all occurrences of a given header name. */
8556__LJMP static int hlua_txn_reply_del_header(lua_State *L)
8557{
8558 const char *name = MAY_LJMP(luaL_checkstring(L, 2));
8559 int ret;
8560
8561 /* First argument (self) must be a table */
Aurelien DARRAGONd83d0452022-10-05 11:46:45 +02008562 MAY_LJMP(luaL_checktype(L, 1, LUA_TTABLE));
Christopher Faulet700d9e82020-01-31 12:21:52 +01008563
8564 /* Push in the stack the "headers" entry. */
8565 ret = lua_getfield(L, 1, "headers");
8566 if (ret != LUA_TTABLE) {
8567 hlua_pusherror(L, "Reply['headers'] is expected to be an array. %s found", lua_typename(L, ret));
8568 WILL_LJMP(lua_error(L));
8569 }
8570
8571 lua_pushstring(L, name);
8572 lua_pushnil(L);
8573 lua_settable(L, -3);
8574
8575 lua_pushboolean(L, 1);
8576 return 1;
8577}
8578
8579/* Set the reply's body. Overwrite any existing entry. */
8580__LJMP static int hlua_txn_reply_set_body(lua_State *L)
8581{
8582 const char *payload = MAY_LJMP(luaL_checkstring(L, 2));
8583
8584 /* First argument (self) must be a table */
Aurelien DARRAGONd83d0452022-10-05 11:46:45 +02008585 MAY_LJMP(luaL_checktype(L, 1, LUA_TTABLE));
Christopher Faulet700d9e82020-01-31 12:21:52 +01008586
8587 lua_pushstring(L, payload);
8588 lua_setfield(L, 1, "body");
8589
8590 lua_pushboolean(L, 1);
8591 return 1;
8592}
8593
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01008594__LJMP static int hlua_log(lua_State *L)
8595{
8596 int level;
8597 const char *msg;
8598
8599 MAY_LJMP(check_args(L, 2, "log"));
8600 level = MAY_LJMP(luaL_checkinteger(L, 1));
8601 msg = MAY_LJMP(luaL_checkstring(L, 2));
8602
8603 if (level < 0 || level >= NB_LOG_LEVELS)
8604 WILL_LJMP(luaL_argerror(L, 1, "Invalid loglevel."));
8605
8606 hlua_sendlog(NULL, level, msg);
8607 return 0;
8608}
8609
8610__LJMP static int hlua_log_debug(lua_State *L)
8611{
8612 const char *msg;
8613
8614 MAY_LJMP(check_args(L, 1, "debug"));
8615 msg = MAY_LJMP(luaL_checkstring(L, 1));
8616 hlua_sendlog(NULL, LOG_DEBUG, msg);
8617 return 0;
8618}
8619
8620__LJMP static int hlua_log_info(lua_State *L)
8621{
8622 const char *msg;
8623
8624 MAY_LJMP(check_args(L, 1, "info"));
8625 msg = MAY_LJMP(luaL_checkstring(L, 1));
8626 hlua_sendlog(NULL, LOG_INFO, msg);
8627 return 0;
8628}
8629
8630__LJMP static int hlua_log_warning(lua_State *L)
8631{
8632 const char *msg;
8633
8634 MAY_LJMP(check_args(L, 1, "warning"));
8635 msg = MAY_LJMP(luaL_checkstring(L, 1));
8636 hlua_sendlog(NULL, LOG_WARNING, msg);
8637 return 0;
8638}
8639
8640__LJMP static int hlua_log_alert(lua_State *L)
8641{
8642 const char *msg;
8643
8644 MAY_LJMP(check_args(L, 1, "alert"));
8645 msg = MAY_LJMP(luaL_checkstring(L, 1));
8646 hlua_sendlog(NULL, LOG_ALERT, msg);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01008647 return 0;
8648}
8649
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01008650__LJMP static int hlua_sleep_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008651{
8652 int wakeup_ms = lua_tointeger(L, -1);
Willy Tarreau12c02702021-09-30 16:12:31 +02008653 if (!tick_is_expired(wakeup_ms, now_ms))
Willy Tarreau9635e032018-10-16 17:52:55 +02008654 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008655 return 0;
8656}
8657
8658__LJMP static int hlua_sleep(lua_State *L)
8659{
8660 unsigned int delay;
Aurelien DARRAGON2a9764b2023-04-04 18:41:04 +02008661 int wakeup_ms; // tick value
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008662
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008663 MAY_LJMP(check_args(L, 1, "sleep"));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008664
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01008665 delay = MAY_LJMP(luaL_checkinteger(L, 1)) * 1000;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008666 wakeup_ms = tick_add(now_ms, delay);
8667 lua_pushinteger(L, wakeup_ms);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008668
Willy Tarreau9635e032018-10-16 17:52:55 +02008669 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008670 return 0;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008671}
8672
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008673__LJMP static int hlua_msleep(lua_State *L)
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008674{
8675 unsigned int delay;
Aurelien DARRAGON2a9764b2023-04-04 18:41:04 +02008676 int wakeup_ms; // tick value
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008677
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008678 MAY_LJMP(check_args(L, 1, "msleep"));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008679
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01008680 delay = MAY_LJMP(luaL_checkinteger(L, 1));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008681 wakeup_ms = tick_add(now_ms, delay);
8682 lua_pushinteger(L, wakeup_ms);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008683
Willy Tarreau9635e032018-10-16 17:52:55 +02008684 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008685 return 0;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008686}
8687
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01008688/* This functionis an LUA binding. it permits to give back
8689 * the hand at the HAProxy scheduler. It is used when the
8690 * LUA processing consumes a lot of time.
8691 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01008692__LJMP static int hlua_yield_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008693{
8694 return 0;
8695}
8696
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01008697__LJMP static int hlua_yield(lua_State *L)
8698{
Willy Tarreau9635e032018-10-16 17:52:55 +02008699 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_yield_yield, TICK_ETERNITY, HLUA_CTRLYIELD));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008700 return 0;
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01008701}
8702
Thierry FOURNIER37196f42015-02-16 19:34:56 +01008703/* This function change the nice of the currently executed
8704 * task. It is used set low or high priority at the current
8705 * task.
8706 */
Willy Tarreau59551662015-03-10 14:23:13 +01008707__LJMP static int hlua_set_nice(lua_State *L)
Thierry FOURNIER37196f42015-02-16 19:34:56 +01008708{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01008709 struct hlua *hlua;
8710 int nice;
Thierry FOURNIER37196f42015-02-16 19:34:56 +01008711
Willy Tarreau80f5fae2015-02-27 16:38:20 +01008712 MAY_LJMP(check_args(L, 1, "set_nice"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01008713 nice = MAY_LJMP(luaL_checkinteger(L, 1));
Thierry FOURNIER37196f42015-02-16 19:34:56 +01008714
Thierry Fournier4234dbd2020-11-28 13:18:23 +01008715 /* Get hlua struct, or NULL if we execute from main lua state */
8716 hlua = hlua_gethlua(L);
8717
8718 /* If the task is not set, I'm in a start mode. */
Thierry FOURNIER37196f42015-02-16 19:34:56 +01008719 if (!hlua || !hlua->task)
8720 return 0;
8721
8722 if (nice < -1024)
8723 nice = -1024;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01008724 else if (nice > 1024)
Thierry FOURNIER37196f42015-02-16 19:34:56 +01008725 nice = 1024;
8726
8727 hlua->task->nice = nice;
8728 return 0;
8729}
8730
Aurelien DARRAGON8cd620b2023-04-07 17:37:46 +02008731/* safe lua coroutine.create() function:
8732 *
8733 * This is a simple wrapper for coroutine.create() that
8734 * ensures the current hlua state ctx is available from
8735 * the new subroutine state
8736 */
8737__LJMP static int hlua_coroutine_create(lua_State *L)
8738{
8739 lua_State *new; /* new coroutine state */
8740 struct hlua **hlua_store;
8741 struct hlua *hlua = hlua_gethlua(L);
8742
8743 new = lua_newthread(L);
8744 if (!new)
8745 return 0;
8746
8747 hlua_store = lua_getextraspace(new);
8748 /* Expose current hlua ctx on new lua thread
8749 * (hlua_gethlua() will properly return the last "known"
8750 * hlua ctx instead of NULL when it is called from such coroutines)
8751 */
8752 *hlua_store = hlua;
8753
8754 /* new lua thread is on the top of the stack, we
8755 * need to duplicate first stack argument (<f> from coroutine.create(<f>))
8756 * on the top of the stack to be able to use xmove() to move it on the new
8757 * stack
8758 */
8759 lua_pushvalue(L, 1);
8760 /* move <f> function to the new stack */
8761 lua_xmove(L, new, 1);
8762 /* new lua thread is back at the top of the stack */
8763 return 1;
8764}
8765
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08008766/* This function is used as a callback of a task. It is called by the
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008767 * HAProxy task subsystem when the task is awaked. The LUA runtime can
8768 * return an E_AGAIN signal, the emmiter of this signal must set a
8769 * signal to wake the task.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008770 *
8771 * Task wrapper are longjmp safe because the only one Lua code
8772 * executed is the safe hlua_ctx_resume();
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008773 */
Willy Tarreau144f84a2021-03-02 16:09:26 +01008774struct task *hlua_process_task(struct task *task, void *context, unsigned int state)
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008775{
Olivier Houchard9f6af332018-05-25 14:04:04 +02008776 struct hlua *hlua = context;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008777 enum hlua_exec status;
8778
Willy Tarreau6ef52f42022-06-15 14:19:48 +02008779 if (task->tid < 0)
8780 task->tid = tid;
8781
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008782 /* If it is the first call to the task, we must initialize the
8783 * execution timeouts.
8784 */
8785 if (!HLUA_IS_RUNNING(hlua))
Aurelien DARRAGONda9503c2022-11-25 09:10:07 +01008786 hlua_timer_init(&hlua->timer, hlua_timeout_task);
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008787
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008788 /* Execute the Lua code. */
8789 status = hlua_ctx_resume(hlua, 1);
8790
8791 switch (status) {
8792 /* finished or yield */
8793 case HLUA_E_OK:
8794 hlua_ctx_destroy(hlua);
Olivier Houchard3f795f72019-04-17 22:51:06 +02008795 task_destroy(task);
Tim Duesterhuscd235c62018-04-24 13:56:01 +02008796 task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008797 break;
8798
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01008799 case HLUA_E_AGAIN: /* co process or timeout wake me later. */
Thierry FOURNIERcb146882017-12-10 17:10:57 +01008800 notification_gc(&hlua->com);
PiBa-NLfe971b32018-05-02 22:27:14 +02008801 task->expire = hlua->wake_time;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008802 break;
8803
8804 /* finished with error. */
Aurelien DARRAGON79544102022-11-24 14:27:15 +01008805 case HLUA_E_ETMOUT:
8806 SEND_ERR(NULL, "Lua task: execution timeout.\n");
8807 goto err_task_abort;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008808 case HLUA_E_ERRMSG:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008809 SEND_ERR(NULL, "Lua task: %s.\n", lua_tostring(hlua->T, -1));
Aurelien DARRAGON79544102022-11-24 14:27:15 +01008810 goto err_task_abort;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008811 case HLUA_E_ERR:
8812 default:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008813 SEND_ERR(NULL, "Lua task: unknown error.\n");
Aurelien DARRAGON79544102022-11-24 14:27:15 +01008814 err_task_abort:
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008815 hlua_ctx_destroy(hlua);
Olivier Houchard3f795f72019-04-17 22:51:06 +02008816 task_destroy(task);
Emeric Brun253e53e2017-10-17 18:58:40 +02008817 task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008818 break;
8819 }
Emeric Brun253e53e2017-10-17 18:58:40 +02008820 return task;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008821}
8822
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008823/* This function is an LUA binding that register LUA function to be
8824 * executed after the HAProxy configuration parsing and before the
8825 * HAProxy scheduler starts. This function expect only one LUA
8826 * argument that is a function. This function returns nothing, but
8827 * throws if an error is encountered.
8828 */
8829__LJMP static int hlua_register_init(lua_State *L)
8830{
8831 struct hlua_init_function *init;
8832 int ref;
8833
8834 MAY_LJMP(check_args(L, 1, "register_init"));
8835
Aurelien DARRAGON87f52972023-02-24 09:43:54 +01008836 if (hlua_gethlua(L)) {
8837 /* runtime processing */
8838 WILL_LJMP(luaL_error(L, "register_init: not available outside of body context"));
8839 }
8840
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008841 ref = MAY_LJMP(hlua_checkfunction(L, 1));
8842
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02008843 init = calloc(1, sizeof(*init));
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +01008844 if (!init) {
8845 hlua_unref(L, ref);
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01008846 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +01008847 }
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008848
8849 init->function_ref = ref;
Willy Tarreau2b718102021-04-21 07:32:39 +02008850 LIST_APPEND(&hlua_init_functions[hlua_state_id], &init->l);
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008851 return 0;
8852}
8853
Ilya Shipitsin6f86eaa2022-11-30 16:22:42 +05008854/* This function is an LUA binding. It permits to register a task
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008855 * executed in parallel of the main HAroxy activity. The task is
8856 * created and it is set in the HAProxy scheduler. It can be called
8857 * from the "init" section, "post init" or during the runtime.
8858 *
8859 * Lua prototype:
8860 *
Aurelien DARRAGONb8038992023-03-09 16:48:30 +01008861 * <none> core.register_task(<function>[, <arg1>[, <arg2>[, ...[, <arg4>]]]])
8862 *
8863 * <arg1..4> are optional arguments that will be provided to <function>
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008864 */
8865static int hlua_register_task(lua_State *L)
8866{
Christopher Faulet5294ec02021-04-12 12:24:47 +02008867 struct hlua *hlua = NULL;
8868 struct task *task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008869 int ref;
Aurelien DARRAGONb8038992023-03-09 16:48:30 +01008870 int nb_arg;
8871 int it;
8872 int arg_ref[4]; /* optional arguments */
Thierry Fournier021d9862020-11-28 23:42:03 +01008873 int state_id;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008874
Aurelien DARRAGONb8038992023-03-09 16:48:30 +01008875 nb_arg = lua_gettop(L);
8876 if (nb_arg < 1)
8877 WILL_LJMP(luaL_error(L, "register_task: <func> argument is required"));
8878 else if (nb_arg > 5)
8879 WILL_LJMP(luaL_error(L, "register_task: no more that 4 optional arguments may be provided"));
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008880
Aurelien DARRAGONb8038992023-03-09 16:48:30 +01008881 /* first arg: function ref */
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008882 ref = MAY_LJMP(hlua_checkfunction(L, 1));
8883
Aurelien DARRAGONb8038992023-03-09 16:48:30 +01008884 /* extract optional args (if any) */
8885 it = 0;
8886 while (--nb_arg) {
8887 lua_pushvalue(L, 2 + it);
8888 arg_ref[it] = hlua_ref(L); /* get arg reference */
8889 it += 1;
8890 }
8891 nb_arg = it;
8892
Thierry Fournier75fc0292020-11-28 13:18:56 +01008893 /* Get the reference state. If the reference is NULL, L is the master
8894 * state, otherwise hlua->T is.
8895 */
8896 hlua = hlua_gethlua(L);
8897 if (hlua)
Thierry Fournier021d9862020-11-28 23:42:03 +01008898 /* we are in runtime processing */
8899 state_id = hlua->state_id;
Thierry Fournier75fc0292020-11-28 13:18:56 +01008900 else
Thierry Fournier021d9862020-11-28 23:42:03 +01008901 /* we are in initialization mode */
Thierry Fournierc7492592020-11-28 23:57:24 +01008902 state_id = hlua_state_id;
Thierry Fournier75fc0292020-11-28 13:18:56 +01008903
Willy Tarreaubafbe012017-11-24 17:34:44 +01008904 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008905 if (!hlua)
Christopher Faulet5294ec02021-04-12 12:24:47 +02008906 goto alloc_error;
Christopher Faulet1e8433f2021-03-24 15:03:01 +01008907 HLUA_INIT(hlua);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008908
Thierry Fournier59f11be2020-11-29 00:37:41 +01008909 /* We are in the common lua state, execute the task anywhere,
8910 * otherwise, inherit the current thread identifier
8911 */
8912 if (state_id == 0)
Willy Tarreaubeeabf52021-10-01 18:23:30 +02008913 task = task_new_anywhere();
Thierry Fournier59f11be2020-11-29 00:37:41 +01008914 else
Willy Tarreaubeeabf52021-10-01 18:23:30 +02008915 task = task_new_here();
Willy Tarreaue09101e2018-10-16 17:37:12 +02008916 if (!task)
Christopher Faulet5294ec02021-04-12 12:24:47 +02008917 goto alloc_error;
Willy Tarreaue09101e2018-10-16 17:37:12 +02008918
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008919 task->context = hlua;
8920 task->process = hlua_process_task;
8921
Aurelien DARRAGON6b0b9bd2023-03-21 14:02:16 +01008922 if (!hlua_ctx_init(hlua, state_id, task))
Christopher Faulet5294ec02021-04-12 12:24:47 +02008923 goto alloc_error;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008924
Aurelien DARRAGONb8038992023-03-09 16:48:30 +01008925 /* Ensure there is enough space on the stack for the function
8926 * plus optional arguments
8927 */
8928 if (!lua_checkstack(hlua->T, (1 + nb_arg)))
8929 goto alloc_error;
8930
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008931 /* Restore the function in the stack. */
Aurelien DARRAGON4fdf8b52023-03-20 17:22:37 +01008932 hlua_pushref(hlua->T, ref);
Aurelien DARRAGONbe58d662023-03-13 14:09:21 +01008933 /* function ref not needed anymore since it was pushed to the substack */
8934 hlua_unref(L, ref);
8935
Aurelien DARRAGONb8038992023-03-09 16:48:30 +01008936 hlua->nargs = nb_arg;
8937
8938 /* push optional arguments to the function */
8939 for (it = 0; it < nb_arg; it++) {
8940 /* push arg to the stack */
8941 hlua_pushref(hlua->T, arg_ref[it]);
8942 /* arg ref not needed anymore since it was pushed to the substack */
8943 hlua_unref(L, arg_ref[it]);
8944 }
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008945
8946 /* Schedule task. */
Willy Tarreaue3957f82021-09-30 16:17:37 +02008947 task_wakeup(task, TASK_WOKEN_INIT);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008948
8949 return 0;
Christopher Faulet5294ec02021-04-12 12:24:47 +02008950
8951 alloc_error:
8952 task_destroy(task);
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +01008953 hlua_unref(L, ref);
Aurelien DARRAGONb8038992023-03-09 16:48:30 +01008954 for (it = 0; it < nb_arg; it++) {
8955 hlua_unref(L, arg_ref[it]);
8956 }
Christopher Faulet5294ec02021-04-12 12:24:47 +02008957 hlua_ctx_destroy(hlua);
8958 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
8959 return 0; /* Never reached */
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008960}
8961
Aurelien DARRAGONc84899c2023-02-20 18:18:59 +01008962/* called from unsafe location */
8963static void hlua_event_subscription_destroy(struct hlua_event_sub *hlua_sub)
8964{
8965 /* hlua cleanup */
8966
8967 hlua_lock(hlua_sub->hlua);
8968 /* registry is shared between coroutines */
8969 hlua_unref(hlua_sub->hlua->T, hlua_sub->fcn_ref);
8970 hlua_unlock(hlua_sub->hlua);
8971
8972 hlua_ctx_destroy(hlua_sub->hlua);
8973
8974 /* free */
8975 pool_free(pool_head_hlua_event_sub, hlua_sub);
8976}
8977
8978/* single event handler: hlua ctx is shared between multiple events handlers
8979 * issued from the same subscription. Thus, it is not destroyed when the event
8980 * is processed: it is destroyed when no more events are expected for the
8981 * subscription (ie: when the subscription ends).
8982 *
8983 * Moreover, events are processed sequentially within the subscription:
8984 * one event must be fully processed before another one may be processed.
8985 * This ensures proper consistency for lua event handling from an ordering
8986 * point of view. This is especially useful with server events for example
8987 * where ADD/DEL/UP/DOWN events ordering really matters to trigger specific
8988 * actions from lua (e.g.: sending emails or making API calls).
8989 *
8990 * Due to this design, each lua event handler is pleased to process the event
8991 * as fast as possible to prevent the event queue from growing up.
8992 * Strictly speaking, there is no runtime limit for the callback function
8993 * (timeout set to default task timeout), but if the event queue goes past
8994 * the limit of unconsumed events an error will be reported and the
8995 * susbscription will pause itself for as long as it takes for the handler to
8996 * catch up (events will be lost as a result).
8997 * If the event handler does not need the sequential ordering and wants to
8998 * process multiple events at a time, it may spawn a new side-task using
8999 * 'core.register_task' to delegate the event handling and make parallel event
9000 * processing within the same subscription set.
9001 */
9002static void hlua_event_handler(struct hlua *hlua)
9003{
9004 enum hlua_exec status;
9005
9006 /* If it is the first call to the task, we must initialize the
9007 * execution timeouts.
9008 */
Aurelien DARRAGONda9503c2022-11-25 09:10:07 +01009009 if (!HLUA_IS_RUNNING(hlua))
9010 hlua_timer_init(&hlua->timer, hlua_timeout_task);
Aurelien DARRAGONc84899c2023-02-20 18:18:59 +01009011
9012 /* make sure to reset the task expiry before each hlua_ctx_resume()
9013 * since the task is re-used for multiple cb function calls
9014 * We couldn't risk to have t->expire pointing to a past date because
9015 * it was set during last function invocation but was never reset since
9016 * (ie: E_AGAIN)
9017 */
9018 hlua->task->expire = TICK_ETERNITY;
9019
9020 /* Execute the Lua code. */
9021 status = hlua_ctx_resume(hlua, 1);
9022
9023 switch (status) {
9024 /* finished or yield */
9025 case HLUA_E_OK:
9026 break;
9027
9028 case HLUA_E_AGAIN: /* co process or timeout wake me later. */
9029 notification_gc(&hlua->com);
9030 hlua->task->expire = hlua->wake_time;
9031 break;
9032
9033 /* finished with error. */
9034 case HLUA_E_ETMOUT:
9035 SEND_ERR(NULL, "Lua event_hdl: execution timeout.\n");
9036 break;
9037
9038 case HLUA_E_ERRMSG:
9039 SEND_ERR(NULL, "Lua event_hdl: %s.\n", lua_tostring(hlua->T, -1));
9040 break;
9041
9042 case HLUA_E_ERR:
9043 default:
9044 SEND_ERR(NULL, "Lua event_hdl: unknown error.\n");
9045 break;
9046 }
9047}
9048
Aurelien DARRAGONc99f3ad2023-04-12 15:47:16 +02009049__LJMP static void hlua_event_hdl_cb_push_event_checkres(lua_State *L,
9050 struct event_hdl_cb_data_server_checkres *check)
9051{
9052 lua_pushstring(L, "agent");
9053 lua_pushboolean(L, check->agent);
9054 lua_settable(L, -3);
9055 lua_pushstring(L, "result");
9056 switch (check->result) {
9057 case CHK_RES_FAILED:
9058 lua_pushstring(L, "FAILED");
9059 break;
9060 case CHK_RES_PASSED:
9061 lua_pushstring(L, "PASSED");
9062 break;
9063 case CHK_RES_CONDPASS:
9064 lua_pushstring(L, "CONDPASS");
9065 break;
9066 default:
9067 lua_pushnil(L);
9068 break;
9069 }
9070 lua_settable(L, -3);
9071
9072 lua_pushstring(L, "duration");
9073 lua_pushinteger(L, check->duration);
9074 lua_settable(L, -3);
9075
9076 lua_pushstring(L, "reason");
9077 lua_newtable(L);
9078
9079 lua_pushstring(L, "short");
9080 lua_pushstring(L, get_check_status_info(check->reason.status));
9081 lua_settable(L, -3);
9082 lua_pushstring(L, "desc");
9083 lua_pushstring(L, get_check_status_description(check->reason.status));
9084 lua_settable(L, -3);
9085 if (check->reason.status >= HCHK_STATUS_L57DATA) {
9086 /* code only available when the check reached data analysis stage */
9087 lua_pushstring(L, "code");
9088 lua_pushinteger(L, check->reason.code);
9089 lua_settable(L, -3);
9090 }
9091
9092 lua_settable(L, -3); /* reason table */
9093
9094 lua_pushstring(L, "health");
9095 lua_newtable(L);
9096
9097 lua_pushstring(L, "cur");
9098 lua_pushinteger(L, check->health.cur);
9099 lua_settable(L, -3);
9100 lua_pushstring(L, "rise");
9101 lua_pushinteger(L, check->health.rise);
9102 lua_settable(L, -3);
9103 lua_pushstring(L, "fall");
9104 lua_pushinteger(L, check->health.fall);
9105 lua_settable(L, -3);
9106
9107 lua_settable(L, -3); /* health table */
9108}
9109
Aurelien DARRAGON2f6a07d2023-03-27 18:16:21 +02009110/* This function pushes various arguments such as event type and event data to
9111 * the lua function that will be called to consume the event.
9112 */
9113__LJMP static void hlua_event_hdl_cb_push_args(struct hlua_event_sub *hlua_sub,
9114 struct event_hdl_async_event *e)
Aurelien DARRAGONc84899c2023-02-20 18:18:59 +01009115{
9116 struct hlua *hlua = hlua_sub->hlua;
Aurelien DARRAGON2f6a07d2023-03-27 18:16:21 +02009117 struct event_hdl_sub_type event = e->type;
9118 void *data = e->data;
Aurelien DARRAGONc84899c2023-02-20 18:18:59 +01009119
Aurelien DARRAGON2f6a07d2023-03-27 18:16:21 +02009120 /* push event type */
Aurelien DARRAGONc84899c2023-02-20 18:18:59 +01009121 hlua->nargs = 1;
9122 lua_pushstring(hlua->T, event_hdl_sub_type_to_string(event));
Aurelien DARRAGON2f6a07d2023-03-27 18:16:21 +02009123
9124 /* push event data (according to event type) */
Aurelien DARRAGONc84899c2023-02-20 18:18:59 +01009125 if (event_hdl_sub_family_equal(EVENT_HDL_SUB_SERVER, event)) {
9126 struct event_hdl_cb_data_server *e_server = data;
9127 struct proxy *px;
9128 struct server *server;
9129
9130 hlua->nargs += 1;
9131 lua_newtable(hlua->T);
9132 /* Add server name */
9133 lua_pushstring(hlua->T, "name");
9134 lua_pushstring(hlua->T, e_server->safe.name);
9135 lua_settable(hlua->T, -3);
9136 /* Add server puid */
9137 lua_pushstring(hlua->T, "puid");
9138 lua_pushinteger(hlua->T, e_server->safe.puid);
9139 lua_settable(hlua->T, -3);
9140 /* Add server rid */
9141 lua_pushstring(hlua->T, "rid");
9142 lua_pushinteger(hlua->T, e_server->safe.rid);
9143 lua_settable(hlua->T, -3);
9144 /* Add server proxy name */
9145 lua_pushstring(hlua->T, "proxy_name");
9146 lua_pushstring(hlua->T, e_server->safe.proxy_name);
9147 lua_settable(hlua->T, -3);
Aurelien DARRAGON55f84c72023-03-22 17:49:04 +01009148 /* Add server proxy uuid */
9149 lua_pushstring(hlua->T, "proxy_uuid");
9150 lua_pushinteger(hlua->T, e_server->safe.proxy_uuid);
9151 lua_settable(hlua->T, -3);
Aurelien DARRAGONc84899c2023-02-20 18:18:59 +01009152
Aurelien DARRAGONc99f3ad2023-04-12 15:47:16 +02009153 /* special events, fetch additional info with explicit type casting */
9154 if (event_hdl_sub_type_equal(EVENT_HDL_SUB_SERVER_STATE, event)) {
9155 struct event_hdl_cb_data_server_state *state = data;
9156 int it;
9157
9158 if (!lua_checkstack(hlua->T, 20))
9159 WILL_LJMP(luaL_error(hlua->T, "Lua out of memory error."));
9160
9161 /* state subclass */
9162 lua_pushstring(hlua->T, "state");
9163 lua_newtable(hlua->T);
9164
9165 lua_pushstring(hlua->T, "admin");
9166 lua_pushboolean(hlua->T, state->safe.type);
9167 lua_settable(hlua->T, -3);
9168
9169 /* is it because of a check ? */
9170 if (!state->safe.type &&
9171 (state->safe.op_st_chg.cause == SRV_OP_STCHGC_HEALTH ||
9172 state->safe.op_st_chg.cause == SRV_OP_STCHGC_AGENT)) {
9173 /* yes, provide check result */
9174 lua_pushstring(hlua->T, "check");
9175 lua_newtable(hlua->T);
9176 hlua_event_hdl_cb_push_event_checkres(hlua->T, &state->safe.op_st_chg.check);
9177 lua_settable(hlua->T, -3); /* check table */
9178 }
9179
9180 lua_pushstring(hlua->T, "cause");
9181 if (state->safe.type)
9182 lua_pushstring(hlua->T, srv_adm_st_chg_cause(state->safe.adm_st_chg.cause));
9183 else
9184 lua_pushstring(hlua->T, srv_op_st_chg_cause(state->safe.op_st_chg.cause));
9185 lua_settable(hlua->T, -3);
9186
9187 /* old_state, new_state */
9188 for (it = 0; it < 2; it++) {
9189 enum srv_state srv_state = (!it) ? state->safe.old_state : state->safe.new_state;
9190
9191 lua_pushstring(hlua->T, (!it) ? "old_state" : "new_state");
9192 switch (srv_state) {
9193 case SRV_ST_STOPPED:
9194 lua_pushstring(hlua->T, "STOPPED");
9195 break;
9196 case SRV_ST_STOPPING:
9197 lua_pushstring(hlua->T, "STOPPING");
9198 break;
9199 case SRV_ST_STARTING:
9200 lua_pushstring(hlua->T, "STARTING");
9201 break;
9202 case SRV_ST_RUNNING:
9203 lua_pushstring(hlua->T, "RUNNING");
9204 break;
9205 default:
9206 lua_pushnil(hlua->T);
9207 break;
9208 }
9209 lua_settable(hlua->T, -3);
9210 }
9211
9212 /* requeued */
9213 lua_pushstring(hlua->T, "requeued");
9214 lua_pushinteger(hlua->T, state->safe.requeued);
9215 lua_settable(hlua->T, -3);
9216
9217 lua_settable(hlua->T, -3); /* state table */
9218 }
Aurelien DARRAGON948dd3d2023-04-26 11:27:09 +02009219 else if (event_hdl_sub_type_equal(EVENT_HDL_SUB_SERVER_ADMIN, event)) {
9220 struct event_hdl_cb_data_server_admin *admin = data;
9221 int it;
9222
9223 if (!lua_checkstack(hlua->T, 20))
9224 WILL_LJMP(luaL_error(hlua->T, "Lua out of memory error."));
9225
9226 /* admin subclass */
9227 lua_pushstring(hlua->T, "admin");
9228 lua_newtable(hlua->T);
9229
9230 lua_pushstring(hlua->T, "cause");
9231 lua_pushstring(hlua->T, srv_adm_st_chg_cause(admin->safe.cause));
9232 lua_settable(hlua->T, -3);
9233
9234 /* old_admin, new_admin */
9235 for (it = 0; it < 2; it++) {
9236 enum srv_admin srv_admin = (!it) ? admin->safe.old_admin : admin->safe.new_admin;
9237
9238 lua_pushstring(hlua->T, (!it) ? "old_admin" : "new_admin");
9239
9240 /* admin state matrix */
9241 lua_newtable(hlua->T);
9242
9243 lua_pushstring(hlua->T, "MAINT");
9244 lua_pushboolean(hlua->T, srv_admin & SRV_ADMF_MAINT);
9245 lua_settable(hlua->T, -3);
9246 lua_pushstring(hlua->T, "FMAINT");
9247 lua_pushboolean(hlua->T, srv_admin & SRV_ADMF_FMAINT);
9248 lua_settable(hlua->T, -3);
9249 lua_pushstring(hlua->T, "IMAINT");
9250 lua_pushboolean(hlua->T, srv_admin & SRV_ADMF_IMAINT);
9251 lua_settable(hlua->T, -3);
9252 lua_pushstring(hlua->T, "RMAINT");
9253 lua_pushboolean(hlua->T, srv_admin & SRV_ADMF_RMAINT);
9254 lua_settable(hlua->T, -3);
9255 lua_pushstring(hlua->T, "CMAINT");
9256 lua_pushboolean(hlua->T, srv_admin & SRV_ADMF_CMAINT);
9257 lua_settable(hlua->T, -3);
9258
9259 lua_pushstring(hlua->T, "DRAIN");
9260 lua_pushboolean(hlua->T, srv_admin & SRV_ADMF_DRAIN);
9261 lua_settable(hlua->T, -3);
9262 lua_pushstring(hlua->T, "FDRAIN");
9263 lua_pushboolean(hlua->T, srv_admin & SRV_ADMF_FDRAIN);
9264 lua_settable(hlua->T, -3);
9265 lua_pushstring(hlua->T, "IDRAIN");
9266 lua_pushboolean(hlua->T, srv_admin & SRV_ADMF_IDRAIN);
9267 lua_settable(hlua->T, -3);
9268
9269 lua_settable(hlua->T, -3); /* matrix table */
9270 }
9271 /* requeued */
9272 lua_pushstring(hlua->T, "requeued");
9273 lua_pushinteger(hlua->T, admin->safe.requeued);
9274 lua_settable(hlua->T, -3);
9275
9276 lua_settable(hlua->T, -3); /* admin table */
9277 }
Aurelien DARRAGON0bd53b22023-03-30 15:53:33 +02009278 else if (event_hdl_sub_type_equal(EVENT_HDL_SUB_SERVER_CHECK, event)) {
9279 struct event_hdl_cb_data_server_check *check = data;
9280
9281 if (!lua_checkstack(hlua->T, 20))
9282 WILL_LJMP(luaL_error(hlua->T, "Lua out of memory error."));
9283
9284 /* check subclass */
9285 lua_pushstring(hlua->T, "check");
9286 lua_newtable(hlua->T);
9287
9288 /* check result snapshot */
9289 hlua_event_hdl_cb_push_event_checkres(hlua->T, &check->safe.res);
9290
9291 lua_settable(hlua->T, -3); /* check table */
9292 }
Aurelien DARRAGONc99f3ad2023-04-12 15:47:16 +02009293
Aurelien DARRAGONc84899c2023-02-20 18:18:59 +01009294 /* attempt to provide reference server object
9295 * (if it wasn't removed yet, SERVER_DEL will never succeed here)
9296 */
Aurelien DARRAGON3d9bf4e2023-03-22 17:46:12 +01009297 px = proxy_find_by_id(e_server->safe.proxy_uuid, PR_CAP_BE, 0);
Aurelien DARRAGONc84899c2023-02-20 18:18:59 +01009298 BUG_ON(!px);
9299 server = findserver_unique_id(px, e_server->safe.puid, e_server->safe.rid);
9300 if (server) {
9301 lua_pushstring(hlua->T, "reference");
9302 hlua_fcn_new_server(hlua->T, server);
9303 lua_settable(hlua->T, -3);
9304 }
9305 }
9306 /* sub mgmt */
9307 hlua->nargs += 1;
9308 hlua_fcn_new_event_sub(hlua->T, hlua_sub->sub);
Aurelien DARRAGON096b3832023-04-20 11:32:46 +02009309
9310 /* when? */
9311 hlua->nargs += 1;
9312 lua_pushinteger(hlua->T, e->when.tv_sec);
Aurelien DARRAGONc84899c2023-02-20 18:18:59 +01009313}
9314
9315/* events runner: if there's an ongoing hlua event handling process, finish it
9316 * then, check if there are new events waiting to be processed
9317 * (events are processed sequentially)
9318 *
9319 * We have a safety measure to warn/guard if the event queue is growing up
9320 * too much due to many events being generated and lua handler is unable to
9321 * keep up the pace (e.g.: when the event queue grows past 100 unconsumed events).
9322 * TODO: make it tunable
9323 */
9324static struct task *hlua_event_runner(struct task *task, void *context, unsigned int state)
9325{
9326 struct hlua_event_sub *hlua_sub = context;
9327 struct event_hdl_async_event *event;
9328 const char *error = NULL;
9329
9330 if (!hlua_sub->paused && event_hdl_async_equeue_size(&hlua_sub->equeue) > 100) {
9331 const char *trace;
9332
9333 /* We reached the limit of pending events in the queue: we should
9334 * warn the user, and temporarily pause the subscription to give a chance
Ilya Shipitsinccf80122023-04-22 20:20:39 +02009335 * to the handler to catch up? (it also prevents resource shortage since
Aurelien DARRAGONc84899c2023-02-20 18:18:59 +01009336 * the queue could grow indefinitely otherwise)
9337 * TODO: find a way to inform the handler that it missed some events
9338 * (example: stats within the subscription in event_hdl api exposed via lua api?)
9339 *
9340 * Nonetheless, reaching this limit means that the handler is not fast enough
9341 * and/or that it subscribed to events that happen too frequently and did not
9342 * expect it. This could come from an inadequate design in the user's script.
9343 */
9344 event_hdl_pause(hlua_sub->sub);
9345 hlua_sub->paused = 1;
9346
9347 /* The following Lua calls can fail. */
9348 if (!SET_SAFE_LJMP(hlua_sub->hlua))
9349 trace = NULL;
9350 trace = hlua_traceback(hlua_sub->hlua->T, ", ");
9351 /* At this point the execution is safe. */
9352 RESET_SAFE_LJMP(hlua_sub->hlua);
9353
9354 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 : ""));
9355 }
9356
9357 if (HLUA_IS_RUNNING(hlua_sub->hlua)) {
9358 /* ongoing hlua event handler, resume it */
9359 hlua_event_handler(hlua_sub->hlua);
9360 } else if ((event = event_hdl_async_equeue_pop(&hlua_sub->equeue))) { /* check for new events */
9361 if (event_hdl_sub_type_equal(event->type, EVENT_HDL_SUB_END)) {
9362 /* ending event: no more events to come */
9363 event_hdl_async_free_event(event);
9364 task_destroy(task);
9365 hlua_event_subscription_destroy(hlua_sub);
9366 return NULL;
9367 }
9368 /* new event: start processing it */
9369
9370 /* The following Lua calls can fail. */
9371 if (!SET_SAFE_LJMP(hlua_sub->hlua)) {
9372 if (lua_type(hlua_sub->hlua->T, -1) == LUA_TSTRING)
9373 error = lua_tostring(hlua_sub->hlua->T, -1);
9374 else
9375 error = "critical error";
9376 ha_alert("Lua event_hdl: %s.\n", error);
9377 goto skip_event;
9378 }
9379
9380 /* Check stack available size. */
9381 if (!lua_checkstack(hlua_sub->hlua->T, 5)) {
9382 ha_alert("Lua event_hdl: full stack.\n");
9383 RESET_SAFE_LJMP(hlua_sub->hlua);
9384 goto skip_event;
9385 }
9386
9387 /* Restore the function in the stack. */
9388 hlua_pushref(hlua_sub->hlua->T, hlua_sub->fcn_ref);
9389
9390 /* push args */
9391 hlua_sub->hlua->nargs = 0;
Aurelien DARRAGON2f6a07d2023-03-27 18:16:21 +02009392 MAY_LJMP(hlua_event_hdl_cb_push_args(hlua_sub, event));
Aurelien DARRAGONc84899c2023-02-20 18:18:59 +01009393
9394 /* At this point the execution is safe. */
9395 RESET_SAFE_LJMP(hlua_sub->hlua);
9396
9397 /* At this point the event was successfully translated into hlua ctx,
Ilya Shipitsinccf80122023-04-22 20:20:39 +02009398 * or hlua error occurred, so we can safely discard it
Aurelien DARRAGONc84899c2023-02-20 18:18:59 +01009399 */
9400 event_hdl_async_free_event(event);
9401 event = NULL;
9402
9403 hlua_event_handler(hlua_sub->hlua);
9404 skip_event:
9405 if (event)
9406 event_hdl_async_free_event(event);
9407
9408 }
9409
9410 if (!HLUA_IS_RUNNING(hlua_sub->hlua)) {
9411 /* we just finished the processing of one event..
9412 * check for new events before becoming idle
9413 */
9414 if (!event_hdl_async_equeue_isempty(&hlua_sub->equeue)) {
9415 /* more events to process, make sure the task
9416 * will be resumed ASAP to process pending events
9417 */
9418 task_wakeup(task, TASK_WOKEN_OTHER);
9419 }
9420 else if (hlua_sub->paused) {
Ilya Shipitsinccf80122023-04-22 20:20:39 +02009421 /* empty queue, the handler caught up: resume the subscription */
Aurelien DARRAGONc84899c2023-02-20 18:18:59 +01009422 event_hdl_resume(hlua_sub->sub);
9423 hlua_sub->paused = 0;
9424 }
9425 }
9426
9427 return task;
9428}
9429
9430/* Must be called directly under lua protected/safe environment
9431 * (not from external callback)
9432 * <fcn_ref> should NOT be dropped after the function successfully returns:
9433 * it will be done automatically in hlua_event_subscription_destroy() when the
9434 * subscription ends.
9435 *
9436 * Returns the new subscription on success and NULL on failure (memory error)
9437 */
9438static struct event_hdl_sub *hlua_event_subscribe(event_hdl_sub_list *list, struct event_hdl_sub_type e_type,
9439 int state_id, int fcn_ref)
9440{
9441 struct hlua_event_sub *hlua_sub;
9442 struct task *task = NULL;
9443
9444 hlua_sub = pool_alloc(pool_head_hlua_event_sub);
9445 if (!hlua_sub)
9446 goto mem_error;
9447 hlua_sub->task = NULL;
9448 hlua_sub->hlua = NULL;
9449 hlua_sub->paused = 0;
9450 if ((task = task_new_here()) == NULL) {
9451 ha_alert("out of memory while allocating hlua event task");
9452 goto mem_error;
9453 }
9454 task->process = hlua_event_runner;
9455 task->context = hlua_sub;
9456 event_hdl_async_equeue_init(&hlua_sub->equeue);
9457 hlua_sub->task = task;
9458 hlua_sub->fcn_ref = fcn_ref;
9459 hlua_sub->state_id = state_id;
9460 hlua_sub->hlua = pool_alloc(pool_head_hlua);
9461 if (!hlua_sub->hlua)
9462 goto mem_error;
9463 HLUA_INIT(hlua_sub->hlua);
9464 if (!hlua_ctx_init(hlua_sub->hlua, hlua_sub->state_id, task))
9465 goto mem_error;
9466
9467 hlua_sub->sub = event_hdl_subscribe_ptr(list, e_type,
9468 EVENT_HDL_ASYNC_TASK(&hlua_sub->equeue,
9469 task,
9470 hlua_sub,
9471 NULL));
9472 if (!hlua_sub->sub)
9473 goto mem_error;
9474
9475 return hlua_sub->sub; /* returns pointer to event_hdl_sub struct */
9476
9477 mem_error:
9478 if (hlua_sub) {
Tim Duesterhusfe83f582023-04-22 17:47:34 +02009479 task_destroy(hlua_sub->task);
Aurelien DARRAGONc84899c2023-02-20 18:18:59 +01009480 if (hlua_sub->hlua)
9481 hlua_ctx_destroy(hlua_sub->hlua);
9482 pool_free(pool_head_hlua_event_sub, hlua_sub);
9483 }
9484
9485 return NULL;
9486}
9487
9488/* looks for an array of strings referring to a composition of event_hdl subscription
9489 * types at <index> in <L> stack
9490 */
9491__LJMP static struct event_hdl_sub_type hlua_check_event_sub_types(lua_State *L, int index)
9492{
9493 struct event_hdl_sub_type subscriptions;
9494 const char *msg;
9495
9496 if (lua_type(L, index) != LUA_TTABLE) {
9497 msg = lua_pushfstring(L, "table of strings expected, got %s", luaL_typename(L, index));
9498 luaL_argerror(L, index, msg);
9499 }
9500
9501 subscriptions = EVENT_HDL_SUB_NONE;
9502
9503 /* browse the argument as an array. */
9504 lua_pushnil(L);
9505 while (lua_next(L, index) != 0) {
9506 if (lua_type(L, -1) != LUA_TSTRING) {
9507 msg = lua_pushfstring(L, "table of strings expected, got %s", luaL_typename(L, index));
9508 luaL_argerror(L, index, msg);
9509 }
9510
9511 if (event_hdl_sub_type_equal(EVENT_HDL_SUB_NONE, event_hdl_string_to_sub_type(lua_tostring(L, -1)))) {
9512 msg = lua_pushfstring(L, "'%s' event type is unknown", lua_tostring(L, -1));
9513 luaL_argerror(L, index, msg);
9514 }
9515
9516 /* perform subscriptions |= current sub */
9517 subscriptions = event_hdl_sub_type_add(subscriptions, event_hdl_string_to_sub_type(lua_tostring(L, -1)));
9518
9519 /* pop the current value. */
9520 lua_pop(L, 1);
9521 }
9522
9523 return subscriptions;
9524}
9525
9526/* Wrapper for hlua_fcn_new_event_sub(): catch errors raised by
9527 * the function to prevent LJMP
9528 *
Ilya Shipitsinccf80122023-04-22 20:20:39 +02009529 * If no error occurred, the function returns 1, else it returns 0 and
Aurelien DARRAGONc84899c2023-02-20 18:18:59 +01009530 * the error message is pushed at the top of the stack
9531 */
9532__LJMP static int _hlua_new_event_sub_safe(lua_State *L)
9533{
9534 struct event_hdl_sub *sub = lua_touserdata(L, 1);
9535
9536 /* this function may raise errors */
9537 return MAY_LJMP(hlua_fcn_new_event_sub(L, sub));
9538}
9539static int hlua_new_event_sub_safe(lua_State *L, struct event_hdl_sub *sub)
9540{
9541 if (!lua_checkstack(L, 2))
9542 return 0;
9543 lua_pushcfunction(L, _hlua_new_event_sub_safe);
9544 lua_pushlightuserdata(L, sub);
9545 switch (lua_pcall(L, 1, 1, 0)) {
9546 case LUA_OK:
9547 return 1;
9548 default:
Ilya Shipitsinccf80122023-04-22 20:20:39 +02009549 /* error was caught */
Aurelien DARRAGONc84899c2023-02-20 18:18:59 +01009550 return 0;
9551 }
9552}
9553
9554/* This function is a LUA helper used for registering lua event callbacks.
9555 * It expects an event subscription array and the function to be executed
9556 * when subscribed events occur (stack arguments).
9557 * It can be called from the "init" section, "post init" or during the runtime.
9558 *
9559 * <sub_list> is the subscription list where the subscription will be attempted
9560 *
9561 * Pushes the newly allocated subscription on the stack on success
9562 */
9563__LJMP int hlua_event_sub(lua_State *L, event_hdl_sub_list *sub_list)
9564{
9565 struct hlua *hlua;
9566 struct event_hdl_sub *sub;
9567 struct event_hdl_sub_type subscriptions;
9568 int fcn_ref;
9569 int state_id;
9570
9571 MAY_LJMP(check_args(L, 2, "event_sub"));
9572
9573 /* Get the reference state */
9574 hlua = hlua_gethlua(L);
9575 if (hlua)
9576 /* we are in runtime processing, any thread may subscribe to events:
9577 * subscription events will be handled by the thread who performed
9578 * the registration.
9579 */
9580 state_id = hlua->state_id;
9581 else {
9582 /* we are in initialization mode, only thread 0 (actual calling thread)
9583 * may subscribe to events to prevent the same handler (from different lua
9584 * stacks) from being registered multiple times
9585 *
9586 * hlua_state_id == 0: monostack (lua-load)
9587 * hlua_state_id > 0: hlua_state_id=tid+1, multi-stack (lua-load-per-thread)
9588 * (thus if hlua_state_id > 1, it means we are not in primary thread ctx)
9589 */
9590 if (hlua_state_id > 1)
9591 return 0; /* skip registration */
9592 state_id = hlua_state_id;
9593 }
9594
9595 /* First argument : event subscriptions. */
9596 subscriptions = MAY_LJMP(hlua_check_event_sub_types(L, 1));
9597
9598 if (event_hdl_sub_type_equal(subscriptions, EVENT_HDL_SUB_NONE)) {
9599 WILL_LJMP(luaL_error(L, "event_sub: no valid event types were provided"));
9600 return 0; /* Never reached */
9601 }
9602
9603 /* Second argument : lua function. */
9604 fcn_ref = MAY_LJMP(hlua_checkfunction(L, 2));
9605
9606 /* try to subscribe */
9607 sub = hlua_event_subscribe(sub_list, subscriptions, state_id, fcn_ref);
9608 if (!sub) {
9609 hlua_unref(L, fcn_ref);
9610 WILL_LJMP(luaL_error(L, "event_sub: lua out of memory error"));
9611 return 0; /* Never reached */
9612 }
9613
9614 /* push the subscription to the stack
9615 *
9616 * Here we use the safe function so that lua errors will be
9617 * handled explicitly to prevent 'sub' from being lost
9618 */
9619 if (!hlua_new_event_sub_safe(L, sub)) {
9620 /* Some events could already be pending in the handler's queue.
9621 * However it is wiser to cancel the subscription since we are unable to
9622 * provide a valid reference to it.
9623 * Pending events will be delivered (unless lua keeps raising errors).
9624 */
9625 event_hdl_unsubscribe(sub); /* cancel the subscription */
9626 WILL_LJMP(luaL_error(L, "event_sub: cannot push the subscription (%s)", lua_tostring(L, -1)));
9627 return 0; /* Never reached */
9628 }
9629 event_hdl_drop(sub); /* sub has been duplicated, discard old ref */
9630
9631 return 1;
9632}
9633
9634/* This function is a LUA wrapper used for registering global lua event callbacks
9635 * The new subscription is pushed onto the stack on success
9636 * Returns the number of arguments pushed to the stack (1 for success)
9637 */
9638__LJMP static int hlua_event_global_sub(lua_State *L)
9639{
9640 /* NULL <sub_list> = global subscription list */
9641 return MAY_LJMP(hlua_event_sub(L, NULL));
9642}
9643
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009644/* Wrapper called by HAProxy to execute an LUA converter. This wrapper
9645 * doesn't allow "yield" functions because the HAProxy engine cannot
9646 * resume converters.
9647 */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02009648static int hlua_sample_conv_wrapper(const struct arg *arg_p, struct sample *smp, void *private)
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009649{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02009650 struct hlua_function *fcn = private;
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02009651 struct stream *stream = smp->strm;
Thierry Fournierfd107a22016-02-19 19:57:23 +01009652 const char *error;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009653
Willy Tarreaube508f12016-03-10 11:47:01 +01009654 if (!stream)
9655 return 0;
9656
Willy Tarreau87b09662015-04-03 00:22:06 +02009657 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01009658 * Lua context can be not initialized. This behavior
9659 * permits to save performances because a systematic
9660 * Lua initialization cause 5% performances loss.
9661 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009662 if (!stream->hlua) {
Christopher Faulet1e8433f2021-03-24 15:03:01 +01009663 struct hlua *hlua;
9664
9665 hlua = pool_alloc(pool_head_hlua);
9666 if (!hlua) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009667 SEND_ERR(stream->be, "Lua converter '%s': can't initialize Lua context.\n", fcn->name);
9668 return 0;
9669 }
Christopher Faulet1e8433f2021-03-24 15:03:01 +01009670 HLUA_INIT(hlua);
9671 stream->hlua = hlua;
Aurelien DARRAGON6b0b9bd2023-03-21 14:02:16 +01009672 if (!hlua_ctx_init(stream->hlua, fcn_ref_to_stack_id(fcn), stream->task)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009673 SEND_ERR(stream->be, "Lua converter '%s': can't initialize Lua context.\n", fcn->name);
9674 return 0;
9675 }
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01009676 }
9677
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009678 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009679 if (!HLUA_IS_RUNNING(stream->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02009680
9681 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009682 if (!SET_SAFE_LJMP(stream->hlua)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009683 if (lua_type(stream->hlua->T, -1) == LUA_TSTRING)
9684 error = lua_tostring(stream->hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +01009685 else
9686 error = "critical error";
9687 SEND_ERR(stream->be, "Lua converter '%s': %s.\n", fcn->name, error);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02009688 return 0;
9689 }
9690
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009691 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009692 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009693 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009694 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009695 return 0;
9696 }
9697
9698 /* Restore the function in the stack. */
Aurelien DARRAGON4fdf8b52023-03-20 17:22:37 +01009699 hlua_pushref(stream->hlua->T, fcn->function_ref[stream->hlua->state_id]);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009700
9701 /* convert input sample and pust-it in the stack. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009702 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009703 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009704 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009705 return 0;
9706 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009707 hlua_smp2lua(stream->hlua->T, smp);
9708 stream->hlua->nargs = 1;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009709
9710 /* push keywords in the stack. */
9711 if (arg_p) {
9712 for (; arg_p->type != ARGT_STOP; arg_p++) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009713 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009714 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009715 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009716 return 0;
9717 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009718 hlua_arg2lua(stream->hlua->T, arg_p);
9719 stream->hlua->nargs++;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009720 }
9721 }
9722
Thierry FOURNIERbd413492015-03-03 16:52:26 +01009723 /* We must initialize the execution timeouts. */
Aurelien DARRAGONda9503c2022-11-25 09:10:07 +01009724 hlua_timer_init(&stream->hlua->timer, hlua_timeout_session);
Thierry FOURNIERbd413492015-03-03 16:52:26 +01009725
Thierry FOURNIERbabae282015-09-17 11:36:37 +02009726 /* At this point the execution is safe. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009727 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009728 }
9729
9730 /* Execute the function. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009731 switch (hlua_ctx_resume(stream->hlua, 0)) {
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009732 /* finished. */
9733 case HLUA_E_OK:
Thierry FOURNIERfd80df12017-05-12 16:32:20 +02009734 /* If the stack is empty, the function fails. */
9735 if (lua_gettop(stream->hlua->T) <= 0)
9736 return 0;
9737
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009738 /* Convert the returned value in sample. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009739 hlua_lua2smp(stream->hlua->T, -1, smp);
9740 lua_pop(stream->hlua->T, 1);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009741 return 1;
9742
9743 /* yield. */
9744 case HLUA_E_AGAIN:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009745 SEND_ERR(stream->be, "Lua converter '%s': cannot use yielded functions.\n", fcn->name);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009746 return 0;
9747
9748 /* finished with error. */
9749 case HLUA_E_ERRMSG:
9750 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009751 SEND_ERR(stream->be, "Lua converter '%s': %s.\n",
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009752 fcn->name, lua_tostring(stream->hlua->T, -1));
9753 lua_pop(stream->hlua->T, 1);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009754 return 0;
9755
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009756 case HLUA_E_ETMOUT:
9757 SEND_ERR(stream->be, "Lua converter '%s': execution timeout.\n", fcn->name);
9758 return 0;
9759
9760 case HLUA_E_NOMEM:
9761 SEND_ERR(stream->be, "Lua converter '%s': out of memory error.\n", fcn->name);
9762 return 0;
9763
9764 case HLUA_E_YIELD:
9765 SEND_ERR(stream->be, "Lua converter '%s': yield functions like core.tcp() or core.sleep() are not allowed.\n", fcn->name);
9766 return 0;
9767
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009768 case HLUA_E_ERR:
9769 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009770 SEND_ERR(stream->be, "Lua converter '%s' returns an unknown error.\n", fcn->name);
Willy Tarreau14de3952022-11-14 07:08:28 +01009771 __fallthrough;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009772
9773 default:
9774 return 0;
9775 }
9776}
9777
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009778/* Wrapper called by HAProxy to execute a sample-fetch. this wrapper
9779 * doesn't allow "yield" functions because the HAProxy engine cannot
Willy Tarreaube508f12016-03-10 11:47:01 +01009780 * resume sample-fetches. This function will be called by the sample
9781 * fetch engine to call lua-based fetch operations.
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009782 */
Thierry FOURNIER0786d052015-05-11 15:42:45 +02009783static int hlua_sample_fetch_wrapper(const struct arg *arg_p, struct sample *smp,
9784 const char *kw, void *private)
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009785{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02009786 struct hlua_function *fcn = private;
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02009787 struct stream *stream = smp->strm;
Thierry Fournierfd107a22016-02-19 19:57:23 +01009788 const char *error;
Christopher Faulet8c9e6bb2021-08-06 16:29:41 +02009789 unsigned int hflags = HLUA_TXN_NOTERM | HLUA_TXN_SMP_CTX;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009790
Willy Tarreaube508f12016-03-10 11:47:01 +01009791 if (!stream)
9792 return 0;
Christopher Fauletafd8f102018-11-08 11:34:21 +01009793
Willy Tarreau87b09662015-04-03 00:22:06 +02009794 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01009795 * Lua context can be not initialized. This behavior
9796 * permits to save performances because a systematic
9797 * Lua initialization cause 5% performances loss.
9798 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009799 if (!stream->hlua) {
Christopher Faulet1e8433f2021-03-24 15:03:01 +01009800 struct hlua *hlua;
9801
9802 hlua = pool_alloc(pool_head_hlua);
9803 if (!hlua) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009804 SEND_ERR(stream->be, "Lua sample-fetch '%s': can't initialize Lua context.\n", fcn->name);
9805 return 0;
9806 }
Christopher Faulet1e8433f2021-03-24 15:03:01 +01009807 hlua->T = NULL;
9808 stream->hlua = hlua;
Aurelien DARRAGON6b0b9bd2023-03-21 14:02:16 +01009809 if (!hlua_ctx_init(stream->hlua, fcn_ref_to_stack_id(fcn), stream->task)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009810 SEND_ERR(stream->be, "Lua sample-fetch '%s': can't initialize Lua context.\n", fcn->name);
9811 return 0;
9812 }
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01009813 }
9814
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009815 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009816 if (!HLUA_IS_RUNNING(stream->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02009817
9818 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009819 if (!SET_SAFE_LJMP(stream->hlua)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009820 if (lua_type(stream->hlua->T, -1) == LUA_TSTRING)
9821 error = lua_tostring(stream->hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +01009822 else
9823 error = "critical error";
9824 SEND_ERR(smp->px, "Lua sample-fetch '%s': %s.\n", fcn->name, error);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02009825 return 0;
9826 }
9827
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009828 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009829 if (!lua_checkstack(stream->hlua->T, 2)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009830 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009831 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009832 return 0;
9833 }
9834
9835 /* Restore the function in the stack. */
Aurelien DARRAGON4fdf8b52023-03-20 17:22:37 +01009836 hlua_pushref(stream->hlua->T, fcn->function_ref[stream->hlua->state_id]);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009837
9838 /* push arguments in the stack. */
Christopher Fauletbfab2dd2019-07-26 15:09:53 +02009839 if (!hlua_txn_new(stream->hlua->T, stream, smp->px, smp->opt & SMP_OPT_DIR, hflags)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009840 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009841 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009842 return 0;
9843 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009844 stream->hlua->nargs = 1;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009845
9846 /* push keywords in the stack. */
9847 for (; arg_p && arg_p->type != ARGT_STOP; arg_p++) {
9848 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009849 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009850 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009851 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009852 return 0;
9853 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009854 hlua_arg2lua(stream->hlua->T, arg_p);
9855 stream->hlua->nargs++;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009856 }
9857
Thierry FOURNIERbd413492015-03-03 16:52:26 +01009858 /* We must initialize the execution timeouts. */
Aurelien DARRAGONda9503c2022-11-25 09:10:07 +01009859 hlua_timer_init(&stream->hlua->timer, hlua_timeout_session);
Thierry FOURNIERbd413492015-03-03 16:52:26 +01009860
Thierry FOURNIERbabae282015-09-17 11:36:37 +02009861 /* At this point the execution is safe. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009862 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009863 }
9864
9865 /* Execute the function. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009866 switch (hlua_ctx_resume(stream->hlua, 0)) {
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009867 /* finished. */
9868 case HLUA_E_OK:
Thierry FOURNIERfd80df12017-05-12 16:32:20 +02009869 /* If the stack is empty, the function fails. */
9870 if (lua_gettop(stream->hlua->T) <= 0)
9871 return 0;
9872
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009873 /* Convert the returned value in sample. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009874 hlua_lua2smp(stream->hlua->T, -1, smp);
9875 lua_pop(stream->hlua->T, 1);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009876
9877 /* Set the end of execution flag. */
9878 smp->flags &= ~SMP_F_MAY_CHANGE;
9879 return 1;
9880
9881 /* yield. */
9882 case HLUA_E_AGAIN:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009883 SEND_ERR(smp->px, "Lua sample-fetch '%s': cannot use yielded functions.\n", fcn->name);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009884 return 0;
9885
9886 /* finished with error. */
9887 case HLUA_E_ERRMSG:
9888 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009889 SEND_ERR(smp->px, "Lua sample-fetch '%s': %s.\n",
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009890 fcn->name, lua_tostring(stream->hlua->T, -1));
9891 lua_pop(stream->hlua->T, 1);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009892 return 0;
9893
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009894 case HLUA_E_ETMOUT:
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009895 SEND_ERR(smp->px, "Lua sample-fetch '%s': execution timeout.\n", fcn->name);
9896 return 0;
9897
9898 case HLUA_E_NOMEM:
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009899 SEND_ERR(smp->px, "Lua sample-fetch '%s': out of memory error.\n", fcn->name);
9900 return 0;
9901
9902 case HLUA_E_YIELD:
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009903 SEND_ERR(smp->px, "Lua sample-fetch '%s': yield not allowed.\n", fcn->name);
9904 return 0;
9905
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009906 case HLUA_E_ERR:
9907 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009908 SEND_ERR(smp->px, "Lua sample-fetch '%s' returns an unknown error.\n", fcn->name);
Willy Tarreau14de3952022-11-14 07:08:28 +01009909 __fallthrough;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009910
9911 default:
9912 return 0;
9913 }
9914}
9915
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009916/* This function is an LUA binding used for registering
9917 * "sample-conv" functions. It expects a converter name used
9918 * in the haproxy configuration file, and an LUA function.
9919 */
9920__LJMP static int hlua_register_converters(lua_State *L)
9921{
9922 struct sample_conv_kw_list *sck;
9923 const char *name;
9924 int ref;
9925 int len;
Christopher Fauletaa224302021-04-12 14:08:21 +02009926 struct hlua_function *fcn = NULL;
Thierry Fournierf67442e2020-11-28 20:41:07 +01009927 struct sample_conv *sc;
9928 struct buffer *trash;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009929
9930 MAY_LJMP(check_args(L, 2, "register_converters"));
9931
Aurelien DARRAGON87f52972023-02-24 09:43:54 +01009932 if (hlua_gethlua(L)) {
9933 /* runtime processing */
9934 WILL_LJMP(luaL_error(L, "register_converters: not available outside of body context"));
9935 }
9936
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009937 /* First argument : converter name. */
9938 name = MAY_LJMP(luaL_checkstring(L, 1));
9939
9940 /* Second argument : lua function. */
9941 ref = MAY_LJMP(hlua_checkfunction(L, 2));
9942
Thierry Fournierf67442e2020-11-28 20:41:07 +01009943 /* Check if the converter is already registered */
9944 trash = get_trash_chunk();
9945 chunk_printf(trash, "lua.%s", name);
9946 sc = find_sample_conv(trash->area, trash->data);
9947 if (sc != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +01009948 fcn = sc->private;
9949 if (fcn->function_ref[hlua_state_id] != -1) {
9950 ha_warning("Trying to register converter 'lua.%s' more than once. "
9951 "This will become a hard error in version 2.5.\n", name);
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +01009952 hlua_unref(L, fcn->function_ref[hlua_state_id]);
Thierry Fournier59f11be2020-11-29 00:37:41 +01009953 }
9954 fcn->function_ref[hlua_state_id] = ref;
9955 return 0;
Thierry Fournierf67442e2020-11-28 20:41:07 +01009956 }
9957
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009958 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02009959 sck = calloc(1, sizeof(*sck) + sizeof(struct sample_conv) * 2);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009960 if (!sck)
Christopher Fauletaa224302021-04-12 14:08:21 +02009961 goto alloc_error;
Thierry Fournier62a22aa2020-11-28 21:06:35 +01009962 fcn = new_hlua_function();
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009963 if (!fcn)
Christopher Fauletaa224302021-04-12 14:08:21 +02009964 goto alloc_error;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009965
9966 /* Fill fcn. */
9967 fcn->name = strdup(name);
9968 if (!fcn->name)
Christopher Fauletaa224302021-04-12 14:08:21 +02009969 goto alloc_error;
Thierry Fournierc7492592020-11-28 23:57:24 +01009970 fcn->function_ref[hlua_state_id] = ref;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009971
9972 /* List head */
9973 sck->list.n = sck->list.p = NULL;
9974
9975 /* converter keyword. */
9976 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02009977 sck->kw[0].kw = calloc(1, len);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009978 if (!sck->kw[0].kw)
Christopher Fauletaa224302021-04-12 14:08:21 +02009979 goto alloc_error;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009980
9981 snprintf((char *)sck->kw[0].kw, len, "lua.%s", name);
9982 sck->kw[0].process = hlua_sample_conv_wrapper;
David Carlier0c437f42016-04-27 16:21:56 +01009983 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 +01009984 sck->kw[0].val_args = NULL;
9985 sck->kw[0].in_type = SMP_T_STR;
9986 sck->kw[0].out_type = SMP_T_STR;
9987 sck->kw[0].private = fcn;
9988
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009989 /* Register this new converter */
9990 sample_register_convs(sck);
9991
9992 return 0;
Christopher Fauletaa224302021-04-12 14:08:21 +02009993
9994 alloc_error:
9995 release_hlua_function(fcn);
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +01009996 hlua_unref(L, ref);
Christopher Fauletaa224302021-04-12 14:08:21 +02009997 ha_free(&sck);
9998 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
9999 return 0; /* Never reached */
Thierry FOURNIER9be813f2015-02-16 20:21:12 +010010000}
10001
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -080010002/* This function is an LUA binding used for registering
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +010010003 * "sample-fetch" functions. It expects a converter name used
10004 * in the haproxy configuration file, and an LUA function.
10005 */
10006__LJMP static int hlua_register_fetches(lua_State *L)
10007{
10008 const char *name;
10009 int ref;
10010 int len;
10011 struct sample_fetch_kw_list *sfk;
Christopher Faulet2567f182021-04-12 14:11:50 +020010012 struct hlua_function *fcn = NULL;
Thierry Fournierf67442e2020-11-28 20:41:07 +010010013 struct sample_fetch *sf;
10014 struct buffer *trash;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +010010015
10016 MAY_LJMP(check_args(L, 2, "register_fetches"));
10017
Aurelien DARRAGON87f52972023-02-24 09:43:54 +010010018 if (hlua_gethlua(L)) {
10019 /* runtime processing */
10020 WILL_LJMP(luaL_error(L, "register_fetches: not available outside of body context"));
10021 }
10022
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +010010023 /* First argument : sample-fetch name. */
10024 name = MAY_LJMP(luaL_checkstring(L, 1));
10025
10026 /* Second argument : lua function. */
10027 ref = MAY_LJMP(hlua_checkfunction(L, 2));
10028
Thierry Fournierf67442e2020-11-28 20:41:07 +010010029 /* Check if the sample-fetch is already registered */
10030 trash = get_trash_chunk();
10031 chunk_printf(trash, "lua.%s", name);
10032 sf = find_sample_fetch(trash->area, trash->data);
10033 if (sf != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +010010034 fcn = sf->private;
10035 if (fcn->function_ref[hlua_state_id] != -1) {
10036 ha_warning("Trying to register sample-fetch 'lua.%s' more than once. "
10037 "This will become a hard error in version 2.5.\n", name);
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +010010038 hlua_unref(L, fcn->function_ref[hlua_state_id]);
Thierry Fournier59f11be2020-11-29 00:37:41 +010010039 }
10040 fcn->function_ref[hlua_state_id] = ref;
10041 return 0;
Thierry Fournierf67442e2020-11-28 20:41:07 +010010042 }
10043
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +010010044 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +020010045 sfk = calloc(1, sizeof(*sfk) + sizeof(struct sample_fetch) * 2);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +010010046 if (!sfk)
Christopher Faulet2567f182021-04-12 14:11:50 +020010047 goto alloc_error;
Thierry Fournier62a22aa2020-11-28 21:06:35 +010010048 fcn = new_hlua_function();
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +010010049 if (!fcn)
Christopher Faulet2567f182021-04-12 14:11:50 +020010050 goto alloc_error;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +010010051
10052 /* Fill fcn. */
10053 fcn->name = strdup(name);
10054 if (!fcn->name)
Christopher Faulet2567f182021-04-12 14:11:50 +020010055 goto alloc_error;
Thierry Fournierc7492592020-11-28 23:57:24 +010010056 fcn->function_ref[hlua_state_id] = ref;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +010010057
10058 /* List head */
10059 sfk->list.n = sfk->list.p = NULL;
10060
10061 /* sample-fetch keyword. */
10062 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +020010063 sfk->kw[0].kw = calloc(1, len);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +010010064 if (!sfk->kw[0].kw)
Christopher Faulet2567f182021-04-12 14:11:50 +020010065 goto alloc_error;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +010010066
10067 snprintf((char *)sfk->kw[0].kw, len, "lua.%s", name);
10068 sfk->kw[0].process = hlua_sample_fetch_wrapper;
David Carlier0c437f42016-04-27 16:21:56 +010010069 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 +010010070 sfk->kw[0].val_args = NULL;
10071 sfk->kw[0].out_type = SMP_T_STR;
10072 sfk->kw[0].use = SMP_USE_HTTP_ANY;
10073 sfk->kw[0].val = 0;
10074 sfk->kw[0].private = fcn;
10075
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +010010076 /* Register this new fetch. */
10077 sample_register_fetches(sfk);
10078
10079 return 0;
Christopher Faulet2567f182021-04-12 14:11:50 +020010080
10081 alloc_error:
10082 release_hlua_function(fcn);
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +010010083 hlua_unref(L, ref);
Christopher Faulet2567f182021-04-12 14:11:50 +020010084 ha_free(&sfk);
10085 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
10086 return 0; /* Never reached */
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +010010087}
10088
Christopher Faulet501465d2020-02-26 14:54:16 +010010089/* This function is a lua binding to set the wake_time.
Christopher Faulet2c2c2e32020-01-31 19:07:52 +010010090 */
Christopher Faulet501465d2020-02-26 14:54:16 +010010091__LJMP static int hlua_set_wake_time(lua_State *L)
Christopher Faulet2c2c2e32020-01-31 19:07:52 +010010092{
Thierry Fournier4234dbd2020-11-28 13:18:23 +010010093 struct hlua *hlua;
Christopher Faulet2c2c2e32020-01-31 19:07:52 +010010094 unsigned int delay;
Aurelien DARRAGON2a9764b2023-04-04 18:41:04 +020010095 int wakeup_ms; // tick value
Christopher Faulet2c2c2e32020-01-31 19:07:52 +010010096
Thierry Fournier4234dbd2020-11-28 13:18:23 +010010097 /* Get hlua struct, or NULL if we execute from main lua state */
10098 hlua = hlua_gethlua(L);
10099 if (!hlua) {
10100 return 0;
10101 }
10102
Christopher Faulet2c2c2e32020-01-31 19:07:52 +010010103 MAY_LJMP(check_args(L, 1, "wake_time"));
10104
10105 delay = MAY_LJMP(luaL_checkinteger(L, 1));
10106 wakeup_ms = tick_add(now_ms, delay);
10107 hlua->wake_time = wakeup_ms;
10108 return 0;
10109}
10110
Christopher Faulet7716cdf2020-01-29 11:53:30 +010010111/* This function is a wrapper to execute each LUA function declared as an action
10112 * wrapper during the initialisation period. This function may return any
10113 * ACT_RET_* value. On error ACT_RET_CONT is returned and the action is
10114 * ignored. If the lua action yields, ACT_RET_YIELD is returned. On success, the
10115 * return value is the first element on the stack.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +010010116 */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +020010117static enum act_return hlua_action(struct act_rule *rule, struct proxy *px,
Willy Tarreau658b85b2015-09-27 10:00:49 +020010118 struct session *sess, struct stream *s, int flags)
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +010010119{
10120 char **arg;
Christopher Faulet8c9e6bb2021-08-06 16:29:41 +020010121 unsigned int hflags = HLUA_TXN_ACT_CTX;
Christopher Faulet7716cdf2020-01-29 11:53:30 +010010122 int dir, act_ret = ACT_RET_CONT;
Thierry Fournierfd107a22016-02-19 19:57:23 +010010123 const char *error;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +020010124
10125 switch (rule->from) {
Christopher Fauletd8f0e072020-02-25 09:45:51 +010010126 case ACT_F_TCP_REQ_CNT: dir = SMP_OPT_DIR_REQ; break;
10127 case ACT_F_TCP_RES_CNT: dir = SMP_OPT_DIR_RES; break;
10128 case ACT_F_HTTP_REQ: dir = SMP_OPT_DIR_REQ; break;
10129 case ACT_F_HTTP_RES: dir = SMP_OPT_DIR_RES; break;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +020010130 default:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +020010131 SEND_ERR(px, "Lua: internal error while execute action.\n");
Christopher Faulet7716cdf2020-01-29 11:53:30 +010010132 goto end;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +020010133 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +010010134
Willy Tarreau87b09662015-04-03 00:22:06 +020010135 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +010010136 * Lua context can be not initialized. This behavior
10137 * permits to save performances because a systematic
10138 * Lua initialization cause 5% performances loss.
10139 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +010010140 if (!s->hlua) {
Christopher Faulet1e8433f2021-03-24 15:03:01 +010010141 struct hlua *hlua;
10142
10143 hlua = pool_alloc(pool_head_hlua);
10144 if (!hlua) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +010010145 SEND_ERR(px, "Lua action '%s': can't initialize Lua context.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010146 rule->arg.hlua_rule->fcn->name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +010010147 goto end;
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +010010148 }
Christopher Faulet1e8433f2021-03-24 15:03:01 +010010149 HLUA_INIT(hlua);
10150 s->hlua = hlua;
Aurelien DARRAGON6b0b9bd2023-03-21 14:02:16 +010010151 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 +010010152 SEND_ERR(px, "Lua action '%s': can't initialize Lua context.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010153 rule->arg.hlua_rule->fcn->name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +010010154 goto end;
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +010010155 }
Thierry FOURNIER05ac4242015-02-27 18:37:27 +010010156 }
10157
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +010010158 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +010010159 if (!HLUA_IS_RUNNING(s->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +020010160
10161 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010162 if (!SET_SAFE_LJMP(s->hlua)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +010010163 if (lua_type(s->hlua->T, -1) == LUA_TSTRING)
10164 error = lua_tostring(s->hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +010010165 else
10166 error = "critical error";
10167 SEND_ERR(px, "Lua function '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010168 rule->arg.hlua_rule->fcn->name, error);
Christopher Faulet7716cdf2020-01-29 11:53:30 +010010169 goto end;
Thierry FOURNIERbabae282015-09-17 11:36:37 +020010170 }
10171
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +010010172 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +010010173 if (!lua_checkstack(s->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +020010174 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010175 rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010176 RESET_SAFE_LJMP(s->hlua);
Christopher Faulet7716cdf2020-01-29 11:53:30 +010010177 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +010010178 }
10179
10180 /* Restore the function in the stack. */
Aurelien DARRAGON4fdf8b52023-03-20 17:22:37 +010010181 hlua_pushref(s->hlua->T, rule->arg.hlua_rule->fcn->function_ref[s->hlua->state_id]);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +010010182
Willy Tarreau87b09662015-04-03 00:22:06 +020010183 /* Create and and push object stream in the stack. */
Christopher Fauletbfab2dd2019-07-26 15:09:53 +020010184 if (!hlua_txn_new(s->hlua->T, s, px, dir, hflags)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +020010185 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010186 rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010187 RESET_SAFE_LJMP(s->hlua);
Christopher Faulet7716cdf2020-01-29 11:53:30 +010010188 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +010010189 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +010010190 s->hlua->nargs = 1;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +010010191
10192 /* push keywords in the stack. */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +020010193 for (arg = rule->arg.hlua_rule->args; arg && *arg; arg++) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +010010194 if (!lua_checkstack(s->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +020010195 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010196 rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010197 RESET_SAFE_LJMP(s->hlua);
Christopher Faulet7716cdf2020-01-29 11:53:30 +010010198 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +010010199 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +010010200 lua_pushstring(s->hlua->T, *arg);
10201 s->hlua->nargs++;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +010010202 }
10203
Thierry FOURNIERbabae282015-09-17 11:36:37 +020010204 /* Now the execution is safe. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010205 RESET_SAFE_LJMP(s->hlua);
Thierry FOURNIERbabae282015-09-17 11:36:37 +020010206
Thierry FOURNIERbd413492015-03-03 16:52:26 +010010207 /* We must initialize the execution timeouts. */
Aurelien DARRAGONda9503c2022-11-25 09:10:07 +010010208 hlua_timer_init(&s->hlua->timer, hlua_timeout_session);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +010010209 }
10210
10211 /* Execute the function. */
Christopher Faulet105ba6c2019-12-18 14:41:51 +010010212 switch (hlua_ctx_resume(s->hlua, !(flags & ACT_OPT_FINAL))) {
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +010010213 /* finished. */
10214 case HLUA_E_OK:
Christopher Faulet7716cdf2020-01-29 11:53:30 +010010215 /* Catch the return value */
10216 if (lua_gettop(s->hlua->T) > 0)
10217 act_ret = lua_tointeger(s->hlua->T, -1);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +010010218
Christopher Faulet2c2c2e32020-01-31 19:07:52 +010010219 /* Set timeout in the required channel. */
Christopher Faulet498c4832020-07-28 11:59:58 +020010220 if (act_ret == ACT_RET_YIELD) {
10221 if (flags & ACT_OPT_FINAL)
10222 goto err_yield;
10223
Christopher Faulet8f587ea2020-07-28 12:01:55 +020010224 if (dir == SMP_OPT_DIR_REQ)
10225 s->req.analyse_exp = tick_first((tick_is_expired(s->req.analyse_exp, now_ms) ? 0 : s->req.analyse_exp),
10226 s->hlua->wake_time);
10227 else
10228 s->res.analyse_exp = tick_first((tick_is_expired(s->res.analyse_exp, now_ms) ? 0 : s->res.analyse_exp),
10229 s->hlua->wake_time);
Christopher Faulet2c2c2e32020-01-31 19:07:52 +010010230 }
10231 goto end;
10232
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +010010233 /* yield. */
10234 case HLUA_E_AGAIN:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +010010235 /* Set timeout in the required channel. */
Christopher Faulet8f587ea2020-07-28 12:01:55 +020010236 if (dir == SMP_OPT_DIR_REQ)
10237 s->req.analyse_exp = tick_first((tick_is_expired(s->req.analyse_exp, now_ms) ? 0 : s->req.analyse_exp),
10238 s->hlua->wake_time);
10239 else
10240 s->res.analyse_exp = tick_first((tick_is_expired(s->res.analyse_exp, now_ms) ? 0 : s->res.analyse_exp),
10241 s->hlua->wake_time);
10242
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +010010243 /* Some actions can be wake up when a "write" event
10244 * is detected on a response channel. This is useful
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -080010245 * only for actions targeted on the requests.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +010010246 */
Christopher Faulet51fa3582019-07-26 14:54:52 +020010247 if (HLUA_IS_WAKERESWR(s->hlua))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +010010248 s->res.flags |= CF_WAKE_WRITE;
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +010010249 if (HLUA_IS_WAKEREQWR(s->hlua))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +010010250 s->req.flags |= CF_WAKE_WRITE;
Christopher Faulet7716cdf2020-01-29 11:53:30 +010010251 act_ret = ACT_RET_YIELD;
10252 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +010010253
10254 /* finished with error. */
10255 case HLUA_E_ERRMSG:
10256 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +020010257 SEND_ERR(px, "Lua function '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010258 rule->arg.hlua_rule->fcn->name, lua_tostring(s->hlua->T, -1));
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +010010259 lua_pop(s->hlua->T, 1);
Christopher Faulet7716cdf2020-01-29 11:53:30 +010010260 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +010010261
Thierry Fournierd5b073c2018-05-21 19:42:47 +020010262 case HLUA_E_ETMOUT:
Thierry Fournierad5345f2020-11-29 02:05:57 +010010263 SEND_ERR(px, "Lua function '%s': execution timeout.\n", rule->arg.hlua_rule->fcn->name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +010010264 goto end;
Thierry Fournierd5b073c2018-05-21 19:42:47 +020010265
10266 case HLUA_E_NOMEM:
Thierry Fournierad5345f2020-11-29 02:05:57 +010010267 SEND_ERR(px, "Lua function '%s': out of memory error.\n", rule->arg.hlua_rule->fcn->name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +010010268 goto end;
Thierry Fournierd5b073c2018-05-21 19:42:47 +020010269
10270 case HLUA_E_YIELD:
Christopher Faulet498c4832020-07-28 11:59:58 +020010271 err_yield:
10272 act_ret = ACT_RET_CONT;
Thierry Fournierd5b073c2018-05-21 19:42:47 +020010273 SEND_ERR(px, "Lua function '%s': aborting Lua processing on expired timeout.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010274 rule->arg.hlua_rule->fcn->name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +010010275 goto end;
Thierry Fournierd5b073c2018-05-21 19:42:47 +020010276
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +010010277 case HLUA_E_ERR:
10278 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +020010279 SEND_ERR(px, "Lua function '%s' return an unknown error.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010280 rule->arg.hlua_rule->fcn->name);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +010010281
10282 default:
Christopher Faulet7716cdf2020-01-29 11:53:30 +010010283 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +010010284 }
Christopher Faulet7716cdf2020-01-29 11:53:30 +010010285
10286 end:
Christopher Faulet2361fd92020-07-30 10:40:58 +020010287 if (act_ret != ACT_RET_YIELD && s->hlua)
Christopher Faulet8f587ea2020-07-28 12:01:55 +020010288 s->hlua->wake_time = TICK_ETERNITY;
Christopher Faulet7716cdf2020-01-29 11:53:30 +010010289 return act_ret;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +010010290}
10291
Willy Tarreau144f84a2021-03-02 16:09:26 +010010292struct task *hlua_applet_wakeup(struct task *t, void *context, unsigned int state)
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010293{
Olivier Houchard9f6af332018-05-25 14:04:04 +020010294 struct appctx *ctx = context;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010295
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010296 appctx_wakeup(ctx);
Willy Tarreaud9587412017-08-23 16:07:33 +020010297 t->expire = TICK_ETERNITY;
Willy Tarreaud1aa41f2017-07-21 16:41:56 +020010298 return t;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010299}
10300
Christopher Faulet4aa1d282022-01-13 16:01:35 +010010301static int hlua_applet_tcp_init(struct appctx *ctx)
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010302{
Willy Tarreaue23f33b2022-05-06 14:07:13 +020010303 struct hlua_tcp_ctx *tcp_ctx = applet_reserve_svcctx(ctx, sizeof(*tcp_ctx));
Willy Tarreauc12b3212022-05-27 11:08:15 +020010304 struct stconn *sc = appctx_sc(ctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +020010305 struct stream *strm = __sc_strm(sc);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +010010306 struct hlua *hlua;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010307 struct task *task;
10308 char **arg;
Thierry Fournierfd107a22016-02-19 19:57:23 +010010309 const char *error;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010310
Willy Tarreaubafbe012017-11-24 17:34:44 +010010311 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +010010312 if (!hlua) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +010010313 SEND_ERR(strm->be, "Lua applet tcp '%s': out of memory.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010314 ctx->rule->arg.hlua_rule->fcn->name);
Christopher Fauletc9929382022-05-12 11:52:27 +020010315 return -1;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +010010316 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010317 HLUA_INIT(hlua);
Willy Tarreaue23f33b2022-05-06 14:07:13 +020010318 tcp_ctx->hlua = hlua;
10319 tcp_ctx->flags = 0;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010320
10321 /* Create task used by signal to wakeup applets. */
Willy Tarreaubeeabf52021-10-01 18:23:30 +020010322 task = task_new_here();
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010323 if (!task) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +010010324 SEND_ERR(strm->be, "Lua applet tcp '%s': out of memory.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010325 ctx->rule->arg.hlua_rule->fcn->name);
Christopher Fauletc9929382022-05-12 11:52:27 +020010326 return -1;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010327 }
10328 task->nice = 0;
10329 task->context = ctx;
10330 task->process = hlua_applet_wakeup;
Willy Tarreaue23f33b2022-05-06 14:07:13 +020010331 tcp_ctx->task = task;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010332
10333 /* In the execution wrappers linked with a stream, the
10334 * Lua context can be not initialized. This behavior
10335 * permits to save performances because a systematic
10336 * Lua initialization cause 5% performances loss.
10337 */
Aurelien DARRAGON6b0b9bd2023-03-21 14:02:16 +010010338 if (!hlua_ctx_init(hlua, fcn_ref_to_stack_id(ctx->rule->arg.hlua_rule->fcn), task)) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +010010339 SEND_ERR(strm->be, "Lua applet tcp '%s': can't initialize Lua context.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010340 ctx->rule->arg.hlua_rule->fcn->name);
Christopher Fauletc9929382022-05-12 11:52:27 +020010341 return -1;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010342 }
10343
10344 /* Set timeout according with the applet configuration. */
Aurelien DARRAGONda9503c2022-11-25 09:10:07 +010010345 hlua_timer_init(&hlua->timer, ctx->applet->timeout);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010346
10347 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010348 if (!SET_SAFE_LJMP(hlua)) {
Thierry Fournierfd107a22016-02-19 19:57:23 +010010349 if (lua_type(hlua->T, -1) == LUA_TSTRING)
10350 error = lua_tostring(hlua->T, -1);
10351 else
10352 error = "critical error";
Christopher Faulet4aa1d282022-01-13 16:01:35 +010010353 SEND_ERR(strm->be, "Lua applet tcp '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010354 ctx->rule->arg.hlua_rule->fcn->name, error);
Christopher Fauletc9929382022-05-12 11:52:27 +020010355 return -1;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010356 }
10357
10358 /* Check stack available size. */
10359 if (!lua_checkstack(hlua->T, 1)) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +010010360 SEND_ERR(strm->be, "Lua applet tcp '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010361 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010362 RESET_SAFE_LJMP(hlua);
Christopher Fauletc9929382022-05-12 11:52:27 +020010363 return -1;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010364 }
10365
10366 /* Restore the function in the stack. */
Aurelien DARRAGON4fdf8b52023-03-20 17:22:37 +010010367 hlua_pushref(hlua->T, ctx->rule->arg.hlua_rule->fcn->function_ref[hlua->state_id]);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010368
10369 /* Create and and push object stream in the stack. */
10370 if (!hlua_applet_tcp_new(hlua->T, ctx)) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +010010371 SEND_ERR(strm->be, "Lua applet tcp '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010372 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010373 RESET_SAFE_LJMP(hlua);
Christopher Fauletc9929382022-05-12 11:52:27 +020010374 return -1;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010375 }
10376 hlua->nargs = 1;
10377
10378 /* push keywords in the stack. */
10379 for (arg = ctx->rule->arg.hlua_rule->args; arg && *arg; arg++) {
10380 if (!lua_checkstack(hlua->T, 1)) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +010010381 SEND_ERR(strm->be, "Lua applet tcp '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010382 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010383 RESET_SAFE_LJMP(hlua);
Christopher Fauletc9929382022-05-12 11:52:27 +020010384 return -1;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010385 }
10386 lua_pushstring(hlua->T, *arg);
10387 hlua->nargs++;
10388 }
10389
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010390 RESET_SAFE_LJMP(hlua);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010391
10392 /* Wakeup the applet ASAP. */
Willy Tarreau90e8b452022-05-25 18:21:43 +020010393 applet_need_more_data(ctx);
Willy Tarreau4164eb92022-05-25 15:42:03 +020010394 applet_have_more_data(ctx);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010395
Christopher Fauletc9929382022-05-12 11:52:27 +020010396 return 0;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010397}
10398
Willy Tarreau60409db2019-08-21 14:14:50 +020010399void hlua_applet_tcp_fct(struct appctx *ctx)
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010400{
Willy Tarreaue23f33b2022-05-06 14:07:13 +020010401 struct hlua_tcp_ctx *tcp_ctx = ctx->svcctx;
Willy Tarreauc12b3212022-05-27 11:08:15 +020010402 struct stconn *sc = appctx_sc(ctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +020010403 struct stream *strm = __sc_strm(sc);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010404 struct act_rule *rule = ctx->rule;
10405 struct proxy *px = strm->be;
Willy Tarreaue23f33b2022-05-06 14:07:13 +020010406 struct hlua *hlua = tcp_ctx->hlua;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010407
Christopher Faulet31572222023-03-31 11:13:48 +020010408 if (unlikely(se_fl_test(ctx->sedesc, (SE_FL_EOS|SE_FL_ERROR|SE_FL_SHR|SE_FL_SHW))))
10409 goto out;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010410
Christopher Faulet31572222023-03-31 11:13:48 +020010411 /* The applet execution is already done. */
10412 if (tcp_ctx->flags & APPLET_DONE)
10413 goto out;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010414
10415 /* Execute the function. */
10416 switch (hlua_ctx_resume(hlua, 1)) {
10417 /* finished. */
10418 case HLUA_E_OK:
Willy Tarreaue23f33b2022-05-06 14:07:13 +020010419 tcp_ctx->flags |= APPLET_DONE;
Christopher Faulet31572222023-03-31 11:13:48 +020010420 se_fl_set(ctx->sedesc, SE_FL_EOI|SE_FL_EOS);
10421 break;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010422
10423 /* yield. */
10424 case HLUA_E_AGAIN:
Thierry Fournier0164f202016-02-20 17:47:43 +010010425 if (hlua->wake_time != TICK_ETERNITY)
Willy Tarreaue23f33b2022-05-06 14:07:13 +020010426 task_schedule(tcp_ctx->task, hlua->wake_time);
Christopher Faulet31572222023-03-31 11:13:48 +020010427 break;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010428
10429 /* finished with error. */
10430 case HLUA_E_ERRMSG:
10431 /* Display log. */
10432 SEND_ERR(px, "Lua applet tcp '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010433 rule->arg.hlua_rule->fcn->name, lua_tostring(hlua->T, -1));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010434 lua_pop(hlua->T, 1);
10435 goto error;
10436
Thierry Fournierd5b073c2018-05-21 19:42:47 +020010437 case HLUA_E_ETMOUT:
10438 SEND_ERR(px, "Lua applet tcp '%s': execution timeout.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010439 rule->arg.hlua_rule->fcn->name);
Thierry Fournierd5b073c2018-05-21 19:42:47 +020010440 goto error;
10441
10442 case HLUA_E_NOMEM:
10443 SEND_ERR(px, "Lua applet tcp '%s': out of memory error.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010444 rule->arg.hlua_rule->fcn->name);
Thierry Fournierd5b073c2018-05-21 19:42:47 +020010445 goto error;
10446
10447 case HLUA_E_YIELD: /* unexpected */
10448 SEND_ERR(px, "Lua applet tcp '%s': yield not allowed.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010449 rule->arg.hlua_rule->fcn->name);
Thierry Fournierd5b073c2018-05-21 19:42:47 +020010450 goto error;
10451
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010452 case HLUA_E_ERR:
10453 /* Display log. */
10454 SEND_ERR(px, "Lua applet tcp '%s' return an unknown error.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010455 rule->arg.hlua_rule->fcn->name);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010456 goto error;
10457
10458 default:
10459 goto error;
10460 }
10461
Christopher Faulet31572222023-03-31 11:13:48 +020010462out:
10463 /* eat the whole request */
10464 co_skip(sc_oc(sc), co_data(sc_oc(sc)));
10465 return;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010466
Christopher Faulet31572222023-03-31 11:13:48 +020010467error:
10468 se_fl_set(ctx->sedesc, SE_FL_ERROR);
Willy Tarreaue23f33b2022-05-06 14:07:13 +020010469 tcp_ctx->flags |= APPLET_DONE;
Christopher Faulet31572222023-03-31 11:13:48 +020010470 goto out;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010471}
10472
10473static void hlua_applet_tcp_release(struct appctx *ctx)
10474{
Willy Tarreaue23f33b2022-05-06 14:07:13 +020010475 struct hlua_tcp_ctx *tcp_ctx = ctx->svcctx;
10476
10477 task_destroy(tcp_ctx->task);
10478 tcp_ctx->task = NULL;
10479 hlua_ctx_destroy(tcp_ctx->hlua);
10480 tcp_ctx->hlua = NULL;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010481}
10482
Christopher Fauletc9929382022-05-12 11:52:27 +020010483/* The function returns 0 if the initialisation is complete or -1 if
10484 * an errors occurs. It also reserves the appctx for an hlua_http_ctx.
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010485 */
Christopher Faulet4aa1d282022-01-13 16:01:35 +010010486static int hlua_applet_http_init(struct appctx *ctx)
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010487{
Willy Tarreauaa229cc2022-05-06 14:26:10 +020010488 struct hlua_http_ctx *http_ctx = applet_reserve_svcctx(ctx, sizeof(*http_ctx));
Willy Tarreauc12b3212022-05-27 11:08:15 +020010489 struct stconn *sc = appctx_sc(ctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +020010490 struct stream *strm = __sc_strm(sc);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010491 struct http_txn *txn;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +010010492 struct hlua *hlua;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010493 char **arg;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010494 struct task *task;
Thierry Fournierfd107a22016-02-19 19:57:23 +010010495 const char *error;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010496
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010497 txn = strm->txn;
Willy Tarreaubafbe012017-11-24 17:34:44 +010010498 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +010010499 if (!hlua) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +010010500 SEND_ERR(strm->be, "Lua applet http '%s': out of memory.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010501 ctx->rule->arg.hlua_rule->fcn->name);
Christopher Fauletc9929382022-05-12 11:52:27 +020010502 return -1;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +010010503 }
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010504 HLUA_INIT(hlua);
Willy Tarreauaa229cc2022-05-06 14:26:10 +020010505 http_ctx->hlua = hlua;
10506 http_ctx->left_bytes = -1;
10507 http_ctx->flags = 0;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010508
Thierry FOURNIERd93ea2b2015-12-20 19:14:52 +010010509 if (txn->req.flags & HTTP_MSGF_VER_11)
Willy Tarreauaa229cc2022-05-06 14:26:10 +020010510 http_ctx->flags |= APPLET_HTTP11;
Thierry FOURNIERd93ea2b2015-12-20 19:14:52 +010010511
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010512 /* Create task used by signal to wakeup applets. */
Willy Tarreaubeeabf52021-10-01 18:23:30 +020010513 task = task_new_here();
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010514 if (!task) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +010010515 SEND_ERR(strm->be, "Lua applet http '%s': out of memory.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010516 ctx->rule->arg.hlua_rule->fcn->name);
Christopher Fauletc9929382022-05-12 11:52:27 +020010517 return -1;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010518 }
10519 task->nice = 0;
10520 task->context = ctx;
10521 task->process = hlua_applet_wakeup;
Willy Tarreauaa229cc2022-05-06 14:26:10 +020010522 http_ctx->task = task;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010523
10524 /* In the execution wrappers linked with a stream, the
10525 * Lua context can be not initialized. This behavior
10526 * permits to save performances because a systematic
10527 * Lua initialization cause 5% performances loss.
10528 */
Aurelien DARRAGON6b0b9bd2023-03-21 14:02:16 +010010529 if (!hlua_ctx_init(hlua, fcn_ref_to_stack_id(ctx->rule->arg.hlua_rule->fcn), task)) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +010010530 SEND_ERR(strm->be, "Lua applet http '%s': can't initialize Lua context.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010531 ctx->rule->arg.hlua_rule->fcn->name);
Christopher Fauletc9929382022-05-12 11:52:27 +020010532 return -1;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010533 }
10534
10535 /* Set timeout according with the applet configuration. */
Aurelien DARRAGONda9503c2022-11-25 09:10:07 +010010536 hlua_timer_init(&hlua->timer, ctx->applet->timeout);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010537
10538 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010539 if (!SET_SAFE_LJMP(hlua)) {
Thierry Fournierfd107a22016-02-19 19:57:23 +010010540 if (lua_type(hlua->T, -1) == LUA_TSTRING)
10541 error = lua_tostring(hlua->T, -1);
10542 else
10543 error = "critical error";
Christopher Faulet4aa1d282022-01-13 16:01:35 +010010544 SEND_ERR(strm->be, "Lua applet http '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010545 ctx->rule->arg.hlua_rule->fcn->name, error);
Christopher Fauletc9929382022-05-12 11:52:27 +020010546 return -1;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010547 }
10548
10549 /* Check stack available size. */
10550 if (!lua_checkstack(hlua->T, 1)) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +010010551 SEND_ERR(strm->be, "Lua applet http '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010552 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010553 RESET_SAFE_LJMP(hlua);
Christopher Fauletc9929382022-05-12 11:52:27 +020010554 return -1;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010555 }
10556
10557 /* Restore the function in the stack. */
Aurelien DARRAGON4fdf8b52023-03-20 17:22:37 +010010558 hlua_pushref(hlua->T, ctx->rule->arg.hlua_rule->fcn->function_ref[hlua->state_id]);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010559
10560 /* Create and and push object stream in the stack. */
10561 if (!hlua_applet_http_new(hlua->T, ctx)) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +010010562 SEND_ERR(strm->be, "Lua applet http '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010563 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010564 RESET_SAFE_LJMP(hlua);
Christopher Fauletc9929382022-05-12 11:52:27 +020010565 return -1;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010566 }
10567 hlua->nargs = 1;
10568
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010569 /* push keywords in the stack. */
10570 for (arg = ctx->rule->arg.hlua_rule->args; arg && *arg; arg++) {
10571 if (!lua_checkstack(hlua->T, 1)) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +010010572 SEND_ERR(strm->be, "Lua applet http '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010573 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010574 RESET_SAFE_LJMP(hlua);
Christopher Fauletc9929382022-05-12 11:52:27 +020010575 return -1;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010576 }
10577 lua_pushstring(hlua->T, *arg);
10578 hlua->nargs++;
10579 }
10580
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010581 RESET_SAFE_LJMP(hlua);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010582
10583 /* Wakeup the applet when data is ready for read. */
Willy Tarreau90e8b452022-05-25 18:21:43 +020010584 applet_need_more_data(ctx);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010585
Christopher Fauletc9929382022-05-12 11:52:27 +020010586 return 0;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010587}
10588
Willy Tarreau60409db2019-08-21 14:14:50 +020010589void hlua_applet_http_fct(struct appctx *ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010590{
Willy Tarreauaa229cc2022-05-06 14:26:10 +020010591 struct hlua_http_ctx *http_ctx = ctx->svcctx;
Willy Tarreauc12b3212022-05-27 11:08:15 +020010592 struct stconn *sc = appctx_sc(ctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +020010593 struct stream *strm = __sc_strm(sc);
10594 struct channel *req = sc_oc(sc);
10595 struct channel *res = sc_ic(sc);
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010596 struct act_rule *rule = ctx->rule;
10597 struct proxy *px = strm->be;
Willy Tarreauaa229cc2022-05-06 14:26:10 +020010598 struct hlua *hlua = http_ctx->hlua;
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010599 struct htx *req_htx, *res_htx;
10600
10601 res_htx = htx_from_buf(&res->buf);
10602
Christopher Faulet31572222023-03-31 11:13:48 +020010603 if (unlikely(se_fl_test(ctx->sedesc, (SE_FL_EOS|SE_FL_ERROR|SE_FL_SHR|SE_FL_SHW))))
10604 goto out;
10605
10606 /* The applet execution is already done. */
10607 if (http_ctx->flags & APPLET_DONE)
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010608 goto out;
10609
Ilya Shipitsin856aabc2020-04-16 23:51:34 +050010610 /* Check if the input buffer is available. */
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010611 if (!b_size(&res->buf)) {
Christopher Faulet7b3d38a2023-05-05 11:28:45 +020010612 sc_need_room(sc, 0);
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010613 goto out;
10614 }
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010615
10616 /* Set the currently running flag. */
10617 if (!HLUA_IS_RUNNING(hlua) &&
Willy Tarreauaa229cc2022-05-06 14:26:10 +020010618 !(http_ctx->flags & APPLET_DONE)) {
Christopher Fauletbd878d22021-04-28 10:50:21 +020010619 if (!co_data(req)) {
Willy Tarreau90e8b452022-05-25 18:21:43 +020010620 applet_need_more_data(ctx);
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010621 goto out;
10622 }
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010623 }
10624
Christopher Faulet31572222023-03-31 11:13:48 +020010625 /* Execute the function. */
10626 switch (hlua_ctx_resume(hlua, 1)) {
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010627 /* finished. */
10628 case HLUA_E_OK:
Willy Tarreauaa229cc2022-05-06 14:26:10 +020010629 http_ctx->flags |= APPLET_DONE;
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010630 break;
10631
10632 /* yield. */
10633 case HLUA_E_AGAIN:
10634 if (hlua->wake_time != TICK_ETERNITY)
Willy Tarreauaa229cc2022-05-06 14:26:10 +020010635 task_schedule(http_ctx->task, hlua->wake_time);
Christopher Faulet56a3d6e2019-02-27 22:06:23 +010010636 goto out;
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010637
10638 /* finished with error. */
10639 case HLUA_E_ERRMSG:
10640 /* Display log. */
10641 SEND_ERR(px, "Lua applet http '%s': %s.\n",
Christopher Faulet31572222023-03-31 11:13:48 +020010642 rule->arg.hlua_rule->fcn->name, lua_tostring(hlua->T, -1));
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010643 lua_pop(hlua->T, 1);
10644 goto error;
10645
10646 case HLUA_E_ETMOUT:
10647 SEND_ERR(px, "Lua applet http '%s': execution timeout.\n",
Christopher Faulet31572222023-03-31 11:13:48 +020010648 rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010649 goto error;
10650
10651 case HLUA_E_NOMEM:
10652 SEND_ERR(px, "Lua applet http '%s': out of memory error.\n",
Christopher Faulet31572222023-03-31 11:13:48 +020010653 rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010654 goto error;
10655
10656 case HLUA_E_YIELD: /* unexpected */
10657 SEND_ERR(px, "Lua applet http '%s': yield not allowed.\n",
Christopher Faulet31572222023-03-31 11:13:48 +020010658 rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010659 goto error;
10660
10661 case HLUA_E_ERR:
10662 /* Display log. */
10663 SEND_ERR(px, "Lua applet http '%s' return an unknown error.\n",
Christopher Faulet31572222023-03-31 11:13:48 +020010664 rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010665 goto error;
10666
10667 default:
10668 goto error;
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010669 }
10670
Willy Tarreauaa229cc2022-05-06 14:26:10 +020010671 if (http_ctx->flags & APPLET_DONE) {
10672 if (http_ctx->flags & APPLET_RSP_SENT)
Christopher Faulet31572222023-03-31 11:13:48 +020010673 goto out;
Christopher Faulet56a3d6e2019-02-27 22:06:23 +010010674
Willy Tarreauaa229cc2022-05-06 14:26:10 +020010675 if (!(http_ctx->flags & APPLET_HDR_SENT))
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010676 goto error;
10677
Christopher Fauletf89af9c2022-04-07 10:07:18 +020010678 /* no more data are expected. If the response buffer is empty
10679 * for a chunked message, be sure to add something (EOT block in
10680 * this case) to have something to send. It is important to be
10681 * sure the EOM flags will be handled by the endpoint.
10682 */
10683 if (htx_is_empty(res_htx) && (strm->txn->rsp.flags & (HTTP_MSGF_XFER_LEN|HTTP_MSGF_CNT_LEN)) == HTTP_MSGF_XFER_LEN) {
10684 if (!htx_add_endof(res_htx, HTX_BLK_EOT)) {
Christopher Faulet7b3d38a2023-05-05 11:28:45 +020010685 sc_need_room(sc, sizeof(struct htx_blk)+1);
Christopher Fauletf89af9c2022-04-07 10:07:18 +020010686 goto out;
10687 }
10688 channel_add_input(res, 1);
10689 }
10690
Christopher Fauletd1ac2b92020-12-02 19:12:22 +010010691 res_htx->flags |= HTX_FL_EOM;
Christopher Faulet31572222023-03-31 11:13:48 +020010692 se_fl_set(ctx->sedesc, SE_FL_EOI|SE_FL_EOS);
Willy Tarreauaa229cc2022-05-06 14:26:10 +020010693 strm->txn->status = http_ctx->status;
10694 http_ctx->flags |= APPLET_RSP_SENT;
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010695 }
10696
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010697 out:
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010698 htx_to_buf(res_htx, &res->buf);
Christopher Faulet31572222023-03-31 11:13:48 +020010699 /* eat the whole request */
10700 if (co_data(req)) {
10701 req_htx = htx_from_buf(&req->buf);
10702 co_htx_skip(req, req_htx, co_data(req));
10703 htx_to_buf(req_htx, &req->buf);
10704 }
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010705 return;
10706
10707 error:
10708
10709 /* If we are in HTTP mode, and we are not send any
10710 * data, return a 500 server error in best effort:
10711 * if there is no room available in the buffer,
10712 * just close the connection.
10713 */
Willy Tarreauaa229cc2022-05-06 14:26:10 +020010714 if (!(http_ctx->flags & APPLET_HDR_SENT)) {
Christopher Fauletf7346382019-07-17 22:02:08 +020010715 struct buffer *err = &http_err_chunks[HTTP_ERR_500];
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010716
10717 channel_erase(res);
10718 res->buf.data = b_data(err);
10719 memcpy(res->buf.area, b_head(err), b_data(err));
10720 res_htx = htx_from_buf(&res->buf);
Christopher Fauletf6cce3f2019-02-27 21:20:09 +010010721 channel_add_input(res, res_htx->data);
Christopher Faulet31572222023-03-31 11:13:48 +020010722 se_fl_set(ctx->sedesc, SE_FL_EOI|SE_FL_EOS);
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010723 }
Christopher Faulet31572222023-03-31 11:13:48 +020010724 else
10725 se_fl_set(ctx->sedesc, SE_FL_ERROR);
10726
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010727 if (!(strm->flags & SF_ERR_MASK))
10728 strm->flags |= SF_ERR_RESOURCE;
Willy Tarreauaa229cc2022-05-06 14:26:10 +020010729 http_ctx->flags |= APPLET_DONE;
Christopher Faulet31572222023-03-31 11:13:48 +020010730 goto out;
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010731}
10732
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010733static void hlua_applet_http_release(struct appctx *ctx)
10734{
Willy Tarreauaa229cc2022-05-06 14:26:10 +020010735 struct hlua_http_ctx *http_ctx = ctx->svcctx;
10736
10737 task_destroy(http_ctx->task);
10738 http_ctx->task = NULL;
10739 hlua_ctx_destroy(http_ctx->hlua);
10740 http_ctx->hlua = NULL;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010741}
10742
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +020010743/* global {tcp|http}-request parser. Return ACT_RET_PRS_OK in
Ilya Shipitsin856aabc2020-04-16 23:51:34 +050010744 * success case, else return ACT_RET_PRS_ERR.
Thierry FOURNIERbabae282015-09-17 11:36:37 +020010745 *
10746 * This function can fail with an abort() due to an Lua critical error.
10747 * We are in the configuration parsing process of HAProxy, this abort() is
10748 * tolerated.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +010010749 */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +020010750static enum act_parse_ret action_register_lua(const char **args, int *cur_arg, struct proxy *px,
10751 struct act_rule *rule, char **err)
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +010010752{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +020010753 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +010010754 int i;
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010755
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +020010756 /* Memory for the rule. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +020010757 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +020010758 if (!rule->arg.hlua_rule) {
10759 memprintf(err, "out of memory error");
Christopher Faulet528526f2021-04-12 14:37:32 +020010760 goto error;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +020010761 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +010010762
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +010010763 /* Memory for arguments. */
Tim Duesterhuse52b6e52020-09-12 20:26:43 +020010764 rule->arg.hlua_rule->args = calloc(fcn->nargs + 1,
10765 sizeof(*rule->arg.hlua_rule->args));
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +010010766 if (!rule->arg.hlua_rule->args) {
10767 memprintf(err, "out of memory error");
Christopher Faulet528526f2021-04-12 14:37:32 +020010768 goto error;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +010010769 }
10770
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +020010771 /* Reference the Lua function and store the reference. */
Thierry Fournierad5345f2020-11-29 02:05:57 +010010772 rule->arg.hlua_rule->fcn = fcn;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +020010773
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +010010774 /* Expect some arguments */
10775 for (i = 0; i < fcn->nargs; i++) {
Thierry FOURNIER1725c2e2019-01-06 19:38:49 +010010776 if (*args[*cur_arg] == '\0') {
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +010010777 memprintf(err, "expect %d arguments", fcn->nargs);
Christopher Faulet528526f2021-04-12 14:37:32 +020010778 goto error;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +010010779 }
Thierry FOURNIER1725c2e2019-01-06 19:38:49 +010010780 rule->arg.hlua_rule->args[i] = strdup(args[*cur_arg]);
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +010010781 if (!rule->arg.hlua_rule->args[i]) {
10782 memprintf(err, "out of memory error");
Christopher Faulet528526f2021-04-12 14:37:32 +020010783 goto error;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +010010784 }
10785 (*cur_arg)++;
10786 }
10787 rule->arg.hlua_rule->args[i] = NULL;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +020010788
Thierry FOURNIER42148732015-09-02 17:17:33 +020010789 rule->action = ACT_CUSTOM;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +020010790 rule->action_ptr = hlua_action;
Thierry FOURNIERafa80492015-08-19 09:04:15 +020010791 return ACT_RET_PRS_OK;
Christopher Faulet528526f2021-04-12 14:37:32 +020010792
10793 error:
10794 if (rule->arg.hlua_rule) {
10795 if (rule->arg.hlua_rule->args) {
10796 for (i = 0; i < fcn->nargs; i++)
10797 ha_free(&rule->arg.hlua_rule->args[i]);
10798 ha_free(&rule->arg.hlua_rule->args);
10799 }
10800 ha_free(&rule->arg.hlua_rule);
10801 }
10802 return ACT_RET_PRS_ERR;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +010010803}
10804
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010805static enum act_parse_ret action_register_service_http(const char **args, int *cur_arg, struct proxy *px,
10806 struct act_rule *rule, char **err)
10807{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +020010808 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010809
Thierry FOURNIER718e2a72015-12-20 20:13:14 +010010810 /* HTTP applets are forbidden in tcp-request rules.
Ilya Shipitsin856aabc2020-04-16 23:51:34 +050010811 * HTTP applet request requires everything initialized by
Thierry FOURNIER718e2a72015-12-20 20:13:14 +010010812 * "http_process_request" (analyzer flag AN_REQ_HTTP_INNER).
Ilya Shipitsin856aabc2020-04-16 23:51:34 +050010813 * The applet will be immediately initialized, but its before
Thierry FOURNIER718e2a72015-12-20 20:13:14 +010010814 * the call of this analyzer.
10815 */
10816 if (rule->from != ACT_F_HTTP_REQ) {
10817 memprintf(err, "HTTP applets are forbidden from 'tcp-request' rulesets");
10818 return ACT_RET_PRS_ERR;
10819 }
10820
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010821 /* Memory for the rule. */
10822 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
10823 if (!rule->arg.hlua_rule) {
10824 memprintf(err, "out of memory error");
10825 return ACT_RET_PRS_ERR;
10826 }
10827
10828 /* Reference the Lua function and store the reference. */
Thierry Fournierad5345f2020-11-29 02:05:57 +010010829 rule->arg.hlua_rule->fcn = fcn;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010830
10831 /* TODO: later accept arguments. */
10832 rule->arg.hlua_rule->args = NULL;
10833
10834 /* Add applet pointer in the rule. */
10835 rule->applet.obj_type = OBJ_TYPE_APPLET;
10836 rule->applet.name = fcn->name;
10837 rule->applet.init = hlua_applet_http_init;
10838 rule->applet.fct = hlua_applet_http_fct;
10839 rule->applet.release = hlua_applet_http_release;
10840 rule->applet.timeout = hlua_timeout_applet;
10841
10842 return ACT_RET_PRS_OK;
10843}
10844
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010845/* This function is an LUA binding used for registering
10846 * "sample-conv" functions. It expects a converter name used
10847 * in the haproxy configuration file, and an LUA function.
10848 */
10849__LJMP static int hlua_register_action(lua_State *L)
10850{
Christopher Faulet4fc9da02021-04-12 15:08:12 +020010851 struct action_kw_list *akl = NULL;
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010852 const char *name;
10853 int ref;
10854 int len;
Christopher Faulet4fc9da02021-04-12 15:08:12 +020010855 struct hlua_function *fcn = NULL;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +010010856 int nargs;
Thierry Fournierf67442e2020-11-28 20:41:07 +010010857 struct buffer *trash;
10858 struct action_kw *akw;
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010859
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +010010860 /* Initialise the number of expected arguments at 0. */
10861 nargs = 0;
10862
10863 if (lua_gettop(L) < 3 || lua_gettop(L) > 4)
10864 WILL_LJMP(luaL_error(L, "'register_action' needs between 3 and 4 arguments"));
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010865
Aurelien DARRAGON87f52972023-02-24 09:43:54 +010010866 if (hlua_gethlua(L)) {
10867 /* runtime processing */
10868 WILL_LJMP(luaL_error(L, "register_action: not available outside of body context"));
10869 }
10870
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010871 /* First argument : converter name. */
10872 name = MAY_LJMP(luaL_checkstring(L, 1));
10873
10874 /* Second argument : environment. */
10875 if (lua_type(L, 2) != LUA_TTABLE)
10876 WILL_LJMP(luaL_error(L, "register_action: second argument must be a table of strings"));
10877
10878 /* Third argument : lua function. */
10879 ref = MAY_LJMP(hlua_checkfunction(L, 3));
10880
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -080010881 /* Fourth argument : number of mandatory arguments expected on the configuration line. */
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +010010882 if (lua_gettop(L) >= 4)
10883 nargs = MAY_LJMP(luaL_checkinteger(L, 4));
10884
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -080010885 /* browse the second argument as an array. */
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010886 lua_pushnil(L);
10887 while (lua_next(L, 2) != 0) {
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +010010888 if (lua_type(L, -1) != LUA_TSTRING) {
10889 hlua_unref(L, ref);
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010890 WILL_LJMP(luaL_error(L, "register_action: second argument must be a table of strings"));
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +010010891 }
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010892
Thierry Fournierf67442e2020-11-28 20:41:07 +010010893 /* Check if action exists */
10894 trash = get_trash_chunk();
10895 chunk_printf(trash, "lua.%s", name);
10896 if (strcmp(lua_tostring(L, -1), "tcp-req") == 0) {
10897 akw = tcp_req_cont_action(trash->area);
10898 } else if (strcmp(lua_tostring(L, -1), "tcp-res") == 0) {
10899 akw = tcp_res_cont_action(trash->area);
10900 } else if (strcmp(lua_tostring(L, -1), "http-req") == 0) {
10901 akw = action_http_req_custom(trash->area);
10902 } else if (strcmp(lua_tostring(L, -1), "http-res") == 0) {
10903 akw = action_http_res_custom(trash->area);
10904 } else {
10905 akw = NULL;
10906 }
10907 if (akw != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +010010908 fcn = akw->private;
10909 if (fcn->function_ref[hlua_state_id] != -1) {
10910 ha_warning("Trying to register action 'lua.%s' more than once. "
10911 "This will become a hard error in version 2.5.\n", name);
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +010010912 hlua_unref(L, fcn->function_ref[hlua_state_id]);
Thierry Fournier59f11be2020-11-29 00:37:41 +010010913 }
10914 fcn->function_ref[hlua_state_id] = ref;
10915
10916 /* pop the environment string. */
10917 lua_pop(L, 1);
10918 continue;
Thierry Fournierf67442e2020-11-28 20:41:07 +010010919 }
10920
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010921 /* Check required environment. Only accepted "http" or "tcp". */
10922 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +020010923 akl = calloc(1, sizeof(*akl) + sizeof(struct action_kw) * 2);
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010924 if (!akl)
Christopher Faulet4fc9da02021-04-12 15:08:12 +020010925 goto alloc_error;;
Thierry Fournier62a22aa2020-11-28 21:06:35 +010010926 fcn = new_hlua_function();
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010927 if (!fcn)
Christopher Faulet4fc9da02021-04-12 15:08:12 +020010928 goto alloc_error;
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010929
10930 /* Fill fcn. */
10931 fcn->name = strdup(name);
10932 if (!fcn->name)
Christopher Faulet4fc9da02021-04-12 15:08:12 +020010933 goto alloc_error;
Thierry Fournierc7492592020-11-28 23:57:24 +010010934 fcn->function_ref[hlua_state_id] = ref;
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010935
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -070010936 /* Set the expected number of arguments. */
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +010010937 fcn->nargs = nargs;
10938
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010939 /* List head */
10940 akl->list.n = akl->list.p = NULL;
10941
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010942 /* action keyword. */
10943 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +020010944 akl->kw[0].kw = calloc(1, len);
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010945 if (!akl->kw[0].kw)
Christopher Faulet4fc9da02021-04-12 15:08:12 +020010946 goto alloc_error;
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010947
10948 snprintf((char *)akl->kw[0].kw, len, "lua.%s", name);
10949
Amaury Denoyellee4a617c2021-05-06 15:33:09 +020010950 akl->kw[0].flags = 0;
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010951 akl->kw[0].private = fcn;
10952 akl->kw[0].parse = action_register_lua;
10953
10954 /* select the action registering point. */
10955 if (strcmp(lua_tostring(L, -1), "tcp-req") == 0)
10956 tcp_req_cont_keywords_register(akl);
10957 else if (strcmp(lua_tostring(L, -1), "tcp-res") == 0)
10958 tcp_res_cont_keywords_register(akl);
10959 else if (strcmp(lua_tostring(L, -1), "http-req") == 0)
10960 http_req_keywords_register(akl);
10961 else if (strcmp(lua_tostring(L, -1), "http-res") == 0)
10962 http_res_keywords_register(akl);
Christopher Faulet4fc9da02021-04-12 15:08:12 +020010963 else {
10964 release_hlua_function(fcn);
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +010010965 hlua_unref(L, ref);
Christopher Faulet4fc9da02021-04-12 15:08:12 +020010966 if (akl)
10967 ha_free((char **)&(akl->kw[0].kw));
10968 ha_free(&akl);
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +010010969 WILL_LJMP(luaL_error(L, "Lua action environment '%s' is unknown. "
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010970 "'tcp-req', 'tcp-res', 'http-req' or 'http-res' "
10971 "are expected.", lua_tostring(L, -1)));
Christopher Faulet4fc9da02021-04-12 15:08:12 +020010972 }
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010973
10974 /* pop the environment string. */
10975 lua_pop(L, 1);
Christopher Faulet4fc9da02021-04-12 15:08:12 +020010976
10977 /* reset for next loop */
10978 akl = NULL;
10979 fcn = NULL;
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010980 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010981 return ACT_RET_PRS_OK;
Christopher Faulet4fc9da02021-04-12 15:08:12 +020010982
10983 alloc_error:
10984 release_hlua_function(fcn);
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +010010985 hlua_unref(L, ref);
Christopher Faulet4fc9da02021-04-12 15:08:12 +020010986 ha_free(&akl);
10987 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
10988 return 0; /* Never reached */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010989}
10990
10991static enum act_parse_ret action_register_service_tcp(const char **args, int *cur_arg, struct proxy *px,
10992 struct act_rule *rule, char **err)
10993{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +020010994 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010995
Christopher Faulet280f85b2019-07-15 15:02:04 +020010996 if (px->mode == PR_MODE_HTTP) {
10997 memprintf(err, "Lua TCP services cannot be used on HTTP proxies");
Christopher Fauletafd8f102018-11-08 11:34:21 +010010998 return ACT_RET_PRS_ERR;
10999 }
11000
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020011001 /* Memory for the rule. */
11002 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
11003 if (!rule->arg.hlua_rule) {
11004 memprintf(err, "out of memory error");
11005 return ACT_RET_PRS_ERR;
11006 }
Thierry FOURNIER8255a752015-09-23 21:03:35 +020011007
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020011008 /* Reference the Lua function and store the reference. */
Thierry Fournierad5345f2020-11-29 02:05:57 +010011009 rule->arg.hlua_rule->fcn = fcn;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020011010
11011 /* TODO: later accept arguments. */
11012 rule->arg.hlua_rule->args = NULL;
11013
11014 /* Add applet pointer in the rule. */
11015 rule->applet.obj_type = OBJ_TYPE_APPLET;
11016 rule->applet.name = fcn->name;
11017 rule->applet.init = hlua_applet_tcp_init;
11018 rule->applet.fct = hlua_applet_tcp_fct;
11019 rule->applet.release = hlua_applet_tcp_release;
11020 rule->applet.timeout = hlua_timeout_applet;
11021
11022 return 0;
11023}
11024
11025/* This function is an LUA binding used for registering
11026 * "sample-conv" functions. It expects a converter name used
11027 * in the haproxy configuration file, and an LUA function.
11028 */
11029__LJMP static int hlua_register_service(lua_State *L)
11030{
11031 struct action_kw_list *akl;
11032 const char *name;
11033 const char *env;
11034 int ref;
11035 int len;
Christopher Faulet5c028d72021-04-12 15:11:44 +020011036 struct hlua_function *fcn = NULL;
Thierry Fournierf67442e2020-11-28 20:41:07 +010011037 struct buffer *trash;
11038 struct action_kw *akw;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020011039
11040 MAY_LJMP(check_args(L, 3, "register_service"));
11041
Aurelien DARRAGON87f52972023-02-24 09:43:54 +010011042 if (hlua_gethlua(L)) {
11043 /* runtime processing */
11044 WILL_LJMP(luaL_error(L, "register_service: not available outside of body context"));
11045 }
11046
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020011047 /* First argument : converter name. */
11048 name = MAY_LJMP(luaL_checkstring(L, 1));
11049
11050 /* Second argument : environment. */
11051 env = MAY_LJMP(luaL_checkstring(L, 2));
11052
11053 /* Third argument : lua function. */
11054 ref = MAY_LJMP(hlua_checkfunction(L, 3));
11055
Thierry Fournierf67442e2020-11-28 20:41:07 +010011056 /* Check for service already registered */
11057 trash = get_trash_chunk();
11058 chunk_printf(trash, "lua.%s", name);
11059 akw = service_find(trash->area);
11060 if (akw != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +010011061 fcn = akw->private;
11062 if (fcn->function_ref[hlua_state_id] != -1) {
11063 ha_warning("Trying to register service 'lua.%s' more than once. "
11064 "This will become a hard error in version 2.5.\n", name);
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +010011065 hlua_unref(L, fcn->function_ref[hlua_state_id]);
Thierry Fournier59f11be2020-11-29 00:37:41 +010011066 }
11067 fcn->function_ref[hlua_state_id] = ref;
11068 return 0;
Thierry Fournierf67442e2020-11-28 20:41:07 +010011069 }
11070
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020011071 /* Allocate and fill the sample fetch keyword struct. */
11072 akl = calloc(1, sizeof(*akl) + sizeof(struct action_kw) * 2);
11073 if (!akl)
Christopher Faulet5c028d72021-04-12 15:11:44 +020011074 goto alloc_error;
Thierry Fournier62a22aa2020-11-28 21:06:35 +010011075 fcn = new_hlua_function();
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020011076 if (!fcn)
Christopher Faulet5c028d72021-04-12 15:11:44 +020011077 goto alloc_error;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020011078
11079 /* Fill fcn. */
11080 len = strlen("<lua.>") + strlen(name) + 1;
11081 fcn->name = calloc(1, len);
11082 if (!fcn->name)
Christopher Faulet5c028d72021-04-12 15:11:44 +020011083 goto alloc_error;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020011084 snprintf((char *)fcn->name, len, "<lua.%s>", name);
Thierry Fournierc7492592020-11-28 23:57:24 +010011085 fcn->function_ref[hlua_state_id] = ref;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020011086
11087 /* List head */
11088 akl->list.n = akl->list.p = NULL;
11089
11090 /* converter keyword. */
11091 len = strlen("lua.") + strlen(name) + 1;
11092 akl->kw[0].kw = calloc(1, len);
11093 if (!akl->kw[0].kw)
Christopher Faulet5c028d72021-04-12 15:11:44 +020011094 goto alloc_error;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020011095
11096 snprintf((char *)akl->kw[0].kw, len, "lua.%s", name);
11097
Thierry FOURNIER / OZON.IO02564fd2016-11-12 11:07:05 +010011098 /* Check required environment. Only accepted "http" or "tcp". */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020011099 if (strcmp(env, "tcp") == 0)
11100 akl->kw[0].parse = action_register_service_tcp;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020011101 else if (strcmp(env, "http") == 0)
11102 akl->kw[0].parse = action_register_service_http;
Christopher Faulet5c028d72021-04-12 15:11:44 +020011103 else {
11104 release_hlua_function(fcn);
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +010011105 hlua_unref(L, ref);
Christopher Faulet5c028d72021-04-12 15:11:44 +020011106 if (akl)
11107 ha_free((char **)&(akl->kw[0].kw));
11108 ha_free(&akl);
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +010011109 WILL_LJMP(luaL_error(L, "Lua service environment '%s' is unknown. "
Eric Salamafe7456f2017-12-21 14:30:07 +010011110 "'tcp' or 'http' are expected.", env));
Christopher Faulet5c028d72021-04-12 15:11:44 +020011111 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020011112
Amaury Denoyellee4a617c2021-05-06 15:33:09 +020011113 akl->kw[0].flags = 0;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020011114 akl->kw[0].private = fcn;
11115
11116 /* End of array. */
11117 memset(&akl->kw[1], 0, sizeof(*akl->kw));
11118
11119 /* Register this new converter */
11120 service_keywords_register(akl);
11121
Thierry FOURNIER8255a752015-09-23 21:03:35 +020011122 return 0;
Christopher Faulet5c028d72021-04-12 15:11:44 +020011123
11124 alloc_error:
11125 release_hlua_function(fcn);
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +010011126 hlua_unref(L, ref);
Christopher Faulet5c028d72021-04-12 15:11:44 +020011127 ha_free(&akl);
11128 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
11129 return 0; /* Never reached */
Thierry FOURNIER8255a752015-09-23 21:03:35 +020011130}
11131
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011132/* This function initialises Lua cli handler. It copies the
11133 * arguments in the Lua stack and create channel IO objects.
11134 */
Aurélien Nephtaliabbf6072018-04-18 13:26:46 +020011135static int hlua_cli_parse_fct(char **args, char *payload, struct appctx *appctx, void *private)
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011136{
Willy Tarreaubcda5f62022-05-03 18:13:39 +020011137 struct hlua_cli_ctx *ctx = applet_reserve_svcctx(appctx, sizeof(*ctx));
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011138 struct hlua *hlua;
11139 struct hlua_function *fcn;
11140 int i;
11141 const char *error;
11142
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011143 fcn = private;
Willy Tarreaubcda5f62022-05-03 18:13:39 +020011144 ctx->fcn = private;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +010011145
Willy Tarreaubafbe012017-11-24 17:34:44 +010011146 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +010011147 if (!hlua) {
11148 SEND_ERR(NULL, "Lua cli '%s': out of memory.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +010011149 return 1;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +010011150 }
11151 HLUA_INIT(hlua);
Willy Tarreaubcda5f62022-05-03 18:13:39 +020011152 ctx->hlua = hlua;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011153
11154 /* Create task used by signal to wakeup applets.
Ilya Shipitsind4259502020-04-08 01:07:56 +050011155 * We use the same wakeup function than the Lua applet_tcp and
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011156 * applet_http. It is absolutely compatible.
11157 */
Willy Tarreaubcda5f62022-05-03 18:13:39 +020011158 ctx->task = task_new_here();
11159 if (!ctx->task) {
Thierry FOURNIERffbf5692016-12-16 11:14:06 +010011160 SEND_ERR(NULL, "Lua cli '%s': out of memory.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +010011161 goto error;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011162 }
Willy Tarreaubcda5f62022-05-03 18:13:39 +020011163 ctx->task->nice = 0;
11164 ctx->task->context = appctx;
11165 ctx->task->process = hlua_applet_wakeup;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011166
11167 /* Initialises the Lua context */
Aurelien DARRAGON6b0b9bd2023-03-21 14:02:16 +010011168 if (!hlua_ctx_init(hlua, fcn_ref_to_stack_id(fcn), ctx->task)) {
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011169 SEND_ERR(NULL, "Lua cli '%s': can't initialize Lua context.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +010011170 goto error;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011171 }
11172
11173 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +010011174 if (!SET_SAFE_LJMP(hlua)) {
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011175 if (lua_type(hlua->T, -1) == LUA_TSTRING)
11176 error = lua_tostring(hlua->T, -1);
11177 else
11178 error = "critical error";
11179 SEND_ERR(NULL, "Lua cli '%s': %s.\n", fcn->name, error);
11180 goto error;
11181 }
11182
11183 /* Check stack available size. */
11184 if (!lua_checkstack(hlua->T, 2)) {
11185 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
11186 goto error;
11187 }
11188
11189 /* Restore the function in the stack. */
Aurelien DARRAGON4fdf8b52023-03-20 17:22:37 +010011190 hlua_pushref(hlua->T, fcn->function_ref[hlua->state_id]);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011191
11192 /* Once the arguments parsed, the CLI is like an AppletTCP,
11193 * so push AppletTCP in the stack.
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011194 */
11195 if (!hlua_applet_tcp_new(hlua->T, appctx)) {
11196 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
11197 goto error;
11198 }
11199 hlua->nargs = 1;
11200
11201 /* push keywords in the stack. */
11202 for (i = 0; *args[i]; i++) {
11203 /* Check stack available size. */
11204 if (!lua_checkstack(hlua->T, 1)) {
11205 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
11206 goto error;
11207 }
11208 lua_pushstring(hlua->T, args[i]);
11209 hlua->nargs++;
11210 }
11211
11212 /* We must initialize the execution timeouts. */
Aurelien DARRAGONda9503c2022-11-25 09:10:07 +010011213 hlua_timer_init(&hlua->timer, hlua_timeout_session);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011214
11215 /* At this point the execution is safe. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +010011216 RESET_SAFE_LJMP(hlua);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011217
11218 /* It's ok */
11219 return 0;
11220
11221 /* It's not ok. */
11222error:
Thierry Fournier7cbe5042020-11-28 17:02:21 +010011223 RESET_SAFE_LJMP(hlua);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011224 hlua_ctx_destroy(hlua);
Willy Tarreaubcda5f62022-05-03 18:13:39 +020011225 ctx->hlua = NULL;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011226 return 1;
11227}
11228
11229static int hlua_cli_io_handler_fct(struct appctx *appctx)
11230{
Willy Tarreaubcda5f62022-05-03 18:13:39 +020011231 struct hlua_cli_ctx *ctx = appctx->svcctx;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011232 struct hlua *hlua;
Willy Tarreau475e4632022-05-27 10:26:46 +020011233 struct stconn *sc;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011234 struct hlua_function *fcn;
11235
Willy Tarreaubcda5f62022-05-03 18:13:39 +020011236 hlua = ctx->hlua;
Willy Tarreauc12b3212022-05-27 11:08:15 +020011237 sc = appctx_sc(appctx);
Willy Tarreaubcda5f62022-05-03 18:13:39 +020011238 fcn = ctx->fcn;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011239
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011240 /* Execute the function. */
11241 switch (hlua_ctx_resume(hlua, 1)) {
11242
11243 /* finished. */
11244 case HLUA_E_OK:
11245 return 1;
11246
11247 /* yield. */
11248 case HLUA_E_AGAIN:
11249 /* We want write. */
11250 if (HLUA_IS_WAKERESWR(hlua))
Christopher Faulet7b3d38a2023-05-05 11:28:45 +020011251 sc_need_room(sc, -1);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011252 /* Set the timeout. */
11253 if (hlua->wake_time != TICK_ETERNITY)
11254 task_schedule(hlua->task, hlua->wake_time);
11255 return 0;
11256
11257 /* finished with error. */
11258 case HLUA_E_ERRMSG:
11259 /* Display log. */
11260 SEND_ERR(NULL, "Lua cli '%s': %s.\n",
11261 fcn->name, lua_tostring(hlua->T, -1));
11262 lua_pop(hlua->T, 1);
11263 return 1;
11264
Thierry Fournierd5b073c2018-05-21 19:42:47 +020011265 case HLUA_E_ETMOUT:
11266 SEND_ERR(NULL, "Lua converter '%s': execution timeout.\n",
11267 fcn->name);
11268 return 1;
11269
11270 case HLUA_E_NOMEM:
11271 SEND_ERR(NULL, "Lua converter '%s': out of memory error.\n",
11272 fcn->name);
11273 return 1;
11274
11275 case HLUA_E_YIELD: /* unexpected */
11276 SEND_ERR(NULL, "Lua converter '%s': yield not allowed.\n",
11277 fcn->name);
11278 return 1;
11279
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011280 case HLUA_E_ERR:
11281 /* Display log. */
11282 SEND_ERR(NULL, "Lua cli '%s' return an unknown error.\n",
11283 fcn->name);
11284 return 1;
11285
11286 default:
11287 return 1;
11288 }
11289
11290 return 1;
11291}
11292
11293static void hlua_cli_io_release_fct(struct appctx *appctx)
11294{
Willy Tarreaubcda5f62022-05-03 18:13:39 +020011295 struct hlua_cli_ctx *ctx = appctx->svcctx;
11296
11297 hlua_ctx_destroy(ctx->hlua);
11298 ctx->hlua = NULL;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011299}
11300
11301/* This function is an LUA binding used for registering
11302 * new keywords in the cli. It expects a list of keywords
11303 * which are the "path". It is limited to 5 keywords. A
11304 * description of the command, a function to be executed
11305 * for the parsing and a function for io handlers.
11306 */
11307__LJMP static int hlua_register_cli(lua_State *L)
11308{
11309 struct cli_kw_list *cli_kws;
11310 const char *message;
11311 int ref_io;
11312 int len;
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020011313 struct hlua_function *fcn = NULL;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011314 int index;
11315 int i;
Thierry Fournierf67442e2020-11-28 20:41:07 +010011316 struct buffer *trash;
11317 const char *kw[5];
11318 struct cli_kw *cli_kw;
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020011319 const char *errmsg;
Willy Tarreau22450af2023-04-07 15:27:55 +020011320 char *end;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011321
11322 MAY_LJMP(check_args(L, 3, "register_cli"));
11323
Aurelien DARRAGON87f52972023-02-24 09:43:54 +010011324 if (hlua_gethlua(L)) {
11325 /* runtime processing */
11326 WILL_LJMP(luaL_error(L, "register_cli: not available outside of body context"));
11327 }
11328
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011329 /* First argument : an array of maximum 5 keywords. */
11330 if (!lua_istable(L, 1))
11331 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table"));
11332
11333 /* Second argument : string with contextual message. */
11334 message = MAY_LJMP(luaL_checkstring(L, 2));
11335
11336 /* Third and fourth argument : lua function. */
11337 ref_io = MAY_LJMP(hlua_checkfunction(L, 3));
11338
Thierry Fournierf67442e2020-11-28 20:41:07 +010011339 /* Check for CLI service already registered */
11340 trash = get_trash_chunk();
11341 index = 0;
11342 lua_pushnil(L);
11343 memset(kw, 0, sizeof(kw));
11344 while (lua_next(L, 1) != 0) {
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +010011345 if (index >= CLI_PREFIX_KW_NB) {
11346 hlua_unref(L, ref_io);
Thierry Fournierf67442e2020-11-28 20:41:07 +010011347 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 +010011348 }
11349 if (lua_type(L, -1) != LUA_TSTRING) {
11350 hlua_unref(L, ref_io);
Thierry Fournierf67442e2020-11-28 20:41:07 +010011351 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table filled with strings"));
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +010011352 }
Thierry Fournierf67442e2020-11-28 20:41:07 +010011353 kw[index] = lua_tostring(L, -1);
11354 if (index == 0)
11355 chunk_printf(trash, "%s", kw[index]);
11356 else
11357 chunk_appendf(trash, " %s", kw[index]);
11358 index++;
11359 lua_pop(L, 1);
11360 }
11361 cli_kw = cli_find_kw_exact((char **)kw);
11362 if (cli_kw != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +010011363 fcn = cli_kw->private;
11364 if (fcn->function_ref[hlua_state_id] != -1) {
11365 ha_warning("Trying to register CLI keyword 'lua.%s' more than once. "
11366 "This will become a hard error in version 2.5.\n", trash->area);
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +010011367 hlua_unref(L, fcn->function_ref[hlua_state_id]);
Thierry Fournier59f11be2020-11-29 00:37:41 +010011368 }
11369 fcn->function_ref[hlua_state_id] = ref_io;
11370 return 0;
Thierry Fournierf67442e2020-11-28 20:41:07 +010011371 }
11372
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011373 /* Allocate and fill the sample fetch keyword struct. */
11374 cli_kws = calloc(1, sizeof(*cli_kws) + sizeof(struct cli_kw) * 2);
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020011375 if (!cli_kws) {
11376 errmsg = "Lua out of memory error.";
11377 goto error;
11378 }
Thierry Fournier62a22aa2020-11-28 21:06:35 +010011379 fcn = new_hlua_function();
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020011380 if (!fcn) {
11381 errmsg = "Lua out of memory error.";
11382 goto error;
11383 }
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011384
11385 /* Fill path. */
11386 index = 0;
11387 lua_pushnil(L);
11388 while(lua_next(L, 1) != 0) {
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020011389 if (index >= 5) {
11390 errmsg = "1st argument must be a table with a maximum of 5 entries";
11391 goto error;
11392 }
11393 if (lua_type(L, -1) != LUA_TSTRING) {
11394 errmsg = "1st argument must be a table filled with strings";
11395 goto error;
11396 }
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011397 cli_kws->kw[0].str_kw[index] = strdup(lua_tostring(L, -1));
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020011398 if (!cli_kws->kw[0].str_kw[index]) {
11399 errmsg = "Lua out of memory error.";
11400 goto error;
11401 }
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011402 index++;
11403 lua_pop(L, 1);
11404 }
11405
11406 /* Copy help message. */
11407 cli_kws->kw[0].usage = strdup(message);
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020011408 if (!cli_kws->kw[0].usage) {
11409 errmsg = "Lua out of memory error.";
11410 goto error;
11411 }
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011412
11413 /* Fill fcn io handler. */
11414 len = strlen("<lua.cli>") + 1;
11415 for (i = 0; i < index; i++)
11416 len += strlen(cli_kws->kw[0].str_kw[i]) + 1;
11417 fcn->name = calloc(1, len);
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020011418 if (!fcn->name) {
11419 errmsg = "Lua out of memory error.";
11420 goto error;
11421 }
Willy Tarreau22450af2023-04-07 15:27:55 +020011422
11423 end = fcn->name;
11424 len = 8;
11425 memcpy(end, "<lua.cli", len);
11426 end += len;
11427
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011428 for (i = 0; i < index; i++) {
Willy Tarreau22450af2023-04-07 15:27:55 +020011429 *(end++) = '.';
11430 len = strlen(cli_kws->kw[0].str_kw[i]);
11431 memcpy(end, cli_kws->kw[0].str_kw[i], len);
11432 end += len;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011433 }
Willy Tarreau22450af2023-04-07 15:27:55 +020011434 *(end++) = '>';
11435 *(end++) = 0;
11436
Thierry Fournierc7492592020-11-28 23:57:24 +010011437 fcn->function_ref[hlua_state_id] = ref_io;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011438
11439 /* Fill last entries. */
11440 cli_kws->kw[0].private = fcn;
11441 cli_kws->kw[0].parse = hlua_cli_parse_fct;
11442 cli_kws->kw[0].io_handler = hlua_cli_io_handler_fct;
11443 cli_kws->kw[0].io_release = hlua_cli_io_release_fct;
11444
11445 /* Register this new converter */
11446 cli_register_kw(cli_kws);
11447
11448 return 0;
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020011449
11450 error:
11451 release_hlua_function(fcn);
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +010011452 hlua_unref(L, ref_io);
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020011453 if (cli_kws) {
11454 for (i = 0; i < index; i++)
11455 ha_free((char **)&(cli_kws->kw[0].str_kw[i]));
11456 ha_free((char **)&(cli_kws->kw[0].usage));
11457 }
11458 ha_free(&cli_kws);
11459 WILL_LJMP(luaL_error(L, errmsg));
11460 return 0; /* Never reached */
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011461}
11462
Christopher Faulet69c581a2021-05-31 08:54:04 +020011463static int hlua_filter_init_per_thread(struct proxy *px, struct flt_conf *fconf)
11464{
11465 struct hlua_flt_config *conf = fconf->conf;
11466 lua_State *L;
11467 int error, pos, state_id, flt_ref;
11468
11469 state_id = reg_flt_to_stack_id(conf->reg);
11470 L = hlua_states[state_id];
11471 pos = lua_gettop(L);
11472
11473 /* The filter parsing function */
Aurelien DARRAGON4fdf8b52023-03-20 17:22:37 +010011474 hlua_pushref(L, conf->reg->fun_ref[state_id]);
Christopher Faulet69c581a2021-05-31 08:54:04 +020011475
11476 /* Push the filter class on the stack and resolve all callbacks */
Aurelien DARRAGON4fdf8b52023-03-20 17:22:37 +010011477 hlua_pushref(L, conf->reg->flt_ref[state_id]);
Christopher Faulet69c581a2021-05-31 08:54:04 +020011478
11479 /* Duplicate the filter class so each filter will have its own copy */
11480 lua_newtable(L);
11481 lua_pushnil(L);
11482
11483 while (lua_next(L, pos+2)) {
11484 lua_pushvalue(L, -2);
11485 lua_insert(L, -2);
11486 lua_settable(L, -4);
11487 }
Aurelien DARRAGON73d1a982023-03-20 17:42:08 +010011488 flt_ref = hlua_ref(L);
Christopher Faulet69c581a2021-05-31 08:54:04 +020011489
11490 /* Remove the original lua filter class from the stack */
11491 lua_pop(L, 1);
11492
11493 /* Push the copy on the stack */
Aurelien DARRAGON4fdf8b52023-03-20 17:22:37 +010011494 hlua_pushref(L, flt_ref);
Christopher Faulet69c581a2021-05-31 08:54:04 +020011495
11496 /* extra args are pushed in a table */
11497 lua_newtable(L);
11498 for (pos = 0; conf->args[pos]; pos++) {
11499 /* Check stack available size. */
11500 if (!lua_checkstack(L, 1)) {
11501 ha_alert("Lua filter '%s' : Lua error : full stack.", conf->reg->name);
11502 goto error;
11503 }
11504 lua_pushstring(L, conf->args[pos]);
11505 lua_rawseti(L, -2, lua_rawlen(L, -2) + 1);
11506 }
11507
11508 error = lua_pcall(L, 2, LUA_MULTRET, 0);
11509 switch (error) {
11510 case LUA_OK:
11511 /* replace the filter ref */
11512 conf->ref[state_id] = flt_ref;
11513 break;
11514 case LUA_ERRRUN:
11515 ha_alert("Lua filter '%s' : runtime error : %s", conf->reg->name, lua_tostring(L, -1));
11516 goto error;
11517 case LUA_ERRMEM:
11518 ha_alert("Lua filter '%s' : out of memory error", conf->reg->name);
11519 goto error;
11520 case LUA_ERRERR:
11521 ha_alert("Lua filter '%s' : message handler error : %s", conf->reg->name, lua_tostring(L, -1));
11522 goto error;
11523#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM <= 503
11524 case LUA_ERRGCMM:
11525 ha_alert("Lua filter '%s' : garbage collector error : %s", conf->reg->name, lua_tostring(L, -1));
11526 goto error;
11527#endif
11528 default:
Ilya Shipitsinff0f2782021-08-22 22:18:07 +050011529 ha_alert("Lua filter '%s' : unknown error : %s", conf->reg->name, lua_tostring(L, -1));
Christopher Faulet69c581a2021-05-31 08:54:04 +020011530 goto error;
11531 }
11532
11533 lua_settop(L, 0);
11534 return 0;
11535
11536 error:
11537 lua_settop(L, 0);
11538 return -1;
11539}
11540
11541static void hlua_filter_deinit_per_thread(struct proxy *px, struct flt_conf *fconf)
11542{
11543 struct hlua_flt_config *conf = fconf->conf;
11544 lua_State *L;
11545 int state_id;
11546
11547 if (!conf)
11548 return;
11549
11550 state_id = reg_flt_to_stack_id(conf->reg);
11551 L = hlua_states[state_id];
Aurelien DARRAGONfde199d2023-03-20 15:09:33 +010011552 hlua_unref(L, conf->ref[state_id]);
Christopher Faulet69c581a2021-05-31 08:54:04 +020011553}
11554
11555static int hlua_filter_init(struct proxy *px, struct flt_conf *fconf)
11556{
11557 struct hlua_flt_config *conf = fconf->conf;
11558 int state_id = reg_flt_to_stack_id(conf->reg);
11559
11560 /* Rely on per-thread init for global scripts */
11561 if (!state_id)
11562 return hlua_filter_init_per_thread(px, fconf);
11563 return 0;
11564}
11565
11566static void hlua_filter_deinit(struct proxy *px, struct flt_conf *fconf)
11567{
11568
11569 if (fconf->conf) {
11570 struct hlua_flt_config *conf = fconf->conf;
11571 int state_id = reg_flt_to_stack_id(conf->reg);
11572 int pos;
11573
11574 /* Rely on per-thread deinit for global scripts */
11575 if (!state_id)
11576 hlua_filter_deinit_per_thread(px, fconf);
11577
11578 for (pos = 0; conf->args[pos]; pos++)
11579 free(conf->args[pos]);
11580 free(conf->args);
11581 }
11582 ha_free(&fconf->conf);
11583 ha_free((char **)&fconf->id);
11584 ha_free(&fconf->ops);
11585}
11586
11587static int hlua_filter_new(struct stream *s, struct filter *filter)
11588{
11589 struct hlua_flt_config *conf = FLT_CONF(filter);
11590 struct hlua_flt_ctx *flt_ctx = NULL;
11591 int ret = 1;
11592
11593 /* In the execution wrappers linked with a stream, the
11594 * Lua context can be not initialized. This behavior
11595 * permits to save performances because a systematic
11596 * Lua initialization cause 5% performances loss.
11597 */
11598 if (!s->hlua) {
11599 struct hlua *hlua;
11600
11601 hlua = pool_alloc(pool_head_hlua);
11602 if (!hlua) {
11603 SEND_ERR(s->be, "Lua filter '%s': can't initialize Lua context.\n",
11604 conf->reg->name);
11605 ret = 0;
11606 goto end;
11607 }
11608 HLUA_INIT(hlua);
11609 s->hlua = hlua;
Aurelien DARRAGON6b0b9bd2023-03-21 14:02:16 +010011610 if (!hlua_ctx_init(s->hlua, reg_flt_to_stack_id(conf->reg), s->task)) {
Christopher Faulet69c581a2021-05-31 08:54:04 +020011611 SEND_ERR(s->be, "Lua filter '%s': can't initialize Lua context.\n",
11612 conf->reg->name);
11613 ret = 0;
11614 goto end;
11615 }
11616 }
11617
11618 flt_ctx = pool_zalloc(pool_head_hlua_flt_ctx);
11619 if (!flt_ctx) {
11620 SEND_ERR(s->be, "Lua filter '%s': can't initialize filter Lua context.\n",
11621 conf->reg->name);
11622 ret = 0;
11623 goto end;
11624 }
11625 flt_ctx->hlua[0] = pool_alloc(pool_head_hlua);
11626 flt_ctx->hlua[1] = pool_alloc(pool_head_hlua);
11627 if (!flt_ctx->hlua[0] || !flt_ctx->hlua[1]) {
11628 SEND_ERR(s->be, "Lua filter '%s': can't initialize filter Lua context.\n",
11629 conf->reg->name);
11630 ret = 0;
11631 goto end;
11632 }
11633 HLUA_INIT(flt_ctx->hlua[0]);
11634 HLUA_INIT(flt_ctx->hlua[1]);
Aurelien DARRAGON6b0b9bd2023-03-21 14:02:16 +010011635 if (!hlua_ctx_init(flt_ctx->hlua[0], reg_flt_to_stack_id(conf->reg), s->task) ||
11636 !hlua_ctx_init(flt_ctx->hlua[1], reg_flt_to_stack_id(conf->reg), s->task)) {
Christopher Faulet69c581a2021-05-31 08:54:04 +020011637 SEND_ERR(s->be, "Lua filter '%s': can't initialize filter Lua context.\n",
11638 conf->reg->name);
11639 ret = 0;
11640 goto end;
11641 }
11642
11643 if (!HLUA_IS_RUNNING(s->hlua)) {
11644 /* The following Lua calls can fail. */
11645 if (!SET_SAFE_LJMP(s->hlua)) {
11646 const char *error;
11647
11648 if (lua_type(s->hlua->T, -1) == LUA_TSTRING)
11649 error = lua_tostring(s->hlua->T, -1);
11650 else
11651 error = "critical error";
11652 SEND_ERR(s->be, "Lua filter '%s': %s.\n", conf->reg->name, error);
11653 ret = 0;
11654 goto end;
11655 }
11656
11657 /* Check stack size. */
11658 if (!lua_checkstack(s->hlua->T, 1)) {
11659 SEND_ERR(s->be, "Lua filter '%s': full stack.\n", conf->reg->name);
Tim Duesterhus22817382021-09-11 23:17:25 +020011660 RESET_SAFE_LJMP(s->hlua);
Christopher Faulet69c581a2021-05-31 08:54:04 +020011661 ret = 0;
11662 goto end;
11663 }
11664
Aurelien DARRAGON4fdf8b52023-03-20 17:22:37 +010011665 hlua_pushref(s->hlua->T, conf->ref[s->hlua->state_id]);
Christopher Faulet69c581a2021-05-31 08:54:04 +020011666 if (lua_getfield(s->hlua->T, -1, "new") != LUA_TFUNCTION) {
11667 SEND_ERR(s->be, "Lua filter '%s': 'new' field is not a function.\n",
11668 conf->reg->name);
11669 RESET_SAFE_LJMP(s->hlua);
11670 ret = 0;
11671 goto end;
11672 }
11673 lua_insert(s->hlua->T, -2);
11674
11675 /* Push the copy on the stack */
11676 s->hlua->nargs = 1;
11677
11678 /* We must initialize the execution timeouts. */
Aurelien DARRAGONda9503c2022-11-25 09:10:07 +010011679 hlua_timer_init(&s->hlua->timer, hlua_timeout_session);
Christopher Faulet69c581a2021-05-31 08:54:04 +020011680
11681 /* At this point the execution is safe. */
11682 RESET_SAFE_LJMP(s->hlua);
11683 }
11684
11685 switch (hlua_ctx_resume(s->hlua, 0)) {
11686 case HLUA_E_OK:
11687 /* Nothing returned or not a table, ignore the filter for current stream */
11688 if (!lua_gettop(s->hlua->T) || !lua_istable(s->hlua->T, 1)) {
11689 ret = 0;
11690 goto end;
11691 }
11692
11693 /* Attached the filter pointer to the ctx */
11694 lua_pushstring(s->hlua->T, "__filter");
11695 lua_pushlightuserdata(s->hlua->T, filter);
11696 lua_settable(s->hlua->T, -3);
11697
11698 /* Save a ref on the filter ctx */
11699 lua_pushvalue(s->hlua->T, 1);
Aurelien DARRAGON73d1a982023-03-20 17:42:08 +010011700 flt_ctx->ref = hlua_ref(s->hlua->T);
Christopher Faulet69c581a2021-05-31 08:54:04 +020011701 filter->ctx = flt_ctx;
11702 break;
11703 case HLUA_E_ERRMSG:
11704 SEND_ERR(s->be, "Lua filter '%s' : %s.\n", conf->reg->name, lua_tostring(s->hlua->T, -1));
11705 ret = -1;
11706 goto end;
11707 case HLUA_E_ETMOUT:
11708 SEND_ERR(s->be, "Lua filter '%s' : 'new' execution timeout.\n", conf->reg->name);
11709 ret = 0;
11710 goto end;
11711 case HLUA_E_NOMEM:
11712 SEND_ERR(s->be, "Lua filter '%s' : out of memory error.\n", conf->reg->name);
11713 ret = 0;
11714 goto end;
11715 case HLUA_E_AGAIN:
11716 case HLUA_E_YIELD:
11717 SEND_ERR(s->be, "Lua filter '%s': yield functions like core.tcp() or core.sleep()"
11718 " are not allowed from 'new' function.\n", conf->reg->name);
11719 ret = 0;
11720 goto end;
11721 case HLUA_E_ERR:
11722 SEND_ERR(s->be, "Lua filter '%s': 'new' returns an unknown error.\n", conf->reg->name);
11723 ret = 0;
11724 goto end;
11725 default:
11726 ret = 0;
11727 goto end;
11728 }
11729
11730 end:
11731 if (s->hlua)
11732 lua_settop(s->hlua->T, 0);
11733 if (ret <= 0) {
11734 if (flt_ctx) {
11735 hlua_ctx_destroy(flt_ctx->hlua[0]);
11736 hlua_ctx_destroy(flt_ctx->hlua[1]);
11737 pool_free(pool_head_hlua_flt_ctx, flt_ctx);
11738 }
11739 }
11740 return ret;
11741}
11742
11743static void hlua_filter_delete(struct stream *s, struct filter *filter)
11744{
11745 struct hlua_flt_ctx *flt_ctx = filter->ctx;
11746
Aurelien DARRAGONfde199d2023-03-20 15:09:33 +010011747 hlua_unref(s->hlua->T, flt_ctx->ref);
Christopher Faulet69c581a2021-05-31 08:54:04 +020011748 hlua_ctx_destroy(flt_ctx->hlua[0]);
11749 hlua_ctx_destroy(flt_ctx->hlua[1]);
11750 pool_free(pool_head_hlua_flt_ctx, flt_ctx);
11751 filter->ctx = NULL;
11752}
11753
Christopher Faulet9f55a502020-02-25 15:21:02 +010011754static int hlua_filter_from_payload(struct filter *filter)
11755{
11756 struct hlua_flt_ctx *flt_ctx = filter->ctx;
11757
11758 return (flt_ctx && !!(flt_ctx->flags & HLUA_FLT_CTX_FL_PAYLOAD));
11759}
11760
Christopher Fauletc404f112020-02-26 15:03:09 +010011761static int hlua_filter_callback(struct stream *s, struct filter *filter, const char *fun,
11762 int dir, unsigned int flags)
11763{
11764 struct hlua *flt_hlua;
11765 struct hlua_flt_config *conf = FLT_CONF(filter);
11766 struct hlua_flt_ctx *flt_ctx = filter->ctx;
11767 unsigned int hflags = HLUA_TXN_FLT_CTX;
11768 int ret = 1;
11769
11770 flt_hlua = flt_ctx->hlua[(dir == SMP_OPT_DIR_REQ ? 0 : 1)];
11771 if (!flt_hlua)
11772 goto end;
11773
11774 if (!HLUA_IS_RUNNING(flt_hlua)) {
11775 int extra_idx = lua_gettop(flt_hlua->T);
11776
11777 /* The following Lua calls can fail. */
11778 if (!SET_SAFE_LJMP(flt_hlua)) {
11779 const char *error;
11780
11781 if (lua_type(flt_hlua->T, -1) == LUA_TSTRING)
11782 error = lua_tostring(flt_hlua->T, -1);
11783 else
11784 error = "critical error";
11785 SEND_ERR(s->be, "Lua filter '%s': %s.\n", conf->reg->name, error);
11786 goto end;
11787 }
11788
11789 /* Check stack size. */
11790 if (!lua_checkstack(flt_hlua->T, 3)) {
11791 SEND_ERR(s->be, "Lua filter '%s': full stack.\n", conf->reg->name);
11792 RESET_SAFE_LJMP(flt_hlua);
11793 goto end;
11794 }
11795
Aurelien DARRAGON4fdf8b52023-03-20 17:22:37 +010011796 hlua_pushref(flt_hlua->T, flt_ctx->ref);
Christopher Fauletc404f112020-02-26 15:03:09 +010011797 if (lua_getfield(flt_hlua->T, -1, fun) != LUA_TFUNCTION) {
11798 RESET_SAFE_LJMP(flt_hlua);
11799 goto end;
11800 }
11801 lua_insert(flt_hlua->T, -2);
11802
11803 if (!hlua_txn_new(flt_hlua->T, s, s->be, dir, hflags)) {
11804 SEND_ERR(s->be, "Lua filter '%s': full stack.\n", conf->reg->name);
11805 RESET_SAFE_LJMP(flt_hlua);
11806 goto end;
11807 }
11808 flt_hlua->nargs = 2;
11809
11810 if (flags & HLUA_FLT_CB_ARG_CHN) {
11811 if (dir == SMP_OPT_DIR_REQ)
11812 lua_getfield(flt_hlua->T, -1, "req");
11813 else
11814 lua_getfield(flt_hlua->T, -1, "res");
11815 if (lua_type(flt_hlua->T, -1) == LUA_TTABLE) {
11816 lua_pushstring(flt_hlua->T, "__filter");
11817 lua_pushlightuserdata(flt_hlua->T, filter);
11818 lua_settable(flt_hlua->T, -3);
11819 }
11820 flt_hlua->nargs++;
11821 }
11822 else if (flags & HLUA_FLT_CB_ARG_HTTP_MSG) {
Christopher Fauleteae8afa2020-02-26 17:15:48 +010011823 if (dir == SMP_OPT_DIR_REQ)
11824 lua_getfield(flt_hlua->T, -1, "http_req");
11825 else
11826 lua_getfield(flt_hlua->T, -1, "http_res");
11827 if (lua_type(flt_hlua->T, -1) == LUA_TTABLE) {
11828 lua_pushstring(flt_hlua->T, "__filter");
11829 lua_pushlightuserdata(flt_hlua->T, filter);
11830 lua_settable(flt_hlua->T, -3);
11831 }
11832 flt_hlua->nargs++;
Christopher Fauletc404f112020-02-26 15:03:09 +010011833 }
11834
11835 /* Check stack size. */
11836 if (!lua_checkstack(flt_hlua->T, 1)) {
11837 SEND_ERR(s->be, "Lua filter '%s': full stack.\n", conf->reg->name);
11838 RESET_SAFE_LJMP(flt_hlua);
11839 goto end;
11840 }
11841
11842 while (extra_idx--) {
11843 lua_pushvalue(flt_hlua->T, 1);
11844 lua_remove(flt_hlua->T, 1);
11845 flt_hlua->nargs++;
11846 }
11847
11848 /* We must initialize the execution timeouts. */
Aurelien DARRAGONda9503c2022-11-25 09:10:07 +010011849 hlua_timer_init(&flt_hlua->timer, hlua_timeout_session);
Christopher Fauletc404f112020-02-26 15:03:09 +010011850
11851 /* At this point the execution is safe. */
11852 RESET_SAFE_LJMP(flt_hlua);
11853 }
11854
11855 switch (hlua_ctx_resume(flt_hlua, !(flags & HLUA_FLT_CB_FINAL))) {
11856 case HLUA_E_OK:
11857 /* Catch the return value if it required */
11858 if ((flags & HLUA_FLT_CB_RETVAL) && lua_gettop(flt_hlua->T) > 0) {
11859 ret = lua_tointeger(flt_hlua->T, -1);
11860 lua_settop(flt_hlua->T, 0); /* Empty the stack. */
11861 }
11862
11863 /* Set timeout in the required channel. */
11864 if (flt_hlua->wake_time != TICK_ETERNITY) {
11865 if (dir == SMP_OPT_DIR_REQ)
11866 s->req.analyse_exp = flt_hlua->wake_time;
11867 else
11868 s->res.analyse_exp = flt_hlua->wake_time;
11869 }
11870 break;
11871 case HLUA_E_AGAIN:
11872 /* Set timeout in the required channel. */
11873 if (flt_hlua->wake_time != TICK_ETERNITY) {
11874 if (dir == SMP_OPT_DIR_REQ)
11875 s->req.analyse_exp = flt_hlua->wake_time;
11876 else
11877 s->res.analyse_exp = flt_hlua->wake_time;
11878 }
11879 /* Some actions can be wake up when a "write" event
11880 * is detected on a response channel. This is useful
11881 * only for actions targeted on the requests.
11882 */
11883 if (HLUA_IS_WAKERESWR(flt_hlua))
11884 s->res.flags |= CF_WAKE_WRITE;
11885 if (HLUA_IS_WAKEREQWR(flt_hlua))
11886 s->req.flags |= CF_WAKE_WRITE;
11887 ret = 0;
11888 goto end;
11889 case HLUA_E_ERRMSG:
11890 SEND_ERR(s->be, "Lua filter '%s' : %s.\n", conf->reg->name, lua_tostring(flt_hlua->T, -1));
11891 ret = -1;
11892 goto end;
11893 case HLUA_E_ETMOUT:
11894 SEND_ERR(s->be, "Lua filter '%s' : '%s' callback execution timeout.\n", conf->reg->name, fun);
11895 goto end;
11896 case HLUA_E_NOMEM:
11897 SEND_ERR(s->be, "Lua filter '%s' : out of memory error.\n", conf->reg->name);
11898 goto end;
11899 case HLUA_E_YIELD:
11900 SEND_ERR(s->be, "Lua filter '%s': yield functions like core.tcp() or core.sleep()"
11901 " are not allowed from '%s' callback.\n", conf->reg->name, fun);
11902 goto end;
11903 case HLUA_E_ERR:
11904 SEND_ERR(s->be, "Lua filter '%s': '%s' returns an unknown error.\n", conf->reg->name, fun);
11905 goto end;
11906 default:
11907 goto end;
11908 }
11909
11910
11911 end:
11912 return ret;
11913}
11914
11915static int hlua_filter_start_analyze(struct stream *s, struct filter *filter, struct channel *chn)
11916{
11917 struct hlua_flt_ctx *flt_ctx = filter->ctx;
11918
11919 flt_ctx->flags = 0;
11920 return hlua_filter_callback(s, filter, "start_analyze",
11921 (!(chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES),
11922 (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_RETVAL | HLUA_FLT_CB_ARG_CHN));
11923}
11924
11925static int hlua_filter_end_analyze(struct stream *s, struct filter *filter, struct channel *chn)
11926{
11927 struct hlua_flt_ctx *flt_ctx = filter->ctx;
11928
11929 flt_ctx->flags &= ~HLUA_FLT_CTX_FL_PAYLOAD;
11930 return hlua_filter_callback(s, filter, "end_analyze",
11931 (!(chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES),
11932 (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_RETVAL | HLUA_FLT_CB_ARG_CHN));
11933}
11934
Christopher Fauleteae8afa2020-02-26 17:15:48 +010011935static int hlua_filter_http_headers(struct stream *s, struct filter *filter, struct http_msg *msg)
11936{
11937 struct hlua_flt_ctx *flt_ctx = filter->ctx;
11938
11939 flt_ctx->flags &= ~HLUA_FLT_CTX_FL_PAYLOAD;
11940 return hlua_filter_callback(s, filter, "http_headers",
11941 (!(msg->chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES),
11942 (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_RETVAL | HLUA_FLT_CB_ARG_HTTP_MSG));
11943}
11944
11945static int hlua_filter_http_payload(struct stream *s, struct filter *filter, struct http_msg *msg,
11946 unsigned int offset, unsigned int len)
11947{
11948 struct hlua_flt_ctx *flt_ctx = filter->ctx;
11949 struct hlua *flt_hlua;
11950 int dir = (!(msg->chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES);
11951 int idx = (dir == SMP_OPT_DIR_REQ ? 0 : 1);
11952 int ret;
11953
11954 flt_hlua = flt_ctx->hlua[idx];
11955 flt_ctx->cur_off[idx] = offset;
11956 flt_ctx->cur_len[idx] = len;
11957 flt_ctx->flags |= HLUA_FLT_CTX_FL_PAYLOAD;
11958 ret = hlua_filter_callback(s, filter, "http_payload", dir, (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_ARG_HTTP_MSG));
11959 if (ret != -1) {
11960 ret = flt_ctx->cur_len[idx];
11961 if (lua_gettop(flt_hlua->T) > 0) {
11962 ret = lua_tointeger(flt_hlua->T, -1);
11963 if (ret > flt_ctx->cur_len[idx])
11964 ret = flt_ctx->cur_len[idx];
11965 lua_settop(flt_hlua->T, 0); /* Empty the stack. */
11966 }
11967 }
11968 return ret;
11969}
11970
11971static int hlua_filter_http_end(struct stream *s, struct filter *filter, struct http_msg *msg)
11972{
11973 struct hlua_flt_ctx *flt_ctx = filter->ctx;
11974
11975 flt_ctx->flags &= ~HLUA_FLT_CTX_FL_PAYLOAD;
11976 return hlua_filter_callback(s, filter, "http_end",
11977 (!(msg->chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES),
11978 (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_RETVAL | HLUA_FLT_CB_ARG_HTTP_MSG));
11979}
11980
Christopher Fauletc404f112020-02-26 15:03:09 +010011981static int hlua_filter_tcp_payload(struct stream *s, struct filter *filter, struct channel *chn,
11982 unsigned int offset, unsigned int len)
11983{
11984 struct hlua_flt_ctx *flt_ctx = filter->ctx;
11985 struct hlua *flt_hlua;
11986 int dir = (!(chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES);
11987 int idx = (dir == SMP_OPT_DIR_REQ ? 0 : 1);
11988 int ret;
11989
11990 flt_hlua = flt_ctx->hlua[idx];
11991 flt_ctx->cur_off[idx] = offset;
11992 flt_ctx->cur_len[idx] = len;
11993 flt_ctx->flags |= HLUA_FLT_CTX_FL_PAYLOAD;
11994 ret = hlua_filter_callback(s, filter, "tcp_payload", dir, (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_ARG_CHN));
11995 if (ret != -1) {
11996 ret = flt_ctx->cur_len[idx];
11997 if (lua_gettop(flt_hlua->T) > 0) {
11998 ret = lua_tointeger(flt_hlua->T, -1);
11999 if (ret > flt_ctx->cur_len[idx])
12000 ret = flt_ctx->cur_len[idx];
12001 lua_settop(flt_hlua->T, 0); /* Empty the stack. */
12002 }
12003 }
12004 return ret;
12005}
12006
Christopher Faulet69c581a2021-05-31 08:54:04 +020012007static int hlua_filter_parse_fct(char **args, int *cur_arg, struct proxy *px,
12008 struct flt_conf *fconf, char **err, void *private)
12009{
12010 struct hlua_reg_filter *reg_flt = private;
12011 lua_State *L;
12012 struct hlua_flt_config *conf = NULL;
12013 const char *flt_id = NULL;
12014 int state_id, pos, flt_flags = 0;
12015 struct flt_ops *hlua_flt_ops = NULL;
12016
12017 state_id = reg_flt_to_stack_id(reg_flt);
12018 L = hlua_states[state_id];
12019
12020 /* Initialize the filter ops with default callbacks */
12021 hlua_flt_ops = calloc(1, sizeof(*hlua_flt_ops));
Christopher Fauletc86bb872021-08-13 08:33:57 +020012022 if (!hlua_flt_ops)
12023 goto error;
Christopher Faulet69c581a2021-05-31 08:54:04 +020012024 hlua_flt_ops->init = hlua_filter_init;
12025 hlua_flt_ops->deinit = hlua_filter_deinit;
12026 if (state_id) {
12027 /* Set per-thread callback if script is loaded per-thread */
12028 hlua_flt_ops->init_per_thread = hlua_filter_init_per_thread;
12029 hlua_flt_ops->deinit_per_thread = hlua_filter_deinit_per_thread;
12030 }
12031 hlua_flt_ops->attach = hlua_filter_new;
12032 hlua_flt_ops->detach = hlua_filter_delete;
12033
12034 /* Push the filter class on the stack and resolve all callbacks */
Aurelien DARRAGON4fdf8b52023-03-20 17:22:37 +010012035 hlua_pushref(L, reg_flt->flt_ref[state_id]);
Christopher Faulet69c581a2021-05-31 08:54:04 +020012036
Christopher Fauletc404f112020-02-26 15:03:09 +010012037 if (lua_getfield(L, -1, "start_analyze") == LUA_TFUNCTION)
12038 hlua_flt_ops->channel_start_analyze = hlua_filter_start_analyze;
12039 lua_pop(L, 1);
12040 if (lua_getfield(L, -1, "end_analyze") == LUA_TFUNCTION)
12041 hlua_flt_ops->channel_end_analyze = hlua_filter_end_analyze;
12042 lua_pop(L, 1);
Christopher Fauleteae8afa2020-02-26 17:15:48 +010012043 if (lua_getfield(L, -1, "http_headers") == LUA_TFUNCTION)
12044 hlua_flt_ops->http_headers = hlua_filter_http_headers;
12045 lua_pop(L, 1);
12046 if (lua_getfield(L, -1, "http_payload") == LUA_TFUNCTION)
12047 hlua_flt_ops->http_payload = hlua_filter_http_payload;
12048 lua_pop(L, 1);
12049 if (lua_getfield(L, -1, "http_end") == LUA_TFUNCTION)
12050 hlua_flt_ops->http_end = hlua_filter_http_end;
12051 lua_pop(L, 1);
Christopher Fauletc404f112020-02-26 15:03:09 +010012052 if (lua_getfield(L, -1, "tcp_payload") == LUA_TFUNCTION)
12053 hlua_flt_ops->tcp_payload = hlua_filter_tcp_payload;
12054 lua_pop(L, 1);
Christopher Faulet69c581a2021-05-31 08:54:04 +020012055
12056 /* Get id and flags of the filter class */
12057 if (lua_getfield(L, -1, "id") == LUA_TSTRING)
12058 flt_id = lua_tostring(L, -1);
12059 lua_pop(L, 1);
12060 if (lua_getfield(L, -1, "flags") == LUA_TNUMBER)
12061 flt_flags = lua_tointeger(L, -1);
12062 lua_pop(L, 1);
12063
12064 /* Create the filter config */
12065 conf = calloc(1, sizeof(*conf));
Christopher Fauletc86bb872021-08-13 08:33:57 +020012066 if (!conf)
Christopher Faulet69c581a2021-05-31 08:54:04 +020012067 goto error;
Christopher Faulet69c581a2021-05-31 08:54:04 +020012068 conf->reg = reg_flt;
12069
12070 /* duplicate args */
12071 for (pos = 0; *args[*cur_arg + 1 + pos]; pos++);
12072 conf->args = calloc(pos + 1, sizeof(*conf->args));
Christopher Fauletc86bb872021-08-13 08:33:57 +020012073 if (!conf->args)
12074 goto error;
12075 for (pos = 0; *args[*cur_arg + 1 + pos]; pos++) {
Christopher Faulet69c581a2021-05-31 08:54:04 +020012076 conf->args[pos] = strdup(args[*cur_arg + 1 + pos]);
Christopher Fauletc86bb872021-08-13 08:33:57 +020012077 if (!conf->args[pos])
12078 goto error;
12079 }
Christopher Faulet69c581a2021-05-31 08:54:04 +020012080 conf->args[pos] = NULL;
12081 *cur_arg += pos + 1;
12082
Christopher Fauletc86bb872021-08-13 08:33:57 +020012083 if (flt_id) {
12084 fconf->id = strdup(flt_id);
12085 if (!fconf->id)
12086 goto error;
12087 }
Christopher Faulet69c581a2021-05-31 08:54:04 +020012088 fconf->flags = flt_flags;
12089 fconf->conf = conf;
12090 fconf->ops = hlua_flt_ops;
12091
12092 lua_settop(L, 0);
12093 return 0;
12094
12095 error:
Christopher Fauletc86bb872021-08-13 08:33:57 +020012096 memprintf(err, "Lua filter '%s' : Lua out of memory error", reg_flt->name);
Christopher Faulet69c581a2021-05-31 08:54:04 +020012097 free(hlua_flt_ops);
Christopher Fauletc86bb872021-08-13 08:33:57 +020012098 if (conf && conf->args) {
12099 for (pos = 0; conf->args[pos]; pos++)
12100 free(conf->args[pos]);
12101 free(conf->args);
12102 }
Christopher Faulet69c581a2021-05-31 08:54:04 +020012103 free(conf);
Christopher Fauletc86bb872021-08-13 08:33:57 +020012104 free((char *)fconf->id);
Christopher Faulet69c581a2021-05-31 08:54:04 +020012105 lua_settop(L, 0);
12106 return -1;
12107}
12108
Christopher Fauletc404f112020-02-26 15:03:09 +010012109__LJMP static int hlua_register_data_filter(lua_State *L)
12110{
12111 struct filter *filter;
12112 struct channel *chn;
12113
12114 MAY_LJMP(check_args(L, 2, "register_data_filter"));
12115 MAY_LJMP(luaL_checktype(L, 1, LUA_TTABLE));
12116 chn = MAY_LJMP(hlua_checkchannel(L, 2));
12117
12118 lua_getfield(L, 1, "__filter");
12119 MAY_LJMP(luaL_checktype(L, -1, LUA_TLIGHTUSERDATA));
12120 filter = lua_touserdata (L, -1);
12121 lua_pop(L, 1);
12122
12123 register_data_filter(chn_strm(chn), chn, filter);
12124 return 1;
12125}
12126
12127__LJMP static int hlua_unregister_data_filter(lua_State *L)
12128{
12129 struct filter *filter;
12130 struct channel *chn;
12131
12132 MAY_LJMP(check_args(L, 2, "unregister_data_filter"));
12133 MAY_LJMP(luaL_checktype(L, 1, LUA_TTABLE));
12134 chn = MAY_LJMP(hlua_checkchannel(L, 2));
12135
12136 lua_getfield(L, 1, "__filter");
12137 MAY_LJMP(luaL_checktype(L, -1, LUA_TLIGHTUSERDATA));
12138 filter = lua_touserdata (L, -1);
12139 lua_pop(L, 1);
12140
12141 unregister_data_filter(chn_strm(chn), chn, filter);
12142 return 1;
12143}
12144
Christopher Faulet69c581a2021-05-31 08:54:04 +020012145/* This function is an LUA binding used for registering a filter. It expects a
Ilya Shipitsinff0f2782021-08-22 22:18:07 +050012146 * filter name used in the haproxy configuration file and a LUA function to
Christopher Faulet69c581a2021-05-31 08:54:04 +020012147 * parse configuration arguments.
12148 */
12149__LJMP static int hlua_register_filter(lua_State *L)
12150{
12151 struct buffer *trash;
12152 struct flt_kw_list *fkl;
12153 struct flt_kw *fkw;
12154 const char *name;
12155 struct hlua_reg_filter *reg_flt= NULL;
12156 int flt_ref, fun_ref;
12157 int len;
12158
12159 MAY_LJMP(check_args(L, 3, "register_filter"));
12160
Aurelien DARRAGON87f52972023-02-24 09:43:54 +010012161 if (hlua_gethlua(L)) {
12162 /* runtime processing */
12163 WILL_LJMP(luaL_error(L, "register_filter: not available outside of body context"));
12164 }
12165
Christopher Faulet69c581a2021-05-31 08:54:04 +020012166 /* First argument : filter name. */
12167 name = MAY_LJMP(luaL_checkstring(L, 1));
12168
12169 /* Second argument : The filter class */
12170 flt_ref = MAY_LJMP(hlua_checktable(L, 2));
12171
12172 /* Third argument : lua function. */
12173 fun_ref = MAY_LJMP(hlua_checkfunction(L, 3));
12174
12175 trash = get_trash_chunk();
12176 chunk_printf(trash, "lua.%s", name);
12177 fkw = flt_find_kw(trash->area);
12178 if (fkw != NULL) {
12179 reg_flt = fkw->private;
12180 if (reg_flt->flt_ref[hlua_state_id] != -1 || reg_flt->fun_ref[hlua_state_id] != -1) {
12181 ha_warning("Trying to register filter 'lua.%s' more than once. "
12182 "This will become a hard error in version 2.5.\n", name);
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +010012183 if (reg_flt->flt_ref[hlua_state_id] != -1)
12184 hlua_unref(L, reg_flt->flt_ref[hlua_state_id]);
12185 if (reg_flt->fun_ref[hlua_state_id] != -1)
12186 hlua_unref(L, reg_flt->fun_ref[hlua_state_id]);
Christopher Faulet69c581a2021-05-31 08:54:04 +020012187 }
12188 reg_flt->flt_ref[hlua_state_id] = flt_ref;
12189 reg_flt->fun_ref[hlua_state_id] = fun_ref;
12190 return 0;
12191 }
12192
12193 fkl = calloc(1, sizeof(*fkl) + sizeof(struct flt_kw) * 2);
12194 if (!fkl)
12195 goto alloc_error;
12196 fkl->scope = "HLUA";
12197
12198 reg_flt = new_hlua_reg_filter(name);
12199 if (!reg_flt)
12200 goto alloc_error;
12201
12202 reg_flt->flt_ref[hlua_state_id] = flt_ref;
12203 reg_flt->fun_ref[hlua_state_id] = fun_ref;
12204
12205 /* The filter keyword */
12206 len = strlen("lua.") + strlen(name) + 1;
12207 fkl->kw[0].kw = calloc(1, len);
12208 if (!fkl->kw[0].kw)
12209 goto alloc_error;
12210
12211 snprintf((char *)fkl->kw[0].kw, len, "lua.%s", name);
12212
12213 fkl->kw[0].parse = hlua_filter_parse_fct;
12214 fkl->kw[0].private = reg_flt;
12215 memset(&fkl->kw[1], 0, sizeof(*fkl->kw));
12216
12217 /* Register this new filter */
12218 flt_register_keywords(fkl);
12219
12220 return 0;
12221
12222 alloc_error:
12223 release_hlua_reg_filter(reg_flt);
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +010012224 hlua_unref(L, flt_ref);
12225 hlua_unref(L, fun_ref);
Christopher Faulet69c581a2021-05-31 08:54:04 +020012226 ha_free(&fkl);
12227 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
12228 return 0; /* Never reached */
12229}
12230
Thierry FOURNIERbd413492015-03-03 16:52:26 +010012231static int hlua_read_timeout(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010012232 const struct proxy *defpx, const char *file, int line,
Thierry FOURNIERbd413492015-03-03 16:52:26 +010012233 char **err, unsigned int *timeout)
12234{
12235 const char *error;
12236
12237 error = parse_time_err(args[1], timeout, TIME_UNIT_MS);
Willy Tarreau9faebe32019-06-07 19:00:37 +020012238 if (error == PARSE_TIME_OVER) {
12239 memprintf(err, "timer overflow in argument <%s> to <%s> (maximum value is 2147483647 ms or ~24.8 days)",
12240 args[1], args[0]);
12241 return -1;
12242 }
12243 else if (error == PARSE_TIME_UNDER) {
12244 memprintf(err, "timer underflow in argument <%s> to <%s> (minimum non-null value is 1 ms)",
12245 args[1], args[0]);
12246 return -1;
12247 }
12248 else if (error) {
Thierry FOURNIERbd413492015-03-03 16:52:26 +010012249 memprintf(err, "%s: invalid timeout", args[0]);
12250 return -1;
12251 }
12252 return 0;
12253}
12254
Aurelien DARRAGON58e36e52023-04-06 22:51:56 +020012255static int hlua_burst_timeout(char **args, int section_type, struct proxy *curpx,
12256 const struct proxy *defpx, const char *file, int line,
12257 char **err)
12258{
12259 return hlua_read_timeout(args, section_type, curpx, defpx,
12260 file, line, err, &hlua_timeout_burst);
12261}
12262
Thierry FOURNIERbd413492015-03-03 16:52:26 +010012263static int hlua_session_timeout(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010012264 const struct proxy *defpx, const char *file, int line,
Thierry FOURNIERbd413492015-03-03 16:52:26 +010012265 char **err)
12266{
12267 return hlua_read_timeout(args, section_type, curpx, defpx,
12268 file, line, err, &hlua_timeout_session);
12269}
12270
12271static int hlua_task_timeout(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010012272 const struct proxy *defpx, const char *file, int line,
Thierry FOURNIERbd413492015-03-03 16:52:26 +010012273 char **err)
12274{
12275 return hlua_read_timeout(args, section_type, curpx, defpx,
12276 file, line, err, &hlua_timeout_task);
12277}
12278
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020012279static int hlua_applet_timeout(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010012280 const struct proxy *defpx, const char *file, int line,
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020012281 char **err)
12282{
12283 return hlua_read_timeout(args, section_type, curpx, defpx,
12284 file, line, err, &hlua_timeout_applet);
12285}
12286
Thierry FOURNIERee9f8022015-03-03 17:37:37 +010012287static int hlua_forced_yield(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010012288 const struct proxy *defpx, const char *file, int line,
Thierry FOURNIERee9f8022015-03-03 17:37:37 +010012289 char **err)
12290{
12291 char *error;
12292
12293 hlua_nb_instruction = strtoll(args[1], &error, 10);
12294 if (*error != '\0') {
12295 memprintf(err, "%s: invalid number", args[0]);
12296 return -1;
12297 }
12298 return 0;
12299}
12300
Willy Tarreau32f61e22015-03-18 17:54:59 +010012301static int hlua_parse_maxmem(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010012302 const struct proxy *defpx, const char *file, int line,
Willy Tarreau32f61e22015-03-18 17:54:59 +010012303 char **err)
12304{
12305 char *error;
12306
12307 if (*(args[1]) == 0) {
Thierry Fournier70e38e92022-09-19 09:01:53 +020012308 memprintf(err, "'%s' expects an integer argument (Lua memory size in MB).", args[0]);
Willy Tarreau32f61e22015-03-18 17:54:59 +010012309 return -1;
12310 }
12311 hlua_global_allocator.limit = strtoll(args[1], &error, 10) * 1024L * 1024L;
12312 if (*error != '\0') {
12313 memprintf(err, "%s: invalid number %s (error at '%c')", args[0], args[1], *error);
12314 return -1;
12315 }
12316 return 0;
12317}
12318
12319
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010012320/* This function is called by the main configuration key "lua-load". It loads and
12321 * execute an lua file during the parsing of the HAProxy configuration file. It is
12322 * the main lua entry point.
12323 *
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -080012324 * This function runs with the HAProxy keywords API. It returns -1 if an error
12325 * occurs, otherwise it returns 0.
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010012326 *
12327 * In some error case, LUA set an error message in top of the stack. This function
12328 * returns this error message in the HAProxy logs and pop it from the stack.
Thierry FOURNIERbabae282015-09-17 11:36:37 +020012329 *
12330 * This function can fail with an abort() due to an Lua critical error.
12331 * We are in the configuration parsing process of HAProxy, this abort() is
12332 * tolerated.
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010012333 */
Thierry Fournierae6b5682022-09-19 09:04:16 +020012334static int hlua_load_state(char **args, lua_State *L, char **err)
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010012335{
12336 int error;
Thierry Fournierae6b5682022-09-19 09:04:16 +020012337 int nargs;
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010012338
12339 /* Just load and compile the file. */
Thierry Fournierae6b5682022-09-19 09:04:16 +020012340 error = luaL_loadfile(L, args[0]);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010012341 if (error) {
Thierry Fournierae6b5682022-09-19 09:04:16 +020012342 memprintf(err, "error in Lua file '%s': %s", args[0], lua_tostring(L, -1));
Thierry Fournierc93c15c2020-11-28 15:02:13 +010012343 lua_pop(L, 1);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010012344 return -1;
12345 }
Thierry Fournierae6b5682022-09-19 09:04:16 +020012346
12347 /* Push args in the Lua stack, except the first one which is the filename */
12348 for (nargs = 1; *(args[nargs]) != 0; nargs++) {
Aurelien DARRAGON4d7aefe2022-09-23 10:22:14 +020012349 /* Check stack size. */
12350 if (!lua_checkstack(L, 1)) {
12351 memprintf(err, "Lua runtime error while loading arguments: stack is full.");
12352 return -1;
12353 }
Thierry Fournierae6b5682022-09-19 09:04:16 +020012354 lua_pushstring(L, args[nargs]);
12355 }
12356 nargs--;
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010012357
12358 /* If no syntax error where detected, execute the code. */
Thierry Fournierae6b5682022-09-19 09:04:16 +020012359 error = lua_pcall(L, nargs, LUA_MULTRET, 0);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010012360 switch (error) {
12361 case LUA_OK:
12362 break;
12363 case LUA_ERRRUN:
Thierry Fournier70e38e92022-09-19 09:01:53 +020012364 memprintf(err, "Lua runtime error: %s", lua_tostring(L, -1));
Thierry Fournierc93c15c2020-11-28 15:02:13 +010012365 lua_pop(L, 1);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010012366 return -1;
12367 case LUA_ERRMEM:
Thierry Fournier70e38e92022-09-19 09:01:53 +020012368 memprintf(err, "Lua out of memory error");
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010012369 return -1;
12370 case LUA_ERRERR:
Thierry Fournier70e38e92022-09-19 09:01:53 +020012371 memprintf(err, "Lua message handler error: %s", lua_tostring(L, -1));
Thierry Fournierc93c15c2020-11-28 15:02:13 +010012372 lua_pop(L, 1);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010012373 return -1;
Christopher Faulet08ed98f2020-07-28 10:33:25 +020012374#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM <= 503
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010012375 case LUA_ERRGCMM:
Thierry Fournier70e38e92022-09-19 09:01:53 +020012376 memprintf(err, "Lua garbage collector error: %s", lua_tostring(L, -1));
Thierry Fournierc93c15c2020-11-28 15:02:13 +010012377 lua_pop(L, 1);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010012378 return -1;
Christopher Faulet08ed98f2020-07-28 10:33:25 +020012379#endif
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010012380 default:
Thierry Fournier70e38e92022-09-19 09:01:53 +020012381 memprintf(err, "Lua unknown error: %s", lua_tostring(L, -1));
Thierry Fournierc93c15c2020-11-28 15:02:13 +010012382 lua_pop(L, 1);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010012383 return -1;
12384 }
12385
12386 return 0;
12387}
12388
Thierry Fournierc93c15c2020-11-28 15:02:13 +010012389static int hlua_load(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010012390 const struct proxy *defpx, const char *file, int line,
Thierry Fournierc93c15c2020-11-28 15:02:13 +010012391 char **err)
12392{
12393 if (*(args[1]) == 0) {
Thierry Fournier70e38e92022-09-19 09:01:53 +020012394 memprintf(err, "'%s' expects a file name as parameter.", args[0]);
Thierry Fournierc93c15c2020-11-28 15:02:13 +010012395 return -1;
12396 }
12397
Thierry Fournier59f11be2020-11-29 00:37:41 +010012398 /* loading for global state */
Thierry Fournierc7492592020-11-28 23:57:24 +010012399 hlua_state_id = 0;
Willy Tarreau43ab05b2021-09-28 09:43:11 +020012400 ha_set_thread(NULL);
Thierry Fournierae6b5682022-09-19 09:04:16 +020012401 return hlua_load_state(&args[1], hlua_states[0], err);
Thierry Fournierc93c15c2020-11-28 15:02:13 +010012402}
12403
Thierry Fournier59f11be2020-11-29 00:37:41 +010012404static int hlua_load_per_thread(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010012405 const struct proxy *defpx, const char *file, int line,
Thierry Fournier59f11be2020-11-29 00:37:41 +010012406 char **err)
12407{
12408 int len;
Thierry Fournierae6b5682022-09-19 09:04:16 +020012409 int i;
Thierry Fournier59f11be2020-11-29 00:37:41 +010012410
12411 if (*(args[1]) == 0) {
Thierry Fournier70e38e92022-09-19 09:01:53 +020012412 memprintf(err, "'%s' expects a file as parameter.", args[0]);
Thierry Fournier59f11be2020-11-29 00:37:41 +010012413 return -1;
12414 }
12415
12416 if (per_thread_load == NULL) {
12417 /* allocate the first entry large enough to store the final NULL */
12418 per_thread_load = calloc(1, sizeof(*per_thread_load));
12419 if (per_thread_load == NULL) {
12420 memprintf(err, "out of memory error");
12421 return -1;
12422 }
12423 }
12424
12425 /* count used entries */
12426 for (len = 0; per_thread_load[len] != NULL; len++)
12427 ;
12428
12429 per_thread_load = realloc(per_thread_load, (len + 2) * sizeof(*per_thread_load));
12430 if (per_thread_load == NULL) {
12431 memprintf(err, "out of memory error");
12432 return -1;
12433 }
Thierry Fournier59f11be2020-11-29 00:37:41 +010012434 per_thread_load[len + 1] = NULL;
12435
Thierry Fournierae6b5682022-09-19 09:04:16 +020012436 /* count args excepting the first, allocate array and copy args */
12437 for (i = 0; *(args[i + 1]) != 0; i++);
Aurelien DARRAGONb12d1692022-09-23 08:48:34 +020012438 per_thread_load[len] = calloc(i + 1, sizeof(*per_thread_load[len]));
Thierry Fournier59f11be2020-11-29 00:37:41 +010012439 if (per_thread_load[len] == NULL) {
12440 memprintf(err, "out of memory error");
12441 return -1;
12442 }
Thierry Fournierae6b5682022-09-19 09:04:16 +020012443 for (i = 1; *(args[i]) != 0; i++) {
12444 per_thread_load[len][i - 1] = strdup(args[i]);
12445 if (per_thread_load[len][i - 1] == NULL) {
12446 memprintf(err, "out of memory error");
12447 return -1;
12448 }
12449 }
12450 per_thread_load[len][i - 1] = strdup("");
12451 if (per_thread_load[len][i - 1] == NULL) {
12452 memprintf(err, "out of memory error");
12453 return -1;
12454 }
Thierry Fournier59f11be2020-11-29 00:37:41 +010012455
12456 /* loading for thread 1 only */
12457 hlua_state_id = 1;
Willy Tarreau43ab05b2021-09-28 09:43:11 +020012458 ha_set_thread(NULL);
Thierry Fournierae6b5682022-09-19 09:04:16 +020012459 return hlua_load_state(per_thread_load[len], hlua_states[1], err);
Thierry Fournier59f11be2020-11-29 00:37:41 +010012460}
12461
Tim Duesterhusc9fc9f22020-01-12 13:55:39 +010012462/* Prepend the given <path> followed by a semicolon to the `package.<type>` variable
12463 * in the given <ctx>.
12464 */
Thierry Fournier3fb9e512020-11-28 10:13:12 +010012465static int hlua_prepend_path(lua_State *L, char *type, char *path)
Tim Duesterhusc9fc9f22020-01-12 13:55:39 +010012466{
Thierry Fournier3fb9e512020-11-28 10:13:12 +010012467 lua_getglobal(L, "package"); /* push package variable */
12468 lua_pushstring(L, path); /* push given path */
12469 lua_pushstring(L, ";"); /* push semicolon */
12470 lua_getfield(L, -3, type); /* push old path */
12471 lua_concat(L, 3); /* concatenate to new path */
12472 lua_setfield(L, -2, type); /* store new path */
12473 lua_pop(L, 1); /* pop package variable */
Tim Duesterhusc9fc9f22020-01-12 13:55:39 +010012474
12475 return 0;
12476}
12477
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010012478static int hlua_config_prepend_path(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010012479 const struct proxy *defpx, const char *file, int line,
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010012480 char **err)
12481{
12482 char *path;
12483 char *type = "path";
Tim Duesterhus621e74a2021-01-03 20:04:36 +010012484 struct prepend_path *p = NULL;
Bertrand Jacquin7fbc7702021-11-24 21:16:06 +000012485 size_t i;
Thierry Fournier59f11be2020-11-29 00:37:41 +010012486
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010012487 if (too_many_args(2, args, err, NULL)) {
Tim Duesterhus621e74a2021-01-03 20:04:36 +010012488 goto err;
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010012489 }
12490
12491 if (!(*args[1])) {
12492 memprintf(err, "'%s' expects to receive a <path> as argument", args[0]);
Tim Duesterhus621e74a2021-01-03 20:04:36 +010012493 goto err;
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010012494 }
12495 path = args[1];
12496
12497 if (*args[2]) {
12498 if (strcmp(args[2], "path") != 0 && strcmp(args[2], "cpath") != 0) {
12499 memprintf(err, "'%s' expects <type> to either be 'path' or 'cpath'", args[0]);
Tim Duesterhus621e74a2021-01-03 20:04:36 +010012500 goto err;
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010012501 }
12502 type = args[2];
12503 }
12504
Thierry Fournier59f11be2020-11-29 00:37:41 +010012505 p = calloc(1, sizeof(*p));
12506 if (p == NULL) {
Tim Duesterhusf89d43a2021-01-03 20:04:37 +010012507 memprintf(err, "memory allocation failed");
Tim Duesterhus621e74a2021-01-03 20:04:36 +010012508 goto err;
Thierry Fournier59f11be2020-11-29 00:37:41 +010012509 }
12510 p->path = strdup(path);
12511 if (p->path == NULL) {
Tim Duesterhusf89d43a2021-01-03 20:04:37 +010012512 memprintf(err, "memory allocation failed");
Tim Duesterhus621e74a2021-01-03 20:04:36 +010012513 goto err2;
Thierry Fournier59f11be2020-11-29 00:37:41 +010012514 }
12515 p->type = strdup(type);
12516 if (p->type == NULL) {
Tim Duesterhusf89d43a2021-01-03 20:04:37 +010012517 memprintf(err, "memory allocation failed");
Tim Duesterhus621e74a2021-01-03 20:04:36 +010012518 goto err2;
Thierry Fournier59f11be2020-11-29 00:37:41 +010012519 }
Willy Tarreau2b718102021-04-21 07:32:39 +020012520 LIST_APPEND(&prepend_path_list, &p->l);
Thierry Fournier59f11be2020-11-29 00:37:41 +010012521
Tim Duesterhus9e5e5862021-10-11 18:51:08 +020012522 /* Handle the global state and the per-thread state for the first
12523 * thread. The remaining threads will be initialized based on
12524 * prepend_path_list.
12525 */
Bertrand Jacquin7fbc7702021-11-24 21:16:06 +000012526 for (i = 0; i < 2; i++) {
Tim Duesterhus9e5e5862021-10-11 18:51:08 +020012527 lua_State *L = hlua_states[i];
12528 const char *error;
12529
12530 if (setjmp(safe_ljmp_env) != 0) {
12531 lua_atpanic(L, hlua_panic_safe);
12532 if (lua_type(L, -1) == LUA_TSTRING)
12533 error = lua_tostring(L, -1);
12534 else
12535 error = "critical error";
12536 fprintf(stderr, "lua-prepend-path: %s.\n", error);
12537 exit(1);
12538 } else {
12539 lua_atpanic(L, hlua_panic_ljmp);
12540 }
12541
12542 hlua_prepend_path(L, type, path);
12543
12544 lua_atpanic(L, hlua_panic_safe);
12545 }
12546
Thierry Fournier59f11be2020-11-29 00:37:41 +010012547 return 0;
Tim Duesterhus621e74a2021-01-03 20:04:36 +010012548
12549err2:
12550 free(p->type);
12551 free(p->path);
12552err:
12553 free(p);
12554 return -1;
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010012555}
12556
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010012557/* configuration keywords declaration */
12558static struct cfg_kw_list cfg_kws = {{ },{
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010012559 { CFG_GLOBAL, "lua-prepend-path", hlua_config_prepend_path },
Thierry FOURNIERbd413492015-03-03 16:52:26 +010012560 { CFG_GLOBAL, "lua-load", hlua_load },
Thierry Fournier59f11be2020-11-29 00:37:41 +010012561 { CFG_GLOBAL, "lua-load-per-thread", hlua_load_per_thread },
Thierry FOURNIERbd413492015-03-03 16:52:26 +010012562 { CFG_GLOBAL, "tune.lua.session-timeout", hlua_session_timeout },
12563 { CFG_GLOBAL, "tune.lua.task-timeout", hlua_task_timeout },
Thierry FOURNIER56da1012015-10-01 08:42:31 +020012564 { CFG_GLOBAL, "tune.lua.service-timeout", hlua_applet_timeout },
Aurelien DARRAGON58e36e52023-04-06 22:51:56 +020012565 { CFG_GLOBAL, "tune.lua.burst-timeout", hlua_burst_timeout },
Thierry FOURNIERee9f8022015-03-03 17:37:37 +010012566 { CFG_GLOBAL, "tune.lua.forced-yield", hlua_forced_yield },
Willy Tarreau32f61e22015-03-18 17:54:59 +010012567 { CFG_GLOBAL, "tune.lua.maxmem", hlua_parse_maxmem },
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010012568 { 0, NULL, NULL },
12569}};
12570
Willy Tarreau0108d902018-11-25 19:14:37 +010012571INITCALL1(STG_REGISTER, cfg_register_keywords, &cfg_kws);
12572
William Lallemand52139182022-03-30 15:05:42 +020012573#ifdef USE_OPENSSL
Christopher Fauletafd8f102018-11-08 11:34:21 +010012574
William Lallemand30fcca12022-03-30 12:03:12 +020012575/*
12576 * This function replace a ckch_store by another one, and rebuild the ckch_inst and all its dependencies.
12577 * It does the sam as "cli_io_handler_commit_cert" but for lua, the major
12578 * difference is that the yield in lua and for the CLI is not handled the same
12579 * way.
12580 */
12581__LJMP static int hlua_ckch_commit_yield(lua_State *L, int status, lua_KContext ctx)
12582{
12583 struct ckch_inst **lua_ckchi = lua_touserdata(L, -1);
12584 struct ckch_store **lua_ckchs = lua_touserdata(L, -2);
12585 struct ckch_inst *ckchi = *lua_ckchi;
12586 struct ckch_store *old_ckchs = lua_ckchs[0];
12587 struct ckch_store *new_ckchs = lua_ckchs[1];
12588 struct hlua *hlua;
12589 char *err = NULL;
12590 int y = 1;
12591
12592 hlua = hlua_gethlua(L);
12593
12594 /* get the first ckchi to copy */
12595 if (ckchi == NULL)
12596 ckchi = LIST_ELEM(old_ckchs->ckch_inst.n, typeof(ckchi), by_ckchs);
12597
12598 /* walk through the old ckch_inst and creates new ckch_inst using the updated ckchs */
12599 list_for_each_entry_from(ckchi, &old_ckchs->ckch_inst, by_ckchs) {
12600 struct ckch_inst *new_inst;
12601
12602 /* it takes a lot of CPU to creates SSL_CTXs, so we yield every 10 CKCH instances */
12603 if (y % 10 == 0) {
12604
12605 *lua_ckchi = ckchi;
12606
12607 task_wakeup(hlua->task, TASK_WOKEN_MSG);
12608 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_ckch_commit_yield, TICK_ETERNITY, 0));
12609 }
12610
12611 if (ckch_inst_rebuild(new_ckchs, ckchi, &new_inst, &err))
12612 goto error;
12613
12614 /* link the new ckch_inst to the duplicate */
12615 LIST_APPEND(&new_ckchs->ckch_inst, &new_inst->by_ckchs);
12616 y++;
12617 }
12618
12619 /* The generation is finished, we can insert everything */
12620 ckch_store_replace(old_ckchs, new_ckchs);
12621
12622 lua_pop(L, 2); /* pop the lua_ckchs and ckchi */
12623
12624 HA_SPIN_UNLOCK(CKCH_LOCK, &ckch_lock);
12625
12626 return 0;
12627
12628error:
12629 ckch_store_free(new_ckchs);
12630 HA_SPIN_UNLOCK(CKCH_LOCK, &ckch_lock);
12631 WILL_LJMP(luaL_error(L, "%s", err));
12632 free(err);
12633
12634 return 0;
12635}
12636
12637/*
12638 * Replace a ckch_store <filename> in the ckchs_tree with a ckch_store created
12639 * from the table in parameter.
12640 *
12641 * This is equivalent to "set ssl cert" + "commit ssl cert" over the CLI, which
12642 * means it does not need to have a transaction since everything is done in the
12643 * same function.
12644 *
12645 * CertCache.set{filename="", crt="", key="", sctl="", ocsp="", issuer=""}
12646 *
12647 */
12648__LJMP static int hlua_ckch_set(lua_State *L)
12649{
12650 struct hlua *hlua;
12651 struct ckch_inst **lua_ckchi;
12652 struct ckch_store **lua_ckchs;
12653 struct ckch_store *old_ckchs = NULL;
12654 struct ckch_store *new_ckchs = NULL;
12655 int errcode = 0;
12656 char *err = NULL;
12657 struct cert_exts *cert_ext = NULL;
12658 char *filename;
William Lallemand52ddd992022-11-22 11:51:53 +010012659 struct ckch_data *data;
William Lallemand30fcca12022-03-30 12:03:12 +020012660 int ret;
12661
12662 if (lua_type(L, -1) != LUA_TTABLE)
12663 WILL_LJMP(luaL_error(L, "'CertCache.set' needs a table as argument"));
12664
12665 hlua = hlua_gethlua(L);
12666
12667 /* FIXME: this should not return an error but should come back later */
12668 if (HA_SPIN_TRYLOCK(CKCH_LOCK, &ckch_lock))
12669 WILL_LJMP(luaL_error(L, "CertCache already under lock"));
12670
12671 ret = lua_getfield(L, -1, "filename");
12672 if (ret != LUA_TSTRING) {
Thierry Fournier70e38e92022-09-19 09:01:53 +020012673 memprintf(&err, "%sNo filename specified!", err ? err : "");
William Lallemand30fcca12022-03-30 12:03:12 +020012674 errcode |= ERR_ALERT | ERR_FATAL;
12675 goto end;
12676 }
12677 filename = (char *)lua_tostring(L, -1);
12678
12679
12680 /* look for the filename in the tree */
12681 old_ckchs = ckchs_lookup(filename);
12682 if (!old_ckchs) {
Thierry Fournier70e38e92022-09-19 09:01:53 +020012683 memprintf(&err, "%sCan't replace a certificate which is not referenced by the configuration!", err ? err : "");
William Lallemand30fcca12022-03-30 12:03:12 +020012684 errcode |= ERR_ALERT | ERR_FATAL;
12685 goto end;
12686 }
12687 /* TODO: handle extra_files_noext */
12688
12689 new_ckchs = ckchs_dup(old_ckchs);
12690 if (!new_ckchs) {
Thierry Fournier70e38e92022-09-19 09:01:53 +020012691 memprintf(&err, "%sCannot allocate memory!", err ? err : "");
William Lallemand30fcca12022-03-30 12:03:12 +020012692 errcode |= ERR_ALERT | ERR_FATAL;
12693 goto end;
12694 }
12695
William Lallemand52ddd992022-11-22 11:51:53 +010012696 data = new_ckchs->data;
William Lallemand30fcca12022-03-30 12:03:12 +020012697
12698 /* loop on the field in the table, which have the same name as the
12699 * possible extensions of files */
12700 lua_pushnil(L);
12701 while (lua_next(L, 1)) {
12702 int i;
12703 const char *field = lua_tostring(L, -2);
12704 char *payload = (char *)lua_tostring(L, -1);
12705
12706 if (!field || strcmp(field, "filename") == 0) {
12707 lua_pop(L, 1);
12708 continue;
12709 }
12710
12711 for (i = 0; field && cert_exts[i].ext != NULL; i++) {
12712 if (strcmp(field, cert_exts[i].ext) == 0) {
12713 cert_ext = &cert_exts[i];
12714 break;
12715 }
12716 }
12717
12718 /* this is the default type, the field is not supported */
12719 if (cert_ext == NULL) {
Thierry Fournier70e38e92022-09-19 09:01:53 +020012720 memprintf(&err, "%sUnsupported field '%s'", err ? err : "", field);
William Lallemand30fcca12022-03-30 12:03:12 +020012721 errcode |= ERR_ALERT | ERR_FATAL;
12722 goto end;
12723 }
12724
12725 /* appply the change on the duplicate */
William Lallemand52ddd992022-11-22 11:51:53 +010012726 if (cert_ext->load(filename, payload, data, &err) != 0) {
Thierry Fournier70e38e92022-09-19 09:01:53 +020012727 memprintf(&err, "%sCan't load the payload for '%s'", err ? err : "", cert_ext->ext);
William Lallemand30fcca12022-03-30 12:03:12 +020012728 errcode |= ERR_ALERT | ERR_FATAL;
12729 goto end;
12730 }
12731 lua_pop(L, 1);
12732 }
12733
12734 /* store the pointers on the lua stack */
12735 lua_ckchs = lua_newuserdata(L, sizeof(struct ckch_store *) * 2);
12736 lua_ckchs[0] = old_ckchs;
12737 lua_ckchs[1] = new_ckchs;
12738 lua_ckchi = lua_newuserdata(L, sizeof(struct ckch_inst *));
12739 *lua_ckchi = NULL;
12740
12741 task_wakeup(hlua->task, TASK_WOKEN_MSG);
12742 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_ckch_commit_yield, TICK_ETERNITY, 0));
12743
12744end:
12745 HA_SPIN_UNLOCK(CKCH_LOCK, &ckch_lock);
12746
12747 if (errcode & ERR_CODE) {
12748 ckch_store_free(new_ckchs);
12749 WILL_LJMP(luaL_error(L, "%s", err));
12750 }
12751 free(err);
12752
12753 return 0;
12754}
12755
William Lallemand52139182022-03-30 15:05:42 +020012756#else
12757
12758__LJMP static int hlua_ckch_set(lua_State *L)
12759{
12760 WILL_LJMP(luaL_error(L, "'CertCache.set' needs an HAProxy built with OpenSSL"));
12761
12762 return 0;
12763}
12764#endif /* ! USE_OPENSSL */
12765
12766
12767
Thierry FOURNIERbabae282015-09-17 11:36:37 +020012768/* This function can fail with an abort() due to an Lua critical error.
12769 * We are in the initialisation process of HAProxy, this abort() is
12770 * tolerated.
12771 */
Thierry Fournierb8cef172020-11-28 15:37:17 +010012772int hlua_post_init_state(lua_State *L)
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010012773{
12774 struct hlua_init_function *init;
12775 const char *msg;
12776 enum hlua_exec ret;
Thierry Fournierfd107a22016-02-19 19:57:23 +010012777 const char *error;
Thierry Fournier670db242020-11-28 10:49:59 +010012778 const char *kind;
12779 const char *trace;
12780 int return_status = 1;
12781#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM >= 504
12782 int nres;
12783#endif
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010012784
Willy Tarreaucdb53462020-12-02 12:12:00 +010012785 /* disable memory limit checks if limit is not set */
12786 if (!hlua_global_allocator.limit)
12787 hlua_global_allocator.limit = ~hlua_global_allocator.limit;
12788
Ilya Shipitsin856aabc2020-04-16 23:51:34 +050012789 /* Call post initialisation function in safe environment. */
Thierry Fournier3c539322020-11-28 16:05:05 +010012790 if (setjmp(safe_ljmp_env) != 0) {
12791 lua_atpanic(L, hlua_panic_safe);
Thierry Fournierb8cef172020-11-28 15:37:17 +010012792 if (lua_type(L, -1) == LUA_TSTRING)
12793 error = lua_tostring(L, -1);
Thierry Fournier3d4a6752016-02-19 20:53:30 +010012794 else
12795 error = "critical error";
12796 fprintf(stderr, "Lua post-init: %s.\n", error);
12797 exit(1);
Thierry Fournier3c539322020-11-28 16:05:05 +010012798 } else {
12799 lua_atpanic(L, hlua_panic_ljmp);
Thierry Fournier3d4a6752016-02-19 20:53:30 +010012800 }
Frédéric Lécaille54f2bcf2018-08-29 13:46:24 +020012801
Thierry Fournierc7492592020-11-28 23:57:24 +010012802 list_for_each_entry(init, &hlua_init_functions[hlua_state_id], l) {
Aurelien DARRAGON4fdf8b52023-03-20 17:22:37 +010012803 hlua_pushref(L, init->function_ref);
Aurelien DARRAGON16d047b2023-03-20 16:29:55 +010012804 /* function ref should be released right away since it was pushed
12805 * on the stack and will not be used anymore
12806 */
12807 hlua_unref(L, init->function_ref);
Thierry Fournier670db242020-11-28 10:49:59 +010012808
12809#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM >= 504
Thierry Fournierb8cef172020-11-28 15:37:17 +010012810 ret = lua_resume(L, L, 0, &nres);
Thierry Fournier670db242020-11-28 10:49:59 +010012811#else
Thierry Fournierb8cef172020-11-28 15:37:17 +010012812 ret = lua_resume(L, L, 0);
Thierry Fournier670db242020-11-28 10:49:59 +010012813#endif
12814 kind = NULL;
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010012815 switch (ret) {
Thierry Fournier670db242020-11-28 10:49:59 +010012816
12817 case LUA_OK:
Thierry Fournierb8cef172020-11-28 15:37:17 +010012818 lua_pop(L, -1);
Thierry Fournier13d08b72020-11-28 11:02:58 +010012819 break;
Thierry Fournier670db242020-11-28 10:49:59 +010012820
12821 case LUA_ERRERR:
12822 kind = "message handler error";
Willy Tarreau14de3952022-11-14 07:08:28 +010012823 __fallthrough;
Thierry Fournier670db242020-11-28 10:49:59 +010012824 case LUA_ERRRUN:
12825 if (!kind)
12826 kind = "runtime error";
Thierry Fournierb8cef172020-11-28 15:37:17 +010012827 msg = lua_tostring(L, -1);
12828 lua_settop(L, 0); /* Empty the stack. */
12829 lua_pop(L, 1);
Christopher Fauletd09cc512021-03-24 14:48:45 +010012830 trace = hlua_traceback(L, ", ");
Thierry Fournier670db242020-11-28 10:49:59 +010012831 if (msg)
12832 ha_alert("Lua init: %s: '%s' from %s\n", kind, msg, trace);
12833 else
12834 ha_alert("Lua init: unknown %s from %s\n", kind, trace);
12835 return_status = 0;
12836 break;
12837
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010012838 default:
Thierry Fournier670db242020-11-28 10:49:59 +010012839 /* Unknown error */
12840 kind = "Unknown error";
Willy Tarreau14de3952022-11-14 07:08:28 +010012841 __fallthrough;
Thierry Fournier670db242020-11-28 10:49:59 +010012842 case LUA_YIELD:
12843 /* yield is not configured at this step, this state doesn't happen */
12844 if (!kind)
12845 kind = "yield not allowed";
Willy Tarreau14de3952022-11-14 07:08:28 +010012846 __fallthrough;
Thierry Fournier670db242020-11-28 10:49:59 +010012847 case LUA_ERRMEM:
12848 if (!kind)
12849 kind = "out of memory error";
Thierry Fournierb8cef172020-11-28 15:37:17 +010012850 lua_settop(L, 0);
12851 lua_pop(L, 1);
Christopher Fauletd09cc512021-03-24 14:48:45 +010012852 trace = hlua_traceback(L, ", ");
Thierry Fournier670db242020-11-28 10:49:59 +010012853 ha_alert("Lua init: %s: %s\n", kind, trace);
12854 return_status = 0;
12855 break;
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010012856 }
Thierry Fournier670db242020-11-28 10:49:59 +010012857 if (!return_status)
12858 break;
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010012859 }
Thierry Fournier3c539322020-11-28 16:05:05 +010012860
12861 lua_atpanic(L, hlua_panic_safe);
Thierry Fournier670db242020-11-28 10:49:59 +010012862 return return_status;
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010012863}
12864
Thierry Fournierb8cef172020-11-28 15:37:17 +010012865int hlua_post_init()
12866{
Thierry Fournier59f11be2020-11-29 00:37:41 +010012867 int ret;
12868 int i;
12869 int errors;
12870 char *err = NULL;
12871 struct hlua_function *fcn;
Christopher Faulet69c581a2021-05-31 08:54:04 +020012872 struct hlua_reg_filter *reg_flt;
Thierry Fournier59f11be2020-11-29 00:37:41 +010012873
Willy Tarreaub1310492021-08-30 09:35:18 +020012874#if defined(USE_OPENSSL)
Thierry Fournierb8cef172020-11-28 15:37:17 +010012875 /* Initialize SSL server. */
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010012876 if (socket_ssl->xprt->prepare_srv) {
Thierry Fournierb8cef172020-11-28 15:37:17 +010012877 int saved_used_backed = global.ssl_used_backend;
12878 // don't affect maxconn automatic computation
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010012879 socket_ssl->xprt->prepare_srv(socket_ssl);
Thierry Fournierb8cef172020-11-28 15:37:17 +010012880 global.ssl_used_backend = saved_used_backed;
12881 }
12882#endif
12883
Thierry Fournierc7492592020-11-28 23:57:24 +010012884 /* Perform post init of common thread */
12885 hlua_state_id = 0;
Willy Tarreau43ab05b2021-09-28 09:43:11 +020012886 ha_set_thread(&ha_thread_info[0]);
Thierry Fournier59f11be2020-11-29 00:37:41 +010012887 ret = hlua_post_init_state(hlua_states[hlua_state_id]);
12888 if (ret == 0)
12889 return 0;
12890
12891 /* init remaining lua states and load files */
12892 for (hlua_state_id = 2; hlua_state_id < global.nbthread + 1; hlua_state_id++) {
12893
12894 /* set thread context */
Willy Tarreau43ab05b2021-09-28 09:43:11 +020012895 ha_set_thread(&ha_thread_info[hlua_state_id - 1]);
Thierry Fournier59f11be2020-11-29 00:37:41 +010012896
12897 /* Init lua state */
12898 hlua_states[hlua_state_id] = hlua_init_state(hlua_state_id);
12899
12900 /* Load lua files */
12901 for (i = 0; per_thread_load && per_thread_load[i]; i++) {
12902 ret = hlua_load_state(per_thread_load[i], hlua_states[hlua_state_id], &err);
12903 if (ret != 0) {
12904 ha_alert("Lua init: %s\n", err);
12905 return 0;
12906 }
12907 }
12908 }
12909
12910 /* Reset thread context */
Willy Tarreau43ab05b2021-09-28 09:43:11 +020012911 ha_set_thread(NULL);
Thierry Fournier59f11be2020-11-29 00:37:41 +010012912
12913 /* Execute post init for all states */
12914 for (hlua_state_id = 1; hlua_state_id < global.nbthread + 1; hlua_state_id++) {
12915
12916 /* set thread context */
Willy Tarreau43ab05b2021-09-28 09:43:11 +020012917 ha_set_thread(&ha_thread_info[hlua_state_id - 1]);
Thierry Fournier59f11be2020-11-29 00:37:41 +010012918
12919 /* run post init */
12920 ret = hlua_post_init_state(hlua_states[hlua_state_id]);
12921 if (ret == 0)
12922 return 0;
12923 }
12924
12925 /* Reset thread context */
Willy Tarreau43ab05b2021-09-28 09:43:11 +020012926 ha_set_thread(NULL);
Thierry Fournier59f11be2020-11-29 00:37:41 +010012927
12928 /* control functions registering. Each function must have:
12929 * - only the function_ref[0] set positive and all other to -1
12930 * - only the function_ref[0] set to -1 and all other positive
12931 * This ensure a same reference is not used both in shared
12932 * lua state and thread dedicated lua state. Note: is the case
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +050012933 * reach, the shared state is priority, but the bug will be
Thierry Fournier59f11be2020-11-29 00:37:41 +010012934 * complicated to found for the end user.
12935 */
12936 errors = 0;
12937 list_for_each_entry(fcn, &referenced_functions, l) {
12938 ret = 0;
12939 for (i = 1; i < global.nbthread + 1; i++) {
12940 if (fcn->function_ref[i] == -1)
12941 ret--;
12942 else
12943 ret++;
12944 }
12945 if (abs(ret) != global.nbthread) {
12946 ha_alert("Lua function '%s' is not referenced in all thread. "
12947 "Expect function in all thread or in none thread.\n", fcn->name);
12948 errors++;
12949 continue;
12950 }
12951
12952 if ((fcn->function_ref[0] == -1) == (ret < 0)) {
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +050012953 ha_alert("Lua function '%s' is referenced both ins shared Lua context (through lua-load) "
12954 "and per-thread Lua context (through lua-load-per-thread). these two context "
Thierry Fournier59f11be2020-11-29 00:37:41 +010012955 "exclusive.\n", fcn->name);
12956 errors++;
12957 }
12958 }
12959
Christopher Faulet69c581a2021-05-31 08:54:04 +020012960 /* Do the same with registered filters */
12961 list_for_each_entry(reg_flt, &referenced_filters, l) {
12962 ret = 0;
12963 for (i = 1; i < global.nbthread + 1; i++) {
12964 if (reg_flt->flt_ref[i] == -1)
12965 ret--;
12966 else
12967 ret++;
12968 }
12969 if (abs(ret) != global.nbthread) {
12970 ha_alert("Lua filter '%s' is not referenced in all thread. "
12971 "Expect function in all thread or in none thread.\n", reg_flt->name);
12972 errors++;
12973 continue;
12974 }
12975
12976 if ((reg_flt->flt_ref[0] == -1) == (ret < 0)) {
12977 ha_alert("Lua filter '%s' is referenced both ins shared Lua context (through lua-load) "
12978 "and per-thread Lua context (through lua-load-per-thread). these two context "
12979 "exclusive.\n", fcn->name);
12980 errors++;
12981 }
12982 }
12983
12984
Thierry Fournier59f11be2020-11-29 00:37:41 +010012985 if (errors > 0)
12986 return 0;
12987
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +050012988 /* after this point, this global will no longer be used, so set to
Thierry Fournier59f11be2020-11-29 00:37:41 +010012989 * -1 in order to have probably a segfault if someone use it
12990 */
12991 hlua_state_id = -1;
12992
12993 return 1;
Thierry Fournierb8cef172020-11-28 15:37:17 +010012994}
12995
Willy Tarreau32f61e22015-03-18 17:54:59 +010012996/* The memory allocator used by the Lua stack. <ud> is a pointer to the
12997 * allocator's context. <ptr> is the pointer to alloc/free/realloc. <osize>
12998 * is the previously allocated size or the kind of object in case of a new
Willy Tarreaud36c7fa2020-12-02 12:26:29 +010012999 * allocation. <nsize> is the requested new size. A new allocation is
13000 * indicated by <ptr> being NULL. A free is indicated by <nsize> being
Willy Tarreaucdb53462020-12-02 12:12:00 +010013001 * zero. This one verifies that the limits are respected but is optimized
13002 * for the fast case where limits are not used, hence stats are not updated.
Willy Tarreaua5efdff2021-10-22 16:00:02 +020013003 *
13004 * Warning: while this API ressembles glibc's realloc() a lot, glibc surpasses
13005 * POSIX by making realloc(ptr,0) an effective free(), but others do not do
13006 * that and will simply allocate zero as if it were the result of malloc(0),
13007 * so mapping this onto realloc() will lead to memory leaks on non-glibc
13008 * systems.
Willy Tarreau32f61e22015-03-18 17:54:59 +010013009 */
13010static void *hlua_alloc(void *ud, void *ptr, size_t osize, size_t nsize)
13011{
13012 struct hlua_mem_allocator *zone = ud;
Willy Tarreaucdb53462020-12-02 12:12:00 +010013013 size_t limit, old, new;
13014
13015 /* a limit of ~0 means unlimited and boot complete, so there's no need
13016 * for accounting anymore.
13017 */
Willy Tarreaua5efdff2021-10-22 16:00:02 +020013018 if (likely(~zone->limit == 0)) {
13019 if (!nsize)
13020 ha_free(&ptr);
13021 else
13022 ptr = realloc(ptr, nsize);
13023 return ptr;
13024 }
Willy Tarreau32f61e22015-03-18 17:54:59 +010013025
Willy Tarreaud36c7fa2020-12-02 12:26:29 +010013026 if (!ptr)
13027 osize = 0;
Willy Tarreau32f61e22015-03-18 17:54:59 +010013028
Willy Tarreaucdb53462020-12-02 12:12:00 +010013029 /* enforce strict limits across all threads */
13030 limit = zone->limit;
13031 old = _HA_ATOMIC_LOAD(&zone->allocated);
13032 do {
13033 new = old + nsize - osize;
13034 if (unlikely(nsize && limit && new > limit))
13035 return NULL;
13036 } while (!_HA_ATOMIC_CAS(&zone->allocated, &old, new));
Willy Tarreau32f61e22015-03-18 17:54:59 +010013037
Willy Tarreaua5efdff2021-10-22 16:00:02 +020013038 if (!nsize)
13039 ha_free(&ptr);
13040 else
13041 ptr = realloc(ptr, nsize);
Willy Tarreaucdb53462020-12-02 12:12:00 +010013042
13043 if (unlikely(!ptr && nsize)) // failed
13044 _HA_ATOMIC_SUB(&zone->allocated, nsize - osize);
13045
13046 __ha_barrier_atomic_store();
Willy Tarreau32f61e22015-03-18 17:54:59 +010013047 return ptr;
13048}
13049
Thierry Fournierecb83c22020-11-28 15:49:44 +010013050/* This function can fail with an abort() due to a Lua critical error.
Thierry FOURNIERbabae282015-09-17 11:36:37 +020013051 * We are in the initialisation process of HAProxy, this abort() is
13052 * tolerated.
13053 */
Thierry Fournierecb83c22020-11-28 15:49:44 +010013054lua_State *hlua_init_state(int thread_num)
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +010013055{
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010013056 int i;
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010013057 int idx;
13058 struct sample_fetch *sf;
Thierry FOURNIER594afe72015-03-10 23:58:30 +010013059 struct sample_conv *sc;
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010013060 char *p;
Thierry Fournierfd107a22016-02-19 19:57:23 +010013061 const char *error_msg;
Thierry Fournier4234dbd2020-11-28 13:18:23 +010013062 void **context;
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013063 lua_State *L;
Thierry Fournier59f11be2020-11-29 00:37:41 +010013064 struct prepend_path *pp;
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010013065
Thierry FOURNIER380d0932015-01-23 14:27:52 +010013066 /* Init main lua stack. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013067 L = lua_newstate(hlua_alloc, &hlua_global_allocator);
Thierry FOURNIER380d0932015-01-23 14:27:52 +010013068
Thierry Fournier4234dbd2020-11-28 13:18:23 +010013069 /* Initialise Lua context to NULL */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013070 context = lua_getextraspace(L);
Thierry Fournier4234dbd2020-11-28 13:18:23 +010013071 *context = NULL;
13072
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -080013073 /* From this point, until the end of the initialisation function,
Thierry FOURNIERbabae282015-09-17 11:36:37 +020013074 * the Lua function can fail with an abort. We are in the initialisation
13075 * process of HAProxy, this abort() is tolerated.
13076 */
13077
Thierry Fournier3c539322020-11-28 16:05:05 +010013078 /* Call post initialisation function in safe environment. */
13079 if (setjmp(safe_ljmp_env) != 0) {
13080 lua_atpanic(L, hlua_panic_safe);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013081 if (lua_type(L, -1) == LUA_TSTRING)
13082 error_msg = lua_tostring(L, -1);
Thierry Fournier2f05cc62020-11-28 16:08:02 +010013083 else
13084 error_msg = "critical error";
13085 fprintf(stderr, "Lua init: %s.\n", error_msg);
13086 exit(1);
Thierry Fournier3c539322020-11-28 16:05:05 +010013087 } else {
13088 lua_atpanic(L, hlua_panic_ljmp);
Thierry Fournier2f05cc62020-11-28 16:08:02 +010013089 }
13090
Thierry FOURNIER380d0932015-01-23 14:27:52 +010013091 /* Initialise lua. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013092 luaL_openlibs(L);
Tim Duesterhus541fe1e2020-01-12 13:55:41 +010013093#define HLUA_PREPEND_PATH_TOSTRING1(x) #x
13094#define HLUA_PREPEND_PATH_TOSTRING(x) HLUA_PREPEND_PATH_TOSTRING1(x)
13095#ifdef HLUA_PREPEND_PATH
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013096 hlua_prepend_path(L, "path", HLUA_PREPEND_PATH_TOSTRING(HLUA_PREPEND_PATH));
Tim Duesterhus541fe1e2020-01-12 13:55:41 +010013097#endif
13098#ifdef HLUA_PREPEND_CPATH
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013099 hlua_prepend_path(L, "cpath", HLUA_PREPEND_PATH_TOSTRING(HLUA_PREPEND_CPATH));
Tim Duesterhus541fe1e2020-01-12 13:55:41 +010013100#endif
13101#undef HLUA_PREPEND_PATH_TOSTRING
13102#undef HLUA_PREPEND_PATH_TOSTRING1
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010013103
Thierry Fournier59f11be2020-11-29 00:37:41 +010013104 /* Apply configured prepend path */
13105 list_for_each_entry(pp, &prepend_path_list, l)
13106 hlua_prepend_path(L, pp->type, pp->path);
13107
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010013108 /*
Aurelien DARRAGON8cd620b2023-04-07 17:37:46 +020013109 * Override some lua functions.
13110 *
13111 */
13112
13113 /* push our "safe" coroutine.create() function */
13114 lua_getglobal(L, "coroutine");
13115 lua_pushcclosure(L, hlua_coroutine_create, 0);
13116 lua_setfield(L, -2, "create");
13117
13118 /*
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010013119 *
13120 * Create "core" object.
13121 *
13122 */
13123
Thierry FOURNIERa2d8c652015-03-11 17:29:39 +010013124 /* This table entry is the object "core" base. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013125 lua_newtable(L);
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010013126
Thierry Fournierecb83c22020-11-28 15:49:44 +010013127 /* set the thread id */
13128 hlua_class_const_int(L, "thread", thread_num);
13129
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010013130 /* Push the loglevel constants. */
Willy Tarreau80f5fae2015-02-27 16:38:20 +010013131 for (i = 0; i < NB_LOG_LEVELS; i++)
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013132 hlua_class_const_int(L, log_levels[i], i);
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010013133
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010013134 /* Register special functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013135 hlua_class_function(L, "register_init", hlua_register_init);
13136 hlua_class_function(L, "register_task", hlua_register_task);
13137 hlua_class_function(L, "register_fetches", hlua_register_fetches);
13138 hlua_class_function(L, "register_converters", hlua_register_converters);
13139 hlua_class_function(L, "register_action", hlua_register_action);
13140 hlua_class_function(L, "register_service", hlua_register_service);
13141 hlua_class_function(L, "register_cli", hlua_register_cli);
Christopher Faulet69c581a2021-05-31 08:54:04 +020013142 hlua_class_function(L, "register_filter", hlua_register_filter);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013143 hlua_class_function(L, "yield", hlua_yield);
13144 hlua_class_function(L, "set_nice", hlua_set_nice);
13145 hlua_class_function(L, "sleep", hlua_sleep);
13146 hlua_class_function(L, "msleep", hlua_msleep);
13147 hlua_class_function(L, "add_acl", hlua_add_acl);
13148 hlua_class_function(L, "del_acl", hlua_del_acl);
13149 hlua_class_function(L, "set_map", hlua_set_map);
13150 hlua_class_function(L, "del_map", hlua_del_map);
13151 hlua_class_function(L, "tcp", hlua_socket_new);
William Lallemand3956c4e2021-09-21 16:25:15 +020013152 hlua_class_function(L, "httpclient", hlua_httpclient_new);
Aurelien DARRAGONc84899c2023-02-20 18:18:59 +010013153 hlua_class_function(L, "event_sub", hlua_event_global_sub);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013154 hlua_class_function(L, "log", hlua_log);
13155 hlua_class_function(L, "Debug", hlua_log_debug);
13156 hlua_class_function(L, "Info", hlua_log_info);
13157 hlua_class_function(L, "Warning", hlua_log_warning);
13158 hlua_class_function(L, "Alert", hlua_log_alert);
13159 hlua_class_function(L, "done", hlua_done);
Aurelien DARRAGON5bed48f2023-04-21 17:32:46 +020013160 hlua_class_function(L, "disable_legacy_mailers", hlua_disable_legacy_mailers);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013161 hlua_fcn_reg_core_fcn(L);
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010013162
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013163 lua_setglobal(L, "core");
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010013164
13165 /*
13166 *
Christopher Faulet0f3c8902020-01-31 18:57:12 +010013167 * Create "act" object.
13168 *
13169 */
13170
13171 /* This table entry is the object "act" base. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013172 lua_newtable(L);
Christopher Faulet0f3c8902020-01-31 18:57:12 +010013173
13174 /* push action return constants */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013175 hlua_class_const_int(L, "CONTINUE", ACT_RET_CONT);
13176 hlua_class_const_int(L, "STOP", ACT_RET_STOP);
13177 hlua_class_const_int(L, "YIELD", ACT_RET_YIELD);
13178 hlua_class_const_int(L, "ERROR", ACT_RET_ERR);
13179 hlua_class_const_int(L, "DONE", ACT_RET_DONE);
13180 hlua_class_const_int(L, "DENY", ACT_RET_DENY);
13181 hlua_class_const_int(L, "ABORT", ACT_RET_ABRT);
13182 hlua_class_const_int(L, "INVALID", ACT_RET_INV);
Christopher Faulet0f3c8902020-01-31 18:57:12 +010013183
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013184 hlua_class_function(L, "wake_time", hlua_set_wake_time);
Christopher Faulet2c2c2e32020-01-31 19:07:52 +010013185
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013186 lua_setglobal(L, "act");
Christopher Faulet0f3c8902020-01-31 18:57:12 +010013187
13188 /*
13189 *
Christopher Faulet69c581a2021-05-31 08:54:04 +020013190 * Create "Filter" object.
13191 *
13192 */
13193
13194 /* This table entry is the object "filter" base. */
13195 lua_newtable(L);
13196
13197 /* push flags and constants */
13198 hlua_class_const_int(L, "CONTINUE", 1);
13199 hlua_class_const_int(L, "WAIT", 0);
13200 hlua_class_const_int(L, "ERROR", -1);
13201
13202 hlua_class_const_int(L, "FLT_CFG_FL_HTX", FLT_CFG_FL_HTX);
13203
Christopher Fauletc404f112020-02-26 15:03:09 +010013204 hlua_class_function(L, "wake_time", hlua_set_wake_time);
13205 hlua_class_function(L, "register_data_filter", hlua_register_data_filter);
13206 hlua_class_function(L, "unregister_data_filter", hlua_unregister_data_filter);
13207
Christopher Faulet69c581a2021-05-31 08:54:04 +020013208 lua_setglobal(L, "filter");
13209
13210 /*
13211 *
Thierry FOURNIER3def3932015-04-07 11:27:54 +020013212 * Register class Map
13213 *
13214 */
13215
13216 /* This table entry is the object "Map" base. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013217 lua_newtable(L);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020013218
13219 /* register pattern types. */
13220 for (i=0; i<PAT_MATCH_NUM; i++)
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013221 hlua_class_const_int(L, pat_match_names[i], i);
Thierry FOURNIER4dc71972017-01-28 08:33:08 +010013222 for (i=0; i<PAT_MATCH_NUM; i++) {
Willy Tarreau843b7cb2018-07-13 10:54:26 +020013223 snprintf(trash.area, trash.size, "_%s", pat_match_names[i]);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013224 hlua_class_const_int(L, trash.area, i);
Thierry FOURNIER4dc71972017-01-28 08:33:08 +010013225 }
Thierry FOURNIER3def3932015-04-07 11:27:54 +020013226
13227 /* register constructor. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013228 hlua_class_function(L, "new", hlua_map_new);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020013229
13230 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013231 lua_newtable(L);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020013232
Ilya Shipitsind4259502020-04-08 01:07:56 +050013233 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013234 lua_pushstring(L, "__index");
13235 lua_newtable(L);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020013236
13237 /* Register . */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013238 hlua_class_function(L, "lookup", hlua_map_lookup);
13239 hlua_class_function(L, "slookup", hlua_map_slookup);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020013240
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013241 lua_rawset(L, -3);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020013242
Thierry Fournier45e78d72016-02-19 18:34:46 +010013243 /* Register previous table in the registry with reference and named entry.
13244 * The function hlua_register_metatable() pops the stack, so we
13245 * previously create a copy of the table.
13246 */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013247 lua_pushvalue(L, -1); /* Copy the -1 entry and push it on the stack. */
13248 class_map_ref = hlua_register_metatable(L, CLASS_MAP);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020013249
13250 /* Assign the metatable to the mai Map object. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013251 lua_setmetatable(L, -2);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020013252
13253 /* Set a name to the table. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013254 lua_setglobal(L, "Map");
Thierry FOURNIER3def3932015-04-07 11:27:54 +020013255
13256 /*
13257 *
William Lallemand30fcca12022-03-30 12:03:12 +020013258 * Register "CertCache" class
13259 *
13260 */
13261
13262 /* Create and fill the metatable. */
13263 lua_newtable(L);
13264 /* Register */
13265 hlua_class_function(L, "set", hlua_ckch_set);
13266 lua_setglobal(L, CLASS_CERTCACHE); /* Create global object called Regex */
13267
13268 /*
13269 *
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010013270 * Register class Channel
13271 *
13272 */
13273
13274 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013275 lua_newtable(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010013276
Ilya Shipitsind4259502020-04-08 01:07:56 +050013277 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013278 lua_pushstring(L, "__index");
13279 lua_newtable(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010013280
13281 /* Register . */
Christopher Faulet6a79fc12021-08-06 16:02:36 +020013282 hlua_class_function(L, "data", hlua_channel_get_data);
13283 hlua_class_function(L, "line", hlua_channel_get_line);
13284 hlua_class_function(L, "set", hlua_channel_set_data);
13285 hlua_class_function(L, "remove", hlua_channel_del_data);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013286 hlua_class_function(L, "append", hlua_channel_append);
Christopher Faulet6a79fc12021-08-06 16:02:36 +020013287 hlua_class_function(L, "prepend", hlua_channel_prepend);
13288 hlua_class_function(L, "insert", hlua_channel_insert_data);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013289 hlua_class_function(L, "send", hlua_channel_send);
13290 hlua_class_function(L, "forward", hlua_channel_forward);
Christopher Faulet6a79fc12021-08-06 16:02:36 +020013291 hlua_class_function(L, "input", hlua_channel_get_in_len);
13292 hlua_class_function(L, "output", hlua_channel_get_out_len);
13293 hlua_class_function(L, "may_recv", hlua_channel_may_recv);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013294 hlua_class_function(L, "is_full", hlua_channel_is_full);
13295 hlua_class_function(L, "is_resp", hlua_channel_is_resp);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010013296
Christopher Faulet6a79fc12021-08-06 16:02:36 +020013297 /* Deprecated API */
13298 hlua_class_function(L, "get", hlua_channel_get);
13299 hlua_class_function(L, "dup", hlua_channel_dup);
13300 hlua_class_function(L, "getline", hlua_channel_getline);
13301 hlua_class_function(L, "get_in_len", hlua_channel_get_in_len);
13302 hlua_class_function(L, "get_out_len", hlua_channel_get_out_len);
13303
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013304 lua_rawset(L, -3);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010013305
13306 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013307 class_channel_ref = hlua_register_metatable(L, CLASS_CHANNEL);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010013308
13309 /*
13310 *
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010013311 * Register class Fetches
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010013312 *
13313 */
13314
13315 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013316 lua_newtable(L);
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010013317
Ilya Shipitsind4259502020-04-08 01:07:56 +050013318 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013319 lua_pushstring(L, "__index");
13320 lua_newtable(L);
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010013321
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010013322 /* Browse existing fetches and create the associated
13323 * object method.
13324 */
13325 sf = NULL;
13326 while ((sf = sample_fetch_getnext(sf, &idx)) != NULL) {
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010013327 /* gL.Tua doesn't support '.' and '-' in the function names, replace it
13328 * by an underscore.
13329 */
Willy Tarreau5ef96562021-08-26 16:48:53 +020013330 strlcpy2(trash.area, sf->kw, trash.size);
Willy Tarreau843b7cb2018-07-13 10:54:26 +020013331 for (p = trash.area; *p; p++)
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010013332 if (*p == '.' || *p == '-' || *p == '+')
13333 *p = '_';
13334
13335 /* Register the function. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013336 lua_pushstring(L, trash.area);
13337 lua_pushlightuserdata(L, sf);
13338 lua_pushcclosure(L, hlua_run_sample_fetch, 1);
13339 lua_rawset(L, -3);
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010013340 }
13341
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013342 lua_rawset(L, -3);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010013343
13344 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013345 class_fetches_ref = hlua_register_metatable(L, CLASS_FETCHES);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010013346
13347 /*
13348 *
Thierry FOURNIER594afe72015-03-10 23:58:30 +010013349 * Register class Converters
13350 *
13351 */
13352
13353 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013354 lua_newtable(L);
Thierry FOURNIER594afe72015-03-10 23:58:30 +010013355
13356 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013357 lua_pushstring(L, "__index");
13358 lua_newtable(L);
Thierry FOURNIER594afe72015-03-10 23:58:30 +010013359
13360 /* Browse existing converters and create the associated
13361 * object method.
13362 */
13363 sc = NULL;
13364 while ((sc = sample_conv_getnext(sc, &idx)) != NULL) {
Thierry FOURNIER594afe72015-03-10 23:58:30 +010013365 /* gL.Tua doesn't support '.' and '-' in the function names, replace it
13366 * by an underscore.
13367 */
Willy Tarreau5ef96562021-08-26 16:48:53 +020013368 strlcpy2(trash.area, sc->kw, trash.size);
Willy Tarreau843b7cb2018-07-13 10:54:26 +020013369 for (p = trash.area; *p; p++)
Thierry FOURNIER594afe72015-03-10 23:58:30 +010013370 if (*p == '.' || *p == '-' || *p == '+')
13371 *p = '_';
13372
13373 /* Register the function. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013374 lua_pushstring(L, trash.area);
13375 lua_pushlightuserdata(L, sc);
13376 lua_pushcclosure(L, hlua_run_sample_conv, 1);
13377 lua_rawset(L, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +010013378 }
13379
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013380 lua_rawset(L, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +010013381
13382 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013383 class_converters_ref = hlua_register_metatable(L, CLASS_CONVERTERS);
Thierry FOURNIER594afe72015-03-10 23:58:30 +010013384
13385 /*
13386 *
Thierry FOURNIER08504f42015-03-16 14:17:08 +010013387 * Register class HTTP
13388 *
13389 */
13390
13391 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013392 lua_newtable(L);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010013393
Ilya Shipitsind4259502020-04-08 01:07:56 +050013394 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013395 lua_pushstring(L, "__index");
13396 lua_newtable(L);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010013397
13398 /* Register Lua functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013399 hlua_class_function(L, "req_get_headers",hlua_http_req_get_headers);
13400 hlua_class_function(L, "req_del_header", hlua_http_req_del_hdr);
13401 hlua_class_function(L, "req_rep_header", hlua_http_req_rep_hdr);
13402 hlua_class_function(L, "req_rep_value", hlua_http_req_rep_val);
13403 hlua_class_function(L, "req_add_header", hlua_http_req_add_hdr);
13404 hlua_class_function(L, "req_set_header", hlua_http_req_set_hdr);
13405 hlua_class_function(L, "req_set_method", hlua_http_req_set_meth);
13406 hlua_class_function(L, "req_set_path", hlua_http_req_set_path);
13407 hlua_class_function(L, "req_set_query", hlua_http_req_set_query);
13408 hlua_class_function(L, "req_set_uri", hlua_http_req_set_uri);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010013409
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013410 hlua_class_function(L, "res_get_headers",hlua_http_res_get_headers);
13411 hlua_class_function(L, "res_del_header", hlua_http_res_del_hdr);
13412 hlua_class_function(L, "res_rep_header", hlua_http_res_rep_hdr);
13413 hlua_class_function(L, "res_rep_value", hlua_http_res_rep_val);
13414 hlua_class_function(L, "res_add_header", hlua_http_res_add_hdr);
13415 hlua_class_function(L, "res_set_header", hlua_http_res_set_hdr);
13416 hlua_class_function(L, "res_set_status", hlua_http_res_set_status);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010013417
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013418 lua_rawset(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010013419
13420 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013421 class_http_ref = hlua_register_metatable(L, CLASS_HTTP);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010013422
Christopher Fauletdf97ac42020-02-26 16:57:19 +010013423 /*
13424 *
13425 * Register class HTTPMessage
13426 *
13427 */
13428
13429 /* Create and fill the metatable. */
13430 lua_newtable(L);
13431
Ilya Shipitsinff0f2782021-08-22 22:18:07 +050013432 /* Create and fill the __index entry. */
Christopher Fauletdf97ac42020-02-26 16:57:19 +010013433 lua_pushstring(L, "__index");
13434 lua_newtable(L);
13435
13436 /* Register Lua functions. */
13437 hlua_class_function(L, "is_resp", hlua_http_msg_is_resp);
13438 hlua_class_function(L, "get_stline", hlua_http_msg_get_stline);
13439 hlua_class_function(L, "get_headers", hlua_http_msg_get_headers);
13440 hlua_class_function(L, "del_header", hlua_http_msg_del_hdr);
13441 hlua_class_function(L, "rep_header", hlua_http_msg_rep_hdr);
13442 hlua_class_function(L, "rep_value", hlua_http_msg_rep_val);
13443 hlua_class_function(L, "add_header", hlua_http_msg_add_hdr);
13444 hlua_class_function(L, "set_header", hlua_http_msg_set_hdr);
13445 hlua_class_function(L, "set_method", hlua_http_msg_set_meth);
13446 hlua_class_function(L, "set_path", hlua_http_msg_set_path);
13447 hlua_class_function(L, "set_query", hlua_http_msg_set_query);
13448 hlua_class_function(L, "set_uri", hlua_http_msg_set_uri);
13449 hlua_class_function(L, "set_status", hlua_http_msg_set_status);
13450 hlua_class_function(L, "is_full", hlua_http_msg_is_full);
13451 hlua_class_function(L, "may_recv", hlua_http_msg_may_recv);
13452 hlua_class_function(L, "eom", hlua_http_msg_is_eom);
13453 hlua_class_function(L, "input", hlua_http_msg_get_in_len);
13454 hlua_class_function(L, "output", hlua_http_msg_get_out_len);
13455
13456 hlua_class_function(L, "body", hlua_http_msg_get_body);
13457 hlua_class_function(L, "set", hlua_http_msg_set_data);
13458 hlua_class_function(L, "remove", hlua_http_msg_del_data);
13459 hlua_class_function(L, "append", hlua_http_msg_append);
13460 hlua_class_function(L, "prepend", hlua_http_msg_prepend);
13461 hlua_class_function(L, "insert", hlua_http_msg_insert_data);
13462 hlua_class_function(L, "set_eom", hlua_http_msg_set_eom);
13463 hlua_class_function(L, "unset_eom", hlua_http_msg_unset_eom);
13464
13465 hlua_class_function(L, "send", hlua_http_msg_send);
13466 hlua_class_function(L, "forward", hlua_http_msg_forward);
13467
13468 lua_rawset(L, -3);
13469
13470 /* Register previous table in the registry with reference and named entry. */
13471 class_http_msg_ref = hlua_register_metatable(L, CLASS_HTTP_MSG);
William Lallemand3956c4e2021-09-21 16:25:15 +020013472
13473 /*
13474 *
13475 * Register class HTTPClient
13476 *
13477 */
13478
13479 /* Create and fill the metatable. */
13480 lua_newtable(L);
13481 lua_pushstring(L, "__index");
13482 lua_newtable(L);
13483 hlua_class_function(L, "get", hlua_httpclient_get);
William Lallemanddc2cc902021-10-26 11:43:26 +020013484 hlua_class_function(L, "head", hlua_httpclient_head);
13485 hlua_class_function(L, "put", hlua_httpclient_put);
13486 hlua_class_function(L, "post", hlua_httpclient_post);
13487 hlua_class_function(L, "delete", hlua_httpclient_delete);
William Lallemand3956c4e2021-09-21 16:25:15 +020013488 lua_settable(L, -3); /* Sets the __index entry. */
William Lallemandf77f1de2021-09-28 19:10:38 +020013489 /* Register the garbage collector entry. */
13490 lua_pushstring(L, "__gc");
13491 lua_pushcclosure(L, hlua_httpclient_gc, 0);
13492 lua_settable(L, -3); /* Push the last 2 entries in the table at index -3 */
13493
William Lallemand3956c4e2021-09-21 16:25:15 +020013494
13495
13496 class_httpclient_ref = hlua_register_metatable(L, CLASS_HTTPCLIENT);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010013497 /*
13498 *
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020013499 * Register class AppletTCP
13500 *
13501 */
13502
13503 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013504 lua_newtable(L);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020013505
Ilya Shipitsind4259502020-04-08 01:07:56 +050013506 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013507 lua_pushstring(L, "__index");
13508 lua_newtable(L);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020013509
13510 /* Register Lua functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013511 hlua_class_function(L, "getline", hlua_applet_tcp_getline);
13512 hlua_class_function(L, "receive", hlua_applet_tcp_recv);
13513 hlua_class_function(L, "send", hlua_applet_tcp_send);
13514 hlua_class_function(L, "set_priv", hlua_applet_tcp_set_priv);
13515 hlua_class_function(L, "get_priv", hlua_applet_tcp_get_priv);
13516 hlua_class_function(L, "set_var", hlua_applet_tcp_set_var);
13517 hlua_class_function(L, "unset_var", hlua_applet_tcp_unset_var);
13518 hlua_class_function(L, "get_var", hlua_applet_tcp_get_var);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020013519
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013520 lua_settable(L, -3);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020013521
13522 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013523 class_applet_tcp_ref = hlua_register_metatable(L, CLASS_APPLET_TCP);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020013524
13525 /*
13526 *
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020013527 * Register class AppletHTTP
13528 *
13529 */
13530
13531 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013532 lua_newtable(L);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020013533
Ilya Shipitsind4259502020-04-08 01:07:56 +050013534 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013535 lua_pushstring(L, "__index");
13536 lua_newtable(L);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020013537
13538 /* Register Lua functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013539 hlua_class_function(L, "set_priv", hlua_applet_http_set_priv);
13540 hlua_class_function(L, "get_priv", hlua_applet_http_get_priv);
13541 hlua_class_function(L, "set_var", hlua_applet_http_set_var);
13542 hlua_class_function(L, "unset_var", hlua_applet_http_unset_var);
13543 hlua_class_function(L, "get_var", hlua_applet_http_get_var);
13544 hlua_class_function(L, "getline", hlua_applet_http_getline);
13545 hlua_class_function(L, "receive", hlua_applet_http_recv);
13546 hlua_class_function(L, "send", hlua_applet_http_send);
13547 hlua_class_function(L, "add_header", hlua_applet_http_addheader);
13548 hlua_class_function(L, "set_status", hlua_applet_http_status);
13549 hlua_class_function(L, "start_response", hlua_applet_http_start_response);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020013550
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013551 lua_settable(L, -3);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020013552
13553 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013554 class_applet_http_ref = hlua_register_metatable(L, CLASS_APPLET_HTTP);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020013555
13556 /*
13557 *
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010013558 * Register class TXN
13559 *
13560 */
13561
13562 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013563 lua_newtable(L);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010013564
Ilya Shipitsind4259502020-04-08 01:07:56 +050013565 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013566 lua_pushstring(L, "__index");
13567 lua_newtable(L);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010013568
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +010013569 /* Register Lua functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013570 hlua_class_function(L, "set_priv", hlua_set_priv);
13571 hlua_class_function(L, "get_priv", hlua_get_priv);
13572 hlua_class_function(L, "set_var", hlua_set_var);
13573 hlua_class_function(L, "unset_var", hlua_unset_var);
13574 hlua_class_function(L, "get_var", hlua_get_var);
13575 hlua_class_function(L, "done", hlua_txn_done);
13576 hlua_class_function(L, "reply", hlua_txn_reply_new);
13577 hlua_class_function(L, "set_loglevel", hlua_txn_set_loglevel);
13578 hlua_class_function(L, "set_tos", hlua_txn_set_tos);
13579 hlua_class_function(L, "set_mark", hlua_txn_set_mark);
13580 hlua_class_function(L, "set_priority_class", hlua_txn_set_priority_class);
13581 hlua_class_function(L, "set_priority_offset", hlua_txn_set_priority_offset);
13582 hlua_class_function(L, "deflog", hlua_txn_deflog);
13583 hlua_class_function(L, "log", hlua_txn_log);
13584 hlua_class_function(L, "Debug", hlua_txn_log_debug);
13585 hlua_class_function(L, "Info", hlua_txn_log_info);
13586 hlua_class_function(L, "Warning", hlua_txn_log_warning);
13587 hlua_class_function(L, "Alert", hlua_txn_log_alert);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +010013588
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013589 lua_rawset(L, -3);
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010013590
13591 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013592 class_txn_ref = hlua_register_metatable(L, CLASS_TXN);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010013593
13594 /*
13595 *
Christopher Faulet700d9e82020-01-31 12:21:52 +010013596 * Register class reply
13597 *
13598 */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013599 lua_newtable(L);
13600 lua_pushstring(L, "__index");
13601 lua_newtable(L);
13602 hlua_class_function(L, "set_status", hlua_txn_reply_set_status);
13603 hlua_class_function(L, "add_header", hlua_txn_reply_add_header);
13604 hlua_class_function(L, "del_header", hlua_txn_reply_del_header);
13605 hlua_class_function(L, "set_body", hlua_txn_reply_set_body);
13606 lua_settable(L, -3); /* Sets the __index entry. */
13607 class_txn_reply_ref = luaL_ref(L, LUA_REGISTRYINDEX);
Christopher Faulet700d9e82020-01-31 12:21:52 +010013608
13609
13610 /*
13611 *
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010013612 * Register class Socket
13613 *
13614 */
13615
13616 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013617 lua_newtable(L);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010013618
Ilya Shipitsind4259502020-04-08 01:07:56 +050013619 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013620 lua_pushstring(L, "__index");
13621 lua_newtable(L);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010013622
Baptiste Assmann84bb4932015-03-02 21:40:06 +010013623#ifdef USE_OPENSSL
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013624 hlua_class_function(L, "connect_ssl", hlua_socket_connect_ssl);
Baptiste Assmann84bb4932015-03-02 21:40:06 +010013625#endif
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013626 hlua_class_function(L, "connect", hlua_socket_connect);
13627 hlua_class_function(L, "send", hlua_socket_send);
13628 hlua_class_function(L, "receive", hlua_socket_receive);
13629 hlua_class_function(L, "close", hlua_socket_close);
13630 hlua_class_function(L, "getpeername", hlua_socket_getpeername);
13631 hlua_class_function(L, "getsockname", hlua_socket_getsockname);
13632 hlua_class_function(L, "setoption", hlua_socket_setoption);
13633 hlua_class_function(L, "settimeout", hlua_socket_settimeout);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010013634
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013635 lua_rawset(L, -3); /* Push the last 2 entries in the table at index -3 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010013636
13637 /* Register the garbage collector entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013638 lua_pushstring(L, "__gc");
13639 lua_pushcclosure(L, hlua_socket_gc, 0);
13640 lua_rawset(L, -3); /* Push the last 2 entries in the table at index -3 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010013641
13642 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013643 class_socket_ref = hlua_register_metatable(L, CLASS_SOCKET);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010013644
Thierry Fournieraafc7772020-12-04 11:47:47 +010013645 lua_atpanic(L, hlua_panic_safe);
13646
13647 return L;
13648}
13649
13650void hlua_init(void) {
13651 int i;
Amaury Denoyelle239fdbf2021-03-24 10:22:03 +010013652 char *errmsg;
Thierry Fournieraafc7772020-12-04 11:47:47 +010013653#ifdef USE_OPENSSL
13654 struct srv_kw *kw;
13655 int tmp_error;
13656 char *error;
13657 char *args[] = { /* SSL client configuration. */
13658 "ssl",
13659 "verify",
13660 "none",
13661 NULL
13662 };
13663#endif
13664
13665 /* Init post init function list head */
13666 for (i = 0; i < MAX_THREADS + 1; i++)
13667 LIST_INIT(&hlua_init_functions[i]);
13668
13669 /* Init state for common/shared lua parts */
13670 hlua_state_id = 0;
Willy Tarreau43ab05b2021-09-28 09:43:11 +020013671 ha_set_thread(NULL);
Thierry Fournieraafc7772020-12-04 11:47:47 +010013672 hlua_states[0] = hlua_init_state(0);
13673
13674 /* Init state 1 for thread 0. We have at least one thread. */
13675 hlua_state_id = 1;
Willy Tarreau43ab05b2021-09-28 09:43:11 +020013676 ha_set_thread(NULL);
Thierry Fournieraafc7772020-12-04 11:47:47 +010013677 hlua_states[1] = hlua_init_state(1);
13678
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010013679 /* Proxy and server configuration initialisation. */
William Lallemand6bb77b92021-07-28 15:48:16 +020013680 socket_proxy = alloc_new_proxy("LUA-SOCKET", PR_CAP_FE|PR_CAP_BE|PR_CAP_INT, &errmsg);
Amaury Denoyelle239fdbf2021-03-24 10:22:03 +010013681 if (!socket_proxy) {
13682 fprintf(stderr, "Lua init: %s\n", errmsg);
13683 exit(1);
13684 }
13685 proxy_preset_defaults(socket_proxy);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010013686
13687 /* Init TCP server: unchanged parameters */
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010013688 socket_tcp = new_server(socket_proxy);
13689 if (!socket_tcp) {
13690 fprintf(stderr, "Lua init: failed to allocate tcp server socket\n");
13691 exit(1);
13692 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010013693
13694#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010013695 /* Init TCP server: unchanged parameters */
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010013696 socket_ssl = new_server(socket_proxy);
13697 if (!socket_ssl) {
13698 fprintf(stderr, "Lua init: failed to allocate ssl server socket\n");
13699 exit(1);
13700 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010013701
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010013702 socket_ssl->use_ssl = 1;
13703 socket_ssl->xprt = xprt_get(XPRT_SSL);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010013704
Bertrand Jacquin80839ff2021-01-21 19:14:46 +000013705 for (i = 0; args[i] != NULL; i++) {
13706 if ((kw = srv_find_kw(args[i])) != NULL) { /* Maybe it's registered server keyword */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010013707 /*
13708 *
13709 * If the keyword is not known, we can search in the registered
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -080013710 * server keywords. This is useful to configure special SSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010013711 * features like client certificates and ssl_verify.
13712 *
13713 */
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010013714 tmp_error = kw->parse(args, &i, socket_proxy, socket_ssl, &error);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010013715 if (tmp_error != 0) {
13716 fprintf(stderr, "INTERNAL ERROR: %s\n", error);
13717 abort(); /* This must be never arrives because the command line
13718 not editable by the user. */
13719 }
Bertrand Jacquin80839ff2021-01-21 19:14:46 +000013720 i += kw->skip;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010013721 }
13722 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010013723#endif
Thierry Fournier75933d42016-01-21 09:30:18 +010013724
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +010013725}
Willy Tarreaubb57d942016-12-21 19:04:56 +010013726
Tim Duesterhusd0c0ca22020-07-04 11:53:26 +020013727static void hlua_deinit()
13728{
Willy Tarreau186f3762020-12-04 11:48:12 +010013729 int thr;
Christopher Faulet69c581a2021-05-31 08:54:04 +020013730 struct hlua_reg_filter *reg_flt, *reg_flt_bck;
13731
13732 list_for_each_entry_safe(reg_flt, reg_flt_bck, &referenced_filters, l)
13733 release_hlua_reg_filter(reg_flt);
Willy Tarreau186f3762020-12-04 11:48:12 +010013734
13735 for (thr = 0; thr < MAX_THREADS+1; thr++) {
13736 if (hlua_states[thr])
13737 lua_close(hlua_states[thr]);
13738 }
Willy Tarreau430bf4a2021-03-04 09:45:32 +010013739
Amaury Denoyellebc2ebfa2021-08-25 15:34:53 +020013740 srv_drop(socket_tcp);
Willy Tarreau430bf4a2021-03-04 09:45:32 +010013741
Willy Tarreau0f143af2021-03-05 10:41:48 +010013742#ifdef USE_OPENSSL
Amaury Denoyellebc2ebfa2021-08-25 15:34:53 +020013743 srv_drop(socket_ssl);
Willy Tarreau0f143af2021-03-05 10:41:48 +010013744#endif
Amaury Denoyelle239fdbf2021-03-24 10:22:03 +010013745
13746 free_proxy(socket_proxy);
Tim Duesterhusd0c0ca22020-07-04 11:53:26 +020013747}
13748
13749REGISTER_POST_DEINIT(hlua_deinit);
13750
Willy Tarreau80713382018-11-26 10:19:54 +010013751static void hlua_register_build_options(void)
13752{
Willy Tarreaubb57d942016-12-21 19:04:56 +010013753 char *ptr = NULL;
Willy Tarreau80713382018-11-26 10:19:54 +010013754
Willy Tarreaubb57d942016-12-21 19:04:56 +010013755 memprintf(&ptr, "Built with Lua version : %s", LUA_RELEASE);
13756 hap_register_build_opts(ptr, 1);
13757}
Willy Tarreau80713382018-11-26 10:19:54 +010013758
13759INITCALL0(STG_REGISTER, hlua_register_build_options);